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