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 TempEnumTypes->replaceAllUsesWith(MDTuple::get(VMContext, AllEnumTypes));
79 SmallVector<Metadata *, 16> RetainValues;
80 // Declarations and definitions of the same type may be retained. Some
81 // clients RAUW these pairs, leaving duplicates in the retained types
82 // list. Use a set to remove the duplicates while we transform the
83 // TrackingVHs back into Values.
84 SmallPtrSet<Metadata *, 16> RetainSet;
85 for (unsigned I = 0, E = AllRetainTypes.size(); I < E; I++)
86 if (RetainSet.insert(AllRetainTypes[I]).second)
87 RetainValues.push_back(AllRetainTypes[I]);
88 TempRetainTypes->replaceAllUsesWith(MDTuple::get(VMContext, RetainValues));
90 DISubprogramArray SPs = MDTuple::get(VMContext, AllSubprograms);
91 TempSubprograms->replaceAllUsesWith(SPs.get());
92 for (auto *SP : SPs) {
93 if (MDTuple *Temp = SP->getVariables().get()) {
94 const auto &PV = PreservedVariables.lookup(SP);
95 SmallVector<Metadata *, 4> Variables(PV.begin(), PV.end());
96 DINodeArray AV = getOrCreateArray(Variables);
97 TempMDTuple(Temp)->replaceAllUsesWith(AV.get());
101 TempGVs->replaceAllUsesWith(MDTuple::get(VMContext, AllGVs));
103 TempImportedModules->replaceAllUsesWith(MDTuple::get(
104 VMContext, SmallVector<Metadata *, 16>(AllImportedModules.begin(),
105 AllImportedModules.end())));
107 // Now that all temp nodes have been replaced or deleted, resolve remaining
109 for (const auto &N : UnresolvedNodes)
110 if (N && !N->isResolved())
112 UnresolvedNodes.clear();
114 // Can't handle unresolved nodes anymore.
115 AllowUnresolvedNodes = false;
118 /// If N is compile unit return NULL otherwise return N.
119 static DIScope *getNonCompileUnitScope(DIScope *N) {
120 if (!N || isa<DICompileUnit>(N))
122 return cast<DIScope>(N);
125 DICompileUnit *DIBuilder::createCompileUnit(
126 unsigned Lang, StringRef Filename, StringRef Directory, StringRef Producer,
127 bool isOptimized, StringRef Flags, unsigned RunTimeVer, StringRef SplitName,
128 DebugEmissionKind Kind, bool EmitDebugInfo) {
130 assert(((Lang <= dwarf::DW_LANG_Fortran08 && Lang >= dwarf::DW_LANG_C89) ||
131 (Lang <= dwarf::DW_LANG_hi_user && Lang >= dwarf::DW_LANG_lo_user)) &&
132 "Invalid Language tag");
133 assert(!Filename.empty() &&
134 "Unable to create compile unit without filename");
136 // TODO: Once we make DICompileUnit distinct, stop using temporaries here
137 // (just start with operands assigned to nullptr).
138 TempEnumTypes = MDTuple::getTemporary(VMContext, None);
139 TempRetainTypes = MDTuple::getTemporary(VMContext, None);
140 TempSubprograms = MDTuple::getTemporary(VMContext, None);
141 TempGVs = MDTuple::getTemporary(VMContext, None);
142 TempImportedModules = MDTuple::getTemporary(VMContext, None);
144 // TODO: Switch to getDistinct(). We never want to merge compile units based
146 DICompileUnit *CUNode = DICompileUnit::get(
147 VMContext, Lang, DIFile::get(VMContext, Filename, Directory), Producer,
148 isOptimized, Flags, RunTimeVer, SplitName, Kind, TempEnumTypes.get(),
149 TempRetainTypes.get(), TempSubprograms.get(), TempGVs.get(),
150 TempImportedModules.get());
152 // Create a named metadata so that it is easier to find cu in a module.
153 // Note that we only generate this when the caller wants to actually
154 // emit debug information. When we are only interested in tracking
155 // source line locations throughout the backend, we prevent codegen from
156 // emitting debug info in the final output by not generating llvm.dbg.cu.
158 NamedMDNode *NMD = M.getOrInsertNamedMetadata("llvm.dbg.cu");
159 NMD->addOperand(CUNode);
162 trackIfUnresolved(CUNode);
166 static DIImportedEntity *
167 createImportedModule(LLVMContext &C, dwarf::Tag Tag, DIScope *Context,
168 Metadata *NS, unsigned Line, StringRef Name,
169 SmallVectorImpl<TrackingMDNodeRef> &AllImportedModules) {
170 auto *M = DIImportedEntity::get(C, Tag, Context, DINodeRef(NS), Line, Name);
171 AllImportedModules.emplace_back(M);
175 DIImportedEntity *DIBuilder::createImportedModule(DIScope *Context,
178 return ::createImportedModule(VMContext, dwarf::DW_TAG_imported_module,
179 Context, NS, Line, StringRef(), AllImportedModules);
182 DIImportedEntity *DIBuilder::createImportedModule(DIScope *Context,
183 DIImportedEntity *NS,
185 return ::createImportedModule(VMContext, dwarf::DW_TAG_imported_module,
186 Context, NS, Line, StringRef(), AllImportedModules);
189 DIImportedEntity *DIBuilder::createImportedDeclaration(DIScope *Context,
193 // Make sure to use the unique identifier based metadata reference for
194 // types that have one.
195 return ::createImportedModule(VMContext, dwarf::DW_TAG_imported_declaration,
196 Context, DINodeRef::get(Decl), Line, Name,
200 DIFile *DIBuilder::createFile(StringRef Filename, StringRef Directory) {
201 return DIFile::get(VMContext, Filename, Directory);
204 DIEnumerator *DIBuilder::createEnumerator(StringRef Name, int64_t Val) {
205 assert(!Name.empty() && "Unable to create enumerator without name");
206 return DIEnumerator::get(VMContext, Val, Name);
209 DIBasicType *DIBuilder::createUnspecifiedType(StringRef Name) {
210 assert(!Name.empty() && "Unable to create type without name");
211 return DIBasicType::get(VMContext, dwarf::DW_TAG_unspecified_type, Name);
214 DIBasicType *DIBuilder::createNullPtrType() {
215 return createUnspecifiedType("decltype(nullptr)");
218 DIBasicType *DIBuilder::createBasicType(StringRef Name, uint64_t SizeInBits,
219 uint64_t AlignInBits,
221 assert(!Name.empty() && "Unable to create type without name");
222 return DIBasicType::get(VMContext, dwarf::DW_TAG_base_type, Name, SizeInBits,
223 AlignInBits, Encoding);
226 DIDerivedType *DIBuilder::createQualifiedType(unsigned Tag, DIType *FromTy) {
227 return DIDerivedType::get(VMContext, Tag, "", nullptr, 0, nullptr,
228 DITypeRef::get(FromTy), 0, 0, 0, 0);
231 DIDerivedType *DIBuilder::createPointerType(DIType *PointeeTy,
233 uint64_t AlignInBits,
235 // FIXME: Why is there a name here?
236 return DIDerivedType::get(VMContext, dwarf::DW_TAG_pointer_type, Name,
237 nullptr, 0, nullptr, DITypeRef::get(PointeeTy),
238 SizeInBits, AlignInBits, 0, 0);
241 DIDerivedType *DIBuilder::createMemberPointerType(DIType *PointeeTy,
244 uint64_t AlignInBits) {
245 return DIDerivedType::get(VMContext, dwarf::DW_TAG_ptr_to_member_type, "",
246 nullptr, 0, nullptr, DITypeRef::get(PointeeTy),
247 SizeInBits, AlignInBits, 0, 0,
248 DITypeRef::get(Base));
251 DIDerivedType *DIBuilder::createReferenceType(unsigned Tag, DIType *RTy) {
252 assert(RTy && "Unable to create reference type");
253 return DIDerivedType::get(VMContext, Tag, "", nullptr, 0, nullptr,
254 DITypeRef::get(RTy), 0, 0, 0, 0);
257 DIDerivedType *DIBuilder::createTypedef(DIType *Ty, StringRef Name,
258 DIFile *File, unsigned LineNo,
260 return DIDerivedType::get(VMContext, dwarf::DW_TAG_typedef, Name, File,
262 DIScopeRef::get(getNonCompileUnitScope(Context)),
263 DITypeRef::get(Ty), 0, 0, 0, 0);
266 DIDerivedType *DIBuilder::createFriend(DIType *Ty, DIType *FriendTy) {
267 assert(Ty && "Invalid type!");
268 assert(FriendTy && "Invalid friend type!");
269 return DIDerivedType::get(VMContext, dwarf::DW_TAG_friend, "", nullptr, 0,
270 DITypeRef::get(Ty), DITypeRef::get(FriendTy), 0, 0,
274 DIDerivedType *DIBuilder::createInheritance(DIType *Ty, DIType *BaseTy,
277 assert(Ty && "Unable to create inheritance");
278 return DIDerivedType::get(VMContext, dwarf::DW_TAG_inheritance, "", nullptr,
279 0, DITypeRef::get(Ty), DITypeRef::get(BaseTy), 0, 0,
283 DIDerivedType *DIBuilder::createMemberType(DIScope *Scope, StringRef Name,
284 DIFile *File, unsigned LineNumber,
286 uint64_t AlignInBits,
287 uint64_t OffsetInBits,
288 unsigned Flags, DIType *Ty) {
289 return DIDerivedType::get(
290 VMContext, dwarf::DW_TAG_member, Name, File, LineNumber,
291 DIScopeRef::get(getNonCompileUnitScope(Scope)), DITypeRef::get(Ty),
292 SizeInBits, AlignInBits, OffsetInBits, Flags);
295 static ConstantAsMetadata *getConstantOrNull(Constant *C) {
297 return ConstantAsMetadata::get(C);
301 DIDerivedType *DIBuilder::createStaticMemberType(DIScope *Scope, StringRef Name,
304 DIType *Ty, unsigned Flags,
305 llvm::Constant *Val) {
306 Flags |= DINode::FlagStaticMember;
307 return DIDerivedType::get(
308 VMContext, dwarf::DW_TAG_member, Name, File, LineNumber,
309 DIScopeRef::get(getNonCompileUnitScope(Scope)), DITypeRef::get(Ty), 0, 0,
310 0, Flags, getConstantOrNull(Val));
313 DIDerivedType *DIBuilder::createObjCIVar(StringRef Name, DIFile *File,
316 uint64_t AlignInBits,
317 uint64_t OffsetInBits, unsigned Flags,
318 DIType *Ty, MDNode *PropertyNode) {
319 return DIDerivedType::get(
320 VMContext, dwarf::DW_TAG_member, Name, File, LineNumber,
321 DIScopeRef::get(getNonCompileUnitScope(File)), DITypeRef::get(Ty),
322 SizeInBits, AlignInBits, OffsetInBits, Flags, PropertyNode);
326 DIBuilder::createObjCProperty(StringRef Name, DIFile *File, unsigned LineNumber,
327 StringRef GetterName, StringRef SetterName,
328 unsigned PropertyAttributes, DIType *Ty) {
329 return DIObjCProperty::get(VMContext, Name, File, LineNumber, GetterName,
330 SetterName, PropertyAttributes, Ty);
333 DITemplateTypeParameter *
334 DIBuilder::createTemplateTypeParameter(DIScope *Context, StringRef Name,
336 assert((!Context || isa<DICompileUnit>(Context)) && "Expected compile unit");
337 return DITemplateTypeParameter::get(VMContext, Name, DITypeRef::get(Ty));
340 static DITemplateValueParameter *
341 createTemplateValueParameterHelper(LLVMContext &VMContext, unsigned Tag,
342 DIScope *Context, StringRef Name, DIType *Ty,
344 assert((!Context || isa<DICompileUnit>(Context)) && "Expected compile unit");
345 return DITemplateValueParameter::get(VMContext, Tag, Name, DITypeRef::get(Ty),
349 DITemplateValueParameter *
350 DIBuilder::createTemplateValueParameter(DIScope *Context, StringRef Name,
351 DIType *Ty, Constant *Val) {
352 return createTemplateValueParameterHelper(
353 VMContext, dwarf::DW_TAG_template_value_parameter, Context, Name, Ty,
354 getConstantOrNull(Val));
357 DITemplateValueParameter *
358 DIBuilder::createTemplateTemplateParameter(DIScope *Context, StringRef Name,
359 DIType *Ty, StringRef Val) {
360 return createTemplateValueParameterHelper(
361 VMContext, dwarf::DW_TAG_GNU_template_template_param, Context, Name, Ty,
362 MDString::get(VMContext, Val));
365 DITemplateValueParameter *
366 DIBuilder::createTemplateParameterPack(DIScope *Context, StringRef Name,
367 DIType *Ty, DINodeArray Val) {
368 return createTemplateValueParameterHelper(
369 VMContext, dwarf::DW_TAG_GNU_template_parameter_pack, Context, Name, Ty,
373 DICompositeType *DIBuilder::createClassType(
374 DIScope *Context, StringRef Name, DIFile *File, unsigned LineNumber,
375 uint64_t SizeInBits, uint64_t AlignInBits, uint64_t OffsetInBits,
376 unsigned Flags, DIType *DerivedFrom, DINodeArray Elements,
377 DIType *VTableHolder, MDNode *TemplateParams, StringRef UniqueIdentifier) {
378 assert((!Context || isa<DIScope>(Context)) &&
379 "createClassType should be called with a valid Context");
381 auto *R = DICompositeType::get(
382 VMContext, dwarf::DW_TAG_structure_type, Name, File, LineNumber,
383 DIScopeRef::get(getNonCompileUnitScope(Context)),
384 DITypeRef::get(DerivedFrom), SizeInBits, AlignInBits, OffsetInBits, Flags,
385 Elements, 0, DITypeRef::get(VTableHolder),
386 cast_or_null<MDTuple>(TemplateParams), UniqueIdentifier);
387 if (!UniqueIdentifier.empty())
389 trackIfUnresolved(R);
393 DICompositeType *DIBuilder::createStructType(
394 DIScope *Context, StringRef Name, DIFile *File, unsigned LineNumber,
395 uint64_t SizeInBits, uint64_t AlignInBits, unsigned Flags,
396 DIType *DerivedFrom, DINodeArray Elements, unsigned RunTimeLang,
397 DIType *VTableHolder, StringRef UniqueIdentifier) {
398 auto *R = DICompositeType::get(
399 VMContext, dwarf::DW_TAG_structure_type, Name, File, LineNumber,
400 DIScopeRef::get(getNonCompileUnitScope(Context)),
401 DITypeRef::get(DerivedFrom), SizeInBits, AlignInBits, 0, Flags, Elements,
402 RunTimeLang, DITypeRef::get(VTableHolder), nullptr, UniqueIdentifier);
403 if (!UniqueIdentifier.empty())
405 trackIfUnresolved(R);
409 DICompositeType *DIBuilder::createUnionType(
410 DIScope *Scope, StringRef Name, DIFile *File, unsigned LineNumber,
411 uint64_t SizeInBits, uint64_t AlignInBits, unsigned Flags,
412 DINodeArray Elements, unsigned RunTimeLang, StringRef UniqueIdentifier) {
413 auto *R = DICompositeType::get(
414 VMContext, dwarf::DW_TAG_union_type, Name, File, LineNumber,
415 DIScopeRef::get(getNonCompileUnitScope(Scope)), nullptr, SizeInBits,
416 AlignInBits, 0, Flags, Elements, RunTimeLang, nullptr, nullptr,
418 if (!UniqueIdentifier.empty())
420 trackIfUnresolved(R);
424 DISubroutineType *DIBuilder::createSubroutineType(DIFile *File,
425 DITypeRefArray ParameterTypes,
427 return DISubroutineType::get(VMContext, Flags, ParameterTypes);
430 DICompositeType *DIBuilder::createEnumerationType(
431 DIScope *Scope, StringRef Name, DIFile *File, unsigned LineNumber,
432 uint64_t SizeInBits, uint64_t AlignInBits, DINodeArray Elements,
433 DIType *UnderlyingType, StringRef UniqueIdentifier) {
434 auto *CTy = DICompositeType::get(
435 VMContext, dwarf::DW_TAG_enumeration_type, Name, File, LineNumber,
436 DIScopeRef::get(getNonCompileUnitScope(Scope)),
437 DITypeRef::get(UnderlyingType), SizeInBits, AlignInBits, 0, 0, Elements,
438 0, nullptr, nullptr, UniqueIdentifier);
439 AllEnumTypes.push_back(CTy);
440 if (!UniqueIdentifier.empty())
442 trackIfUnresolved(CTy);
446 DICompositeType *DIBuilder::createArrayType(uint64_t Size, uint64_t AlignInBits,
448 DINodeArray Subscripts) {
449 auto *R = DICompositeType::get(VMContext, dwarf::DW_TAG_array_type, "",
450 nullptr, 0, nullptr, DITypeRef::get(Ty), Size,
451 AlignInBits, 0, 0, Subscripts, 0, nullptr);
452 trackIfUnresolved(R);
456 DICompositeType *DIBuilder::createVectorType(uint64_t Size,
457 uint64_t AlignInBits, DIType *Ty,
458 DINodeArray Subscripts) {
460 DICompositeType::get(VMContext, dwarf::DW_TAG_array_type, "", nullptr, 0,
461 nullptr, DITypeRef::get(Ty), Size, AlignInBits, 0,
462 DINode::FlagVector, Subscripts, 0, nullptr);
463 trackIfUnresolved(R);
467 static DIType *createTypeWithFlags(LLVMContext &Context, DIType *Ty,
468 unsigned FlagsToSet) {
469 auto NewTy = Ty->clone();
470 NewTy->setFlags(NewTy->getFlags() | FlagsToSet);
471 return MDNode::replaceWithUniqued(std::move(NewTy));
474 DIType *DIBuilder::createArtificialType(DIType *Ty) {
475 // FIXME: Restrict this to the nodes where it's valid.
476 if (Ty->isArtificial())
478 return createTypeWithFlags(VMContext, Ty, DINode::FlagArtificial);
481 DIType *DIBuilder::createObjectPointerType(DIType *Ty) {
482 // FIXME: Restrict this to the nodes where it's valid.
483 if (Ty->isObjectPointer())
485 unsigned Flags = DINode::FlagObjectPointer | DINode::FlagArtificial;
486 return createTypeWithFlags(VMContext, Ty, Flags);
489 void DIBuilder::retainType(DIType *T) {
490 assert(T && "Expected non-null type");
491 AllRetainTypes.emplace_back(T);
494 DIBasicType *DIBuilder::createUnspecifiedParameter() { return nullptr; }
497 DIBuilder::createForwardDecl(unsigned Tag, StringRef Name, DIScope *Scope,
498 DIFile *F, unsigned Line, unsigned RuntimeLang,
499 uint64_t SizeInBits, uint64_t AlignInBits,
500 StringRef UniqueIdentifier) {
501 // FIXME: Define in terms of createReplaceableForwardDecl() by calling
502 // replaceWithUniqued().
503 auto *RetTy = DICompositeType::get(
504 VMContext, Tag, Name, F, Line,
505 DIScopeRef::get(getNonCompileUnitScope(Scope)), nullptr, SizeInBits,
506 AlignInBits, 0, DINode::FlagFwdDecl, nullptr, RuntimeLang, nullptr,
507 nullptr, UniqueIdentifier);
508 if (!UniqueIdentifier.empty())
510 trackIfUnresolved(RetTy);
514 DICompositeType *DIBuilder::createReplaceableCompositeType(
515 unsigned Tag, StringRef Name, DIScope *Scope, DIFile *F, unsigned Line,
516 unsigned RuntimeLang, uint64_t SizeInBits, uint64_t AlignInBits,
517 unsigned Flags, StringRef UniqueIdentifier) {
518 auto *RetTy = DICompositeType::getTemporary(
519 VMContext, Tag, Name, F, Line,
520 DIScopeRef::get(getNonCompileUnitScope(Scope)), nullptr,
521 SizeInBits, AlignInBits, 0, Flags, nullptr, RuntimeLang,
522 nullptr, nullptr, UniqueIdentifier)
524 if (!UniqueIdentifier.empty())
526 trackIfUnresolved(RetTy);
530 DINodeArray DIBuilder::getOrCreateArray(ArrayRef<Metadata *> Elements) {
531 return MDTuple::get(VMContext, Elements);
534 DITypeRefArray DIBuilder::getOrCreateTypeArray(ArrayRef<Metadata *> Elements) {
535 SmallVector<llvm::Metadata *, 16> Elts;
536 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
537 if (Elements[i] && isa<MDNode>(Elements[i]))
538 Elts.push_back(DITypeRef::get(cast<DIType>(Elements[i])));
540 Elts.push_back(Elements[i]);
542 return DITypeRefArray(MDNode::get(VMContext, Elts));
545 DISubrange *DIBuilder::getOrCreateSubrange(int64_t Lo, int64_t Count) {
546 return DISubrange::get(VMContext, Count, Lo);
549 static void checkGlobalVariableScope(DIScope *Context) {
552 dyn_cast_or_null<DICompositeType>(getNonCompileUnitScope(Context)))
553 assert(CT->getIdentifier().empty() &&
554 "Context of a global variable should not be a type with identifier");
558 DIGlobalVariable *DIBuilder::createGlobalVariable(
559 DIScope *Context, StringRef Name, StringRef LinkageName, DIFile *F,
560 unsigned LineNumber, DIType *Ty, bool isLocalToUnit, Constant *Val,
562 checkGlobalVariableScope(Context);
564 auto *N = DIGlobalVariable::get(VMContext, cast_or_null<DIScope>(Context),
565 Name, LinkageName, F, LineNumber,
566 DITypeRef::get(Ty), isLocalToUnit, true, Val,
567 cast_or_null<DIDerivedType>(Decl));
572 DIGlobalVariable *DIBuilder::createTempGlobalVariableFwdDecl(
573 DIScope *Context, StringRef Name, StringRef LinkageName, DIFile *F,
574 unsigned LineNumber, DIType *Ty, bool isLocalToUnit, Constant *Val,
576 checkGlobalVariableScope(Context);
578 return DIGlobalVariable::getTemporary(
579 VMContext, cast_or_null<DIScope>(Context), Name, LinkageName, F,
580 LineNumber, DITypeRef::get(Ty), isLocalToUnit, false, Val,
581 cast_or_null<DIDerivedType>(Decl))
585 DILocalVariable *DIBuilder::createLocalVariable(
586 unsigned Tag, DIScope *Scope, StringRef Name, DIFile *File, unsigned LineNo,
587 DIType *Ty, bool AlwaysPreserve, unsigned Flags, unsigned ArgNo) {
588 // FIXME: Why getNonCompileUnitScope()?
589 // FIXME: Why is "!Context" okay here?
590 // FIXME: WHy doesn't this check for a subprogram or lexical block (AFAICT
591 // the only valid scopes)?
592 DIScope *Context = getNonCompileUnitScope(Scope);
594 auto *Node = DILocalVariable::get(
595 VMContext, Tag, cast_or_null<DILocalScope>(Context), Name, File, LineNo,
596 DITypeRef::get(Ty), ArgNo, Flags);
597 if (AlwaysPreserve) {
598 // The optimizer may remove local variable. If there is an interest
599 // to preserve variable info in such situation then stash it in a
601 DISubprogram *Fn = getDISubprogram(Scope);
602 assert(Fn && "Missing subprogram for local variable");
603 PreservedVariables[Fn].emplace_back(Node);
608 DIExpression *DIBuilder::createExpression(ArrayRef<uint64_t> Addr) {
609 return DIExpression::get(VMContext, Addr);
612 DIExpression *DIBuilder::createExpression(ArrayRef<int64_t> Signed) {
613 // TODO: Remove the callers of this signed version and delete.
614 SmallVector<uint64_t, 8> Addr(Signed.begin(), Signed.end());
615 return createExpression(Addr);
618 DIExpression *DIBuilder::createBitPieceExpression(unsigned OffsetInBytes,
619 unsigned SizeInBytes) {
620 uint64_t Addr[] = {dwarf::DW_OP_bit_piece, OffsetInBytes, SizeInBytes};
621 return DIExpression::get(VMContext, Addr);
624 DISubprogram *DIBuilder::createFunction(DIScopeRef Context, StringRef Name,
625 StringRef LinkageName, DIFile *File,
626 unsigned LineNo, DISubroutineType *Ty,
627 bool isLocalToUnit, bool isDefinition,
628 unsigned ScopeLine, unsigned Flags,
629 bool isOptimized, Function *Fn,
630 MDNode *TParams, MDNode *Decl) {
631 // dragonegg does not generate identifier for types, so using an empty map
632 // to resolve the context should be fine.
633 DITypeIdentifierMap EmptyMap;
634 return createFunction(Context.resolve(EmptyMap), Name, LinkageName, File,
635 LineNo, Ty, isLocalToUnit, isDefinition, ScopeLine,
636 Flags, isOptimized, Fn, TParams, Decl);
639 DISubprogram *DIBuilder::createFunction(DIScope *Context, StringRef Name,
640 StringRef LinkageName, DIFile *File,
641 unsigned LineNo, DISubroutineType *Ty,
642 bool isLocalToUnit, bool isDefinition,
643 unsigned ScopeLine, unsigned Flags,
644 bool isOptimized, Function *Fn,
645 MDNode *TParams, MDNode *Decl) {
646 assert(Ty->getTag() == dwarf::DW_TAG_subroutine_type &&
647 "function types should be subroutines");
648 auto *Node = DISubprogram::get(
649 VMContext, DIScopeRef::get(getNonCompileUnitScope(Context)), Name,
650 LinkageName, File, LineNo, Ty, isLocalToUnit, isDefinition, ScopeLine,
651 nullptr, 0, 0, Flags, isOptimized, Fn, cast_or_null<MDTuple>(TParams),
652 cast_or_null<DISubprogram>(Decl),
653 MDTuple::getTemporary(VMContext, None).release());
656 AllSubprograms.push_back(Node);
657 trackIfUnresolved(Node);
661 DISubprogram *DIBuilder::createTempFunctionFwdDecl(
662 DIScope *Context, StringRef Name, StringRef LinkageName, DIFile *File,
663 unsigned LineNo, DISubroutineType *Ty, bool isLocalToUnit,
664 bool isDefinition, unsigned ScopeLine, unsigned Flags, bool isOptimized,
665 Function *Fn, MDNode *TParams, MDNode *Decl) {
666 return DISubprogram::getTemporary(
667 VMContext, DIScopeRef::get(getNonCompileUnitScope(Context)), Name,
668 LinkageName, File, LineNo, Ty, isLocalToUnit, isDefinition,
669 ScopeLine, nullptr, 0, 0, Flags, isOptimized, Fn,
670 cast_or_null<MDTuple>(TParams), cast_or_null<DISubprogram>(Decl),
676 DIBuilder::createMethod(DIScope *Context, StringRef Name, StringRef LinkageName,
677 DIFile *F, unsigned LineNo, DISubroutineType *Ty,
678 bool isLocalToUnit, bool isDefinition, unsigned VK,
679 unsigned VIndex, DIType *VTableHolder, unsigned Flags,
680 bool isOptimized, Function *Fn, MDNode *TParam) {
681 assert(Ty->getTag() == dwarf::DW_TAG_subroutine_type &&
682 "function types should be subroutines");
683 assert(getNonCompileUnitScope(Context) &&
684 "Methods should have both a Context and a context that isn't "
685 "the compile unit.");
686 // FIXME: Do we want to use different scope/lines?
687 auto *SP = DISubprogram::get(
688 VMContext, DIScopeRef::get(cast<DIScope>(Context)), Name, LinkageName, F,
689 LineNo, Ty, isLocalToUnit, isDefinition, LineNo,
690 DITypeRef::get(VTableHolder), VK, VIndex, Flags, isOptimized, Fn,
691 cast_or_null<MDTuple>(TParam), nullptr, nullptr);
694 AllSubprograms.push_back(SP);
695 trackIfUnresolved(SP);
699 DINamespace *DIBuilder::createNameSpace(DIScope *Scope, StringRef Name,
700 DIFile *File, unsigned LineNo) {
701 return DINamespace::get(VMContext, getNonCompileUnitScope(Scope), File, Name,
705 DILexicalBlockFile *DIBuilder::createLexicalBlockFile(DIScope *Scope,
707 unsigned Discriminator) {
708 return DILexicalBlockFile::get(VMContext, Scope, File, Discriminator);
711 DILexicalBlock *DIBuilder::createLexicalBlock(DIScope *Scope, DIFile *File,
712 unsigned Line, unsigned Col) {
713 // Make these distinct, to avoid merging two lexical blocks on the same
715 return DILexicalBlock::getDistinct(VMContext, getNonCompileUnitScope(Scope),
719 static Value *getDbgIntrinsicValueImpl(LLVMContext &VMContext, Value *V) {
720 assert(V && "no value passed to dbg intrinsic");
721 return MetadataAsValue::get(VMContext, ValueAsMetadata::get(V));
724 static Instruction *withDebugLoc(Instruction *I, const DILocation *DL) {
725 I->setDebugLoc(const_cast<DILocation *>(DL));
729 Instruction *DIBuilder::insertDeclare(Value *Storage, DILocalVariable *VarInfo,
730 DIExpression *Expr, const DILocation *DL,
731 Instruction *InsertBefore) {
732 assert(VarInfo && "empty or invalid DILocalVariable* passed to dbg.declare");
733 assert(DL && "Expected debug loc");
734 assert(DL->getScope()->getSubprogram() ==
735 VarInfo->getScope()->getSubprogram() &&
736 "Expected matching subprograms");
738 DeclareFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_declare);
740 trackIfUnresolved(VarInfo);
741 trackIfUnresolved(Expr);
742 Value *Args[] = {getDbgIntrinsicValueImpl(VMContext, Storage),
743 MetadataAsValue::get(VMContext, VarInfo),
744 MetadataAsValue::get(VMContext, Expr)};
745 return withDebugLoc(CallInst::Create(DeclareFn, Args, "", InsertBefore), DL);
748 Instruction *DIBuilder::insertDeclare(Value *Storage, DILocalVariable *VarInfo,
749 DIExpression *Expr, const DILocation *DL,
750 BasicBlock *InsertAtEnd) {
751 assert(VarInfo && "empty or invalid DILocalVariable* passed to dbg.declare");
752 assert(DL && "Expected debug loc");
753 assert(DL->getScope()->getSubprogram() ==
754 VarInfo->getScope()->getSubprogram() &&
755 "Expected matching subprograms");
757 DeclareFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_declare);
759 trackIfUnresolved(VarInfo);
760 trackIfUnresolved(Expr);
761 Value *Args[] = {getDbgIntrinsicValueImpl(VMContext, Storage),
762 MetadataAsValue::get(VMContext, VarInfo),
763 MetadataAsValue::get(VMContext, Expr)};
765 // If this block already has a terminator then insert this intrinsic
766 // before the terminator.
767 if (TerminatorInst *T = InsertAtEnd->getTerminator())
768 return withDebugLoc(CallInst::Create(DeclareFn, Args, "", T), DL);
769 return withDebugLoc(CallInst::Create(DeclareFn, Args, "", InsertAtEnd), DL);
772 Instruction *DIBuilder::insertDbgValueIntrinsic(Value *V, uint64_t Offset,
773 DILocalVariable *VarInfo,
775 const DILocation *DL,
776 Instruction *InsertBefore) {
777 assert(V && "no value passed to dbg.value");
778 assert(VarInfo && "empty or invalid DILocalVariable* passed to dbg.value");
779 assert(DL && "Expected debug loc");
780 assert(DL->getScope()->getSubprogram() ==
781 VarInfo->getScope()->getSubprogram() &&
782 "Expected matching subprograms");
784 ValueFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_value);
786 trackIfUnresolved(VarInfo);
787 trackIfUnresolved(Expr);
788 Value *Args[] = {getDbgIntrinsicValueImpl(VMContext, V),
789 ConstantInt::get(Type::getInt64Ty(VMContext), Offset),
790 MetadataAsValue::get(VMContext, VarInfo),
791 MetadataAsValue::get(VMContext, Expr)};
792 return withDebugLoc(CallInst::Create(ValueFn, Args, "", InsertBefore), DL);
795 Instruction *DIBuilder::insertDbgValueIntrinsic(Value *V, uint64_t Offset,
796 DILocalVariable *VarInfo,
798 const DILocation *DL,
799 BasicBlock *InsertAtEnd) {
800 assert(V && "no value passed to dbg.value");
801 assert(VarInfo && "empty or invalid DILocalVariable* passed to dbg.value");
802 assert(DL && "Expected debug loc");
803 assert(DL->getScope()->getSubprogram() ==
804 VarInfo->getScope()->getSubprogram() &&
805 "Expected matching subprograms");
807 ValueFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_value);
809 trackIfUnresolved(VarInfo);
810 trackIfUnresolved(Expr);
811 Value *Args[] = {getDbgIntrinsicValueImpl(VMContext, V),
812 ConstantInt::get(Type::getInt64Ty(VMContext), Offset),
813 MetadataAsValue::get(VMContext, VarInfo),
814 MetadataAsValue::get(VMContext, Expr)};
816 return withDebugLoc(CallInst::Create(ValueFn, Args, "", InsertAtEnd), DL);
819 void DIBuilder::replaceVTableHolder(DICompositeType *&T,
820 DICompositeType *VTableHolder) {
822 TypedTrackingMDRef<DICompositeType> N(T);
823 N->replaceVTableHolder(DITypeRef::get(VTableHolder));
827 // If this didn't create a self-reference, just return.
828 if (T != VTableHolder)
831 // Look for unresolved operands. T will drop RAUW support, orphaning any
832 // cycles underneath it.
834 for (const MDOperand &O : T->operands())
835 if (auto *N = dyn_cast_or_null<MDNode>(O))
836 trackIfUnresolved(N);
839 void DIBuilder::replaceArrays(DICompositeType *&T, DINodeArray Elements,
840 DINodeArray TParams) {
842 TypedTrackingMDRef<DICompositeType> N(T);
844 N->replaceElements(Elements);
846 N->replaceTemplateParams(DITemplateParameterArray(TParams));
850 // If T isn't resolved, there's no problem.
851 if (!T->isResolved())
854 // If "T" is resolved, it may be due to a self-reference cycle. Track the
855 // arrays explicitly if they're unresolved, or else the cycles will be
858 trackIfUnresolved(Elements.get());
860 trackIfUnresolved(TParams.get());