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"
22 #include "LLVMContextImpl.h"
25 using namespace llvm::dwarf;
27 DIBuilder::DIBuilder(Module &m, bool AllowUnresolvedNodes)
28 : M(m), VMContext(M.getContext()), CUNode(nullptr),
29 DeclareFn(nullptr), ValueFn(nullptr),
30 AllowUnresolvedNodes(AllowUnresolvedNodes) {}
32 void DIBuilder::trackIfUnresolved(MDNode *N) {
38 assert(AllowUnresolvedNodes && "Cannot handle unresolved nodes");
39 UnresolvedNodes.emplace_back(N);
42 void DIBuilder::finalize() {
44 assert(!AllowUnresolvedNodes &&
45 "creating type nodes without a CU is not supported");
49 CUNode->replaceEnumTypes(MDTuple::get(VMContext, AllEnumTypes));
51 SmallVector<Metadata *, 16> RetainValues;
52 // Declarations and definitions of the same type may be retained. Some
53 // clients RAUW these pairs, leaving duplicates in the retained types
54 // list. Use a set to remove the duplicates while we transform the
55 // TrackingVHs back into Values.
56 SmallPtrSet<Metadata *, 16> RetainSet;
57 for (unsigned I = 0, E = AllRetainTypes.size(); I < E; I++)
58 if (RetainSet.insert(AllRetainTypes[I]).second)
59 RetainValues.push_back(AllRetainTypes[I]);
61 if (!RetainValues.empty())
62 CUNode->replaceRetainedTypes(MDTuple::get(VMContext, RetainValues));
64 DISubprogramArray SPs = MDTuple::get(VMContext, AllSubprograms);
65 auto resolveVariables = [&](DISubprogram *SP) {
66 MDTuple *Temp = SP->getVariables().get();
70 SmallVector<Metadata *, 4> Variables;
72 auto PV = PreservedVariables.find(SP);
73 if (PV != PreservedVariables.end())
74 Variables.append(PV->second.begin(), PV->second.end());
76 DINodeArray AV = getOrCreateArray(Variables);
77 TempMDTuple(Temp)->replaceAllUsesWith(AV.get());
81 for (auto *N : RetainValues)
82 if (auto *SP = dyn_cast<DISubprogram>(N))
86 CUNode->replaceGlobalVariables(MDTuple::get(VMContext, AllGVs));
88 if (!AllImportedModules.empty())
89 CUNode->replaceImportedEntities(MDTuple::get(
90 VMContext, SmallVector<Metadata *, 16>(AllImportedModules.begin(),
91 AllImportedModules.end())));
93 for (const auto &I : AllMacrosPerParent) {
94 // DIMacroNode's with nullptr parent are DICompileUnit direct children.
96 CUNode->replaceMacros(MDTuple::get(VMContext, I.second.getArrayRef()));
99 // Otherwise, it must be a temporary DIMacroFile that need to be resolved.
100 auto *TMF = cast<DIMacroFile>(I.first);
101 auto *MF = DIMacroFile::get(VMContext, dwarf::DW_MACINFO_start_file,
102 TMF->getLine(), TMF->getFile(),
103 getOrCreateMacroArray(I.second.getArrayRef()));
104 replaceTemporary(llvm::TempDIMacroNode(TMF), MF);
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, DIFile *File, StringRef Producer, bool isOptimized,
127 StringRef Flags, unsigned RunTimeVer, StringRef SplitName,
128 DICompileUnit::DebugEmissionKind Kind, uint64_t DWOId,
129 bool SplitDebugInlining, bool DebugInfoForProfiling) {
131 assert(((Lang <= dwarf::DW_LANG_Fortran08 && Lang >= dwarf::DW_LANG_C89) ||
132 (Lang <= dwarf::DW_LANG_hi_user && Lang >= dwarf::DW_LANG_lo_user)) &&
133 "Invalid Language tag");
135 assert(!CUNode && "Can only make one compile unit per DIBuilder instance");
136 CUNode = DICompileUnit::getDistinct(
137 VMContext, Lang, File, Producer, isOptimized, Flags, RunTimeVer,
138 SplitName, Kind, nullptr, nullptr, nullptr, nullptr, nullptr, DWOId,
139 SplitDebugInlining, DebugInfoForProfiling);
141 // Create a named metadata so that it is easier to find cu in a module.
142 NamedMDNode *NMD = M.getOrInsertNamedMetadata("llvm.dbg.cu");
143 NMD->addOperand(CUNode);
144 trackIfUnresolved(CUNode);
148 static DIImportedEntity *
149 createImportedModule(LLVMContext &C, dwarf::Tag Tag, DIScope *Context,
150 Metadata *NS, unsigned Line, StringRef Name,
151 SmallVectorImpl<TrackingMDNodeRef> &AllImportedModules) {
152 unsigned EntitiesCount = C.pImpl->DIImportedEntitys.size();
153 auto *M = DIImportedEntity::get(C, Tag, Context, DINodeRef(NS), Line, Name);
154 if (EntitiesCount < C.pImpl->DIImportedEntitys.size())
155 // A new Imported Entity was just added to the context.
156 // Add it to the Imported Modules list.
157 AllImportedModules.emplace_back(M);
161 DIImportedEntity *DIBuilder::createImportedModule(DIScope *Context,
164 return ::createImportedModule(VMContext, dwarf::DW_TAG_imported_module,
165 Context, NS, Line, StringRef(), AllImportedModules);
168 DIImportedEntity *DIBuilder::createImportedModule(DIScope *Context,
169 DIImportedEntity *NS,
171 return ::createImportedModule(VMContext, dwarf::DW_TAG_imported_module,
172 Context, NS, Line, StringRef(), AllImportedModules);
175 DIImportedEntity *DIBuilder::createImportedModule(DIScope *Context, DIModule *M,
177 return ::createImportedModule(VMContext, dwarf::DW_TAG_imported_module,
178 Context, M, Line, StringRef(), AllImportedModules);
181 DIImportedEntity *DIBuilder::createImportedDeclaration(DIScope *Context,
185 // Make sure to use the unique identifier based metadata reference for
186 // types that have one.
187 return ::createImportedModule(VMContext, dwarf::DW_TAG_imported_declaration,
188 Context, Decl, Line, Name, AllImportedModules);
191 DIFile *DIBuilder::createFile(StringRef Filename, StringRef Directory,
192 DIFile::ChecksumKind CSKind, StringRef Checksum) {
193 return DIFile::get(VMContext, Filename, Directory, CSKind, Checksum);
196 DIMacro *DIBuilder::createMacro(DIMacroFile *Parent, unsigned LineNumber,
197 unsigned MacroType, StringRef Name,
199 assert(!Name.empty() && "Unable to create macro without name");
200 assert((MacroType == dwarf::DW_MACINFO_undef ||
201 MacroType == dwarf::DW_MACINFO_define) &&
202 "Unexpected macro type");
203 auto *M = DIMacro::get(VMContext, MacroType, LineNumber, Name, Value);
204 AllMacrosPerParent[Parent].insert(M);
208 DIMacroFile *DIBuilder::createTempMacroFile(DIMacroFile *Parent,
209 unsigned LineNumber, DIFile *File) {
210 auto *MF = DIMacroFile::getTemporary(VMContext, dwarf::DW_MACINFO_start_file,
211 LineNumber, File, DIMacroNodeArray())
213 AllMacrosPerParent[Parent].insert(MF);
214 // Add the new temporary DIMacroFile to the macro per parent map as a parent.
215 // This is needed to assure DIMacroFile with no children to have an entry in
216 // the map. Otherwise, it will not be resolved in DIBuilder::finalize().
217 AllMacrosPerParent.insert({MF, {}});
221 DIEnumerator *DIBuilder::createEnumerator(StringRef Name, int64_t Val) {
222 assert(!Name.empty() && "Unable to create enumerator without name");
223 return DIEnumerator::get(VMContext, Val, Name);
226 DIBasicType *DIBuilder::createUnspecifiedType(StringRef Name) {
227 assert(!Name.empty() && "Unable to create type without name");
228 return DIBasicType::get(VMContext, dwarf::DW_TAG_unspecified_type, Name);
231 DIBasicType *DIBuilder::createNullPtrType() {
232 return createUnspecifiedType("decltype(nullptr)");
235 DIBasicType *DIBuilder::createBasicType(StringRef Name, uint64_t SizeInBits,
237 assert(!Name.empty() && "Unable to create type without name");
238 return DIBasicType::get(VMContext, dwarf::DW_TAG_base_type, Name, SizeInBits,
242 DIDerivedType *DIBuilder::createQualifiedType(unsigned Tag, DIType *FromTy) {
243 return DIDerivedType::get(VMContext, Tag, "", nullptr, 0, nullptr, FromTy, 0,
244 0, 0, None, DINode::FlagZero);
247 DIDerivedType *DIBuilder::createPointerType(
250 uint32_t AlignInBits,
251 Optional<unsigned> DWARFAddressSpace,
253 // FIXME: Why is there a name here?
254 return DIDerivedType::get(VMContext, dwarf::DW_TAG_pointer_type, Name,
255 nullptr, 0, nullptr, PointeeTy, SizeInBits,
256 AlignInBits, 0, DWARFAddressSpace,
260 DIDerivedType *DIBuilder::createMemberPointerType(DIType *PointeeTy,
263 uint32_t AlignInBits,
264 DINode::DIFlags Flags) {
265 return DIDerivedType::get(VMContext, dwarf::DW_TAG_ptr_to_member_type, "",
266 nullptr, 0, nullptr, PointeeTy, SizeInBits,
267 AlignInBits, 0, None, Flags, Base);
270 DIDerivedType *DIBuilder::createReferenceType(
271 unsigned Tag, DIType *RTy,
273 uint32_t AlignInBits,
274 Optional<unsigned> DWARFAddressSpace) {
275 assert(RTy && "Unable to create reference type");
276 return DIDerivedType::get(VMContext, Tag, "", nullptr, 0, nullptr, RTy,
277 SizeInBits, AlignInBits, 0, DWARFAddressSpace,
281 DIDerivedType *DIBuilder::createTypedef(DIType *Ty, StringRef Name,
282 DIFile *File, unsigned LineNo,
284 return DIDerivedType::get(VMContext, dwarf::DW_TAG_typedef, Name, File,
285 LineNo, getNonCompileUnitScope(Context), Ty, 0, 0,
286 0, None, DINode::FlagZero);
289 DIDerivedType *DIBuilder::createFriend(DIType *Ty, DIType *FriendTy) {
290 assert(Ty && "Invalid type!");
291 assert(FriendTy && "Invalid friend type!");
292 return DIDerivedType::get(VMContext, dwarf::DW_TAG_friend, "", nullptr, 0, Ty,
293 FriendTy, 0, 0, 0, None, DINode::FlagZero);
296 DIDerivedType *DIBuilder::createInheritance(DIType *Ty, DIType *BaseTy,
298 DINode::DIFlags Flags) {
299 assert(Ty && "Unable to create inheritance");
300 return DIDerivedType::get(VMContext, dwarf::DW_TAG_inheritance, "", nullptr,
301 0, Ty, BaseTy, 0, 0, BaseOffset, None, Flags);
304 DIDerivedType *DIBuilder::createMemberType(DIScope *Scope, StringRef Name,
305 DIFile *File, unsigned LineNumber,
307 uint32_t AlignInBits,
308 uint64_t OffsetInBits,
309 DINode::DIFlags Flags, DIType *Ty) {
310 return DIDerivedType::get(VMContext, dwarf::DW_TAG_member, Name, File,
311 LineNumber, getNonCompileUnitScope(Scope), Ty,
312 SizeInBits, AlignInBits, OffsetInBits, None, Flags);
315 static ConstantAsMetadata *getConstantOrNull(Constant *C) {
317 return ConstantAsMetadata::get(C);
321 DIDerivedType *DIBuilder::createBitFieldMemberType(
322 DIScope *Scope, StringRef Name, DIFile *File, unsigned LineNumber,
323 uint64_t SizeInBits, uint64_t OffsetInBits, uint64_t StorageOffsetInBits,
324 DINode::DIFlags Flags, DIType *Ty) {
325 Flags |= DINode::FlagBitField;
326 return DIDerivedType::get(
327 VMContext, dwarf::DW_TAG_member, Name, File, LineNumber,
328 getNonCompileUnitScope(Scope), Ty, SizeInBits, /* AlignInBits */ 0,
329 OffsetInBits, None, Flags,
330 ConstantAsMetadata::get(ConstantInt::get(IntegerType::get(VMContext, 64),
331 StorageOffsetInBits)));
335 DIBuilder::createStaticMemberType(DIScope *Scope, StringRef Name, DIFile *File,
336 unsigned LineNumber, DIType *Ty,
337 DINode::DIFlags Flags, llvm::Constant *Val,
338 uint32_t AlignInBits) {
339 Flags |= DINode::FlagStaticMember;
340 return DIDerivedType::get(VMContext, dwarf::DW_TAG_member, Name, File,
341 LineNumber, getNonCompileUnitScope(Scope), Ty, 0,
342 AlignInBits, 0, None, Flags,
343 getConstantOrNull(Val));
347 DIBuilder::createObjCIVar(StringRef Name, DIFile *File, unsigned LineNumber,
348 uint64_t SizeInBits, uint32_t AlignInBits,
349 uint64_t OffsetInBits, DINode::DIFlags Flags,
350 DIType *Ty, MDNode *PropertyNode) {
351 return DIDerivedType::get(VMContext, dwarf::DW_TAG_member, Name, File,
352 LineNumber, getNonCompileUnitScope(File), Ty,
353 SizeInBits, AlignInBits, OffsetInBits, None, Flags,
358 DIBuilder::createObjCProperty(StringRef Name, DIFile *File, unsigned LineNumber,
359 StringRef GetterName, StringRef SetterName,
360 unsigned PropertyAttributes, DIType *Ty) {
361 return DIObjCProperty::get(VMContext, Name, File, LineNumber, GetterName,
362 SetterName, PropertyAttributes, Ty);
365 DITemplateTypeParameter *
366 DIBuilder::createTemplateTypeParameter(DIScope *Context, StringRef Name,
368 assert((!Context || isa<DICompileUnit>(Context)) && "Expected compile unit");
369 return DITemplateTypeParameter::get(VMContext, Name, Ty);
372 static DITemplateValueParameter *
373 createTemplateValueParameterHelper(LLVMContext &VMContext, unsigned Tag,
374 DIScope *Context, StringRef Name, DIType *Ty,
376 assert((!Context || isa<DICompileUnit>(Context)) && "Expected compile unit");
377 return DITemplateValueParameter::get(VMContext, Tag, Name, Ty, MD);
380 DITemplateValueParameter *
381 DIBuilder::createTemplateValueParameter(DIScope *Context, StringRef Name,
382 DIType *Ty, Constant *Val) {
383 return createTemplateValueParameterHelper(
384 VMContext, dwarf::DW_TAG_template_value_parameter, Context, Name, Ty,
385 getConstantOrNull(Val));
388 DITemplateValueParameter *
389 DIBuilder::createTemplateTemplateParameter(DIScope *Context, StringRef Name,
390 DIType *Ty, StringRef Val) {
391 return createTemplateValueParameterHelper(
392 VMContext, dwarf::DW_TAG_GNU_template_template_param, Context, Name, Ty,
393 MDString::get(VMContext, Val));
396 DITemplateValueParameter *
397 DIBuilder::createTemplateParameterPack(DIScope *Context, StringRef Name,
398 DIType *Ty, DINodeArray Val) {
399 return createTemplateValueParameterHelper(
400 VMContext, dwarf::DW_TAG_GNU_template_parameter_pack, Context, Name, Ty,
404 DICompositeType *DIBuilder::createClassType(
405 DIScope *Context, StringRef Name, DIFile *File, unsigned LineNumber,
406 uint64_t SizeInBits, uint32_t AlignInBits, uint64_t OffsetInBits,
407 DINode::DIFlags Flags, DIType *DerivedFrom, DINodeArray Elements,
408 DIType *VTableHolder, MDNode *TemplateParams, StringRef UniqueIdentifier) {
409 assert((!Context || isa<DIScope>(Context)) &&
410 "createClassType should be called with a valid Context");
412 auto *R = DICompositeType::get(
413 VMContext, dwarf::DW_TAG_structure_type, Name, File, LineNumber,
414 getNonCompileUnitScope(Context), DerivedFrom, SizeInBits, AlignInBits,
415 OffsetInBits, Flags, Elements, 0, VTableHolder,
416 cast_or_null<MDTuple>(TemplateParams), UniqueIdentifier);
417 trackIfUnresolved(R);
421 DICompositeType *DIBuilder::createStructType(
422 DIScope *Context, StringRef Name, DIFile *File, unsigned LineNumber,
423 uint64_t SizeInBits, uint32_t AlignInBits, DINode::DIFlags Flags,
424 DIType *DerivedFrom, DINodeArray Elements, unsigned RunTimeLang,
425 DIType *VTableHolder, StringRef UniqueIdentifier) {
426 auto *R = DICompositeType::get(
427 VMContext, dwarf::DW_TAG_structure_type, Name, File, LineNumber,
428 getNonCompileUnitScope(Context), DerivedFrom, SizeInBits, AlignInBits, 0,
429 Flags, Elements, RunTimeLang, VTableHolder, nullptr, UniqueIdentifier);
430 trackIfUnresolved(R);
434 DICompositeType *DIBuilder::createUnionType(
435 DIScope *Scope, StringRef Name, DIFile *File, unsigned LineNumber,
436 uint64_t SizeInBits, uint32_t AlignInBits, DINode::DIFlags Flags,
437 DINodeArray Elements, unsigned RunTimeLang, StringRef UniqueIdentifier) {
438 auto *R = DICompositeType::get(
439 VMContext, dwarf::DW_TAG_union_type, Name, File, LineNumber,
440 getNonCompileUnitScope(Scope), nullptr, SizeInBits, AlignInBits, 0, Flags,
441 Elements, RunTimeLang, nullptr, nullptr, UniqueIdentifier);
442 trackIfUnresolved(R);
446 DISubroutineType *DIBuilder::createSubroutineType(DITypeRefArray ParameterTypes,
447 DINode::DIFlags Flags,
449 return DISubroutineType::get(VMContext, Flags, CC, ParameterTypes);
452 DICompositeType *DIBuilder::createEnumerationType(
453 DIScope *Scope, StringRef Name, DIFile *File, unsigned LineNumber,
454 uint64_t SizeInBits, uint32_t AlignInBits, DINodeArray Elements,
455 DIType *UnderlyingType, StringRef UniqueIdentifier) {
456 auto *CTy = DICompositeType::get(
457 VMContext, dwarf::DW_TAG_enumeration_type, Name, File, LineNumber,
458 getNonCompileUnitScope(Scope), UnderlyingType, SizeInBits, AlignInBits, 0,
459 DINode::FlagZero, Elements, 0, nullptr, nullptr, UniqueIdentifier);
460 AllEnumTypes.push_back(CTy);
461 trackIfUnresolved(CTy);
465 DICompositeType *DIBuilder::createArrayType(uint64_t Size,
466 uint32_t AlignInBits, DIType *Ty,
467 DINodeArray Subscripts) {
468 auto *R = DICompositeType::get(VMContext, dwarf::DW_TAG_array_type, "",
469 nullptr, 0, nullptr, Ty, Size, AlignInBits, 0,
470 DINode::FlagZero, Subscripts, 0, nullptr);
471 trackIfUnresolved(R);
475 DICompositeType *DIBuilder::createVectorType(uint64_t Size,
476 uint32_t AlignInBits, DIType *Ty,
477 DINodeArray Subscripts) {
478 auto *R = DICompositeType::get(VMContext, dwarf::DW_TAG_array_type, "",
479 nullptr, 0, nullptr, Ty, Size, AlignInBits, 0,
480 DINode::FlagVector, Subscripts, 0, nullptr);
481 trackIfUnresolved(R);
485 static DIType *createTypeWithFlags(LLVMContext &Context, DIType *Ty,
486 DINode::DIFlags FlagsToSet) {
487 auto NewTy = Ty->clone();
488 NewTy->setFlags(NewTy->getFlags() | FlagsToSet);
489 return MDNode::replaceWithUniqued(std::move(NewTy));
492 DIType *DIBuilder::createArtificialType(DIType *Ty) {
493 // FIXME: Restrict this to the nodes where it's valid.
494 if (Ty->isArtificial())
496 return createTypeWithFlags(VMContext, Ty, DINode::FlagArtificial);
499 DIType *DIBuilder::createObjectPointerType(DIType *Ty) {
500 // FIXME: Restrict this to the nodes where it's valid.
501 if (Ty->isObjectPointer())
503 DINode::DIFlags Flags = DINode::FlagObjectPointer | DINode::FlagArtificial;
504 return createTypeWithFlags(VMContext, Ty, Flags);
507 void DIBuilder::retainType(DIScope *T) {
508 assert(T && "Expected non-null type");
509 assert((isa<DIType>(T) || (isa<DISubprogram>(T) &&
510 cast<DISubprogram>(T)->isDefinition() == false)) &&
511 "Expected type or subprogram declaration");
512 AllRetainTypes.emplace_back(T);
515 DIBasicType *DIBuilder::createUnspecifiedParameter() { return nullptr; }
518 DIBuilder::createForwardDecl(unsigned Tag, StringRef Name, DIScope *Scope,
519 DIFile *F, unsigned Line, unsigned RuntimeLang,
520 uint64_t SizeInBits, uint32_t AlignInBits,
521 StringRef UniqueIdentifier) {
522 // FIXME: Define in terms of createReplaceableForwardDecl() by calling
523 // replaceWithUniqued().
524 auto *RetTy = DICompositeType::get(
525 VMContext, Tag, Name, F, Line, getNonCompileUnitScope(Scope), nullptr,
526 SizeInBits, AlignInBits, 0, DINode::FlagFwdDecl, nullptr, RuntimeLang,
527 nullptr, nullptr, UniqueIdentifier);
528 trackIfUnresolved(RetTy);
532 DICompositeType *DIBuilder::createReplaceableCompositeType(
533 unsigned Tag, StringRef Name, DIScope *Scope, DIFile *F, unsigned Line,
534 unsigned RuntimeLang, uint64_t SizeInBits, uint32_t AlignInBits,
535 DINode::DIFlags Flags, StringRef UniqueIdentifier) {
537 DICompositeType::getTemporary(
538 VMContext, Tag, Name, F, Line, getNonCompileUnitScope(Scope), nullptr,
539 SizeInBits, AlignInBits, 0, Flags, nullptr, RuntimeLang, nullptr,
540 nullptr, UniqueIdentifier)
542 trackIfUnresolved(RetTy);
546 DINodeArray DIBuilder::getOrCreateArray(ArrayRef<Metadata *> Elements) {
547 return MDTuple::get(VMContext, Elements);
551 DIBuilder::getOrCreateMacroArray(ArrayRef<Metadata *> Elements) {
552 return MDTuple::get(VMContext, Elements);
555 DITypeRefArray DIBuilder::getOrCreateTypeArray(ArrayRef<Metadata *> Elements) {
556 SmallVector<llvm::Metadata *, 16> Elts;
557 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
558 if (Elements[i] && isa<MDNode>(Elements[i]))
559 Elts.push_back(cast<DIType>(Elements[i]));
561 Elts.push_back(Elements[i]);
563 return DITypeRefArray(MDNode::get(VMContext, Elts));
566 DISubrange *DIBuilder::getOrCreateSubrange(int64_t Lo, int64_t Count) {
567 return DISubrange::get(VMContext, Count, Lo);
570 static void checkGlobalVariableScope(DIScope *Context) {
573 dyn_cast_or_null<DICompositeType>(getNonCompileUnitScope(Context)))
574 assert(CT->getIdentifier().empty() &&
575 "Context of a global variable should not be a type with identifier");
579 DIGlobalVariableExpression *DIBuilder::createGlobalVariableExpression(
580 DIScope *Context, StringRef Name, StringRef LinkageName, DIFile *F,
581 unsigned LineNumber, DIType *Ty, bool isLocalToUnit, DIExpression *Expr,
582 MDNode *Decl, uint32_t AlignInBits) {
583 checkGlobalVariableScope(Context);
585 auto *GV = DIGlobalVariable::getDistinct(
586 VMContext, cast_or_null<DIScope>(Context), Name, LinkageName, F,
587 LineNumber, Ty, isLocalToUnit, true, cast_or_null<DIDerivedType>(Decl),
589 auto *N = DIGlobalVariableExpression::get(VMContext, GV, Expr);
594 DIGlobalVariable *DIBuilder::createTempGlobalVariableFwdDecl(
595 DIScope *Context, StringRef Name, StringRef LinkageName, DIFile *F,
596 unsigned LineNumber, DIType *Ty, bool isLocalToUnit, MDNode *Decl,
597 uint32_t AlignInBits) {
598 checkGlobalVariableScope(Context);
600 return DIGlobalVariable::getTemporary(
601 VMContext, cast_or_null<DIScope>(Context), Name, LinkageName, F,
602 LineNumber, Ty, isLocalToUnit, false,
603 cast_or_null<DIDerivedType>(Decl), AlignInBits)
607 static DILocalVariable *createLocalVariable(
608 LLVMContext &VMContext,
609 DenseMap<MDNode *, SmallVector<TrackingMDNodeRef, 1>> &PreservedVariables,
610 DIScope *Scope, StringRef Name, unsigned ArgNo, DIFile *File,
611 unsigned LineNo, DIType *Ty, bool AlwaysPreserve, DINode::DIFlags Flags,
612 uint32_t AlignInBits) {
613 // FIXME: Why getNonCompileUnitScope()?
614 // FIXME: Why is "!Context" okay here?
615 // FIXME: Why doesn't this check for a subprogram or lexical block (AFAICT
616 // the only valid scopes)?
617 DIScope *Context = getNonCompileUnitScope(Scope);
620 DILocalVariable::get(VMContext, cast_or_null<DILocalScope>(Context), Name,
621 File, LineNo, Ty, ArgNo, Flags, AlignInBits);
622 if (AlwaysPreserve) {
623 // The optimizer may remove local variables. If there is an interest
624 // to preserve variable info in such situation then stash it in a
626 DISubprogram *Fn = getDISubprogram(Scope);
627 assert(Fn && "Missing subprogram for local variable");
628 PreservedVariables[Fn].emplace_back(Node);
633 DILocalVariable *DIBuilder::createAutoVariable(DIScope *Scope, StringRef Name,
634 DIFile *File, unsigned LineNo,
635 DIType *Ty, bool AlwaysPreserve,
636 DINode::DIFlags Flags,
637 uint32_t AlignInBits) {
638 return createLocalVariable(VMContext, PreservedVariables, Scope, Name,
639 /* ArgNo */ 0, File, LineNo, Ty, AlwaysPreserve,
643 DILocalVariable *DIBuilder::createParameterVariable(
644 DIScope *Scope, StringRef Name, unsigned ArgNo, DIFile *File,
645 unsigned LineNo, DIType *Ty, bool AlwaysPreserve, DINode::DIFlags Flags) {
646 assert(ArgNo && "Expected non-zero argument number for parameter");
647 return createLocalVariable(VMContext, PreservedVariables, Scope, Name, ArgNo,
648 File, LineNo, Ty, AlwaysPreserve, Flags,
652 DIExpression *DIBuilder::createExpression(ArrayRef<uint64_t> Addr) {
653 return DIExpression::get(VMContext, Addr);
656 DIExpression *DIBuilder::createExpression(ArrayRef<int64_t> Signed) {
657 // TODO: Remove the callers of this signed version and delete.
658 SmallVector<uint64_t, 8> Addr(Signed.begin(), Signed.end());
659 return createExpression(Addr);
662 DIExpression *DIBuilder::createFragmentExpression(unsigned OffsetInBytes,
663 unsigned SizeInBytes) {
664 uint64_t Addr[] = {dwarf::DW_OP_LLVM_fragment, OffsetInBytes, SizeInBytes};
665 return DIExpression::get(VMContext, Addr);
668 template <class... Ts>
669 static DISubprogram *getSubprogram(bool IsDistinct, Ts &&... Args) {
671 return DISubprogram::getDistinct(std::forward<Ts>(Args)...);
672 return DISubprogram::get(std::forward<Ts>(Args)...);
675 DISubprogram *DIBuilder::createFunction(
676 DIScope *Context, StringRef Name, StringRef LinkageName, DIFile *File,
677 unsigned LineNo, DISubroutineType *Ty, bool isLocalToUnit,
678 bool isDefinition, unsigned ScopeLine, DINode::DIFlags Flags,
679 bool isOptimized, DITemplateParameterArray TParams, DISubprogram *Decl) {
680 auto *Node = getSubprogram(
681 /* IsDistinct = */ isDefinition, VMContext,
682 getNonCompileUnitScope(Context), Name, LinkageName, File, LineNo, Ty,
683 isLocalToUnit, isDefinition, ScopeLine, nullptr, 0, 0, 0, Flags,
684 isOptimized, isDefinition ? CUNode : nullptr, TParams, Decl,
685 MDTuple::getTemporary(VMContext, None).release());
688 AllSubprograms.push_back(Node);
689 trackIfUnresolved(Node);
693 DISubprogram *DIBuilder::createTempFunctionFwdDecl(
694 DIScope *Context, StringRef Name, StringRef LinkageName, DIFile *File,
695 unsigned LineNo, DISubroutineType *Ty, bool isLocalToUnit,
696 bool isDefinition, unsigned ScopeLine, DINode::DIFlags Flags,
697 bool isOptimized, DITemplateParameterArray TParams, DISubprogram *Decl) {
698 return DISubprogram::getTemporary(
699 VMContext, getNonCompileUnitScope(Context), Name, LinkageName,
700 File, LineNo, Ty, isLocalToUnit, isDefinition, ScopeLine, nullptr,
701 0, 0, 0, Flags, isOptimized, isDefinition ? CUNode : nullptr,
702 TParams, Decl, nullptr)
706 DISubprogram *DIBuilder::createMethod(DIScope *Context, StringRef Name,
707 StringRef LinkageName, DIFile *F,
708 unsigned LineNo, DISubroutineType *Ty,
709 bool isLocalToUnit, bool isDefinition,
710 unsigned VK, unsigned VIndex,
711 int ThisAdjustment, DIType *VTableHolder,
712 DINode::DIFlags Flags, bool isOptimized,
713 DITemplateParameterArray TParams) {
714 assert(getNonCompileUnitScope(Context) &&
715 "Methods should have both a Context and a context that isn't "
716 "the compile unit.");
717 // FIXME: Do we want to use different scope/lines?
718 auto *SP = getSubprogram(
719 /* IsDistinct = */ isDefinition, VMContext, cast<DIScope>(Context), Name,
720 LinkageName, F, LineNo, Ty, isLocalToUnit, isDefinition, LineNo,
721 VTableHolder, VK, VIndex, ThisAdjustment, Flags, isOptimized,
722 isDefinition ? CUNode : nullptr, TParams, nullptr, nullptr);
725 AllSubprograms.push_back(SP);
726 trackIfUnresolved(SP);
730 DINamespace *DIBuilder::createNameSpace(DIScope *Scope, StringRef Name,
731 DIFile *File, unsigned LineNo,
732 bool ExportSymbols) {
733 return DINamespace::get(VMContext, getNonCompileUnitScope(Scope), File, Name,
734 LineNo, ExportSymbols);
737 DIModule *DIBuilder::createModule(DIScope *Scope, StringRef Name,
738 StringRef ConfigurationMacros,
739 StringRef IncludePath,
740 StringRef ISysRoot) {
741 return DIModule::get(VMContext, getNonCompileUnitScope(Scope), Name,
742 ConfigurationMacros, IncludePath, ISysRoot);
745 DILexicalBlockFile *DIBuilder::createLexicalBlockFile(DIScope *Scope,
747 unsigned Discriminator) {
748 return DILexicalBlockFile::get(VMContext, Scope, File, Discriminator);
751 DILexicalBlock *DIBuilder::createLexicalBlock(DIScope *Scope, DIFile *File,
752 unsigned Line, unsigned Col) {
753 // Make these distinct, to avoid merging two lexical blocks on the same
755 return DILexicalBlock::getDistinct(VMContext, getNonCompileUnitScope(Scope),
759 static Value *getDbgIntrinsicValueImpl(LLVMContext &VMContext, Value *V) {
760 assert(V && "no value passed to dbg intrinsic");
761 return MetadataAsValue::get(VMContext, ValueAsMetadata::get(V));
764 static Instruction *withDebugLoc(Instruction *I, const DILocation *DL) {
765 I->setDebugLoc(const_cast<DILocation *>(DL));
769 Instruction *DIBuilder::insertDeclare(Value *Storage, DILocalVariable *VarInfo,
770 DIExpression *Expr, const DILocation *DL,
771 Instruction *InsertBefore) {
772 assert(VarInfo && "empty or invalid DILocalVariable* passed to dbg.declare");
773 assert(DL && "Expected debug loc");
774 assert(DL->getScope()->getSubprogram() ==
775 VarInfo->getScope()->getSubprogram() &&
776 "Expected matching subprograms");
778 DeclareFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_declare);
780 trackIfUnresolved(VarInfo);
781 trackIfUnresolved(Expr);
782 Value *Args[] = {getDbgIntrinsicValueImpl(VMContext, Storage),
783 MetadataAsValue::get(VMContext, VarInfo),
784 MetadataAsValue::get(VMContext, Expr)};
785 return withDebugLoc(CallInst::Create(DeclareFn, Args, "", InsertBefore), DL);
788 Instruction *DIBuilder::insertDeclare(Value *Storage, DILocalVariable *VarInfo,
789 DIExpression *Expr, const DILocation *DL,
790 BasicBlock *InsertAtEnd) {
791 assert(VarInfo && "empty or invalid DILocalVariable* passed to dbg.declare");
792 assert(DL && "Expected debug loc");
793 assert(DL->getScope()->getSubprogram() ==
794 VarInfo->getScope()->getSubprogram() &&
795 "Expected matching subprograms");
797 DeclareFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_declare);
799 trackIfUnresolved(VarInfo);
800 trackIfUnresolved(Expr);
801 Value *Args[] = {getDbgIntrinsicValueImpl(VMContext, Storage),
802 MetadataAsValue::get(VMContext, VarInfo),
803 MetadataAsValue::get(VMContext, Expr)};
805 // If this block already has a terminator then insert this intrinsic
806 // before the terminator.
807 if (TerminatorInst *T = InsertAtEnd->getTerminator())
808 return withDebugLoc(CallInst::Create(DeclareFn, Args, "", T), DL);
809 return withDebugLoc(CallInst::Create(DeclareFn, Args, "", InsertAtEnd), DL);
812 Instruction *DIBuilder::insertDbgValueIntrinsic(Value *V, uint64_t Offset,
813 DILocalVariable *VarInfo,
815 const DILocation *DL,
816 Instruction *InsertBefore) {
817 assert(V && "no value passed to dbg.value");
818 assert(VarInfo && "empty or invalid DILocalVariable* passed to dbg.value");
819 assert(DL && "Expected debug loc");
820 assert(DL->getScope()->getSubprogram() ==
821 VarInfo->getScope()->getSubprogram() &&
822 "Expected matching subprograms");
824 ValueFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_value);
826 trackIfUnresolved(VarInfo);
827 trackIfUnresolved(Expr);
828 Value *Args[] = {getDbgIntrinsicValueImpl(VMContext, V),
829 ConstantInt::get(Type::getInt64Ty(VMContext), Offset),
830 MetadataAsValue::get(VMContext, VarInfo),
831 MetadataAsValue::get(VMContext, Expr)};
832 return withDebugLoc(CallInst::Create(ValueFn, Args, "", InsertBefore), DL);
835 Instruction *DIBuilder::insertDbgValueIntrinsic(Value *V, uint64_t Offset,
836 DILocalVariable *VarInfo,
838 const DILocation *DL,
839 BasicBlock *InsertAtEnd) {
840 assert(V && "no value passed to dbg.value");
841 assert(VarInfo && "empty or invalid DILocalVariable* passed to dbg.value");
842 assert(DL && "Expected debug loc");
843 assert(DL->getScope()->getSubprogram() ==
844 VarInfo->getScope()->getSubprogram() &&
845 "Expected matching subprograms");
847 ValueFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_value);
849 trackIfUnresolved(VarInfo);
850 trackIfUnresolved(Expr);
851 Value *Args[] = {getDbgIntrinsicValueImpl(VMContext, V),
852 ConstantInt::get(Type::getInt64Ty(VMContext), Offset),
853 MetadataAsValue::get(VMContext, VarInfo),
854 MetadataAsValue::get(VMContext, Expr)};
856 return withDebugLoc(CallInst::Create(ValueFn, Args, "", InsertAtEnd), DL);
859 void DIBuilder::replaceVTableHolder(DICompositeType *&T,
860 DICompositeType *VTableHolder) {
862 TypedTrackingMDRef<DICompositeType> N(T);
863 N->replaceVTableHolder(VTableHolder);
867 // If this didn't create a self-reference, just return.
868 if (T != VTableHolder)
871 // Look for unresolved operands. T will drop RAUW support, orphaning any
872 // cycles underneath it.
874 for (const MDOperand &O : T->operands())
875 if (auto *N = dyn_cast_or_null<MDNode>(O))
876 trackIfUnresolved(N);
879 void DIBuilder::replaceArrays(DICompositeType *&T, DINodeArray Elements,
880 DINodeArray TParams) {
882 TypedTrackingMDRef<DICompositeType> N(T);
884 N->replaceElements(Elements);
886 N->replaceTemplateParams(DITemplateParameterArray(TParams));
890 // If T isn't resolved, there's no problem.
891 if (!T->isResolved())
894 // If T is resolved, it may be due to a self-reference cycle. Track the
895 // arrays explicitly if they're unresolved, or else the cycles will be
898 trackIfUnresolved(Elements.get());
900 trackIfUnresolved(TParams.get());