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()), CUNode(nullptr),
62 DeclareFn(nullptr), ValueFn(nullptr),
63 AllowUnresolvedNodes(AllowUnresolvedNodes) {}
65 void DIBuilder::trackIfUnresolved(MDNode *N) {
71 assert(AllowUnresolvedNodes && "Cannot handle unresolved nodes");
72 UnresolvedNodes.emplace_back(N);
75 void DIBuilder::finalize() {
77 assert(!AllowUnresolvedNodes &&
78 "creating type nodes without a CU is not supported");
82 CUNode->replaceEnumTypes(MDTuple::get(VMContext, AllEnumTypes));
84 SmallVector<Metadata *, 16> RetainValues;
85 // Declarations and definitions of the same type may be retained. Some
86 // clients RAUW these pairs, leaving duplicates in the retained types
87 // list. Use a set to remove the duplicates while we transform the
88 // TrackingVHs back into Values.
89 SmallPtrSet<Metadata *, 16> RetainSet;
90 for (unsigned I = 0, E = AllRetainTypes.size(); I < E; I++)
91 if (RetainSet.insert(AllRetainTypes[I]).second)
92 RetainValues.push_back(AllRetainTypes[I]);
94 if (!RetainValues.empty())
95 CUNode->replaceRetainedTypes(MDTuple::get(VMContext, RetainValues));
97 DISubprogramArray SPs = MDTuple::get(VMContext, AllSubprograms);
98 if (!AllSubprograms.empty())
99 CUNode->replaceSubprograms(SPs.get());
101 for (auto *SP : SPs) {
102 if (MDTuple *Temp = SP->getVariables().get()) {
103 const auto &PV = PreservedVariables.lookup(SP);
104 SmallVector<Metadata *, 4> Variables(PV.begin(), PV.end());
105 DINodeArray AV = getOrCreateArray(Variables);
106 TempMDTuple(Temp)->replaceAllUsesWith(AV.get());
111 CUNode->replaceGlobalVariables(MDTuple::get(VMContext, AllGVs));
113 if (!AllImportedModules.empty())
114 CUNode->replaceImportedEntities(MDTuple::get(
115 VMContext, SmallVector<Metadata *, 16>(AllImportedModules.begin(),
116 AllImportedModules.end())));
118 // Now that all temp nodes have been replaced or deleted, resolve remaining
120 for (const auto &N : UnresolvedNodes)
121 if (N && !N->isResolved())
123 UnresolvedNodes.clear();
125 // Can't handle unresolved nodes anymore.
126 AllowUnresolvedNodes = false;
129 /// If N is compile unit return NULL otherwise return N.
130 static DIScope *getNonCompileUnitScope(DIScope *N) {
131 if (!N || isa<DICompileUnit>(N))
133 return cast<DIScope>(N);
136 DICompileUnit *DIBuilder::createCompileUnit(
137 unsigned Lang, StringRef Filename, StringRef Directory, StringRef Producer,
138 bool isOptimized, StringRef Flags, unsigned RunTimeVer, StringRef SplitName,
139 DebugEmissionKind Kind, uint64_t DWOId, bool EmitDebugInfo) {
141 assert(((Lang <= dwarf::DW_LANG_Fortran08 && Lang >= dwarf::DW_LANG_C89) ||
142 (Lang <= dwarf::DW_LANG_hi_user && Lang >= dwarf::DW_LANG_lo_user)) &&
143 "Invalid Language tag");
144 assert(!Filename.empty() &&
145 "Unable to create compile unit without filename");
147 assert(!CUNode && "Can only make one compile unit per DIBuilder instance");
148 CUNode = DICompileUnit::getDistinct(
149 VMContext, Lang, DIFile::get(VMContext, Filename, Directory), Producer,
150 isOptimized, Flags, RunTimeVer, SplitName, Kind, nullptr,
151 nullptr, nullptr, nullptr, nullptr, DWOId);
153 // Create a named metadata so that it is easier to find cu in a module.
154 // Note that we only generate this when the caller wants to actually
155 // emit debug information. When we are only interested in tracking
156 // source line locations throughout the backend, we prevent codegen from
157 // emitting debug info in the final output by not generating llvm.dbg.cu.
159 NamedMDNode *NMD = M.getOrInsertNamedMetadata("llvm.dbg.cu");
160 NMD->addOperand(CUNode);
163 trackIfUnresolved(CUNode);
167 static DIImportedEntity *
168 createImportedModule(LLVMContext &C, dwarf::Tag Tag, DIScope *Context,
169 Metadata *NS, unsigned Line, StringRef Name,
170 SmallVectorImpl<TrackingMDNodeRef> &AllImportedModules) {
171 auto *M = DIImportedEntity::get(C, Tag, Context, DINodeRef(NS), Line, Name);
172 AllImportedModules.emplace_back(M);
176 DIImportedEntity *DIBuilder::createImportedModule(DIScope *Context,
179 return ::createImportedModule(VMContext, dwarf::DW_TAG_imported_module,
180 Context, NS, Line, StringRef(), AllImportedModules);
183 DIImportedEntity *DIBuilder::createImportedModule(DIScope *Context,
184 DIImportedEntity *NS,
186 return ::createImportedModule(VMContext, dwarf::DW_TAG_imported_module,
187 Context, NS, Line, StringRef(), AllImportedModules);
190 DIImportedEntity *DIBuilder::createImportedModule(DIScope *Context, DIModule *M,
192 return ::createImportedModule(VMContext, dwarf::DW_TAG_imported_module,
193 Context, M, Line, StringRef(), AllImportedModules);
196 DIImportedEntity *DIBuilder::createImportedDeclaration(DIScope *Context,
200 // Make sure to use the unique identifier based metadata reference for
201 // types that have one.
202 return ::createImportedModule(VMContext, dwarf::DW_TAG_imported_declaration,
203 Context, DINodeRef::get(Decl), Line, Name,
207 DIFile *DIBuilder::createFile(StringRef Filename, StringRef Directory) {
208 return DIFile::get(VMContext, Filename, Directory);
211 DIEnumerator *DIBuilder::createEnumerator(StringRef Name, int64_t Val) {
212 assert(!Name.empty() && "Unable to create enumerator without name");
213 return DIEnumerator::get(VMContext, Val, Name);
216 DIBasicType *DIBuilder::createUnspecifiedType(StringRef Name) {
217 assert(!Name.empty() && "Unable to create type without name");
218 return DIBasicType::get(VMContext, dwarf::DW_TAG_unspecified_type, Name);
221 DIBasicType *DIBuilder::createNullPtrType() {
222 return createUnspecifiedType("decltype(nullptr)");
225 DIBasicType *DIBuilder::createBasicType(StringRef Name, uint64_t SizeInBits,
226 uint64_t AlignInBits,
228 assert(!Name.empty() && "Unable to create type without name");
229 return DIBasicType::get(VMContext, dwarf::DW_TAG_base_type, Name, SizeInBits,
230 AlignInBits, Encoding);
233 DIDerivedType *DIBuilder::createQualifiedType(unsigned Tag, DIType *FromTy) {
234 return DIDerivedType::get(VMContext, Tag, "", nullptr, 0, nullptr,
235 DITypeRef::get(FromTy), 0, 0, 0, 0);
238 DIDerivedType *DIBuilder::createPointerType(DIType *PointeeTy,
240 uint64_t AlignInBits,
242 // FIXME: Why is there a name here?
243 return DIDerivedType::get(VMContext, dwarf::DW_TAG_pointer_type, Name,
244 nullptr, 0, nullptr, DITypeRef::get(PointeeTy),
245 SizeInBits, AlignInBits, 0, 0);
248 DIDerivedType *DIBuilder::createMemberPointerType(DIType *PointeeTy,
251 uint64_t AlignInBits) {
252 return DIDerivedType::get(VMContext, dwarf::DW_TAG_ptr_to_member_type, "",
253 nullptr, 0, nullptr, DITypeRef::get(PointeeTy),
254 SizeInBits, AlignInBits, 0, 0,
255 DITypeRef::get(Base));
258 DIDerivedType *DIBuilder::createReferenceType(unsigned Tag, DIType *RTy) {
259 assert(RTy && "Unable to create reference type");
260 return DIDerivedType::get(VMContext, Tag, "", nullptr, 0, nullptr,
261 DITypeRef::get(RTy), 0, 0, 0, 0);
264 DIDerivedType *DIBuilder::createTypedef(DIType *Ty, StringRef Name,
265 DIFile *File, unsigned LineNo,
267 return DIDerivedType::get(VMContext, dwarf::DW_TAG_typedef, Name, File,
269 DIScopeRef::get(getNonCompileUnitScope(Context)),
270 DITypeRef::get(Ty), 0, 0, 0, 0);
273 DIDerivedType *DIBuilder::createFriend(DIType *Ty, DIType *FriendTy) {
274 assert(Ty && "Invalid type!");
275 assert(FriendTy && "Invalid friend type!");
276 return DIDerivedType::get(VMContext, dwarf::DW_TAG_friend, "", nullptr, 0,
277 DITypeRef::get(Ty), DITypeRef::get(FriendTy), 0, 0,
281 DIDerivedType *DIBuilder::createInheritance(DIType *Ty, DIType *BaseTy,
284 assert(Ty && "Unable to create inheritance");
285 return DIDerivedType::get(VMContext, dwarf::DW_TAG_inheritance, "", nullptr,
286 0, DITypeRef::get(Ty), DITypeRef::get(BaseTy), 0, 0,
290 DIDerivedType *DIBuilder::createMemberType(DIScope *Scope, StringRef Name,
291 DIFile *File, unsigned LineNumber,
293 uint64_t AlignInBits,
294 uint64_t OffsetInBits,
295 unsigned Flags, DIType *Ty) {
296 return DIDerivedType::get(
297 VMContext, dwarf::DW_TAG_member, Name, File, LineNumber,
298 DIScopeRef::get(getNonCompileUnitScope(Scope)), DITypeRef::get(Ty),
299 SizeInBits, AlignInBits, OffsetInBits, Flags);
302 static ConstantAsMetadata *getConstantOrNull(Constant *C) {
304 return ConstantAsMetadata::get(C);
308 DIDerivedType *DIBuilder::createStaticMemberType(DIScope *Scope, StringRef Name,
311 DIType *Ty, unsigned Flags,
312 llvm::Constant *Val) {
313 Flags |= DINode::FlagStaticMember;
314 return DIDerivedType::get(
315 VMContext, dwarf::DW_TAG_member, Name, File, LineNumber,
316 DIScopeRef::get(getNonCompileUnitScope(Scope)), DITypeRef::get(Ty), 0, 0,
317 0, Flags, getConstantOrNull(Val));
320 DIDerivedType *DIBuilder::createObjCIVar(StringRef Name, DIFile *File,
323 uint64_t AlignInBits,
324 uint64_t OffsetInBits, unsigned Flags,
325 DIType *Ty, MDNode *PropertyNode) {
326 return DIDerivedType::get(
327 VMContext, dwarf::DW_TAG_member, Name, File, LineNumber,
328 DIScopeRef::get(getNonCompileUnitScope(File)), DITypeRef::get(Ty),
329 SizeInBits, AlignInBits, OffsetInBits, Flags, PropertyNode);
333 DIBuilder::createObjCProperty(StringRef Name, DIFile *File, unsigned LineNumber,
334 StringRef GetterName, StringRef SetterName,
335 unsigned PropertyAttributes, DIType *Ty) {
336 return DIObjCProperty::get(VMContext, Name, File, LineNumber, GetterName,
337 SetterName, PropertyAttributes,
341 DITemplateTypeParameter *
342 DIBuilder::createTemplateTypeParameter(DIScope *Context, StringRef Name,
344 assert((!Context || isa<DICompileUnit>(Context)) && "Expected compile unit");
345 return DITemplateTypeParameter::get(VMContext, Name, DITypeRef::get(Ty));
348 static DITemplateValueParameter *
349 createTemplateValueParameterHelper(LLVMContext &VMContext, unsigned Tag,
350 DIScope *Context, StringRef Name, DIType *Ty,
352 assert((!Context || isa<DICompileUnit>(Context)) && "Expected compile unit");
353 return DITemplateValueParameter::get(VMContext, Tag, Name, DITypeRef::get(Ty),
357 DITemplateValueParameter *
358 DIBuilder::createTemplateValueParameter(DIScope *Context, StringRef Name,
359 DIType *Ty, Constant *Val) {
360 return createTemplateValueParameterHelper(
361 VMContext, dwarf::DW_TAG_template_value_parameter, Context, Name, Ty,
362 getConstantOrNull(Val));
365 DITemplateValueParameter *
366 DIBuilder::createTemplateTemplateParameter(DIScope *Context, StringRef Name,
367 DIType *Ty, StringRef Val) {
368 return createTemplateValueParameterHelper(
369 VMContext, dwarf::DW_TAG_GNU_template_template_param, Context, Name, Ty,
370 MDString::get(VMContext, Val));
373 DITemplateValueParameter *
374 DIBuilder::createTemplateParameterPack(DIScope *Context, StringRef Name,
375 DIType *Ty, DINodeArray Val) {
376 return createTemplateValueParameterHelper(
377 VMContext, dwarf::DW_TAG_GNU_template_parameter_pack, Context, Name, Ty,
381 DICompositeType *DIBuilder::createClassType(
382 DIScope *Context, StringRef Name, DIFile *File, unsigned LineNumber,
383 uint64_t SizeInBits, uint64_t AlignInBits, uint64_t OffsetInBits,
384 unsigned Flags, DIType *DerivedFrom, DINodeArray Elements,
385 DIType *VTableHolder, MDNode *TemplateParams, StringRef UniqueIdentifier) {
386 assert((!Context || isa<DIScope>(Context)) &&
387 "createClassType should be called with a valid Context");
389 auto *R = DICompositeType::get(
390 VMContext, dwarf::DW_TAG_structure_type, Name, File, LineNumber,
391 DIScopeRef::get(getNonCompileUnitScope(Context)),
392 DITypeRef::get(DerivedFrom), SizeInBits, AlignInBits, OffsetInBits, Flags,
393 Elements, 0, DITypeRef::get(VTableHolder),
394 cast_or_null<MDTuple>(TemplateParams), UniqueIdentifier);
395 if (!UniqueIdentifier.empty())
397 trackIfUnresolved(R);
401 DICompositeType *DIBuilder::createStructType(
402 DIScope *Context, StringRef Name, DIFile *File, unsigned LineNumber,
403 uint64_t SizeInBits, uint64_t AlignInBits, unsigned Flags,
404 DIType *DerivedFrom, DINodeArray Elements, unsigned RunTimeLang,
405 DIType *VTableHolder, StringRef UniqueIdentifier) {
406 auto *R = DICompositeType::get(
407 VMContext, dwarf::DW_TAG_structure_type, Name, File, LineNumber,
408 DIScopeRef::get(getNonCompileUnitScope(Context)),
409 DITypeRef::get(DerivedFrom), SizeInBits, AlignInBits, 0, Flags, Elements,
410 RunTimeLang, DITypeRef::get(VTableHolder), nullptr, UniqueIdentifier);
411 if (!UniqueIdentifier.empty())
413 trackIfUnresolved(R);
417 DICompositeType *DIBuilder::createUnionType(
418 DIScope *Scope, StringRef Name, DIFile *File, unsigned LineNumber,
419 uint64_t SizeInBits, uint64_t AlignInBits, unsigned Flags,
420 DINodeArray Elements, unsigned RunTimeLang, StringRef UniqueIdentifier) {
421 auto *R = DICompositeType::get(
422 VMContext, dwarf::DW_TAG_union_type, Name, File, LineNumber,
423 DIScopeRef::get(getNonCompileUnitScope(Scope)), nullptr, SizeInBits,
424 AlignInBits, 0, Flags, Elements, RunTimeLang, nullptr, nullptr,
426 if (!UniqueIdentifier.empty())
428 trackIfUnresolved(R);
432 DISubroutineType *DIBuilder::createSubroutineType(DIFile *File,
433 DITypeRefArray ParameterTypes,
435 return DISubroutineType::get(VMContext, Flags, ParameterTypes);
438 DICompositeType *DIBuilder::createExternalTypeRef(unsigned Tag, DIFile *File,
439 StringRef UniqueIdentifier) {
440 assert(!UniqueIdentifier.empty() && "external type ref without uid");
442 DICompositeType::get(VMContext, Tag, "", nullptr, 0, nullptr, nullptr, 0,
443 0, 0, DINode::FlagExternalTypeRef, nullptr, 0,
444 nullptr, nullptr, UniqueIdentifier);
445 // Types with unique IDs need to be in the type map.
450 DICompositeType *DIBuilder::createEnumerationType(
451 DIScope *Scope, StringRef Name, DIFile *File, unsigned LineNumber,
452 uint64_t SizeInBits, uint64_t AlignInBits, DINodeArray Elements,
453 DIType *UnderlyingType, StringRef UniqueIdentifier) {
454 auto *CTy = DICompositeType::get(
455 VMContext, dwarf::DW_TAG_enumeration_type, Name, File, LineNumber,
456 DIScopeRef::get(getNonCompileUnitScope(Scope)),
457 DITypeRef::get(UnderlyingType), SizeInBits, AlignInBits, 0, 0, Elements,
458 0, nullptr, nullptr, UniqueIdentifier);
459 AllEnumTypes.push_back(CTy);
460 if (!UniqueIdentifier.empty())
462 trackIfUnresolved(CTy);
466 DICompositeType *DIBuilder::createArrayType(uint64_t Size, uint64_t AlignInBits,
468 DINodeArray Subscripts) {
469 auto *R = DICompositeType::get(VMContext, dwarf::DW_TAG_array_type, "",
470 nullptr, 0, nullptr, DITypeRef::get(Ty), Size,
471 AlignInBits, 0, 0, Subscripts, 0, nullptr);
472 trackIfUnresolved(R);
476 DICompositeType *DIBuilder::createVectorType(uint64_t Size,
477 uint64_t AlignInBits, DIType *Ty,
478 DINodeArray Subscripts) {
480 DICompositeType::get(VMContext, dwarf::DW_TAG_array_type, "", nullptr, 0,
481 nullptr, DITypeRef::get(Ty), Size, AlignInBits, 0,
482 DINode::FlagVector, Subscripts, 0, nullptr);
483 trackIfUnresolved(R);
487 static DIType *createTypeWithFlags(LLVMContext &Context, DIType *Ty,
488 unsigned FlagsToSet) {
489 auto NewTy = Ty->clone();
490 NewTy->setFlags(NewTy->getFlags() | FlagsToSet);
491 return MDNode::replaceWithUniqued(std::move(NewTy));
494 DIType *DIBuilder::createArtificialType(DIType *Ty) {
495 // FIXME: Restrict this to the nodes where it's valid.
496 if (Ty->isArtificial())
498 return createTypeWithFlags(VMContext, Ty, DINode::FlagArtificial);
501 DIType *DIBuilder::createObjectPointerType(DIType *Ty) {
502 // FIXME: Restrict this to the nodes where it's valid.
503 if (Ty->isObjectPointer())
505 unsigned Flags = DINode::FlagObjectPointer | DINode::FlagArtificial;
506 return createTypeWithFlags(VMContext, Ty, Flags);
509 void DIBuilder::retainType(DIType *T) {
510 assert(T && "Expected non-null type");
511 AllRetainTypes.emplace_back(T);
514 DIBasicType *DIBuilder::createUnspecifiedParameter() { return nullptr; }
517 DIBuilder::createForwardDecl(unsigned Tag, StringRef Name, DIScope *Scope,
518 DIFile *F, unsigned Line, unsigned RuntimeLang,
519 uint64_t SizeInBits, uint64_t AlignInBits,
520 StringRef UniqueIdentifier) {
521 // FIXME: Define in terms of createReplaceableForwardDecl() by calling
522 // replaceWithUniqued().
523 auto *RetTy = DICompositeType::get(
524 VMContext, Tag, Name, F, Line,
525 DIScopeRef::get(getNonCompileUnitScope(Scope)), nullptr, SizeInBits,
526 AlignInBits, 0, DINode::FlagFwdDecl, nullptr, RuntimeLang, nullptr,
527 nullptr, UniqueIdentifier);
528 if (!UniqueIdentifier.empty())
530 trackIfUnresolved(RetTy);
534 DICompositeType *DIBuilder::createReplaceableCompositeType(
535 unsigned Tag, StringRef Name, DIScope *Scope, DIFile *F, unsigned Line,
536 unsigned RuntimeLang, uint64_t SizeInBits, uint64_t AlignInBits,
537 unsigned Flags, StringRef UniqueIdentifier) {
538 auto *RetTy = DICompositeType::getTemporary(
539 VMContext, Tag, Name, F, Line,
540 DIScopeRef::get(getNonCompileUnitScope(Scope)), nullptr,
541 SizeInBits, AlignInBits, 0, Flags, nullptr, RuntimeLang,
542 nullptr, nullptr, UniqueIdentifier)
544 if (!UniqueIdentifier.empty())
546 trackIfUnresolved(RetTy);
550 DINodeArray DIBuilder::getOrCreateArray(ArrayRef<Metadata *> Elements) {
551 return MDTuple::get(VMContext, Elements);
554 DITypeRefArray DIBuilder::getOrCreateTypeArray(ArrayRef<Metadata *> Elements) {
555 SmallVector<llvm::Metadata *, 16> Elts;
556 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
557 if (Elements[i] && isa<MDNode>(Elements[i]))
558 Elts.push_back(DITypeRef::get(cast<DIType>(Elements[i])));
560 Elts.push_back(Elements[i]);
562 return DITypeRefArray(MDNode::get(VMContext, Elts));
565 DISubrange *DIBuilder::getOrCreateSubrange(int64_t Lo, int64_t Count) {
566 return DISubrange::get(VMContext, Count, Lo);
569 static void checkGlobalVariableScope(DIScope *Context) {
572 dyn_cast_or_null<DICompositeType>(getNonCompileUnitScope(Context)))
573 assert(CT->getIdentifier().empty() &&
574 "Context of a global variable should not be a type with identifier");
578 DIGlobalVariable *DIBuilder::createGlobalVariable(
579 DIScope *Context, StringRef Name, StringRef LinkageName, DIFile *F,
580 unsigned LineNumber, DIType *Ty, bool isLocalToUnit, Constant *Val,
582 checkGlobalVariableScope(Context);
584 auto *N = DIGlobalVariable::get(VMContext, cast_or_null<DIScope>(Context),
585 Name, LinkageName, F, LineNumber,
586 DITypeRef::get(Ty), isLocalToUnit, true, Val,
587 cast_or_null<DIDerivedType>(Decl));
592 DIGlobalVariable *DIBuilder::createTempGlobalVariableFwdDecl(
593 DIScope *Context, StringRef Name, StringRef LinkageName, DIFile *F,
594 unsigned LineNumber, DIType *Ty, bool isLocalToUnit, Constant *Val,
596 checkGlobalVariableScope(Context);
598 return DIGlobalVariable::getTemporary(
599 VMContext, cast_or_null<DIScope>(Context), Name, LinkageName, F,
600 LineNumber, DITypeRef::get(Ty), isLocalToUnit, false, Val,
601 cast_or_null<DIDerivedType>(Decl))
605 static DILocalVariable *createLocalVariable(
606 LLVMContext &VMContext,
607 DenseMap<MDNode *, std::vector<TrackingMDNodeRef>> &PreservedVariables,
608 DIScope *Scope, StringRef Name, unsigned ArgNo, DIFile *File,
609 unsigned LineNo, DIType *Ty, 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 DIScope *Context = getNonCompileUnitScope(Scope);
616 dwarf::Tag Tag = ArgNo ? dwarf::DW_TAG_arg_variable : dwarf::DW_TAG_auto_variable;
617 auto *Node = DILocalVariable::get(
618 VMContext, Tag, cast_or_null<DILocalScope>(Context), Name, File, LineNo,
619 DITypeRef::get(Ty), ArgNo, Flags);
620 if (AlwaysPreserve) {
621 // The optimizer may remove local variables. If there is an interest
622 // to preserve variable info in such situation then stash it in a
624 DISubprogram *Fn = getDISubprogram(Scope);
625 assert(Fn && "Missing subprogram for local variable");
626 PreservedVariables[Fn].emplace_back(Node);
631 DILocalVariable *DIBuilder::createAutoVariable(DIScope *Scope, StringRef Name,
632 DIFile *File, unsigned LineNo,
633 DIType *Ty, bool AlwaysPreserve,
635 return createLocalVariable(VMContext, PreservedVariables, Scope, Name,
636 /* ArgNo */ 0, File, LineNo, Ty, AlwaysPreserve,
640 DILocalVariable *DIBuilder::createParameterVariable(
641 DIScope *Scope, StringRef Name, unsigned ArgNo, DIFile *File,
642 unsigned LineNo, DIType *Ty, bool AlwaysPreserve, unsigned Flags) {
643 assert(ArgNo && "Expected non-zero argument number for parameter");
644 return createLocalVariable(VMContext, PreservedVariables, Scope, Name, ArgNo,
645 File, LineNo, Ty, AlwaysPreserve, Flags);
648 DIExpression *DIBuilder::createExpression(ArrayRef<uint64_t> Addr) {
649 return DIExpression::get(VMContext, Addr);
652 DIExpression *DIBuilder::createExpression(ArrayRef<int64_t> Signed) {
653 // TODO: Remove the callers of this signed version and delete.
654 SmallVector<uint64_t, 8> Addr(Signed.begin(), Signed.end());
655 return createExpression(Addr);
658 DIExpression *DIBuilder::createBitPieceExpression(unsigned OffsetInBytes,
659 unsigned SizeInBytes) {
660 uint64_t Addr[] = {dwarf::DW_OP_bit_piece, OffsetInBytes, SizeInBytes};
661 return DIExpression::get(VMContext, Addr);
664 DISubprogram *DIBuilder::createFunction(DIScopeRef Context, StringRef Name,
665 StringRef LinkageName, DIFile *File,
666 unsigned LineNo, DISubroutineType *Ty,
667 bool isLocalToUnit, bool isDefinition,
668 unsigned ScopeLine, unsigned Flags,
669 bool isOptimized, Function *Fn,
670 MDNode *TParams, MDNode *Decl) {
671 // dragonegg does not generate identifier for types, so using an empty map
672 // to resolve the context should be fine.
673 DITypeIdentifierMap EmptyMap;
674 return createFunction(Context.resolve(EmptyMap), Name, LinkageName, File,
675 LineNo, Ty, isLocalToUnit, isDefinition, ScopeLine,
676 Flags, isOptimized, Fn, TParams, Decl);
679 DISubprogram *DIBuilder::createFunction(DIScope *Context, StringRef Name,
680 StringRef LinkageName, DIFile *File,
681 unsigned LineNo, DISubroutineType *Ty,
682 bool isLocalToUnit, bool isDefinition,
683 unsigned ScopeLine, unsigned Flags,
684 bool isOptimized, Function *Fn,
685 MDNode *TParams, MDNode *Decl) {
686 assert(Ty->getTag() == dwarf::DW_TAG_subroutine_type &&
687 "function types should be subroutines");
688 auto *Node = DISubprogram::get(
689 VMContext, DIScopeRef::get(getNonCompileUnitScope(Context)), Name,
690 LinkageName, File, LineNo, Ty, isLocalToUnit, isDefinition, ScopeLine,
691 nullptr, 0, 0, Flags, isOptimized, Fn, cast_or_null<MDTuple>(TParams),
692 cast_or_null<DISubprogram>(Decl),
693 MDTuple::getTemporary(VMContext, None).release());
696 AllSubprograms.push_back(Node);
697 trackIfUnresolved(Node);
701 DISubprogram *DIBuilder::createTempFunctionFwdDecl(
702 DIScope *Context, StringRef Name, StringRef LinkageName, DIFile *File,
703 unsigned LineNo, DISubroutineType *Ty, bool isLocalToUnit,
704 bool isDefinition, unsigned ScopeLine, unsigned Flags, bool isOptimized,
705 Function *Fn, MDNode *TParams, MDNode *Decl) {
706 return DISubprogram::getTemporary(
707 VMContext, DIScopeRef::get(getNonCompileUnitScope(Context)), Name,
708 LinkageName, File, LineNo, Ty, isLocalToUnit, isDefinition,
709 ScopeLine, nullptr, 0, 0, Flags, isOptimized, Fn,
710 cast_or_null<MDTuple>(TParams), cast_or_null<DISubprogram>(Decl),
716 DIBuilder::createMethod(DIScope *Context, StringRef Name, StringRef LinkageName,
717 DIFile *F, unsigned LineNo, DISubroutineType *Ty,
718 bool isLocalToUnit, bool isDefinition, unsigned VK,
719 unsigned VIndex, DIType *VTableHolder, unsigned Flags,
720 bool isOptimized, Function *Fn, MDNode *TParam) {
721 assert(Ty->getTag() == dwarf::DW_TAG_subroutine_type &&
722 "function types should be subroutines");
723 assert(getNonCompileUnitScope(Context) &&
724 "Methods should have both a Context and a context that isn't "
725 "the compile unit.");
726 // FIXME: Do we want to use different scope/lines?
727 auto *SP = DISubprogram::get(
728 VMContext, DIScopeRef::get(cast<DIScope>(Context)), Name, LinkageName, F,
729 LineNo, Ty, isLocalToUnit, isDefinition, LineNo,
730 DITypeRef::get(VTableHolder), VK, VIndex, Flags, isOptimized, Fn,
731 cast_or_null<MDTuple>(TParam), nullptr, nullptr);
734 AllSubprograms.push_back(SP);
735 trackIfUnresolved(SP);
739 DINamespace *DIBuilder::createNameSpace(DIScope *Scope, StringRef Name,
740 DIFile *File, unsigned LineNo) {
741 return DINamespace::get(VMContext, getNonCompileUnitScope(Scope), File, Name,
745 DIModule *DIBuilder::createModule(DIScope *Scope, StringRef Name,
746 StringRef ConfigurationMacros,
747 StringRef IncludePath,
748 StringRef ISysRoot) {
749 return DIModule::get(VMContext, getNonCompileUnitScope(Scope), Name,
750 ConfigurationMacros, IncludePath, ISysRoot);
753 DILexicalBlockFile *DIBuilder::createLexicalBlockFile(DIScope *Scope,
755 unsigned Discriminator) {
756 return DILexicalBlockFile::get(VMContext, Scope, File, Discriminator);
759 DILexicalBlock *DIBuilder::createLexicalBlock(DIScope *Scope, DIFile *File,
760 unsigned Line, unsigned Col) {
761 // Make these distinct, to avoid merging two lexical blocks on the same
763 return DILexicalBlock::getDistinct(VMContext, getNonCompileUnitScope(Scope),
767 static Value *getDbgIntrinsicValueImpl(LLVMContext &VMContext, Value *V) {
768 assert(V && "no value passed to dbg intrinsic");
769 return MetadataAsValue::get(VMContext, ValueAsMetadata::get(V));
772 static Instruction *withDebugLoc(Instruction *I, const DILocation *DL) {
773 I->setDebugLoc(const_cast<DILocation *>(DL));
777 Instruction *DIBuilder::insertDeclare(Value *Storage, DILocalVariable *VarInfo,
778 DIExpression *Expr, const DILocation *DL,
779 Instruction *InsertBefore) {
780 assert(VarInfo && "empty or invalid DILocalVariable* passed to dbg.declare");
781 assert(DL && "Expected debug loc");
782 assert(DL->getScope()->getSubprogram() ==
783 VarInfo->getScope()->getSubprogram() &&
784 "Expected matching subprograms");
786 DeclareFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_declare);
788 trackIfUnresolved(VarInfo);
789 trackIfUnresolved(Expr);
790 Value *Args[] = {getDbgIntrinsicValueImpl(VMContext, Storage),
791 MetadataAsValue::get(VMContext, VarInfo),
792 MetadataAsValue::get(VMContext, Expr)};
793 return withDebugLoc(CallInst::Create(DeclareFn, Args, "", InsertBefore), DL);
796 Instruction *DIBuilder::insertDeclare(Value *Storage, DILocalVariable *VarInfo,
797 DIExpression *Expr, const DILocation *DL,
798 BasicBlock *InsertAtEnd) {
799 assert(VarInfo && "empty or invalid DILocalVariable* passed to dbg.declare");
800 assert(DL && "Expected debug loc");
801 assert(DL->getScope()->getSubprogram() ==
802 VarInfo->getScope()->getSubprogram() &&
803 "Expected matching subprograms");
805 DeclareFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_declare);
807 trackIfUnresolved(VarInfo);
808 trackIfUnresolved(Expr);
809 Value *Args[] = {getDbgIntrinsicValueImpl(VMContext, Storage),
810 MetadataAsValue::get(VMContext, VarInfo),
811 MetadataAsValue::get(VMContext, Expr)};
813 // If this block already has a terminator then insert this intrinsic
814 // before the terminator.
815 if (TerminatorInst *T = InsertAtEnd->getTerminator())
816 return withDebugLoc(CallInst::Create(DeclareFn, Args, "", T), DL);
817 return withDebugLoc(CallInst::Create(DeclareFn, Args, "", InsertAtEnd), DL);
820 Instruction *DIBuilder::insertDbgValueIntrinsic(Value *V, uint64_t Offset,
821 DILocalVariable *VarInfo,
823 const DILocation *DL,
824 Instruction *InsertBefore) {
825 assert(V && "no value passed to dbg.value");
826 assert(VarInfo && "empty or invalid DILocalVariable* passed to dbg.value");
827 assert(DL && "Expected debug loc");
828 assert(DL->getScope()->getSubprogram() ==
829 VarInfo->getScope()->getSubprogram() &&
830 "Expected matching subprograms");
832 ValueFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_value);
834 trackIfUnresolved(VarInfo);
835 trackIfUnresolved(Expr);
836 Value *Args[] = {getDbgIntrinsicValueImpl(VMContext, V),
837 ConstantInt::get(Type::getInt64Ty(VMContext), Offset),
838 MetadataAsValue::get(VMContext, VarInfo),
839 MetadataAsValue::get(VMContext, Expr)};
840 return withDebugLoc(CallInst::Create(ValueFn, Args, "", InsertBefore), DL);
843 Instruction *DIBuilder::insertDbgValueIntrinsic(Value *V, uint64_t Offset,
844 DILocalVariable *VarInfo,
846 const DILocation *DL,
847 BasicBlock *InsertAtEnd) {
848 assert(V && "no value passed to dbg.value");
849 assert(VarInfo && "empty or invalid DILocalVariable* passed to dbg.value");
850 assert(DL && "Expected debug loc");
851 assert(DL->getScope()->getSubprogram() ==
852 VarInfo->getScope()->getSubprogram() &&
853 "Expected matching subprograms");
855 ValueFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_value);
857 trackIfUnresolved(VarInfo);
858 trackIfUnresolved(Expr);
859 Value *Args[] = {getDbgIntrinsicValueImpl(VMContext, V),
860 ConstantInt::get(Type::getInt64Ty(VMContext), Offset),
861 MetadataAsValue::get(VMContext, VarInfo),
862 MetadataAsValue::get(VMContext, Expr)};
864 return withDebugLoc(CallInst::Create(ValueFn, Args, "", InsertAtEnd), DL);
867 void DIBuilder::replaceVTableHolder(DICompositeType *&T,
868 DICompositeType *VTableHolder) {
870 TypedTrackingMDRef<DICompositeType> N(T);
871 N->replaceVTableHolder(DITypeRef::get(VTableHolder));
875 // If this didn't create a self-reference, just return.
876 if (T != VTableHolder)
879 // Look for unresolved operands. T will drop RAUW support, orphaning any
880 // cycles underneath it.
882 for (const MDOperand &O : T->operands())
883 if (auto *N = dyn_cast_or_null<MDNode>(O))
884 trackIfUnresolved(N);
887 void DIBuilder::replaceArrays(DICompositeType *&T, DINodeArray Elements,
888 DINodeArray TParams) {
890 TypedTrackingMDRef<DICompositeType> N(T);
892 N->replaceElements(Elements);
894 N->replaceTemplateParams(DITemplateParameterArray(TParams));
898 // If T isn't resolved, there's no problem.
899 if (!T->isResolved())
902 // If T is resolved, it may be due to a self-reference cycle. Track the
903 // arrays explicitly if they're unresolved, or else the cycles will be
906 trackIfUnresolved(Elements.get());
908 trackIfUnresolved(TParams.get());