IR: Split GenericMDNode into MDTuple and UniquableMDNode
[oota-llvm.git] / lib / IR / DIBuilder.cpp
1 //===--- DIBuilder.cpp - Debug Information Builder ------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the DIBuilder.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/IR/DIBuilder.h"
15 #include "llvm/ADT/STLExtras.h"
16 #include "llvm/IR/Constants.h"
17 #include "llvm/IR/DebugInfo.h"
18 #include "llvm/IR/IntrinsicInst.h"
19 #include "llvm/IR/Module.h"
20 #include "llvm/Support/Debug.h"
21 #include "llvm/Support/Dwarf.h"
22
23 using namespace llvm;
24 using namespace llvm::dwarf;
25
26 namespace {
27 class HeaderBuilder {
28   SmallVector<char, 256> Chars;
29
30 public:
31   explicit HeaderBuilder(Twine T) { T.toVector(Chars); }
32   HeaderBuilder(const HeaderBuilder &X) : Chars(X.Chars) {}
33   HeaderBuilder(HeaderBuilder &&X) : Chars(std::move(X.Chars)) {}
34
35   template <class Twineable> HeaderBuilder &concat(Twineable &&X) {
36     Chars.push_back(0);
37     Twine(X).toVector(Chars);
38     return *this;
39   }
40
41   MDString *get(LLVMContext &Context) const {
42     return MDString::get(Context, StringRef(Chars.begin(), Chars.size()));
43   }
44
45   static HeaderBuilder get(unsigned Tag) {
46     return HeaderBuilder("0x" + Twine::utohexstr(Tag));
47   }
48 };
49 }
50
51 DIBuilder::DIBuilder(Module &m, bool AllowUnresolvedNodes)
52     : M(m), VMContext(M.getContext()), TempEnumTypes(nullptr),
53       TempRetainTypes(nullptr), TempSubprograms(nullptr), TempGVs(nullptr),
54       DeclareFn(nullptr), ValueFn(nullptr),
55       AllowUnresolvedNodes(AllowUnresolvedNodes) {}
56
57 static bool isUnresolved(MDNode *N) {
58   return N &&
59          (isa<MDNodeFwdDecl>(N) || !cast<UniquableMDNode>(N)->isResolved());
60 }
61
62 void DIBuilder::trackIfUnresolved(MDNode *N) {
63   if (!AllowUnresolvedNodes) {
64     assert(!isUnresolved(N) && "Cannot handle unresolved nodes");
65     return;
66   }
67   if (isUnresolved(N))
68     UnresolvedNodes.emplace_back(N);
69   return;
70 }
71
72 void DIBuilder::finalize() {
73   DIArray Enums = getOrCreateArray(AllEnumTypes);
74   DIType(TempEnumTypes).replaceAllUsesWith(Enums);
75
76   SmallVector<Metadata *, 16> RetainValues;
77   // Declarations and definitions of the same type may be retained. Some
78   // clients RAUW these pairs, leaving duplicates in the retained types
79   // list. Use a set to remove the duplicates while we transform the
80   // TrackingVHs back into Values.
81   SmallPtrSet<Metadata *, 16> RetainSet;
82   for (unsigned I = 0, E = AllRetainTypes.size(); I < E; I++)
83     if (RetainSet.insert(AllRetainTypes[I]).second)
84       RetainValues.push_back(AllRetainTypes[I]);
85   DIArray RetainTypes = getOrCreateArray(RetainValues);
86   DIType(TempRetainTypes).replaceAllUsesWith(RetainTypes);
87
88   DIArray SPs = getOrCreateArray(AllSubprograms);
89   DIType(TempSubprograms).replaceAllUsesWith(SPs);
90   for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i) {
91     DISubprogram SP(SPs.getElement(i));
92     if (MDNode *Temp = SP.getVariablesNodes()) {
93       SmallVector<Metadata *, 4> Variables;
94       for (Metadata *V : PreservedVariables.lookup(SP))
95         Variables.push_back(V);
96       DIArray AV = getOrCreateArray(Variables);
97       DIType(Temp).replaceAllUsesWith(AV);
98     }
99   }
100
101   DIArray GVs = getOrCreateArray(AllGVs);
102   DIType(TempGVs).replaceAllUsesWith(GVs);
103
104   SmallVector<Metadata *, 16> RetainValuesI;
105   for (unsigned I = 0, E = AllImportedModules.size(); I < E; I++)
106     RetainValuesI.push_back(AllImportedModules[I]);
107   DIArray IMs = getOrCreateArray(RetainValuesI);
108   DIType(TempImportedModules).replaceAllUsesWith(IMs);
109
110   // Now that all temp nodes have been replaced or deleted, resolve remaining
111   // cycles.
112   for (const auto &N : UnresolvedNodes)
113     if (N)
114       cast<UniquableMDNode>(N)->resolveCycles();
115   UnresolvedNodes.clear();
116
117   // Can't handle unresolved nodes anymore.
118   AllowUnresolvedNodes = false;
119 }
120
121 /// If N is compile unit return NULL otherwise return N.
122 static MDNode *getNonCompileUnitScope(MDNode *N) {
123   if (DIDescriptor(N).isCompileUnit())
124     return nullptr;
125   return N;
126 }
127
128 static MDNode *createFilePathPair(LLVMContext &VMContext, StringRef Filename,
129                                   StringRef Directory) {
130   assert(!Filename.empty() && "Unable to create file without name");
131   Metadata *Pair[] = {MDString::get(VMContext, Filename),
132                       MDString::get(VMContext, Directory)};
133   return MDNode::get(VMContext, Pair);
134 }
135
136 DICompileUnit DIBuilder::createCompileUnit(unsigned Lang, StringRef Filename,
137                                            StringRef Directory,
138                                            StringRef Producer, bool isOptimized,
139                                            StringRef Flags, unsigned RunTimeVer,
140                                            StringRef SplitName,
141                                            DebugEmissionKind Kind,
142                                            bool EmitDebugInfo) {
143
144   assert(((Lang <= dwarf::DW_LANG_OCaml && Lang >= dwarf::DW_LANG_C89) ||
145           (Lang <= dwarf::DW_LANG_hi_user && Lang >= dwarf::DW_LANG_lo_user)) &&
146          "Invalid Language tag");
147   assert(!Filename.empty() &&
148          "Unable to create compile unit without filename");
149   Metadata *TElts[] = {HeaderBuilder::get(DW_TAG_base_type).get(VMContext)};
150   TempEnumTypes = MDNode::getTemporary(VMContext, TElts);
151
152   TempRetainTypes = MDNode::getTemporary(VMContext, TElts);
153
154   TempSubprograms = MDNode::getTemporary(VMContext, TElts);
155
156   TempGVs = MDNode::getTemporary(VMContext, TElts);
157
158   TempImportedModules = MDNode::getTemporary(VMContext, TElts);
159
160   Metadata *Elts[] = {HeaderBuilder::get(dwarf::DW_TAG_compile_unit)
161                           .concat(Lang)
162                           .concat(Producer)
163                           .concat(isOptimized)
164                           .concat(Flags)
165                           .concat(RunTimeVer)
166                           .concat(SplitName)
167                           .concat(Kind)
168                           .get(VMContext),
169                       createFilePathPair(VMContext, Filename, Directory),
170                       TempEnumTypes, TempRetainTypes, TempSubprograms, TempGVs,
171                       TempImportedModules};
172
173   MDNode *CUNode = MDNode::get(VMContext, Elts);
174
175   // Create a named metadata so that it is easier to find cu in a module.
176   // Note that we only generate this when the caller wants to actually
177   // emit debug information. When we are only interested in tracking
178   // source line locations throughout the backend, we prevent codegen from
179   // emitting debug info in the final output by not generating llvm.dbg.cu.
180   if (EmitDebugInfo) {
181     NamedMDNode *NMD = M.getOrInsertNamedMetadata("llvm.dbg.cu");
182     NMD->addOperand(CUNode);
183   }
184
185   trackIfUnresolved(CUNode);
186   return DICompileUnit(CUNode);
187 }
188
189 static DIImportedEntity
190 createImportedModule(LLVMContext &C, dwarf::Tag Tag, DIScope Context,
191                      Metadata *NS, unsigned Line, StringRef Name,
192                      SmallVectorImpl<TrackingMDNodeRef> &AllImportedModules) {
193   const MDNode *R;
194   Metadata *Elts[] = {HeaderBuilder::get(Tag).concat(Line).concat(Name).get(C),
195                       Context, NS};
196   R = MDNode::get(C, Elts);
197   DIImportedEntity M(R);
198   assert(M.Verify() && "Imported module should be valid");
199   AllImportedModules.emplace_back(M.get());
200   return M;
201 }
202
203 DIImportedEntity DIBuilder::createImportedModule(DIScope Context,
204                                                  DINameSpace NS,
205                                                  unsigned Line) {
206   return ::createImportedModule(VMContext, dwarf::DW_TAG_imported_module,
207                                 Context, NS, Line, StringRef(), AllImportedModules);
208 }
209
210 DIImportedEntity DIBuilder::createImportedModule(DIScope Context,
211                                                  DIImportedEntity NS,
212                                                  unsigned Line) {
213   return ::createImportedModule(VMContext, dwarf::DW_TAG_imported_module,
214                                 Context, NS, Line, StringRef(), AllImportedModules);
215 }
216
217 DIImportedEntity DIBuilder::createImportedDeclaration(DIScope Context,
218                                                       DIDescriptor Decl,
219                                                       unsigned Line, StringRef Name) {
220   // Make sure to use the unique identifier based metadata reference for
221   // types that have one.
222   Metadata *V =
223       Decl.isType() ? static_cast<Metadata *>(DIType(Decl).getRef()) : Decl;
224   return ::createImportedModule(VMContext, dwarf::DW_TAG_imported_declaration,
225                                 Context, V, Line, Name,
226                                 AllImportedModules);
227 }
228
229 DIImportedEntity DIBuilder::createImportedDeclaration(DIScope Context,
230                                                       DIImportedEntity Imp,
231                                                       unsigned Line, StringRef Name) {
232   return ::createImportedModule(VMContext, dwarf::DW_TAG_imported_declaration,
233                                 Context, Imp, Line, Name, AllImportedModules);
234 }
235
236 DIFile DIBuilder::createFile(StringRef Filename, StringRef Directory) {
237   Metadata *Elts[] = {
238       HeaderBuilder::get(dwarf::DW_TAG_file_type).get(VMContext),
239       createFilePathPair(VMContext, Filename, Directory)};
240   return DIFile(MDNode::get(VMContext, Elts));
241 }
242
243 DIEnumerator DIBuilder::createEnumerator(StringRef Name, int64_t Val) {
244   assert(!Name.empty() && "Unable to create enumerator without name");
245   Metadata *Elts[] = {HeaderBuilder::get(dwarf::DW_TAG_enumerator)
246                           .concat(Name)
247                           .concat(Val)
248                           .get(VMContext)};
249   return DIEnumerator(MDNode::get(VMContext, Elts));
250 }
251
252 DIBasicType DIBuilder::createUnspecifiedType(StringRef Name) {
253   assert(!Name.empty() && "Unable to create type without name");
254   // Unspecified types are encoded in DIBasicType format. Line number, filename,
255   // size, alignment, offset and flags are always empty here.
256   Metadata *Elts[] = {
257       HeaderBuilder::get(dwarf::DW_TAG_unspecified_type)
258           .concat(Name)
259           .concat(0)
260           .concat(0)
261           .concat(0)
262           .concat(0)
263           .concat(0)
264           .concat(0)
265           .get(VMContext),
266       nullptr, // Filename
267       nullptr  // Unused
268   };
269   return DIBasicType(MDNode::get(VMContext, Elts));
270 }
271
272 DIBasicType DIBuilder::createNullPtrType() {
273   return createUnspecifiedType("decltype(nullptr)");
274 }
275
276 DIBasicType
277 DIBuilder::createBasicType(StringRef Name, uint64_t SizeInBits,
278                            uint64_t AlignInBits, unsigned Encoding) {
279   assert(!Name.empty() && "Unable to create type without name");
280   // Basic types are encoded in DIBasicType format. Line number, filename,
281   // offset and flags are always empty here.
282   Metadata *Elts[] = {
283       HeaderBuilder::get(dwarf::DW_TAG_base_type)
284           .concat(Name)
285           .concat(0) // Line
286           .concat(SizeInBits)
287           .concat(AlignInBits)
288           .concat(0) // Offset
289           .concat(0) // Flags
290           .concat(Encoding)
291           .get(VMContext),
292       nullptr, // Filename
293       nullptr  // Unused
294   };
295   return DIBasicType(MDNode::get(VMContext, Elts));
296 }
297
298 DIDerivedType DIBuilder::createQualifiedType(unsigned Tag, DIType FromTy) {
299   // Qualified types are encoded in DIDerivedType format.
300   Metadata *Elts[] = {HeaderBuilder::get(Tag)
301                           .concat(StringRef()) // Name
302                           .concat(0)           // Line
303                           .concat(0)           // Size
304                           .concat(0)           // Align
305                           .concat(0)           // Offset
306                           .concat(0)           // Flags
307                           .get(VMContext),
308                       nullptr, // Filename
309                       nullptr, // Unused
310                       FromTy.getRef()};
311   return DIDerivedType(MDNode::get(VMContext, Elts));
312 }
313
314 DIDerivedType
315 DIBuilder::createPointerType(DIType PointeeTy, uint64_t SizeInBits,
316                              uint64_t AlignInBits, StringRef Name) {
317   // Pointer types are encoded in DIDerivedType format.
318   Metadata *Elts[] = {HeaderBuilder::get(dwarf::DW_TAG_pointer_type)
319                           .concat(Name)
320                           .concat(0) // Line
321                           .concat(SizeInBits)
322                           .concat(AlignInBits)
323                           .concat(0) // Offset
324                           .concat(0) // Flags
325                           .get(VMContext),
326                       nullptr, // Filename
327                       nullptr, // Unused
328                       PointeeTy.getRef()};
329   return DIDerivedType(MDNode::get(VMContext, Elts));
330 }
331
332 DIDerivedType
333 DIBuilder::createMemberPointerType(DIType PointeeTy, DIType Base,
334                                    uint64_t SizeInBits, uint64_t AlignInBits) {
335   // Pointer types are encoded in DIDerivedType format.
336   Metadata *Elts[] = {HeaderBuilder::get(dwarf::DW_TAG_ptr_to_member_type)
337                           .concat(StringRef())
338                           .concat(0) // Line
339                           .concat(SizeInBits) // Size
340                           .concat(AlignInBits) // Align
341                           .concat(0) // Offset
342                           .concat(0) // Flags
343                           .get(VMContext),
344                       nullptr, // Filename
345                       nullptr, // Unused
346                       PointeeTy.getRef(), Base.getRef()};
347   return DIDerivedType(MDNode::get(VMContext, Elts));
348 }
349
350 DIDerivedType DIBuilder::createReferenceType(unsigned Tag, DIType RTy) {
351   assert(RTy.isType() && "Unable to create reference type");
352   // References are encoded in DIDerivedType format.
353   Metadata *Elts[] = {HeaderBuilder::get(Tag)
354                           .concat(StringRef()) // Name
355                           .concat(0)           // Line
356                           .concat(0)           // Size
357                           .concat(0)           // Align
358                           .concat(0)           // Offset
359                           .concat(0)           // Flags
360                           .get(VMContext),
361                       nullptr, // Filename
362                       nullptr, // TheCU,
363                       RTy.getRef()};
364   return DIDerivedType(MDNode::get(VMContext, Elts));
365 }
366
367 DIDerivedType DIBuilder::createTypedef(DIType Ty, StringRef Name, DIFile File,
368                                        unsigned LineNo, DIDescriptor Context) {
369   // typedefs are encoded in DIDerivedType format.
370   Metadata *Elts[] = {HeaderBuilder::get(dwarf::DW_TAG_typedef)
371                           .concat(Name)
372                           .concat(LineNo)
373                           .concat(0) // Size
374                           .concat(0) // Align
375                           .concat(0) // Offset
376                           .concat(0) // Flags
377                           .get(VMContext),
378                       File.getFileNode(),
379                       DIScope(getNonCompileUnitScope(Context)).getRef(),
380                       Ty.getRef()};
381   return DIDerivedType(MDNode::get(VMContext, Elts));
382 }
383
384 DIDerivedType DIBuilder::createFriend(DIType Ty, DIType FriendTy) {
385   // typedefs are encoded in DIDerivedType format.
386   assert(Ty.isType() && "Invalid type!");
387   assert(FriendTy.isType() && "Invalid friend type!");
388   Metadata *Elts[] = {HeaderBuilder::get(dwarf::DW_TAG_friend)
389                           .concat(StringRef()) // Name
390                           .concat(0)           // Line
391                           .concat(0)           // Size
392                           .concat(0)           // Align
393                           .concat(0)           // Offset
394                           .concat(0)           // Flags
395                           .get(VMContext),
396                       nullptr, Ty.getRef(), FriendTy.getRef()};
397   return DIDerivedType(MDNode::get(VMContext, Elts));
398 }
399
400 DIDerivedType DIBuilder::createInheritance(DIType Ty, DIType BaseTy,
401                                            uint64_t BaseOffset,
402                                            unsigned Flags) {
403   assert(Ty.isType() && "Unable to create inheritance");
404   // TAG_inheritance is encoded in DIDerivedType format.
405   Metadata *Elts[] = {HeaderBuilder::get(dwarf::DW_TAG_inheritance)
406                           .concat(StringRef()) // Name
407                           .concat(0)           // Line
408                           .concat(0)           // Size
409                           .concat(0)           // Align
410                           .concat(BaseOffset)
411                           .concat(Flags)
412                           .get(VMContext),
413                       nullptr, Ty.getRef(), BaseTy.getRef()};
414   return DIDerivedType(MDNode::get(VMContext, Elts));
415 }
416
417 DIDerivedType DIBuilder::createMemberType(DIDescriptor Scope, StringRef Name,
418                                           DIFile File, unsigned LineNumber,
419                                           uint64_t SizeInBits,
420                                           uint64_t AlignInBits,
421                                           uint64_t OffsetInBits, unsigned Flags,
422                                           DIType Ty) {
423   // TAG_member is encoded in DIDerivedType format.
424   Metadata *Elts[] = {HeaderBuilder::get(dwarf::DW_TAG_member)
425                           .concat(Name)
426                           .concat(LineNumber)
427                           .concat(SizeInBits)
428                           .concat(AlignInBits)
429                           .concat(OffsetInBits)
430                           .concat(Flags)
431                           .get(VMContext),
432                       File.getFileNode(),
433                       DIScope(getNonCompileUnitScope(Scope)).getRef(),
434                       Ty.getRef()};
435   return DIDerivedType(MDNode::get(VMContext, Elts));
436 }
437
438 static Metadata *getConstantOrNull(Constant *C) {
439   if (C)
440     return ConstantAsMetadata::get(C);
441   return nullptr;
442 }
443
444 DIDerivedType DIBuilder::createStaticMemberType(DIDescriptor Scope,
445                                                 StringRef Name, DIFile File,
446                                                 unsigned LineNumber, DIType Ty,
447                                                 unsigned Flags,
448                                                 llvm::Constant *Val) {
449   // TAG_member is encoded in DIDerivedType format.
450   Flags |= DIDescriptor::FlagStaticMember;
451   Metadata *Elts[] = {HeaderBuilder::get(dwarf::DW_TAG_member)
452                           .concat(Name)
453                           .concat(LineNumber)
454                           .concat(0) // Size
455                           .concat(0) // Align
456                           .concat(0) // Offset
457                           .concat(Flags)
458                           .get(VMContext),
459                       File.getFileNode(),
460                       DIScope(getNonCompileUnitScope(Scope)).getRef(),
461                       Ty.getRef(), getConstantOrNull(Val)};
462   return DIDerivedType(MDNode::get(VMContext, Elts));
463 }
464
465 DIDerivedType DIBuilder::createObjCIVar(StringRef Name, DIFile File,
466                                         unsigned LineNumber,
467                                         uint64_t SizeInBits,
468                                         uint64_t AlignInBits,
469                                         uint64_t OffsetInBits, unsigned Flags,
470                                         DIType Ty, MDNode *PropertyNode) {
471   // TAG_member is encoded in DIDerivedType format.
472   Metadata *Elts[] = {HeaderBuilder::get(dwarf::DW_TAG_member)
473                           .concat(Name)
474                           .concat(LineNumber)
475                           .concat(SizeInBits)
476                           .concat(AlignInBits)
477                           .concat(OffsetInBits)
478                           .concat(Flags)
479                           .get(VMContext),
480                       File.getFileNode(), getNonCompileUnitScope(File), Ty,
481                       PropertyNode};
482   return DIDerivedType(MDNode::get(VMContext, Elts));
483 }
484
485 DIObjCProperty
486 DIBuilder::createObjCProperty(StringRef Name, DIFile File, unsigned LineNumber,
487                               StringRef GetterName, StringRef SetterName,
488                               unsigned PropertyAttributes, DIType Ty) {
489   Metadata *Elts[] = {HeaderBuilder::get(dwarf::DW_TAG_APPLE_property)
490                           .concat(Name)
491                           .concat(LineNumber)
492                           .concat(GetterName)
493                           .concat(SetterName)
494                           .concat(PropertyAttributes)
495                           .get(VMContext),
496                       File, Ty};
497   return DIObjCProperty(MDNode::get(VMContext, Elts));
498 }
499
500 DITemplateTypeParameter
501 DIBuilder::createTemplateTypeParameter(DIDescriptor Context, StringRef Name,
502                                        DIType Ty, MDNode *File, unsigned LineNo,
503                                        unsigned ColumnNo) {
504   Metadata *Elts[] = {HeaderBuilder::get(dwarf::DW_TAG_template_type_parameter)
505                           .concat(Name)
506                           .concat(LineNo)
507                           .concat(ColumnNo)
508                           .get(VMContext),
509                       DIScope(getNonCompileUnitScope(Context)).getRef(),
510                       Ty.getRef(), File};
511   return DITemplateTypeParameter(MDNode::get(VMContext, Elts));
512 }
513
514 static DITemplateValueParameter createTemplateValueParameterHelper(
515     LLVMContext &VMContext, unsigned Tag, DIDescriptor Context, StringRef Name,
516     DIType Ty, Metadata *MD, MDNode *File, unsigned LineNo, unsigned ColumnNo) {
517   Metadata *Elts[] = {
518       HeaderBuilder::get(Tag).concat(Name).concat(LineNo).concat(ColumnNo).get(
519           VMContext),
520       DIScope(getNonCompileUnitScope(Context)).getRef(), Ty.getRef(), MD, File};
521   return DITemplateValueParameter(MDNode::get(VMContext, Elts));
522 }
523
524 DITemplateValueParameter
525 DIBuilder::createTemplateValueParameter(DIDescriptor Context, StringRef Name,
526                                         DIType Ty, Constant *Val, MDNode *File,
527                                         unsigned LineNo, unsigned ColumnNo) {
528   return createTemplateValueParameterHelper(
529       VMContext, dwarf::DW_TAG_template_value_parameter, Context, Name, Ty,
530       getConstantOrNull(Val), File, LineNo, ColumnNo);
531 }
532
533 DITemplateValueParameter
534 DIBuilder::createTemplateTemplateParameter(DIDescriptor Context, StringRef Name,
535                                            DIType Ty, StringRef Val,
536                                            MDNode *File, unsigned LineNo,
537                                            unsigned ColumnNo) {
538   return createTemplateValueParameterHelper(
539       VMContext, dwarf::DW_TAG_GNU_template_template_param, Context, Name, Ty,
540       MDString::get(VMContext, Val), File, LineNo, ColumnNo);
541 }
542
543 DITemplateValueParameter
544 DIBuilder::createTemplateParameterPack(DIDescriptor Context, StringRef Name,
545                                        DIType Ty, DIArray Val,
546                                        MDNode *File, unsigned LineNo,
547                                        unsigned ColumnNo) {
548   return createTemplateValueParameterHelper(
549       VMContext, dwarf::DW_TAG_GNU_template_parameter_pack, Context, Name, Ty,
550       Val, File, LineNo, ColumnNo);
551 }
552
553 DICompositeType DIBuilder::createClassType(DIDescriptor Context, StringRef Name,
554                                            DIFile File, unsigned LineNumber,
555                                            uint64_t SizeInBits,
556                                            uint64_t AlignInBits,
557                                            uint64_t OffsetInBits,
558                                            unsigned Flags, DIType DerivedFrom,
559                                            DIArray Elements,
560                                            DIType VTableHolder,
561                                            MDNode *TemplateParams,
562                                            StringRef UniqueIdentifier) {
563   assert((!Context || Context.isScope() || Context.isType()) &&
564          "createClassType should be called with a valid Context");
565   // TAG_class_type is encoded in DICompositeType format.
566   Metadata *Elts[] = {
567       HeaderBuilder::get(dwarf::DW_TAG_class_type)
568           .concat(Name)
569           .concat(LineNumber)
570           .concat(SizeInBits)
571           .concat(AlignInBits)
572           .concat(OffsetInBits)
573           .concat(Flags)
574           .concat(0)
575           .get(VMContext),
576       File.getFileNode(), DIScope(getNonCompileUnitScope(Context)).getRef(),
577       DerivedFrom.getRef(), Elements, VTableHolder.getRef(), TemplateParams,
578       UniqueIdentifier.empty() ? nullptr
579                                : MDString::get(VMContext, UniqueIdentifier)};
580   DICompositeType R(MDNode::get(VMContext, Elts));
581   assert(R.isCompositeType() &&
582          "createClassType should return a DICompositeType");
583   if (!UniqueIdentifier.empty())
584     retainType(R);
585   return R;
586 }
587
588 DICompositeType DIBuilder::createStructType(DIDescriptor Context,
589                                             StringRef Name, DIFile File,
590                                             unsigned LineNumber,
591                                             uint64_t SizeInBits,
592                                             uint64_t AlignInBits,
593                                             unsigned Flags, DIType DerivedFrom,
594                                             DIArray Elements,
595                                             unsigned RunTimeLang,
596                                             DIType VTableHolder,
597                                             StringRef UniqueIdentifier) {
598  // TAG_structure_type is encoded in DICompositeType format.
599   Metadata *Elts[] = {
600       HeaderBuilder::get(dwarf::DW_TAG_structure_type)
601           .concat(Name)
602           .concat(LineNumber)
603           .concat(SizeInBits)
604           .concat(AlignInBits)
605           .concat(0)
606           .concat(Flags)
607           .concat(RunTimeLang)
608           .get(VMContext),
609       File.getFileNode(), DIScope(getNonCompileUnitScope(Context)).getRef(),
610       DerivedFrom.getRef(), Elements, VTableHolder.getRef(), nullptr,
611       UniqueIdentifier.empty() ? nullptr
612                                : MDString::get(VMContext, UniqueIdentifier)};
613   DICompositeType R(MDNode::get(VMContext, Elts));
614   assert(R.isCompositeType() &&
615          "createStructType should return a DICompositeType");
616   if (!UniqueIdentifier.empty())
617     retainType(R);
618   return R;
619 }
620
621 DICompositeType DIBuilder::createUnionType(DIDescriptor Scope, StringRef Name,
622                                            DIFile File, unsigned LineNumber,
623                                            uint64_t SizeInBits,
624                                            uint64_t AlignInBits, unsigned Flags,
625                                            DIArray Elements,
626                                            unsigned RunTimeLang,
627                                            StringRef UniqueIdentifier) {
628   // TAG_union_type is encoded in DICompositeType format.
629   Metadata *Elts[] = {
630       HeaderBuilder::get(dwarf::DW_TAG_union_type)
631           .concat(Name)
632           .concat(LineNumber)
633           .concat(SizeInBits)
634           .concat(AlignInBits)
635           .concat(0) // Offset
636           .concat(Flags)
637           .concat(RunTimeLang)
638           .get(VMContext),
639       File.getFileNode(), DIScope(getNonCompileUnitScope(Scope)).getRef(),
640       nullptr, Elements, nullptr, nullptr,
641       UniqueIdentifier.empty() ? nullptr
642                                : MDString::get(VMContext, UniqueIdentifier)};
643   DICompositeType R(MDNode::get(VMContext, Elts));
644   if (!UniqueIdentifier.empty())
645     retainType(R);
646   return R;
647 }
648
649 DISubroutineType DIBuilder::createSubroutineType(DIFile File,
650                                                  DITypeArray ParameterTypes,
651                                                  unsigned Flags) {
652   // TAG_subroutine_type is encoded in DICompositeType format.
653   Metadata *Elts[] = {
654       HeaderBuilder::get(dwarf::DW_TAG_subroutine_type)
655           .concat(StringRef())
656           .concat(0)     // Line
657           .concat(0)     // Size
658           .concat(0)     // Align
659           .concat(0)     // Offset
660           .concat(Flags) // Flags
661           .concat(0)
662           .get(VMContext),
663       nullptr, nullptr, nullptr, ParameterTypes, nullptr, nullptr,
664       nullptr // Type Identifer
665   };
666   return DISubroutineType(MDNode::get(VMContext, Elts));
667 }
668
669 DICompositeType DIBuilder::createEnumerationType(
670     DIDescriptor Scope, StringRef Name, DIFile File, unsigned LineNumber,
671     uint64_t SizeInBits, uint64_t AlignInBits, DIArray Elements,
672     DIType UnderlyingType, StringRef UniqueIdentifier) {
673   // TAG_enumeration_type is encoded in DICompositeType format.
674   Metadata *Elts[] = {
675       HeaderBuilder::get(dwarf::DW_TAG_enumeration_type)
676           .concat(Name)
677           .concat(LineNumber)
678           .concat(SizeInBits)
679           .concat(AlignInBits)
680           .concat(0) // Offset
681           .concat(0) // Flags
682           .concat(0)
683           .get(VMContext),
684       File.getFileNode(), DIScope(getNonCompileUnitScope(Scope)).getRef(),
685       UnderlyingType.getRef(), Elements, nullptr, nullptr,
686       UniqueIdentifier.empty() ? nullptr
687                                : MDString::get(VMContext, UniqueIdentifier)};
688   DICompositeType CTy(MDNode::get(VMContext, Elts));
689   AllEnumTypes.push_back(CTy);
690   if (!UniqueIdentifier.empty())
691     retainType(CTy);
692   return CTy;
693 }
694
695 DICompositeType DIBuilder::createArrayType(uint64_t Size, uint64_t AlignInBits,
696                                            DIType Ty, DIArray Subscripts) {
697   // TAG_array_type is encoded in DICompositeType format.
698   Metadata *Elts[] = {
699       HeaderBuilder::get(dwarf::DW_TAG_array_type)
700           .concat(StringRef())
701           .concat(0) // Line
702           .concat(Size)
703           .concat(AlignInBits)
704           .concat(0) // Offset
705           .concat(0) // Flags
706           .concat(0)
707           .get(VMContext),
708       nullptr, // Filename/Directory,
709       nullptr, // Unused
710       Ty.getRef(), Subscripts, nullptr, nullptr,
711       nullptr // Type Identifer
712   };
713   return DICompositeType(MDNode::get(VMContext, Elts));
714 }
715
716 DICompositeType DIBuilder::createVectorType(uint64_t Size, uint64_t AlignInBits,
717                                             DIType Ty, DIArray Subscripts) {
718   // A vector is an array type with the FlagVector flag applied.
719   Metadata *Elts[] = {
720       HeaderBuilder::get(dwarf::DW_TAG_array_type)
721           .concat("")
722           .concat(0) // Line
723           .concat(Size)
724           .concat(AlignInBits)
725           .concat(0) // Offset
726           .concat(DIType::FlagVector)
727           .concat(0)
728           .get(VMContext),
729       nullptr, // Filename/Directory,
730       nullptr, // Unused
731       Ty.getRef(), Subscripts, nullptr, nullptr,
732       nullptr // Type Identifer
733   };
734   return DICompositeType(MDNode::get(VMContext, Elts));
735 }
736
737 static HeaderBuilder setTypeFlagsInHeader(StringRef Header,
738                                           unsigned FlagsToSet) {
739   DIHeaderFieldIterator I(Header);
740   std::advance(I, 6);
741
742   unsigned Flags;
743   if (I->getAsInteger(0, Flags))
744     Flags = 0;
745   Flags |= FlagsToSet;
746
747   return HeaderBuilder(Twine(I.getPrefix())).concat(Flags).concat(
748       I.getSuffix());
749 }
750
751 static DIType createTypeWithFlags(LLVMContext &Context, DIType Ty,
752                                   unsigned FlagsToSet) {
753   SmallVector<Metadata *, 9> Elts;
754   MDNode *N = Ty;
755   assert(N && "Unexpected input DIType!");
756   // Update header field.
757   Elts.push_back(setTypeFlagsInHeader(Ty.getHeader(), FlagsToSet).get(Context));
758   for (unsigned I = 1, E = N->getNumOperands(); I != E; ++I)
759     Elts.push_back(N->getOperand(I));
760
761   return DIType(MDNode::get(Context, Elts));
762 }
763
764 DIType DIBuilder::createArtificialType(DIType Ty) {
765   if (Ty.isArtificial())
766     return Ty;
767   return createTypeWithFlags(VMContext, Ty, DIType::FlagArtificial);
768 }
769
770 DIType DIBuilder::createObjectPointerType(DIType Ty) {
771   if (Ty.isObjectPointer())
772     return Ty;
773   unsigned Flags = DIType::FlagObjectPointer | DIType::FlagArtificial;
774   return createTypeWithFlags(VMContext, Ty, Flags);
775 }
776
777 void DIBuilder::retainType(DIType T) { AllRetainTypes.emplace_back(T); }
778
779 DIBasicType DIBuilder::createUnspecifiedParameter() {
780   return DIBasicType();
781 }
782
783 DICompositeType
784 DIBuilder::createForwardDecl(unsigned Tag, StringRef Name, DIDescriptor Scope,
785                              DIFile F, unsigned Line, unsigned RuntimeLang,
786                              uint64_t SizeInBits, uint64_t AlignInBits,
787                              StringRef UniqueIdentifier) {
788   // Create a temporary MDNode.
789   Metadata *Elts[] = {
790       HeaderBuilder::get(Tag)
791           .concat(Name)
792           .concat(Line)
793           .concat(SizeInBits)
794           .concat(AlignInBits)
795           .concat(0) // Offset
796           .concat(DIDescriptor::FlagFwdDecl)
797           .concat(RuntimeLang)
798           .get(VMContext),
799       F.getFileNode(), DIScope(getNonCompileUnitScope(Scope)).getRef(), nullptr,
800       DIArray(), nullptr,
801       nullptr, // TemplateParams
802       UniqueIdentifier.empty() ? nullptr
803                                : MDString::get(VMContext, UniqueIdentifier)};
804   MDNode *Node = MDNode::get(VMContext, Elts);
805   DICompositeType RetTy(Node);
806   assert(RetTy.isCompositeType() &&
807          "createForwardDecl result should be a DIType");
808   if (!UniqueIdentifier.empty())
809     retainType(RetTy);
810   return RetTy;
811 }
812
813 DICompositeType DIBuilder::createReplaceableForwardDecl(
814     unsigned Tag, StringRef Name, DIDescriptor Scope, DIFile F, unsigned Line,
815     unsigned RuntimeLang, uint64_t SizeInBits, uint64_t AlignInBits,
816     StringRef UniqueIdentifier) {
817   // Create a temporary MDNode.
818   Metadata *Elts[] = {
819       HeaderBuilder::get(Tag)
820           .concat(Name)
821           .concat(Line)
822           .concat(SizeInBits)
823           .concat(AlignInBits)
824           .concat(0) // Offset
825           .concat(DIDescriptor::FlagFwdDecl)
826           .concat(RuntimeLang)
827           .get(VMContext),
828       F.getFileNode(), DIScope(getNonCompileUnitScope(Scope)).getRef(), nullptr,
829       DIArray(), nullptr,
830       nullptr, // TemplateParams
831       UniqueIdentifier.empty() ? nullptr
832                                : MDString::get(VMContext, UniqueIdentifier)};
833   DICompositeType RetTy(MDNode::getTemporary(VMContext, Elts));
834   assert(RetTy.isCompositeType() &&
835          "createReplaceableForwardDecl result should be a DIType");
836   if (!UniqueIdentifier.empty())
837     retainType(RetTy);
838   return RetTy;
839 }
840
841 DIArray DIBuilder::getOrCreateArray(ArrayRef<Metadata *> Elements) {
842   return DIArray(MDNode::get(VMContext, Elements));
843 }
844
845 DITypeArray DIBuilder::getOrCreateTypeArray(ArrayRef<Metadata *> Elements) {
846   SmallVector<llvm::Metadata *, 16> Elts;
847   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
848     if (Elements[i] && isa<MDNode>(Elements[i]))
849       Elts.push_back(DIType(cast<MDNode>(Elements[i])).getRef());
850     else
851       Elts.push_back(Elements[i]);
852   }
853   return DITypeArray(MDNode::get(VMContext, Elts));
854 }
855
856 DISubrange DIBuilder::getOrCreateSubrange(int64_t Lo, int64_t Count) {
857   Metadata *Elts[] = {HeaderBuilder::get(dwarf::DW_TAG_subrange_type)
858                           .concat(Lo)
859                           .concat(Count)
860                           .get(VMContext)};
861
862   return DISubrange(MDNode::get(VMContext, Elts));
863 }
864
865 static DIGlobalVariable createGlobalVariableHelper(
866     LLVMContext &VMContext, DIDescriptor Context, StringRef Name,
867     StringRef LinkageName, DIFile F, unsigned LineNumber, DITypeRef Ty,
868     bool isLocalToUnit, Constant *Val, MDNode *Decl, bool isDefinition,
869     std::function<MDNode *(ArrayRef<Metadata *>)> CreateFunc) {
870
871   MDNode *TheCtx = getNonCompileUnitScope(Context);
872   if (DIScope(TheCtx).isCompositeType()) {
873     assert(!DICompositeType(TheCtx).getIdentifier() &&
874            "Context of a global variable should not be a type with identifier");
875   }
876
877   Metadata *Elts[] = {HeaderBuilder::get(dwarf::DW_TAG_variable)
878                           .concat(Name)
879                           .concat(Name)
880                           .concat(LinkageName)
881                           .concat(LineNumber)
882                           .concat(isLocalToUnit)
883                           .concat(isDefinition)
884                           .get(VMContext),
885                       TheCtx, F, Ty, getConstantOrNull(Val),
886                       DIDescriptor(Decl)};
887
888   return DIGlobalVariable(CreateFunc(Elts));
889 }
890
891 DIGlobalVariable DIBuilder::createGlobalVariable(
892     DIDescriptor Context, StringRef Name, StringRef LinkageName, DIFile F,
893     unsigned LineNumber, DITypeRef Ty, bool isLocalToUnit, Constant *Val,
894     MDNode *Decl) {
895   return createGlobalVariableHelper(
896       VMContext, Context, Name, LinkageName, F, LineNumber, Ty, isLocalToUnit,
897       Val, Decl, true, [&](ArrayRef<Metadata *> Elts) -> MDNode *{
898         MDNode *Node = MDNode::get(VMContext, Elts);
899         AllGVs.push_back(Node);
900         return Node;
901       });
902 }
903
904 DIGlobalVariable DIBuilder::createTempGlobalVariableFwdDecl(
905     DIDescriptor Context, StringRef Name, StringRef LinkageName, DIFile F,
906     unsigned LineNumber, DITypeRef Ty, bool isLocalToUnit, Constant *Val,
907     MDNode *Decl) {
908   return createGlobalVariableHelper(VMContext, Context, Name, LinkageName, F,
909                                     LineNumber, Ty, isLocalToUnit, Val, Decl,
910                                     false, [&](ArrayRef<Metadata *> Elts) {
911     return MDNode::getTemporary(VMContext, Elts);
912   });
913 }
914
915 DIVariable DIBuilder::createLocalVariable(unsigned Tag, DIDescriptor Scope,
916                                           StringRef Name, DIFile File,
917                                           unsigned LineNo, DITypeRef Ty,
918                                           bool AlwaysPreserve, unsigned Flags,
919                                           unsigned ArgNo) {
920   DIDescriptor Context(getNonCompileUnitScope(Scope));
921   assert((!Context || Context.isScope()) &&
922          "createLocalVariable should be called with a valid Context");
923   Metadata *Elts[] = {HeaderBuilder::get(Tag)
924                           .concat(Name)
925                           .concat(LineNo | (ArgNo << 24))
926                           .concat(Flags)
927                           .get(VMContext),
928                       getNonCompileUnitScope(Scope), File, Ty};
929   MDNode *Node = MDNode::get(VMContext, Elts);
930   if (AlwaysPreserve) {
931     // The optimizer may remove local variable. If there is an interest
932     // to preserve variable info in such situation then stash it in a
933     // named mdnode.
934     DISubprogram Fn(getDISubprogram(Scope));
935     assert(Fn && "Missing subprogram for local variable");
936     PreservedVariables[Fn].emplace_back(Node);
937   }
938   DIVariable RetVar(Node);
939   assert(RetVar.isVariable() &&
940          "createLocalVariable should return a valid DIVariable");
941   return RetVar;
942 }
943
944 DIExpression DIBuilder::createExpression(ArrayRef<int64_t> Addr) {
945   auto Header = HeaderBuilder::get(DW_TAG_expression);
946   for (int64_t I : Addr)
947     Header.concat(I);
948   Metadata *Elts[] = {Header.get(VMContext)};
949   return DIExpression(MDNode::get(VMContext, Elts));
950 }
951
952 DIExpression DIBuilder::createPieceExpression(unsigned OffsetInBytes,
953                                               unsigned SizeInBytes) {
954   int64_t Addr[] = {dwarf::DW_OP_piece, OffsetInBytes, SizeInBytes};
955   return createExpression(Addr);
956 }
957
958 DISubprogram DIBuilder::createFunction(DIScopeRef Context, StringRef Name,
959                                        StringRef LinkageName, DIFile File,
960                                        unsigned LineNo, DICompositeType Ty,
961                                        bool isLocalToUnit, bool isDefinition,
962                                        unsigned ScopeLine, unsigned Flags,
963                                        bool isOptimized, Function *Fn,
964                                        MDNode *TParams, MDNode *Decl) {
965   // dragonegg does not generate identifier for types, so using an empty map
966   // to resolve the context should be fine.
967   DITypeIdentifierMap EmptyMap;
968   return createFunction(Context.resolve(EmptyMap), Name, LinkageName, File,
969                         LineNo, Ty, isLocalToUnit, isDefinition, ScopeLine,
970                         Flags, isOptimized, Fn, TParams, Decl);
971 }
972
973 static DISubprogram createFunctionHelper(
974     LLVMContext &VMContext, DIDescriptor Context, StringRef Name,
975     StringRef LinkageName, DIFile File, unsigned LineNo, DICompositeType Ty,
976     bool isLocalToUnit, bool isDefinition, unsigned ScopeLine, unsigned Flags,
977     bool isOptimized, Function *Fn, MDNode *TParams, MDNode *Decl, MDNode *Vars,
978     std::function<MDNode *(ArrayRef<Metadata *>)> CreateFunc) {
979   assert(Ty.getTag() == dwarf::DW_TAG_subroutine_type &&
980          "function types should be subroutines");
981   Metadata *Elts[] = {HeaderBuilder::get(dwarf::DW_TAG_subprogram)
982                           .concat(Name)
983                           .concat(Name)
984                           .concat(LinkageName)
985                           .concat(LineNo)
986                           .concat(isLocalToUnit)
987                           .concat(isDefinition)
988                           .concat(0)
989                           .concat(0)
990                           .concat(Flags)
991                           .concat(isOptimized)
992                           .concat(ScopeLine)
993                           .get(VMContext),
994                       File.getFileNode(),
995                       DIScope(getNonCompileUnitScope(Context)).getRef(), Ty,
996                       nullptr, getConstantOrNull(Fn), TParams, Decl, Vars};
997
998   DISubprogram S(CreateFunc(Elts));
999   assert(S.isSubprogram() &&
1000          "createFunction should return a valid DISubprogram");
1001   return S;
1002 }
1003
1004
1005 DISubprogram DIBuilder::createFunction(DIDescriptor Context, StringRef Name,
1006                                        StringRef LinkageName, DIFile File,
1007                                        unsigned LineNo, DICompositeType Ty,
1008                                        bool isLocalToUnit, bool isDefinition,
1009                                        unsigned ScopeLine, unsigned Flags,
1010                                        bool isOptimized, Function *Fn,
1011                                        MDNode *TParams, MDNode *Decl) {
1012   return createFunctionHelper(VMContext, Context, Name, LinkageName, File,
1013                               LineNo, Ty, isLocalToUnit, isDefinition,
1014                               ScopeLine, Flags, isOptimized, Fn, TParams, Decl,
1015                               MDNode::getTemporary(VMContext, None),
1016                               [&](ArrayRef<Metadata *> Elts) -> MDNode *{
1017     MDNode *Node = MDNode::get(VMContext, Elts);
1018     // Create a named metadata so that we
1019     // do not lose this mdnode.
1020     if (isDefinition)
1021       AllSubprograms.push_back(Node);
1022     return Node;
1023   });
1024 }
1025
1026 DISubprogram
1027 DIBuilder::createTempFunctionFwdDecl(DIDescriptor Context, StringRef Name,
1028                                      StringRef LinkageName, DIFile File,
1029                                      unsigned LineNo, DICompositeType Ty,
1030                                      bool isLocalToUnit, bool isDefinition,
1031                                      unsigned ScopeLine, unsigned Flags,
1032                                      bool isOptimized, Function *Fn,
1033                                      MDNode *TParams, MDNode *Decl) {
1034   return createFunctionHelper(VMContext, Context, Name, LinkageName, File,
1035                               LineNo, Ty, isLocalToUnit, isDefinition,
1036                               ScopeLine, Flags, isOptimized, Fn, TParams, Decl,
1037                               nullptr, [&](ArrayRef<Metadata *> Elts) {
1038     return MDNode::getTemporary(VMContext, Elts);
1039   });
1040 }
1041
1042 DISubprogram DIBuilder::createMethod(DIDescriptor Context, StringRef Name,
1043                                      StringRef LinkageName, DIFile F,
1044                                      unsigned LineNo, DICompositeType Ty,
1045                                      bool isLocalToUnit, bool isDefinition,
1046                                      unsigned VK, unsigned VIndex,
1047                                      DIType VTableHolder, unsigned Flags,
1048                                      bool isOptimized, Function *Fn,
1049                                      MDNode *TParam) {
1050   assert(Ty.getTag() == dwarf::DW_TAG_subroutine_type &&
1051          "function types should be subroutines");
1052   assert(getNonCompileUnitScope(Context) &&
1053          "Methods should have both a Context and a context that isn't "
1054          "the compile unit.");
1055   Metadata *Elts[] = {HeaderBuilder::get(dwarf::DW_TAG_subprogram)
1056                           .concat(Name)
1057                           .concat(Name)
1058                           .concat(LinkageName)
1059                           .concat(LineNo)
1060                           .concat(isLocalToUnit)
1061                           .concat(isDefinition)
1062                           .concat(VK)
1063                           .concat(VIndex)
1064                           .concat(Flags)
1065                           .concat(isOptimized)
1066                           .concat(LineNo)
1067                           // FIXME: Do we want to use different scope/lines?
1068                           .get(VMContext),
1069                       F.getFileNode(), DIScope(Context).getRef(), Ty,
1070                       VTableHolder.getRef(), getConstantOrNull(Fn), TParam,
1071                       nullptr, nullptr};
1072   MDNode *Node = MDNode::get(VMContext, Elts);
1073   if (isDefinition)
1074     AllSubprograms.push_back(Node);
1075   DISubprogram S(Node);
1076   assert(S.isSubprogram() && "createMethod should return a valid DISubprogram");
1077   return S;
1078 }
1079
1080 DINameSpace DIBuilder::createNameSpace(DIDescriptor Scope, StringRef Name,
1081                                        DIFile File, unsigned LineNo) {
1082   Metadata *Elts[] = {HeaderBuilder::get(dwarf::DW_TAG_namespace)
1083                           .concat(Name)
1084                           .concat(LineNo)
1085                           .get(VMContext),
1086                       File.getFileNode(), getNonCompileUnitScope(Scope)};
1087   DINameSpace R(MDNode::get(VMContext, Elts));
1088   assert(R.Verify() &&
1089          "createNameSpace should return a verifiable DINameSpace");
1090   return R;
1091 }
1092
1093 DILexicalBlockFile DIBuilder::createLexicalBlockFile(DIDescriptor Scope,
1094                                                      DIFile File,
1095                                                      unsigned Discriminator) {
1096   Metadata *Elts[] = {HeaderBuilder::get(dwarf::DW_TAG_lexical_block)
1097                           .concat(Discriminator)
1098                           .get(VMContext),
1099                       File.getFileNode(), Scope};
1100   DILexicalBlockFile R(MDNode::get(VMContext, Elts));
1101   assert(
1102       R.Verify() &&
1103       "createLexicalBlockFile should return a verifiable DILexicalBlockFile");
1104   return R;
1105 }
1106
1107 DILexicalBlock DIBuilder::createLexicalBlock(DIDescriptor Scope, DIFile File,
1108                                              unsigned Line, unsigned Col) {
1109   // FIXME: This isn't thread safe nor the right way to defeat MDNode uniquing.
1110   // I believe the right way is to have a self-referential element in the node.
1111   // Also: why do we bother with line/column - they're not used and the
1112   // documentation (SourceLevelDebugging.rst) claims the line/col are necessary
1113   // for uniquing, yet then we have this other solution (because line/col were
1114   // inadequate) anyway. Remove all 3 and replace them with a self-reference.
1115
1116   // Defeat MDNode uniquing for lexical blocks by using unique id.
1117   static unsigned int unique_id = 0;
1118   Metadata *Elts[] = {HeaderBuilder::get(dwarf::DW_TAG_lexical_block)
1119                           .concat(Line)
1120                           .concat(Col)
1121                           .concat(unique_id++)
1122                           .get(VMContext),
1123                       File.getFileNode(), getNonCompileUnitScope(Scope)};
1124   DILexicalBlock R(MDNode::get(VMContext, Elts));
1125   assert(R.Verify() &&
1126          "createLexicalBlock should return a verifiable DILexicalBlock");
1127   return R;
1128 }
1129
1130 static Value *getDbgIntrinsicValueImpl(LLVMContext &VMContext, Value *V) {
1131   assert(V && "no value passed to dbg intrinsic");
1132   return MetadataAsValue::get(VMContext, ValueAsMetadata::get(V));
1133 }
1134
1135 Instruction *DIBuilder::insertDeclare(Value *Storage, DIVariable VarInfo,
1136                                       DIExpression Expr,
1137                                       Instruction *InsertBefore) {
1138   assert(VarInfo.isVariable() &&
1139          "empty or invalid DIVariable passed to dbg.declare");
1140   if (!DeclareFn)
1141     DeclareFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_declare);
1142
1143   trackIfUnresolved(VarInfo);
1144   trackIfUnresolved(Expr);
1145   Value *Args[] = {getDbgIntrinsicValueImpl(VMContext, Storage),
1146                    MetadataAsValue::get(VMContext, VarInfo),
1147                    MetadataAsValue::get(VMContext, Expr)};
1148   return CallInst::Create(DeclareFn, Args, "", InsertBefore);
1149 }
1150
1151 Instruction *DIBuilder::insertDeclare(Value *Storage, DIVariable VarInfo,
1152                                       DIExpression Expr,
1153                                       BasicBlock *InsertAtEnd) {
1154   assert(VarInfo.isVariable() &&
1155          "empty or invalid DIVariable passed to dbg.declare");
1156   if (!DeclareFn)
1157     DeclareFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_declare);
1158
1159   trackIfUnresolved(VarInfo);
1160   trackIfUnresolved(Expr);
1161   Value *Args[] = {getDbgIntrinsicValueImpl(VMContext, Storage),
1162                    MetadataAsValue::get(VMContext, VarInfo),
1163                    MetadataAsValue::get(VMContext, Expr)};
1164
1165   // If this block already has a terminator then insert this intrinsic
1166   // before the terminator.
1167   if (TerminatorInst *T = InsertAtEnd->getTerminator())
1168     return CallInst::Create(DeclareFn, Args, "", T);
1169   else
1170     return CallInst::Create(DeclareFn, Args, "", InsertAtEnd);
1171 }
1172
1173 Instruction *DIBuilder::insertDbgValueIntrinsic(Value *V, uint64_t Offset,
1174                                                 DIVariable VarInfo,
1175                                                 DIExpression Expr,
1176                                                 Instruction *InsertBefore) {
1177   assert(V && "no value passed to dbg.value");
1178   assert(VarInfo.isVariable() &&
1179          "empty or invalid DIVariable passed to dbg.value");
1180   if (!ValueFn)
1181     ValueFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_value);
1182
1183   trackIfUnresolved(VarInfo);
1184   trackIfUnresolved(Expr);
1185   Value *Args[] = {getDbgIntrinsicValueImpl(VMContext, V),
1186                    ConstantInt::get(Type::getInt64Ty(VMContext), Offset),
1187                    MetadataAsValue::get(VMContext, VarInfo),
1188                    MetadataAsValue::get(VMContext, Expr)};
1189   return CallInst::Create(ValueFn, Args, "", InsertBefore);
1190 }
1191
1192 Instruction *DIBuilder::insertDbgValueIntrinsic(Value *V, uint64_t Offset,
1193                                                 DIVariable VarInfo,
1194                                                 DIExpression Expr,
1195                                                 BasicBlock *InsertAtEnd) {
1196   assert(V && "no value passed to dbg.value");
1197   assert(VarInfo.isVariable() &&
1198          "empty or invalid DIVariable passed to dbg.value");
1199   if (!ValueFn)
1200     ValueFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_value);
1201
1202   trackIfUnresolved(VarInfo);
1203   trackIfUnresolved(Expr);
1204   Value *Args[] = {getDbgIntrinsicValueImpl(VMContext, V),
1205                    ConstantInt::get(Type::getInt64Ty(VMContext), Offset),
1206                    MetadataAsValue::get(VMContext, VarInfo),
1207                    MetadataAsValue::get(VMContext, Expr)};
1208   return CallInst::Create(ValueFn, Args, "", InsertAtEnd);
1209 }
1210
1211 void DIBuilder::replaceVTableHolder(DICompositeType &T, DICompositeType VTableHolder) {
1212   T.setContainingType(VTableHolder);
1213
1214   // If this didn't create a self-reference, just return.
1215   if (T != VTableHolder)
1216     return;
1217
1218   // Look for unresolved operands.  T has dropped RAUW support and is already
1219   // marked resolved, orphaning any cycles underneath it.
1220   assert(T->isResolved() && "Expected self-reference to be resolved");
1221   for (const MDOperand &O : T->operands())
1222     if (auto *N = dyn_cast_or_null<MDNode>(O))
1223       trackIfUnresolved(N);
1224 }
1225
1226 void DIBuilder::replaceArrays(DICompositeType &T, DIArray Elements,
1227                               DIArray TParams) {
1228   T.setArrays(Elements, TParams);
1229
1230   // If T isn't resolved, there's no problem.
1231   if (!T->isResolved())
1232     return;
1233
1234   // If "T" is resolved, it may be due to a self-reference cycle.  Track the
1235   // arrays explicitly if they're unresolved, or else the cycles will be
1236   // orphaned.
1237   if (Elements)
1238     trackIfUnresolved(Elements);
1239   if (TParams)
1240     trackIfUnresolved(TParams);
1241 }