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