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