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