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