IR: Remove MDTupleTypedArrayWrapper::operator MDTuple*()
[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   TempEnumTypes->replaceAllUsesWith(Enums.get());
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   TempRetainTypes->replaceAllUsesWith(RetainTypes.get());
91
92   DIArray SPs = getOrCreateArray(AllSubprograms);
93   TempSubprograms->replaceAllUsesWith(SPs.get());
94   for (unsigned i = 0, e = SPs.size(); i != e; ++i) {
95     DISubprogram SP = cast<MDSubprogram>(SPs[i]);
96     if (MDNode *Temp = SP.getVariables().get()) {
97       const auto &PV = PreservedVariables.lookup(SP);
98       SmallVector<Metadata *, 4> Variables(PV.begin(), PV.end());
99       DIArray AV = getOrCreateArray(Variables);
100       Temp->replaceAllUsesWith(AV.get());
101     }
102   }
103
104   DIArray GVs = getOrCreateArray(AllGVs);
105   TempGVs->replaceAllUsesWith(GVs.get());
106
107   SmallVector<Metadata *, 16> RetainValuesI(AllImportedModules.begin(),
108                                             AllImportedModules.end());
109   DIArray IMs = getOrCreateArray(RetainValuesI);
110   TempImportedModules->replaceAllUsesWith(IMs.get());
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   MDCompileUnit *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 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 =
178       MDImportedEntity::get(C, Tag, Context, DebugNodeRef(NS), Line, Name);
179   AllImportedModules.emplace_back(M.get());
180   return M;
181 }
182
183 DIImportedEntity DIBuilder::createImportedModule(DIScope Context,
184                                                  DINameSpace NS,
185                                                  unsigned Line) {
186   return ::createImportedModule(VMContext, dwarf::DW_TAG_imported_module,
187                                 Context, NS, Line, StringRef(), AllImportedModules);
188 }
189
190 DIImportedEntity DIBuilder::createImportedModule(DIScope Context,
191                                                  DIImportedEntity NS,
192                                                  unsigned Line) {
193   return ::createImportedModule(VMContext, dwarf::DW_TAG_imported_module,
194                                 Context, NS, Line, StringRef(), AllImportedModules);
195 }
196
197 DIImportedEntity DIBuilder::createImportedDeclaration(DIScope Context,
198                                                       DIDescriptor Decl,
199                                                       unsigned Line,
200                                                       StringRef Name) {
201   // Make sure to use the unique identifier based metadata reference for
202   // types that have one.
203   return ::createImportedModule(
204       VMContext, dwarf::DW_TAG_imported_declaration, Context,
205       DebugNodeRef::get(cast_or_null<DebugNode>(Decl.get())), Line, Name,
206       AllImportedModules);
207 }
208
209 DIImportedEntity DIBuilder::createImportedDeclaration(DIScope Context,
210                                                       DIImportedEntity Imp,
211                                                       unsigned Line, StringRef Name) {
212   return ::createImportedModule(VMContext, dwarf::DW_TAG_imported_declaration,
213                                 Context, Imp, Line, Name, AllImportedModules);
214 }
215
216 DIFile DIBuilder::createFile(StringRef Filename, StringRef Directory) {
217   return MDFile::get(VMContext, Filename, Directory);
218 }
219
220 DIEnumerator DIBuilder::createEnumerator(StringRef Name, int64_t Val) {
221   assert(!Name.empty() && "Unable to create enumerator without name");
222   return MDEnumerator::get(VMContext, Val, Name);
223 }
224
225 DIBasicType DIBuilder::createUnspecifiedType(StringRef Name) {
226   assert(!Name.empty() && "Unable to create type without name");
227   return MDBasicType::get(VMContext, dwarf::DW_TAG_unspecified_type, Name);
228 }
229
230 DIBasicType DIBuilder::createNullPtrType() {
231   return createUnspecifiedType("decltype(nullptr)");
232 }
233
234 DIBasicType
235 DIBuilder::createBasicType(StringRef Name, uint64_t SizeInBits,
236                            uint64_t AlignInBits, unsigned Encoding) {
237   assert(!Name.empty() && "Unable to create type without name");
238   return MDBasicType::get(VMContext, dwarf::DW_TAG_base_type, Name, SizeInBits,
239                           AlignInBits, Encoding);
240 }
241
242 DIDerivedType DIBuilder::createQualifiedType(unsigned Tag, DIType FromTy) {
243   return MDDerivedType::get(VMContext, Tag, "", nullptr, 0, nullptr,
244                             MDTypeRef::get(FromTy), 0, 0, 0, 0);
245 }
246
247 DIDerivedType
248 DIBuilder::createPointerType(DIType PointeeTy, uint64_t SizeInBits,
249                              uint64_t AlignInBits, StringRef Name) {
250   // FIXME: Why is there a name here?
251   return MDDerivedType::get(VMContext, dwarf::DW_TAG_pointer_type, Name,
252                             nullptr, 0, nullptr, MDTypeRef::get(PointeeTy),
253                             SizeInBits, AlignInBits, 0, 0);
254 }
255
256 DIDerivedType
257 DIBuilder::createMemberPointerType(DIType PointeeTy, DIType Base,
258                                    uint64_t SizeInBits, uint64_t AlignInBits) {
259   return MDDerivedType::get(VMContext, dwarf::DW_TAG_ptr_to_member_type, "",
260                             nullptr, 0, nullptr, MDTypeRef::get(PointeeTy),
261                             SizeInBits, AlignInBits, 0, 0, MDTypeRef::get(Base));
262 }
263
264 DIDerivedType DIBuilder::createReferenceType(unsigned Tag, DIType RTy) {
265   assert(RTy && "Unable to create reference type");
266   return MDDerivedType::get(VMContext, Tag, "", nullptr, 0, nullptr,
267                             MDTypeRef::get(RTy), 0, 0, 0, 0);
268 }
269
270 DIDerivedType DIBuilder::createTypedef(DIType Ty, StringRef Name, DIFile File,
271                                        unsigned LineNo, DIDescriptor Context) {
272   return MDDerivedType::get(
273       VMContext, dwarf::DW_TAG_typedef, Name, File, LineNo,
274       MDScopeRef::get(DIScope(getNonCompileUnitScope(Context))),
275       MDTypeRef::get(Ty), 0, 0, 0, 0);
276 }
277
278 DIDerivedType DIBuilder::createFriend(DIType Ty, DIType FriendTy) {
279   // typedefs are encoded in DIDerivedType format.
280   assert(Ty && "Invalid type!");
281   assert(FriendTy && "Invalid friend type!");
282   return MDDerivedType::get(VMContext, dwarf::DW_TAG_friend, "", nullptr, 0,
283                             MDTypeRef::get(Ty), MDTypeRef::get(FriendTy), 0, 0,
284                             0, 0);
285 }
286
287 DIDerivedType DIBuilder::createInheritance(DIType Ty, DIType BaseTy,
288                                            uint64_t BaseOffset,
289                                            unsigned Flags) {
290   assert(Ty && "Unable to create inheritance");
291   return MDDerivedType::get(VMContext, dwarf::DW_TAG_inheritance, "", nullptr,
292                             0, MDTypeRef::get(Ty), MDTypeRef::get(BaseTy), 0, 0,
293                             BaseOffset, Flags);
294 }
295
296 DIDerivedType DIBuilder::createMemberType(DIDescriptor Scope, StringRef Name,
297                                           DIFile File, unsigned LineNumber,
298                                           uint64_t SizeInBits,
299                                           uint64_t AlignInBits,
300                                           uint64_t OffsetInBits, unsigned Flags,
301                                           DIType Ty) {
302   return MDDerivedType::get(
303       VMContext, dwarf::DW_TAG_member, Name, File, LineNumber,
304       MDScopeRef::get(DIScope(getNonCompileUnitScope(Scope))),
305       MDTypeRef::get(Ty), SizeInBits, AlignInBits, OffsetInBits, Flags);
306 }
307
308 static ConstantAsMetadata *getConstantOrNull(Constant *C) {
309   if (C)
310     return ConstantAsMetadata::get(C);
311   return nullptr;
312 }
313
314 DIDerivedType DIBuilder::createStaticMemberType(DIDescriptor Scope,
315                                                 StringRef Name, DIFile File,
316                                                 unsigned LineNumber, DIType Ty,
317                                                 unsigned Flags,
318                                                 llvm::Constant *Val) {
319   // TAG_member is encoded in DIDerivedType format.
320   Flags |= DIDescriptor::FlagStaticMember;
321   return MDDerivedType::get(
322       VMContext, dwarf::DW_TAG_member, Name, File, LineNumber,
323       MDScopeRef::get(DIScope(getNonCompileUnitScope(Scope))),
324       MDTypeRef::get(Ty), 0, 0, 0, Flags, getConstantOrNull(Val));
325 }
326
327 DIDerivedType DIBuilder::createObjCIVar(StringRef Name, DIFile File,
328                                         unsigned LineNumber,
329                                         uint64_t SizeInBits,
330                                         uint64_t AlignInBits,
331                                         uint64_t OffsetInBits, unsigned Flags,
332                                         DIType Ty, MDNode *PropertyNode) {
333   return MDDerivedType::get(
334       VMContext, dwarf::DW_TAG_member, Name, File, LineNumber,
335       MDScopeRef::get(getNonCompileUnitScope(File)), MDTypeRef::get(Ty),
336       SizeInBits, AlignInBits, OffsetInBits, Flags, PropertyNode);
337 }
338
339 DIObjCProperty
340 DIBuilder::createObjCProperty(StringRef Name, DIFile File, unsigned LineNumber,
341                               StringRef GetterName, StringRef SetterName,
342                               unsigned PropertyAttributes, DIType Ty) {
343   return MDObjCProperty::get(VMContext, Name, File, LineNumber, GetterName,
344                              SetterName, PropertyAttributes, Ty);
345 }
346
347 DITemplateTypeParameter
348 DIBuilder::createTemplateTypeParameter(DIDescriptor Context, StringRef Name,
349                                        DIType Ty) {
350   assert((!Context || isa<MDCompileUnit>(Context.get())) &&
351          "Expected compile unit");
352   return MDTemplateTypeParameter::get(VMContext, Name, MDTypeRef::get(Ty));
353 }
354
355 static DITemplateValueParameter
356 createTemplateValueParameterHelper(LLVMContext &VMContext, unsigned Tag,
357                                    DIDescriptor Context, StringRef Name,
358                                    DIType Ty, Metadata *MD) {
359   assert((!Context || isa<MDCompileUnit>(Context.get())) &&
360          "Expected compile unit");
361   return MDTemplateValueParameter::get(VMContext, Tag, Name, MDTypeRef::get(Ty),
362                                        MD);
363 }
364
365 DITemplateValueParameter
366 DIBuilder::createTemplateValueParameter(DIDescriptor Context, StringRef Name,
367                                         DIType Ty, Constant *Val) {
368   return createTemplateValueParameterHelper(
369       VMContext, dwarf::DW_TAG_template_value_parameter, Context, Name, Ty,
370       getConstantOrNull(Val));
371 }
372
373 DITemplateValueParameter
374 DIBuilder::createTemplateTemplateParameter(DIDescriptor Context, StringRef Name,
375                                            DIType Ty, StringRef Val) {
376   return createTemplateValueParameterHelper(
377       VMContext, dwarf::DW_TAG_GNU_template_template_param, Context, Name, Ty,
378       MDString::get(VMContext, Val));
379 }
380
381 DITemplateValueParameter
382 DIBuilder::createTemplateParameterPack(DIDescriptor Context, StringRef Name,
383                                        DIType Ty, DIArray Val) {
384   return createTemplateValueParameterHelper(
385       VMContext, dwarf::DW_TAG_GNU_template_parameter_pack, Context, Name, Ty,
386       Val.get());
387 }
388
389 DICompositeType DIBuilder::createClassType(DIDescriptor Context, StringRef Name,
390                                            DIFile File, unsigned LineNumber,
391                                            uint64_t SizeInBits,
392                                            uint64_t AlignInBits,
393                                            uint64_t OffsetInBits,
394                                            unsigned Flags, DIType DerivedFrom,
395                                            DIArray Elements,
396                                            DIType VTableHolder,
397                                            MDNode *TemplateParams,
398                                            StringRef UniqueIdentifier) {
399   assert((!Context || isa<MDScope>(Context)) &&
400          "createClassType should be called with a valid Context");
401   // TAG_class_type is encoded in DICompositeType format.
402   DICompositeType R = MDCompositeType::get(
403       VMContext, dwarf::DW_TAG_structure_type, Name, File, LineNumber,
404       MDScopeRef::get(DIScope(getNonCompileUnitScope(Context))),
405       MDTypeRef::get(DerivedFrom), SizeInBits, AlignInBits, OffsetInBits, Flags,
406       Elements, 0, MDTypeRef::get(VTableHolder),
407       cast_or_null<MDTuple>(TemplateParams), UniqueIdentifier);
408   if (!UniqueIdentifier.empty())
409     retainType(R);
410   trackIfUnresolved(R);
411   return R;
412 }
413
414 DICompositeType DIBuilder::createStructType(DIDescriptor Context,
415                                             StringRef Name, DIFile File,
416                                             unsigned LineNumber,
417                                             uint64_t SizeInBits,
418                                             uint64_t AlignInBits,
419                                             unsigned Flags, DIType DerivedFrom,
420                                             DIArray Elements,
421                                             unsigned RunTimeLang,
422                                             DIType VTableHolder,
423                                             StringRef UniqueIdentifier) {
424   DICompositeType R = MDCompositeType::get(
425       VMContext, dwarf::DW_TAG_structure_type, Name, File, LineNumber,
426       MDScopeRef::get(DIScope(getNonCompileUnitScope(Context))),
427       MDTypeRef::get(DerivedFrom), SizeInBits, AlignInBits, 0, Flags, Elements,
428       RunTimeLang, MDTypeRef::get(VTableHolder), nullptr, UniqueIdentifier);
429   if (!UniqueIdentifier.empty())
430     retainType(R);
431   trackIfUnresolved(R);
432   return R;
433 }
434
435 DICompositeType DIBuilder::createUnionType(DIDescriptor Scope, StringRef Name,
436                                            DIFile File, unsigned LineNumber,
437                                            uint64_t SizeInBits,
438                                            uint64_t AlignInBits, unsigned Flags,
439                                            DIArray Elements,
440                                            unsigned RunTimeLang,
441                                            StringRef UniqueIdentifier) {
442   DICompositeType R = MDCompositeType::get(
443       VMContext, dwarf::DW_TAG_union_type, Name, File, LineNumber,
444       MDScopeRef::get(DIScope(getNonCompileUnitScope(Scope))), nullptr,
445       SizeInBits, AlignInBits, 0, Flags, Elements, RunTimeLang, nullptr,
446       nullptr, UniqueIdentifier);
447   if (!UniqueIdentifier.empty())
448     retainType(R);
449   trackIfUnresolved(R);
450   return R;
451 }
452
453 DISubroutineType DIBuilder::createSubroutineType(DIFile File,
454                                                  DITypeArray ParameterTypes,
455                                                  unsigned Flags) {
456   return MDSubroutineType::get(VMContext, Flags, ParameterTypes);
457 }
458
459 DICompositeType DIBuilder::createEnumerationType(
460     DIDescriptor Scope, StringRef Name, DIFile File, unsigned LineNumber,
461     uint64_t SizeInBits, uint64_t AlignInBits, DIArray Elements,
462     DIType UnderlyingType, StringRef UniqueIdentifier) {
463   DICompositeType CTy = MDCompositeType::get(
464       VMContext, dwarf::DW_TAG_enumeration_type, Name, File, LineNumber,
465       MDScopeRef::get(DIScope(getNonCompileUnitScope(Scope))),
466       MDTypeRef::get(UnderlyingType), SizeInBits, AlignInBits, 0, 0, Elements,
467       0, nullptr, nullptr, UniqueIdentifier);
468   AllEnumTypes.push_back(CTy);
469   if (!UniqueIdentifier.empty())
470     retainType(CTy);
471   trackIfUnresolved(CTy);
472   return CTy;
473 }
474
475 DICompositeType DIBuilder::createArrayType(uint64_t Size, uint64_t AlignInBits,
476                                            DIType Ty, DIArray Subscripts) {
477   auto *R = MDCompositeType::get(VMContext, dwarf::DW_TAG_array_type, "",
478                                  nullptr, 0, nullptr, MDTypeRef::get(Ty), Size,
479                                  AlignInBits, 0, 0, Subscripts, 0, nullptr);
480   trackIfUnresolved(R);
481   return R;
482 }
483
484 DICompositeType DIBuilder::createVectorType(uint64_t Size, uint64_t AlignInBits,
485                                             DIType Ty, DIArray Subscripts) {
486   auto *R =
487       MDCompositeType::get(VMContext, dwarf::DW_TAG_array_type, "", nullptr, 0,
488                            nullptr, MDTypeRef::get(Ty), Size, AlignInBits, 0,
489                            DIType::FlagVector, Subscripts, 0, nullptr);
490   trackIfUnresolved(R);
491   return R;
492 }
493
494 static DIType createTypeWithFlags(LLVMContext &Context, DIType Ty,
495                                   unsigned FlagsToSet) {
496   TempMDType NewTy = cast<MDType>(static_cast<MDNode *>(Ty))->clone();
497   NewTy->setFlags(NewTy->getFlags() | FlagsToSet);
498   return MDNode::replaceWithUniqued(std::move(NewTy));
499 }
500
501 DIType DIBuilder::createArtificialType(DIType Ty) {
502   // FIXME: Restrict this to the nodes where it's valid.
503   if (Ty.isArtificial())
504     return Ty;
505   return createTypeWithFlags(VMContext, Ty, DIType::FlagArtificial);
506 }
507
508 DIType DIBuilder::createObjectPointerType(DIType Ty) {
509   // FIXME: Restrict this to the nodes where it's valid.
510   if (Ty.isObjectPointer())
511     return Ty;
512   unsigned Flags = DIType::FlagObjectPointer | DIType::FlagArtificial;
513   return createTypeWithFlags(VMContext, Ty, Flags);
514 }
515
516 void DIBuilder::retainType(DIType T) {
517   assert(T.get() && "Expected non-null type");
518   AllRetainTypes.emplace_back(T);
519 }
520
521 DIBasicType DIBuilder::createUnspecifiedParameter() {
522   return DIBasicType();
523 }
524
525 DICompositeType
526 DIBuilder::createForwardDecl(unsigned Tag, StringRef Name, DIDescriptor Scope,
527                              DIFile F, unsigned Line, unsigned RuntimeLang,
528                              uint64_t SizeInBits, uint64_t AlignInBits,
529                              StringRef UniqueIdentifier) {
530   // FIXME: Define in terms of createReplaceableForwardDecl() by calling
531   // replaceWithUniqued().
532   DICompositeType RetTy = MDCompositeType::get(
533       VMContext, Tag, Name, F, Line,
534       MDScopeRef::get(DIScope(getNonCompileUnitScope(Scope))), nullptr,
535       SizeInBits, AlignInBits, 0, DIDescriptor::FlagFwdDecl, nullptr,
536       RuntimeLang, nullptr, nullptr, UniqueIdentifier);
537   if (!UniqueIdentifier.empty())
538     retainType(RetTy);
539   trackIfUnresolved(RetTy);
540   return RetTy;
541 }
542
543 DICompositeType DIBuilder::createReplaceableCompositeType(
544     unsigned Tag, StringRef Name, DIDescriptor Scope, DIFile F, unsigned Line,
545     unsigned RuntimeLang, uint64_t SizeInBits, uint64_t AlignInBits,
546     unsigned Flags, StringRef UniqueIdentifier) {
547   DICompositeType RetTy =
548       MDCompositeType::getTemporary(
549           VMContext, Tag, Name, F, Line,
550           MDScopeRef::get(DIScope(getNonCompileUnitScope(Scope))), nullptr,
551           SizeInBits, AlignInBits, 0, Flags, nullptr, RuntimeLang, nullptr,
552           nullptr, UniqueIdentifier)
553           .release();
554   if (!UniqueIdentifier.empty())
555     retainType(RetTy);
556   trackIfUnresolved(RetTy);
557   return RetTy;
558 }
559
560 DIArray DIBuilder::getOrCreateArray(ArrayRef<Metadata *> Elements) {
561   return DIArray(MDNode::get(VMContext, Elements));
562 }
563
564 DITypeArray DIBuilder::getOrCreateTypeArray(ArrayRef<Metadata *> Elements) {
565   SmallVector<llvm::Metadata *, 16> Elts;
566   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
567     if (Elements[i] && isa<MDNode>(Elements[i]))
568       Elts.push_back(MDTypeRef::get(cast<MDType>(Elements[i])));
569     else
570       Elts.push_back(Elements[i]);
571   }
572   return DITypeArray(MDNode::get(VMContext, Elts));
573 }
574
575 DISubrange DIBuilder::getOrCreateSubrange(int64_t Lo, int64_t Count) {
576   return MDSubrange::get(VMContext, Count, Lo);
577 }
578
579 static void checkGlobalVariableScope(DIDescriptor Context) {
580 #ifndef NDEBUG
581   if (DICompositeType CT =
582           dyn_cast_or_null<MDCompositeType>(getNonCompileUnitScope(Context)))
583     assert(!CT.getIdentifier() &&
584            "Context of a global variable should not be a type with identifier");
585 #endif
586 }
587
588 DIGlobalVariable DIBuilder::createGlobalVariable(
589     DIDescriptor Context, StringRef Name, StringRef LinkageName, DIFile F,
590     unsigned LineNumber, DIType Ty, bool isLocalToUnit, Constant *Val,
591     MDNode *Decl) {
592   checkGlobalVariableScope(Context);
593
594   auto *N = MDGlobalVariable::get(
595       VMContext, cast_or_null<MDScope>(Context.get()), Name, LinkageName, F,
596       LineNumber, MDTypeRef::get(Ty), isLocalToUnit, true,
597       getConstantOrNull(Val), cast_or_null<MDDerivedType>(Decl));
598   AllGVs.push_back(N);
599   return N;
600 }
601
602 DIGlobalVariable DIBuilder::createTempGlobalVariableFwdDecl(
603     DIDescriptor Context, StringRef Name, StringRef LinkageName, DIFile F,
604     unsigned LineNumber, DIType Ty, bool isLocalToUnit, Constant *Val,
605     MDNode *Decl) {
606   checkGlobalVariableScope(Context);
607
608   return MDGlobalVariable::getTemporary(
609              VMContext, cast_or_null<MDScope>(Context.get()), Name, LinkageName,
610              F, LineNumber, MDTypeRef::get(Ty), isLocalToUnit, false, getConstantOrNull(Val),
611              cast_or_null<MDDerivedType>(Decl)).release();
612 }
613
614 DIVariable DIBuilder::createLocalVariable(unsigned Tag, DIDescriptor Scope,
615                                           StringRef Name, DIFile File,
616                                           unsigned LineNo, DIType Ty,
617                                           bool AlwaysPreserve, unsigned Flags,
618                                           unsigned ArgNo) {
619   // FIXME: Why getNonCompileUnitScope()?
620   // FIXME: Why is "!Context" okay here?
621   // FIXME: WHy doesn't this check for a subprogram or lexical block (AFAICT
622   // the only valid scopes)?
623   DIScope Context = getNonCompileUnitScope(Scope);
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 *SP = MDSubprogram::get(
727       VMContext, MDScopeRef::get(cast<MDScope>(Context)), Name, LinkageName,
728       F.get(), 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(SP);
735   trackIfUnresolved(SP);
736   return SP;
737 }
738
739 DINameSpace DIBuilder::createNameSpace(DIDescriptor Scope, StringRef Name,
740                                        DIFile File, unsigned LineNo) {
741   return MDNamespace::get(VMContext, getNonCompileUnitScope(Scope), File, Name,
742                           LineNo);
743 }
744
745 DILexicalBlockFile DIBuilder::createLexicalBlockFile(DIDescriptor Scope,
746                                                      DIFile File,
747                                                      unsigned Discriminator) {
748   return MDLexicalBlockFile::get(VMContext, Scope, File.getFileNode(),
749                                  Discriminator);
750 }
751
752 DILexicalBlock DIBuilder::createLexicalBlock(DIDescriptor Scope, DIFile File,
753                                              unsigned Line, unsigned Col) {
754   // Make these distinct, to avoid merging two lexical blocks on the same
755   // file/line/column.
756   return MDLexicalBlock::getDistinct(VMContext, getNonCompileUnitScope(Scope),
757                                      File.getFileNode(), Line, Col);
758 }
759
760 static Value *getDbgIntrinsicValueImpl(LLVMContext &VMContext, Value *V) {
761   assert(V && "no value passed to dbg intrinsic");
762   return MetadataAsValue::get(VMContext, ValueAsMetadata::get(V));
763 }
764
765 Instruction *DIBuilder::insertDeclare(Value *Storage, DIVariable VarInfo,
766                                       DIExpression Expr,
767                                       Instruction *InsertBefore) {
768   assert(VarInfo && "empty or invalid DIVariable passed to dbg.declare");
769   if (!DeclareFn)
770     DeclareFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_declare);
771
772   trackIfUnresolved(VarInfo);
773   trackIfUnresolved(Expr);
774   Value *Args[] = {getDbgIntrinsicValueImpl(VMContext, Storage),
775                    MetadataAsValue::get(VMContext, VarInfo),
776                    MetadataAsValue::get(VMContext, Expr)};
777   return CallInst::Create(DeclareFn, Args, "", InsertBefore);
778 }
779
780 Instruction *DIBuilder::insertDeclare(Value *Storage, DIVariable VarInfo,
781                                       DIExpression Expr,
782                                       BasicBlock *InsertAtEnd) {
783   assert(VarInfo && "empty or invalid DIVariable passed to dbg.declare");
784   if (!DeclareFn)
785     DeclareFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_declare);
786
787   trackIfUnresolved(VarInfo);
788   trackIfUnresolved(Expr);
789   Value *Args[] = {getDbgIntrinsicValueImpl(VMContext, Storage),
790                    MetadataAsValue::get(VMContext, VarInfo),
791                    MetadataAsValue::get(VMContext, Expr)};
792
793   // If this block already has a terminator then insert this intrinsic
794   // before the terminator.
795   if (TerminatorInst *T = InsertAtEnd->getTerminator())
796     return CallInst::Create(DeclareFn, Args, "", T);
797   else
798     return CallInst::Create(DeclareFn, Args, "", InsertAtEnd);
799 }
800
801 Instruction *DIBuilder::insertDbgValueIntrinsic(Value *V, uint64_t Offset,
802                                                 DIVariable VarInfo,
803                                                 DIExpression Expr,
804                                                 Instruction *InsertBefore) {
805   assert(V && "no value passed to dbg.value");
806   assert(VarInfo && "empty or invalid DIVariable passed to dbg.value");
807   if (!ValueFn)
808     ValueFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_value);
809
810   trackIfUnresolved(VarInfo);
811   trackIfUnresolved(Expr);
812   Value *Args[] = {getDbgIntrinsicValueImpl(VMContext, V),
813                    ConstantInt::get(Type::getInt64Ty(VMContext), Offset),
814                    MetadataAsValue::get(VMContext, VarInfo),
815                    MetadataAsValue::get(VMContext, Expr)};
816   return CallInst::Create(ValueFn, Args, "", InsertBefore);
817 }
818
819 Instruction *DIBuilder::insertDbgValueIntrinsic(Value *V, uint64_t Offset,
820                                                 DIVariable VarInfo,
821                                                 DIExpression Expr,
822                                                 BasicBlock *InsertAtEnd) {
823   assert(V && "no value passed to dbg.value");
824   assert(VarInfo && "empty or invalid DIVariable passed to dbg.value");
825   if (!ValueFn)
826     ValueFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_value);
827
828   trackIfUnresolved(VarInfo);
829   trackIfUnresolved(Expr);
830   Value *Args[] = {getDbgIntrinsicValueImpl(VMContext, V),
831                    ConstantInt::get(Type::getInt64Ty(VMContext), Offset),
832                    MetadataAsValue::get(VMContext, VarInfo),
833                    MetadataAsValue::get(VMContext, Expr)};
834   return CallInst::Create(ValueFn, Args, "", InsertAtEnd);
835 }
836
837 void DIBuilder::replaceVTableHolder(DICompositeType &T, DICompositeType VTableHolder) {
838   {
839     TypedTrackingMDRef<MDCompositeTypeBase> N(T);
840     N->replaceVTableHolder(MDTypeRef::get(VTableHolder));
841     T = N.get();
842   }
843
844   // If this didn't create a self-reference, just return.
845   if (T != VTableHolder)
846     return;
847
848   // Look for unresolved operands.  T will drop RAUW support, orphaning any
849   // cycles underneath it.
850   if (T->isResolved())
851     for (const MDOperand &O : T->operands())
852       if (auto *N = dyn_cast_or_null<MDNode>(O))
853         trackIfUnresolved(N);
854 }
855
856 void DIBuilder::replaceArrays(DICompositeType &T, DIArray Elements,
857                               DIArray TParams) {
858   {
859     TypedTrackingMDRef<MDCompositeTypeBase> N(T);
860     if (Elements)
861       N->replaceElements(Elements);
862     if (TParams)
863       N->replaceTemplateParams(MDTemplateParameterArray(TParams));
864     T = N.get();
865   }
866
867   // If T isn't resolved, there's no problem.
868   if (!T->isResolved())
869     return;
870
871   // If "T" is resolved, it may be due to a self-reference cycle.  Track the
872   // arrays explicitly if they're unresolved, or else the cycles will be
873   // orphaned.
874   if (Elements)
875     trackIfUnresolved(Elements.get());
876   if (TParams)
877     trackIfUnresolved(TParams.get());
878 }