1 //===--- DIBuilder.cpp - Debug Information Builder ------------------------===//
2 //
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
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the DIBuilder.
10 //
11 //===----------------------------------------------------------------------===//
12
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"
25
26 using namespace llvm;
27 using namespace llvm::dwarf;
28
29 static cl::opt<bool>
30 UseDbgAddr("use-dbg-addr",
31 llvm::cl::desc("Use llvm.dbg.addr for all local variables"),
32 cl::init(false), cl::Hidden);
33
DIBuilder(Module & m,bool AllowUnresolvedNodes,DICompileUnit * CU)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) {}
38
trackIfUnresolved(MDNode * N)39 void DIBuilder::trackIfUnresolved(MDNode *N) {
40 if (!N)
41 return;
42 if (N->isResolved())
43 return;
44
45 assert(AllowUnresolvedNodes && "Cannot handle unresolved nodes");
46 UnresolvedNodes.emplace_back(N);
47 }
48
finalizeSubprogram(DISubprogram * SP)49 void DIBuilder::finalizeSubprogram(DISubprogram *SP) {
50 MDTuple *Temp = SP->getRetainedNodes().get();
51 if (!Temp || !Temp->isTemporary())
52 return;
53
54 SmallVector<Metadata *, 16> RetainedNodes;
55
56 auto PV = PreservedVariables.find(SP);
57 if (PV != PreservedVariables.end())
58 RetainedNodes.append(PV->second.begin(), PV->second.end());
59
60 auto PL = PreservedLabels.find(SP);
61 if (PL != PreservedLabels.end())
62 RetainedNodes.append(PL->second.begin(), PL->second.end());
63
64 DINodeArray Node = getOrCreateArray(RetainedNodes);
65
66 TempMDTuple(Temp)->replaceAllUsesWith(Node.get());
67 }
68
finalize()69 void DIBuilder::finalize() {
70 if (!CUNode) {
71 assert(!AllowUnresolvedNodes &&
72 "creating type nodes without a CU is not supported");
73 return;
74 }
75
76 CUNode->replaceEnumTypes(MDTuple::get(VMContext, AllEnumTypes));
77
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]);
87
88 if (!RetainValues.empty())
89 CUNode->replaceRetainedTypes(MDTuple::get(VMContext, RetainValues));
90
91 DISubprogramArray SPs = MDTuple::get(VMContext, AllSubprograms);
92 for (auto *SP : SPs)
93 finalizeSubprogram(SP);
94 for (auto *N : RetainValues)
95 if (auto *SP = dyn_cast<DISubprogram>(N))
96 finalizeSubprogram(SP);
97
98 if (!AllGVs.empty())
99 CUNode->replaceGlobalVariables(MDTuple::get(VMContext, AllGVs));
100
101 if (!AllImportedModules.empty())
102 CUNode->replaceImportedEntities(MDTuple::get(
103 VMContext, SmallVector<Metadata *, 16>(AllImportedModules.begin(),
104 AllImportedModules.end())));
105
106 for (const auto &I : AllMacrosPerParent) {
107 // DIMacroNode's with nullptr parent are DICompileUnit direct children.
108 if (!I.first) {
109 CUNode->replaceMacros(MDTuple::get(VMContext, I.second.getArrayRef()));
110 continue;
111 }
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);
118 }
119
120 // Now that all temp nodes have been replaced or deleted, resolve remaining
121 // cycles.
122 for (const auto &N : UnresolvedNodes)
123 if (N && !N->isResolved())
124 N->resolveCycles();
125 UnresolvedNodes.clear();
126
127 // Can't handle unresolved nodes anymore.
128 AllowUnresolvedNodes = false;
129 }
130
131 /// If N is compile unit return NULL otherwise return N.
getNonCompileUnitScope(DIScope * N)132 static DIScope *getNonCompileUnitScope(DIScope *N) {
133 if (!N || isa<DICompileUnit>(N))
134 return nullptr;
135 return cast<DIScope>(N);
136 }
137
createCompileUnit(unsigned Lang,DIFile * File,StringRef Producer,bool isOptimized,StringRef Flags,unsigned RunTimeVer,StringRef SplitName,DICompileUnit::DebugEmissionKind Kind,uint64_t DWOId,bool SplitDebugInlining,bool DebugInfoForProfiling,DICompileUnit::DebugNameTableKind NameTableKind,bool RangesBaseAddress)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) {
144
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");
148
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,
154 RangesBaseAddress);
155
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);
160 return CUNode;
161 }
162
163 static DIImportedEntity *
createImportedModule(LLVMContext & C,dwarf::Tag Tag,DIScope * Context,Metadata * NS,DIFile * File,unsigned Line,StringRef Name,SmallVectorImpl<TrackingMDNodeRef> & AllImportedModules)164 createImportedModule(LLVMContext &C, dwarf::Tag Tag, DIScope *Context,
165 Metadata *NS, DIFile *File, unsigned Line, StringRef Name,
166 SmallVectorImpl<TrackingMDNodeRef> &AllImportedModules) {
167 if (Line)
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),
171 File, Line, Name);
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);
176 return M;
177 }
178
createImportedModule(DIScope * Context,DINamespace * NS,DIFile * File,unsigned Line)179 DIImportedEntity *DIBuilder::createImportedModule(DIScope *Context,
180 DINamespace *NS, DIFile *File,
181 unsigned Line) {
182 return ::createImportedModule(VMContext, dwarf::DW_TAG_imported_module,
183 Context, NS, File, Line, StringRef(),
184 AllImportedModules);
185 }
186
createImportedModule(DIScope * Context,DIImportedEntity * NS,DIFile * File,unsigned Line)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(),
192 AllImportedModules);
193 }
194
createImportedModule(DIScope * Context,DIModule * M,DIFile * File,unsigned Line)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(),
199 AllImportedModules);
200 }
201
createImportedDeclaration(DIScope * Context,DINode * Decl,DIFile * File,unsigned Line,StringRef Name)202 DIImportedEntity *DIBuilder::createImportedDeclaration(DIScope *Context,
203 DINode *Decl,
204 DIFile *File,
205 unsigned Line,
206 StringRef Name) {
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,
211 AllImportedModules);
212 }
213
createFile(StringRef Filename,StringRef Directory,Optional<DIFile::ChecksumInfo<StringRef>> CS,Optional<StringRef> Source)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);
218 }
219
createMacro(DIMacroFile * Parent,unsigned LineNumber,unsigned MacroType,StringRef Name,StringRef Value)220 DIMacro *DIBuilder::createMacro(DIMacroFile *Parent, unsigned LineNumber,
221 unsigned MacroType, StringRef Name,
222 StringRef Value) {
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);
229 return M;
230 }
231
createTempMacroFile(DIMacroFile * Parent,unsigned LineNumber,DIFile * File)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())
236 .release();
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, {}});
242 return MF;
243 }
244
createEnumerator(StringRef Name,int64_t Val,bool IsUnsigned)245 DIEnumerator *DIBuilder::createEnumerator(StringRef Name, int64_t Val,
246 bool IsUnsigned) {
247 assert(!Name.empty() && "Unable to create enumerator without name");
248 return DIEnumerator::get(VMContext, Val, IsUnsigned, Name);
249 }
250
createUnspecifiedType(StringRef 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);
254 }
255
createNullPtrType()256 DIBasicType *DIBuilder::createNullPtrType() {
257 return createUnspecifiedType("decltype(nullptr)");
258 }
259
createBasicType(StringRef Name,uint64_t SizeInBits,unsigned Encoding,DINode::DIFlags Flags)260 DIBasicType *DIBuilder::createBasicType(StringRef Name, uint64_t SizeInBits,
261 unsigned Encoding,
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,
265 0, Encoding, Flags);
266 }
267
createQualifiedType(unsigned Tag,DIType * FromTy)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);
271 }
272
createPointerType(DIType * PointeeTy,uint64_t SizeInBits,uint32_t AlignInBits,Optional<unsigned> DWARFAddressSpace,StringRef Name)273 DIDerivedType *DIBuilder::createPointerType(
274 DIType *PointeeTy,
275 uint64_t SizeInBits,
276 uint32_t AlignInBits,
277 Optional<unsigned> DWARFAddressSpace,
278 StringRef Name) {
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,
283 DINode::FlagZero);
284 }
285
createMemberPointerType(DIType * PointeeTy,DIType * Base,uint64_t SizeInBits,uint32_t AlignInBits,DINode::DIFlags Flags)286 DIDerivedType *DIBuilder::createMemberPointerType(DIType *PointeeTy,
287 DIType *Base,
288 uint64_t SizeInBits,
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);
294 }
295
createReferenceType(unsigned Tag,DIType * RTy,uint64_t SizeInBits,uint32_t AlignInBits,Optional<unsigned> DWARFAddressSpace)296 DIDerivedType *DIBuilder::createReferenceType(
297 unsigned Tag, DIType *RTy,
298 uint64_t SizeInBits,
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,
304 DINode::FlagZero);
305 }
306
createTypedef(DIType * Ty,StringRef Name,DIFile * File,unsigned LineNo,DIScope * Context,uint32_t AlignInBits)307 DIDerivedType *DIBuilder::createTypedef(DIType *Ty, StringRef Name,
308 DIFile *File, unsigned LineNo,
309 DIScope *Context,
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);
314 }
315
createFriend(DIType * Ty,DIType * FriendTy)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);
321 }
322
createInheritance(DIType * Ty,DIType * BaseTy,uint64_t BaseOffset,uint32_t VBPtrOffset,DINode::DIFlags Flags)323 DIDerivedType *DIBuilder::createInheritance(DIType *Ty, DIType *BaseTy,
324 uint64_t BaseOffset,
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,
332 Flags, ExtraData);
333 }
334
createMemberType(DIScope * Scope,StringRef Name,DIFile * File,unsigned LineNumber,uint64_t SizeInBits,uint32_t AlignInBits,uint64_t OffsetInBits,DINode::DIFlags Flags,DIType * Ty)335 DIDerivedType *DIBuilder::createMemberType(DIScope *Scope, StringRef Name,
336 DIFile *File, unsigned LineNumber,
337 uint64_t SizeInBits,
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);
344 }
345
getConstantOrNull(Constant * C)346 static ConstantAsMetadata *getConstantOrNull(Constant *C) {
347 if (C)
348 return ConstantAsMetadata::get(C);
349 return nullptr;
350 }
351
createVariantMemberType(DIScope * Scope,StringRef Name,DIFile * File,unsigned LineNumber,uint64_t SizeInBits,uint32_t AlignInBits,uint64_t OffsetInBits,Constant * Discriminant,DINode::DIFlags Flags,DIType * Ty)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));
360 }
361
createBitFieldMemberType(DIScope * Scope,StringRef Name,DIFile * File,unsigned LineNumber,uint64_t SizeInBits,uint64_t OffsetInBits,uint64_t StorageOffsetInBits,DINode::DIFlags Flags,DIType * Ty)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)));
373 }
374
375 DIDerivedType *
createStaticMemberType(DIScope * Scope,StringRef Name,DIFile * File,unsigned LineNumber,DIType * Ty,DINode::DIFlags Flags,llvm::Constant * Val,uint32_t AlignInBits)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));
385 }
386
387 DIDerivedType *
createObjCIVar(StringRef Name,DIFile * File,unsigned LineNumber,uint64_t SizeInBits,uint32_t AlignInBits,uint64_t OffsetInBits,DINode::DIFlags Flags,DIType * Ty,MDNode * PropertyNode)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,
395 PropertyNode);
396 }
397
398 DIObjCProperty *
createObjCProperty(StringRef Name,DIFile * File,unsigned LineNumber,StringRef GetterName,StringRef SetterName,unsigned PropertyAttributes,DIType * Ty)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);
404 }
405
406 DITemplateTypeParameter *
createTemplateTypeParameter(DIScope * Context,StringRef Name,DIType * Ty)407 DIBuilder::createTemplateTypeParameter(DIScope *Context, StringRef Name,
408 DIType *Ty) {
409 assert((!Context || isa<DICompileUnit>(Context)) && "Expected compile unit");
410 return DITemplateTypeParameter::get(VMContext, Name, Ty);
411 }
412
413 static DITemplateValueParameter *
createTemplateValueParameterHelper(LLVMContext & VMContext,unsigned Tag,DIScope * Context,StringRef Name,DIType * Ty,Metadata * MD)414 createTemplateValueParameterHelper(LLVMContext &VMContext, unsigned Tag,
415 DIScope *Context, StringRef Name, DIType *Ty,
416 Metadata *MD) {
417 assert((!Context || isa<DICompileUnit>(Context)) && "Expected compile unit");
418 return DITemplateValueParameter::get(VMContext, Tag, Name, Ty, MD);
419 }
420
421 DITemplateValueParameter *
createTemplateValueParameter(DIScope * Context,StringRef Name,DIType * Ty,Constant * Val)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));
427 }
428
429 DITemplateValueParameter *
createTemplateTemplateParameter(DIScope * Context,StringRef Name,DIType * Ty,StringRef Val)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));
435 }
436
437 DITemplateValueParameter *
createTemplateParameterPack(DIScope * Context,StringRef Name,DIType * Ty,DINodeArray Val)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,
442 Val.get());
443 }
444
createClassType(DIScope * Context,StringRef Name,DIFile * File,unsigned LineNumber,uint64_t SizeInBits,uint32_t AlignInBits,uint64_t OffsetInBits,DINode::DIFlags Flags,DIType * DerivedFrom,DINodeArray Elements,DIType * VTableHolder,MDNode * TemplateParams,StringRef UniqueIdentifier)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");
452
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);
459 return R;
460 }
461
createStructType(DIScope * Context,StringRef Name,DIFile * File,unsigned LineNumber,uint64_t SizeInBits,uint32_t AlignInBits,DINode::DIFlags Flags,DIType * DerivedFrom,DINodeArray Elements,unsigned RunTimeLang,DIType * VTableHolder,StringRef UniqueIdentifier)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);
472 return R;
473 }
474
createUnionType(DIScope * Scope,StringRef Name,DIFile * File,unsigned LineNumber,uint64_t SizeInBits,uint32_t AlignInBits,DINode::DIFlags Flags,DINodeArray Elements,unsigned RunTimeLang,StringRef UniqueIdentifier)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);
484 return R;
485 }
486
createVariantPart(DIScope * Scope,StringRef Name,DIFile * File,unsigned LineNumber,uint64_t SizeInBits,uint32_t AlignInBits,DINode::DIFlags Flags,DIDerivedType * Discriminator,DINodeArray Elements,StringRef UniqueIdentifier)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);
496 return R;
497 }
498
createSubroutineType(DITypeRefArray ParameterTypes,DINode::DIFlags Flags,unsigned CC)499 DISubroutineType *DIBuilder::createSubroutineType(DITypeRefArray ParameterTypes,
500 DINode::DIFlags Flags,
501 unsigned CC) {
502 return DISubroutineType::get(VMContext, Flags, CC, ParameterTypes);
503 }
504
createEnumerationType(DIScope * Scope,StringRef Name,DIFile * File,unsigned LineNumber,uint64_t SizeInBits,uint32_t AlignInBits,DINodeArray Elements,DIType * UnderlyingType,StringRef UniqueIdentifier,bool IsScoped)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);
516 return CTy;
517 }
518
createArrayType(uint64_t Size,uint32_t AlignInBits,DIType * Ty,DINodeArray Subscripts)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);
526 return R;
527 }
528
createVectorType(uint64_t Size,uint32_t AlignInBits,DIType * Ty,DINodeArray Subscripts)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);
536 return R;
537 }
538
createArtificialSubprogram(DISubprogram * SP)539 DISubprogram *DIBuilder::createArtificialSubprogram(DISubprogram *SP) {
540 auto NewSP = SP->cloneWithFlags(SP->getFlags() | DINode::FlagArtificial);
541 return MDNode::replaceWithDistinct(std::move(NewSP));
542 }
543
createTypeWithFlags(const DIType * Ty,DINode::DIFlags FlagsToSet)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));
548 }
549
createArtificialType(DIType * Ty)550 DIType *DIBuilder::createArtificialType(DIType *Ty) {
551 // FIXME: Restrict this to the nodes where it's valid.
552 if (Ty->isArtificial())
553 return Ty;
554 return createTypeWithFlags(Ty, DINode::FlagArtificial);
555 }
556
createObjectPointerType(DIType * Ty)557 DIType *DIBuilder::createObjectPointerType(DIType *Ty) {
558 // FIXME: Restrict this to the nodes where it's valid.
559 if (Ty->isObjectPointer())
560 return Ty;
561 DINode::DIFlags Flags = DINode::FlagObjectPointer | DINode::FlagArtificial;
562 return createTypeWithFlags(Ty, Flags);
563 }
564
retainType(DIScope * T)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);
571 }
572
createUnspecifiedParameter()573 DIBasicType *DIBuilder::createUnspecifiedParameter() { return nullptr; }
574
575 DICompositeType *
createForwardDecl(unsigned Tag,StringRef Name,DIScope * Scope,DIFile * F,unsigned Line,unsigned RuntimeLang,uint64_t SizeInBits,uint32_t AlignInBits,StringRef UniqueIdentifier)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);
587 return RetTy;
588 }
589
createReplaceableCompositeType(unsigned Tag,StringRef Name,DIScope * Scope,DIFile * F,unsigned Line,unsigned RuntimeLang,uint64_t SizeInBits,uint32_t AlignInBits,DINode::DIFlags Flags,StringRef UniqueIdentifier)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) {
594 auto *RetTy =
595 DICompositeType::getTemporary(
596 VMContext, Tag, Name, F, Line, getNonCompileUnitScope(Scope), nullptr,
597 SizeInBits, AlignInBits, 0, Flags, nullptr, RuntimeLang, nullptr,
598 nullptr, UniqueIdentifier)
599 .release();
600 trackIfUnresolved(RetTy);
601 return RetTy;
602 }
603
getOrCreateArray(ArrayRef<Metadata * > Elements)604 DINodeArray DIBuilder::getOrCreateArray(ArrayRef<Metadata *> Elements) {
605 return MDTuple::get(VMContext, Elements);
606 }
607
608 DIMacroNodeArray
getOrCreateMacroArray(ArrayRef<Metadata * > Elements)609 DIBuilder::getOrCreateMacroArray(ArrayRef<Metadata *> Elements) {
610 return MDTuple::get(VMContext, Elements);
611 }
612
getOrCreateTypeArray(ArrayRef<Metadata * > 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]));
618 else
619 Elts.push_back(Elements[i]);
620 }
621 return DITypeRefArray(MDNode::get(VMContext, Elts));
622 }
623
getOrCreateSubrange(int64_t Lo,int64_t Count)624 DISubrange *DIBuilder::getOrCreateSubrange(int64_t Lo, int64_t Count) {
625 return DISubrange::get(VMContext, Count, Lo);
626 }
627
getOrCreateSubrange(int64_t Lo,Metadata * CountNode)628 DISubrange *DIBuilder::getOrCreateSubrange(int64_t Lo, Metadata *CountNode) {
629 return DISubrange::get(VMContext, CountNode, Lo);
630 }
631
checkGlobalVariableScope(DIScope * Context)632 static void checkGlobalVariableScope(DIScope *Context) {
633 #ifndef NDEBUG
634 if (auto *CT =
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");
638 #endif
639 }
640
createGlobalVariableExpression(DIScope * Context,StringRef Name,StringRef LinkageName,DIFile * F,unsigned LineNumber,DIType * Ty,bool IsLocalToUnit,bool isDefined,DIExpression * Expr,MDNode * Decl,MDTuple * TemplateParams,uint32_t AlignInBits)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);
647
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);
652 if (!Expr)
653 Expr = createExpression();
654 auto *N = DIGlobalVariableExpression::get(VMContext, GV, Expr);
655 AllGVs.push_back(N);
656 return N;
657 }
658
createTempGlobalVariableFwdDecl(DIScope * Context,StringRef Name,StringRef LinkageName,DIFile * F,unsigned LineNumber,DIType * Ty,bool IsLocalToUnit,MDNode * Decl,MDTuple * TemplateParams,uint32_t AlignInBits)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);
664
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)
669 .release();
670 }
671
createLocalVariable(LLVMContext & VMContext,DenseMap<MDNode *,SmallVector<TrackingMDNodeRef,1>> & PreservedVariables,DIScope * Scope,StringRef Name,unsigned ArgNo,DIFile * File,unsigned LineNo,DIType * Ty,bool AlwaysPreserve,DINode::DIFlags Flags,uint32_t 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);
683
684 auto *Node =
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
690 // named mdnode.
691 DISubprogram *Fn = getDISubprogram(Scope);
692 assert(Fn && "Missing subprogram for local variable");
693 PreservedVariables[Fn].emplace_back(Node);
694 }
695 return Node;
696 }
697
createAutoVariable(DIScope * Scope,StringRef Name,DIFile * File,unsigned LineNo,DIType * Ty,bool AlwaysPreserve,DINode::DIFlags Flags,uint32_t AlignInBits)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,
705 Flags, AlignInBits);
706 }
707
createParameterVariable(DIScope * Scope,StringRef Name,unsigned ArgNo,DIFile * File,unsigned LineNo,DIType * Ty,bool AlwaysPreserve,DINode::DIFlags Flags)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,
714 /* AlignInBits */0);
715 }
716
createLabel(DIScope * Scope,StringRef Name,DIFile * File,unsigned LineNo,bool AlwaysPreserve)717 DILabel *DIBuilder::createLabel(
718 DIScope *Scope, StringRef Name, DIFile *File,
719 unsigned LineNo, bool AlwaysPreserve) {
720 DIScope *Context = getNonCompileUnitScope(Scope);
721
722 auto *Node =
723 DILabel::get(VMContext, cast_or_null<DILocalScope>(Context), Name,
724 File, LineNo);
725
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);
733 }
734 return Node;
735 }
736
createExpression(ArrayRef<uint64_t> Addr)737 DIExpression *DIBuilder::createExpression(ArrayRef<uint64_t> Addr) {
738 return DIExpression::get(VMContext, Addr);
739 }
740
createExpression(ArrayRef<int64_t> Signed)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);
745 }
746
747 template <class... Ts>
getSubprogram(bool IsDistinct,Ts &&...Args)748 static DISubprogram *getSubprogram(bool IsDistinct, Ts &&... Args) {
749 if (IsDistinct)
750 return DISubprogram::getDistinct(std::forward<Ts>(Args)...);
751 return DISubprogram::get(std::forward<Ts>(Args)...);
752 }
753
createFunction(DIScope * Context,StringRef Name,StringRef LinkageName,DIFile * File,unsigned LineNo,DISubroutineType * Ty,unsigned ScopeLine,DINode::DIFlags Flags,DISubprogram::DISPFlags SPFlags,DITemplateParameterArray TParams,DISubprogram * Decl,DITypeArray ThrownTypes)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);
766
767 if (IsDefinition)
768 AllSubprograms.push_back(Node);
769 trackIfUnresolved(Node);
770 return Node;
771 }
772
createTempFunctionFwdDecl(DIScope * Context,StringRef Name,StringRef LinkageName,DIFile * File,unsigned LineNo,DISubroutineType * Ty,unsigned ScopeLine,DINode::DIFlags Flags,DISubprogram::DISPFlags SPFlags,DITemplateParameterArray TParams,DISubprogram * Decl,DITypeArray ThrownTypes)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)
785 .release();
786 }
787
createMethod(DIScope * Context,StringRef Name,StringRef LinkageName,DIFile * F,unsigned LineNo,DISubroutineType * Ty,unsigned VIndex,int ThisAdjustment,DIType * VTableHolder,DINode::DIFlags Flags,DISubprogram::DISPFlags SPFlags,DITemplateParameterArray TParams,DITypeArray 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);
804
805 if (IsDefinition)
806 AllSubprograms.push_back(SP);
807 trackIfUnresolved(SP);
808 return SP;
809 }
810
createCommonBlock(DIScope * Scope,DIGlobalVariable * Decl,StringRef Name,DIFile * File,unsigned LineNo)811 DICommonBlock *DIBuilder::createCommonBlock(
812 DIScope *Scope, DIGlobalVariable *Decl, StringRef Name, DIFile *File,
813 unsigned LineNo) {
814 return DICommonBlock::get(
815 VMContext, Scope, Decl, Name, File, LineNo);
816 }
817
createNameSpace(DIScope * Scope,StringRef Name,bool ExportSymbols)818 DINamespace *DIBuilder::createNameSpace(DIScope *Scope, StringRef Name,
819 bool ExportSymbols) {
820
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,
827 ExportSymbols);
828 }
829
createModule(DIScope * Scope,StringRef Name,StringRef ConfigurationMacros,StringRef IncludePath,StringRef SysRoot)830 DIModule *DIBuilder::createModule(DIScope *Scope, StringRef Name,
831 StringRef ConfigurationMacros,
832 StringRef IncludePath,
833 StringRef SysRoot) {
834 return DIModule::get(VMContext, getNonCompileUnitScope(Scope), Name,
835 ConfigurationMacros, IncludePath, SysRoot);
836 }
837
createLexicalBlockFile(DIScope * Scope,DIFile * File,unsigned Discriminator)838 DILexicalBlockFile *DIBuilder::createLexicalBlockFile(DIScope *Scope,
839 DIFile *File,
840 unsigned Discriminator) {
841 return DILexicalBlockFile::get(VMContext, Scope, File, Discriminator);
842 }
843
createLexicalBlock(DIScope * Scope,DIFile * File,unsigned Line,unsigned Col)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
847 // file/line/column.
848 return DILexicalBlock::getDistinct(VMContext, getNonCompileUnitScope(Scope),
849 File, Line, Col);
850 }
851
insertDeclare(Value * Storage,DILocalVariable * VarInfo,DIExpression * Expr,const DILocation * DL,Instruction * InsertBefore)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(),
856 InsertBefore);
857 }
858
insertDeclare(Value * Storage,DILocalVariable * VarInfo,DIExpression * Expr,const DILocation * DL,BasicBlock * InsertAtEnd)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);
866 }
867
insertLabel(DILabel * LabelInfo,const DILocation * DL,Instruction * InsertBefore)868 Instruction *DIBuilder::insertLabel(DILabel *LabelInfo, const DILocation *DL,
869 Instruction *InsertBefore) {
870 return insertLabel(
871 LabelInfo, DL, InsertBefore ? InsertBefore->getParent() : nullptr,
872 InsertBefore);
873 }
874
insertLabel(DILabel * LabelInfo,const DILocation * DL,BasicBlock * InsertAtEnd)875 Instruction *DIBuilder::insertLabel(DILabel *LabelInfo, const DILocation *DL,
876 BasicBlock *InsertAtEnd) {
877 return insertLabel(LabelInfo, DL, InsertAtEnd, nullptr);
878 }
879
insertDbgValueIntrinsic(Value * V,DILocalVariable * VarInfo,DIExpression * Expr,const DILocation * DL,Instruction * InsertBefore)880 Instruction *DIBuilder::insertDbgValueIntrinsic(Value *V,
881 DILocalVariable *VarInfo,
882 DIExpression *Expr,
883 const DILocation *DL,
884 Instruction *InsertBefore) {
885 return insertDbgValueIntrinsic(
886 V, VarInfo, Expr, DL, InsertBefore ? InsertBefore->getParent() : nullptr,
887 InsertBefore);
888 }
889
insertDbgValueIntrinsic(Value * V,DILocalVariable * VarInfo,DIExpression * Expr,const DILocation * DL,BasicBlock * InsertAtEnd)890 Instruction *DIBuilder::insertDbgValueIntrinsic(Value *V,
891 DILocalVariable *VarInfo,
892 DIExpression *Expr,
893 const DILocation *DL,
894 BasicBlock *InsertAtEnd) {
895 return insertDbgValueIntrinsic(V, VarInfo, Expr, DL, InsertAtEnd, nullptr);
896 }
897
898 /// Return an IRBuilder for inserting dbg.declare and dbg.value intrinsics. This
899 /// abstracts over the various ways to specify an insert position.
getIRBForDbgInsertion(const DILocation * DL,BasicBlock * InsertBB,Instruction * InsertBefore)900 static IRBuilder<> getIRBForDbgInsertion(const DILocation *DL,
901 BasicBlock *InsertBB,
902 Instruction *InsertBefore) {
903 IRBuilder<> B(DL->getContext());
904 if (InsertBefore)
905 B.SetInsertPoint(InsertBefore);
906 else if (InsertBB)
907 B.SetInsertPoint(InsertBB);
908 B.SetCurrentDebugLocation(DL);
909 return B;
910 }
911
getDbgIntrinsicValueImpl(LLVMContext & VMContext,Value * V)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));
915 }
916
getDeclareIntrin(Module & M)917 static Function *getDeclareIntrin(Module &M) {
918 return Intrinsic::getDeclaration(&M, UseDbgAddr ? Intrinsic::dbg_addr
919 : Intrinsic::dbg_declare);
920 }
921
insertDeclare(Value * Storage,DILocalVariable * VarInfo,DIExpression * Expr,const DILocation * DL,BasicBlock * InsertBB,Instruction * InsertBefore)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");
930 if (!DeclareFn)
931 DeclareFn = getDeclareIntrin(M);
932
933 trackIfUnresolved(VarInfo);
934 trackIfUnresolved(Expr);
935 Value *Args[] = {getDbgIntrinsicValueImpl(VMContext, Storage),
936 MetadataAsValue::get(VMContext, VarInfo),
937 MetadataAsValue::get(VMContext, Expr)};
938
939 IRBuilder<> B = getIRBForDbgInsertion(DL, InsertBB, InsertBefore);
940 return B.CreateCall(DeclareFn, Args);
941 }
942
insertDbgValueIntrinsic(Value * V,DILocalVariable * VarInfo,DIExpression * Expr,const DILocation * DL,BasicBlock * InsertBB,Instruction * InsertBefore)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");
952 if (!ValueFn)
953 ValueFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_value);
954
955 trackIfUnresolved(VarInfo);
956 trackIfUnresolved(Expr);
957 Value *Args[] = {getDbgIntrinsicValueImpl(VMContext, V),
958 MetadataAsValue::get(VMContext, VarInfo),
959 MetadataAsValue::get(VMContext, Expr)};
960
961 IRBuilder<> B = getIRBForDbgInsertion(DL, InsertBB, InsertBefore);
962 return B.CreateCall(ValueFn, Args);
963 }
964
insertLabel(DILabel * LabelInfo,const DILocation * DL,BasicBlock * InsertBB,Instruction * InsertBefore)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");
973 if (!LabelFn)
974 LabelFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_label);
975
976 trackIfUnresolved(LabelInfo);
977 Value *Args[] = {MetadataAsValue::get(VMContext, LabelInfo)};
978
979 IRBuilder<> B = getIRBForDbgInsertion(DL, InsertBB, InsertBefore);
980 return B.CreateCall(LabelFn, Args);
981 }
982
replaceVTableHolder(DICompositeType * & T,DIType * VTableHolder)983 void DIBuilder::replaceVTableHolder(DICompositeType *&T,
984 DIType *VTableHolder) {
985 {
986 TypedTrackingMDRef<DICompositeType> N(T);
987 N->replaceVTableHolder(VTableHolder);
988 T = N.get();
989 }
990
991 // If this didn't create a self-reference, just return.
992 if (T != VTableHolder)
993 return;
994
995 // Look for unresolved operands. T will drop RAUW support, orphaning any
996 // cycles underneath it.
997 if (T->isResolved())
998 for (const MDOperand &O : T->operands())
999 if (auto *N = dyn_cast_or_null<MDNode>(O))
1000 trackIfUnresolved(N);
1001 }
1002
replaceArrays(DICompositeType * & T,DINodeArray Elements,DINodeArray TParams)1003 void DIBuilder::replaceArrays(DICompositeType *&T, DINodeArray Elements,
1004 DINodeArray TParams) {
1005 {
1006 TypedTrackingMDRef<DICompositeType> N(T);
1007 if (Elements)
1008 N->replaceElements(Elements);
1009 if (TParams)
1010 N->replaceTemplateParams(DITemplateParameterArray(TParams));
1011 T = N.get();
1012 }
1013
1014 // If T isn't resolved, there's no problem.
1015 if (!T->isResolved())
1016 return;
1017
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
1020 // orphaned.
1021 if (Elements)
1022 trackIfUnresolved(Elements.get());
1023 if (TParams)
1024 trackIfUnresolved(TParams.get());
1025 }
1026