LLVM  mainline
DIBuilder.cpp
Go to the documentation of this file.
00001 //===--- DIBuilder.cpp - Debug Information Builder ------------------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements the DIBuilder.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "llvm/IR/DIBuilder.h"
00015 #include "llvm/ADT/STLExtras.h"
00016 #include "llvm/IR/Constants.h"
00017 #include "llvm/IR/DebugInfo.h"
00018 #include "llvm/IR/IntrinsicInst.h"
00019 #include "llvm/IR/Module.h"
00020 #include "llvm/Support/Debug.h"
00021 #include "llvm/Support/Dwarf.h"
00022 
00023 using namespace llvm;
00024 using namespace llvm::dwarf;
00025 
00026 namespace {
00027 class HeaderBuilder {
00028   /// \brief Whether there are any fields yet.
00029   ///
00030   /// Note that this is not equivalent to \c Chars.empty(), since \a concat()
00031   /// may have been called already with an empty string.
00032   bool IsEmpty;
00033   SmallVector<char, 256> Chars;
00034 
00035 public:
00036   HeaderBuilder() : IsEmpty(true) {}
00037   HeaderBuilder(const HeaderBuilder &X) : IsEmpty(X.IsEmpty), Chars(X.Chars) {}
00038   HeaderBuilder(HeaderBuilder &&X)
00039       : IsEmpty(X.IsEmpty), Chars(std::move(X.Chars)) {}
00040 
00041   template <class Twineable> HeaderBuilder &concat(Twineable &&X) {
00042     if (IsEmpty)
00043       IsEmpty = false;
00044     else
00045       Chars.push_back(0);
00046     Twine(X).toVector(Chars);
00047     return *this;
00048   }
00049 
00050   MDString *get(LLVMContext &Context) const {
00051     return MDString::get(Context, StringRef(Chars.begin(), Chars.size()));
00052   }
00053 
00054   static HeaderBuilder get(unsigned Tag) {
00055     return HeaderBuilder().concat("0x" + Twine::utohexstr(Tag));
00056   }
00057 };
00058 }
00059 
00060 DIBuilder::DIBuilder(Module &m, bool AllowUnresolvedNodes)
00061     : M(m), VMContext(M.getContext()), TempEnumTypes(nullptr),
00062       TempRetainTypes(nullptr), TempSubprograms(nullptr), TempGVs(nullptr),
00063       DeclareFn(nullptr), ValueFn(nullptr),
00064       AllowUnresolvedNodes(AllowUnresolvedNodes) {}
00065 
00066 void DIBuilder::trackIfUnresolved(MDNode *N) {
00067   if (!N)
00068     return;
00069   if (N->isResolved())
00070     return;
00071 
00072   assert(AllowUnresolvedNodes && "Cannot handle unresolved nodes");
00073   UnresolvedNodes.emplace_back(N);
00074 }
00075 
00076 void DIBuilder::finalize() {
00077   TempEnumTypes->replaceAllUsesWith(MDTuple::get(VMContext, AllEnumTypes));
00078 
00079   SmallVector<Metadata *, 16> RetainValues;
00080   // Declarations and definitions of the same type may be retained. Some
00081   // clients RAUW these pairs, leaving duplicates in the retained types
00082   // list. Use a set to remove the duplicates while we transform the
00083   // TrackingVHs back into Values.
00084   SmallPtrSet<Metadata *, 16> RetainSet;
00085   for (unsigned I = 0, E = AllRetainTypes.size(); I < E; I++)
00086     if (RetainSet.insert(AllRetainTypes[I]).second)
00087       RetainValues.push_back(AllRetainTypes[I]);
00088   TempRetainTypes->replaceAllUsesWith(MDTuple::get(VMContext, RetainValues));
00089 
00090   MDSubprogramArray SPs = MDTuple::get(VMContext, AllSubprograms);
00091   TempSubprograms->replaceAllUsesWith(SPs.get());
00092   for (auto *SP : SPs) {
00093     if (MDTuple *Temp = SP->getVariables().get()) {
00094       const auto &PV = PreservedVariables.lookup(SP);
00095       SmallVector<Metadata *, 4> Variables(PV.begin(), PV.end());
00096       DIArray AV = getOrCreateArray(Variables);
00097       TempMDTuple(Temp)->replaceAllUsesWith(AV.get());
00098     }
00099   }
00100 
00101   TempGVs->replaceAllUsesWith(MDTuple::get(VMContext, AllGVs));
00102 
00103   TempImportedModules->replaceAllUsesWith(MDTuple::get(
00104       VMContext, SmallVector<Metadata *, 16>(AllImportedModules.begin(),
00105                                              AllImportedModules.end())));
00106 
00107   // Now that all temp nodes have been replaced or deleted, resolve remaining
00108   // cycles.
00109   for (const auto &N : UnresolvedNodes)
00110     if (N && !N->isResolved())
00111       N->resolveCycles();
00112   UnresolvedNodes.clear();
00113 
00114   // Can't handle unresolved nodes anymore.
00115   AllowUnresolvedNodes = false;
00116 }
00117 
00118 /// If N is compile unit return NULL otherwise return N.
00119 static MDScope *getNonCompileUnitScope(MDScope *N) {
00120   if (!N || isa<MDCompileUnit>(N))
00121     return nullptr;
00122   return cast<MDScope>(N);
00123 }
00124 
00125 MDCompileUnit *DIBuilder::createCompileUnit(
00126     unsigned Lang, StringRef Filename, StringRef Directory, StringRef Producer,
00127     bool isOptimized, StringRef Flags, unsigned RunTimeVer, StringRef SplitName,
00128     DebugEmissionKind Kind, bool EmitDebugInfo) {
00129 
00130   assert(((Lang <= dwarf::DW_LANG_Fortran08 && Lang >= dwarf::DW_LANG_C89) ||
00131           (Lang <= dwarf::DW_LANG_hi_user && Lang >= dwarf::DW_LANG_lo_user)) &&
00132          "Invalid Language tag");
00133   assert(!Filename.empty() &&
00134          "Unable to create compile unit without filename");
00135 
00136   // TODO: Once we make MDCompileUnit distinct, stop using temporaries here
00137   // (just start with operands assigned to nullptr).
00138   TempEnumTypes = MDTuple::getTemporary(VMContext, None);
00139   TempRetainTypes = MDTuple::getTemporary(VMContext, None);
00140   TempSubprograms = MDTuple::getTemporary(VMContext, None);
00141   TempGVs = MDTuple::getTemporary(VMContext, None);
00142   TempImportedModules = MDTuple::getTemporary(VMContext, None);
00143 
00144   // TODO: Switch to getDistinct().  We never want to merge compile units based
00145   // on contents.
00146   MDCompileUnit *CUNode = MDCompileUnit::get(
00147       VMContext, Lang, MDFile::get(VMContext, Filename, Directory), Producer,
00148       isOptimized, Flags, RunTimeVer, SplitName, Kind, TempEnumTypes.get(),
00149       TempRetainTypes.get(), TempSubprograms.get(), TempGVs.get(),
00150       TempImportedModules.get());
00151 
00152   // Create a named metadata so that it is easier to find cu in a module.
00153   // Note that we only generate this when the caller wants to actually
00154   // emit debug information. When we are only interested in tracking
00155   // source line locations throughout the backend, we prevent codegen from
00156   // emitting debug info in the final output by not generating llvm.dbg.cu.
00157   if (EmitDebugInfo) {
00158     NamedMDNode *NMD = M.getOrInsertNamedMetadata("llvm.dbg.cu");
00159     NMD->addOperand(CUNode);
00160   }
00161 
00162   trackIfUnresolved(CUNode);
00163   return CUNode;
00164 }
00165 
00166 static MDImportedEntity*
00167 createImportedModule(LLVMContext &C, dwarf::Tag Tag, MDScope* Context,
00168                      Metadata *NS, unsigned Line, StringRef Name,
00169                      SmallVectorImpl<TrackingMDNodeRef> &AllImportedModules) {
00170   auto *M =
00171       MDImportedEntity::get(C, Tag, Context, DebugNodeRef(NS), Line, Name);
00172   AllImportedModules.emplace_back(M);
00173   return M;
00174 }
00175 
00176 MDImportedEntity* DIBuilder::createImportedModule(MDScope* Context,
00177                                                  MDNamespace* NS,
00178                                                  unsigned Line) {
00179   return ::createImportedModule(VMContext, dwarf::DW_TAG_imported_module,
00180                                 Context, NS, Line, StringRef(), AllImportedModules);
00181 }
00182 
00183 MDImportedEntity* DIBuilder::createImportedModule(MDScope* Context,
00184                                                  MDImportedEntity* NS,
00185                                                  unsigned Line) {
00186   return ::createImportedModule(VMContext, dwarf::DW_TAG_imported_module,
00187                                 Context, NS, Line, StringRef(), AllImportedModules);
00188 }
00189 
00190 MDImportedEntity *DIBuilder::createImportedDeclaration(MDScope *Context,
00191                                                        DebugNode *Decl,
00192                                                        unsigned Line,
00193                                                        StringRef Name) {
00194   // Make sure to use the unique identifier based metadata reference for
00195   // types that have one.
00196   return ::createImportedModule(VMContext, dwarf::DW_TAG_imported_declaration,
00197                                 Context, DebugNodeRef::get(Decl), Line, Name,
00198                                 AllImportedModules);
00199 }
00200 
00201 MDFile* DIBuilder::createFile(StringRef Filename, StringRef Directory) {
00202   return MDFile::get(VMContext, Filename, Directory);
00203 }
00204 
00205 MDEnumerator *DIBuilder::createEnumerator(StringRef Name, int64_t Val) {
00206   assert(!Name.empty() && "Unable to create enumerator without name");
00207   return MDEnumerator::get(VMContext, Val, Name);
00208 }
00209 
00210 MDBasicType *DIBuilder::createUnspecifiedType(StringRef Name) {
00211   assert(!Name.empty() && "Unable to create type without name");
00212   return MDBasicType::get(VMContext, dwarf::DW_TAG_unspecified_type, Name);
00213 }
00214 
00215 MDBasicType *DIBuilder::createNullPtrType() {
00216   return createUnspecifiedType("decltype(nullptr)");
00217 }
00218 
00219 MDBasicType *DIBuilder::createBasicType(StringRef Name, uint64_t SizeInBits,
00220                                         uint64_t AlignInBits,
00221                                         unsigned Encoding) {
00222   assert(!Name.empty() && "Unable to create type without name");
00223   return MDBasicType::get(VMContext, dwarf::DW_TAG_base_type, Name, SizeInBits,
00224                           AlignInBits, Encoding);
00225 }
00226 
00227 MDDerivedType *DIBuilder::createQualifiedType(unsigned Tag, MDType *FromTy) {
00228   return MDDerivedType::get(VMContext, Tag, "", nullptr, 0, nullptr,
00229                             MDTypeRef::get(FromTy), 0, 0, 0, 0);
00230 }
00231 
00232 MDDerivedType *DIBuilder::createPointerType(MDType *PointeeTy,
00233                                             uint64_t SizeInBits,
00234                                             uint64_t AlignInBits,
00235                                             StringRef Name) {
00236   // FIXME: Why is there a name here?
00237   return MDDerivedType::get(VMContext, dwarf::DW_TAG_pointer_type, Name,
00238                             nullptr, 0, nullptr, MDTypeRef::get(PointeeTy),
00239                             SizeInBits, AlignInBits, 0, 0);
00240 }
00241 
00242 MDDerivedType *DIBuilder::createMemberPointerType(MDType *PointeeTy,
00243                                                   MDType *Base,
00244                                                   uint64_t SizeInBits,
00245                                                   uint64_t AlignInBits) {
00246   return MDDerivedType::get(VMContext, dwarf::DW_TAG_ptr_to_member_type, "",
00247                             nullptr, 0, nullptr, MDTypeRef::get(PointeeTy),
00248                             SizeInBits, AlignInBits, 0, 0, MDTypeRef::get(Base));
00249 }
00250 
00251 MDDerivedType *DIBuilder::createReferenceType(unsigned Tag, MDType *RTy) {
00252   assert(RTy && "Unable to create reference type");
00253   return MDDerivedType::get(VMContext, Tag, "", nullptr, 0, nullptr,
00254                             MDTypeRef::get(RTy), 0, 0, 0, 0);
00255 }
00256 
00257 MDDerivedType *DIBuilder::createTypedef(MDType *Ty, StringRef Name,
00258                                         MDFile *File, unsigned LineNo,
00259                                         MDScope *Context) {
00260   return MDDerivedType::get(VMContext, dwarf::DW_TAG_typedef, Name, File,
00261                             LineNo,
00262                             MDScopeRef::get(getNonCompileUnitScope(Context)),
00263                             MDTypeRef::get(Ty), 0, 0, 0, 0);
00264 }
00265 
00266 MDDerivedType *DIBuilder::createFriend(MDType *Ty, MDType *FriendTy) {
00267   assert(Ty && "Invalid type!");
00268   assert(FriendTy && "Invalid friend type!");
00269   return MDDerivedType::get(VMContext, dwarf::DW_TAG_friend, "", nullptr, 0,
00270                             MDTypeRef::get(Ty), MDTypeRef::get(FriendTy), 0, 0,
00271                             0, 0);
00272 }
00273 
00274 MDDerivedType *DIBuilder::createInheritance(MDType *Ty, MDType *BaseTy,
00275                                             uint64_t BaseOffset,
00276                                             unsigned Flags) {
00277   assert(Ty && "Unable to create inheritance");
00278   return MDDerivedType::get(VMContext, dwarf::DW_TAG_inheritance, "", nullptr,
00279                             0, MDTypeRef::get(Ty), MDTypeRef::get(BaseTy), 0, 0,
00280                             BaseOffset, Flags);
00281 }
00282 
00283 MDDerivedType *DIBuilder::createMemberType(MDScope *Scope, StringRef Name,
00284                                            MDFile *File, unsigned LineNumber,
00285                                            uint64_t SizeInBits,
00286                                            uint64_t AlignInBits,
00287                                            uint64_t OffsetInBits,
00288                                            unsigned Flags, MDType *Ty) {
00289   return MDDerivedType::get(
00290       VMContext, dwarf::DW_TAG_member, Name, File, LineNumber,
00291       MDScopeRef::get(getNonCompileUnitScope(Scope)), MDTypeRef::get(Ty),
00292       SizeInBits, AlignInBits, OffsetInBits, Flags);
00293 }
00294 
00295 static ConstantAsMetadata *getConstantOrNull(Constant *C) {
00296   if (C)
00297     return ConstantAsMetadata::get(C);
00298   return nullptr;
00299 }
00300 
00301 MDDerivedType *DIBuilder::createStaticMemberType(MDScope *Scope, StringRef Name,
00302                                                  MDFile *File,
00303                                                  unsigned LineNumber,
00304                                                  MDType *Ty, unsigned Flags,
00305                                                  llvm::Constant *Val) {
00306   Flags |= DebugNode::FlagStaticMember;
00307   return MDDerivedType::get(
00308       VMContext, dwarf::DW_TAG_member, Name, File, LineNumber,
00309       MDScopeRef::get(getNonCompileUnitScope(Scope)), MDTypeRef::get(Ty), 0, 0,
00310       0, Flags, getConstantOrNull(Val));
00311 }
00312 
00313 MDDerivedType *DIBuilder::createObjCIVar(StringRef Name, MDFile *File,
00314                                          unsigned LineNumber,
00315                                          uint64_t SizeInBits,
00316                                          uint64_t AlignInBits,
00317                                          uint64_t OffsetInBits, unsigned Flags,
00318                                          MDType *Ty, MDNode *PropertyNode) {
00319   return MDDerivedType::get(
00320       VMContext, dwarf::DW_TAG_member, Name, File, LineNumber,
00321       MDScopeRef::get(getNonCompileUnitScope(File)), MDTypeRef::get(Ty),
00322       SizeInBits, AlignInBits, OffsetInBits, Flags, PropertyNode);
00323 }
00324 
00325 MDObjCProperty *
00326 DIBuilder::createObjCProperty(StringRef Name, MDFile *File, unsigned LineNumber,
00327                               StringRef GetterName, StringRef SetterName,
00328                               unsigned PropertyAttributes, MDType *Ty) {
00329   return MDObjCProperty::get(VMContext, Name, File, LineNumber, GetterName,
00330                              SetterName, PropertyAttributes, Ty);
00331 }
00332 
00333 MDTemplateTypeParameter *
00334 DIBuilder::createTemplateTypeParameter(MDScope *Context, StringRef Name,
00335                                        MDType *Ty) {
00336   assert((!Context || isa<MDCompileUnit>(Context)) && "Expected compile unit");
00337   return MDTemplateTypeParameter::get(VMContext, Name, MDTypeRef::get(Ty));
00338 }
00339 
00340 static MDTemplateValueParameter *
00341 createTemplateValueParameterHelper(LLVMContext &VMContext, unsigned Tag,
00342                                    MDScope *Context, StringRef Name, MDType *Ty,
00343                                    Metadata *MD) {
00344   assert((!Context || isa<MDCompileUnit>(Context)) && "Expected compile unit");
00345   return MDTemplateValueParameter::get(VMContext, Tag, Name, MDTypeRef::get(Ty),
00346                                        MD);
00347 }
00348 
00349 MDTemplateValueParameter *
00350 DIBuilder::createTemplateValueParameter(MDScope *Context, StringRef Name,
00351                                         MDType *Ty, Constant *Val) {
00352   return createTemplateValueParameterHelper(
00353       VMContext, dwarf::DW_TAG_template_value_parameter, Context, Name, Ty,
00354       getConstantOrNull(Val));
00355 }
00356 
00357 MDTemplateValueParameter *
00358 DIBuilder::createTemplateTemplateParameter(MDScope *Context, StringRef Name,
00359                                            MDType *Ty, StringRef Val) {
00360   return createTemplateValueParameterHelper(
00361       VMContext, dwarf::DW_TAG_GNU_template_template_param, Context, Name, Ty,
00362       MDString::get(VMContext, Val));
00363 }
00364 
00365 MDTemplateValueParameter *
00366 DIBuilder::createTemplateParameterPack(MDScope *Context, StringRef Name,
00367                                        MDType *Ty, DIArray Val) {
00368   return createTemplateValueParameterHelper(
00369       VMContext, dwarf::DW_TAG_GNU_template_parameter_pack, Context, Name, Ty,
00370       Val.get());
00371 }
00372 
00373 MDCompositeType *DIBuilder::createClassType(
00374     MDScope *Context, StringRef Name, MDFile *File, unsigned LineNumber,
00375     uint64_t SizeInBits, uint64_t AlignInBits, uint64_t OffsetInBits,
00376     unsigned Flags, MDType *DerivedFrom, DIArray Elements, MDType *VTableHolder,
00377     MDNode *TemplateParams, StringRef UniqueIdentifier) {
00378   assert((!Context || isa<MDScope>(Context)) &&
00379          "createClassType should be called with a valid Context");
00380 
00381   auto *R = MDCompositeType::get(
00382       VMContext, dwarf::DW_TAG_structure_type, Name, File, LineNumber,
00383       MDScopeRef::get(getNonCompileUnitScope(Context)),
00384       MDTypeRef::get(DerivedFrom), SizeInBits, AlignInBits, OffsetInBits, Flags,
00385       Elements, 0, MDTypeRef::get(VTableHolder),
00386       cast_or_null<MDTuple>(TemplateParams), UniqueIdentifier);
00387   if (!UniqueIdentifier.empty())
00388     retainType(R);
00389   trackIfUnresolved(R);
00390   return R;
00391 }
00392 
00393 MDCompositeType *DIBuilder::createStructType(
00394     MDScope *Context, StringRef Name, MDFile *File, unsigned LineNumber,
00395     uint64_t SizeInBits, uint64_t AlignInBits, unsigned Flags,
00396     MDType *DerivedFrom, DIArray Elements, unsigned RunTimeLang,
00397     MDType *VTableHolder, StringRef UniqueIdentifier) {
00398   auto *R = MDCompositeType::get(
00399       VMContext, dwarf::DW_TAG_structure_type, Name, File, LineNumber,
00400       MDScopeRef::get(getNonCompileUnitScope(Context)),
00401       MDTypeRef::get(DerivedFrom), SizeInBits, AlignInBits, 0, Flags, Elements,
00402       RunTimeLang, MDTypeRef::get(VTableHolder), nullptr, UniqueIdentifier);
00403   if (!UniqueIdentifier.empty())
00404     retainType(R);
00405   trackIfUnresolved(R);
00406   return R;
00407 }
00408 
00409 MDCompositeType* DIBuilder::createUnionType(MDScope * Scope, StringRef Name,
00410                                            MDFile* File, unsigned LineNumber,
00411                                            uint64_t SizeInBits,
00412                                            uint64_t AlignInBits, unsigned Flags,
00413                                            DIArray Elements,
00414                                            unsigned RunTimeLang,
00415                                            StringRef UniqueIdentifier) {
00416   auto *R = MDCompositeType::get(
00417       VMContext, dwarf::DW_TAG_union_type, Name, File, LineNumber,
00418       MDScopeRef::get(getNonCompileUnitScope(Scope)), nullptr, SizeInBits,
00419       AlignInBits, 0, Flags, Elements, RunTimeLang, nullptr, nullptr,
00420       UniqueIdentifier);
00421   if (!UniqueIdentifier.empty())
00422     retainType(R);
00423   trackIfUnresolved(R);
00424   return R;
00425 }
00426 
00427 MDSubroutineType *DIBuilder::createSubroutineType(MDFile *File,
00428                                                   DITypeArray ParameterTypes,
00429                                                   unsigned Flags) {
00430   return MDSubroutineType::get(VMContext, Flags, ParameterTypes);
00431 }
00432 
00433 MDCompositeType *DIBuilder::createEnumerationType(
00434     MDScope *Scope, StringRef Name, MDFile *File, unsigned LineNumber,
00435     uint64_t SizeInBits, uint64_t AlignInBits, DIArray Elements,
00436     MDType *UnderlyingType, StringRef UniqueIdentifier) {
00437   auto *CTy = MDCompositeType::get(
00438       VMContext, dwarf::DW_TAG_enumeration_type, Name, File, LineNumber,
00439       MDScopeRef::get(getNonCompileUnitScope(Scope)),
00440       MDTypeRef::get(UnderlyingType), SizeInBits, AlignInBits, 0, 0, Elements,
00441       0, nullptr, nullptr, UniqueIdentifier);
00442   AllEnumTypes.push_back(CTy);
00443   if (!UniqueIdentifier.empty())
00444     retainType(CTy);
00445   trackIfUnresolved(CTy);
00446   return CTy;
00447 }
00448 
00449 MDCompositeType *DIBuilder::createArrayType(uint64_t Size, uint64_t AlignInBits,
00450                                             MDType *Ty, DIArray Subscripts) {
00451   auto *R = MDCompositeType::get(VMContext, dwarf::DW_TAG_array_type, "",
00452                                  nullptr, 0, nullptr, MDTypeRef::get(Ty), Size,
00453                                  AlignInBits, 0, 0, Subscripts, 0, nullptr);
00454   trackIfUnresolved(R);
00455   return R;
00456 }
00457 
00458 MDCompositeType *DIBuilder::createVectorType(uint64_t Size,
00459                                              uint64_t AlignInBits, MDType *Ty,
00460                                              DIArray Subscripts) {
00461   auto *R =
00462       MDCompositeType::get(VMContext, dwarf::DW_TAG_array_type, "", nullptr, 0,
00463                            nullptr, MDTypeRef::get(Ty), Size, AlignInBits, 0,
00464                            DebugNode::FlagVector, Subscripts, 0, nullptr);
00465   trackIfUnresolved(R);
00466   return R;
00467 }
00468 
00469 static MDType *createTypeWithFlags(LLVMContext &Context, MDType *Ty,
00470                                    unsigned FlagsToSet) {
00471   auto NewTy = Ty->clone();
00472   NewTy->setFlags(NewTy->getFlags() | FlagsToSet);
00473   return MDNode::replaceWithUniqued(std::move(NewTy));
00474 }
00475 
00476 MDType *DIBuilder::createArtificialType(MDType *Ty) {
00477   // FIXME: Restrict this to the nodes where it's valid.
00478   if (Ty->isArtificial())
00479     return Ty;
00480   return createTypeWithFlags(VMContext, Ty, DebugNode::FlagArtificial);
00481 }
00482 
00483 MDType *DIBuilder::createObjectPointerType(MDType *Ty) {
00484   // FIXME: Restrict this to the nodes where it's valid.
00485   if (Ty->isObjectPointer())
00486     return Ty;
00487   unsigned Flags = DebugNode::FlagObjectPointer | DebugNode::FlagArtificial;
00488   return createTypeWithFlags(VMContext, Ty, Flags);
00489 }
00490 
00491 void DIBuilder::retainType(MDType *T) {
00492   assert(T && "Expected non-null type");
00493   AllRetainTypes.emplace_back(T);
00494 }
00495 
00496 MDBasicType *DIBuilder::createUnspecifiedParameter() { return nullptr; }
00497 
00498 MDCompositeType*
00499 DIBuilder::createForwardDecl(unsigned Tag, StringRef Name, MDScope * Scope,
00500                              MDFile* F, unsigned Line, unsigned RuntimeLang,
00501                              uint64_t SizeInBits, uint64_t AlignInBits,
00502                              StringRef UniqueIdentifier) {
00503   // FIXME: Define in terms of createReplaceableForwardDecl() by calling
00504   // replaceWithUniqued().
00505   auto *RetTy = MDCompositeType::get(
00506       VMContext, Tag, Name, F, Line,
00507       MDScopeRef::get(getNonCompileUnitScope(Scope)), nullptr, SizeInBits,
00508       AlignInBits, 0, DebugNode::FlagFwdDecl, nullptr, RuntimeLang, nullptr,
00509       nullptr, UniqueIdentifier);
00510   if (!UniqueIdentifier.empty())
00511     retainType(RetTy);
00512   trackIfUnresolved(RetTy);
00513   return RetTy;
00514 }
00515 
00516 MDCompositeType* DIBuilder::createReplaceableCompositeType(
00517     unsigned Tag, StringRef Name, MDScope * Scope, MDFile* F, unsigned Line,
00518     unsigned RuntimeLang, uint64_t SizeInBits, uint64_t AlignInBits,
00519     unsigned Flags, StringRef UniqueIdentifier) {
00520   auto *RetTy = MDCompositeType::getTemporary(
00521                     VMContext, Tag, Name, F, Line,
00522                     MDScopeRef::get(getNonCompileUnitScope(Scope)), nullptr,
00523                     SizeInBits, AlignInBits, 0, Flags, nullptr, RuntimeLang,
00524                     nullptr, nullptr, UniqueIdentifier).release();
00525   if (!UniqueIdentifier.empty())
00526     retainType(RetTy);
00527   trackIfUnresolved(RetTy);
00528   return RetTy;
00529 }
00530 
00531 DIArray DIBuilder::getOrCreateArray(ArrayRef<Metadata *> Elements) {
00532   return MDTuple::get(VMContext, Elements);
00533 }
00534 
00535 DITypeArray DIBuilder::getOrCreateTypeArray(ArrayRef<Metadata *> Elements) {
00536   SmallVector<llvm::Metadata *, 16> Elts;
00537   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
00538     if (Elements[i] && isa<MDNode>(Elements[i]))
00539       Elts.push_back(MDTypeRef::get(cast<MDType>(Elements[i])));
00540     else
00541       Elts.push_back(Elements[i]);
00542   }
00543   return DITypeArray(MDNode::get(VMContext, Elts));
00544 }
00545 
00546 MDSubrange *DIBuilder::getOrCreateSubrange(int64_t Lo, int64_t Count) {
00547   return MDSubrange::get(VMContext, Count, Lo);
00548 }
00549 
00550 static void checkGlobalVariableScope(MDScope * Context) {
00551 #ifndef NDEBUG
00552   if (auto *CT =
00553           dyn_cast_or_null<MDCompositeType>(getNonCompileUnitScope(Context)))
00554     assert(CT->getIdentifier().empty() &&
00555            "Context of a global variable should not be a type with identifier");
00556 #endif
00557 }
00558 
00559 MDGlobalVariable *DIBuilder::createGlobalVariable(
00560     MDScope *Context, StringRef Name, StringRef LinkageName, MDFile *F,
00561     unsigned LineNumber, MDType *Ty, bool isLocalToUnit, Constant *Val,
00562     MDNode *Decl) {
00563   checkGlobalVariableScope(Context);
00564 
00565   auto *N = MDGlobalVariable::get(VMContext, cast_or_null<MDScope>(Context),
00566                                   Name, LinkageName, F, LineNumber,
00567                                   MDTypeRef::get(Ty), isLocalToUnit, true, Val,
00568                                   cast_or_null<MDDerivedType>(Decl));
00569   AllGVs.push_back(N);
00570   return N;
00571 }
00572 
00573 MDGlobalVariable *DIBuilder::createTempGlobalVariableFwdDecl(
00574     MDScope *Context, StringRef Name, StringRef LinkageName, MDFile *F,
00575     unsigned LineNumber, MDType *Ty, bool isLocalToUnit, Constant *Val,
00576     MDNode *Decl) {
00577   checkGlobalVariableScope(Context);
00578 
00579   return MDGlobalVariable::getTemporary(
00580              VMContext, cast_or_null<MDScope>(Context), Name, LinkageName, F,
00581              LineNumber, MDTypeRef::get(Ty), isLocalToUnit, false, Val,
00582              cast_or_null<MDDerivedType>(Decl))
00583       .release();
00584 }
00585 
00586 MDLocalVariable *DIBuilder::createLocalVariable(
00587     unsigned Tag, MDScope *Scope, StringRef Name, MDFile *File, unsigned LineNo,
00588     MDType *Ty, bool AlwaysPreserve, unsigned Flags, unsigned ArgNo) {
00589   // FIXME: Why getNonCompileUnitScope()?
00590   // FIXME: Why is "!Context" okay here?
00591   // FIXME: WHy doesn't this check for a subprogram or lexical block (AFAICT
00592   // the only valid scopes)?
00593   MDScope* Context = getNonCompileUnitScope(Scope);
00594 
00595   auto *Node = MDLocalVariable::get(
00596       VMContext, Tag, cast_or_null<MDLocalScope>(Context), Name, File, LineNo,
00597       MDTypeRef::get(Ty), ArgNo, Flags);
00598   if (AlwaysPreserve) {
00599     // The optimizer may remove local variable. If there is an interest
00600     // to preserve variable info in such situation then stash it in a
00601     // named mdnode.
00602     MDSubprogram *Fn = getDISubprogram(Scope);
00603     assert(Fn && "Missing subprogram for local variable");
00604     PreservedVariables[Fn].emplace_back(Node);
00605   }
00606   return Node;
00607 }
00608 
00609 MDExpression* DIBuilder::createExpression(ArrayRef<uint64_t> Addr) {
00610   return MDExpression::get(VMContext, Addr);
00611 }
00612 
00613 MDExpression* DIBuilder::createExpression(ArrayRef<int64_t> Signed) {
00614   // TODO: Remove the callers of this signed version and delete.
00615   SmallVector<uint64_t, 8> Addr(Signed.begin(), Signed.end());
00616   return createExpression(Addr);
00617 }
00618 
00619 MDExpression* DIBuilder::createBitPieceExpression(unsigned OffsetInBytes,
00620                                                  unsigned SizeInBytes) {
00621   uint64_t Addr[] = {dwarf::DW_OP_bit_piece, OffsetInBytes, SizeInBytes};
00622   return MDExpression::get(VMContext, Addr);
00623 }
00624 
00625 MDSubprogram* DIBuilder::createFunction(DIScopeRef Context, StringRef Name,
00626                                        StringRef LinkageName, MDFile* File,
00627                                        unsigned LineNo, MDSubroutineType* Ty,
00628                                        bool isLocalToUnit, bool isDefinition,
00629                                        unsigned ScopeLine, unsigned Flags,
00630                                        bool isOptimized, Function *Fn,
00631                                        MDNode *TParams, MDNode *Decl) {
00632   // dragonegg does not generate identifier for types, so using an empty map
00633   // to resolve the context should be fine.
00634   DITypeIdentifierMap EmptyMap;
00635   return createFunction(Context.resolve(EmptyMap), Name, LinkageName, File,
00636                         LineNo, Ty, isLocalToUnit, isDefinition, ScopeLine,
00637                         Flags, isOptimized, Fn, TParams, Decl);
00638 }
00639 
00640 MDSubprogram* DIBuilder::createFunction(MDScope * Context, StringRef Name,
00641                                        StringRef LinkageName, MDFile* File,
00642                                        unsigned LineNo, MDSubroutineType* Ty,
00643                                        bool isLocalToUnit, bool isDefinition,
00644                                        unsigned ScopeLine, unsigned Flags,
00645                                        bool isOptimized, Function *Fn,
00646                                        MDNode *TParams, MDNode *Decl) {
00647   assert(Ty->getTag() == dwarf::DW_TAG_subroutine_type &&
00648          "function types should be subroutines");
00649   auto *Node = MDSubprogram::get(
00650       VMContext, MDScopeRef::get(getNonCompileUnitScope(Context)), Name,
00651       LinkageName, File, LineNo, Ty,
00652       isLocalToUnit, isDefinition, ScopeLine, nullptr, 0, 0, Flags, isOptimized,
00653       Fn, cast_or_null<MDTuple>(TParams), cast_or_null<MDSubprogram>(Decl),
00654       MDTuple::getTemporary(VMContext, None).release());
00655 
00656   if (isDefinition)
00657     AllSubprograms.push_back(Node);
00658   trackIfUnresolved(Node);
00659   return Node;
00660 }
00661 
00662 MDSubprogram*
00663 DIBuilder::createTempFunctionFwdDecl(MDScope * Context, StringRef Name,
00664                                      StringRef LinkageName, MDFile* File,
00665                                      unsigned LineNo, MDSubroutineType* Ty,
00666                                      bool isLocalToUnit, bool isDefinition,
00667                                      unsigned ScopeLine, unsigned Flags,
00668                                      bool isOptimized, Function *Fn,
00669                                      MDNode *TParams, MDNode *Decl) {
00670   return MDSubprogram::getTemporary(
00671              VMContext, MDScopeRef::get(getNonCompileUnitScope(Context)), Name,
00672              LinkageName, File, LineNo, Ty,
00673              isLocalToUnit, isDefinition, ScopeLine, nullptr, 0, 0, Flags,
00674              isOptimized, Fn, cast_or_null<MDTuple>(TParams),
00675              cast_or_null<MDSubprogram>(Decl), nullptr).release();
00676 }
00677 
00678 MDSubprogram *
00679 DIBuilder::createMethod(MDScope *Context, StringRef Name, StringRef LinkageName,
00680                         MDFile *F, unsigned LineNo, MDSubroutineType *Ty,
00681                         bool isLocalToUnit, bool isDefinition, unsigned VK,
00682                         unsigned VIndex, MDType *VTableHolder, unsigned Flags,
00683                         bool isOptimized, Function *Fn, MDNode *TParam) {
00684   assert(Ty->getTag() == dwarf::DW_TAG_subroutine_type &&
00685          "function types should be subroutines");
00686   assert(getNonCompileUnitScope(Context) &&
00687          "Methods should have both a Context and a context that isn't "
00688          "the compile unit.");
00689   // FIXME: Do we want to use different scope/lines?
00690   auto *SP = MDSubprogram::get(
00691       VMContext, MDScopeRef::get(cast<MDScope>(Context)), Name, LinkageName, F,
00692       LineNo, Ty, isLocalToUnit, isDefinition, LineNo,
00693       MDTypeRef::get(VTableHolder), VK, VIndex, Flags, isOptimized, Fn,
00694       cast_or_null<MDTuple>(TParam), nullptr, nullptr);
00695 
00696   if (isDefinition)
00697     AllSubprograms.push_back(SP);
00698   trackIfUnresolved(SP);
00699   return SP;
00700 }
00701 
00702 MDNamespace* DIBuilder::createNameSpace(MDScope * Scope, StringRef Name,
00703                                        MDFile* File, unsigned LineNo) {
00704   return MDNamespace::get(VMContext, getNonCompileUnitScope(Scope), File, Name,
00705                           LineNo);
00706 }
00707 
00708 MDLexicalBlockFile* DIBuilder::createLexicalBlockFile(MDScope * Scope,
00709                                                      MDFile* File,
00710                                                      unsigned Discriminator) {
00711   return MDLexicalBlockFile::get(VMContext, Scope, File, Discriminator);
00712 }
00713 
00714 MDLexicalBlock* DIBuilder::createLexicalBlock(MDScope * Scope, MDFile* File,
00715                                              unsigned Line, unsigned Col) {
00716   // Make these distinct, to avoid merging two lexical blocks on the same
00717   // file/line/column.
00718   return MDLexicalBlock::getDistinct(VMContext, getNonCompileUnitScope(Scope),
00719                                      File, Line, Col);
00720 }
00721 
00722 static Value *getDbgIntrinsicValueImpl(LLVMContext &VMContext, Value *V) {
00723   assert(V && "no value passed to dbg intrinsic");
00724   return MetadataAsValue::get(VMContext, ValueAsMetadata::get(V));
00725 }
00726 
00727 static Instruction *withDebugLoc(Instruction *I, const MDLocation *DL) {
00728   I->setDebugLoc(const_cast<MDLocation *>(DL));
00729   return I;
00730 }
00731 
00732 Instruction *DIBuilder::insertDeclare(Value *Storage, MDLocalVariable* VarInfo,
00733                                       MDExpression* Expr, const MDLocation *DL,
00734                                       Instruction *InsertBefore) {
00735   assert(VarInfo && "empty or invalid MDLocalVariable* passed to dbg.declare");
00736   assert(DL && "Expected debug loc");
00737   assert(DL->getScope()->getSubprogram() ==
00738              VarInfo->getScope()->getSubprogram() &&
00739          "Expected matching subprograms");
00740   if (!DeclareFn)
00741     DeclareFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_declare);
00742 
00743   trackIfUnresolved(VarInfo);
00744   trackIfUnresolved(Expr);
00745   Value *Args[] = {getDbgIntrinsicValueImpl(VMContext, Storage),
00746                    MetadataAsValue::get(VMContext, VarInfo),
00747                    MetadataAsValue::get(VMContext, Expr)};
00748   return withDebugLoc(CallInst::Create(DeclareFn, Args, "", InsertBefore), DL);
00749 }
00750 
00751 Instruction *DIBuilder::insertDeclare(Value *Storage, MDLocalVariable* VarInfo,
00752                                       MDExpression* Expr, const MDLocation *DL,
00753                                       BasicBlock *InsertAtEnd) {
00754   assert(VarInfo && "empty or invalid MDLocalVariable* passed to dbg.declare");
00755   assert(DL && "Expected debug loc");
00756   assert(DL->getScope()->getSubprogram() ==
00757              VarInfo->getScope()->getSubprogram() &&
00758          "Expected matching subprograms");
00759   if (!DeclareFn)
00760     DeclareFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_declare);
00761 
00762   trackIfUnresolved(VarInfo);
00763   trackIfUnresolved(Expr);
00764   Value *Args[] = {getDbgIntrinsicValueImpl(VMContext, Storage),
00765                    MetadataAsValue::get(VMContext, VarInfo),
00766                    MetadataAsValue::get(VMContext, Expr)};
00767 
00768   // If this block already has a terminator then insert this intrinsic
00769   // before the terminator.
00770   if (TerminatorInst *T = InsertAtEnd->getTerminator())
00771     return withDebugLoc(CallInst::Create(DeclareFn, Args, "", T), DL);
00772   return withDebugLoc(CallInst::Create(DeclareFn, Args, "", InsertAtEnd), DL);
00773 }
00774 
00775 Instruction *DIBuilder::insertDbgValueIntrinsic(Value *V, uint64_t Offset,
00776                                                 MDLocalVariable* VarInfo,
00777                                                 MDExpression* Expr,
00778                                                 const MDLocation *DL,
00779                                                 Instruction *InsertBefore) {
00780   assert(V && "no value passed to dbg.value");
00781   assert(VarInfo && "empty or invalid MDLocalVariable* passed to dbg.value");
00782   assert(DL && "Expected debug loc");
00783   assert(DL->getScope()->getSubprogram() ==
00784              VarInfo->getScope()->getSubprogram() &&
00785          "Expected matching subprograms");
00786   if (!ValueFn)
00787     ValueFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_value);
00788 
00789   trackIfUnresolved(VarInfo);
00790   trackIfUnresolved(Expr);
00791   Value *Args[] = {getDbgIntrinsicValueImpl(VMContext, V),
00792                    ConstantInt::get(Type::getInt64Ty(VMContext), Offset),
00793                    MetadataAsValue::get(VMContext, VarInfo),
00794                    MetadataAsValue::get(VMContext, Expr)};
00795   return withDebugLoc(CallInst::Create(ValueFn, Args, "", InsertBefore), DL);
00796 }
00797 
00798 Instruction *DIBuilder::insertDbgValueIntrinsic(Value *V, uint64_t Offset,
00799                                                 MDLocalVariable* VarInfo,
00800                                                 MDExpression* Expr,
00801                                                 const MDLocation *DL,
00802                                                 BasicBlock *InsertAtEnd) {
00803   assert(V && "no value passed to dbg.value");
00804   assert(VarInfo && "empty or invalid MDLocalVariable* passed to dbg.value");
00805   assert(DL && "Expected debug loc");
00806   assert(DL->getScope()->getSubprogram() ==
00807              VarInfo->getScope()->getSubprogram() &&
00808          "Expected matching subprograms");
00809   if (!ValueFn)
00810     ValueFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_value);
00811 
00812   trackIfUnresolved(VarInfo);
00813   trackIfUnresolved(Expr);
00814   Value *Args[] = {getDbgIntrinsicValueImpl(VMContext, V),
00815                    ConstantInt::get(Type::getInt64Ty(VMContext), Offset),
00816                    MetadataAsValue::get(VMContext, VarInfo),
00817                    MetadataAsValue::get(VMContext, Expr)};
00818 
00819   return withDebugLoc(CallInst::Create(ValueFn, Args, "", InsertAtEnd), DL);
00820 }
00821 
00822 void DIBuilder::replaceVTableHolder(MDCompositeType* &T, MDCompositeType* VTableHolder) {
00823   {
00824     TypedTrackingMDRef<MDCompositeType> N(T);
00825     N->replaceVTableHolder(MDTypeRef::get(VTableHolder));
00826     T = N.get();
00827   }
00828 
00829   // If this didn't create a self-reference, just return.
00830   if (T != VTableHolder)
00831     return;
00832 
00833   // Look for unresolved operands.  T will drop RAUW support, orphaning any
00834   // cycles underneath it.
00835   if (T->isResolved())
00836     for (const MDOperand &O : T->operands())
00837       if (auto *N = dyn_cast_or_null<MDNode>(O))
00838         trackIfUnresolved(N);
00839 }
00840 
00841 void DIBuilder::replaceArrays(MDCompositeType* &T, DIArray Elements,
00842                               DIArray TParams) {
00843   {
00844     TypedTrackingMDRef<MDCompositeType> N(T);
00845     if (Elements)
00846       N->replaceElements(Elements);
00847     if (TParams)
00848       N->replaceTemplateParams(MDTemplateParameterArray(TParams));
00849     T = N.get();
00850   }
00851 
00852   // If T isn't resolved, there's no problem.
00853   if (!T->isResolved())
00854     return;
00855 
00856   // If "T" is resolved, it may be due to a self-reference cycle.  Track the
00857   // arrays explicitly if they're unresolved, or else the cycles will be
00858   // orphaned.
00859   if (Elements)
00860     trackIfUnresolved(Elements.get());
00861   if (TParams)
00862     trackIfUnresolved(TParams.get());
00863 }