DIBuilder.cpp 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879
  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. #include "llvm/IR/DIBuilder.h"
  14. #include "llvm/ADT/STLExtras.h"
  15. #include "llvm/IR/Constants.h"
  16. #include "llvm/IR/DebugInfo.h"
  17. #include "llvm/IR/IntrinsicInst.h"
  18. #include "llvm/IR/Module.h"
  19. #include "llvm/Support/Debug.h"
  20. #include "llvm/Support/Dwarf.h"
  21. using namespace llvm;
  22. using namespace llvm::dwarf;
  23. namespace {
  24. class HeaderBuilder {
  25. /// \brief Whether there are any fields yet.
  26. ///
  27. /// Note that this is not equivalent to \c Chars.empty(), since \a concat()
  28. /// may have been called already with an empty string.
  29. bool IsEmpty;
  30. SmallVector<char, 256> Chars;
  31. public:
  32. HeaderBuilder() : IsEmpty(true) {}
  33. HeaderBuilder(const HeaderBuilder &X) : IsEmpty(X.IsEmpty), Chars(X.Chars) {}
  34. HeaderBuilder(HeaderBuilder &&X)
  35. : IsEmpty(X.IsEmpty), Chars(std::move(X.Chars)) {}
  36. template <class Twineable> HeaderBuilder &concat(Twineable &&X) {
  37. if (IsEmpty)
  38. IsEmpty = false;
  39. else
  40. Chars.push_back(0);
  41. Twine(X).toVector(Chars);
  42. return *this;
  43. }
  44. MDString *get(LLVMContext &Context) const {
  45. return MDString::get(Context, StringRef(Chars.begin(), Chars.size()));
  46. }
  47. static HeaderBuilder get(unsigned Tag) {
  48. return HeaderBuilder().concat("0x" + Twine::utohexstr(Tag));
  49. }
  50. };
  51. }
  52. DIBuilder::DIBuilder(Module &m, bool AllowUnresolvedNodes)
  53. : M(m), VMContext(M.getContext()), CUNode(nullptr),
  54. DeclareFn(nullptr), ValueFn(nullptr),
  55. AllowUnresolvedNodes(AllowUnresolvedNodes) {}
  56. void DIBuilder::trackIfUnresolved(MDNode *N) {
  57. if (!N)
  58. return;
  59. if (N->isResolved())
  60. return;
  61. assert(AllowUnresolvedNodes && "Cannot handle unresolved nodes");
  62. UnresolvedNodes.emplace_back(N);
  63. }
  64. void DIBuilder::finalize() {
  65. if (!CUNode) {
  66. assert(!AllowUnresolvedNodes &&
  67. "creating type nodes without a CU is not supported");
  68. return;
  69. }
  70. CUNode->replaceEnumTypes(MDTuple::get(VMContext, AllEnumTypes));
  71. SmallVector<Metadata *, 16> RetainValues;
  72. // Declarations and definitions of the same type may be retained. Some
  73. // clients RAUW these pairs, leaving duplicates in the retained types
  74. // list. Use a set to remove the duplicates while we transform the
  75. // TrackingVHs back into Values.
  76. SmallPtrSet<Metadata *, 16> RetainSet;
  77. for (unsigned I = 0, E = AllRetainTypes.size(); I < E; I++)
  78. if (RetainSet.insert(AllRetainTypes[I]).second)
  79. RetainValues.push_back(AllRetainTypes[I]);
  80. if (!RetainValues.empty())
  81. CUNode->replaceRetainedTypes(MDTuple::get(VMContext, RetainValues));
  82. DISubprogramArray SPs = MDTuple::get(VMContext, AllSubprograms);
  83. if (!AllSubprograms.empty())
  84. CUNode->replaceSubprograms(SPs.get());
  85. for (auto *SP : SPs) {
  86. if (MDTuple *Temp = SP->getVariables().get()) {
  87. const auto &PV = PreservedVariables.lookup(SP);
  88. SmallVector<Metadata *, 4> Variables(PV.begin(), PV.end());
  89. DINodeArray AV = getOrCreateArray(Variables);
  90. TempMDTuple(Temp)->replaceAllUsesWith(AV.get());
  91. }
  92. }
  93. if (!AllGVs.empty())
  94. CUNode->replaceGlobalVariables(MDTuple::get(VMContext, AllGVs));
  95. if (!AllImportedModules.empty())
  96. CUNode->replaceImportedEntities(MDTuple::get(
  97. VMContext, SmallVector<Metadata *, 16>(AllImportedModules.begin(),
  98. AllImportedModules.end())));
  99. // Now that all temp nodes have been replaced or deleted, resolve remaining
  100. // cycles.
  101. for (const auto &N : UnresolvedNodes)
  102. if (N && !N->isResolved())
  103. N->resolveCycles();
  104. UnresolvedNodes.clear();
  105. // Can't handle unresolved nodes anymore.
  106. AllowUnresolvedNodes = false;
  107. }
  108. /// If N is compile unit return NULL otherwise return N.
  109. static DIScope *getNonCompileUnitScope(DIScope *N) {
  110. if (!N || isa<DICompileUnit>(N))
  111. return nullptr;
  112. return cast<DIScope>(N);
  113. }
  114. DICompileUnit *DIBuilder::createCompileUnit(
  115. unsigned Lang, StringRef Filename, StringRef Directory, StringRef Producer,
  116. bool isOptimized, StringRef Flags, unsigned RunTimeVer, StringRef SplitName,
  117. DebugEmissionKind Kind, uint64_t DWOId, bool EmitDebugInfo) {
  118. assert(((Lang <= dwarf::DW_LANG_Fortran08 && Lang >= dwarf::DW_LANG_C89) ||
  119. (Lang <= dwarf::DW_LANG_hi_user && Lang >= dwarf::DW_LANG_lo_user)) &&
  120. "Invalid Language tag");
  121. assert(!Filename.empty() &&
  122. "Unable to create compile unit without filename");
  123. assert(!CUNode && "Can only make one compile unit per DIBuilder instance");
  124. CUNode = DICompileUnit::getDistinct(
  125. VMContext, Lang, DIFile::get(VMContext, Filename, Directory), Producer,
  126. isOptimized, Flags, RunTimeVer, SplitName, Kind, nullptr,
  127. nullptr, nullptr, nullptr, nullptr, DWOId);
  128. // Create a named metadata so that it is easier to find cu in a module.
  129. // Note that we only generate this when the caller wants to actually
  130. // emit debug information. When we are only interested in tracking
  131. // source line locations throughout the backend, we prevent codegen from
  132. // emitting debug info in the final output by not generating llvm.dbg.cu.
  133. if (EmitDebugInfo) {
  134. NamedMDNode *NMD = M.getOrInsertNamedMetadata("llvm.dbg.cu");
  135. NMD->addOperand(CUNode);
  136. }
  137. trackIfUnresolved(CUNode);
  138. return CUNode;
  139. }
  140. static DIImportedEntity *
  141. createImportedModule(LLVMContext &C, dwarf::Tag Tag, DIScope *Context,
  142. Metadata *NS, unsigned Line, StringRef Name,
  143. SmallVectorImpl<TrackingMDNodeRef> &AllImportedModules) {
  144. auto *M = DIImportedEntity::get(C, Tag, Context, DINodeRef(NS), Line, Name);
  145. AllImportedModules.emplace_back(M);
  146. return M;
  147. }
  148. DIImportedEntity *DIBuilder::createImportedModule(DIScope *Context,
  149. DINamespace *NS,
  150. unsigned Line) {
  151. return ::createImportedModule(VMContext, dwarf::DW_TAG_imported_module,
  152. Context, NS, Line, StringRef(), AllImportedModules);
  153. }
  154. DIImportedEntity *DIBuilder::createImportedModule(DIScope *Context,
  155. DIImportedEntity *NS,
  156. unsigned Line) {
  157. return ::createImportedModule(VMContext, dwarf::DW_TAG_imported_module,
  158. Context, NS, Line, StringRef(), AllImportedModules);
  159. }
  160. DIImportedEntity *DIBuilder::createImportedModule(DIScope *Context, DIModule *M,
  161. unsigned Line) {
  162. return ::createImportedModule(VMContext, dwarf::DW_TAG_imported_module,
  163. Context, M, Line, StringRef(), AllImportedModules);
  164. }
  165. DIImportedEntity *DIBuilder::createImportedDeclaration(DIScope *Context,
  166. DINode *Decl,
  167. unsigned Line,
  168. StringRef Name) {
  169. // Make sure to use the unique identifier based metadata reference for
  170. // types that have one.
  171. return ::createImportedModule(VMContext, dwarf::DW_TAG_imported_declaration,
  172. Context, DINodeRef::get(Decl), Line, Name,
  173. AllImportedModules);
  174. }
  175. DIFile *DIBuilder::createFile(StringRef Filename, StringRef Directory) {
  176. return DIFile::get(VMContext, Filename, Directory);
  177. }
  178. DIEnumerator *DIBuilder::createEnumerator(StringRef Name, int64_t Val) {
  179. assert(!Name.empty() && "Unable to create enumerator without name");
  180. return DIEnumerator::get(VMContext, Val, Name);
  181. }
  182. DIBasicType *DIBuilder::createUnspecifiedType(StringRef Name) {
  183. assert(!Name.empty() && "Unable to create type without name");
  184. return DIBasicType::get(VMContext, dwarf::DW_TAG_unspecified_type, Name);
  185. }
  186. DIBasicType *DIBuilder::createNullPtrType() {
  187. return createUnspecifiedType("decltype(nullptr)");
  188. }
  189. DIBasicType *DIBuilder::createBasicType(StringRef Name, uint64_t SizeInBits,
  190. uint64_t AlignInBits,
  191. unsigned Encoding) {
  192. assert(!Name.empty() && "Unable to create type without name");
  193. return DIBasicType::get(VMContext, dwarf::DW_TAG_base_type, Name, SizeInBits,
  194. AlignInBits, Encoding);
  195. }
  196. DIDerivedType *DIBuilder::createQualifiedType(unsigned Tag, DIType *FromTy) {
  197. return DIDerivedType::get(VMContext, Tag, "", nullptr, 0, nullptr,
  198. DITypeRef::get(FromTy), 0, 0, 0, 0);
  199. }
  200. DIDerivedType *DIBuilder::createPointerType(DIType *PointeeTy,
  201. uint64_t SizeInBits,
  202. uint64_t AlignInBits,
  203. StringRef Name) {
  204. // FIXME: Why is there a name here?
  205. return DIDerivedType::get(VMContext, dwarf::DW_TAG_pointer_type, Name,
  206. nullptr, 0, nullptr, DITypeRef::get(PointeeTy),
  207. SizeInBits, AlignInBits, 0, 0);
  208. }
  209. DIDerivedType *DIBuilder::createMemberPointerType(DIType *PointeeTy,
  210. DIType *Base,
  211. uint64_t SizeInBits,
  212. uint64_t AlignInBits) {
  213. return DIDerivedType::get(VMContext, dwarf::DW_TAG_ptr_to_member_type, "",
  214. nullptr, 0, nullptr, DITypeRef::get(PointeeTy),
  215. SizeInBits, AlignInBits, 0, 0,
  216. DITypeRef::get(Base));
  217. }
  218. DIDerivedType *DIBuilder::createReferenceType(unsigned Tag, DIType *RTy) {
  219. assert(RTy && "Unable to create reference type");
  220. return DIDerivedType::get(VMContext, Tag, "", nullptr, 0, nullptr,
  221. DITypeRef::get(RTy), 0, 0, 0, 0);
  222. }
  223. DIDerivedType *DIBuilder::createTypedef(DIType *Ty, StringRef Name,
  224. DIFile *File, unsigned LineNo,
  225. DIScope *Context) {
  226. return DIDerivedType::get(VMContext, dwarf::DW_TAG_typedef, Name, File,
  227. LineNo,
  228. DIScopeRef::get(getNonCompileUnitScope(Context)),
  229. DITypeRef::get(Ty), 0, 0, 0, 0);
  230. }
  231. DIDerivedType *DIBuilder::createFriend(DIType *Ty, DIType *FriendTy) {
  232. assert(Ty && "Invalid type!");
  233. assert(FriendTy && "Invalid friend type!");
  234. return DIDerivedType::get(VMContext, dwarf::DW_TAG_friend, "", nullptr, 0,
  235. DITypeRef::get(Ty), DITypeRef::get(FriendTy), 0, 0,
  236. 0, 0);
  237. }
  238. DIDerivedType *DIBuilder::createInheritance(DIType *Ty, DIType *BaseTy,
  239. uint64_t BaseOffset,
  240. unsigned Flags) {
  241. assert(Ty && "Unable to create inheritance");
  242. return DIDerivedType::get(VMContext, dwarf::DW_TAG_inheritance, "", nullptr,
  243. 0, DITypeRef::get(Ty), DITypeRef::get(BaseTy), 0, 0,
  244. BaseOffset, Flags);
  245. }
  246. DIDerivedType *DIBuilder::createMemberType(DIScope *Scope, StringRef Name,
  247. DIFile *File, unsigned LineNumber,
  248. uint64_t SizeInBits,
  249. uint64_t AlignInBits,
  250. uint64_t OffsetInBits,
  251. unsigned Flags, DIType *Ty) {
  252. return DIDerivedType::get(
  253. VMContext, dwarf::DW_TAG_member, Name, File, LineNumber,
  254. DIScopeRef::get(getNonCompileUnitScope(Scope)), DITypeRef::get(Ty),
  255. SizeInBits, AlignInBits, OffsetInBits, Flags);
  256. }
  257. static ConstantAsMetadata *getConstantOrNull(Constant *C) {
  258. if (C)
  259. return ConstantAsMetadata::get(C);
  260. return nullptr;
  261. }
  262. DIDerivedType *DIBuilder::createStaticMemberType(DIScope *Scope, StringRef Name,
  263. DIFile *File,
  264. unsigned LineNumber,
  265. DIType *Ty, unsigned Flags,
  266. llvm::Constant *Val) {
  267. Flags |= DINode::FlagStaticMember;
  268. return DIDerivedType::get(
  269. VMContext, dwarf::DW_TAG_member, Name, File, LineNumber,
  270. DIScopeRef::get(getNonCompileUnitScope(Scope)), DITypeRef::get(Ty), 0, 0,
  271. 0, Flags, getConstantOrNull(Val));
  272. }
  273. DIDerivedType *DIBuilder::createObjCIVar(StringRef Name, DIFile *File,
  274. unsigned LineNumber,
  275. uint64_t SizeInBits,
  276. uint64_t AlignInBits,
  277. uint64_t OffsetInBits, unsigned Flags,
  278. DIType *Ty, MDNode *PropertyNode) {
  279. return DIDerivedType::get(
  280. VMContext, dwarf::DW_TAG_member, Name, File, LineNumber,
  281. DIScopeRef::get(getNonCompileUnitScope(File)), DITypeRef::get(Ty),
  282. SizeInBits, AlignInBits, OffsetInBits, Flags, PropertyNode);
  283. }
  284. DIObjCProperty *
  285. DIBuilder::createObjCProperty(StringRef Name, DIFile *File, unsigned LineNumber,
  286. StringRef GetterName, StringRef SetterName,
  287. unsigned PropertyAttributes, DIType *Ty) {
  288. return DIObjCProperty::get(VMContext, Name, File, LineNumber, GetterName,
  289. SetterName, PropertyAttributes,
  290. DITypeRef::get(Ty));
  291. }
  292. DITemplateTypeParameter *
  293. DIBuilder::createTemplateTypeParameter(DIScope *Context, StringRef Name,
  294. DIType *Ty) {
  295. assert((!Context || isa<DICompileUnit>(Context)) && "Expected compile unit");
  296. return DITemplateTypeParameter::get(VMContext, Name, DITypeRef::get(Ty));
  297. }
  298. static DITemplateValueParameter *
  299. createTemplateValueParameterHelper(LLVMContext &VMContext, unsigned Tag,
  300. DIScope *Context, StringRef Name, DIType *Ty,
  301. Metadata *MD) {
  302. assert((!Context || isa<DICompileUnit>(Context)) && "Expected compile unit");
  303. return DITemplateValueParameter::get(VMContext, Tag, Name, DITypeRef::get(Ty),
  304. MD);
  305. }
  306. DITemplateValueParameter *
  307. DIBuilder::createTemplateValueParameter(DIScope *Context, StringRef Name,
  308. DIType *Ty, Constant *Val) {
  309. return createTemplateValueParameterHelper(
  310. VMContext, dwarf::DW_TAG_template_value_parameter, Context, Name, Ty,
  311. getConstantOrNull(Val));
  312. }
  313. DITemplateValueParameter *
  314. DIBuilder::createTemplateTemplateParameter(DIScope *Context, StringRef Name,
  315. DIType *Ty, StringRef Val) {
  316. return createTemplateValueParameterHelper(
  317. VMContext, dwarf::DW_TAG_GNU_template_template_param, Context, Name, Ty,
  318. MDString::get(VMContext, Val));
  319. }
  320. DITemplateValueParameter *
  321. DIBuilder::createTemplateParameterPack(DIScope *Context, StringRef Name,
  322. DIType *Ty, DINodeArray Val) {
  323. return createTemplateValueParameterHelper(
  324. VMContext, dwarf::DW_TAG_GNU_template_parameter_pack, Context, Name, Ty,
  325. Val.get());
  326. }
  327. DICompositeType *DIBuilder::createClassType(
  328. DIScope *Context, StringRef Name, DIFile *File, unsigned LineNumber,
  329. uint64_t SizeInBits, uint64_t AlignInBits, uint64_t OffsetInBits,
  330. unsigned Flags, DIType *DerivedFrom, DINodeArray Elements,
  331. DIType *VTableHolder, MDNode *TemplateParams, StringRef UniqueIdentifier) {
  332. assert((!Context || isa<DIScope>(Context)) &&
  333. "createClassType should be called with a valid Context");
  334. auto *R = DICompositeType::get(
  335. VMContext, dwarf::DW_TAG_structure_type, Name, File, LineNumber,
  336. DIScopeRef::get(getNonCompileUnitScope(Context)),
  337. DITypeRef::get(DerivedFrom), SizeInBits, AlignInBits, OffsetInBits, Flags,
  338. Elements, 0, DITypeRef::get(VTableHolder),
  339. cast_or_null<MDTuple>(TemplateParams), UniqueIdentifier);
  340. if (!UniqueIdentifier.empty())
  341. retainType(R);
  342. trackIfUnresolved(R);
  343. return R;
  344. }
  345. DICompositeType *DIBuilder::createStructType(
  346. DIScope *Context, StringRef Name, DIFile *File, unsigned LineNumber,
  347. uint64_t SizeInBits, uint64_t AlignInBits, unsigned Flags,
  348. DIType *DerivedFrom, DINodeArray Elements, unsigned RunTimeLang,
  349. DIType *VTableHolder, StringRef UniqueIdentifier) {
  350. auto *R = DICompositeType::get(
  351. VMContext, dwarf::DW_TAG_structure_type, Name, File, LineNumber,
  352. DIScopeRef::get(getNonCompileUnitScope(Context)),
  353. DITypeRef::get(DerivedFrom), SizeInBits, AlignInBits, 0, Flags, Elements,
  354. RunTimeLang, DITypeRef::get(VTableHolder), nullptr, UniqueIdentifier);
  355. if (!UniqueIdentifier.empty())
  356. retainType(R);
  357. trackIfUnresolved(R);
  358. return R;
  359. }
  360. DICompositeType *DIBuilder::createUnionType(
  361. DIScope *Scope, StringRef Name, DIFile *File, unsigned LineNumber,
  362. uint64_t SizeInBits, uint64_t AlignInBits, unsigned Flags,
  363. DINodeArray Elements, unsigned RunTimeLang, StringRef UniqueIdentifier) {
  364. auto *R = DICompositeType::get(
  365. VMContext, dwarf::DW_TAG_union_type, Name, File, LineNumber,
  366. DIScopeRef::get(getNonCompileUnitScope(Scope)), nullptr, SizeInBits,
  367. AlignInBits, 0, Flags, Elements, RunTimeLang, nullptr, nullptr,
  368. UniqueIdentifier);
  369. if (!UniqueIdentifier.empty())
  370. retainType(R);
  371. trackIfUnresolved(R);
  372. return R;
  373. }
  374. DISubroutineType *DIBuilder::createSubroutineType(DIFile *File,
  375. DITypeRefArray ParameterTypes,
  376. unsigned Flags) {
  377. return DISubroutineType::get(VMContext, Flags, ParameterTypes);
  378. }
  379. DICompositeType *DIBuilder::createEnumerationType(
  380. DIScope *Scope, StringRef Name, DIFile *File, unsigned LineNumber,
  381. uint64_t SizeInBits, uint64_t AlignInBits, DINodeArray Elements,
  382. DIType *UnderlyingType, StringRef UniqueIdentifier) {
  383. auto *CTy = DICompositeType::get(
  384. VMContext, dwarf::DW_TAG_enumeration_type, Name, File, LineNumber,
  385. DIScopeRef::get(getNonCompileUnitScope(Scope)),
  386. DITypeRef::get(UnderlyingType), SizeInBits, AlignInBits, 0, 0, Elements,
  387. 0, nullptr, nullptr, UniqueIdentifier);
  388. AllEnumTypes.push_back(CTy);
  389. if (!UniqueIdentifier.empty())
  390. retainType(CTy);
  391. trackIfUnresolved(CTy);
  392. return CTy;
  393. }
  394. DICompositeType *DIBuilder::createArrayType(uint64_t Size, uint64_t AlignInBits,
  395. DIType *Ty,
  396. DINodeArray Subscripts) {
  397. auto *R = DICompositeType::get(VMContext, dwarf::DW_TAG_array_type, "",
  398. nullptr, 0, nullptr, DITypeRef::get(Ty), Size,
  399. AlignInBits, 0, 0, Subscripts, 0, nullptr);
  400. trackIfUnresolved(R);
  401. return R;
  402. }
  403. DICompositeType *DIBuilder::createVectorType(uint64_t Size,
  404. uint64_t AlignInBits, DIType *Ty,
  405. DINodeArray Subscripts) {
  406. auto *R =
  407. DICompositeType::get(VMContext, dwarf::DW_TAG_array_type, "", nullptr, 0,
  408. nullptr, DITypeRef::get(Ty), Size, AlignInBits, 0,
  409. DINode::FlagVector, Subscripts, 0, nullptr);
  410. trackIfUnresolved(R);
  411. return R;
  412. }
  413. static DIType *createTypeWithFlags(LLVMContext &Context, DIType *Ty,
  414. unsigned FlagsToSet) {
  415. auto NewTy = Ty->clone();
  416. NewTy->setFlags(NewTy->getFlags() | FlagsToSet);
  417. return MDNode::replaceWithUniqued(std::move(NewTy));
  418. }
  419. DIType *DIBuilder::createArtificialType(DIType *Ty) {
  420. // FIXME: Restrict this to the nodes where it's valid.
  421. if (Ty->isArtificial())
  422. return Ty;
  423. return createTypeWithFlags(VMContext, Ty, DINode::FlagArtificial);
  424. }
  425. DIType *DIBuilder::createObjectPointerType(DIType *Ty) {
  426. // FIXME: Restrict this to the nodes where it's valid.
  427. if (Ty->isObjectPointer())
  428. return Ty;
  429. unsigned Flags = DINode::FlagObjectPointer | DINode::FlagArtificial;
  430. return createTypeWithFlags(VMContext, Ty, Flags);
  431. }
  432. void DIBuilder::retainType(DIType *T) {
  433. assert(T && "Expected non-null type");
  434. AllRetainTypes.emplace_back(T);
  435. }
  436. DIBasicType *DIBuilder::createUnspecifiedParameter() { return nullptr; }
  437. DICompositeType *
  438. DIBuilder::createForwardDecl(unsigned Tag, StringRef Name, DIScope *Scope,
  439. DIFile *F, unsigned Line, unsigned RuntimeLang,
  440. uint64_t SizeInBits, uint64_t AlignInBits,
  441. StringRef UniqueIdentifier) {
  442. // FIXME: Define in terms of createReplaceableForwardDecl() by calling
  443. // replaceWithUniqued().
  444. auto *RetTy = DICompositeType::get(
  445. VMContext, Tag, Name, F, Line,
  446. DIScopeRef::get(getNonCompileUnitScope(Scope)), nullptr, SizeInBits,
  447. AlignInBits, 0, DINode::FlagFwdDecl, nullptr, RuntimeLang, nullptr,
  448. nullptr, UniqueIdentifier);
  449. if (!UniqueIdentifier.empty())
  450. retainType(RetTy);
  451. trackIfUnresolved(RetTy);
  452. return RetTy;
  453. }
  454. DICompositeType *DIBuilder::createReplaceableCompositeType(
  455. unsigned Tag, StringRef Name, DIScope *Scope, DIFile *F, unsigned Line,
  456. unsigned RuntimeLang, uint64_t SizeInBits, uint64_t AlignInBits,
  457. unsigned Flags, StringRef UniqueIdentifier) {
  458. auto *RetTy = DICompositeType::getTemporary(
  459. VMContext, Tag, Name, F, Line,
  460. DIScopeRef::get(getNonCompileUnitScope(Scope)), nullptr,
  461. SizeInBits, AlignInBits, 0, Flags, nullptr, RuntimeLang,
  462. nullptr, nullptr, UniqueIdentifier)
  463. .release();
  464. if (!UniqueIdentifier.empty())
  465. retainType(RetTy);
  466. trackIfUnresolved(RetTy);
  467. return RetTy;
  468. }
  469. DINodeArray DIBuilder::getOrCreateArray(ArrayRef<Metadata *> Elements) {
  470. return MDTuple::get(VMContext, Elements);
  471. }
  472. DITypeRefArray DIBuilder::getOrCreateTypeArray(ArrayRef<Metadata *> Elements) {
  473. SmallVector<llvm::Metadata *, 16> Elts;
  474. for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
  475. if (Elements[i] && isa<MDNode>(Elements[i]))
  476. Elts.push_back(DITypeRef::get(cast<DIType>(Elements[i])));
  477. else
  478. Elts.push_back(Elements[i]);
  479. }
  480. return DITypeRefArray(MDNode::get(VMContext, Elts));
  481. }
  482. DISubrange *DIBuilder::getOrCreateSubrange(int64_t Lo, int64_t Count) {
  483. return DISubrange::get(VMContext, Count, Lo);
  484. }
  485. static void checkGlobalVariableScope(DIScope *Context) {
  486. #ifndef NDEBUG
  487. if (auto *CT =
  488. dyn_cast_or_null<DICompositeType>(getNonCompileUnitScope(Context)))
  489. assert(CT->getIdentifier().empty() &&
  490. "Context of a global variable should not be a type with identifier");
  491. #endif
  492. }
  493. DIGlobalVariable *DIBuilder::createGlobalVariable(
  494. DIScope *Context, StringRef Name, StringRef LinkageName, DIFile *F,
  495. unsigned LineNumber, DIType *Ty, bool isLocalToUnit, Constant *Val,
  496. MDNode *Decl) {
  497. checkGlobalVariableScope(Context);
  498. auto *N = DIGlobalVariable::get(VMContext, cast_or_null<DIScope>(Context),
  499. Name, LinkageName, F, LineNumber,
  500. DITypeRef::get(Ty), isLocalToUnit, true, Val,
  501. cast_or_null<DIDerivedType>(Decl));
  502. AllGVs.push_back(N);
  503. return N;
  504. }
  505. DIGlobalVariable *DIBuilder::createTempGlobalVariableFwdDecl(
  506. DIScope *Context, StringRef Name, StringRef LinkageName, DIFile *F,
  507. unsigned LineNumber, DIType *Ty, bool isLocalToUnit, Constant *Val,
  508. MDNode *Decl) {
  509. checkGlobalVariableScope(Context);
  510. return DIGlobalVariable::getTemporary(
  511. VMContext, cast_or_null<DIScope>(Context), Name, LinkageName, F,
  512. LineNumber, DITypeRef::get(Ty), isLocalToUnit, false, Val,
  513. cast_or_null<DIDerivedType>(Decl))
  514. .release();
  515. }
  516. DILocalVariable *DIBuilder::createLocalVariable(
  517. unsigned Tag, DIScope *Scope, StringRef Name, DIFile *File, unsigned LineNo,
  518. DIType *Ty, bool AlwaysPreserve, unsigned Flags, unsigned ArgNo) {
  519. // FIXME: Why getNonCompileUnitScope()?
  520. // FIXME: Why is "!Context" okay here?
  521. // FIXME: Why doesn't this check for a subprogram or lexical block (AFAICT
  522. // the only valid scopes)?
  523. DIScope *Context = getNonCompileUnitScope(Scope);
  524. auto *Node = DILocalVariable::get(
  525. VMContext, Tag, cast_or_null<DILocalScope>(Context), Name, File, LineNo,
  526. DITypeRef::get(Ty), ArgNo, Flags);
  527. if (AlwaysPreserve) {
  528. // The optimizer may remove local variables. If there is an interest
  529. // to preserve variable info in such situation then stash it in a
  530. // named mdnode.
  531. DISubprogram *Fn = getDISubprogram(Scope);
  532. assert(Fn && "Missing subprogram for local variable");
  533. PreservedVariables[Fn].emplace_back(Node);
  534. }
  535. return Node;
  536. }
  537. DIExpression *DIBuilder::createExpression(ArrayRef<uint64_t> Addr) {
  538. return DIExpression::get(VMContext, Addr);
  539. }
  540. DIExpression *DIBuilder::createExpression(ArrayRef<int64_t> Signed) {
  541. // TODO: Remove the callers of this signed version and delete.
  542. SmallVector<uint64_t, 8> Addr(Signed.begin(), Signed.end());
  543. return createExpression(Addr);
  544. }
  545. // HLSL Begin Change: Match -InBits suffixes from header
  546. DIExpression *DIBuilder::createBitPieceExpression(unsigned OffsetInBits,
  547. unsigned SizeInBits) {
  548. uint64_t Addr[] = {dwarf::DW_OP_bit_piece, OffsetInBits, SizeInBits};
  549. // HLSL End Change
  550. return DIExpression::get(VMContext, Addr);
  551. }
  552. DISubprogram *DIBuilder::createFunction(DIScopeRef Context, StringRef Name,
  553. StringRef LinkageName, DIFile *File,
  554. unsigned LineNo, DISubroutineType *Ty,
  555. bool isLocalToUnit, bool isDefinition,
  556. unsigned ScopeLine, unsigned Flags,
  557. bool isOptimized, Function *Fn,
  558. MDNode *TParams, MDNode *Decl) {
  559. // dragonegg does not generate identifier for types, so using an empty map
  560. // to resolve the context should be fine.
  561. DITypeIdentifierMap EmptyMap;
  562. return createFunction(Context.resolve(EmptyMap), Name, LinkageName, File,
  563. LineNo, Ty, isLocalToUnit, isDefinition, ScopeLine,
  564. Flags, isOptimized, Fn, TParams, Decl);
  565. }
  566. DISubprogram *DIBuilder::createFunction(DIScope *Context, StringRef Name,
  567. StringRef LinkageName, DIFile *File,
  568. unsigned LineNo, DISubroutineType *Ty,
  569. bool isLocalToUnit, bool isDefinition,
  570. unsigned ScopeLine, unsigned Flags,
  571. bool isOptimized, Function *Fn,
  572. MDNode *TParams, MDNode *Decl) {
  573. assert(Ty->getTag() == dwarf::DW_TAG_subroutine_type &&
  574. "function types should be subroutines");
  575. auto *Node = DISubprogram::get(
  576. VMContext, DIScopeRef::get(getNonCompileUnitScope(Context)), Name,
  577. LinkageName, File, LineNo, Ty, isLocalToUnit, isDefinition, ScopeLine,
  578. nullptr, 0, 0, Flags, isOptimized, Fn, cast_or_null<MDTuple>(TParams),
  579. cast_or_null<DISubprogram>(Decl),
  580. nullptr); // HLSL Change - this leaked, better nullptr than empty anyway - MDTuple::getTemporary(VMContext, None).release());
  581. if (isDefinition)
  582. AllSubprograms.push_back(Node);
  583. trackIfUnresolved(Node);
  584. return Node;
  585. }
  586. DISubprogram *DIBuilder::createTempFunctionFwdDecl(
  587. DIScope *Context, StringRef Name, StringRef LinkageName, DIFile *File,
  588. unsigned LineNo, DISubroutineType *Ty, bool isLocalToUnit,
  589. bool isDefinition, unsigned ScopeLine, unsigned Flags, bool isOptimized,
  590. Function *Fn, MDNode *TParams, MDNode *Decl) {
  591. return DISubprogram::getTemporary(
  592. VMContext, DIScopeRef::get(getNonCompileUnitScope(Context)), Name,
  593. LinkageName, File, LineNo, Ty, isLocalToUnit, isDefinition,
  594. ScopeLine, nullptr, 0, 0, Flags, isOptimized, Fn,
  595. cast_or_null<MDTuple>(TParams), cast_or_null<DISubprogram>(Decl),
  596. nullptr)
  597. .release();
  598. }
  599. DISubprogram *
  600. DIBuilder::createMethod(DIScope *Context, StringRef Name, StringRef LinkageName,
  601. DIFile *F, unsigned LineNo, DISubroutineType *Ty,
  602. bool isLocalToUnit, bool isDefinition, unsigned VK,
  603. unsigned VIndex, DIType *VTableHolder, unsigned Flags,
  604. bool isOptimized, Function *Fn, MDNode *TParam) {
  605. assert(Ty->getTag() == dwarf::DW_TAG_subroutine_type &&
  606. "function types should be subroutines");
  607. assert(getNonCompileUnitScope(Context) &&
  608. "Methods should have both a Context and a context that isn't "
  609. "the compile unit.");
  610. // FIXME: Do we want to use different scope/lines?
  611. auto *SP = DISubprogram::get(
  612. VMContext, DIScopeRef::get(cast<DIScope>(Context)), Name, LinkageName, F,
  613. LineNo, Ty, isLocalToUnit, isDefinition, LineNo,
  614. DITypeRef::get(VTableHolder), VK, VIndex, Flags, isOptimized, Fn,
  615. cast_or_null<MDTuple>(TParam), nullptr, nullptr);
  616. if (isDefinition)
  617. AllSubprograms.push_back(SP);
  618. trackIfUnresolved(SP);
  619. return SP;
  620. }
  621. DINamespace *DIBuilder::createNameSpace(DIScope *Scope, StringRef Name,
  622. DIFile *File, unsigned LineNo) {
  623. return DINamespace::get(VMContext, getNonCompileUnitScope(Scope), File, Name,
  624. LineNo);
  625. }
  626. DIModule *DIBuilder::createModule(DIScope *Scope, StringRef Name,
  627. StringRef ConfigurationMacros,
  628. StringRef IncludePath,
  629. StringRef ISysRoot) {
  630. return DIModule::get(VMContext, getNonCompileUnitScope(Scope), Name,
  631. ConfigurationMacros, IncludePath, ISysRoot);
  632. }
  633. DILexicalBlockFile *DIBuilder::createLexicalBlockFile(DIScope *Scope,
  634. DIFile *File,
  635. unsigned Discriminator) {
  636. return DILexicalBlockFile::get(VMContext, Scope, File, Discriminator);
  637. }
  638. DILexicalBlock *DIBuilder::createLexicalBlock(DIScope *Scope, DIFile *File,
  639. unsigned Line, unsigned Col) {
  640. // Make these distinct, to avoid merging two lexical blocks on the same
  641. // file/line/column.
  642. return DILexicalBlock::getDistinct(VMContext, getNonCompileUnitScope(Scope),
  643. File, Line, Col);
  644. }
  645. static Value *getDbgIntrinsicValueImpl(LLVMContext &VMContext, Value *V) {
  646. assert(V && "no value passed to dbg intrinsic");
  647. return MetadataAsValue::get(VMContext, ValueAsMetadata::get(V));
  648. }
  649. static Instruction *withDebugLoc(Instruction *I, const DILocation *DL) {
  650. I->setDebugLoc(const_cast<DILocation *>(DL));
  651. return I;
  652. }
  653. Instruction *DIBuilder::insertDeclare(Value *Storage, DILocalVariable *VarInfo,
  654. DIExpression *Expr, const DILocation *DL,
  655. Instruction *InsertBefore) {
  656. assert(VarInfo && "empty or invalid DILocalVariable* passed to dbg.declare");
  657. assert(DL && "Expected debug loc");
  658. assert(DL->getScope()->getSubprogram() ==
  659. VarInfo->getScope()->getSubprogram() &&
  660. "Expected matching subprograms");
  661. if (!DeclareFn)
  662. DeclareFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_declare);
  663. trackIfUnresolved(VarInfo);
  664. trackIfUnresolved(Expr);
  665. Value *Args[] = {getDbgIntrinsicValueImpl(VMContext, Storage),
  666. MetadataAsValue::get(VMContext, VarInfo),
  667. MetadataAsValue::get(VMContext, Expr)};
  668. return withDebugLoc(CallInst::Create(DeclareFn, Args, "", InsertBefore), DL);
  669. }
  670. Instruction *DIBuilder::insertDeclare(Value *Storage, DILocalVariable *VarInfo,
  671. DIExpression *Expr, const DILocation *DL,
  672. BasicBlock *InsertAtEnd) {
  673. assert(VarInfo && "empty or invalid DILocalVariable* passed to dbg.declare");
  674. assert(DL && "Expected debug loc");
  675. assert(DL->getScope()->getSubprogram() ==
  676. VarInfo->getScope()->getSubprogram() &&
  677. "Expected matching subprograms");
  678. if (!DeclareFn)
  679. DeclareFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_declare);
  680. trackIfUnresolved(VarInfo);
  681. trackIfUnresolved(Expr);
  682. Value *Args[] = {getDbgIntrinsicValueImpl(VMContext, Storage),
  683. MetadataAsValue::get(VMContext, VarInfo),
  684. MetadataAsValue::get(VMContext, Expr)};
  685. // If this block already has a terminator then insert this intrinsic
  686. // before the terminator.
  687. if (TerminatorInst *T = InsertAtEnd->getTerminator())
  688. return withDebugLoc(CallInst::Create(DeclareFn, Args, "", T), DL);
  689. return withDebugLoc(CallInst::Create(DeclareFn, Args, "", InsertAtEnd), DL);
  690. }
  691. Instruction *DIBuilder::insertDbgValueIntrinsic(Value *V, uint64_t Offset,
  692. DILocalVariable *VarInfo,
  693. DIExpression *Expr,
  694. const DILocation *DL,
  695. Instruction *InsertBefore) {
  696. assert(V && "no value passed to dbg.value");
  697. assert(VarInfo && "empty or invalid DILocalVariable* passed to dbg.value");
  698. assert(DL && "Expected debug loc");
  699. assert(DL->getScope()->getSubprogram() ==
  700. VarInfo->getScope()->getSubprogram() &&
  701. "Expected matching subprograms");
  702. if (!ValueFn)
  703. ValueFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_value);
  704. trackIfUnresolved(VarInfo);
  705. trackIfUnresolved(Expr);
  706. Value *Args[] = {getDbgIntrinsicValueImpl(VMContext, V),
  707. ConstantInt::get(Type::getInt64Ty(VMContext), Offset),
  708. MetadataAsValue::get(VMContext, VarInfo),
  709. MetadataAsValue::get(VMContext, Expr)};
  710. return withDebugLoc(CallInst::Create(ValueFn, Args, "", InsertBefore), DL);
  711. }
  712. Instruction *DIBuilder::insertDbgValueIntrinsic(Value *V, uint64_t Offset,
  713. DILocalVariable *VarInfo,
  714. DIExpression *Expr,
  715. const DILocation *DL,
  716. BasicBlock *InsertAtEnd) {
  717. assert(V && "no value passed to dbg.value");
  718. assert(VarInfo && "empty or invalid DILocalVariable* passed to dbg.value");
  719. assert(DL && "Expected debug loc");
  720. assert(DL->getScope()->getSubprogram() ==
  721. VarInfo->getScope()->getSubprogram() &&
  722. "Expected matching subprograms");
  723. if (!ValueFn)
  724. ValueFn = Intrinsic::getDeclaration(&M, Intrinsic::dbg_value);
  725. trackIfUnresolved(VarInfo);
  726. trackIfUnresolved(Expr);
  727. Value *Args[] = {getDbgIntrinsicValueImpl(VMContext, V),
  728. ConstantInt::get(Type::getInt64Ty(VMContext), Offset),
  729. MetadataAsValue::get(VMContext, VarInfo),
  730. MetadataAsValue::get(VMContext, Expr)};
  731. return withDebugLoc(CallInst::Create(ValueFn, Args, "", InsertAtEnd), DL);
  732. }
  733. void DIBuilder::replaceVTableHolder(DICompositeType *&T,
  734. DICompositeType *VTableHolder) {
  735. {
  736. TypedTrackingMDRef<DICompositeType> N(T);
  737. N->replaceVTableHolder(DITypeRef::get(VTableHolder));
  738. T = N.get();
  739. }
  740. // If this didn't create a self-reference, just return.
  741. if (T != VTableHolder)
  742. return;
  743. // Look for unresolved operands. T will drop RAUW support, orphaning any
  744. // cycles underneath it.
  745. if (T->isResolved())
  746. for (const MDOperand &O : T->operands())
  747. if (auto *N = dyn_cast_or_null<MDNode>(O))
  748. trackIfUnresolved(N);
  749. }
  750. void DIBuilder::replaceArrays(DICompositeType *&T, DINodeArray Elements,
  751. DINodeArray TParams) {
  752. {
  753. TypedTrackingMDRef<DICompositeType> N(T);
  754. if (Elements)
  755. N->replaceElements(Elements);
  756. if (TParams)
  757. N->replaceTemplateParams(DITemplateParameterArray(TParams));
  758. T = N.get();
  759. }
  760. // If T isn't resolved, there's no problem.
  761. if (!T->isResolved())
  762. return;
  763. // If T is resolved, it may be due to a self-reference cycle. Track the
  764. // arrays explicitly if they're unresolved, or else the cycles will be
  765. // orphaned.
  766. if (Elements)
  767. trackIfUnresolved(Elements.get());
  768. if (TParams)
  769. trackIfUnresolved(TParams.get());
  770. }