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