1 //===--- DIBuilder.cpp - Debug Information Builder ------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the DIBuilder.
11 //
12 //===----------------------------------------------------------------------===//
13 
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"
23 
24 using namespace llvm;
25 using namespace llvm::dwarf;
26 
27 namespace {
28 class HeaderBuilder {
29   /// \brief Whether there are any fields yet.
30   ///
31   /// Note that this is not equivalent to \c Chars.empty(), since \a concat()
32   /// may have been called already with an empty string.
33   bool IsEmpty;
34   SmallVector<char, 256> Chars;
35 
36 public:
37   HeaderBuilder() : IsEmpty(true) {}
38   HeaderBuilder(const HeaderBuilder &X) : IsEmpty(X.IsEmpty), Chars(X.Chars) {}
39   HeaderBuilder(HeaderBuilder &&X)
40       : IsEmpty(X.IsEmpty), Chars(std::move(X.Chars)) {}
41 
42   template <class Twineable> HeaderBuilder &concat(Twineable &&X) {
43     if (IsEmpty)
44       IsEmpty = false;
45     else
46       Chars.push_back(0);
47     Twine(X).toVector(Chars);
48     return *this;
49   }
50 
51   MDString *get(LLVMContext &Context) const {
52     return MDString::get(Context, StringRef(Chars.begin(), Chars.size()));
53   }
54 
55   static HeaderBuilder get(unsigned Tag) {
56     return HeaderBuilder().concat("0x" + Twine::utohexstr(Tag));
57   }
58 };
59 }
60 
61 DIBuilder::DIBuilder(Module &m, bool AllowUnresolvedNodes)
62   : M(m), VMContext(M.getContext()), CUNode(nullptr),
63       DeclareFn(nullptr), ValueFn(nullptr),
64       AllowUnresolvedNodes(AllowUnresolvedNodes) {}
65 
66 void DIBuilder::trackIfUnresolved(MDNode *N) {
67   if (!N)
68     return;
69   if (N->isResolved())
70     return;
71 
72   assert(AllowUnresolvedNodes && "Cannot handle unresolved nodes");
73   UnresolvedNodes.emplace_back(N);
74 }
75 
76 void DIBuilder::finalize() {
77   if (!CUNode) {
78     assert(!AllowUnresolvedNodes &&
79            "creating type nodes without a CU is not supported");
80     return;
81   }
82 
83   CUNode->replaceEnumTypes(MDTuple::get(VMContext, AllEnumTypes));
84 
85   SmallVector<Metadata *, 16> RetainValues;
86   // Declarations and definitions of the same type may be retained. Some
87   // clients RAUW these pairs, leaving duplicates in the retained types
88   // list. Use a set to remove the duplicates while we transform the
89   // TrackingVHs back into Values.
90   SmallPtrSet<Metadata *, 16> RetainSet;
91   for (unsigned I = 0, E = AllRetainTypes.size(); I < E; I++)
92     if (RetainSet.insert(AllRetainTypes[I]).second)
93       RetainValues.push_back(AllRetainTypes[I]);
94 
95   if (!RetainValues.empty())
96     CUNode->replaceRetainedTypes(MDTuple::get(VMContext, RetainValues));
97 
98   DISubprogramArray SPs = MDTuple::get(VMContext, AllSubprograms);
99   if (!AllSubprograms.empty())
100     CUNode->replaceSubprograms(SPs.get());
101 
102   for (auto *SP : SPs) {
103     if (MDTuple *Temp = SP->getVariables().get()) {
104       const auto &PV = PreservedVariables.lookup(SP);
105       SmallVector<Metadata *, 4> Variables(PV.begin(), PV.end());
106       DINodeArray AV = getOrCreateArray(Variables);
107       TempMDTuple(Temp)->replaceAllUsesWith(AV.get());
108     }
109   }
110 
111   if (!AllGVs.empty())
112     CUNode->replaceGlobalVariables(MDTuple::get(VMContext, AllGVs));
113 
114   if (!AllImportedModules.empty())
115     CUNode->replaceImportedEntities(MDTuple::get(
116         VMContext, SmallVector<Metadata *, 16>(AllImportedModules.begin(),
117                                                AllImportedModules.end())));
118 
119   // Now that all temp nodes have been replaced or deleted, resolve remaining
120   // cycles.
121   for (const auto &N : UnresolvedNodes)
122     if (N && !N->isResolved())
123       N->resolveCycles();
124   UnresolvedNodes.clear();
125 
126   // Can't handle unresolved nodes anymore.
127   AllowUnresolvedNodes = false;
128 }
129 
130 /// If N is compile unit return NULL otherwise return N.
131 static DIScope *getNonCompileUnitScope(DIScope *N) {
132   if (!N || isa<DICompileUnit>(N))
133     return nullptr;
134   return cast<DIScope>(N);
135 }
136 
137 DICompileUnit *DIBuilder::createCompileUnit(
138     unsigned Lang, StringRef Filename, StringRef Directory, StringRef Producer,
139     bool isOptimized, StringRef Flags, unsigned RunTimeVer, StringRef SplitName,
140     DebugEmissionKind Kind, uint64_t DWOId, bool EmitDebugInfo) {
141 
142   assert(((Lang <= dwarf::DW_LANG_Fortran08 && Lang >= dwarf::DW_LANG_C89) ||
143           (Lang <= dwarf::DW_LANG_hi_user && Lang >= dwarf::DW_LANG_lo_user)) &&
144          "Invalid Language tag");
145   assert(!Filename.empty() &&
146          "Unable to create compile unit without filename");
147 
148   assert(!CUNode && "Can only make one compile unit per DIBuilder instance");
149   CUNode = DICompileUnit::getDistinct(
150       VMContext, Lang, DIFile::get(VMContext, Filename, Directory), Producer,
151       isOptimized, Flags, RunTimeVer, SplitName, Kind, nullptr,
152       nullptr, nullptr, nullptr, nullptr, nullptr, DWOId);
153 
154   // Create a named metadata so that it is easier to find cu in a module.
155   // Note that we only generate this when the caller wants to actually
156   // emit debug information. When we are only interested in tracking
157   // source line locations throughout the backend, we prevent codegen from
158   // emitting debug info in the final output by not generating llvm.dbg.cu.
159   if (EmitDebugInfo) {
160     NamedMDNode *NMD = M.getOrInsertNamedMetadata("llvm.dbg.cu");
161     NMD->addOperand(CUNode);
162   }
163 
164   trackIfUnresolved(CUNode);
165   return CUNode;
166 }
167 
168 static DIImportedEntity *
169 createImportedModule(LLVMContext &C, dwarf::Tag Tag, DIScope *Context,
170                      Metadata *NS, unsigned Line, StringRef Name,
171                      SmallVectorImpl<TrackingMDNodeRef> &AllImportedModules) {
172   unsigned EntitiesCount = C.pImpl->DIImportedEntitys.size();
173   auto *M = DIImportedEntity::get(C, Tag, Context, DINodeRef(NS), Line, Name);
174   if (EntitiesCount < C.pImpl->DIImportedEntitys.size())
175     // A new Imported Entity was just added to the context.
176     // Add it to the Imported Modules list.
177     AllImportedModules.emplace_back(M);
178   return M;
179 }
180 
181 DIImportedEntity *DIBuilder::createImportedModule(DIScope *Context,
182                                                   DINamespace *NS,
183                                                   unsigned Line) {
184   return ::createImportedModule(VMContext, dwarf::DW_TAG_imported_module,
185                                 Context, NS, Line, StringRef(), AllImportedModules);
186 }
187 
188 DIImportedEntity *DIBuilder::createImportedModule(DIScope *Context,
189                                                   DIImportedEntity *NS,
190                                                   unsigned Line) {
191   return ::createImportedModule(VMContext, dwarf::DW_TAG_imported_module,
192                                 Context, NS, Line, StringRef(), AllImportedModules);
193 }
194 
195 DIImportedEntity *DIBuilder::createImportedModule(DIScope *Context, DIModule *M,
196                                                   unsigned Line) {
197   return ::createImportedModule(VMContext, dwarf::DW_TAG_imported_module,
198                                 Context, M, Line, StringRef(), AllImportedModules);
199 }
200 
201 DIImportedEntity *DIBuilder::createImportedDeclaration(DIScope *Context,
202                                                        DINode *Decl,
203                                                        unsigned Line,
204                                                        StringRef Name) {
205   // Make sure to use the unique identifier based metadata reference for
206   // types that have one.
207   return ::createImportedModule(VMContext, dwarf::DW_TAG_imported_declaration,
208                                 Context, DINodeRef::get(Decl), Line, Name,
209                                 AllImportedModules);
210 }
211 
212 DIFile *DIBuilder::createFile(StringRef Filename, StringRef Directory) {
213   return DIFile::get(VMContext, Filename, Directory);
214 }
215 
216 DIEnumerator *DIBuilder::createEnumerator(StringRef Name, int64_t Val) {
217   assert(!Name.empty() && "Unable to create enumerator without name");
218   return DIEnumerator::get(VMContext, Val, Name);
219 }
220 
221 DIBasicType *DIBuilder::createUnspecifiedType(StringRef Name) {
222   assert(!Name.empty() && "Unable to create type without name");
223   return DIBasicType::get(VMContext, dwarf::DW_TAG_unspecified_type, Name);
224 }
225 
226 DIBasicType *DIBuilder::createNullPtrType() {
227   return createUnspecifiedType("decltype(nullptr)");
228 }
229 
230 DIBasicType *DIBuilder::createBasicType(StringRef Name, uint64_t SizeInBits,
231                                         uint64_t AlignInBits,
232                                         unsigned Encoding) {
233   assert(!Name.empty() && "Unable to create type without name");
234   return DIBasicType::get(VMContext, dwarf::DW_TAG_base_type, Name, SizeInBits,
235                           AlignInBits, Encoding);
236 }
237 
238 DIDerivedType *DIBuilder::createQualifiedType(unsigned Tag, DIType *FromTy) {
239   return DIDerivedType::get(VMContext, Tag, "", nullptr, 0, nullptr,
240                             DITypeRef::get(FromTy), 0, 0, 0, 0);
241 }
242 
243 DIDerivedType *DIBuilder::createPointerType(DIType *PointeeTy,
244                                             uint64_t SizeInBits,
245                                             uint64_t AlignInBits,
246                                             StringRef Name) {
247   // FIXME: Why is there a name here?
248   return DIDerivedType::get(VMContext, dwarf::DW_TAG_pointer_type, Name,
249                             nullptr, 0, nullptr, DITypeRef::get(PointeeTy),
250                             SizeInBits, AlignInBits, 0, 0);
251 }
252 
253 DIDerivedType *DIBuilder::createMemberPointerType(DIType *PointeeTy,
254                                                   DIType *Base,
255                                                   uint64_t SizeInBits,
256                                                   uint64_t AlignInBits) {
257   return DIDerivedType::get(VMContext, dwarf::DW_TAG_ptr_to_member_type, "",
258                             nullptr, 0, nullptr, DITypeRef::get(PointeeTy),
259                             SizeInBits, AlignInBits, 0, 0,
260                             DITypeRef::get(Base));
261 }
262 
263 DIDerivedType *DIBuilder::createReferenceType(unsigned Tag, DIType *RTy,
264                                               uint64_t SizeInBits,
265                                               uint64_t AlignInBits) {
266   assert(RTy && "Unable to create reference type");
267   return DIDerivedType::get(VMContext, Tag, "", nullptr, 0, nullptr,
268                             DITypeRef::get(RTy), SizeInBits, AlignInBits, 0, 0);
269 }
270 
271 DIDerivedType *DIBuilder::createTypedef(DIType *Ty, StringRef Name,
272                                         DIFile *File, unsigned LineNo,
273                                         DIScope *Context) {
274   return DIDerivedType::get(VMContext, dwarf::DW_TAG_typedef, Name, File,
275                             LineNo,
276                             DIScopeRef::get(getNonCompileUnitScope(Context)),
277                             DITypeRef::get(Ty), 0, 0, 0, 0);
278 }
279 
280 DIDerivedType *DIBuilder::createFriend(DIType *Ty, DIType *FriendTy) {
281   assert(Ty && "Invalid type!");
282   assert(FriendTy && "Invalid friend type!");
283   return DIDerivedType::get(VMContext, dwarf::DW_TAG_friend, "", nullptr, 0,
284                             DITypeRef::get(Ty), DITypeRef::get(FriendTy), 0, 0,
285                             0, 0);
286 }
287 
288 DIDerivedType *DIBuilder::createInheritance(DIType *Ty, DIType *BaseTy,
289                                             uint64_t BaseOffset,
290                                             unsigned Flags) {
291   assert(Ty && "Unable to create inheritance");
292   return DIDerivedType::get(VMContext, dwarf::DW_TAG_inheritance, "", nullptr,
293                             0, DITypeRef::get(Ty), DITypeRef::get(BaseTy), 0, 0,
294                             BaseOffset, Flags);
295 }
296 
297 DIDerivedType *DIBuilder::createMemberType(DIScope *Scope, StringRef Name,
298                                            DIFile *File, unsigned LineNumber,
299                                            uint64_t SizeInBits,
300                                            uint64_t AlignInBits,
301                                            uint64_t OffsetInBits,
302                                            unsigned Flags, DIType *Ty) {
303   return DIDerivedType::get(
304       VMContext, dwarf::DW_TAG_member, Name, File, LineNumber,
305       DIScopeRef::get(getNonCompileUnitScope(Scope)), DITypeRef::get(Ty),
306       SizeInBits, AlignInBits, OffsetInBits, Flags);
307 }
308 
309 static ConstantAsMetadata *getConstantOrNull(Constant *C) {
310   if (C)
311     return ConstantAsMetadata::get(C);
312   return nullptr;
313 }
314 
315 DIDerivedType *DIBuilder::createStaticMemberType(DIScope *Scope, StringRef Name,
316                                                  DIFile *File,
317                                                  unsigned LineNumber,
318                                                  DIType *Ty, unsigned Flags,
319                                                  llvm::Constant *Val) {
320   Flags |= DINode::FlagStaticMember;
321   return DIDerivedType::get(
322       VMContext, dwarf::DW_TAG_member, Name, File, LineNumber,
323       DIScopeRef::get(getNonCompileUnitScope(Scope)), DITypeRef::get(Ty), 0, 0,
324       0, Flags, getConstantOrNull(Val));
325 }
326 
327 DIDerivedType *DIBuilder::createObjCIVar(StringRef Name, DIFile *File,
328                                          unsigned LineNumber,
329                                          uint64_t SizeInBits,
330                                          uint64_t AlignInBits,
331                                          uint64_t OffsetInBits, unsigned Flags,
332                                          DIType *Ty, MDNode *PropertyNode) {
333   return DIDerivedType::get(
334       VMContext, dwarf::DW_TAG_member, Name, File, LineNumber,
335       DIScopeRef::get(getNonCompileUnitScope(File)), DITypeRef::get(Ty),
336       SizeInBits, AlignInBits, OffsetInBits, Flags, PropertyNode);
337 }
338 
339 DIObjCProperty *
340 DIBuilder::createObjCProperty(StringRef Name, DIFile *File, unsigned LineNumber,
341                               StringRef GetterName, StringRef SetterName,
342                               unsigned PropertyAttributes, DIType *Ty) {
343   return DIObjCProperty::get(VMContext, Name, File, LineNumber, GetterName,
344                              SetterName, PropertyAttributes,
345                              DITypeRef::get(Ty));
346 }
347 
348 DITemplateTypeParameter *
349 DIBuilder::createTemplateTypeParameter(DIScope *Context, StringRef Name,
350                                        DIType *Ty) {
351   assert((!Context || isa<DICompileUnit>(Context)) && "Expected compile unit");
352   return DITemplateTypeParameter::get(VMContext, Name, DITypeRef::get(Ty));
353 }
354 
355 static DITemplateValueParameter *
356 createTemplateValueParameterHelper(LLVMContext &VMContext, unsigned Tag,
357                                    DIScope *Context, StringRef Name, DIType *Ty,
358                                    Metadata *MD) {
359   assert((!Context || isa<DICompileUnit>(Context)) && "Expected compile unit");
360   return DITemplateValueParameter::get(VMContext, Tag, Name, DITypeRef::get(Ty),
361                                        MD);
362 }
363 
364 DITemplateValueParameter *
365 DIBuilder::createTemplateValueParameter(DIScope *Context, StringRef Name,
366                                         DIType *Ty, Constant *Val) {
367   return createTemplateValueParameterHelper(
368       VMContext, dwarf::DW_TAG_template_value_parameter, Context, Name, Ty,
369       getConstantOrNull(Val));
370 }
371 
372 DITemplateValueParameter *
373 DIBuilder::createTemplateTemplateParameter(DIScope *Context, StringRef Name,
374                                            DIType *Ty, StringRef Val) {
375   return createTemplateValueParameterHelper(
376       VMContext, dwarf::DW_TAG_GNU_template_template_param, Context, Name, Ty,
377       MDString::get(VMContext, Val));
378 }
379 
380 DITemplateValueParameter *
381 DIBuilder::createTemplateParameterPack(DIScope *Context, StringRef Name,
382                                        DIType *Ty, DINodeArray Val) {
383   return createTemplateValueParameterHelper(
384       VMContext, dwarf::DW_TAG_GNU_template_parameter_pack, Context, Name, Ty,
385       Val.get());
386 }
387 
388 DICompositeType *DIBuilder::createClassType(
389     DIScope *Context, StringRef Name, DIFile *File, unsigned LineNumber,
390     uint64_t SizeInBits, uint64_t AlignInBits, uint64_t OffsetInBits,
391     unsigned Flags, DIType *DerivedFrom, DINodeArray Elements,
392     DIType *VTableHolder, MDNode *TemplateParams, StringRef UniqueIdentifier) {
393   assert((!Context || isa<DIScope>(Context)) &&
394          "createClassType should be called with a valid Context");
395 
396   auto *R = DICompositeType::get(
397       VMContext, dwarf::DW_TAG_structure_type, Name, File, LineNumber,
398       DIScopeRef::get(getNonCompileUnitScope(Context)),
399       DITypeRef::get(DerivedFrom), SizeInBits, AlignInBits, OffsetInBits, Flags,
400       Elements, 0, DITypeRef::get(VTableHolder),
401       cast_or_null<MDTuple>(TemplateParams), UniqueIdentifier);
402   if (!UniqueIdentifier.empty())
403     retainType(R);
404   trackIfUnresolved(R);
405   return R;
406 }
407 
408 DICompositeType *DIBuilder::createStructType(
409     DIScope *Context, StringRef Name, DIFile *File, unsigned LineNumber,
410     uint64_t SizeInBits, uint64_t AlignInBits, unsigned Flags,
411     DIType *DerivedFrom, DINodeArray Elements, unsigned RunTimeLang,
412     DIType *VTableHolder, StringRef UniqueIdentifier) {
413   auto *R = DICompositeType::get(
414       VMContext, dwarf::DW_TAG_structure_type, Name, File, LineNumber,
415       DIScopeRef::get(getNonCompileUnitScope(Context)),
416       DITypeRef::get(DerivedFrom), SizeInBits, AlignInBits, 0, Flags, Elements,
417       RunTimeLang, DITypeRef::get(VTableHolder), nullptr, UniqueIdentifier);
418   if (!UniqueIdentifier.empty())
419     retainType(R);
420   trackIfUnresolved(R);
421   return R;
422 }
423 
424 DICompositeType *DIBuilder::createUnionType(
425     DIScope *Scope, StringRef Name, DIFile *File, unsigned LineNumber,
426     uint64_t SizeInBits, uint64_t AlignInBits, unsigned Flags,
427     DINodeArray Elements, unsigned RunTimeLang, StringRef UniqueIdentifier) {
428   auto *R = DICompositeType::get(
429       VMContext, dwarf::DW_TAG_union_type, Name, File, LineNumber,
430       DIScopeRef::get(getNonCompileUnitScope(Scope)), nullptr, SizeInBits,
431       AlignInBits, 0, Flags, Elements, RunTimeLang, nullptr, nullptr,
432       UniqueIdentifier);
433   if (!UniqueIdentifier.empty())
434     retainType(R);
435   trackIfUnresolved(R);
436   return R;
437 }
438 
439 DISubroutineType *DIBuilder::createSubroutineType(DITypeRefArray ParameterTypes,
440                                                   unsigned Flags) {
441   return DISubroutineType::get(VMContext, Flags, ParameterTypes);
442 }
443 
444 DICompositeType *DIBuilder::createExternalTypeRef(unsigned Tag, DIFile *File,
445                                                   StringRef UniqueIdentifier) {
446   assert(!UniqueIdentifier.empty() && "external type ref without uid");
447   auto *CTy =
448       DICompositeType::get(VMContext, Tag, "", nullptr, 0, nullptr, nullptr, 0,
449                            0, 0, DINode::FlagExternalTypeRef, nullptr, 0,
450                            nullptr, nullptr, UniqueIdentifier);
451   // Types with unique IDs need to be in the type map.
452   retainType(CTy);
453   return CTy;
454 }
455 
456 DICompositeType *DIBuilder::createEnumerationType(
457     DIScope *Scope, StringRef Name, DIFile *File, unsigned LineNumber,
458     uint64_t SizeInBits, uint64_t AlignInBits, DINodeArray Elements,
459     DIType *UnderlyingType, StringRef UniqueIdentifier) {
460   auto *CTy = DICompositeType::get(
461       VMContext, dwarf::DW_TAG_enumeration_type, Name, File, LineNumber,
462       DIScopeRef::get(getNonCompileUnitScope(Scope)),
463       DITypeRef::get(UnderlyingType), SizeInBits, AlignInBits, 0, 0, Elements,
464       0, nullptr, nullptr, UniqueIdentifier);
465   AllEnumTypes.push_back(CTy);
466   if (!UniqueIdentifier.empty())
467     retainType(CTy);
468   trackIfUnresolved(CTy);
469   return CTy;
470 }
471 
472 DICompositeType *DIBuilder::createArrayType(uint64_t Size, uint64_t AlignInBits,
473                                             DIType *Ty,
474                                             DINodeArray Subscripts) {
475   auto *R = DICompositeType::get(VMContext, dwarf::DW_TAG_array_type, "",
476                                  nullptr, 0, nullptr, DITypeRef::get(Ty), Size,
477                                  AlignInBits, 0, 0, Subscripts, 0, nullptr);
478   trackIfUnresolved(R);
479   return R;
480 }
481 
482 DICompositeType *DIBuilder::createVectorType(uint64_t Size,
483                                              uint64_t AlignInBits, DIType *Ty,
484                                              DINodeArray Subscripts) {
485   auto *R =
486       DICompositeType::get(VMContext, dwarf::DW_TAG_array_type, "", nullptr, 0,
487                            nullptr, DITypeRef::get(Ty), Size, AlignInBits, 0,
488                            DINode::FlagVector, Subscripts, 0, nullptr);
489   trackIfUnresolved(R);
490   return R;
491 }
492 
493 static DIType *createTypeWithFlags(LLVMContext &Context, DIType *Ty,
494                                    unsigned FlagsToSet) {
495   auto NewTy = Ty->clone();
496   NewTy->setFlags(NewTy->getFlags() | FlagsToSet);
497   return MDNode::replaceWithUniqued(std::move(NewTy));
498 }
499 
500 DIType *DIBuilder::createArtificialType(DIType *Ty) {
501   // FIXME: Restrict this to the nodes where it's valid.
502   if (Ty->isArtificial())
503     return Ty;
504   return createTypeWithFlags(VMContext, Ty, DINode::FlagArtificial);
505 }
506 
507 DIType *DIBuilder::createObjectPointerType(DIType *Ty) {
508   // FIXME: Restrict this to the nodes where it's valid.
509   if (Ty->isObjectPointer())
510     return Ty;
511   unsigned Flags = DINode::FlagObjectPointer | DINode::FlagArtificial;
512   return createTypeWithFlags(VMContext, Ty, Flags);
513 }
514 
515 void DIBuilder::retainType(DIType *T) {
516   assert(T && "Expected non-null type");
517   AllRetainTypes.emplace_back(T);
518 }
519 
520 DIBasicType *DIBuilder::createUnspecifiedParameter() { return nullptr; }
521 
522 DICompositeType *
523 DIBuilder::createForwardDecl(unsigned Tag, StringRef Name, DIScope *Scope,
524                              DIFile *F, unsigned Line, unsigned RuntimeLang,
525                              uint64_t SizeInBits, uint64_t AlignInBits,
526                              StringRef UniqueIdentifier) {
527   // FIXME: Define in terms of createReplaceableForwardDecl() by calling
528   // replaceWithUniqued().
529   auto *RetTy = DICompositeType::get(
530       VMContext, Tag, Name, F, Line,
531       DIScopeRef::get(getNonCompileUnitScope(Scope)), nullptr, SizeInBits,
532       AlignInBits, 0, DINode::FlagFwdDecl, nullptr, RuntimeLang, nullptr,
533       nullptr, UniqueIdentifier);
534   if (!UniqueIdentifier.empty())
535     retainType(RetTy);
536   trackIfUnresolved(RetTy);
537   return RetTy;
538 }
539 
540 DICompositeType *DIBuilder::createReplaceableCompositeType(
541     unsigned Tag, StringRef Name, DIScope *Scope, DIFile *F, unsigned Line,
542     unsigned RuntimeLang, uint64_t SizeInBits, uint64_t AlignInBits,
543     unsigned Flags, StringRef UniqueIdentifier) {
544   auto *RetTy = DICompositeType::getTemporary(
545                     VMContext, Tag, Name, F, Line,
546                     DIScopeRef::get(getNonCompileUnitScope(Scope)), nullptr,
547                     SizeInBits, AlignInBits, 0, Flags, nullptr, RuntimeLang,
548                     nullptr, nullptr, UniqueIdentifier)
549                     .release();
550   if (!UniqueIdentifier.empty())
551     retainType(RetTy);
552   trackIfUnresolved(RetTy);
553   return RetTy;
554 }
555 
556 DINodeArray DIBuilder::getOrCreateArray(ArrayRef<Metadata *> Elements) {
557   return MDTuple::get(VMContext, Elements);
558 }
559 
560 DITypeRefArray DIBuilder::getOrCreateTypeArray(ArrayRef<Metadata *> Elements) {
561   SmallVector<llvm::Metadata *, 16> Elts;
562   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
563     if (Elements[i] && isa<MDNode>(Elements[i]))
564       Elts.push_back(DITypeRef::get(cast<DIType>(Elements[i])));
565     else
566       Elts.push_back(Elements[i]);
567   }
568   return DITypeRefArray(MDNode::get(VMContext, Elts));
569 }
570 
571 DISubrange *DIBuilder::getOrCreateSubrange(int64_t Lo, int64_t Count) {
572   return DISubrange::get(VMContext, Count, Lo);
573 }
574 
575 static void checkGlobalVariableScope(DIScope *Context) {
576 #ifndef NDEBUG
577   if (auto *CT =
578           dyn_cast_or_null<DICompositeType>(getNonCompileUnitScope(Context)))
579     assert(CT->getIdentifier().empty() &&
580            "Context of a global variable should not be a type with identifier");
581 #endif
582 }
583 
584 DIGlobalVariable *DIBuilder::createGlobalVariable(
585     DIScope *Context, StringRef Name, StringRef LinkageName, DIFile *F,
586     unsigned LineNumber, DIType *Ty, bool isLocalToUnit, Constant *Val,
587     MDNode *Decl) {
588   checkGlobalVariableScope(Context);
589 
590   auto *N = DIGlobalVariable::get(VMContext, cast_or_null<DIScope>(Context),
591                                   Name, LinkageName, F, LineNumber,
592                                   DITypeRef::get(Ty), isLocalToUnit, true, Val,
593                                   cast_or_null<DIDerivedType>(Decl));
594   AllGVs.push_back(N);
595   return N;
596 }
597 
598 DIGlobalVariable *DIBuilder::createTempGlobalVariableFwdDecl(
599     DIScope *Context, StringRef Name, StringRef LinkageName, DIFile *F,
600     unsigned LineNumber, DIType *Ty, bool isLocalToUnit, Constant *Val,
601     MDNode *Decl) {
602   checkGlobalVariableScope(Context);
603 
604   return DIGlobalVariable::getTemporary(
605              VMContext, cast_or_null<DIScope>(Context), Name, LinkageName, F,
606              LineNumber, DITypeRef::get(Ty), isLocalToUnit, false, Val,
607              cast_or_null<DIDerivedType>(Decl))
608       .release();
609 }
610 
611 static DILocalVariable *createLocalVariable(
612     LLVMContext &VMContext,
613     DenseMap<MDNode *, std::vector<TrackingMDNodeRef>> &PreservedVariables,
614     DIScope *Scope, StringRef Name, unsigned ArgNo, DIFile *File,
615     unsigned LineNo, DIType *Ty, bool AlwaysPreserve, unsigned Flags) {
616   // FIXME: Why getNonCompileUnitScope()?
617   // FIXME: Why is "!Context" okay here?
618   // FIXME: Why doesn't this check for a subprogram or lexical block (AFAICT
619   // the only valid scopes)?
620   DIScope *Context = getNonCompileUnitScope(Scope);
621 
622   auto *Node =
623       DILocalVariable::get(VMContext, cast_or_null<DILocalScope>(Context), Name,
624                            File, LineNo, DITypeRef::get(Ty), ArgNo, Flags);
625   if (AlwaysPreserve) {
626     // The optimizer may remove local variables. If there is an interest
627     // to preserve variable info in such situation then stash it in a
628     // named mdnode.
629     DISubprogram *Fn = getDISubprogram(Scope);
630     assert(Fn && "Missing subprogram for local variable");
631     PreservedVariables[Fn].emplace_back(Node);
632   }
633   return Node;
634 }
635 
636 DILocalVariable *DIBuilder::createAutoVariable(DIScope *Scope, StringRef Name,
637                                                DIFile *File, unsigned LineNo,
638                                                DIType *Ty, bool AlwaysPreserve,
639                                                unsigned Flags) {
640   return createLocalVariable(VMContext, PreservedVariables, Scope, Name,
641                              /* ArgNo */ 0, File, LineNo, Ty, AlwaysPreserve,
642                              Flags);
643 }
644 
645 DILocalVariable *DIBuilder::createParameterVariable(
646     DIScope *Scope, StringRef Name, unsigned ArgNo, DIFile *File,
647     unsigned LineNo, DIType *Ty, bool AlwaysPreserve, unsigned Flags) {
648   assert(ArgNo && "Expected non-zero argument number for parameter");
649   return createLocalVariable(VMContext, PreservedVariables, Scope, Name, ArgNo,
650                              File, LineNo, Ty, AlwaysPreserve, Flags);
651 }
652 
653 DIExpression *DIBuilder::createExpression(ArrayRef<uint64_t> Addr) {
654   return DIExpression::get(VMContext, Addr);
655 }
656 
657 DIExpression *DIBuilder::createExpression(ArrayRef<int64_t> Signed) {
658   // TODO: Remove the callers of this signed version and delete.
659   SmallVector<uint64_t, 8> Addr(Signed.begin(), Signed.end());
660   return createExpression(Addr);
661 }
662 
663 DIExpression *DIBuilder::createBitPieceExpression(unsigned OffsetInBytes,
664                                                   unsigned SizeInBytes) {
665   uint64_t Addr[] = {dwarf::DW_OP_bit_piece, OffsetInBytes, SizeInBytes};
666   return DIExpression::get(VMContext, Addr);
667 }
668 
669 DISubprogram *DIBuilder::createFunction(
670     DIScopeRef Context, StringRef Name, StringRef LinkageName, DIFile *File,
671     unsigned LineNo, DISubroutineType *Ty, bool isLocalToUnit,
672     bool isDefinition, unsigned ScopeLine, unsigned Flags, bool isOptimized,
673     DITemplateParameterArray TParams, DISubprogram *Decl) {
674   // dragonegg does not generate identifier for types, so using an empty map
675   // to resolve the context should be fine.
676   DITypeIdentifierMap EmptyMap;
677   return createFunction(Context.resolve(EmptyMap), Name, LinkageName, File,
678                         LineNo, Ty, isLocalToUnit, isDefinition, ScopeLine,
679                         Flags, isOptimized, TParams, Decl);
680 }
681 
682 template <class... Ts>
683 static DISubprogram *getSubprogram(bool IsDistinct, Ts &&... Args) {
684   if (IsDistinct)
685     return DISubprogram::getDistinct(std::forward<Ts>(Args)...);
686   return DISubprogram::get(std::forward<Ts>(Args)...);
687 }
688 
689 DISubprogram *DIBuilder::createFunction(
690     DIScope *Context, StringRef Name, StringRef LinkageName, DIFile *File,
691     unsigned LineNo, DISubroutineType *Ty, bool isLocalToUnit,
692     bool isDefinition, unsigned ScopeLine, unsigned Flags, bool isOptimized,
693     DITemplateParameterArray TParams, DISubprogram *Decl) {
694   auto *Node =
695       getSubprogram(/* IsDistinct = */ isDefinition, VMContext,
696                     DIScopeRef::get(getNonCompileUnitScope(Context)), Name,
697                     LinkageName, File, LineNo, Ty, isLocalToUnit, isDefinition,
698                     ScopeLine, nullptr, 0, 0, Flags, isOptimized, TParams, Decl,
699                     MDTuple::getTemporary(VMContext, None).release());
700 
701   if (isDefinition)
702     AllSubprograms.push_back(Node);
703   trackIfUnresolved(Node);
704   return Node;
705 }
706 
707 DISubprogram *DIBuilder::createTempFunctionFwdDecl(
708     DIScope *Context, StringRef Name, StringRef LinkageName, DIFile *File,
709     unsigned LineNo, DISubroutineType *Ty, bool isLocalToUnit,
710     bool isDefinition, unsigned ScopeLine, unsigned Flags, bool isOptimized,
711     DITemplateParameterArray TParams, DISubprogram *Decl) {
712   return DISubprogram::getTemporary(
713              VMContext, DIScopeRef::get(getNonCompileUnitScope(Context)), Name,
714              LinkageName, File, LineNo, Ty, isLocalToUnit, isDefinition,
715              ScopeLine, nullptr, 0, 0, Flags, isOptimized, TParams, Decl,
716              nullptr)
717       .release();
718 }
719 
720 DISubprogram *
721 DIBuilder::createMethod(DIScope *Context, StringRef Name, StringRef LinkageName,
722                         DIFile *F, unsigned LineNo, DISubroutineType *Ty,
723                         bool isLocalToUnit, bool isDefinition, unsigned VK,
724                         unsigned VIndex, DIType *VTableHolder, unsigned Flags,
725                         bool isOptimized, DITemplateParameterArray TParams) {
726   assert(getNonCompileUnitScope(Context) &&
727          "Methods should have both a Context and a context that isn't "
728          "the compile unit.");
729   // FIXME: Do we want to use different scope/lines?
730   auto *SP = getSubprogram(
731       /* IsDistinct = */ isDefinition, VMContext,
732       DIScopeRef::get(cast<DIScope>(Context)), Name, LinkageName, F, LineNo, Ty,
733       isLocalToUnit, isDefinition, LineNo, DITypeRef::get(VTableHolder), VK,
734       VIndex, Flags, isOptimized, TParams, nullptr, nullptr);
735 
736   if (isDefinition)
737     AllSubprograms.push_back(SP);
738   trackIfUnresolved(SP);
739   return SP;
740 }
741 
742 DINamespace *DIBuilder::createNameSpace(DIScope *Scope, StringRef Name,
743                                         DIFile *File, unsigned LineNo) {
744   return DINamespace::get(VMContext, getNonCompileUnitScope(Scope), File, Name,
745                           LineNo);
746 }
747 
748 DIModule *DIBuilder::createModule(DIScope *Scope, StringRef Name,
749                                   StringRef ConfigurationMacros,
750                                   StringRef IncludePath,
751                                   StringRef ISysRoot) {
752  return DIModule::get(VMContext, getNonCompileUnitScope(Scope), Name,
753                       ConfigurationMacros, IncludePath, ISysRoot);
754 }
755 
756 DILexicalBlockFile *DIBuilder::createLexicalBlockFile(DIScope *Scope,
757                                                       DIFile *File,
758                                                       unsigned Discriminator) {
759   return DILexicalBlockFile::get(VMContext, Scope, File, Discriminator);
760 }
761 
762 DILexicalBlock *DIBuilder::createLexicalBlock(DIScope *Scope, DIFile *File,
763                                               unsigned Line, unsigned Col) {
764   // Make these distinct, to avoid merging two lexical blocks on the same
765   // file/line/column.
766   return DILexicalBlock::getDistinct(VMContext, getNonCompileUnitScope(Scope),
767                                      File, Line, Col);
768 }
769 
770 static Value *getDbgIntrinsicValueImpl(LLVMContext &VMContext, Value *V) {
771   assert(V && "no value passed to dbg intrinsic");
772   return MetadataAsValue::get(VMContext, ValueAsMetadata::get(V));
773 }
774 
775 static Instruction *withDebugLoc(Instruction *I, const DILocation *DL) {
776   I->setDebugLoc(const_cast<DILocation *>(DL));
777   return I;
778 }
779 
780 Instruction *DIBuilder::insertDeclare(Value *Storage, DILocalVariable *VarInfo,
781                                       DIExpression *Expr, const DILocation *DL,
782                                       Instruction *InsertBefore) {
783   assert(VarInfo && "empty or invalid DILocalVariable* passed to dbg.declare");
784   assert(DL && "Expected debug loc");
785   assert(DL->getScope()->getSubprogram() ==
786              VarInfo->getScope()->getSubprogram() &&
787          "Expected matching subprograms");
788   if (!DeclareFn)
789     DeclareFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_declare);
790 
791   trackIfUnresolved(VarInfo);
792   trackIfUnresolved(Expr);
793   Value *Args[] = {getDbgIntrinsicValueImpl(VMContext, Storage),
794                    MetadataAsValue::get(VMContext, VarInfo),
795                    MetadataAsValue::get(VMContext, Expr)};
796   return withDebugLoc(CallInst::Create(DeclareFn, Args, "", InsertBefore), DL);
797 }
798 
799 Instruction *DIBuilder::insertDeclare(Value *Storage, DILocalVariable *VarInfo,
800                                       DIExpression *Expr, const DILocation *DL,
801                                       BasicBlock *InsertAtEnd) {
802   assert(VarInfo && "empty or invalid DILocalVariable* passed to dbg.declare");
803   assert(DL && "Expected debug loc");
804   assert(DL->getScope()->getSubprogram() ==
805              VarInfo->getScope()->getSubprogram() &&
806          "Expected matching subprograms");
807   if (!DeclareFn)
808     DeclareFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_declare);
809 
810   trackIfUnresolved(VarInfo);
811   trackIfUnresolved(Expr);
812   Value *Args[] = {getDbgIntrinsicValueImpl(VMContext, Storage),
813                    MetadataAsValue::get(VMContext, VarInfo),
814                    MetadataAsValue::get(VMContext, Expr)};
815 
816   // If this block already has a terminator then insert this intrinsic
817   // before the terminator.
818   if (TerminatorInst *T = InsertAtEnd->getTerminator())
819     return withDebugLoc(CallInst::Create(DeclareFn, Args, "", T), DL);
820   return withDebugLoc(CallInst::Create(DeclareFn, Args, "", InsertAtEnd), DL);
821 }
822 
823 Instruction *DIBuilder::insertDbgValueIntrinsic(Value *V, uint64_t Offset,
824                                                 DILocalVariable *VarInfo,
825                                                 DIExpression *Expr,
826                                                 const DILocation *DL,
827                                                 Instruction *InsertBefore) {
828   assert(V && "no value passed to dbg.value");
829   assert(VarInfo && "empty or invalid DILocalVariable* passed to dbg.value");
830   assert(DL && "Expected debug loc");
831   assert(DL->getScope()->getSubprogram() ==
832              VarInfo->getScope()->getSubprogram() &&
833          "Expected matching subprograms");
834   if (!ValueFn)
835     ValueFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_value);
836 
837   trackIfUnresolved(VarInfo);
838   trackIfUnresolved(Expr);
839   Value *Args[] = {getDbgIntrinsicValueImpl(VMContext, V),
840                    ConstantInt::get(Type::getInt64Ty(VMContext), Offset),
841                    MetadataAsValue::get(VMContext, VarInfo),
842                    MetadataAsValue::get(VMContext, Expr)};
843   return withDebugLoc(CallInst::Create(ValueFn, Args, "", InsertBefore), DL);
844 }
845 
846 Instruction *DIBuilder::insertDbgValueIntrinsic(Value *V, uint64_t Offset,
847                                                 DILocalVariable *VarInfo,
848                                                 DIExpression *Expr,
849                                                 const DILocation *DL,
850                                                 BasicBlock *InsertAtEnd) {
851   assert(V && "no value passed to dbg.value");
852   assert(VarInfo && "empty or invalid DILocalVariable* passed to dbg.value");
853   assert(DL && "Expected debug loc");
854   assert(DL->getScope()->getSubprogram() ==
855              VarInfo->getScope()->getSubprogram() &&
856          "Expected matching subprograms");
857   if (!ValueFn)
858     ValueFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_value);
859 
860   trackIfUnresolved(VarInfo);
861   trackIfUnresolved(Expr);
862   Value *Args[] = {getDbgIntrinsicValueImpl(VMContext, V),
863                    ConstantInt::get(Type::getInt64Ty(VMContext), Offset),
864                    MetadataAsValue::get(VMContext, VarInfo),
865                    MetadataAsValue::get(VMContext, Expr)};
866 
867   return withDebugLoc(CallInst::Create(ValueFn, Args, "", InsertAtEnd), DL);
868 }
869 
870 void DIBuilder::replaceVTableHolder(DICompositeType *&T,
871                                     DICompositeType *VTableHolder) {
872   {
873     TypedTrackingMDRef<DICompositeType> N(T);
874     N->replaceVTableHolder(DITypeRef::get(VTableHolder));
875     T = N.get();
876   }
877 
878   // If this didn't create a self-reference, just return.
879   if (T != VTableHolder)
880     return;
881 
882   // Look for unresolved operands.  T will drop RAUW support, orphaning any
883   // cycles underneath it.
884   if (T->isResolved())
885     for (const MDOperand &O : T->operands())
886       if (auto *N = dyn_cast_or_null<MDNode>(O))
887         trackIfUnresolved(N);
888 }
889 
890 void DIBuilder::replaceArrays(DICompositeType *&T, DINodeArray Elements,
891                               DINodeArray TParams) {
892   {
893     TypedTrackingMDRef<DICompositeType> N(T);
894     if (Elements)
895       N->replaceElements(Elements);
896     if (TParams)
897       N->replaceTemplateParams(DITemplateParameterArray(TParams));
898     T = N.get();
899   }
900 
901   // If T isn't resolved, there's no problem.
902   if (!T->isResolved())
903     return;
904 
905   // If T is resolved, it may be due to a self-reference cycle.  Track the
906   // arrays explicitly if they're unresolved, or else the cycles will be
907   // orphaned.
908   if (Elements)
909     trackIfUnresolved(Elements.get());
910   if (TParams)
911     trackIfUnresolved(TParams.get());
912 }
913