4b837af9d44b3b5cc372bd88e3ea3e9f26cfdf1a
[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   assert(M.Verify() && "Imported module should be valid");
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, StringRef Name) {
200   // Make sure to use the unique identifier based metadata reference for
201   // types that have one.
202   Metadata *V =
203       Decl.isType() ? static_cast<Metadata *>(DIType(Decl).getRef()) : Decl;
204   return ::createImportedModule(VMContext, dwarf::DW_TAG_imported_declaration,
205                                 Context, V, 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                             FromTy.getRef(), 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, PointeeTy.getRef(), SizeInBits,
253                             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, PointeeTy.getRef(), SizeInBits,
261                             AlignInBits, 0, 0, Base.getRef());
262 }
263
264 DIDerivedType DIBuilder::createReferenceType(unsigned Tag, DIType RTy) {
265   assert(RTy.isType() && "Unable to create reference type");
266   return MDDerivedType::get(VMContext, Tag, "", nullptr, 0, nullptr,
267                             RTy.getRef(), 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(VMContext, dwarf::DW_TAG_typedef, Name,
273                             File.getFileNode(), LineNo,
274                             DIScope(getNonCompileUnitScope(Context)).getRef(),
275                             Ty.getRef(), 0, 0, 0, 0);
276 }
277
278 DIDerivedType DIBuilder::createFriend(DIType Ty, DIType FriendTy) {
279   // typedefs are encoded in DIDerivedType format.
280   assert(Ty.isType() && "Invalid type!");
281   assert(FriendTy.isType() && "Invalid friend type!");
282   return MDDerivedType::get(VMContext, dwarf::DW_TAG_friend, "", nullptr, 0,
283                             Ty.getRef(), FriendTy.getRef(), 0, 0, 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, Ty.getRef(), BaseTy.getRef(), 0, 0, BaseOffset,
292                             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       DIScope(getNonCompileUnitScope(Scope)).getRef(), Ty.getRef(), SizeInBits,
304       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       DIScope(getNonCompileUnitScope(Scope)).getRef(), Ty.getRef(), 0, 0, 0,
323       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(VMContext, dwarf::DW_TAG_member, Name, File,
333                             LineNumber, getNonCompileUnitScope(File),
334                             Ty.getRef(), SizeInBits, AlignInBits, OffsetInBits,
335                             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(!DIScope(getNonCompileUnitScope(Context)).getRef() &&
350          "Expected compile unit");
351   return MDTemplateTypeParameter::get(VMContext, Name, Ty.getRef());
352 }
353
354 static DITemplateValueParameter
355 createTemplateValueParameterHelper(LLVMContext &VMContext, unsigned Tag,
356                                    DIDescriptor Context, StringRef Name,
357                                    DIType Ty, Metadata *MD) {
358   assert(!DIScope(getNonCompileUnitScope(Context)).getRef() &&
359          "Expected compile unit");
360   return MDTemplateValueParameter::get(VMContext, Tag, Name, Ty.getRef(), MD);
361 }
362
363 DITemplateValueParameter
364 DIBuilder::createTemplateValueParameter(DIDescriptor Context, StringRef Name,
365                                         DIType Ty, Constant *Val) {
366   return createTemplateValueParameterHelper(
367       VMContext, dwarf::DW_TAG_template_value_parameter, Context, Name, Ty,
368       getConstantOrNull(Val));
369 }
370
371 DITemplateValueParameter
372 DIBuilder::createTemplateTemplateParameter(DIDescriptor Context, StringRef Name,
373                                            DIType Ty, StringRef Val) {
374   return createTemplateValueParameterHelper(
375       VMContext, dwarf::DW_TAG_GNU_template_template_param, Context, Name, Ty,
376       MDString::get(VMContext, Val));
377 }
378
379 DITemplateValueParameter
380 DIBuilder::createTemplateParameterPack(DIDescriptor Context, StringRef Name,
381                                        DIType Ty, DIArray Val) {
382   return createTemplateValueParameterHelper(
383       VMContext, dwarf::DW_TAG_GNU_template_parameter_pack, Context, Name, Ty,
384       Val);
385 }
386
387 DICompositeType DIBuilder::createClassType(DIDescriptor Context, StringRef Name,
388                                            DIFile File, unsigned LineNumber,
389                                            uint64_t SizeInBits,
390                                            uint64_t AlignInBits,
391                                            uint64_t OffsetInBits,
392                                            unsigned Flags, DIType DerivedFrom,
393                                            DIArray Elements,
394                                            DIType VTableHolder,
395                                            MDNode *TemplateParams,
396                                            StringRef UniqueIdentifier) {
397   assert((!Context || Context.isScope() || Context.isType()) &&
398          "createClassType should be called with a valid Context");
399   // TAG_class_type is encoded in DICompositeType format.
400   DICompositeType R = MDCompositeType::get(
401       VMContext, dwarf::DW_TAG_structure_type, Name, File, LineNumber,
402       DIScope(getNonCompileUnitScope(Context)).getRef(), DerivedFrom.getRef(),
403       SizeInBits, AlignInBits, OffsetInBits, Flags, Elements, 0,
404       VTableHolder.getRef(), TemplateParams, UniqueIdentifier);
405   if (!UniqueIdentifier.empty())
406     retainType(R);
407   trackIfUnresolved(R);
408   return R;
409 }
410
411 DICompositeType DIBuilder::createStructType(DIDescriptor Context,
412                                             StringRef Name, DIFile File,
413                                             unsigned LineNumber,
414                                             uint64_t SizeInBits,
415                                             uint64_t AlignInBits,
416                                             unsigned Flags, DIType DerivedFrom,
417                                             DIArray Elements,
418                                             unsigned RunTimeLang,
419                                             DIType VTableHolder,
420                                             StringRef UniqueIdentifier) {
421   DICompositeType R = MDCompositeType::get(
422       VMContext, dwarf::DW_TAG_structure_type, Name, File, LineNumber,
423       DIScope(getNonCompileUnitScope(Context)).getRef(), DerivedFrom.getRef(),
424       SizeInBits, AlignInBits, 0, Flags, Elements, RunTimeLang,
425       VTableHolder.getRef(), nullptr, UniqueIdentifier);
426   if (!UniqueIdentifier.empty())
427     retainType(R);
428   trackIfUnresolved(R);
429   return R;
430 }
431
432 DICompositeType DIBuilder::createUnionType(DIDescriptor Scope, StringRef Name,
433                                            DIFile File, unsigned LineNumber,
434                                            uint64_t SizeInBits,
435                                            uint64_t AlignInBits, unsigned Flags,
436                                            DIArray Elements,
437                                            unsigned RunTimeLang,
438                                            StringRef UniqueIdentifier) {
439   DICompositeType R = MDCompositeType::get(
440       VMContext, dwarf::DW_TAG_union_type, Name, File, LineNumber,
441       DIScope(getNonCompileUnitScope(Scope)).getRef(), nullptr, SizeInBits,
442       AlignInBits, 0, Flags, Elements, RunTimeLang, nullptr, nullptr,
443       UniqueIdentifier);
444   if (!UniqueIdentifier.empty())
445     retainType(R);
446   trackIfUnresolved(R);
447   return R;
448 }
449
450 DISubroutineType DIBuilder::createSubroutineType(DIFile File,
451                                                  DITypeArray ParameterTypes,
452                                                  unsigned Flags) {
453   return MDSubroutineType::get(VMContext, Flags, ParameterTypes);
454 }
455
456 DICompositeType DIBuilder::createEnumerationType(
457     DIDescriptor Scope, StringRef Name, DIFile File, unsigned LineNumber,
458     uint64_t SizeInBits, uint64_t AlignInBits, DIArray Elements,
459     DIType UnderlyingType, StringRef UniqueIdentifier) {
460   DICompositeType CTy = MDCompositeType::get(
461       VMContext, dwarf::DW_TAG_enumeration_type, Name, File, LineNumber,
462       DIScope(getNonCompileUnitScope(Scope)).getRef(), UnderlyingType.getRef(),
463       SizeInBits, AlignInBits, 0, 0, Elements, 0, nullptr, nullptr,
464       UniqueIdentifier);
465   AllEnumTypes.push_back(CTy);
466   if (!UniqueIdentifier.empty())
467     retainType(CTy);
468   trackIfUnresolved(CTy);
469   return CTy;
470 }
471
472 DICompositeType DIBuilder::createArrayType(uint64_t Size, uint64_t AlignInBits,
473                                            DIType Ty, DIArray Subscripts) {
474   auto *R = MDCompositeType::get(VMContext, dwarf::DW_TAG_array_type, "",
475                                  nullptr, 0, nullptr, Ty.getRef(), Size,
476                                  AlignInBits, 0, 0, Subscripts, 0, nullptr);
477   trackIfUnresolved(R);
478   return R;
479 }
480
481 DICompositeType DIBuilder::createVectorType(uint64_t Size, uint64_t AlignInBits,
482                                             DIType Ty, DIArray Subscripts) {
483   auto *R = MDCompositeType::get(
484       VMContext, dwarf::DW_TAG_array_type, "", nullptr, 0, nullptr, Ty.getRef(),
485       Size, AlignInBits, 0, DIType::FlagVector, Subscripts, 0, nullptr);
486   trackIfUnresolved(R);
487   return R;
488 }
489
490 static DIType createTypeWithFlags(LLVMContext &Context, DIType Ty,
491                                   unsigned FlagsToSet) {
492   TempMDType NewTy = cast<MDType>(static_cast<MDNode *>(Ty))->clone();
493   NewTy->setFlags(NewTy->getFlags() | FlagsToSet);
494   return MDNode::replaceWithUniqued(std::move(NewTy));
495 }
496
497 DIType DIBuilder::createArtificialType(DIType Ty) {
498   // FIXME: Restrict this to the nodes where it's valid.
499   if (Ty.isArtificial())
500     return Ty;
501   return createTypeWithFlags(VMContext, Ty, DIType::FlagArtificial);
502 }
503
504 DIType DIBuilder::createObjectPointerType(DIType Ty) {
505   // FIXME: Restrict this to the nodes where it's valid.
506   if (Ty.isObjectPointer())
507     return Ty;
508   unsigned Flags = DIType::FlagObjectPointer | DIType::FlagArtificial;
509   return createTypeWithFlags(VMContext, Ty, Flags);
510 }
511
512 void DIBuilder::retainType(DIType T) {
513   assert(T.get() && "Expected non-null type");
514   AllRetainTypes.emplace_back(T);
515 }
516
517 DIBasicType DIBuilder::createUnspecifiedParameter() {
518   return DIBasicType();
519 }
520
521 DICompositeType
522 DIBuilder::createForwardDecl(unsigned Tag, StringRef Name, DIDescriptor Scope,
523                              DIFile F, unsigned Line, unsigned RuntimeLang,
524                              uint64_t SizeInBits, uint64_t AlignInBits,
525                              StringRef UniqueIdentifier) {
526   // FIXME: Define in terms of createReplaceableForwardDecl() by calling
527   // replaceWithUniqued().
528   DICompositeType RetTy = MDCompositeType::get(
529       VMContext, Tag, Name, F.getFileNode(), Line,
530       DIScope(getNonCompileUnitScope(Scope)).getRef(), nullptr, SizeInBits,
531       AlignInBits, 0, DIDescriptor::FlagFwdDecl, nullptr, RuntimeLang, nullptr,
532       nullptr, UniqueIdentifier);
533   if (!UniqueIdentifier.empty())
534     retainType(RetTy);
535   trackIfUnresolved(RetTy);
536   return RetTy;
537 }
538
539 DICompositeType DIBuilder::createReplaceableCompositeType(
540     unsigned Tag, StringRef Name, DIDescriptor Scope, DIFile F, unsigned Line,
541     unsigned RuntimeLang, uint64_t SizeInBits, uint64_t AlignInBits,
542     unsigned Flags, StringRef UniqueIdentifier) {
543   DICompositeType RetTy =
544       MDCompositeType::getTemporary(
545           VMContext, Tag, Name, F.getFileNode(), Line,
546           DIScope(getNonCompileUnitScope(Scope)).getRef(), nullptr, SizeInBits,
547           AlignInBits, 0, Flags, nullptr, RuntimeLang,
548           nullptr, nullptr, UniqueIdentifier).release();
549   if (!UniqueIdentifier.empty())
550     retainType(RetTy);
551   trackIfUnresolved(RetTy);
552   return RetTy;
553 }
554
555 DIArray DIBuilder::getOrCreateArray(ArrayRef<Metadata *> Elements) {
556   return DIArray(MDNode::get(VMContext, Elements));
557 }
558
559 DITypeArray DIBuilder::getOrCreateTypeArray(ArrayRef<Metadata *> Elements) {
560   SmallVector<llvm::Metadata *, 16> Elts;
561   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
562     if (Elements[i] && isa<MDNode>(Elements[i]))
563       Elts.push_back(DIType(cast<MDNode>(Elements[i])).getRef());
564     else
565       Elts.push_back(Elements[i]);
566   }
567   return DITypeArray(MDNode::get(VMContext, Elts));
568 }
569
570 DISubrange DIBuilder::getOrCreateSubrange(int64_t Lo, int64_t Count) {
571   return MDSubrange::get(VMContext, Count, Lo);
572 }
573
574 static void checkGlobalVariableScope(DIDescriptor Context) {
575   MDNode *TheCtx = getNonCompileUnitScope(Context);
576   if (DIScope(TheCtx).isCompositeType()) {
577     assert(!DICompositeType(TheCtx).getIdentifier() &&
578            "Context of a global variable should not be a type with identifier");
579   }
580 }
581
582 DIGlobalVariable DIBuilder::createGlobalVariable(
583     DIDescriptor Context, StringRef Name, StringRef LinkageName, DIFile F,
584     unsigned LineNumber, DITypeRef Ty, bool isLocalToUnit, Constant *Val,
585     MDNode *Decl) {
586   checkGlobalVariableScope(Context);
587
588   auto *N = MDGlobalVariable::get(
589       VMContext, cast_or_null<MDScope>(Context.get()), Name, LinkageName, F,
590       LineNumber, Ty, isLocalToUnit, true, getConstantOrNull(Val),
591       cast_or_null<MDDerivedType>(Decl));
592   AllGVs.push_back(N);
593   return N;
594 }
595
596 DIGlobalVariable DIBuilder::createTempGlobalVariableFwdDecl(
597     DIDescriptor Context, StringRef Name, StringRef LinkageName, DIFile F,
598     unsigned LineNumber, DITypeRef Ty, bool isLocalToUnit, Constant *Val,
599     MDNode *Decl) {
600   checkGlobalVariableScope(Context);
601
602   return MDGlobalVariable::getTemporary(
603              VMContext, cast_or_null<MDScope>(Context.get()), Name, LinkageName,
604              F, LineNumber, Ty, isLocalToUnit, false, getConstantOrNull(Val),
605              cast_or_null<MDDerivedType>(Decl)).release();
606 }
607
608 DIVariable DIBuilder::createLocalVariable(unsigned Tag, DIDescriptor Scope,
609                                           StringRef Name, DIFile File,
610                                           unsigned LineNo, DITypeRef Ty,
611                                           bool AlwaysPreserve, unsigned Flags,
612                                           unsigned ArgNo) {
613   // FIXME: Why getNonCompileUnitScope()?
614   // FIXME: Why is "!Context" okay here?
615   // FIXME: WHy doesn't this check for a subprogram or lexical block (AFAICT
616   // the only valid scopes)?
617   DIDescriptor Context(getNonCompileUnitScope(Scope));
618   assert((!Context || Context.isScope()) &&
619          "createLocalVariable should be called with a valid Context");
620
621   auto *Node = MDLocalVariable::get(VMContext, Tag,
622                                     cast_or_null<MDLocalScope>(Context.get()),
623                                     Name, File, LineNo, Ty, ArgNo, Flags);
624   if (AlwaysPreserve) {
625     // The optimizer may remove local variable. If there is an interest
626     // to preserve variable info in such situation then stash it in a
627     // named mdnode.
628     DISubprogram Fn(getDISubprogram(Scope));
629     assert(Fn && "Missing subprogram for local variable");
630     PreservedVariables[Fn].emplace_back(Node);
631   }
632   return Node;
633 }
634
635 DIExpression DIBuilder::createExpression(ArrayRef<uint64_t> Addr) {
636   return MDExpression::get(VMContext, Addr);
637 }
638
639 DIExpression DIBuilder::createExpression(ArrayRef<int64_t> Signed) {
640   // TODO: Remove the callers of this signed version and delete.
641   SmallVector<uint64_t, 8> Addr(Signed.begin(), Signed.end());
642   return createExpression(Addr);
643 }
644
645 DIExpression DIBuilder::createBitPieceExpression(unsigned OffsetInBytes,
646                                                  unsigned SizeInBytes) {
647   uint64_t Addr[] = {dwarf::DW_OP_bit_piece, OffsetInBytes, SizeInBytes};
648   return MDExpression::get(VMContext, Addr);
649 }
650
651 DISubprogram DIBuilder::createFunction(DIScopeRef Context, StringRef Name,
652                                        StringRef LinkageName, DIFile File,
653                                        unsigned LineNo, DICompositeType Ty,
654                                        bool isLocalToUnit, bool isDefinition,
655                                        unsigned ScopeLine, unsigned Flags,
656                                        bool isOptimized, Function *Fn,
657                                        MDNode *TParams, MDNode *Decl) {
658   // dragonegg does not generate identifier for types, so using an empty map
659   // to resolve the context should be fine.
660   DITypeIdentifierMap EmptyMap;
661   return createFunction(Context.resolve(EmptyMap), Name, LinkageName, File,
662                         LineNo, Ty, isLocalToUnit, isDefinition, ScopeLine,
663                         Flags, isOptimized, Fn, TParams, Decl);
664 }
665
666 DISubprogram DIBuilder::createFunction(DIDescriptor Context, StringRef Name,
667                                        StringRef LinkageName, DIFile File,
668                                        unsigned LineNo, DICompositeType Ty,
669                                        bool isLocalToUnit, bool isDefinition,
670                                        unsigned ScopeLine, unsigned Flags,
671                                        bool isOptimized, Function *Fn,
672                                        MDNode *TParams, MDNode *Decl) {
673   assert(Ty.getTag() == dwarf::DW_TAG_subroutine_type &&
674          "function types should be subroutines");
675   auto *Node = MDSubprogram::get(
676       VMContext, DIScope(getNonCompileUnitScope(Context)).getRef(), Name,
677       LinkageName, File.getFileNode(), LineNo, Ty, isLocalToUnit, isDefinition,
678       ScopeLine, nullptr, 0, 0, Flags, isOptimized, getConstantOrNull(Fn),
679       TParams, Decl, MDNode::getTemporary(VMContext, None).release());
680
681   if (isDefinition)
682     AllSubprograms.push_back(Node);
683   trackIfUnresolved(Node);
684   return Node;
685 }
686
687 DISubprogram
688 DIBuilder::createTempFunctionFwdDecl(DIDescriptor Context, StringRef Name,
689                                      StringRef LinkageName, DIFile File,
690                                      unsigned LineNo, DICompositeType Ty,
691                                      bool isLocalToUnit, bool isDefinition,
692                                      unsigned ScopeLine, unsigned Flags,
693                                      bool isOptimized, Function *Fn,
694                                      MDNode *TParams, MDNode *Decl) {
695   return MDSubprogram::getTemporary(
696              VMContext, DIScope(getNonCompileUnitScope(Context)).getRef(), Name,
697              LinkageName, File.getFileNode(), LineNo, Ty, isLocalToUnit,
698              isDefinition, ScopeLine, nullptr, 0, 0, Flags, isOptimized,
699              getConstantOrNull(Fn), TParams, Decl, nullptr).release();
700 }
701
702 DISubprogram DIBuilder::createMethod(DIDescriptor Context, StringRef Name,
703                                      StringRef LinkageName, DIFile F,
704                                      unsigned LineNo, DICompositeType Ty,
705                                      bool isLocalToUnit, bool isDefinition,
706                                      unsigned VK, unsigned VIndex,
707                                      DIType VTableHolder, unsigned Flags,
708                                      bool isOptimized, Function *Fn,
709                                      MDNode *TParam) {
710   assert(Ty.getTag() == dwarf::DW_TAG_subroutine_type &&
711          "function types should be subroutines");
712   assert(getNonCompileUnitScope(Context) &&
713          "Methods should have both a Context and a context that isn't "
714          "the compile unit.");
715   // FIXME: Do we want to use different scope/lines?
716   auto *Node = MDSubprogram::get(
717       VMContext, DIScope(Context).getRef(), Name, LinkageName, F.getFileNode(),
718       LineNo, Ty, isLocalToUnit, isDefinition, LineNo, VTableHolder.getRef(),
719       VK, VIndex, Flags, isOptimized, getConstantOrNull(Fn), TParam, nullptr,
720       nullptr);
721
722   if (isDefinition)
723     AllSubprograms.push_back(Node);
724   DISubprogram S(Node);
725   assert(S.isSubprogram() && "createMethod should return a valid DISubprogram");
726   trackIfUnresolved(S);
727   return S;
728 }
729
730 DINameSpace DIBuilder::createNameSpace(DIDescriptor Scope, StringRef Name,
731                                        DIFile File, unsigned LineNo) {
732   DINameSpace R = MDNamespace::get(VMContext, getNonCompileUnitScope(Scope),
733                                    File.getFileNode(), Name, LineNo);
734   assert(R.Verify() &&
735          "createNameSpace should return a verifiable DINameSpace");
736   return R;
737 }
738
739 DILexicalBlockFile DIBuilder::createLexicalBlockFile(DIDescriptor Scope,
740                                                      DIFile File,
741                                                      unsigned Discriminator) {
742   DILexicalBlockFile R = MDLexicalBlockFile::get(
743       VMContext, Scope, File.getFileNode(), Discriminator);
744   assert(
745       R.Verify() &&
746       "createLexicalBlockFile should return a verifiable DILexicalBlockFile");
747   return R;
748 }
749
750 DILexicalBlock DIBuilder::createLexicalBlock(DIDescriptor Scope, DIFile File,
751                                              unsigned Line, unsigned Col) {
752   // Make these distinct, to avoid merging two lexical blocks on the same
753   // file/line/column.
754   DILexicalBlock R = MDLexicalBlock::getDistinct(
755       VMContext, getNonCompileUnitScope(Scope), File.getFileNode(), Line, Col);
756   assert(R.Verify() &&
757          "createLexicalBlock should return a verifiable DILexicalBlock");
758   return R;
759 }
760
761 static Value *getDbgIntrinsicValueImpl(LLVMContext &VMContext, Value *V) {
762   assert(V && "no value passed to dbg intrinsic");
763   return MetadataAsValue::get(VMContext, ValueAsMetadata::get(V));
764 }
765
766 Instruction *DIBuilder::insertDeclare(Value *Storage, DIVariable VarInfo,
767                                       DIExpression Expr,
768                                       Instruction *InsertBefore) {
769   assert(VarInfo.isVariable() &&
770          "empty or invalid DIVariable passed to dbg.declare");
771   if (!DeclareFn)
772     DeclareFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_declare);
773
774   trackIfUnresolved(VarInfo);
775   trackIfUnresolved(Expr);
776   Value *Args[] = {getDbgIntrinsicValueImpl(VMContext, Storage),
777                    MetadataAsValue::get(VMContext, VarInfo),
778                    MetadataAsValue::get(VMContext, Expr)};
779   return CallInst::Create(DeclareFn, Args, "", InsertBefore);
780 }
781
782 Instruction *DIBuilder::insertDeclare(Value *Storage, DIVariable VarInfo,
783                                       DIExpression Expr,
784                                       BasicBlock *InsertAtEnd) {
785   assert(VarInfo.isVariable() &&
786          "empty or invalid DIVariable passed to dbg.declare");
787   if (!DeclareFn)
788     DeclareFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_declare);
789
790   trackIfUnresolved(VarInfo);
791   trackIfUnresolved(Expr);
792   Value *Args[] = {getDbgIntrinsicValueImpl(VMContext, Storage),
793                    MetadataAsValue::get(VMContext, VarInfo),
794                    MetadataAsValue::get(VMContext, Expr)};
795
796   // If this block already has a terminator then insert this intrinsic
797   // before the terminator.
798   if (TerminatorInst *T = InsertAtEnd->getTerminator())
799     return CallInst::Create(DeclareFn, Args, "", T);
800   else
801     return CallInst::Create(DeclareFn, Args, "", InsertAtEnd);
802 }
803
804 Instruction *DIBuilder::insertDbgValueIntrinsic(Value *V, uint64_t Offset,
805                                                 DIVariable VarInfo,
806                                                 DIExpression Expr,
807                                                 Instruction *InsertBefore) {
808   assert(V && "no value passed to dbg.value");
809   assert(VarInfo.isVariable() &&
810          "empty or invalid DIVariable passed to dbg.value");
811   if (!ValueFn)
812     ValueFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_value);
813
814   trackIfUnresolved(VarInfo);
815   trackIfUnresolved(Expr);
816   Value *Args[] = {getDbgIntrinsicValueImpl(VMContext, V),
817                    ConstantInt::get(Type::getInt64Ty(VMContext), Offset),
818                    MetadataAsValue::get(VMContext, VarInfo),
819                    MetadataAsValue::get(VMContext, Expr)};
820   return CallInst::Create(ValueFn, Args, "", InsertBefore);
821 }
822
823 Instruction *DIBuilder::insertDbgValueIntrinsic(Value *V, uint64_t Offset,
824                                                 DIVariable VarInfo,
825                                                 DIExpression Expr,
826                                                 BasicBlock *InsertAtEnd) {
827   assert(V && "no value passed to dbg.value");
828   assert(VarInfo.isVariable() &&
829          "empty or invalid DIVariable passed to dbg.value");
830   if (!ValueFn)
831     ValueFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_value);
832
833   trackIfUnresolved(VarInfo);
834   trackIfUnresolved(Expr);
835   Value *Args[] = {getDbgIntrinsicValueImpl(VMContext, V),
836                    ConstantInt::get(Type::getInt64Ty(VMContext), Offset),
837                    MetadataAsValue::get(VMContext, VarInfo),
838                    MetadataAsValue::get(VMContext, Expr)};
839   return CallInst::Create(ValueFn, Args, "", InsertAtEnd);
840 }
841
842 void DIBuilder::replaceVTableHolder(DICompositeType &T, DICompositeType VTableHolder) {
843   T.setContainingType(VTableHolder);
844
845   // If this didn't create a self-reference, just return.
846   if (T != VTableHolder)
847     return;
848
849   // Look for unresolved operands.  T will drop RAUW support, orphaning any
850   // cycles underneath it.
851   if (T->isResolved())
852     for (const MDOperand &O : T->operands())
853       if (auto *N = dyn_cast_or_null<MDNode>(O))
854         trackIfUnresolved(N);
855 }
856
857 void DIBuilder::replaceArrays(DICompositeType &T, DIArray Elements,
858                               DIArray TParams) {
859   T.setArrays(Elements, TParams);
860
861   // If T isn't resolved, there's no problem.
862   if (!T->isResolved())
863     return;
864
865   // If "T" is resolved, it may be due to a self-reference cycle.  Track the
866   // arrays explicitly if they're unresolved, or else the cycles will be
867   // orphaned.
868   if (Elements)
869     trackIfUnresolved(Elements);
870   if (TParams)
871     trackIfUnresolved(TParams);
872 }