DebugInfoMetadata.cpp 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233
  1. //===- DebugInfoMetadata.cpp - Implement debug info metadata --------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file implements the debug info Metadata classes.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "llvm/IR/DebugInfoMetadata.h"
  13. #include "LLVMContextImpl.h"
  14. #include "MetadataImpl.h"
  15. #include "llvm/ADT/SmallSet.h"
  16. #include "llvm/ADT/StringSwitch.h"
  17. #include "llvm/IR/DIBuilder.h"
  18. #include "llvm/IR/Function.h"
  19. #include "llvm/IR/Instructions.h"
  20. #include <numeric>
  21. using namespace llvm;
  22. DILocation::DILocation(LLVMContext &C, StorageType Storage, unsigned Line,
  23. unsigned Column, ArrayRef<Metadata *> MDs,
  24. bool ImplicitCode)
  25. : MDNode(C, DILocationKind, Storage, MDs) {
  26. assert((MDs.size() == 1 || MDs.size() == 2) &&
  27. "Expected a scope and optional inlined-at");
  28. // Set line and column.
  29. assert(Column < (1u << 16) && "Expected 16-bit column");
  30. SubclassData32 = Line;
  31. SubclassData16 = Column;
  32. setImplicitCode(ImplicitCode);
  33. }
  34. static void adjustColumn(unsigned &Column) {
  35. // Set to unknown on overflow. We only have 16 bits to play with here.
  36. if (Column >= (1u << 16))
  37. Column = 0;
  38. }
  39. DILocation *DILocation::getImpl(LLVMContext &Context, unsigned Line,
  40. unsigned Column, Metadata *Scope,
  41. Metadata *InlinedAt, bool ImplicitCode,
  42. StorageType Storage, bool ShouldCreate) {
  43. // Fixup column.
  44. adjustColumn(Column);
  45. if (Storage == Uniqued) {
  46. if (auto *N = getUniqued(Context.pImpl->DILocations,
  47. DILocationInfo::KeyTy(Line, Column, Scope,
  48. InlinedAt, ImplicitCode)))
  49. return N;
  50. if (!ShouldCreate)
  51. return nullptr;
  52. } else {
  53. assert(ShouldCreate && "Expected non-uniqued nodes to always be created");
  54. }
  55. SmallVector<Metadata *, 2> Ops;
  56. Ops.push_back(Scope);
  57. if (InlinedAt)
  58. Ops.push_back(InlinedAt);
  59. return storeImpl(new (Ops.size()) DILocation(Context, Storage, Line, Column,
  60. Ops, ImplicitCode),
  61. Storage, Context.pImpl->DILocations);
  62. }
  63. const DILocation *DILocation::getMergedLocation(const DILocation *LocA,
  64. const DILocation *LocB) {
  65. if (!LocA || !LocB)
  66. return nullptr;
  67. if (LocA == LocB)
  68. return LocA;
  69. SmallPtrSet<DILocation *, 5> InlinedLocationsA;
  70. for (DILocation *L = LocA->getInlinedAt(); L; L = L->getInlinedAt())
  71. InlinedLocationsA.insert(L);
  72. SmallSet<std::pair<DIScope *, DILocation *>, 5> Locations;
  73. DIScope *S = LocA->getScope();
  74. DILocation *L = LocA->getInlinedAt();
  75. while (S) {
  76. Locations.insert(std::make_pair(S, L));
  77. S = S->getScope();
  78. if (!S && L) {
  79. S = L->getScope();
  80. L = L->getInlinedAt();
  81. }
  82. }
  83. const DILocation *Result = LocB;
  84. S = LocB->getScope();
  85. L = LocB->getInlinedAt();
  86. while (S) {
  87. if (Locations.count(std::make_pair(S, L)))
  88. break;
  89. S = S->getScope();
  90. if (!S && L) {
  91. S = L->getScope();
  92. L = L->getInlinedAt();
  93. }
  94. }
  95. // If the two locations are irreconsilable, just pick one. This is misleading,
  96. // but on the other hand, it's a "line 0" location.
  97. if (!S || !isa<DILocalScope>(S))
  98. S = LocA->getScope();
  99. return DILocation::get(Result->getContext(), 0, 0, S, L);
  100. }
  101. Optional<unsigned> DILocation::encodeDiscriminator(unsigned BD, unsigned DF, unsigned CI) {
  102. SmallVector<unsigned, 3> Components = {BD, DF, CI};
  103. uint64_t RemainingWork = 0U;
  104. // We use RemainingWork to figure out if we have no remaining components to
  105. // encode. For example: if BD != 0 but DF == 0 && CI == 0, we don't need to
  106. // encode anything for the latter 2.
  107. // Since any of the input components is at most 32 bits, their sum will be
  108. // less than 34 bits, and thus RemainingWork won't overflow.
  109. RemainingWork = std::accumulate(Components.begin(), Components.end(), RemainingWork);
  110. int I = 0;
  111. unsigned Ret = 0;
  112. unsigned NextBitInsertionIndex = 0;
  113. while (RemainingWork > 0) {
  114. unsigned C = Components[I++];
  115. RemainingWork -= C;
  116. unsigned EC = encodeComponent(C);
  117. Ret |= (EC << NextBitInsertionIndex);
  118. NextBitInsertionIndex += encodingBits(C);
  119. }
  120. // Encoding may be unsuccessful because of overflow. We determine success by
  121. // checking equivalence of components before & after encoding. Alternatively,
  122. // we could determine Success during encoding, but the current alternative is
  123. // simpler.
  124. unsigned TBD, TDF, TCI = 0;
  125. decodeDiscriminator(Ret, TBD, TDF, TCI);
  126. if (TBD == BD && TDF == DF && TCI == CI)
  127. return Ret;
  128. return None;
  129. }
  130. void DILocation::decodeDiscriminator(unsigned D, unsigned &BD, unsigned &DF,
  131. unsigned &CI) {
  132. BD = getUnsignedFromPrefixEncoding(D);
  133. DF = getUnsignedFromPrefixEncoding(getNextComponentInDiscriminator(D));
  134. CI = getUnsignedFromPrefixEncoding(
  135. getNextComponentInDiscriminator(getNextComponentInDiscriminator(D)));
  136. }
  137. DINode::DIFlags DINode::getFlag(StringRef Flag) {
  138. return StringSwitch<DIFlags>(Flag)
  139. #define HANDLE_DI_FLAG(ID, NAME) .Case("DIFlag" #NAME, Flag##NAME)
  140. #include "llvm/IR/DebugInfoFlags.def"
  141. .Default(DINode::FlagZero);
  142. }
  143. StringRef DINode::getFlagString(DIFlags Flag) {
  144. switch (Flag) {
  145. #define HANDLE_DI_FLAG(ID, NAME) \
  146. case Flag##NAME: \
  147. return "DIFlag" #NAME;
  148. #include "llvm/IR/DebugInfoFlags.def"
  149. }
  150. return "";
  151. }
  152. DINode::DIFlags DINode::splitFlags(DIFlags Flags,
  153. SmallVectorImpl<DIFlags> &SplitFlags) {
  154. // Flags that are packed together need to be specially handled, so
  155. // that, for example, we emit "DIFlagPublic" and not
  156. // "DIFlagPrivate | DIFlagProtected".
  157. if (DIFlags A = Flags & FlagAccessibility) {
  158. if (A == FlagPrivate)
  159. SplitFlags.push_back(FlagPrivate);
  160. else if (A == FlagProtected)
  161. SplitFlags.push_back(FlagProtected);
  162. else
  163. SplitFlags.push_back(FlagPublic);
  164. Flags &= ~A;
  165. }
  166. if (DIFlags R = Flags & FlagPtrToMemberRep) {
  167. if (R == FlagSingleInheritance)
  168. SplitFlags.push_back(FlagSingleInheritance);
  169. else if (R == FlagMultipleInheritance)
  170. SplitFlags.push_back(FlagMultipleInheritance);
  171. else
  172. SplitFlags.push_back(FlagVirtualInheritance);
  173. Flags &= ~R;
  174. }
  175. if ((Flags & FlagIndirectVirtualBase) == FlagIndirectVirtualBase) {
  176. Flags &= ~FlagIndirectVirtualBase;
  177. SplitFlags.push_back(FlagIndirectVirtualBase);
  178. }
  179. #define HANDLE_DI_FLAG(ID, NAME) \
  180. if (DIFlags Bit = Flags & Flag##NAME) { \
  181. SplitFlags.push_back(Bit); \
  182. Flags &= ~Bit; \
  183. }
  184. #include "llvm/IR/DebugInfoFlags.def"
  185. return Flags;
  186. }
  187. DIScope *DIScope::getScope() const {
  188. if (auto *T = dyn_cast<DIType>(this))
  189. return T->getScope();
  190. if (auto *SP = dyn_cast<DISubprogram>(this))
  191. return SP->getScope();
  192. if (auto *LB = dyn_cast<DILexicalBlockBase>(this))
  193. return LB->getScope();
  194. if (auto *NS = dyn_cast<DINamespace>(this))
  195. return NS->getScope();
  196. if (auto *CB = dyn_cast<DICommonBlock>(this))
  197. return CB->getScope();
  198. if (auto *M = dyn_cast<DIModule>(this))
  199. return M->getScope();
  200. assert((isa<DIFile>(this) || isa<DICompileUnit>(this)) &&
  201. "Unhandled type of scope.");
  202. return nullptr;
  203. }
  204. StringRef DIScope::getName() const {
  205. if (auto *T = dyn_cast<DIType>(this))
  206. return T->getName();
  207. if (auto *SP = dyn_cast<DISubprogram>(this))
  208. return SP->getName();
  209. if (auto *NS = dyn_cast<DINamespace>(this))
  210. return NS->getName();
  211. if (auto *CB = dyn_cast<DICommonBlock>(this))
  212. return CB->getName();
  213. if (auto *M = dyn_cast<DIModule>(this))
  214. return M->getName();
  215. assert((isa<DILexicalBlockBase>(this) || isa<DIFile>(this) ||
  216. isa<DICompileUnit>(this)) &&
  217. "Unhandled type of scope.");
  218. return "";
  219. }
  220. #ifndef NDEBUG
  221. static bool isCanonical(const MDString *S) {
  222. return !S || !S->getString().empty();
  223. }
  224. #endif
  225. GenericDINode *GenericDINode::getImpl(LLVMContext &Context, unsigned Tag,
  226. MDString *Header,
  227. ArrayRef<Metadata *> DwarfOps,
  228. StorageType Storage, bool ShouldCreate) {
  229. unsigned Hash = 0;
  230. if (Storage == Uniqued) {
  231. GenericDINodeInfo::KeyTy Key(Tag, Header, DwarfOps);
  232. if (auto *N = getUniqued(Context.pImpl->GenericDINodes, Key))
  233. return N;
  234. if (!ShouldCreate)
  235. return nullptr;
  236. Hash = Key.getHash();
  237. } else {
  238. assert(ShouldCreate && "Expected non-uniqued nodes to always be created");
  239. }
  240. // Use a nullptr for empty headers.
  241. assert(isCanonical(Header) && "Expected canonical MDString");
  242. Metadata *PreOps[] = {Header};
  243. return storeImpl(new (DwarfOps.size() + 1) GenericDINode(
  244. Context, Storage, Hash, Tag, PreOps, DwarfOps),
  245. Storage, Context.pImpl->GenericDINodes);
  246. }
  247. void GenericDINode::recalculateHash() {
  248. setHash(GenericDINodeInfo::KeyTy::calculateHash(this));
  249. }
  250. #define UNWRAP_ARGS_IMPL(...) __VA_ARGS__
  251. #define UNWRAP_ARGS(ARGS) UNWRAP_ARGS_IMPL ARGS
  252. #define DEFINE_GETIMPL_LOOKUP(CLASS, ARGS) \
  253. do { \
  254. if (Storage == Uniqued) { \
  255. if (auto *N = getUniqued(Context.pImpl->CLASS##s, \
  256. CLASS##Info::KeyTy(UNWRAP_ARGS(ARGS)))) \
  257. return N; \
  258. if (!ShouldCreate) \
  259. return nullptr; \
  260. } else { \
  261. assert(ShouldCreate && \
  262. "Expected non-uniqued nodes to always be created"); \
  263. } \
  264. } while (false)
  265. #define DEFINE_GETIMPL_STORE(CLASS, ARGS, OPS) \
  266. return storeImpl(new (array_lengthof(OPS)) \
  267. CLASS(Context, Storage, UNWRAP_ARGS(ARGS), OPS), \
  268. Storage, Context.pImpl->CLASS##s)
  269. #define DEFINE_GETIMPL_STORE_NO_OPS(CLASS, ARGS) \
  270. return storeImpl(new (0u) CLASS(Context, Storage, UNWRAP_ARGS(ARGS)), \
  271. Storage, Context.pImpl->CLASS##s)
  272. #define DEFINE_GETIMPL_STORE_NO_CONSTRUCTOR_ARGS(CLASS, OPS) \
  273. return storeImpl(new (array_lengthof(OPS)) CLASS(Context, Storage, OPS), \
  274. Storage, Context.pImpl->CLASS##s)
  275. #define DEFINE_GETIMPL_STORE_N(CLASS, ARGS, OPS, NUM_OPS) \
  276. return storeImpl(new (NUM_OPS) \
  277. CLASS(Context, Storage, UNWRAP_ARGS(ARGS), OPS), \
  278. Storage, Context.pImpl->CLASS##s)
  279. DISubrange *DISubrange::getImpl(LLVMContext &Context, int64_t Count, int64_t Lo,
  280. StorageType Storage, bool ShouldCreate) {
  281. auto *CountNode = ConstantAsMetadata::get(
  282. ConstantInt::getSigned(Type::getInt64Ty(Context), Count));
  283. return getImpl(Context, CountNode, Lo, Storage, ShouldCreate);
  284. }
  285. DISubrange *DISubrange::getImpl(LLVMContext &Context, Metadata *CountNode,
  286. int64_t Lo, StorageType Storage,
  287. bool ShouldCreate) {
  288. DEFINE_GETIMPL_LOOKUP(DISubrange, (CountNode, Lo));
  289. Metadata *Ops[] = { CountNode };
  290. DEFINE_GETIMPL_STORE(DISubrange, (CountNode, Lo), Ops);
  291. }
  292. DIEnumerator *DIEnumerator::getImpl(LLVMContext &Context, int64_t Value,
  293. bool IsUnsigned, MDString *Name,
  294. StorageType Storage, bool ShouldCreate) {
  295. assert(isCanonical(Name) && "Expected canonical MDString");
  296. DEFINE_GETIMPL_LOOKUP(DIEnumerator, (Value, IsUnsigned, Name));
  297. Metadata *Ops[] = {Name};
  298. DEFINE_GETIMPL_STORE(DIEnumerator, (Value, IsUnsigned), Ops);
  299. }
  300. DIBasicType *DIBasicType::getImpl(LLVMContext &Context, unsigned Tag,
  301. MDString *Name, uint64_t SizeInBits,
  302. uint32_t AlignInBits, unsigned Encoding,
  303. DIFlags Flags, StorageType Storage,
  304. bool ShouldCreate) {
  305. assert(isCanonical(Name) && "Expected canonical MDString");
  306. DEFINE_GETIMPL_LOOKUP(DIBasicType,
  307. (Tag, Name, SizeInBits, AlignInBits, Encoding, Flags));
  308. Metadata *Ops[] = {nullptr, nullptr, Name};
  309. DEFINE_GETIMPL_STORE(DIBasicType, (Tag, SizeInBits, AlignInBits, Encoding,
  310. Flags), Ops);
  311. }
  312. Optional<DIBasicType::Signedness> DIBasicType::getSignedness() const {
  313. switch (getEncoding()) {
  314. case dwarf::DW_ATE_signed:
  315. case dwarf::DW_ATE_signed_char:
  316. return Signedness::Signed;
  317. case dwarf::DW_ATE_unsigned:
  318. case dwarf::DW_ATE_unsigned_char:
  319. return Signedness::Unsigned;
  320. default:
  321. return None;
  322. }
  323. }
  324. DIDerivedType *DIDerivedType::getImpl(
  325. LLVMContext &Context, unsigned Tag, MDString *Name, Metadata *File,
  326. unsigned Line, Metadata *Scope, Metadata *BaseType, uint64_t SizeInBits,
  327. uint32_t AlignInBits, uint64_t OffsetInBits,
  328. Optional<unsigned> DWARFAddressSpace, DIFlags Flags, Metadata *ExtraData,
  329. StorageType Storage, bool ShouldCreate) {
  330. assert(isCanonical(Name) && "Expected canonical MDString");
  331. DEFINE_GETIMPL_LOOKUP(DIDerivedType,
  332. (Tag, Name, File, Line, Scope, BaseType, SizeInBits,
  333. AlignInBits, OffsetInBits, DWARFAddressSpace, Flags,
  334. ExtraData));
  335. Metadata *Ops[] = {File, Scope, Name, BaseType, ExtraData};
  336. DEFINE_GETIMPL_STORE(
  337. DIDerivedType, (Tag, Line, SizeInBits, AlignInBits, OffsetInBits,
  338. DWARFAddressSpace, Flags), Ops);
  339. }
  340. DICompositeType *DICompositeType::getImpl(
  341. LLVMContext &Context, unsigned Tag, MDString *Name, Metadata *File,
  342. unsigned Line, Metadata *Scope, Metadata *BaseType, uint64_t SizeInBits,
  343. uint32_t AlignInBits, uint64_t OffsetInBits, DIFlags Flags,
  344. Metadata *Elements, unsigned RuntimeLang, Metadata *VTableHolder,
  345. Metadata *TemplateParams, MDString *Identifier, Metadata *Discriminator,
  346. StorageType Storage, bool ShouldCreate) {
  347. assert(isCanonical(Name) && "Expected canonical MDString");
  348. // Keep this in sync with buildODRType.
  349. DEFINE_GETIMPL_LOOKUP(
  350. DICompositeType, (Tag, Name, File, Line, Scope, BaseType, SizeInBits,
  351. AlignInBits, OffsetInBits, Flags, Elements, RuntimeLang,
  352. VTableHolder, TemplateParams, Identifier, Discriminator));
  353. Metadata *Ops[] = {File, Scope, Name, BaseType,
  354. Elements, VTableHolder, TemplateParams, Identifier,
  355. Discriminator};
  356. DEFINE_GETIMPL_STORE(DICompositeType, (Tag, Line, RuntimeLang, SizeInBits,
  357. AlignInBits, OffsetInBits, Flags),
  358. Ops);
  359. }
  360. DICompositeType *DICompositeType::buildODRType(
  361. LLVMContext &Context, MDString &Identifier, unsigned Tag, MDString *Name,
  362. Metadata *File, unsigned Line, Metadata *Scope, Metadata *BaseType,
  363. uint64_t SizeInBits, uint32_t AlignInBits, uint64_t OffsetInBits,
  364. DIFlags Flags, Metadata *Elements, unsigned RuntimeLang,
  365. Metadata *VTableHolder, Metadata *TemplateParams, Metadata *Discriminator) {
  366. assert(!Identifier.getString().empty() && "Expected valid identifier");
  367. if (!Context.isODRUniquingDebugTypes())
  368. return nullptr;
  369. auto *&CT = (*Context.pImpl->DITypeMap)[&Identifier];
  370. if (!CT)
  371. return CT = DICompositeType::getDistinct(
  372. Context, Tag, Name, File, Line, Scope, BaseType, SizeInBits,
  373. AlignInBits, OffsetInBits, Flags, Elements, RuntimeLang,
  374. VTableHolder, TemplateParams, &Identifier, Discriminator);
  375. // Only mutate CT if it's a forward declaration and the new operands aren't.
  376. assert(CT->getRawIdentifier() == &Identifier && "Wrong ODR identifier?");
  377. if (!CT->isForwardDecl() || (Flags & DINode::FlagFwdDecl))
  378. return CT;
  379. // Mutate CT in place. Keep this in sync with getImpl.
  380. CT->mutate(Tag, Line, RuntimeLang, SizeInBits, AlignInBits, OffsetInBits,
  381. Flags);
  382. Metadata *Ops[] = {File, Scope, Name, BaseType,
  383. Elements, VTableHolder, TemplateParams, &Identifier,
  384. Discriminator};
  385. assert((std::end(Ops) - std::begin(Ops)) == (int)CT->getNumOperands() &&
  386. "Mismatched number of operands");
  387. for (unsigned I = 0, E = CT->getNumOperands(); I != E; ++I)
  388. if (Ops[I] != CT->getOperand(I))
  389. CT->setOperand(I, Ops[I]);
  390. return CT;
  391. }
  392. DICompositeType *DICompositeType::getODRType(
  393. LLVMContext &Context, MDString &Identifier, unsigned Tag, MDString *Name,
  394. Metadata *File, unsigned Line, Metadata *Scope, Metadata *BaseType,
  395. uint64_t SizeInBits, uint32_t AlignInBits, uint64_t OffsetInBits,
  396. DIFlags Flags, Metadata *Elements, unsigned RuntimeLang,
  397. Metadata *VTableHolder, Metadata *TemplateParams, Metadata *Discriminator) {
  398. assert(!Identifier.getString().empty() && "Expected valid identifier");
  399. if (!Context.isODRUniquingDebugTypes())
  400. return nullptr;
  401. auto *&CT = (*Context.pImpl->DITypeMap)[&Identifier];
  402. if (!CT)
  403. CT = DICompositeType::getDistinct(
  404. Context, Tag, Name, File, Line, Scope, BaseType, SizeInBits,
  405. AlignInBits, OffsetInBits, Flags, Elements, RuntimeLang, VTableHolder,
  406. TemplateParams, &Identifier, Discriminator);
  407. return CT;
  408. }
  409. DICompositeType *DICompositeType::getODRTypeIfExists(LLVMContext &Context,
  410. MDString &Identifier) {
  411. assert(!Identifier.getString().empty() && "Expected valid identifier");
  412. if (!Context.isODRUniquingDebugTypes())
  413. return nullptr;
  414. return Context.pImpl->DITypeMap->lookup(&Identifier);
  415. }
  416. DISubroutineType *DISubroutineType::getImpl(LLVMContext &Context, DIFlags Flags,
  417. uint8_t CC, Metadata *TypeArray,
  418. StorageType Storage,
  419. bool ShouldCreate) {
  420. DEFINE_GETIMPL_LOOKUP(DISubroutineType, (Flags, CC, TypeArray));
  421. Metadata *Ops[] = {nullptr, nullptr, nullptr, TypeArray};
  422. DEFINE_GETIMPL_STORE(DISubroutineType, (Flags, CC), Ops);
  423. }
  424. // FIXME: Implement this string-enum correspondence with a .def file and macros,
  425. // so that the association is explicit rather than implied.
  426. static const char *ChecksumKindName[DIFile::CSK_Last] = {
  427. "CSK_MD5",
  428. "CSK_SHA1"
  429. };
  430. StringRef DIFile::getChecksumKindAsString(ChecksumKind CSKind) {
  431. assert(CSKind <= DIFile::CSK_Last && "Invalid checksum kind");
  432. // The first space was originally the CSK_None variant, which is now
  433. // obsolete, but the space is still reserved in ChecksumKind, so we account
  434. // for it here.
  435. return ChecksumKindName[CSKind - 1];
  436. }
  437. Optional<DIFile::ChecksumKind> DIFile::getChecksumKind(StringRef CSKindStr) {
  438. return StringSwitch<Optional<DIFile::ChecksumKind>>(CSKindStr)
  439. .Case("CSK_MD5", DIFile::CSK_MD5)
  440. .Case("CSK_SHA1", DIFile::CSK_SHA1)
  441. .Default(None);
  442. }
  443. DIFile *DIFile::getImpl(LLVMContext &Context, MDString *Filename,
  444. MDString *Directory,
  445. Optional<DIFile::ChecksumInfo<MDString *>> CS,
  446. Optional<MDString *> Source, StorageType Storage,
  447. bool ShouldCreate) {
  448. assert(isCanonical(Filename) && "Expected canonical MDString");
  449. assert(isCanonical(Directory) && "Expected canonical MDString");
  450. assert((!CS || isCanonical(CS->Value)) && "Expected canonical MDString");
  451. assert((!Source || isCanonical(*Source)) && "Expected canonical MDString");
  452. DEFINE_GETIMPL_LOOKUP(DIFile, (Filename, Directory, CS, Source));
  453. Metadata *Ops[] = {Filename, Directory, CS ? CS->Value : nullptr,
  454. Source.getValueOr(nullptr)};
  455. DEFINE_GETIMPL_STORE(DIFile, (CS, Source), Ops);
  456. }
  457. DICompileUnit *DICompileUnit::getImpl(
  458. LLVMContext &Context, unsigned SourceLanguage, Metadata *File,
  459. MDString *Producer, bool IsOptimized, MDString *Flags,
  460. unsigned RuntimeVersion, MDString *SplitDebugFilename,
  461. unsigned EmissionKind, Metadata *EnumTypes, Metadata *RetainedTypes,
  462. Metadata *GlobalVariables, Metadata *ImportedEntities, Metadata *Macros,
  463. uint64_t DWOId, bool SplitDebugInlining, bool DebugInfoForProfiling,
  464. unsigned NameTableKind, bool RangesBaseAddress, StorageType Storage,
  465. bool ShouldCreate) {
  466. assert(Storage != Uniqued && "Cannot unique DICompileUnit");
  467. assert(isCanonical(Producer) && "Expected canonical MDString");
  468. assert(isCanonical(Flags) && "Expected canonical MDString");
  469. assert(isCanonical(SplitDebugFilename) && "Expected canonical MDString");
  470. Metadata *Ops[] = {
  471. File, Producer, Flags, SplitDebugFilename,
  472. EnumTypes, RetainedTypes, GlobalVariables, ImportedEntities,
  473. Macros};
  474. return storeImpl(new (array_lengthof(Ops)) DICompileUnit(
  475. Context, Storage, SourceLanguage, IsOptimized,
  476. RuntimeVersion, EmissionKind, DWOId, SplitDebugInlining,
  477. DebugInfoForProfiling, NameTableKind, RangesBaseAddress,
  478. Ops),
  479. Storage);
  480. }
  481. Optional<DICompileUnit::DebugEmissionKind>
  482. DICompileUnit::getEmissionKind(StringRef Str) {
  483. return StringSwitch<Optional<DebugEmissionKind>>(Str)
  484. .Case("NoDebug", NoDebug)
  485. .Case("FullDebug", FullDebug)
  486. .Case("LineTablesOnly", LineTablesOnly)
  487. .Case("DebugDirectivesOnly", DebugDirectivesOnly)
  488. .Default(None);
  489. }
  490. Optional<DICompileUnit::DebugNameTableKind>
  491. DICompileUnit::getNameTableKind(StringRef Str) {
  492. return StringSwitch<Optional<DebugNameTableKind>>(Str)
  493. .Case("Default", DebugNameTableKind::Default)
  494. .Case("GNU", DebugNameTableKind::GNU)
  495. .Case("None", DebugNameTableKind::None)
  496. .Default(None);
  497. }
  498. const char *DICompileUnit::emissionKindString(DebugEmissionKind EK) {
  499. switch (EK) {
  500. case NoDebug: return "NoDebug";
  501. case FullDebug: return "FullDebug";
  502. case LineTablesOnly: return "LineTablesOnly";
  503. case DebugDirectivesOnly: return "DebugDirectivesOnly";
  504. }
  505. return nullptr;
  506. }
  507. const char *DICompileUnit::nameTableKindString(DebugNameTableKind NTK) {
  508. switch (NTK) {
  509. case DebugNameTableKind::Default:
  510. return nullptr;
  511. case DebugNameTableKind::GNU:
  512. return "GNU";
  513. case DebugNameTableKind::None:
  514. return "None";
  515. }
  516. return nullptr;
  517. }
  518. DISubprogram *DILocalScope::getSubprogram() const {
  519. if (auto *Block = dyn_cast<DILexicalBlockBase>(this))
  520. return Block->getScope()->getSubprogram();
  521. return const_cast<DISubprogram *>(cast<DISubprogram>(this));
  522. }
  523. DILocalScope *DILocalScope::getNonLexicalBlockFileScope() const {
  524. if (auto *File = dyn_cast<DILexicalBlockFile>(this))
  525. return File->getScope()->getNonLexicalBlockFileScope();
  526. return const_cast<DILocalScope *>(this);
  527. }
  528. DISubprogram::DISPFlags DISubprogram::getFlag(StringRef Flag) {
  529. return StringSwitch<DISPFlags>(Flag)
  530. #define HANDLE_DISP_FLAG(ID, NAME) .Case("DISPFlag" #NAME, SPFlag##NAME)
  531. #include "llvm/IR/DebugInfoFlags.def"
  532. .Default(SPFlagZero);
  533. }
  534. StringRef DISubprogram::getFlagString(DISPFlags Flag) {
  535. switch (Flag) {
  536. // Appease a warning.
  537. case SPFlagVirtuality:
  538. return "";
  539. #define HANDLE_DISP_FLAG(ID, NAME) \
  540. case SPFlag##NAME: \
  541. return "DISPFlag" #NAME;
  542. #include "llvm/IR/DebugInfoFlags.def"
  543. }
  544. return "";
  545. }
  546. DISubprogram::DISPFlags
  547. DISubprogram::splitFlags(DISPFlags Flags,
  548. SmallVectorImpl<DISPFlags> &SplitFlags) {
  549. // Multi-bit fields can require special handling. In our case, however, the
  550. // only multi-bit field is virtuality, and all its values happen to be
  551. // single-bit values, so the right behavior just falls out.
  552. #define HANDLE_DISP_FLAG(ID, NAME) \
  553. if (DISPFlags Bit = Flags & SPFlag##NAME) { \
  554. SplitFlags.push_back(Bit); \
  555. Flags &= ~Bit; \
  556. }
  557. #include "llvm/IR/DebugInfoFlags.def"
  558. return Flags;
  559. }
  560. DISubprogram *DISubprogram::getImpl(
  561. LLVMContext &Context, Metadata *Scope, MDString *Name,
  562. MDString *LinkageName, Metadata *File, unsigned Line, Metadata *Type,
  563. unsigned ScopeLine, Metadata *ContainingType, unsigned VirtualIndex,
  564. int ThisAdjustment, DIFlags Flags, DISPFlags SPFlags, Metadata *Unit,
  565. Metadata *TemplateParams, Metadata *Declaration, Metadata *RetainedNodes,
  566. Metadata *ThrownTypes, StorageType Storage, bool ShouldCreate) {
  567. assert(isCanonical(Name) && "Expected canonical MDString");
  568. assert(isCanonical(LinkageName) && "Expected canonical MDString");
  569. DEFINE_GETIMPL_LOOKUP(DISubprogram,
  570. (Scope, Name, LinkageName, File, Line, Type, ScopeLine,
  571. ContainingType, VirtualIndex, ThisAdjustment, Flags,
  572. SPFlags, Unit, TemplateParams, Declaration,
  573. RetainedNodes, ThrownTypes));
  574. SmallVector<Metadata *, 11> Ops = {
  575. File, Scope, Name, LinkageName, Type, Unit,
  576. Declaration, RetainedNodes, ContainingType, TemplateParams, ThrownTypes};
  577. if (!ThrownTypes) {
  578. Ops.pop_back();
  579. if (!TemplateParams) {
  580. Ops.pop_back();
  581. if (!ContainingType)
  582. Ops.pop_back();
  583. }
  584. }
  585. DEFINE_GETIMPL_STORE_N(
  586. DISubprogram,
  587. (Line, ScopeLine, VirtualIndex, ThisAdjustment, Flags, SPFlags), Ops,
  588. Ops.size());
  589. }
  590. bool DISubprogram::describes(const Function *F) const {
  591. assert(F && "Invalid function");
  592. if (F->getSubprogram() == this)
  593. return true;
  594. StringRef Name = getLinkageName();
  595. if (Name.empty())
  596. Name = getName();
  597. return F->getName() == Name;
  598. }
  599. DILexicalBlock *DILexicalBlock::getImpl(LLVMContext &Context, Metadata *Scope,
  600. Metadata *File, unsigned Line,
  601. unsigned Column, StorageType Storage,
  602. bool ShouldCreate) {
  603. // Fixup column.
  604. adjustColumn(Column);
  605. assert(Scope && "Expected scope");
  606. DEFINE_GETIMPL_LOOKUP(DILexicalBlock, (Scope, File, Line, Column));
  607. Metadata *Ops[] = {File, Scope};
  608. DEFINE_GETIMPL_STORE(DILexicalBlock, (Line, Column), Ops);
  609. }
  610. DILexicalBlockFile *DILexicalBlockFile::getImpl(LLVMContext &Context,
  611. Metadata *Scope, Metadata *File,
  612. unsigned Discriminator,
  613. StorageType Storage,
  614. bool ShouldCreate) {
  615. assert(Scope && "Expected scope");
  616. DEFINE_GETIMPL_LOOKUP(DILexicalBlockFile, (Scope, File, Discriminator));
  617. Metadata *Ops[] = {File, Scope};
  618. DEFINE_GETIMPL_STORE(DILexicalBlockFile, (Discriminator), Ops);
  619. }
  620. DINamespace *DINamespace::getImpl(LLVMContext &Context, Metadata *Scope,
  621. MDString *Name, bool ExportSymbols,
  622. StorageType Storage, bool ShouldCreate) {
  623. assert(isCanonical(Name) && "Expected canonical MDString");
  624. DEFINE_GETIMPL_LOOKUP(DINamespace, (Scope, Name, ExportSymbols));
  625. // The nullptr is for DIScope's File operand. This should be refactored.
  626. Metadata *Ops[] = {nullptr, Scope, Name};
  627. DEFINE_GETIMPL_STORE(DINamespace, (ExportSymbols), Ops);
  628. }
  629. DICommonBlock *DICommonBlock::getImpl(LLVMContext &Context, Metadata *Scope,
  630. Metadata *Decl, MDString *Name,
  631. Metadata *File, unsigned LineNo,
  632. StorageType Storage, bool ShouldCreate) {
  633. assert(isCanonical(Name) && "Expected canonical MDString");
  634. DEFINE_GETIMPL_LOOKUP(DICommonBlock, (Scope, Decl, Name, File, LineNo));
  635. // The nullptr is for DIScope's File operand. This should be refactored.
  636. Metadata *Ops[] = {Scope, Decl, Name, File};
  637. DEFINE_GETIMPL_STORE(DICommonBlock, (LineNo), Ops);
  638. }
  639. DIModule *DIModule::getImpl(LLVMContext &Context, Metadata *Scope,
  640. MDString *Name, MDString *ConfigurationMacros,
  641. MDString *IncludePath, MDString *ISysRoot,
  642. StorageType Storage, bool ShouldCreate) {
  643. assert(isCanonical(Name) && "Expected canonical MDString");
  644. DEFINE_GETIMPL_LOOKUP(
  645. DIModule, (Scope, Name, ConfigurationMacros, IncludePath, ISysRoot));
  646. Metadata *Ops[] = {Scope, Name, ConfigurationMacros, IncludePath, ISysRoot};
  647. DEFINE_GETIMPL_STORE_NO_CONSTRUCTOR_ARGS(DIModule, Ops);
  648. }
  649. DITemplateTypeParameter *DITemplateTypeParameter::getImpl(LLVMContext &Context,
  650. MDString *Name,
  651. Metadata *Type,
  652. StorageType Storage,
  653. bool ShouldCreate) {
  654. assert(isCanonical(Name) && "Expected canonical MDString");
  655. DEFINE_GETIMPL_LOOKUP(DITemplateTypeParameter, (Name, Type));
  656. Metadata *Ops[] = {Name, Type};
  657. DEFINE_GETIMPL_STORE_NO_CONSTRUCTOR_ARGS(DITemplateTypeParameter, Ops);
  658. }
  659. DITemplateValueParameter *DITemplateValueParameter::getImpl(
  660. LLVMContext &Context, unsigned Tag, MDString *Name, Metadata *Type,
  661. Metadata *Value, StorageType Storage, bool ShouldCreate) {
  662. assert(isCanonical(Name) && "Expected canonical MDString");
  663. DEFINE_GETIMPL_LOOKUP(DITemplateValueParameter, (Tag, Name, Type, Value));
  664. Metadata *Ops[] = {Name, Type, Value};
  665. DEFINE_GETIMPL_STORE(DITemplateValueParameter, (Tag), Ops);
  666. }
  667. DIGlobalVariable *
  668. DIGlobalVariable::getImpl(LLVMContext &Context, Metadata *Scope, MDString *Name,
  669. MDString *LinkageName, Metadata *File, unsigned Line,
  670. Metadata *Type, bool IsLocalToUnit, bool IsDefinition,
  671. Metadata *StaticDataMemberDeclaration,
  672. Metadata *TemplateParams, uint32_t AlignInBits,
  673. StorageType Storage, bool ShouldCreate) {
  674. assert(isCanonical(Name) && "Expected canonical MDString");
  675. assert(isCanonical(LinkageName) && "Expected canonical MDString");
  676. DEFINE_GETIMPL_LOOKUP(DIGlobalVariable, (Scope, Name, LinkageName, File, Line,
  677. Type, IsLocalToUnit, IsDefinition,
  678. StaticDataMemberDeclaration,
  679. TemplateParams, AlignInBits));
  680. Metadata *Ops[] = {Scope,
  681. Name,
  682. File,
  683. Type,
  684. Name,
  685. LinkageName,
  686. StaticDataMemberDeclaration,
  687. TemplateParams};
  688. DEFINE_GETIMPL_STORE(DIGlobalVariable,
  689. (Line, IsLocalToUnit, IsDefinition, AlignInBits), Ops);
  690. }
  691. DILocalVariable *DILocalVariable::getImpl(LLVMContext &Context, Metadata *Scope,
  692. MDString *Name, Metadata *File,
  693. unsigned Line, Metadata *Type,
  694. unsigned Arg, DIFlags Flags,
  695. uint32_t AlignInBits,
  696. StorageType Storage,
  697. bool ShouldCreate) {
  698. // 64K ought to be enough for any frontend.
  699. assert(Arg <= UINT16_MAX && "Expected argument number to fit in 16-bits");
  700. assert(Scope && "Expected scope");
  701. assert(isCanonical(Name) && "Expected canonical MDString");
  702. DEFINE_GETIMPL_LOOKUP(DILocalVariable,
  703. (Scope, Name, File, Line, Type, Arg, Flags,
  704. AlignInBits));
  705. Metadata *Ops[] = {Scope, Name, File, Type};
  706. DEFINE_GETIMPL_STORE(DILocalVariable, (Line, Arg, Flags, AlignInBits), Ops);
  707. }
  708. Optional<uint64_t> DIVariable::getSizeInBits() const {
  709. // This is used by the Verifier so be mindful of broken types.
  710. const Metadata *RawType = getRawType();
  711. while (RawType) {
  712. // Try to get the size directly.
  713. if (auto *T = dyn_cast<DIType>(RawType))
  714. if (uint64_t Size = T->getSizeInBits())
  715. return Size;
  716. if (auto *DT = dyn_cast<DIDerivedType>(RawType)) {
  717. // Look at the base type.
  718. RawType = DT->getRawBaseType();
  719. continue;
  720. }
  721. // Missing type or size.
  722. break;
  723. }
  724. // Fail gracefully.
  725. return None;
  726. }
  727. DILabel *DILabel::getImpl(LLVMContext &Context, Metadata *Scope,
  728. MDString *Name, Metadata *File, unsigned Line,
  729. StorageType Storage,
  730. bool ShouldCreate) {
  731. assert(Scope && "Expected scope");
  732. assert(isCanonical(Name) && "Expected canonical MDString");
  733. DEFINE_GETIMPL_LOOKUP(DILabel,
  734. (Scope, Name, File, Line));
  735. Metadata *Ops[] = {Scope, Name, File};
  736. DEFINE_GETIMPL_STORE(DILabel, (Line), Ops);
  737. }
  738. DIExpression *DIExpression::getImpl(LLVMContext &Context,
  739. ArrayRef<uint64_t> Elements,
  740. StorageType Storage, bool ShouldCreate) {
  741. DEFINE_GETIMPL_LOOKUP(DIExpression, (Elements));
  742. DEFINE_GETIMPL_STORE_NO_OPS(DIExpression, (Elements));
  743. }
  744. unsigned DIExpression::ExprOperand::getSize() const {
  745. uint64_t Op = getOp();
  746. if (Op >= dwarf::DW_OP_breg0 && Op <= dwarf::DW_OP_breg31)
  747. return 2;
  748. switch (Op) {
  749. case dwarf::DW_OP_LLVM_convert:
  750. case dwarf::DW_OP_LLVM_fragment:
  751. case dwarf::DW_OP_bregx:
  752. return 3;
  753. case dwarf::DW_OP_constu:
  754. case dwarf::DW_OP_consts:
  755. case dwarf::DW_OP_deref_size:
  756. case dwarf::DW_OP_plus_uconst:
  757. case dwarf::DW_OP_LLVM_tag_offset:
  758. case dwarf::DW_OP_entry_value:
  759. case dwarf::DW_OP_regx:
  760. return 2;
  761. default:
  762. return 1;
  763. }
  764. }
  765. bool DIExpression::isValid() const {
  766. for (auto I = expr_op_begin(), E = expr_op_end(); I != E; ++I) {
  767. // Check that there's space for the operand.
  768. if (I->get() + I->getSize() > E->get())
  769. return false;
  770. uint64_t Op = I->getOp();
  771. if ((Op >= dwarf::DW_OP_reg0 && Op <= dwarf::DW_OP_reg31) ||
  772. (Op >= dwarf::DW_OP_breg0 && Op <= dwarf::DW_OP_breg31))
  773. return true;
  774. // Check that the operand is valid.
  775. switch (Op) {
  776. default:
  777. return false;
  778. case dwarf::DW_OP_LLVM_fragment:
  779. // A fragment operator must appear at the end.
  780. return I->get() + I->getSize() == E->get();
  781. case dwarf::DW_OP_stack_value: {
  782. // Must be the last one or followed by a DW_OP_LLVM_fragment.
  783. if (I->get() + I->getSize() == E->get())
  784. break;
  785. auto J = I;
  786. if ((++J)->getOp() != dwarf::DW_OP_LLVM_fragment)
  787. return false;
  788. break;
  789. }
  790. case dwarf::DW_OP_swap: {
  791. // Must be more than one implicit element on the stack.
  792. // FIXME: A better way to implement this would be to add a local variable
  793. // that keeps track of the stack depth and introduce something like a
  794. // DW_LLVM_OP_implicit_location as a placeholder for the location this
  795. // DIExpression is attached to, or else pass the number of implicit stack
  796. // elements into isValid.
  797. if (getNumElements() == 1)
  798. return false;
  799. break;
  800. }
  801. case dwarf::DW_OP_entry_value: {
  802. // An entry value operator must appear at the begin and the size
  803. // of following expression should be 1, because we support only
  804. // entry values of a simple register location.
  805. return I->get() == expr_op_begin()->get() && I->getArg(0) == 1 &&
  806. getNumElements() == 2;
  807. }
  808. case dwarf::DW_OP_LLVM_convert:
  809. case dwarf::DW_OP_LLVM_tag_offset:
  810. case dwarf::DW_OP_constu:
  811. case dwarf::DW_OP_plus_uconst:
  812. case dwarf::DW_OP_plus:
  813. case dwarf::DW_OP_minus:
  814. case dwarf::DW_OP_mul:
  815. case dwarf::DW_OP_div:
  816. case dwarf::DW_OP_mod:
  817. case dwarf::DW_OP_or:
  818. case dwarf::DW_OP_and:
  819. case dwarf::DW_OP_xor:
  820. case dwarf::DW_OP_shl:
  821. case dwarf::DW_OP_shr:
  822. case dwarf::DW_OP_shra:
  823. case dwarf::DW_OP_deref:
  824. case dwarf::DW_OP_deref_size:
  825. case dwarf::DW_OP_xderef:
  826. case dwarf::DW_OP_lit0:
  827. case dwarf::DW_OP_not:
  828. case dwarf::DW_OP_dup:
  829. case dwarf::DW_OP_regx:
  830. case dwarf::DW_OP_bregx:
  831. break;
  832. }
  833. }
  834. return true;
  835. }
  836. bool DIExpression::isImplicit() const {
  837. unsigned N = getNumElements();
  838. if (isValid() && N > 0) {
  839. switch (getElement(N-1)) {
  840. case dwarf::DW_OP_stack_value:
  841. case dwarf::DW_OP_LLVM_tag_offset:
  842. return true;
  843. case dwarf::DW_OP_LLVM_fragment:
  844. return N > 1 && getElement(N-2) == dwarf::DW_OP_stack_value;
  845. default: break;
  846. }
  847. }
  848. return false;
  849. }
  850. bool DIExpression::isComplex() const {
  851. if (!isValid())
  852. return false;
  853. if (getNumElements() == 0)
  854. return false;
  855. // If there are any elements other than fragment or tag_offset, then some
  856. // kind of complex computation occurs.
  857. for (const auto &It : expr_ops()) {
  858. switch (It.getOp()) {
  859. case dwarf::DW_OP_LLVM_tag_offset:
  860. case dwarf::DW_OP_LLVM_fragment:
  861. continue;
  862. default: return true;
  863. }
  864. }
  865. return false;
  866. }
  867. Optional<DIExpression::FragmentInfo>
  868. DIExpression::getFragmentInfo(expr_op_iterator Start, expr_op_iterator End) {
  869. for (auto I = Start; I != End; ++I)
  870. if (I->getOp() == dwarf::DW_OP_LLVM_fragment) {
  871. DIExpression::FragmentInfo Info = {I->getArg(1), I->getArg(0)};
  872. return Info;
  873. }
  874. return None;
  875. }
  876. void DIExpression::appendOffset(SmallVectorImpl<uint64_t> &Ops,
  877. int64_t Offset) {
  878. if (Offset > 0) {
  879. Ops.push_back(dwarf::DW_OP_plus_uconst);
  880. Ops.push_back(Offset);
  881. } else if (Offset < 0) {
  882. Ops.push_back(dwarf::DW_OP_constu);
  883. Ops.push_back(-Offset);
  884. Ops.push_back(dwarf::DW_OP_minus);
  885. }
  886. }
  887. bool DIExpression::extractIfOffset(int64_t &Offset) const {
  888. if (getNumElements() == 0) {
  889. Offset = 0;
  890. return true;
  891. }
  892. if (getNumElements() == 2 && Elements[0] == dwarf::DW_OP_plus_uconst) {
  893. Offset = Elements[1];
  894. return true;
  895. }
  896. if (getNumElements() == 3 && Elements[0] == dwarf::DW_OP_constu) {
  897. if (Elements[2] == dwarf::DW_OP_plus) {
  898. Offset = Elements[1];
  899. return true;
  900. }
  901. if (Elements[2] == dwarf::DW_OP_minus) {
  902. Offset = -Elements[1];
  903. return true;
  904. }
  905. }
  906. return false;
  907. }
  908. const DIExpression *DIExpression::extractAddressClass(const DIExpression *Expr,
  909. unsigned &AddrClass) {
  910. const unsigned PatternSize = 4;
  911. if (Expr->Elements.size() >= PatternSize &&
  912. Expr->Elements[PatternSize - 4] == dwarf::DW_OP_constu &&
  913. Expr->Elements[PatternSize - 2] == dwarf::DW_OP_swap &&
  914. Expr->Elements[PatternSize - 1] == dwarf::DW_OP_xderef) {
  915. AddrClass = Expr->Elements[PatternSize - 3];
  916. if (Expr->Elements.size() == PatternSize)
  917. return nullptr;
  918. return DIExpression::get(Expr->getContext(),
  919. makeArrayRef(&*Expr->Elements.begin(),
  920. Expr->Elements.size() - PatternSize));
  921. }
  922. return Expr;
  923. }
  924. DIExpression *DIExpression::prepend(const DIExpression *Expr, uint8_t Flags,
  925. int64_t Offset) {
  926. SmallVector<uint64_t, 8> Ops;
  927. if (Flags & DIExpression::DerefBefore)
  928. Ops.push_back(dwarf::DW_OP_deref);
  929. appendOffset(Ops, Offset);
  930. if (Flags & DIExpression::DerefAfter)
  931. Ops.push_back(dwarf::DW_OP_deref);
  932. bool StackValue = Flags & DIExpression::StackValue;
  933. bool EntryValue = Flags & DIExpression::EntryValue;
  934. return prependOpcodes(Expr, Ops, StackValue, EntryValue);
  935. }
  936. DIExpression *DIExpression::prependOpcodes(const DIExpression *Expr,
  937. SmallVectorImpl<uint64_t> &Ops,
  938. bool StackValue,
  939. bool EntryValue) {
  940. assert(Expr && "Can't prepend ops to this expression");
  941. if (EntryValue) {
  942. Ops.push_back(dwarf::DW_OP_entry_value);
  943. // Add size info needed for entry value expression.
  944. // Add plus one for target register operand.
  945. Ops.push_back(Expr->getNumElements() + 1);
  946. }
  947. // If there are no ops to prepend, do not even add the DW_OP_stack_value.
  948. if (Ops.empty())
  949. StackValue = false;
  950. for (auto Op : Expr->expr_ops()) {
  951. // A DW_OP_stack_value comes at the end, but before a DW_OP_LLVM_fragment.
  952. if (StackValue) {
  953. if (Op.getOp() == dwarf::DW_OP_stack_value)
  954. StackValue = false;
  955. else if (Op.getOp() == dwarf::DW_OP_LLVM_fragment) {
  956. Ops.push_back(dwarf::DW_OP_stack_value);
  957. StackValue = false;
  958. }
  959. }
  960. Op.appendToVector(Ops);
  961. }
  962. if (StackValue)
  963. Ops.push_back(dwarf::DW_OP_stack_value);
  964. return DIExpression::get(Expr->getContext(), Ops);
  965. }
  966. DIExpression *DIExpression::append(const DIExpression *Expr,
  967. ArrayRef<uint64_t> Ops) {
  968. assert(Expr && !Ops.empty() && "Can't append ops to this expression");
  969. // Copy Expr's current op list.
  970. SmallVector<uint64_t, 16> NewOps;
  971. for (auto Op : Expr->expr_ops()) {
  972. // Append new opcodes before DW_OP_{stack_value, LLVM_fragment}.
  973. if (Op.getOp() == dwarf::DW_OP_stack_value ||
  974. Op.getOp() == dwarf::DW_OP_LLVM_fragment) {
  975. NewOps.append(Ops.begin(), Ops.end());
  976. // Ensure that the new opcodes are only appended once.
  977. Ops = None;
  978. }
  979. Op.appendToVector(NewOps);
  980. }
  981. NewOps.append(Ops.begin(), Ops.end());
  982. return DIExpression::get(Expr->getContext(), NewOps);
  983. }
  984. DIExpression *DIExpression::appendToStack(const DIExpression *Expr,
  985. ArrayRef<uint64_t> Ops) {
  986. assert(Expr && !Ops.empty() && "Can't append ops to this expression");
  987. assert(none_of(Ops,
  988. [](uint64_t Op) {
  989. return Op == dwarf::DW_OP_stack_value ||
  990. Op == dwarf::DW_OP_LLVM_fragment;
  991. }) &&
  992. "Can't append this op");
  993. // Append a DW_OP_deref after Expr's current op list if it's non-empty and
  994. // has no DW_OP_stack_value.
  995. //
  996. // Match .* DW_OP_stack_value (DW_OP_LLVM_fragment A B)?.
  997. Optional<FragmentInfo> FI = Expr->getFragmentInfo();
  998. unsigned DropUntilStackValue = FI.hasValue() ? 3 : 0;
  999. ArrayRef<uint64_t> ExprOpsBeforeFragment =
  1000. Expr->getElements().drop_back(DropUntilStackValue);
  1001. bool NeedsDeref = (Expr->getNumElements() > DropUntilStackValue) &&
  1002. (ExprOpsBeforeFragment.back() != dwarf::DW_OP_stack_value);
  1003. bool NeedsStackValue = NeedsDeref || ExprOpsBeforeFragment.empty();
  1004. // Append a DW_OP_deref after Expr's current op list if needed, then append
  1005. // the new ops, and finally ensure that a single DW_OP_stack_value is present.
  1006. SmallVector<uint64_t, 16> NewOps;
  1007. if (NeedsDeref)
  1008. NewOps.push_back(dwarf::DW_OP_deref);
  1009. NewOps.append(Ops.begin(), Ops.end());
  1010. if (NeedsStackValue)
  1011. NewOps.push_back(dwarf::DW_OP_stack_value);
  1012. return DIExpression::append(Expr, NewOps);
  1013. }
  1014. Optional<DIExpression *> DIExpression::createFragmentExpression(
  1015. const DIExpression *Expr, unsigned OffsetInBits, unsigned SizeInBits) {
  1016. SmallVector<uint64_t, 8> Ops;
  1017. // Copy over the expression, but leave off any trailing DW_OP_LLVM_fragment.
  1018. if (Expr) {
  1019. for (auto Op : Expr->expr_ops()) {
  1020. switch (Op.getOp()) {
  1021. default: break;
  1022. case dwarf::DW_OP_plus:
  1023. case dwarf::DW_OP_minus:
  1024. // We can't safely split arithmetic into multiple fragments because we
  1025. // can't express carry-over between fragments.
  1026. //
  1027. // FIXME: We *could* preserve the lowest fragment of a constant offset
  1028. // operation if the offset fits into SizeInBits.
  1029. return None;
  1030. case dwarf::DW_OP_LLVM_fragment: {
  1031. // Make the new offset point into the existing fragment.
  1032. uint64_t FragmentOffsetInBits = Op.getArg(0);
  1033. uint64_t FragmentSizeInBits = Op.getArg(1);
  1034. (void)FragmentSizeInBits;
  1035. assert((OffsetInBits + SizeInBits <= FragmentSizeInBits) &&
  1036. "new fragment outside of original fragment");
  1037. OffsetInBits += FragmentOffsetInBits;
  1038. continue;
  1039. }
  1040. }
  1041. Op.appendToVector(Ops);
  1042. }
  1043. }
  1044. Ops.push_back(dwarf::DW_OP_LLVM_fragment);
  1045. Ops.push_back(OffsetInBits);
  1046. Ops.push_back(SizeInBits);
  1047. return DIExpression::get(Expr->getContext(), Ops);
  1048. }
  1049. bool DIExpression::isConstant() const {
  1050. // Recognize DW_OP_constu C DW_OP_stack_value (DW_OP_LLVM_fragment Len Ofs)?.
  1051. if (getNumElements() != 3 && getNumElements() != 6)
  1052. return false;
  1053. if (getElement(0) != dwarf::DW_OP_constu ||
  1054. getElement(2) != dwarf::DW_OP_stack_value)
  1055. return false;
  1056. if (getNumElements() == 6 && getElement(3) != dwarf::DW_OP_LLVM_fragment)
  1057. return false;
  1058. return true;
  1059. }
  1060. DIGlobalVariableExpression *
  1061. DIGlobalVariableExpression::getImpl(LLVMContext &Context, Metadata *Variable,
  1062. Metadata *Expression, StorageType Storage,
  1063. bool ShouldCreate) {
  1064. DEFINE_GETIMPL_LOOKUP(DIGlobalVariableExpression, (Variable, Expression));
  1065. Metadata *Ops[] = {Variable, Expression};
  1066. DEFINE_GETIMPL_STORE_NO_CONSTRUCTOR_ARGS(DIGlobalVariableExpression, Ops);
  1067. }
  1068. DIObjCProperty *DIObjCProperty::getImpl(
  1069. LLVMContext &Context, MDString *Name, Metadata *File, unsigned Line,
  1070. MDString *GetterName, MDString *SetterName, unsigned Attributes,
  1071. Metadata *Type, StorageType Storage, bool ShouldCreate) {
  1072. assert(isCanonical(Name) && "Expected canonical MDString");
  1073. assert(isCanonical(GetterName) && "Expected canonical MDString");
  1074. assert(isCanonical(SetterName) && "Expected canonical MDString");
  1075. DEFINE_GETIMPL_LOOKUP(DIObjCProperty, (Name, File, Line, GetterName,
  1076. SetterName, Attributes, Type));
  1077. Metadata *Ops[] = {Name, File, GetterName, SetterName, Type};
  1078. DEFINE_GETIMPL_STORE(DIObjCProperty, (Line, Attributes), Ops);
  1079. }
  1080. DIImportedEntity *DIImportedEntity::getImpl(LLVMContext &Context, unsigned Tag,
  1081. Metadata *Scope, Metadata *Entity,
  1082. Metadata *File, unsigned Line,
  1083. MDString *Name, StorageType Storage,
  1084. bool ShouldCreate) {
  1085. assert(isCanonical(Name) && "Expected canonical MDString");
  1086. DEFINE_GETIMPL_LOOKUP(DIImportedEntity,
  1087. (Tag, Scope, Entity, File, Line, Name));
  1088. Metadata *Ops[] = {Scope, Entity, Name, File};
  1089. DEFINE_GETIMPL_STORE(DIImportedEntity, (Tag, Line), Ops);
  1090. }
  1091. DIMacro *DIMacro::getImpl(LLVMContext &Context, unsigned MIType,
  1092. unsigned Line, MDString *Name, MDString *Value,
  1093. StorageType Storage, bool ShouldCreate) {
  1094. assert(isCanonical(Name) && "Expected canonical MDString");
  1095. DEFINE_GETIMPL_LOOKUP(DIMacro, (MIType, Line, Name, Value));
  1096. Metadata *Ops[] = { Name, Value };
  1097. DEFINE_GETIMPL_STORE(DIMacro, (MIType, Line), Ops);
  1098. }
  1099. DIMacroFile *DIMacroFile::getImpl(LLVMContext &Context, unsigned MIType,
  1100. unsigned Line, Metadata *File,
  1101. Metadata *Elements, StorageType Storage,
  1102. bool ShouldCreate) {
  1103. DEFINE_GETIMPL_LOOKUP(DIMacroFile,
  1104. (MIType, Line, File, Elements));
  1105. Metadata *Ops[] = { File, Elements };
  1106. DEFINE_GETIMPL_STORE(DIMacroFile, (MIType, Line), Ops);
  1107. }