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/IR/IRBuilder.h"
16 #include "LLVMContextImpl.h"
17 #include "llvm/ADT/Optional.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/BinaryFormat/Dwarf.h"
20 #include "llvm/IR/Constants.h"
21 #include "llvm/IR/DebugInfo.h"
22 #include "llvm/IR/IntrinsicInst.h"
23 #include "llvm/IR/Module.h"
24 #include "llvm/Support/Debug.h"
25 
26 using namespace llvm;
27 using namespace llvm::dwarf;
28 
29 cl::opt<bool>
30     UseDbgAddr("use-dbg-addr",
31                llvm::cl::desc("Use llvm.dbg.addr for all local variables"),
32                cl::init(false), cl::Hidden);
33 
34 DIBuilder::DIBuilder(Module &m, bool AllowUnresolvedNodes, DICompileUnit *CU)
35   : M(m), VMContext(M.getContext()), CUNode(CU),
36       DeclareFn(nullptr), ValueFn(nullptr), LabelFn(nullptr),
37       AllowUnresolvedNodes(AllowUnresolvedNodes) {}
38 
39 void DIBuilder::trackIfUnresolved(MDNode *N) {
40   if (!N)
41     return;
42   if (N->isResolved())
43     return;
44 
45   assert(AllowUnresolvedNodes && "Cannot handle unresolved nodes");
46   UnresolvedNodes.emplace_back(N);
47 }
48 
49 void DIBuilder::finalizeSubprogram(DISubprogram *SP) {
50   MDTuple *Temp = SP->getRetainedNodes().get();
51   if (!Temp || !Temp->isTemporary())
52     return;
53 
54   SmallVector<Metadata *, 16> RetainedNodes;
55 
56   auto PV = PreservedVariables.find(SP);
57   if (PV != PreservedVariables.end())
58     RetainedNodes.append(PV->second.begin(), PV->second.end());
59 
60   auto PL = PreservedLabels.find(SP);
61   if (PL != PreservedLabels.end())
62     RetainedNodes.append(PL->second.begin(), PL->second.end());
63 
64   DINodeArray Node = getOrCreateArray(RetainedNodes);
65 
66   TempMDTuple(Temp)->replaceAllUsesWith(Node.get());
67 }
68 
69 void DIBuilder::finalize() {
70   if (!CUNode) {
71     assert(!AllowUnresolvedNodes &&
72            "creating type nodes without a CU is not supported");
73     return;
74   }
75 
76   CUNode->replaceEnumTypes(MDTuple::get(VMContext, AllEnumTypes));
77 
78   SmallVector<Metadata *, 16> RetainValues;
79   // Declarations and definitions of the same type may be retained. Some
80   // clients RAUW these pairs, leaving duplicates in the retained types
81   // list. Use a set to remove the duplicates while we transform the
82   // TrackingVHs back into Values.
83   SmallPtrSet<Metadata *, 16> RetainSet;
84   for (unsigned I = 0, E = AllRetainTypes.size(); I < E; I++)
85     if (RetainSet.insert(AllRetainTypes[I]).second)
86       RetainValues.push_back(AllRetainTypes[I]);
87 
88   if (!RetainValues.empty())
89     CUNode->replaceRetainedTypes(MDTuple::get(VMContext, RetainValues));
90 
91   DISubprogramArray SPs = MDTuple::get(VMContext, AllSubprograms);
92   for (auto *SP : SPs)
93     finalizeSubprogram(SP);
94   for (auto *N : RetainValues)
95     if (auto *SP = dyn_cast<DISubprogram>(N))
96       finalizeSubprogram(SP);
97 
98   if (!AllGVs.empty())
99     CUNode->replaceGlobalVariables(MDTuple::get(VMContext, AllGVs));
100 
101   if (!AllImportedModules.empty())
102     CUNode->replaceImportedEntities(MDTuple::get(
103         VMContext, SmallVector<Metadata *, 16>(AllImportedModules.begin(),
104                                                AllImportedModules.end())));
105 
106   for (const auto &I : AllMacrosPerParent) {
107     // DIMacroNode's with nullptr parent are DICompileUnit direct children.
108     if (!I.first) {
109       CUNode->replaceMacros(MDTuple::get(VMContext, I.second.getArrayRef()));
110       continue;
111     }
112     // Otherwise, it must be a temporary DIMacroFile that need to be resolved.
113     auto *TMF = cast<DIMacroFile>(I.first);
114     auto *MF = DIMacroFile::get(VMContext, dwarf::DW_MACINFO_start_file,
115                                 TMF->getLine(), TMF->getFile(),
116                                 getOrCreateMacroArray(I.second.getArrayRef()));
117     replaceTemporary(llvm::TempDIMacroNode(TMF), MF);
118   }
119 
120   // Now that all temp nodes have been replaced or deleted, resolve remaining
121   // cycles.
122   for (const auto &N : UnresolvedNodes)
123     if (N && !N->isResolved())
124       N->resolveCycles();
125   UnresolvedNodes.clear();
126 
127   // Can't handle unresolved nodes anymore.
128   AllowUnresolvedNodes = false;
129 }
130 
131 /// If N is compile unit return NULL otherwise return N.
132 static DIScope *getNonCompileUnitScope(DIScope *N) {
133   if (!N || isa<DICompileUnit>(N))
134     return nullptr;
135   return cast<DIScope>(N);
136 }
137 
138 DICompileUnit *DIBuilder::createCompileUnit(
139     unsigned Lang, DIFile *File, StringRef Producer, bool isOptimized,
140     StringRef Flags, unsigned RunTimeVer, StringRef SplitName,
141     DICompileUnit::DebugEmissionKind Kind, uint64_t DWOId,
142     bool SplitDebugInlining, bool DebugInfoForProfiling, bool GnuPubnames) {
143 
144   assert(((Lang <= dwarf::DW_LANG_Fortran08 && Lang >= dwarf::DW_LANG_C89) ||
145           (Lang <= dwarf::DW_LANG_hi_user && Lang >= dwarf::DW_LANG_lo_user)) &&
146          "Invalid Language tag");
147 
148   assert(!CUNode && "Can only make one compile unit per DIBuilder instance");
149   CUNode = DICompileUnit::getDistinct(
150       VMContext, Lang, File, Producer, isOptimized, Flags, RunTimeVer,
151       SplitName, Kind, nullptr, nullptr, nullptr, nullptr, nullptr, DWOId,
152       SplitDebugInlining, DebugInfoForProfiling, GnuPubnames);
153 
154   // Create a named metadata so that it is easier to find cu in a module.
155   NamedMDNode *NMD = M.getOrInsertNamedMetadata("llvm.dbg.cu");
156   NMD->addOperand(CUNode);
157   trackIfUnresolved(CUNode);
158   return CUNode;
159 }
160 
161 static DIImportedEntity *
162 createImportedModule(LLVMContext &C, dwarf::Tag Tag, DIScope *Context,
163                      Metadata *NS, DIFile *File, unsigned Line, StringRef Name,
164                      SmallVectorImpl<TrackingMDNodeRef> &AllImportedModules) {
165   if (Line)
166     assert(File && "Source location has line number but no file");
167   unsigned EntitiesCount = C.pImpl->DIImportedEntitys.size();
168   auto *M =
169       DIImportedEntity::get(C, Tag, Context, DINodeRef(NS), File, Line, Name);
170   if (EntitiesCount < C.pImpl->DIImportedEntitys.size())
171     // A new Imported Entity was just added to the context.
172     // Add it to the Imported Modules list.
173     AllImportedModules.emplace_back(M);
174   return M;
175 }
176 
177 DIImportedEntity *DIBuilder::createImportedModule(DIScope *Context,
178                                                   DINamespace *NS, DIFile *File,
179                                                   unsigned Line) {
180   return ::createImportedModule(VMContext, dwarf::DW_TAG_imported_module,
181                                 Context, NS, File, Line, StringRef(),
182                                 AllImportedModules);
183 }
184 
185 DIImportedEntity *DIBuilder::createImportedModule(DIScope *Context,
186                                                   DIImportedEntity *NS,
187                                                   DIFile *File, unsigned Line) {
188   return ::createImportedModule(VMContext, dwarf::DW_TAG_imported_module,
189                                 Context, NS, File, Line, StringRef(),
190                                 AllImportedModules);
191 }
192 
193 DIImportedEntity *DIBuilder::createImportedModule(DIScope *Context, DIModule *M,
194                                                   DIFile *File, unsigned Line) {
195   return ::createImportedModule(VMContext, dwarf::DW_TAG_imported_module,
196                                 Context, M, File, Line, StringRef(),
197                                 AllImportedModules);
198 }
199 
200 DIImportedEntity *DIBuilder::createImportedDeclaration(DIScope *Context,
201                                                        DINode *Decl,
202                                                        DIFile *File,
203                                                        unsigned Line,
204                                                        StringRef Name) {
205   // Make sure to use the unique identifier based metadata reference for
206   // types that have one.
207   return ::createImportedModule(VMContext, dwarf::DW_TAG_imported_declaration,
208                                 Context, Decl, File, Line, Name,
209                                 AllImportedModules);
210 }
211 
212 DIFile *DIBuilder::createFile(StringRef Filename, StringRef Directory,
213                               Optional<DIFile::ChecksumInfo<StringRef>> CS,
214                               Optional<StringRef> Source) {
215   return DIFile::get(VMContext, Filename, Directory, CS, Source);
216 }
217 
218 DIMacro *DIBuilder::createMacro(DIMacroFile *Parent, unsigned LineNumber,
219                                 unsigned MacroType, StringRef Name,
220                                 StringRef Value) {
221   assert(!Name.empty() && "Unable to create macro without name");
222   assert((MacroType == dwarf::DW_MACINFO_undef ||
223           MacroType == dwarf::DW_MACINFO_define) &&
224          "Unexpected macro type");
225   auto *M = DIMacro::get(VMContext, MacroType, LineNumber, Name, Value);
226   AllMacrosPerParent[Parent].insert(M);
227   return M;
228 }
229 
230 DIMacroFile *DIBuilder::createTempMacroFile(DIMacroFile *Parent,
231                                             unsigned LineNumber, DIFile *File) {
232   auto *MF = DIMacroFile::getTemporary(VMContext, dwarf::DW_MACINFO_start_file,
233                                        LineNumber, File, DIMacroNodeArray())
234                  .release();
235   AllMacrosPerParent[Parent].insert(MF);
236   // Add the new temporary DIMacroFile to the macro per parent map as a parent.
237   // This is needed to assure DIMacroFile with no children to have an entry in
238   // the map. Otherwise, it will not be resolved in DIBuilder::finalize().
239   AllMacrosPerParent.insert({MF, {}});
240   return MF;
241 }
242 
243 DIEnumerator *DIBuilder::createEnumerator(StringRef Name, int64_t Val,
244                                           bool IsUnsigned) {
245   assert(!Name.empty() && "Unable to create enumerator without name");
246   return DIEnumerator::get(VMContext, Val, IsUnsigned, Name);
247 }
248 
249 DIBasicType *DIBuilder::createUnspecifiedType(StringRef Name) {
250   assert(!Name.empty() && "Unable to create type without name");
251   return DIBasicType::get(VMContext, dwarf::DW_TAG_unspecified_type, Name);
252 }
253 
254 DIBasicType *DIBuilder::createNullPtrType() {
255   return createUnspecifiedType("decltype(nullptr)");
256 }
257 
258 DIBasicType *DIBuilder::createBasicType(StringRef Name, uint64_t SizeInBits,
259                                         unsigned Encoding) {
260   assert(!Name.empty() && "Unable to create type without name");
261   return DIBasicType::get(VMContext, dwarf::DW_TAG_base_type, Name, SizeInBits,
262                           0, Encoding);
263 }
264 
265 DIDerivedType *DIBuilder::createQualifiedType(unsigned Tag, DIType *FromTy) {
266   return DIDerivedType::get(VMContext, Tag, "", nullptr, 0, nullptr, FromTy, 0,
267                             0, 0, None, DINode::FlagZero);
268 }
269 
270 DIDerivedType *DIBuilder::createPointerType(
271     DIType *PointeeTy,
272     uint64_t SizeInBits,
273     uint32_t AlignInBits,
274     Optional<unsigned> DWARFAddressSpace,
275     StringRef Name) {
276   // FIXME: Why is there a name here?
277   return DIDerivedType::get(VMContext, dwarf::DW_TAG_pointer_type, Name,
278                             nullptr, 0, nullptr, PointeeTy, SizeInBits,
279                             AlignInBits, 0, DWARFAddressSpace,
280                             DINode::FlagZero);
281 }
282 
283 DIDerivedType *DIBuilder::createMemberPointerType(DIType *PointeeTy,
284                                                   DIType *Base,
285                                                   uint64_t SizeInBits,
286                                                   uint32_t AlignInBits,
287                                                   DINode::DIFlags Flags) {
288   return DIDerivedType::get(VMContext, dwarf::DW_TAG_ptr_to_member_type, "",
289                             nullptr, 0, nullptr, PointeeTy, SizeInBits,
290                             AlignInBits, 0, None, Flags, Base);
291 }
292 
293 DIDerivedType *DIBuilder::createReferenceType(
294     unsigned Tag, DIType *RTy,
295     uint64_t SizeInBits,
296     uint32_t AlignInBits,
297     Optional<unsigned> DWARFAddressSpace) {
298   assert(RTy && "Unable to create reference type");
299   return DIDerivedType::get(VMContext, Tag, "", nullptr, 0, nullptr, RTy,
300                             SizeInBits, AlignInBits, 0, DWARFAddressSpace,
301                             DINode::FlagZero);
302 }
303 
304 DIDerivedType *DIBuilder::createTypedef(DIType *Ty, StringRef Name,
305                                         DIFile *File, unsigned LineNo,
306                                         DIScope *Context) {
307   return DIDerivedType::get(VMContext, dwarf::DW_TAG_typedef, Name, File,
308                             LineNo, getNonCompileUnitScope(Context), Ty, 0, 0,
309                             0, None, DINode::FlagZero);
310 }
311 
312 DIDerivedType *DIBuilder::createFriend(DIType *Ty, DIType *FriendTy) {
313   assert(Ty && "Invalid type!");
314   assert(FriendTy && "Invalid friend type!");
315   return DIDerivedType::get(VMContext, dwarf::DW_TAG_friend, "", nullptr, 0, Ty,
316                             FriendTy, 0, 0, 0, None, DINode::FlagZero);
317 }
318 
319 DIDerivedType *DIBuilder::createInheritance(DIType *Ty, DIType *BaseTy,
320                                             uint64_t BaseOffset,
321                                             DINode::DIFlags Flags) {
322   assert(Ty && "Unable to create inheritance");
323   return DIDerivedType::get(VMContext, dwarf::DW_TAG_inheritance, "", nullptr,
324                             0, Ty, BaseTy, 0, 0, BaseOffset, None, Flags);
325 }
326 
327 DIDerivedType *DIBuilder::createMemberType(DIScope *Scope, StringRef Name,
328                                            DIFile *File, unsigned LineNumber,
329                                            uint64_t SizeInBits,
330                                            uint32_t AlignInBits,
331                                            uint64_t OffsetInBits,
332                                            DINode::DIFlags Flags, DIType *Ty) {
333   return DIDerivedType::get(VMContext, dwarf::DW_TAG_member, Name, File,
334                             LineNumber, getNonCompileUnitScope(Scope), Ty,
335                             SizeInBits, AlignInBits, OffsetInBits, None, Flags);
336 }
337 
338 static ConstantAsMetadata *getConstantOrNull(Constant *C) {
339   if (C)
340     return ConstantAsMetadata::get(C);
341   return nullptr;
342 }
343 
344 DIDerivedType *DIBuilder::createVariantMemberType(DIScope *Scope, StringRef Name,
345 						  DIFile *File, unsigned LineNumber,
346 						  uint64_t SizeInBits,
347 						  uint32_t AlignInBits,
348 						  uint64_t OffsetInBits,
349 						  Constant *Discriminant,
350 						  DINode::DIFlags Flags, DIType *Ty) {
351   return DIDerivedType::get(VMContext, dwarf::DW_TAG_member, Name, File,
352                             LineNumber, getNonCompileUnitScope(Scope), Ty,
353                             SizeInBits, AlignInBits, OffsetInBits, None, Flags,
354                             getConstantOrNull(Discriminant));
355 }
356 
357 DIDerivedType *DIBuilder::createBitFieldMemberType(
358     DIScope *Scope, StringRef Name, DIFile *File, unsigned LineNumber,
359     uint64_t SizeInBits, uint64_t OffsetInBits, uint64_t StorageOffsetInBits,
360     DINode::DIFlags Flags, DIType *Ty) {
361   Flags |= DINode::FlagBitField;
362   return DIDerivedType::get(
363       VMContext, dwarf::DW_TAG_member, Name, File, LineNumber,
364       getNonCompileUnitScope(Scope), Ty, SizeInBits, /* AlignInBits */ 0,
365       OffsetInBits, None, Flags,
366       ConstantAsMetadata::get(ConstantInt::get(IntegerType::get(VMContext, 64),
367                                                StorageOffsetInBits)));
368 }
369 
370 DIDerivedType *
371 DIBuilder::createStaticMemberType(DIScope *Scope, StringRef Name, DIFile *File,
372                                   unsigned LineNumber, DIType *Ty,
373                                   DINode::DIFlags Flags, llvm::Constant *Val,
374                                   uint32_t AlignInBits) {
375   Flags |= DINode::FlagStaticMember;
376   return DIDerivedType::get(VMContext, dwarf::DW_TAG_member, Name, File,
377                             LineNumber, getNonCompileUnitScope(Scope), Ty, 0,
378                             AlignInBits, 0, None, Flags,
379                             getConstantOrNull(Val));
380 }
381 
382 DIDerivedType *
383 DIBuilder::createObjCIVar(StringRef Name, DIFile *File, unsigned LineNumber,
384                           uint64_t SizeInBits, uint32_t AlignInBits,
385                           uint64_t OffsetInBits, DINode::DIFlags Flags,
386                           DIType *Ty, MDNode *PropertyNode) {
387   return DIDerivedType::get(VMContext, dwarf::DW_TAG_member, Name, File,
388                             LineNumber, getNonCompileUnitScope(File), Ty,
389                             SizeInBits, AlignInBits, OffsetInBits, None, Flags,
390                             PropertyNode);
391 }
392 
393 DIObjCProperty *
394 DIBuilder::createObjCProperty(StringRef Name, DIFile *File, unsigned LineNumber,
395                               StringRef GetterName, StringRef SetterName,
396                               unsigned PropertyAttributes, DIType *Ty) {
397   return DIObjCProperty::get(VMContext, Name, File, LineNumber, GetterName,
398                              SetterName, PropertyAttributes, Ty);
399 }
400 
401 DITemplateTypeParameter *
402 DIBuilder::createTemplateTypeParameter(DIScope *Context, StringRef Name,
403                                        DIType *Ty) {
404   assert((!Context || isa<DICompileUnit>(Context)) && "Expected compile unit");
405   return DITemplateTypeParameter::get(VMContext, Name, Ty);
406 }
407 
408 static DITemplateValueParameter *
409 createTemplateValueParameterHelper(LLVMContext &VMContext, unsigned Tag,
410                                    DIScope *Context, StringRef Name, DIType *Ty,
411                                    Metadata *MD) {
412   assert((!Context || isa<DICompileUnit>(Context)) && "Expected compile unit");
413   return DITemplateValueParameter::get(VMContext, Tag, Name, Ty, MD);
414 }
415 
416 DITemplateValueParameter *
417 DIBuilder::createTemplateValueParameter(DIScope *Context, StringRef Name,
418                                         DIType *Ty, Constant *Val) {
419   return createTemplateValueParameterHelper(
420       VMContext, dwarf::DW_TAG_template_value_parameter, Context, Name, Ty,
421       getConstantOrNull(Val));
422 }
423 
424 DITemplateValueParameter *
425 DIBuilder::createTemplateTemplateParameter(DIScope *Context, StringRef Name,
426                                            DIType *Ty, StringRef Val) {
427   return createTemplateValueParameterHelper(
428       VMContext, dwarf::DW_TAG_GNU_template_template_param, Context, Name, Ty,
429       MDString::get(VMContext, Val));
430 }
431 
432 DITemplateValueParameter *
433 DIBuilder::createTemplateParameterPack(DIScope *Context, StringRef Name,
434                                        DIType *Ty, DINodeArray Val) {
435   return createTemplateValueParameterHelper(
436       VMContext, dwarf::DW_TAG_GNU_template_parameter_pack, Context, Name, Ty,
437       Val.get());
438 }
439 
440 DICompositeType *DIBuilder::createClassType(
441     DIScope *Context, StringRef Name, DIFile *File, unsigned LineNumber,
442     uint64_t SizeInBits, uint32_t AlignInBits, uint64_t OffsetInBits,
443     DINode::DIFlags Flags, DIType *DerivedFrom, DINodeArray Elements,
444     DIType *VTableHolder, MDNode *TemplateParams, StringRef UniqueIdentifier) {
445   assert((!Context || isa<DIScope>(Context)) &&
446          "createClassType should be called with a valid Context");
447 
448   auto *R = DICompositeType::get(
449       VMContext, dwarf::DW_TAG_structure_type, Name, File, LineNumber,
450       getNonCompileUnitScope(Context), DerivedFrom, SizeInBits, AlignInBits,
451       OffsetInBits, Flags, Elements, 0, VTableHolder,
452       cast_or_null<MDTuple>(TemplateParams), UniqueIdentifier);
453   trackIfUnresolved(R);
454   return R;
455 }
456 
457 DICompositeType *DIBuilder::createStructType(
458     DIScope *Context, StringRef Name, DIFile *File, unsigned LineNumber,
459     uint64_t SizeInBits, uint32_t AlignInBits, DINode::DIFlags Flags,
460     DIType *DerivedFrom, DINodeArray Elements, unsigned RunTimeLang,
461     DIType *VTableHolder, StringRef UniqueIdentifier) {
462   auto *R = DICompositeType::get(
463       VMContext, dwarf::DW_TAG_structure_type, Name, File, LineNumber,
464       getNonCompileUnitScope(Context), DerivedFrom, SizeInBits, AlignInBits, 0,
465       Flags, Elements, RunTimeLang, VTableHolder, nullptr, UniqueIdentifier);
466   trackIfUnresolved(R);
467   return R;
468 }
469 
470 DICompositeType *DIBuilder::createUnionType(
471     DIScope *Scope, StringRef Name, DIFile *File, unsigned LineNumber,
472     uint64_t SizeInBits, uint32_t AlignInBits, DINode::DIFlags Flags,
473     DINodeArray Elements, unsigned RunTimeLang, StringRef UniqueIdentifier) {
474   auto *R = DICompositeType::get(
475       VMContext, dwarf::DW_TAG_union_type, Name, File, LineNumber,
476       getNonCompileUnitScope(Scope), nullptr, SizeInBits, AlignInBits, 0, Flags,
477       Elements, RunTimeLang, nullptr, nullptr, UniqueIdentifier);
478   trackIfUnresolved(R);
479   return R;
480 }
481 
482 DICompositeType *DIBuilder::createVariantPart(
483     DIScope *Scope, StringRef Name, DIFile *File, unsigned LineNumber,
484     uint64_t SizeInBits, uint32_t AlignInBits, DINode::DIFlags Flags,
485     DIDerivedType *Discriminator, DINodeArray Elements, StringRef UniqueIdentifier) {
486   auto *R = DICompositeType::get(
487       VMContext, dwarf::DW_TAG_variant_part, Name, File, LineNumber,
488       getNonCompileUnitScope(Scope), nullptr, SizeInBits, AlignInBits, 0, Flags,
489       Elements, 0, nullptr, nullptr, UniqueIdentifier, Discriminator);
490   trackIfUnresolved(R);
491   return R;
492 }
493 
494 DISubroutineType *DIBuilder::createSubroutineType(DITypeRefArray ParameterTypes,
495                                                   DINode::DIFlags Flags,
496                                                   unsigned CC) {
497   return DISubroutineType::get(VMContext, Flags, CC, ParameterTypes);
498 }
499 
500 DICompositeType *DIBuilder::createEnumerationType(
501     DIScope *Scope, StringRef Name, DIFile *File, unsigned LineNumber,
502     uint64_t SizeInBits, uint32_t AlignInBits, DINodeArray Elements,
503     DIType *UnderlyingType, StringRef UniqueIdentifier, bool IsFixed) {
504   auto *CTy = DICompositeType::get(
505       VMContext, dwarf::DW_TAG_enumeration_type, Name, File, LineNumber,
506       getNonCompileUnitScope(Scope), UnderlyingType, SizeInBits, AlignInBits, 0,
507       IsFixed ? DINode::FlagFixedEnum : DINode::FlagZero, Elements, 0, nullptr,
508       nullptr, UniqueIdentifier);
509   AllEnumTypes.push_back(CTy);
510   trackIfUnresolved(CTy);
511   return CTy;
512 }
513 
514 DICompositeType *DIBuilder::createArrayType(uint64_t Size,
515                                             uint32_t AlignInBits, DIType *Ty,
516                                             DINodeArray Subscripts) {
517   auto *R = DICompositeType::get(VMContext, dwarf::DW_TAG_array_type, "",
518                                  nullptr, 0, nullptr, Ty, Size, AlignInBits, 0,
519                                  DINode::FlagZero, Subscripts, 0, nullptr);
520   trackIfUnresolved(R);
521   return R;
522 }
523 
524 DICompositeType *DIBuilder::createVectorType(uint64_t Size,
525                                              uint32_t AlignInBits, DIType *Ty,
526                                              DINodeArray Subscripts) {
527   auto *R = DICompositeType::get(VMContext, dwarf::DW_TAG_array_type, "",
528                                  nullptr, 0, nullptr, Ty, Size, AlignInBits, 0,
529                                  DINode::FlagVector, Subscripts, 0, nullptr);
530   trackIfUnresolved(R);
531   return R;
532 }
533 
534 static DIType *createTypeWithFlags(LLVMContext &Context, DIType *Ty,
535                                    DINode::DIFlags FlagsToSet) {
536   auto NewTy = Ty->clone();
537   NewTy->setFlags(NewTy->getFlags() | FlagsToSet);
538   return MDNode::replaceWithUniqued(std::move(NewTy));
539 }
540 
541 DIType *DIBuilder::createArtificialType(DIType *Ty) {
542   // FIXME: Restrict this to the nodes where it's valid.
543   if (Ty->isArtificial())
544     return Ty;
545   return createTypeWithFlags(VMContext, Ty, DINode::FlagArtificial);
546 }
547 
548 DIType *DIBuilder::createObjectPointerType(DIType *Ty) {
549   // FIXME: Restrict this to the nodes where it's valid.
550   if (Ty->isObjectPointer())
551     return Ty;
552   DINode::DIFlags Flags = DINode::FlagObjectPointer | DINode::FlagArtificial;
553   return createTypeWithFlags(VMContext, Ty, Flags);
554 }
555 
556 void DIBuilder::retainType(DIScope *T) {
557   assert(T && "Expected non-null type");
558   assert((isa<DIType>(T) || (isa<DISubprogram>(T) &&
559                              cast<DISubprogram>(T)->isDefinition() == false)) &&
560          "Expected type or subprogram declaration");
561   AllRetainTypes.emplace_back(T);
562 }
563 
564 DIBasicType *DIBuilder::createUnspecifiedParameter() { return nullptr; }
565 
566 DICompositeType *
567 DIBuilder::createForwardDecl(unsigned Tag, StringRef Name, DIScope *Scope,
568                              DIFile *F, unsigned Line, unsigned RuntimeLang,
569                              uint64_t SizeInBits, uint32_t AlignInBits,
570                              StringRef UniqueIdentifier) {
571   // FIXME: Define in terms of createReplaceableForwardDecl() by calling
572   // replaceWithUniqued().
573   auto *RetTy = DICompositeType::get(
574       VMContext, Tag, Name, F, Line, getNonCompileUnitScope(Scope), nullptr,
575       SizeInBits, AlignInBits, 0, DINode::FlagFwdDecl, nullptr, RuntimeLang,
576       nullptr, nullptr, UniqueIdentifier);
577   trackIfUnresolved(RetTy);
578   return RetTy;
579 }
580 
581 DICompositeType *DIBuilder::createReplaceableCompositeType(
582     unsigned Tag, StringRef Name, DIScope *Scope, DIFile *F, unsigned Line,
583     unsigned RuntimeLang, uint64_t SizeInBits, uint32_t AlignInBits,
584     DINode::DIFlags Flags, StringRef UniqueIdentifier) {
585   auto *RetTy =
586       DICompositeType::getTemporary(
587           VMContext, Tag, Name, F, Line, getNonCompileUnitScope(Scope), nullptr,
588           SizeInBits, AlignInBits, 0, Flags, nullptr, RuntimeLang, nullptr,
589           nullptr, UniqueIdentifier)
590           .release();
591   trackIfUnresolved(RetTy);
592   return RetTy;
593 }
594 
595 DINodeArray DIBuilder::getOrCreateArray(ArrayRef<Metadata *> Elements) {
596   return MDTuple::get(VMContext, Elements);
597 }
598 
599 DIMacroNodeArray
600 DIBuilder::getOrCreateMacroArray(ArrayRef<Metadata *> Elements) {
601   return MDTuple::get(VMContext, Elements);
602 }
603 
604 DITypeRefArray DIBuilder::getOrCreateTypeArray(ArrayRef<Metadata *> Elements) {
605   SmallVector<llvm::Metadata *, 16> Elts;
606   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
607     if (Elements[i] && isa<MDNode>(Elements[i]))
608       Elts.push_back(cast<DIType>(Elements[i]));
609     else
610       Elts.push_back(Elements[i]);
611   }
612   return DITypeRefArray(MDNode::get(VMContext, Elts));
613 }
614 
615 DISubrange *DIBuilder::getOrCreateSubrange(int64_t Lo, int64_t Count) {
616   return DISubrange::get(VMContext, Count, Lo);
617 }
618 
619 DISubrange *DIBuilder::getOrCreateSubrange(int64_t Lo, Metadata *CountNode) {
620   return DISubrange::get(VMContext, CountNode, Lo);
621 }
622 
623 static void checkGlobalVariableScope(DIScope *Context) {
624 #ifndef NDEBUG
625   if (auto *CT =
626           dyn_cast_or_null<DICompositeType>(getNonCompileUnitScope(Context)))
627     assert(CT->getIdentifier().empty() &&
628            "Context of a global variable should not be a type with identifier");
629 #endif
630 }
631 
632 DIGlobalVariableExpression *DIBuilder::createGlobalVariableExpression(
633     DIScope *Context, StringRef Name, StringRef LinkageName, DIFile *F,
634     unsigned LineNumber, DIType *Ty, bool isLocalToUnit, DIExpression *Expr,
635     MDNode *Decl, uint32_t AlignInBits) {
636   checkGlobalVariableScope(Context);
637 
638   auto *GV = DIGlobalVariable::getDistinct(
639       VMContext, cast_or_null<DIScope>(Context), Name, LinkageName, F,
640       LineNumber, Ty, isLocalToUnit, true, cast_or_null<DIDerivedType>(Decl),
641       AlignInBits);
642   if (!Expr)
643     Expr = createExpression();
644   auto *N = DIGlobalVariableExpression::get(VMContext, GV, Expr);
645   AllGVs.push_back(N);
646   return N;
647 }
648 
649 DIGlobalVariable *DIBuilder::createTempGlobalVariableFwdDecl(
650     DIScope *Context, StringRef Name, StringRef LinkageName, DIFile *F,
651     unsigned LineNumber, DIType *Ty, bool isLocalToUnit, MDNode *Decl,
652     uint32_t AlignInBits) {
653   checkGlobalVariableScope(Context);
654 
655   return DIGlobalVariable::getTemporary(
656              VMContext, cast_or_null<DIScope>(Context), Name, LinkageName, F,
657              LineNumber, Ty, isLocalToUnit, false,
658              cast_or_null<DIDerivedType>(Decl), AlignInBits)
659       .release();
660 }
661 
662 static DILocalVariable *createLocalVariable(
663     LLVMContext &VMContext,
664     DenseMap<MDNode *, SmallVector<TrackingMDNodeRef, 1>> &PreservedVariables,
665     DIScope *Scope, StringRef Name, unsigned ArgNo, DIFile *File,
666     unsigned LineNo, DIType *Ty, bool AlwaysPreserve, DINode::DIFlags Flags,
667     uint32_t AlignInBits) {
668   // FIXME: Why getNonCompileUnitScope()?
669   // FIXME: Why is "!Context" okay here?
670   // FIXME: Why doesn't this check for a subprogram or lexical block (AFAICT
671   // the only valid scopes)?
672   DIScope *Context = getNonCompileUnitScope(Scope);
673 
674   auto *Node =
675       DILocalVariable::get(VMContext, cast_or_null<DILocalScope>(Context), Name,
676                            File, LineNo, Ty, ArgNo, Flags, AlignInBits);
677   if (AlwaysPreserve) {
678     // The optimizer may remove local variables. If there is an interest
679     // to preserve variable info in such situation then stash it in a
680     // named mdnode.
681     DISubprogram *Fn = getDISubprogram(Scope);
682     assert(Fn && "Missing subprogram for local variable");
683     PreservedVariables[Fn].emplace_back(Node);
684   }
685   return Node;
686 }
687 
688 DILocalVariable *DIBuilder::createAutoVariable(DIScope *Scope, StringRef Name,
689                                                DIFile *File, unsigned LineNo,
690                                                DIType *Ty, bool AlwaysPreserve,
691                                                DINode::DIFlags Flags,
692                                                uint32_t AlignInBits) {
693   return createLocalVariable(VMContext, PreservedVariables, Scope, Name,
694                              /* ArgNo */ 0, File, LineNo, Ty, AlwaysPreserve,
695                              Flags, AlignInBits);
696 }
697 
698 DILocalVariable *DIBuilder::createParameterVariable(
699     DIScope *Scope, StringRef Name, unsigned ArgNo, DIFile *File,
700     unsigned LineNo, DIType *Ty, bool AlwaysPreserve, DINode::DIFlags Flags) {
701   assert(ArgNo && "Expected non-zero argument number for parameter");
702   return createLocalVariable(VMContext, PreservedVariables, Scope, Name, ArgNo,
703                              File, LineNo, Ty, AlwaysPreserve, Flags,
704                              /* AlignInBits */0);
705 }
706 
707 DILabel *DIBuilder::createLabel(
708     DIScope *Scope, StringRef Name, DIFile *File,
709     unsigned LineNo, bool AlwaysPreserve) {
710   DIScope *Context = getNonCompileUnitScope(Scope);
711 
712   auto *Node =
713       DILabel::get(VMContext, cast_or_null<DILocalScope>(Context), Name,
714                    File, LineNo);
715 
716   if (AlwaysPreserve) {
717     /// The optimizer may remove labels. If there is an interest
718     /// to preserve label info in such situation then append it to
719     /// the list of retained nodes of the DISubprogram.
720     DISubprogram *Fn = getDISubprogram(Scope);
721     assert(Fn && "Missing subprogram for label");
722     PreservedLabels[Fn].emplace_back(Node);
723   }
724   return Node;
725 }
726 
727 DIExpression *DIBuilder::createExpression(ArrayRef<uint64_t> Addr) {
728   return DIExpression::get(VMContext, Addr);
729 }
730 
731 DIExpression *DIBuilder::createExpression(ArrayRef<int64_t> Signed) {
732   // TODO: Remove the callers of this signed version and delete.
733   SmallVector<uint64_t, 8> Addr(Signed.begin(), Signed.end());
734   return createExpression(Addr);
735 }
736 
737 template <class... Ts>
738 static DISubprogram *getSubprogram(bool IsDistinct, Ts &&... Args) {
739   if (IsDistinct)
740     return DISubprogram::getDistinct(std::forward<Ts>(Args)...);
741   return DISubprogram::get(std::forward<Ts>(Args)...);
742 }
743 
744 DISubprogram *DIBuilder::createFunction(
745     DIScope *Context, StringRef Name, StringRef LinkageName, DIFile *File,
746     unsigned LineNo, DISubroutineType *Ty, bool isLocalToUnit,
747     bool isDefinition, unsigned ScopeLine, DINode::DIFlags Flags,
748     bool isOptimized, DITemplateParameterArray TParams, DISubprogram *Decl,
749     DITypeArray ThrownTypes) {
750   auto *Node = getSubprogram(
751       /* IsDistinct = */ isDefinition, VMContext,
752       getNonCompileUnitScope(Context), Name, LinkageName, File, LineNo, Ty,
753       isLocalToUnit, isDefinition, ScopeLine, nullptr, 0, 0, 0, Flags,
754       isOptimized, isDefinition ? CUNode : nullptr, TParams, Decl,
755       MDTuple::getTemporary(VMContext, None).release(), ThrownTypes);
756 
757   if (isDefinition)
758     AllSubprograms.push_back(Node);
759   trackIfUnresolved(Node);
760   return Node;
761 }
762 
763 DISubprogram *DIBuilder::createTempFunctionFwdDecl(
764     DIScope *Context, StringRef Name, StringRef LinkageName, DIFile *File,
765     unsigned LineNo, DISubroutineType *Ty, bool isLocalToUnit,
766     bool isDefinition, unsigned ScopeLine, DINode::DIFlags Flags,
767     bool isOptimized, DITemplateParameterArray TParams, DISubprogram *Decl,
768     DITypeArray ThrownTypes) {
769   return DISubprogram::getTemporary(
770              VMContext, getNonCompileUnitScope(Context), Name, LinkageName,
771              File, LineNo, Ty, isLocalToUnit, isDefinition, ScopeLine, nullptr,
772              0, 0, 0, Flags, isOptimized, isDefinition ? CUNode : nullptr,
773              TParams, Decl, nullptr, ThrownTypes)
774       .release();
775 }
776 
777 DISubprogram *DIBuilder::createMethod(
778     DIScope *Context, StringRef Name, StringRef LinkageName, DIFile *F,
779     unsigned LineNo, DISubroutineType *Ty, bool isLocalToUnit,
780     bool isDefinition, unsigned VK, unsigned VIndex, int ThisAdjustment,
781     DIType *VTableHolder, DINode::DIFlags Flags, bool isOptimized,
782     DITemplateParameterArray TParams, DITypeArray ThrownTypes) {
783   assert(getNonCompileUnitScope(Context) &&
784          "Methods should have both a Context and a context that isn't "
785          "the compile unit.");
786   // FIXME: Do we want to use different scope/lines?
787   auto *SP = getSubprogram(
788       /* IsDistinct = */ isDefinition, VMContext, cast<DIScope>(Context), Name,
789       LinkageName, F, LineNo, Ty, isLocalToUnit, isDefinition, LineNo,
790       VTableHolder, VK, VIndex, ThisAdjustment, Flags, isOptimized,
791       isDefinition ? CUNode : nullptr, TParams, nullptr, nullptr, ThrownTypes);
792 
793   if (isDefinition)
794     AllSubprograms.push_back(SP);
795   trackIfUnresolved(SP);
796   return SP;
797 }
798 
799 DINamespace *DIBuilder::createNameSpace(DIScope *Scope, StringRef Name,
800                                         bool ExportSymbols) {
801 
802   // It is okay to *not* make anonymous top-level namespaces distinct, because
803   // all nodes that have an anonymous namespace as their parent scope are
804   // guaranteed to be unique and/or are linked to their containing
805   // DICompileUnit. This decision is an explicit tradeoff of link time versus
806   // memory usage versus code simplicity and may get revisited in the future.
807   return DINamespace::get(VMContext, getNonCompileUnitScope(Scope), Name,
808                           ExportSymbols);
809 }
810 
811 DIModule *DIBuilder::createModule(DIScope *Scope, StringRef Name,
812                                   StringRef ConfigurationMacros,
813                                   StringRef IncludePath,
814                                   StringRef ISysRoot) {
815  return DIModule::get(VMContext, getNonCompileUnitScope(Scope), Name,
816                       ConfigurationMacros, IncludePath, ISysRoot);
817 }
818 
819 DILexicalBlockFile *DIBuilder::createLexicalBlockFile(DIScope *Scope,
820                                                       DIFile *File,
821                                                       unsigned Discriminator) {
822   return DILexicalBlockFile::get(VMContext, Scope, File, Discriminator);
823 }
824 
825 DILexicalBlock *DIBuilder::createLexicalBlock(DIScope *Scope, DIFile *File,
826                                               unsigned Line, unsigned Col) {
827   // Make these distinct, to avoid merging two lexical blocks on the same
828   // file/line/column.
829   return DILexicalBlock::getDistinct(VMContext, getNonCompileUnitScope(Scope),
830                                      File, Line, Col);
831 }
832 
833 Instruction *DIBuilder::insertDeclare(Value *Storage, DILocalVariable *VarInfo,
834                                       DIExpression *Expr, const DILocation *DL,
835                                       Instruction *InsertBefore) {
836   return insertDeclare(Storage, VarInfo, Expr, DL, InsertBefore->getParent(),
837                        InsertBefore);
838 }
839 
840 Instruction *DIBuilder::insertDeclare(Value *Storage, DILocalVariable *VarInfo,
841                                       DIExpression *Expr, const DILocation *DL,
842                                       BasicBlock *InsertAtEnd) {
843   // If this block already has a terminator then insert this intrinsic before
844   // the terminator. Otherwise, put it at the end of the block.
845   Instruction *InsertBefore = InsertAtEnd->getTerminator();
846   return insertDeclare(Storage, VarInfo, Expr, DL, InsertAtEnd, InsertBefore);
847 }
848 
849 Instruction *DIBuilder::insertLabel(DILabel *LabelInfo, const DILocation *DL,
850                                     Instruction *InsertBefore) {
851   return insertLabel(
852       LabelInfo, DL, InsertBefore ? InsertBefore->getParent() : nullptr,
853       InsertBefore);
854 }
855 
856 Instruction *DIBuilder::insertLabel(DILabel *LabelInfo, const DILocation *DL,
857                                     BasicBlock *InsertAtEnd) {
858   return insertLabel(LabelInfo, DL, InsertAtEnd, nullptr);
859 }
860 
861 Instruction *DIBuilder::insertDbgValueIntrinsic(Value *V,
862                                                 DILocalVariable *VarInfo,
863                                                 DIExpression *Expr,
864                                                 const DILocation *DL,
865                                                 Instruction *InsertBefore) {
866   return insertDbgValueIntrinsic(
867       V, VarInfo, Expr, DL, InsertBefore ? InsertBefore->getParent() : nullptr,
868       InsertBefore);
869 }
870 
871 Instruction *DIBuilder::insertDbgValueIntrinsic(Value *V,
872                                                 DILocalVariable *VarInfo,
873                                                 DIExpression *Expr,
874                                                 const DILocation *DL,
875                                                 BasicBlock *InsertAtEnd) {
876   return insertDbgValueIntrinsic(V, VarInfo, Expr, DL, InsertAtEnd, nullptr);
877 }
878 
879 /// Return an IRBuilder for inserting dbg.declare and dbg.value intrinsics. This
880 /// abstracts over the various ways to specify an insert position.
881 static IRBuilder<> getIRBForDbgInsertion(const DILocation *DL,
882                                          BasicBlock *InsertBB,
883                                          Instruction *InsertBefore) {
884   IRBuilder<> B(DL->getContext());
885   if (InsertBefore)
886     B.SetInsertPoint(InsertBefore);
887   else if (InsertBB)
888     B.SetInsertPoint(InsertBB);
889   B.SetCurrentDebugLocation(DL);
890   return B;
891 }
892 
893 static Value *getDbgIntrinsicValueImpl(LLVMContext &VMContext, Value *V) {
894   assert(V && "no value passed to dbg intrinsic");
895   return MetadataAsValue::get(VMContext, ValueAsMetadata::get(V));
896 }
897 
898 static Function *getDeclareIntrin(Module &M) {
899   return Intrinsic::getDeclaration(&M, UseDbgAddr ? Intrinsic::dbg_addr
900                                                   : Intrinsic::dbg_declare);
901 }
902 
903 Instruction *DIBuilder::insertDeclare(Value *Storage, DILocalVariable *VarInfo,
904                                       DIExpression *Expr, const DILocation *DL,
905                                       BasicBlock *InsertBB, Instruction *InsertBefore) {
906   assert(VarInfo && "empty or invalid DILocalVariable* passed to dbg.declare");
907   assert(DL && "Expected debug loc");
908   assert(DL->getScope()->getSubprogram() ==
909              VarInfo->getScope()->getSubprogram() &&
910          "Expected matching subprograms");
911   if (!DeclareFn)
912     DeclareFn = getDeclareIntrin(M);
913 
914   trackIfUnresolved(VarInfo);
915   trackIfUnresolved(Expr);
916   Value *Args[] = {getDbgIntrinsicValueImpl(VMContext, Storage),
917                    MetadataAsValue::get(VMContext, VarInfo),
918                    MetadataAsValue::get(VMContext, Expr)};
919 
920   IRBuilder<> B = getIRBForDbgInsertion(DL, InsertBB, InsertBefore);
921   return B.CreateCall(DeclareFn, Args);
922 }
923 
924 Instruction *DIBuilder::insertDbgValueIntrinsic(
925     Value *V, DILocalVariable *VarInfo, DIExpression *Expr,
926     const DILocation *DL, BasicBlock *InsertBB, Instruction *InsertBefore) {
927   assert(V && "no value passed to dbg.value");
928   assert(VarInfo && "empty or invalid DILocalVariable* passed to dbg.value");
929   assert(DL && "Expected debug loc");
930   assert(DL->getScope()->getSubprogram() ==
931              VarInfo->getScope()->getSubprogram() &&
932          "Expected matching subprograms");
933   if (!ValueFn)
934     ValueFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_value);
935 
936   trackIfUnresolved(VarInfo);
937   trackIfUnresolved(Expr);
938   Value *Args[] = {getDbgIntrinsicValueImpl(VMContext, V),
939                    MetadataAsValue::get(VMContext, VarInfo),
940                    MetadataAsValue::get(VMContext, Expr)};
941 
942   IRBuilder<> B = getIRBForDbgInsertion(DL, InsertBB, InsertBefore);
943   return B.CreateCall(ValueFn, Args);
944 }
945 
946 Instruction *DIBuilder::insertLabel(
947     DILabel *LabelInfo, const DILocation *DL,
948     BasicBlock *InsertBB, Instruction *InsertBefore) {
949   assert(LabelInfo && "empty or invalid DILabel* passed to dbg.label");
950   assert(DL && "Expected debug loc");
951   assert(DL->getScope()->getSubprogram() ==
952              LabelInfo->getScope()->getSubprogram() &&
953          "Expected matching subprograms");
954   if (!LabelFn)
955     LabelFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_label);
956 
957   trackIfUnresolved(LabelInfo);
958   Value *Args[] = {MetadataAsValue::get(VMContext, LabelInfo)};
959 
960   IRBuilder<> B = getIRBForDbgInsertion(DL, InsertBB, InsertBefore);
961   return B.CreateCall(LabelFn, Args);
962 }
963 
964 void DIBuilder::replaceVTableHolder(DICompositeType *&T,
965                                     DIType *VTableHolder) {
966   {
967     TypedTrackingMDRef<DICompositeType> N(T);
968     N->replaceVTableHolder(VTableHolder);
969     T = N.get();
970   }
971 
972   // If this didn't create a self-reference, just return.
973   if (T != VTableHolder)
974     return;
975 
976   // Look for unresolved operands.  T will drop RAUW support, orphaning any
977   // cycles underneath it.
978   if (T->isResolved())
979     for (const MDOperand &O : T->operands())
980       if (auto *N = dyn_cast_or_null<MDNode>(O))
981         trackIfUnresolved(N);
982 }
983 
984 void DIBuilder::replaceArrays(DICompositeType *&T, DINodeArray Elements,
985                               DINodeArray TParams) {
986   {
987     TypedTrackingMDRef<DICompositeType> N(T);
988     if (Elements)
989       N->replaceElements(Elements);
990     if (TParams)
991       N->replaceTemplateParams(DITemplateParameterArray(TParams));
992     T = N.get();
993   }
994 
995   // If T isn't resolved, there's no problem.
996   if (!T->isResolved())
997     return;
998 
999   // If T is resolved, it may be due to a self-reference cycle.  Track the
1000   // arrays explicitly if they're unresolved, or else the cycles will be
1001   // orphaned.
1002   if (Elements)
1003     trackIfUnresolved(Elements.get());
1004   if (TParams)
1005     trackIfUnresolved(TParams.get());
1006 }
1007