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