1 //===--- DIBuilder.cpp - Debug Information Builder ------------------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This file implements the DIBuilder.
11 //===----------------------------------------------------------------------===//
13 #include "llvm/IR/DIBuilder.h"
14 #include "LLVMContextImpl.h"
15 #include "llvm/ADT/Optional.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/BinaryFormat/Dwarf.h"
18 #include "llvm/IR/Constants.h"
19 #include "llvm/IR/DebugInfo.h"
20 #include "llvm/IR/IRBuilder.h"
21 #include "llvm/IR/IntrinsicInst.h"
22 #include "llvm/IR/Module.h"
23 #include "llvm/Support/CommandLine.h"
24 #include "llvm/Support/Debug.h"
27 using namespace llvm::dwarf;
30 UseDbgAddr("use-dbg-addr",
31 llvm::cl::desc("Use llvm.dbg.addr for all local variables"),
32 cl::init(false), cl::Hidden);
34 DIBuilder::DIBuilder(Module &m, bool AllowUnresolvedNodes, DICompileUnit *CU)
35 : M(m), VMContext(M.getContext()), CUNode(CU),
36 DeclareFn(nullptr), ValueFn(nullptr), LabelFn(nullptr),
37 AllowUnresolvedNodes(AllowUnresolvedNodes) {}
39 void DIBuilder::trackIfUnresolved(MDNode *N) {
45 assert(AllowUnresolvedNodes && "Cannot handle unresolved nodes");
46 UnresolvedNodes.emplace_back(N);
49 void DIBuilder::finalizeSubprogram(DISubprogram *SP) {
50 MDTuple *Temp = SP->getRetainedNodes().get();
51 if (!Temp || !Temp->isTemporary())
54 SmallVector<Metadata *, 16> RetainedNodes;
56 auto PV = PreservedVariables.find(SP);
57 if (PV != PreservedVariables.end())
58 RetainedNodes.append(PV->second.begin(), PV->second.end());
60 auto PL = PreservedLabels.find(SP);
61 if (PL != PreservedLabels.end())
62 RetainedNodes.append(PL->second.begin(), PL->second.end());
64 DINodeArray Node = getOrCreateArray(RetainedNodes);
66 TempMDTuple(Temp)->replaceAllUsesWith(Node.get());
69 void DIBuilder::finalize() {
71 assert(!AllowUnresolvedNodes &&
72 "creating type nodes without a CU is not supported");
76 CUNode->replaceEnumTypes(MDTuple::get(VMContext, AllEnumTypes));
78 SmallVector<Metadata *, 16> RetainValues;
79 // Declarations and definitions of the same type may be retained. Some
80 // clients RAUW these pairs, leaving duplicates in the retained types
81 // list. Use a set to remove the duplicates while we transform the
82 // TrackingVHs back into Values.
83 SmallPtrSet<Metadata *, 16> RetainSet;
84 for (unsigned I = 0, E = AllRetainTypes.size(); I < E; I++)
85 if (RetainSet.insert(AllRetainTypes[I]).second)
86 RetainValues.push_back(AllRetainTypes[I]);
88 if (!RetainValues.empty())
89 CUNode->replaceRetainedTypes(MDTuple::get(VMContext, RetainValues));
91 DISubprogramArray SPs = MDTuple::get(VMContext, AllSubprograms);
93 finalizeSubprogram(SP);
94 for (auto *N : RetainValues)
95 if (auto *SP = dyn_cast<DISubprogram>(N))
96 finalizeSubprogram(SP);
99 CUNode->replaceGlobalVariables(MDTuple::get(VMContext, AllGVs));
101 if (!AllImportedModules.empty())
102 CUNode->replaceImportedEntities(MDTuple::get(
103 VMContext, SmallVector<Metadata *, 16>(AllImportedModules.begin(),
104 AllImportedModules.end())));
106 for (const auto &I : AllMacrosPerParent) {
107 // DIMacroNode's with nullptr parent are DICompileUnit direct children.
109 CUNode->replaceMacros(MDTuple::get(VMContext, I.second.getArrayRef()));
112 // Otherwise, it must be a temporary DIMacroFile that need to be resolved.
113 auto *TMF = cast<DIMacroFile>(I.first);
114 auto *MF = DIMacroFile::get(VMContext, dwarf::DW_MACINFO_start_file,
115 TMF->getLine(), TMF->getFile(),
116 getOrCreateMacroArray(I.second.getArrayRef()));
117 replaceTemporary(llvm::TempDIMacroNode(TMF), MF);
120 // Now that all temp nodes have been replaced or deleted, resolve remaining
122 for (const auto &N : UnresolvedNodes)
123 if (N && !N->isResolved())
125 UnresolvedNodes.clear();
127 // Can't handle unresolved nodes anymore.
128 AllowUnresolvedNodes = false;
131 /// If N is compile unit return NULL otherwise return N.
132 static DIScope *getNonCompileUnitScope(DIScope *N) {
133 if (!N || isa<DICompileUnit>(N))
135 return cast<DIScope>(N);
138 DICompileUnit *DIBuilder::createCompileUnit(
139 unsigned Lang, DIFile *File, StringRef Producer, bool isOptimized,
140 StringRef Flags, unsigned RunTimeVer, StringRef SplitName,
141 DICompileUnit::DebugEmissionKind Kind, uint64_t DWOId,
142 bool SplitDebugInlining, bool DebugInfoForProfiling,
143 DICompileUnit::DebugNameTableKind NameTableKind, bool RangesBaseAddress) {
145 assert(((Lang <= dwarf::DW_LANG_Fortran08 && Lang >= dwarf::DW_LANG_C89) ||
146 (Lang <= dwarf::DW_LANG_hi_user && Lang >= dwarf::DW_LANG_lo_user)) &&
147 "Invalid Language tag");
149 assert(!CUNode && "Can only make one compile unit per DIBuilder instance");
150 CUNode = DICompileUnit::getDistinct(
151 VMContext, Lang, File, Producer, isOptimized, Flags, RunTimeVer,
152 SplitName, Kind, nullptr, nullptr, nullptr, nullptr, nullptr, DWOId,
153 SplitDebugInlining, DebugInfoForProfiling, NameTableKind,
156 // Create a named metadata so that it is easier to find cu in a module.
157 NamedMDNode *NMD = M.getOrInsertNamedMetadata("llvm.dbg.cu");
158 NMD->addOperand(CUNode);
159 trackIfUnresolved(CUNode);
163 static DIImportedEntity *
164 createImportedModule(LLVMContext &C, dwarf::Tag Tag, DIScope *Context,
165 Metadata *NS, DIFile *File, unsigned Line, StringRef Name,
166 SmallVectorImpl<TrackingMDNodeRef> &AllImportedModules) {
168 assert(File && "Source location has line number but no file");
169 unsigned EntitiesCount = C.pImpl->DIImportedEntitys.size();
170 auto *M = DIImportedEntity::get(C, Tag, Context, cast_or_null<DINode>(NS),
172 if (EntitiesCount < C.pImpl->DIImportedEntitys.size())
173 // A new Imported Entity was just added to the context.
174 // Add it to the Imported Modules list.
175 AllImportedModules.emplace_back(M);
179 DIImportedEntity *DIBuilder::createImportedModule(DIScope *Context,
180 DINamespace *NS, DIFile *File,
182 return ::createImportedModule(VMContext, dwarf::DW_TAG_imported_module,
183 Context, NS, File, Line, StringRef(),
187 DIImportedEntity *DIBuilder::createImportedModule(DIScope *Context,
188 DIImportedEntity *NS,
189 DIFile *File, unsigned Line) {
190 return ::createImportedModule(VMContext, dwarf::DW_TAG_imported_module,
191 Context, NS, File, Line, StringRef(),
195 DIImportedEntity *DIBuilder::createImportedModule(DIScope *Context, DIModule *M,
196 DIFile *File, unsigned Line) {
197 return ::createImportedModule(VMContext, dwarf::DW_TAG_imported_module,
198 Context, M, File, Line, StringRef(),
202 DIImportedEntity *DIBuilder::createImportedDeclaration(DIScope *Context,
207 // Make sure to use the unique identifier based metadata reference for
208 // types that have one.
209 return ::createImportedModule(VMContext, dwarf::DW_TAG_imported_declaration,
210 Context, Decl, File, Line, Name,
214 DIFile *DIBuilder::createFile(StringRef Filename, StringRef Directory,
215 Optional<DIFile::ChecksumInfo<StringRef>> CS,
216 Optional<StringRef> Source) {
217 return DIFile::get(VMContext, Filename, Directory, CS, Source);
220 DIMacro *DIBuilder::createMacro(DIMacroFile *Parent, unsigned LineNumber,
221 unsigned MacroType, StringRef Name,
223 assert(!Name.empty() && "Unable to create macro without name");
224 assert((MacroType == dwarf::DW_MACINFO_undef ||
225 MacroType == dwarf::DW_MACINFO_define) &&
226 "Unexpected macro type");
227 auto *M = DIMacro::get(VMContext, MacroType, LineNumber, Name, Value);
228 AllMacrosPerParent[Parent].insert(M);
232 DIMacroFile *DIBuilder::createTempMacroFile(DIMacroFile *Parent,
233 unsigned LineNumber, DIFile *File) {
234 auto *MF = DIMacroFile::getTemporary(VMContext, dwarf::DW_MACINFO_start_file,
235 LineNumber, File, DIMacroNodeArray())
237 AllMacrosPerParent[Parent].insert(MF);
238 // Add the new temporary DIMacroFile to the macro per parent map as a parent.
239 // This is needed to assure DIMacroFile with no children to have an entry in
240 // the map. Otherwise, it will not be resolved in DIBuilder::finalize().
241 AllMacrosPerParent.insert({MF, {}});
245 DIEnumerator *DIBuilder::createEnumerator(StringRef Name, int64_t Val,
247 assert(!Name.empty() && "Unable to create enumerator without name");
248 return DIEnumerator::get(VMContext, Val, IsUnsigned, Name);
251 DIBasicType *DIBuilder::createUnspecifiedType(StringRef Name) {
252 assert(!Name.empty() && "Unable to create type without name");
253 return DIBasicType::get(VMContext, dwarf::DW_TAG_unspecified_type, Name);
256 DIBasicType *DIBuilder::createNullPtrType() {
257 return createUnspecifiedType("decltype(nullptr)");
260 DIBasicType *DIBuilder::createBasicType(StringRef Name, uint64_t SizeInBits,
262 DINode::DIFlags Flags) {
263 assert(!Name.empty() && "Unable to create type without name");
264 return DIBasicType::get(VMContext, dwarf::DW_TAG_base_type, Name, SizeInBits,
268 DIDerivedType *DIBuilder::createQualifiedType(unsigned Tag, DIType *FromTy) {
269 return DIDerivedType::get(VMContext, Tag, "", nullptr, 0, nullptr, FromTy, 0,
270 0, 0, None, DINode::FlagZero);
273 DIDerivedType *DIBuilder::createPointerType(
276 uint32_t AlignInBits,
277 Optional<unsigned> DWARFAddressSpace,
279 // FIXME: Why is there a name here?
280 return DIDerivedType::get(VMContext, dwarf::DW_TAG_pointer_type, Name,
281 nullptr, 0, nullptr, PointeeTy, SizeInBits,
282 AlignInBits, 0, DWARFAddressSpace,
286 DIDerivedType *DIBuilder::createMemberPointerType(DIType *PointeeTy,
289 uint32_t AlignInBits,
290 DINode::DIFlags Flags) {
291 return DIDerivedType::get(VMContext, dwarf::DW_TAG_ptr_to_member_type, "",
292 nullptr, 0, nullptr, PointeeTy, SizeInBits,
293 AlignInBits, 0, None, Flags, Base);
296 DIDerivedType *DIBuilder::createReferenceType(
297 unsigned Tag, DIType *RTy,
299 uint32_t AlignInBits,
300 Optional<unsigned> DWARFAddressSpace) {
301 assert(RTy && "Unable to create reference type");
302 return DIDerivedType::get(VMContext, Tag, "", nullptr, 0, nullptr, RTy,
303 SizeInBits, AlignInBits, 0, DWARFAddressSpace,
307 DIDerivedType *DIBuilder::createTypedef(DIType *Ty, StringRef Name,
308 DIFile *File, unsigned LineNo,
310 uint32_t AlignInBits) {
311 return DIDerivedType::get(VMContext, dwarf::DW_TAG_typedef, Name, File,
312 LineNo, getNonCompileUnitScope(Context), Ty, 0,
313 AlignInBits, 0, None, DINode::FlagZero);
316 DIDerivedType *DIBuilder::createFriend(DIType *Ty, DIType *FriendTy) {
317 assert(Ty && "Invalid type!");
318 assert(FriendTy && "Invalid friend type!");
319 return DIDerivedType::get(VMContext, dwarf::DW_TAG_friend, "", nullptr, 0, Ty,
320 FriendTy, 0, 0, 0, None, DINode::FlagZero);
323 DIDerivedType *DIBuilder::createInheritance(DIType *Ty, DIType *BaseTy,
325 uint32_t VBPtrOffset,
326 DINode::DIFlags Flags) {
327 assert(Ty && "Unable to create inheritance");
328 Metadata *ExtraData = ConstantAsMetadata::get(
329 ConstantInt::get(IntegerType::get(VMContext, 32), VBPtrOffset));
330 return DIDerivedType::get(VMContext, dwarf::DW_TAG_inheritance, "", nullptr,
331 0, Ty, BaseTy, 0, 0, BaseOffset, None,
335 DIDerivedType *DIBuilder::createMemberType(DIScope *Scope, StringRef Name,
336 DIFile *File, unsigned LineNumber,
338 uint32_t AlignInBits,
339 uint64_t OffsetInBits,
340 DINode::DIFlags Flags, DIType *Ty) {
341 return DIDerivedType::get(VMContext, dwarf::DW_TAG_member, Name, File,
342 LineNumber, getNonCompileUnitScope(Scope), Ty,
343 SizeInBits, AlignInBits, OffsetInBits, None, Flags);
346 static ConstantAsMetadata *getConstantOrNull(Constant *C) {
348 return ConstantAsMetadata::get(C);
352 DIDerivedType *DIBuilder::createVariantMemberType(
353 DIScope *Scope, StringRef Name, DIFile *File, unsigned LineNumber,
354 uint64_t SizeInBits, uint32_t AlignInBits, uint64_t OffsetInBits,
355 Constant *Discriminant, DINode::DIFlags Flags, DIType *Ty) {
356 return DIDerivedType::get(VMContext, dwarf::DW_TAG_member, Name, File,
357 LineNumber, getNonCompileUnitScope(Scope), Ty,
358 SizeInBits, AlignInBits, OffsetInBits, None, Flags,
359 getConstantOrNull(Discriminant));
362 DIDerivedType *DIBuilder::createBitFieldMemberType(
363 DIScope *Scope, StringRef Name, DIFile *File, unsigned LineNumber,
364 uint64_t SizeInBits, uint64_t OffsetInBits, uint64_t StorageOffsetInBits,
365 DINode::DIFlags Flags, DIType *Ty) {
366 Flags |= DINode::FlagBitField;
367 return DIDerivedType::get(
368 VMContext, dwarf::DW_TAG_member, Name, File, LineNumber,
369 getNonCompileUnitScope(Scope), Ty, SizeInBits, /* AlignInBits */ 0,
370 OffsetInBits, None, Flags,
371 ConstantAsMetadata::get(ConstantInt::get(IntegerType::get(VMContext, 64),
372 StorageOffsetInBits)));
376 DIBuilder::createStaticMemberType(DIScope *Scope, StringRef Name, DIFile *File,
377 unsigned LineNumber, DIType *Ty,
378 DINode::DIFlags Flags, llvm::Constant *Val,
379 uint32_t AlignInBits) {
380 Flags |= DINode::FlagStaticMember;
381 return DIDerivedType::get(VMContext, dwarf::DW_TAG_member, Name, File,
382 LineNumber, getNonCompileUnitScope(Scope), Ty, 0,
383 AlignInBits, 0, None, Flags,
384 getConstantOrNull(Val));
388 DIBuilder::createObjCIVar(StringRef Name, DIFile *File, unsigned LineNumber,
389 uint64_t SizeInBits, uint32_t AlignInBits,
390 uint64_t OffsetInBits, DINode::DIFlags Flags,
391 DIType *Ty, MDNode *PropertyNode) {
392 return DIDerivedType::get(VMContext, dwarf::DW_TAG_member, Name, File,
393 LineNumber, getNonCompileUnitScope(File), Ty,
394 SizeInBits, AlignInBits, OffsetInBits, None, Flags,
399 DIBuilder::createObjCProperty(StringRef Name, DIFile *File, unsigned LineNumber,
400 StringRef GetterName, StringRef SetterName,
401 unsigned PropertyAttributes, DIType *Ty) {
402 return DIObjCProperty::get(VMContext, Name, File, LineNumber, GetterName,
403 SetterName, PropertyAttributes, Ty);
406 DITemplateTypeParameter *
407 DIBuilder::createTemplateTypeParameter(DIScope *Context, StringRef Name,
409 assert((!Context || isa<DICompileUnit>(Context)) && "Expected compile unit");
410 return DITemplateTypeParameter::get(VMContext, Name, Ty);
413 static DITemplateValueParameter *
414 createTemplateValueParameterHelper(LLVMContext &VMContext, unsigned Tag,
415 DIScope *Context, StringRef Name, DIType *Ty,
417 assert((!Context || isa<DICompileUnit>(Context)) && "Expected compile unit");
418 return DITemplateValueParameter::get(VMContext, Tag, Name, Ty, MD);
421 DITemplateValueParameter *
422 DIBuilder::createTemplateValueParameter(DIScope *Context, StringRef Name,
423 DIType *Ty, Constant *Val) {
424 return createTemplateValueParameterHelper(
425 VMContext, dwarf::DW_TAG_template_value_parameter, Context, Name, Ty,
426 getConstantOrNull(Val));
429 DITemplateValueParameter *
430 DIBuilder::createTemplateTemplateParameter(DIScope *Context, StringRef Name,
431 DIType *Ty, StringRef Val) {
432 return createTemplateValueParameterHelper(
433 VMContext, dwarf::DW_TAG_GNU_template_template_param, Context, Name, Ty,
434 MDString::get(VMContext, Val));
437 DITemplateValueParameter *
438 DIBuilder::createTemplateParameterPack(DIScope *Context, StringRef Name,
439 DIType *Ty, DINodeArray Val) {
440 return createTemplateValueParameterHelper(
441 VMContext, dwarf::DW_TAG_GNU_template_parameter_pack, Context, Name, Ty,
445 DICompositeType *DIBuilder::createClassType(
446 DIScope *Context, StringRef Name, DIFile *File, unsigned LineNumber,
447 uint64_t SizeInBits, uint32_t AlignInBits, uint64_t OffsetInBits,
448 DINode::DIFlags Flags, DIType *DerivedFrom, DINodeArray Elements,
449 DIType *VTableHolder, MDNode *TemplateParams, StringRef UniqueIdentifier) {
450 assert((!Context || isa<DIScope>(Context)) &&
451 "createClassType should be called with a valid Context");
453 auto *R = DICompositeType::get(
454 VMContext, dwarf::DW_TAG_structure_type, Name, File, LineNumber,
455 getNonCompileUnitScope(Context), DerivedFrom, SizeInBits, AlignInBits,
456 OffsetInBits, Flags, Elements, 0, VTableHolder,
457 cast_or_null<MDTuple>(TemplateParams), UniqueIdentifier);
458 trackIfUnresolved(R);
462 DICompositeType *DIBuilder::createStructType(
463 DIScope *Context, StringRef Name, DIFile *File, unsigned LineNumber,
464 uint64_t SizeInBits, uint32_t AlignInBits, DINode::DIFlags Flags,
465 DIType *DerivedFrom, DINodeArray Elements, unsigned RunTimeLang,
466 DIType *VTableHolder, StringRef UniqueIdentifier) {
467 auto *R = DICompositeType::get(
468 VMContext, dwarf::DW_TAG_structure_type, Name, File, LineNumber,
469 getNonCompileUnitScope(Context), DerivedFrom, SizeInBits, AlignInBits, 0,
470 Flags, Elements, RunTimeLang, VTableHolder, nullptr, UniqueIdentifier);
471 trackIfUnresolved(R);
475 DICompositeType *DIBuilder::createUnionType(
476 DIScope *Scope, StringRef Name, DIFile *File, unsigned LineNumber,
477 uint64_t SizeInBits, uint32_t AlignInBits, DINode::DIFlags Flags,
478 DINodeArray Elements, unsigned RunTimeLang, StringRef UniqueIdentifier) {
479 auto *R = DICompositeType::get(
480 VMContext, dwarf::DW_TAG_union_type, Name, File, LineNumber,
481 getNonCompileUnitScope(Scope), nullptr, SizeInBits, AlignInBits, 0, Flags,
482 Elements, RunTimeLang, nullptr, nullptr, UniqueIdentifier);
483 trackIfUnresolved(R);
487 DICompositeType *DIBuilder::createVariantPart(
488 DIScope *Scope, StringRef Name, DIFile *File, unsigned LineNumber,
489 uint64_t SizeInBits, uint32_t AlignInBits, DINode::DIFlags Flags,
490 DIDerivedType *Discriminator, DINodeArray Elements, StringRef UniqueIdentifier) {
491 auto *R = DICompositeType::get(
492 VMContext, dwarf::DW_TAG_variant_part, Name, File, LineNumber,
493 getNonCompileUnitScope(Scope), nullptr, SizeInBits, AlignInBits, 0, Flags,
494 Elements, 0, nullptr, nullptr, UniqueIdentifier, Discriminator);
495 trackIfUnresolved(R);
499 DISubroutineType *DIBuilder::createSubroutineType(DITypeRefArray ParameterTypes,
500 DINode::DIFlags Flags,
502 return DISubroutineType::get(VMContext, Flags, CC, ParameterTypes);
505 DICompositeType *DIBuilder::createEnumerationType(
506 DIScope *Scope, StringRef Name, DIFile *File, unsigned LineNumber,
507 uint64_t SizeInBits, uint32_t AlignInBits, DINodeArray Elements,
508 DIType *UnderlyingType, StringRef UniqueIdentifier, bool IsScoped) {
509 auto *CTy = DICompositeType::get(
510 VMContext, dwarf::DW_TAG_enumeration_type, Name, File, LineNumber,
511 getNonCompileUnitScope(Scope), UnderlyingType, SizeInBits, AlignInBits, 0,
512 IsScoped ? DINode::FlagEnumClass : DINode::FlagZero, Elements, 0, nullptr,
513 nullptr, UniqueIdentifier);
514 AllEnumTypes.push_back(CTy);
515 trackIfUnresolved(CTy);
519 DICompositeType *DIBuilder::createArrayType(uint64_t Size,
520 uint32_t AlignInBits, DIType *Ty,
521 DINodeArray Subscripts) {
522 auto *R = DICompositeType::get(VMContext, dwarf::DW_TAG_array_type, "",
523 nullptr, 0, nullptr, Ty, Size, AlignInBits, 0,
524 DINode::FlagZero, Subscripts, 0, nullptr);
525 trackIfUnresolved(R);
529 DICompositeType *DIBuilder::createVectorType(uint64_t Size,
530 uint32_t AlignInBits, DIType *Ty,
531 DINodeArray Subscripts) {
532 auto *R = DICompositeType::get(VMContext, dwarf::DW_TAG_array_type, "",
533 nullptr, 0, nullptr, Ty, Size, AlignInBits, 0,
534 DINode::FlagVector, Subscripts, 0, nullptr);
535 trackIfUnresolved(R);
539 DISubprogram *DIBuilder::createArtificialSubprogram(DISubprogram *SP) {
540 auto NewSP = SP->cloneWithFlags(SP->getFlags() | DINode::FlagArtificial);
541 return MDNode::replaceWithDistinct(std::move(NewSP));
544 static DIType *createTypeWithFlags(const DIType *Ty,
545 DINode::DIFlags FlagsToSet) {
546 auto NewTy = Ty->cloneWithFlags(Ty->getFlags() | FlagsToSet);
547 return MDNode::replaceWithUniqued(std::move(NewTy));
550 DIType *DIBuilder::createArtificialType(DIType *Ty) {
551 // FIXME: Restrict this to the nodes where it's valid.
552 if (Ty->isArtificial())
554 return createTypeWithFlags(Ty, DINode::FlagArtificial);
557 DIType *DIBuilder::createObjectPointerType(DIType *Ty) {
558 // FIXME: Restrict this to the nodes where it's valid.
559 if (Ty->isObjectPointer())
561 DINode::DIFlags Flags = DINode::FlagObjectPointer | DINode::FlagArtificial;
562 return createTypeWithFlags(Ty, Flags);
565 void DIBuilder::retainType(DIScope *T) {
566 assert(T && "Expected non-null type");
567 assert((isa<DIType>(T) || (isa<DISubprogram>(T) &&
568 cast<DISubprogram>(T)->isDefinition() == false)) &&
569 "Expected type or subprogram declaration");
570 AllRetainTypes.emplace_back(T);
573 DIBasicType *DIBuilder::createUnspecifiedParameter() { return nullptr; }
576 DIBuilder::createForwardDecl(unsigned Tag, StringRef Name, DIScope *Scope,
577 DIFile *F, unsigned Line, unsigned RuntimeLang,
578 uint64_t SizeInBits, uint32_t AlignInBits,
579 StringRef UniqueIdentifier) {
580 // FIXME: Define in terms of createReplaceableForwardDecl() by calling
581 // replaceWithUniqued().
582 auto *RetTy = DICompositeType::get(
583 VMContext, Tag, Name, F, Line, getNonCompileUnitScope(Scope), nullptr,
584 SizeInBits, AlignInBits, 0, DINode::FlagFwdDecl, nullptr, RuntimeLang,
585 nullptr, nullptr, UniqueIdentifier);
586 trackIfUnresolved(RetTy);
590 DICompositeType *DIBuilder::createReplaceableCompositeType(
591 unsigned Tag, StringRef Name, DIScope *Scope, DIFile *F, unsigned Line,
592 unsigned RuntimeLang, uint64_t SizeInBits, uint32_t AlignInBits,
593 DINode::DIFlags Flags, StringRef UniqueIdentifier) {
595 DICompositeType::getTemporary(
596 VMContext, Tag, Name, F, Line, getNonCompileUnitScope(Scope), nullptr,
597 SizeInBits, AlignInBits, 0, Flags, nullptr, RuntimeLang, nullptr,
598 nullptr, UniqueIdentifier)
600 trackIfUnresolved(RetTy);
604 DINodeArray DIBuilder::getOrCreateArray(ArrayRef<Metadata *> Elements) {
605 return MDTuple::get(VMContext, Elements);
609 DIBuilder::getOrCreateMacroArray(ArrayRef<Metadata *> Elements) {
610 return MDTuple::get(VMContext, Elements);
613 DITypeRefArray DIBuilder::getOrCreateTypeArray(ArrayRef<Metadata *> Elements) {
614 SmallVector<llvm::Metadata *, 16> Elts;
615 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
616 if (Elements[i] && isa<MDNode>(Elements[i]))
617 Elts.push_back(cast<DIType>(Elements[i]));
619 Elts.push_back(Elements[i]);
621 return DITypeRefArray(MDNode::get(VMContext, Elts));
624 DISubrange *DIBuilder::getOrCreateSubrange(int64_t Lo, int64_t Count) {
625 return DISubrange::get(VMContext, Count, Lo);
628 DISubrange *DIBuilder::getOrCreateSubrange(int64_t Lo, Metadata *CountNode) {
629 return DISubrange::get(VMContext, CountNode, Lo);
632 static void checkGlobalVariableScope(DIScope *Context) {
635 dyn_cast_or_null<DICompositeType>(getNonCompileUnitScope(Context)))
636 assert(CT->getIdentifier().empty() &&
637 "Context of a global variable should not be a type with identifier");
641 DIGlobalVariableExpression *DIBuilder::createGlobalVariableExpression(
642 DIScope *Context, StringRef Name, StringRef LinkageName, DIFile *F,
643 unsigned LineNumber, DIType *Ty, bool IsLocalToUnit,
644 bool isDefined, DIExpression *Expr,
645 MDNode *Decl, MDTuple *TemplateParams, uint32_t AlignInBits) {
646 checkGlobalVariableScope(Context);
648 auto *GV = DIGlobalVariable::getDistinct(
649 VMContext, cast_or_null<DIScope>(Context), Name, LinkageName, F,
650 LineNumber, Ty, IsLocalToUnit, isDefined, cast_or_null<DIDerivedType>(Decl),
651 TemplateParams, AlignInBits);
653 Expr = createExpression();
654 auto *N = DIGlobalVariableExpression::get(VMContext, GV, Expr);
659 DIGlobalVariable *DIBuilder::createTempGlobalVariableFwdDecl(
660 DIScope *Context, StringRef Name, StringRef LinkageName, DIFile *F,
661 unsigned LineNumber, DIType *Ty, bool IsLocalToUnit, MDNode *Decl,
662 MDTuple *TemplateParams, uint32_t AlignInBits) {
663 checkGlobalVariableScope(Context);
665 return DIGlobalVariable::getTemporary(
666 VMContext, cast_or_null<DIScope>(Context), Name, LinkageName, F,
667 LineNumber, Ty, IsLocalToUnit, false,
668 cast_or_null<DIDerivedType>(Decl), TemplateParams, AlignInBits)
672 static DILocalVariable *createLocalVariable(
673 LLVMContext &VMContext,
674 DenseMap<MDNode *, SmallVector<TrackingMDNodeRef, 1>> &PreservedVariables,
675 DIScope *Scope, StringRef Name, unsigned ArgNo, DIFile *File,
676 unsigned LineNo, DIType *Ty, bool AlwaysPreserve, DINode::DIFlags Flags,
677 uint32_t AlignInBits) {
678 // FIXME: Why getNonCompileUnitScope()?
679 // FIXME: Why is "!Context" okay here?
680 // FIXME: Why doesn't this check for a subprogram or lexical block (AFAICT
681 // the only valid scopes)?
682 DIScope *Context = getNonCompileUnitScope(Scope);
685 DILocalVariable::get(VMContext, cast_or_null<DILocalScope>(Context), Name,
686 File, LineNo, Ty, ArgNo, Flags, AlignInBits);
687 if (AlwaysPreserve) {
688 // The optimizer may remove local variables. If there is an interest
689 // to preserve variable info in such situation then stash it in a
691 DISubprogram *Fn = getDISubprogram(Scope);
692 assert(Fn && "Missing subprogram for local variable");
693 PreservedVariables[Fn].emplace_back(Node);
698 DILocalVariable *DIBuilder::createAutoVariable(DIScope *Scope, StringRef Name,
699 DIFile *File, unsigned LineNo,
700 DIType *Ty, bool AlwaysPreserve,
701 DINode::DIFlags Flags,
702 uint32_t AlignInBits) {
703 return createLocalVariable(VMContext, PreservedVariables, Scope, Name,
704 /* ArgNo */ 0, File, LineNo, Ty, AlwaysPreserve,
708 DILocalVariable *DIBuilder::createParameterVariable(
709 DIScope *Scope, StringRef Name, unsigned ArgNo, DIFile *File,
710 unsigned LineNo, DIType *Ty, bool AlwaysPreserve, DINode::DIFlags Flags) {
711 assert(ArgNo && "Expected non-zero argument number for parameter");
712 return createLocalVariable(VMContext, PreservedVariables, Scope, Name, ArgNo,
713 File, LineNo, Ty, AlwaysPreserve, Flags,
717 DILabel *DIBuilder::createLabel(
718 DIScope *Scope, StringRef Name, DIFile *File,
719 unsigned LineNo, bool AlwaysPreserve) {
720 DIScope *Context = getNonCompileUnitScope(Scope);
723 DILabel::get(VMContext, cast_or_null<DILocalScope>(Context), Name,
726 if (AlwaysPreserve) {
727 /// The optimizer may remove labels. If there is an interest
728 /// to preserve label info in such situation then append it to
729 /// the list of retained nodes of the DISubprogram.
730 DISubprogram *Fn = getDISubprogram(Scope);
731 assert(Fn && "Missing subprogram for label");
732 PreservedLabels[Fn].emplace_back(Node);
737 DIExpression *DIBuilder::createExpression(ArrayRef<uint64_t> Addr) {
738 return DIExpression::get(VMContext, Addr);
741 DIExpression *DIBuilder::createExpression(ArrayRef<int64_t> Signed) {
742 // TODO: Remove the callers of this signed version and delete.
743 SmallVector<uint64_t, 8> Addr(Signed.begin(), Signed.end());
744 return createExpression(Addr);
747 template <class... Ts>
748 static DISubprogram *getSubprogram(bool IsDistinct, Ts &&... Args) {
750 return DISubprogram::getDistinct(std::forward<Ts>(Args)...);
751 return DISubprogram::get(std::forward<Ts>(Args)...);
754 DISubprogram *DIBuilder::createFunction(
755 DIScope *Context, StringRef Name, StringRef LinkageName, DIFile *File,
756 unsigned LineNo, DISubroutineType *Ty, unsigned ScopeLine,
757 DINode::DIFlags Flags, DISubprogram::DISPFlags SPFlags,
758 DITemplateParameterArray TParams, DISubprogram *Decl,
759 DITypeArray ThrownTypes) {
760 bool IsDefinition = SPFlags & DISubprogram::SPFlagDefinition;
761 auto *Node = getSubprogram(
762 /*IsDistinct=*/IsDefinition, VMContext, getNonCompileUnitScope(Context),
763 Name, LinkageName, File, LineNo, Ty, ScopeLine, nullptr, 0, 0, Flags,
764 SPFlags, IsDefinition ? CUNode : nullptr, TParams, Decl,
765 MDTuple::getTemporary(VMContext, None).release(), ThrownTypes);
768 AllSubprograms.push_back(Node);
769 trackIfUnresolved(Node);
773 DISubprogram *DIBuilder::createTempFunctionFwdDecl(
774 DIScope *Context, StringRef Name, StringRef LinkageName, DIFile *File,
775 unsigned LineNo, DISubroutineType *Ty, unsigned ScopeLine,
776 DINode::DIFlags Flags, DISubprogram::DISPFlags SPFlags,
777 DITemplateParameterArray TParams, DISubprogram *Decl,
778 DITypeArray ThrownTypes) {
779 bool IsDefinition = SPFlags & DISubprogram::SPFlagDefinition;
780 return DISubprogram::getTemporary(VMContext, getNonCompileUnitScope(Context),
781 Name, LinkageName, File, LineNo, Ty,
782 ScopeLine, nullptr, 0, 0, Flags, SPFlags,
783 IsDefinition ? CUNode : nullptr, TParams,
784 Decl, nullptr, ThrownTypes)
788 DISubprogram *DIBuilder::createMethod(
789 DIScope *Context, StringRef Name, StringRef LinkageName, DIFile *F,
790 unsigned LineNo, DISubroutineType *Ty, unsigned VIndex, int ThisAdjustment,
791 DIType *VTableHolder, DINode::DIFlags Flags,
792 DISubprogram::DISPFlags SPFlags, DITemplateParameterArray TParams,
793 DITypeArray ThrownTypes) {
794 assert(getNonCompileUnitScope(Context) &&
795 "Methods should have both a Context and a context that isn't "
796 "the compile unit.");
797 // FIXME: Do we want to use different scope/lines?
798 bool IsDefinition = SPFlags & DISubprogram::SPFlagDefinition;
799 auto *SP = getSubprogram(
800 /*IsDistinct=*/IsDefinition, VMContext, cast<DIScope>(Context), Name,
801 LinkageName, F, LineNo, Ty, LineNo, VTableHolder, VIndex, ThisAdjustment,
802 Flags, SPFlags, IsDefinition ? CUNode : nullptr, TParams, nullptr,
803 nullptr, ThrownTypes);
806 AllSubprograms.push_back(SP);
807 trackIfUnresolved(SP);
811 DICommonBlock *DIBuilder::createCommonBlock(
812 DIScope *Scope, DIGlobalVariable *Decl, StringRef Name, DIFile *File,
814 return DICommonBlock::get(
815 VMContext, Scope, Decl, Name, File, LineNo);
818 DINamespace *DIBuilder::createNameSpace(DIScope *Scope, StringRef Name,
819 bool ExportSymbols) {
821 // It is okay to *not* make anonymous top-level namespaces distinct, because
822 // all nodes that have an anonymous namespace as their parent scope are
823 // guaranteed to be unique and/or are linked to their containing
824 // DICompileUnit. This decision is an explicit tradeoff of link time versus
825 // memory usage versus code simplicity and may get revisited in the future.
826 return DINamespace::get(VMContext, getNonCompileUnitScope(Scope), Name,
830 DIModule *DIBuilder::createModule(DIScope *Scope, StringRef Name,
831 StringRef ConfigurationMacros,
832 StringRef IncludePath,
834 return DIModule::get(VMContext, getNonCompileUnitScope(Scope), Name,
835 ConfigurationMacros, IncludePath, SysRoot);
838 DILexicalBlockFile *DIBuilder::createLexicalBlockFile(DIScope *Scope,
840 unsigned Discriminator) {
841 return DILexicalBlockFile::get(VMContext, Scope, File, Discriminator);
844 DILexicalBlock *DIBuilder::createLexicalBlock(DIScope *Scope, DIFile *File,
845 unsigned Line, unsigned Col) {
846 // Make these distinct, to avoid merging two lexical blocks on the same
848 return DILexicalBlock::getDistinct(VMContext, getNonCompileUnitScope(Scope),
852 Instruction *DIBuilder::insertDeclare(Value *Storage, DILocalVariable *VarInfo,
853 DIExpression *Expr, const DILocation *DL,
854 Instruction *InsertBefore) {
855 return insertDeclare(Storage, VarInfo, Expr, DL, InsertBefore->getParent(),
859 Instruction *DIBuilder::insertDeclare(Value *Storage, DILocalVariable *VarInfo,
860 DIExpression *Expr, const DILocation *DL,
861 BasicBlock *InsertAtEnd) {
862 // If this block already has a terminator then insert this intrinsic before
863 // the terminator. Otherwise, put it at the end of the block.
864 Instruction *InsertBefore = InsertAtEnd->getTerminator();
865 return insertDeclare(Storage, VarInfo, Expr, DL, InsertAtEnd, InsertBefore);
868 Instruction *DIBuilder::insertLabel(DILabel *LabelInfo, const DILocation *DL,
869 Instruction *InsertBefore) {
871 LabelInfo, DL, InsertBefore ? InsertBefore->getParent() : nullptr,
875 Instruction *DIBuilder::insertLabel(DILabel *LabelInfo, const DILocation *DL,
876 BasicBlock *InsertAtEnd) {
877 return insertLabel(LabelInfo, DL, InsertAtEnd, nullptr);
880 Instruction *DIBuilder::insertDbgValueIntrinsic(Value *V,
881 DILocalVariable *VarInfo,
883 const DILocation *DL,
884 Instruction *InsertBefore) {
885 return insertDbgValueIntrinsic(
886 V, VarInfo, Expr, DL, InsertBefore ? InsertBefore->getParent() : nullptr,
890 Instruction *DIBuilder::insertDbgValueIntrinsic(Value *V,
891 DILocalVariable *VarInfo,
893 const DILocation *DL,
894 BasicBlock *InsertAtEnd) {
895 return insertDbgValueIntrinsic(V, VarInfo, Expr, DL, InsertAtEnd, nullptr);
898 /// Return an IRBuilder for inserting dbg.declare and dbg.value intrinsics. This
899 /// abstracts over the various ways to specify an insert position.
900 static IRBuilder<> getIRBForDbgInsertion(const DILocation *DL,
901 BasicBlock *InsertBB,
902 Instruction *InsertBefore) {
903 IRBuilder<> B(DL->getContext());
905 B.SetInsertPoint(InsertBefore);
907 B.SetInsertPoint(InsertBB);
908 B.SetCurrentDebugLocation(DL);
912 static Value *getDbgIntrinsicValueImpl(LLVMContext &VMContext, Value *V) {
913 assert(V && "no value passed to dbg intrinsic");
914 return MetadataAsValue::get(VMContext, ValueAsMetadata::get(V));
917 static Function *getDeclareIntrin(Module &M) {
918 return Intrinsic::getDeclaration(&M, UseDbgAddr ? Intrinsic::dbg_addr
919 : Intrinsic::dbg_declare);
922 Instruction *DIBuilder::insertDeclare(Value *Storage, DILocalVariable *VarInfo,
923 DIExpression *Expr, const DILocation *DL,
924 BasicBlock *InsertBB, Instruction *InsertBefore) {
925 assert(VarInfo && "empty or invalid DILocalVariable* passed to dbg.declare");
926 assert(DL && "Expected debug loc");
927 assert(DL->getScope()->getSubprogram() ==
928 VarInfo->getScope()->getSubprogram() &&
929 "Expected matching subprograms");
931 DeclareFn = getDeclareIntrin(M);
933 trackIfUnresolved(VarInfo);
934 trackIfUnresolved(Expr);
935 Value *Args[] = {getDbgIntrinsicValueImpl(VMContext, Storage),
936 MetadataAsValue::get(VMContext, VarInfo),
937 MetadataAsValue::get(VMContext, Expr)};
939 IRBuilder<> B = getIRBForDbgInsertion(DL, InsertBB, InsertBefore);
940 return B.CreateCall(DeclareFn, Args);
943 Instruction *DIBuilder::insertDbgValueIntrinsic(
944 Value *V, DILocalVariable *VarInfo, DIExpression *Expr,
945 const DILocation *DL, BasicBlock *InsertBB, Instruction *InsertBefore) {
946 assert(V && "no value passed to dbg.value");
947 assert(VarInfo && "empty or invalid DILocalVariable* passed to dbg.value");
948 assert(DL && "Expected debug loc");
949 assert(DL->getScope()->getSubprogram() ==
950 VarInfo->getScope()->getSubprogram() &&
951 "Expected matching subprograms");
953 ValueFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_value);
955 trackIfUnresolved(VarInfo);
956 trackIfUnresolved(Expr);
957 Value *Args[] = {getDbgIntrinsicValueImpl(VMContext, V),
958 MetadataAsValue::get(VMContext, VarInfo),
959 MetadataAsValue::get(VMContext, Expr)};
961 IRBuilder<> B = getIRBForDbgInsertion(DL, InsertBB, InsertBefore);
962 return B.CreateCall(ValueFn, Args);
965 Instruction *DIBuilder::insertLabel(
966 DILabel *LabelInfo, const DILocation *DL,
967 BasicBlock *InsertBB, Instruction *InsertBefore) {
968 assert(LabelInfo && "empty or invalid DILabel* passed to dbg.label");
969 assert(DL && "Expected debug loc");
970 assert(DL->getScope()->getSubprogram() ==
971 LabelInfo->getScope()->getSubprogram() &&
972 "Expected matching subprograms");
974 LabelFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_label);
976 trackIfUnresolved(LabelInfo);
977 Value *Args[] = {MetadataAsValue::get(VMContext, LabelInfo)};
979 IRBuilder<> B = getIRBForDbgInsertion(DL, InsertBB, InsertBefore);
980 return B.CreateCall(LabelFn, Args);
983 void DIBuilder::replaceVTableHolder(DICompositeType *&T,
984 DIType *VTableHolder) {
986 TypedTrackingMDRef<DICompositeType> N(T);
987 N->replaceVTableHolder(VTableHolder);
991 // If this didn't create a self-reference, just return.
992 if (T != VTableHolder)
995 // Look for unresolved operands. T will drop RAUW support, orphaning any
996 // cycles underneath it.
998 for (const MDOperand &O : T->operands())
999 if (auto *N = dyn_cast_or_null<MDNode>(O))
1000 trackIfUnresolved(N);
1003 void DIBuilder::replaceArrays(DICompositeType *&T, DINodeArray Elements,
1004 DINodeArray TParams) {
1006 TypedTrackingMDRef<DICompositeType> N(T);
1008 N->replaceElements(Elements);
1010 N->replaceTemplateParams(DITemplateParameterArray(TParams));
1014 // If T isn't resolved, there's no problem.
1015 if (!T->isResolved())
1018 // If T is resolved, it may be due to a self-reference cycle. Track the
1019 // arrays explicitly if they're unresolved, or else the cycles will be
1022 trackIfUnresolved(Elements.get());
1024 trackIfUnresolved(TParams.get());