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