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