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