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