DebugInfoMetadata.cpp 63 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692
  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/Function.h"
  18. #include "llvm/IR/Type.h"
  19. #include "llvm/IR/Value.h"
  20. #include <numeric>
  21. using namespace llvm;
  22. namespace llvm {
  23. // Use FS-AFDO discriminator.
  24. cl::opt<bool> EnableFSDiscriminator(
  25. "enable-fs-discriminator", cl::Hidden, cl::init(false),
  26. cl::desc("Enable adding flow sensitive discriminators"));
  27. } // namespace llvm
  28. const DIExpression::FragmentInfo DebugVariable::DefaultFragment = {
  29. std::numeric_limits<uint64_t>::max(), std::numeric_limits<uint64_t>::min()};
  30. DILocation::DILocation(LLVMContext &C, StorageType Storage, unsigned Line,
  31. unsigned Column, ArrayRef<Metadata *> MDs,
  32. bool ImplicitCode)
  33. : MDNode(C, DILocationKind, Storage, MDs) {
  34. assert((MDs.size() == 1 || MDs.size() == 2) &&
  35. "Expected a scope and optional inlined-at");
  36. // Set line and column.
  37. assert(Column < (1u << 16) && "Expected 16-bit column");
  38. SubclassData32 = Line;
  39. SubclassData16 = Column;
  40. setImplicitCode(ImplicitCode);
  41. }
  42. static void adjustColumn(unsigned &Column) {
  43. // Set to unknown on overflow. We only have 16 bits to play with here.
  44. if (Column >= (1u << 16))
  45. Column = 0;
  46. }
  47. DILocation *DILocation::getImpl(LLVMContext &Context, unsigned Line,
  48. unsigned Column, Metadata *Scope,
  49. Metadata *InlinedAt, bool ImplicitCode,
  50. StorageType Storage, bool ShouldCreate) {
  51. // Fixup column.
  52. adjustColumn(Column);
  53. if (Storage == Uniqued) {
  54. if (auto *N = getUniqued(Context.pImpl->DILocations,
  55. DILocationInfo::KeyTy(Line, Column, Scope,
  56. InlinedAt, ImplicitCode)))
  57. return N;
  58. if (!ShouldCreate)
  59. return nullptr;
  60. } else {
  61. assert(ShouldCreate && "Expected non-uniqued nodes to always be created");
  62. }
  63. SmallVector<Metadata *, 2> Ops;
  64. Ops.push_back(Scope);
  65. if (InlinedAt)
  66. Ops.push_back(InlinedAt);
  67. return storeImpl(new (Ops.size()) DILocation(Context, Storage, Line, Column,
  68. Ops, ImplicitCode),
  69. Storage, Context.pImpl->DILocations);
  70. }
  71. const DILocation *
  72. DILocation::getMergedLocations(ArrayRef<const DILocation *> Locs) {
  73. if (Locs.empty())
  74. return nullptr;
  75. if (Locs.size() == 1)
  76. return Locs[0];
  77. auto *Merged = Locs[0];
  78. for (const DILocation *L : llvm::drop_begin(Locs)) {
  79. Merged = getMergedLocation(Merged, L);
  80. if (Merged == nullptr)
  81. break;
  82. }
  83. return Merged;
  84. }
  85. const DILocation *DILocation::getMergedLocation(const DILocation *LocA,
  86. const DILocation *LocB) {
  87. if (!LocA || !LocB)
  88. return nullptr;
  89. if (LocA == LocB)
  90. return LocA;
  91. SmallPtrSet<DILocation *, 5> InlinedLocationsA;
  92. for (DILocation *L = LocA->getInlinedAt(); L; L = L->getInlinedAt())
  93. InlinedLocationsA.insert(L);
  94. SmallSet<std::pair<DIScope *, DILocation *>, 5> Locations;
  95. DIScope *S = LocA->getScope();
  96. DILocation *L = LocA->getInlinedAt();
  97. while (S) {
  98. Locations.insert(std::make_pair(S, L));
  99. S = S->getScope();
  100. if (!S && L) {
  101. S = L->getScope();
  102. L = L->getInlinedAt();
  103. }
  104. }
  105. const DILocation *Result = LocB;
  106. S = LocB->getScope();
  107. L = LocB->getInlinedAt();
  108. while (S) {
  109. if (Locations.count(std::make_pair(S, L)))
  110. break;
  111. S = S->getScope();
  112. if (!S && L) {
  113. S = L->getScope();
  114. L = L->getInlinedAt();
  115. }
  116. }
  117. // If the two locations are irreconsilable, just pick one. This is misleading,
  118. // but on the other hand, it's a "line 0" location.
  119. if (!S || !isa<DILocalScope>(S))
  120. S = LocA->getScope();
  121. return DILocation::get(Result->getContext(), 0, 0, S, L);
  122. }
  123. Optional<unsigned> DILocation::encodeDiscriminator(unsigned BD, unsigned DF,
  124. unsigned CI) {
  125. std::array<unsigned, 3> Components = {BD, DF, CI};
  126. uint64_t RemainingWork = 0U;
  127. // We use RemainingWork to figure out if we have no remaining components to
  128. // encode. For example: if BD != 0 but DF == 0 && CI == 0, we don't need to
  129. // encode anything for the latter 2.
  130. // Since any of the input components is at most 32 bits, their sum will be
  131. // less than 34 bits, and thus RemainingWork won't overflow.
  132. RemainingWork =
  133. std::accumulate(Components.begin(), Components.end(), RemainingWork);
  134. int I = 0;
  135. unsigned Ret = 0;
  136. unsigned NextBitInsertionIndex = 0;
  137. while (RemainingWork > 0) {
  138. unsigned C = Components[I++];
  139. RemainingWork -= C;
  140. unsigned EC = encodeComponent(C);
  141. Ret |= (EC << NextBitInsertionIndex);
  142. NextBitInsertionIndex += encodingBits(C);
  143. }
  144. // Encoding may be unsuccessful because of overflow. We determine success by
  145. // checking equivalence of components before & after encoding. Alternatively,
  146. // we could determine Success during encoding, but the current alternative is
  147. // simpler.
  148. unsigned TBD, TDF, TCI = 0;
  149. decodeDiscriminator(Ret, TBD, TDF, TCI);
  150. if (TBD == BD && TDF == DF && TCI == CI)
  151. return Ret;
  152. return None;
  153. }
  154. void DILocation::decodeDiscriminator(unsigned D, unsigned &BD, unsigned &DF,
  155. unsigned &CI) {
  156. BD = getUnsignedFromPrefixEncoding(D);
  157. DF = getUnsignedFromPrefixEncoding(getNextComponentInDiscriminator(D));
  158. CI = getUnsignedFromPrefixEncoding(
  159. getNextComponentInDiscriminator(getNextComponentInDiscriminator(D)));
  160. }
  161. DINode::DIFlags DINode::getFlag(StringRef Flag) {
  162. return StringSwitch<DIFlags>(Flag)
  163. #define HANDLE_DI_FLAG(ID, NAME) .Case("DIFlag" #NAME, Flag##NAME)
  164. #include "llvm/IR/DebugInfoFlags.def"
  165. .Default(DINode::FlagZero);
  166. }
  167. StringRef DINode::getFlagString(DIFlags Flag) {
  168. switch (Flag) {
  169. #define HANDLE_DI_FLAG(ID, NAME) \
  170. case Flag##NAME: \
  171. return "DIFlag" #NAME;
  172. #include "llvm/IR/DebugInfoFlags.def"
  173. }
  174. return "";
  175. }
  176. DINode::DIFlags DINode::splitFlags(DIFlags Flags,
  177. SmallVectorImpl<DIFlags> &SplitFlags) {
  178. // Flags that are packed together need to be specially handled, so
  179. // that, for example, we emit "DIFlagPublic" and not
  180. // "DIFlagPrivate | DIFlagProtected".
  181. if (DIFlags A = Flags & FlagAccessibility) {
  182. if (A == FlagPrivate)
  183. SplitFlags.push_back(FlagPrivate);
  184. else if (A == FlagProtected)
  185. SplitFlags.push_back(FlagProtected);
  186. else
  187. SplitFlags.push_back(FlagPublic);
  188. Flags &= ~A;
  189. }
  190. if (DIFlags R = Flags & FlagPtrToMemberRep) {
  191. if (R == FlagSingleInheritance)
  192. SplitFlags.push_back(FlagSingleInheritance);
  193. else if (R == FlagMultipleInheritance)
  194. SplitFlags.push_back(FlagMultipleInheritance);
  195. else
  196. SplitFlags.push_back(FlagVirtualInheritance);
  197. Flags &= ~R;
  198. }
  199. if ((Flags & FlagIndirectVirtualBase) == FlagIndirectVirtualBase) {
  200. Flags &= ~FlagIndirectVirtualBase;
  201. SplitFlags.push_back(FlagIndirectVirtualBase);
  202. }
  203. #define HANDLE_DI_FLAG(ID, NAME) \
  204. if (DIFlags Bit = Flags & Flag##NAME) { \
  205. SplitFlags.push_back(Bit); \
  206. Flags &= ~Bit; \
  207. }
  208. #include "llvm/IR/DebugInfoFlags.def"
  209. return Flags;
  210. }
  211. DIScope *DIScope::getScope() const {
  212. if (auto *T = dyn_cast<DIType>(this))
  213. return T->getScope();
  214. if (auto *SP = dyn_cast<DISubprogram>(this))
  215. return SP->getScope();
  216. if (auto *LB = dyn_cast<DILexicalBlockBase>(this))
  217. return LB->getScope();
  218. if (auto *NS = dyn_cast<DINamespace>(this))
  219. return NS->getScope();
  220. if (auto *CB = dyn_cast<DICommonBlock>(this))
  221. return CB->getScope();
  222. if (auto *M = dyn_cast<DIModule>(this))
  223. return M->getScope();
  224. assert((isa<DIFile>(this) || isa<DICompileUnit>(this)) &&
  225. "Unhandled type of scope.");
  226. return nullptr;
  227. }
  228. StringRef DIScope::getName() const {
  229. if (auto *T = dyn_cast<DIType>(this))
  230. return T->getName();
  231. if (auto *SP = dyn_cast<DISubprogram>(this))
  232. return SP->getName();
  233. if (auto *NS = dyn_cast<DINamespace>(this))
  234. return NS->getName();
  235. if (auto *CB = dyn_cast<DICommonBlock>(this))
  236. return CB->getName();
  237. if (auto *M = dyn_cast<DIModule>(this))
  238. return M->getName();
  239. assert((isa<DILexicalBlockBase>(this) || isa<DIFile>(this) ||
  240. isa<DICompileUnit>(this)) &&
  241. "Unhandled type of scope.");
  242. return "";
  243. }
  244. #ifndef NDEBUG
  245. static bool isCanonical(const MDString *S) {
  246. return !S || !S->getString().empty();
  247. }
  248. #endif
  249. GenericDINode *GenericDINode::getImpl(LLVMContext &Context, unsigned Tag,
  250. MDString *Header,
  251. ArrayRef<Metadata *> DwarfOps,
  252. StorageType Storage, bool ShouldCreate) {
  253. unsigned Hash = 0;
  254. if (Storage == Uniqued) {
  255. GenericDINodeInfo::KeyTy Key(Tag, Header, DwarfOps);
  256. if (auto *N = getUniqued(Context.pImpl->GenericDINodes, Key))
  257. return N;
  258. if (!ShouldCreate)
  259. return nullptr;
  260. Hash = Key.getHash();
  261. } else {
  262. assert(ShouldCreate && "Expected non-uniqued nodes to always be created");
  263. }
  264. // Use a nullptr for empty headers.
  265. assert(isCanonical(Header) && "Expected canonical MDString");
  266. Metadata *PreOps[] = {Header};
  267. return storeImpl(new (DwarfOps.size() + 1) GenericDINode(
  268. Context, Storage, Hash, Tag, PreOps, DwarfOps),
  269. Storage, Context.pImpl->GenericDINodes);
  270. }
  271. void GenericDINode::recalculateHash() {
  272. setHash(GenericDINodeInfo::KeyTy::calculateHash(this));
  273. }
  274. #define UNWRAP_ARGS_IMPL(...) __VA_ARGS__
  275. #define UNWRAP_ARGS(ARGS) UNWRAP_ARGS_IMPL ARGS
  276. #define DEFINE_GETIMPL_LOOKUP(CLASS, ARGS) \
  277. do { \
  278. if (Storage == Uniqued) { \
  279. if (auto *N = getUniqued(Context.pImpl->CLASS##s, \
  280. CLASS##Info::KeyTy(UNWRAP_ARGS(ARGS)))) \
  281. return N; \
  282. if (!ShouldCreate) \
  283. return nullptr; \
  284. } else { \
  285. assert(ShouldCreate && \
  286. "Expected non-uniqued nodes to always be created"); \
  287. } \
  288. } while (false)
  289. #define DEFINE_GETIMPL_STORE(CLASS, ARGS, OPS) \
  290. return storeImpl(new (array_lengthof(OPS)) \
  291. CLASS(Context, Storage, UNWRAP_ARGS(ARGS), OPS), \
  292. Storage, Context.pImpl->CLASS##s)
  293. #define DEFINE_GETIMPL_STORE_NO_OPS(CLASS, ARGS) \
  294. return storeImpl(new (0u) CLASS(Context, Storage, UNWRAP_ARGS(ARGS)), \
  295. Storage, Context.pImpl->CLASS##s)
  296. #define DEFINE_GETIMPL_STORE_NO_CONSTRUCTOR_ARGS(CLASS, OPS) \
  297. return storeImpl(new (array_lengthof(OPS)) CLASS(Context, Storage, OPS), \
  298. Storage, Context.pImpl->CLASS##s)
  299. #define DEFINE_GETIMPL_STORE_N(CLASS, ARGS, OPS, NUM_OPS) \
  300. return storeImpl(new (NUM_OPS) \
  301. CLASS(Context, Storage, UNWRAP_ARGS(ARGS), OPS), \
  302. Storage, Context.pImpl->CLASS##s)
  303. DISubrange *DISubrange::getImpl(LLVMContext &Context, int64_t Count, int64_t Lo,
  304. StorageType Storage, bool ShouldCreate) {
  305. auto *CountNode = ConstantAsMetadata::get(
  306. ConstantInt::getSigned(Type::getInt64Ty(Context), Count));
  307. auto *LB = ConstantAsMetadata::get(
  308. ConstantInt::getSigned(Type::getInt64Ty(Context), Lo));
  309. return getImpl(Context, CountNode, LB, nullptr, nullptr, Storage,
  310. ShouldCreate);
  311. }
  312. DISubrange *DISubrange::getImpl(LLVMContext &Context, Metadata *CountNode,
  313. int64_t Lo, StorageType Storage,
  314. bool ShouldCreate) {
  315. auto *LB = ConstantAsMetadata::get(
  316. ConstantInt::getSigned(Type::getInt64Ty(Context), Lo));
  317. return getImpl(Context, CountNode, LB, nullptr, nullptr, Storage,
  318. ShouldCreate);
  319. }
  320. DISubrange *DISubrange::getImpl(LLVMContext &Context, Metadata *CountNode,
  321. Metadata *LB, Metadata *UB, Metadata *Stride,
  322. StorageType Storage, bool ShouldCreate) {
  323. DEFINE_GETIMPL_LOOKUP(DISubrange, (CountNode, LB, UB, Stride));
  324. Metadata *Ops[] = {CountNode, LB, UB, Stride};
  325. DEFINE_GETIMPL_STORE_NO_CONSTRUCTOR_ARGS(DISubrange, Ops);
  326. }
  327. DISubrange::BoundType DISubrange::getCount() const {
  328. Metadata *CB = getRawCountNode();
  329. if (!CB)
  330. return BoundType();
  331. assert((isa<ConstantAsMetadata>(CB) || isa<DIVariable>(CB) ||
  332. isa<DIExpression>(CB)) &&
  333. "Count must be signed constant or DIVariable or DIExpression");
  334. if (auto *MD = dyn_cast<ConstantAsMetadata>(CB))
  335. return BoundType(cast<ConstantInt>(MD->getValue()));
  336. if (auto *MD = dyn_cast<DIVariable>(CB))
  337. return BoundType(MD);
  338. if (auto *MD = dyn_cast<DIExpression>(CB))
  339. return BoundType(MD);
  340. return BoundType();
  341. }
  342. DISubrange::BoundType DISubrange::getLowerBound() const {
  343. Metadata *LB = getRawLowerBound();
  344. if (!LB)
  345. return BoundType();
  346. assert((isa<ConstantAsMetadata>(LB) || isa<DIVariable>(LB) ||
  347. isa<DIExpression>(LB)) &&
  348. "LowerBound must be signed constant or DIVariable or DIExpression");
  349. if (auto *MD = dyn_cast<ConstantAsMetadata>(LB))
  350. return BoundType(cast<ConstantInt>(MD->getValue()));
  351. if (auto *MD = dyn_cast<DIVariable>(LB))
  352. return BoundType(MD);
  353. if (auto *MD = dyn_cast<DIExpression>(LB))
  354. return BoundType(MD);
  355. return BoundType();
  356. }
  357. DISubrange::BoundType DISubrange::getUpperBound() const {
  358. Metadata *UB = getRawUpperBound();
  359. if (!UB)
  360. return BoundType();
  361. assert((isa<ConstantAsMetadata>(UB) || isa<DIVariable>(UB) ||
  362. isa<DIExpression>(UB)) &&
  363. "UpperBound must be signed constant or DIVariable or DIExpression");
  364. if (auto *MD = dyn_cast<ConstantAsMetadata>(UB))
  365. return BoundType(cast<ConstantInt>(MD->getValue()));
  366. if (auto *MD = dyn_cast<DIVariable>(UB))
  367. return BoundType(MD);
  368. if (auto *MD = dyn_cast<DIExpression>(UB))
  369. return BoundType(MD);
  370. return BoundType();
  371. }
  372. DISubrange::BoundType DISubrange::getStride() const {
  373. Metadata *ST = getRawStride();
  374. if (!ST)
  375. return BoundType();
  376. assert((isa<ConstantAsMetadata>(ST) || isa<DIVariable>(ST) ||
  377. isa<DIExpression>(ST)) &&
  378. "Stride must be signed constant or DIVariable or DIExpression");
  379. if (auto *MD = dyn_cast<ConstantAsMetadata>(ST))
  380. return BoundType(cast<ConstantInt>(MD->getValue()));
  381. if (auto *MD = dyn_cast<DIVariable>(ST))
  382. return BoundType(MD);
  383. if (auto *MD = dyn_cast<DIExpression>(ST))
  384. return BoundType(MD);
  385. return BoundType();
  386. }
  387. DIGenericSubrange *DIGenericSubrange::getImpl(LLVMContext &Context,
  388. Metadata *CountNode, Metadata *LB,
  389. Metadata *UB, Metadata *Stride,
  390. StorageType Storage,
  391. bool ShouldCreate) {
  392. DEFINE_GETIMPL_LOOKUP(DIGenericSubrange, (CountNode, LB, UB, Stride));
  393. Metadata *Ops[] = {CountNode, LB, UB, Stride};
  394. DEFINE_GETIMPL_STORE_NO_CONSTRUCTOR_ARGS(DIGenericSubrange, Ops);
  395. }
  396. DIGenericSubrange::BoundType DIGenericSubrange::getCount() const {
  397. Metadata *CB = getRawCountNode();
  398. if (!CB)
  399. return BoundType();
  400. assert((isa<DIVariable>(CB) || isa<DIExpression>(CB)) &&
  401. "Count must be signed constant or DIVariable or DIExpression");
  402. if (auto *MD = dyn_cast<DIVariable>(CB))
  403. return BoundType(MD);
  404. if (auto *MD = dyn_cast<DIExpression>(CB))
  405. return BoundType(MD);
  406. return BoundType();
  407. }
  408. DIGenericSubrange::BoundType DIGenericSubrange::getLowerBound() const {
  409. Metadata *LB = getRawLowerBound();
  410. if (!LB)
  411. return BoundType();
  412. assert((isa<DIVariable>(LB) || isa<DIExpression>(LB)) &&
  413. "LowerBound must be signed constant or DIVariable or DIExpression");
  414. if (auto *MD = dyn_cast<DIVariable>(LB))
  415. return BoundType(MD);
  416. if (auto *MD = dyn_cast<DIExpression>(LB))
  417. return BoundType(MD);
  418. return BoundType();
  419. }
  420. DIGenericSubrange::BoundType DIGenericSubrange::getUpperBound() const {
  421. Metadata *UB = getRawUpperBound();
  422. if (!UB)
  423. return BoundType();
  424. assert((isa<DIVariable>(UB) || isa<DIExpression>(UB)) &&
  425. "UpperBound must be signed constant or DIVariable or DIExpression");
  426. if (auto *MD = dyn_cast<DIVariable>(UB))
  427. return BoundType(MD);
  428. if (auto *MD = dyn_cast<DIExpression>(UB))
  429. return BoundType(MD);
  430. return BoundType();
  431. }
  432. DIGenericSubrange::BoundType DIGenericSubrange::getStride() const {
  433. Metadata *ST = getRawStride();
  434. if (!ST)
  435. return BoundType();
  436. assert((isa<DIVariable>(ST) || isa<DIExpression>(ST)) &&
  437. "Stride must be signed constant or DIVariable or DIExpression");
  438. if (auto *MD = dyn_cast<DIVariable>(ST))
  439. return BoundType(MD);
  440. if (auto *MD = dyn_cast<DIExpression>(ST))
  441. return BoundType(MD);
  442. return BoundType();
  443. }
  444. DIEnumerator *DIEnumerator::getImpl(LLVMContext &Context, const APInt &Value,
  445. bool IsUnsigned, MDString *Name,
  446. StorageType Storage, bool ShouldCreate) {
  447. assert(isCanonical(Name) && "Expected canonical MDString");
  448. DEFINE_GETIMPL_LOOKUP(DIEnumerator, (Value, IsUnsigned, Name));
  449. Metadata *Ops[] = {Name};
  450. DEFINE_GETIMPL_STORE(DIEnumerator, (Value, IsUnsigned), Ops);
  451. }
  452. DIBasicType *DIBasicType::getImpl(LLVMContext &Context, unsigned Tag,
  453. MDString *Name, uint64_t SizeInBits,
  454. uint32_t AlignInBits, unsigned Encoding,
  455. DIFlags Flags, StorageType Storage,
  456. bool ShouldCreate) {
  457. assert(isCanonical(Name) && "Expected canonical MDString");
  458. DEFINE_GETIMPL_LOOKUP(DIBasicType,
  459. (Tag, Name, SizeInBits, AlignInBits, Encoding, Flags));
  460. Metadata *Ops[] = {nullptr, nullptr, Name};
  461. DEFINE_GETIMPL_STORE(DIBasicType,
  462. (Tag, SizeInBits, AlignInBits, Encoding, Flags), Ops);
  463. }
  464. Optional<DIBasicType::Signedness> DIBasicType::getSignedness() const {
  465. switch (getEncoding()) {
  466. case dwarf::DW_ATE_signed:
  467. case dwarf::DW_ATE_signed_char:
  468. return Signedness::Signed;
  469. case dwarf::DW_ATE_unsigned:
  470. case dwarf::DW_ATE_unsigned_char:
  471. return Signedness::Unsigned;
  472. default:
  473. return None;
  474. }
  475. }
  476. DIStringType *DIStringType::getImpl(LLVMContext &Context, unsigned Tag,
  477. MDString *Name, Metadata *StringLength,
  478. Metadata *StringLengthExp,
  479. Metadata *StringLocationExp,
  480. uint64_t SizeInBits, uint32_t AlignInBits,
  481. unsigned Encoding, StorageType Storage,
  482. bool ShouldCreate) {
  483. assert(isCanonical(Name) && "Expected canonical MDString");
  484. DEFINE_GETIMPL_LOOKUP(DIStringType,
  485. (Tag, Name, StringLength, StringLengthExp,
  486. StringLocationExp, SizeInBits, AlignInBits, Encoding));
  487. Metadata *Ops[] = {nullptr, nullptr, Name,
  488. StringLength, StringLengthExp, StringLocationExp};
  489. DEFINE_GETIMPL_STORE(DIStringType, (Tag, SizeInBits, AlignInBits, Encoding),
  490. Ops);
  491. }
  492. DIDerivedType *DIDerivedType::getImpl(
  493. LLVMContext &Context, unsigned Tag, MDString *Name, Metadata *File,
  494. unsigned Line, Metadata *Scope, Metadata *BaseType, uint64_t SizeInBits,
  495. uint32_t AlignInBits, uint64_t OffsetInBits,
  496. Optional<unsigned> DWARFAddressSpace, DIFlags Flags, Metadata *ExtraData,
  497. Metadata *Annotations, StorageType Storage, bool ShouldCreate) {
  498. assert(isCanonical(Name) && "Expected canonical MDString");
  499. DEFINE_GETIMPL_LOOKUP(DIDerivedType,
  500. (Tag, Name, File, Line, Scope, BaseType, SizeInBits,
  501. AlignInBits, OffsetInBits, DWARFAddressSpace, Flags,
  502. ExtraData, Annotations));
  503. Metadata *Ops[] = {File, Scope, Name, BaseType, ExtraData, Annotations};
  504. DEFINE_GETIMPL_STORE(DIDerivedType,
  505. (Tag, Line, SizeInBits, AlignInBits, OffsetInBits,
  506. DWARFAddressSpace, Flags),
  507. Ops);
  508. }
  509. DICompositeType *DICompositeType::getImpl(
  510. LLVMContext &Context, unsigned Tag, MDString *Name, Metadata *File,
  511. unsigned Line, Metadata *Scope, Metadata *BaseType, uint64_t SizeInBits,
  512. uint32_t AlignInBits, uint64_t OffsetInBits, DIFlags Flags,
  513. Metadata *Elements, unsigned RuntimeLang, Metadata *VTableHolder,
  514. Metadata *TemplateParams, MDString *Identifier, Metadata *Discriminator,
  515. Metadata *DataLocation, Metadata *Associated, Metadata *Allocated,
  516. Metadata *Rank, Metadata *Annotations, StorageType Storage,
  517. bool ShouldCreate) {
  518. assert(isCanonical(Name) && "Expected canonical MDString");
  519. // Keep this in sync with buildODRType.
  520. DEFINE_GETIMPL_LOOKUP(DICompositeType,
  521. (Tag, Name, File, Line, Scope, BaseType, SizeInBits,
  522. AlignInBits, OffsetInBits, Flags, Elements,
  523. RuntimeLang, VTableHolder, TemplateParams, Identifier,
  524. Discriminator, DataLocation, Associated, Allocated,
  525. Rank, Annotations));
  526. Metadata *Ops[] = {File, Scope, Name, BaseType,
  527. Elements, VTableHolder, TemplateParams, Identifier,
  528. Discriminator, DataLocation, Associated, Allocated,
  529. Rank, Annotations};
  530. DEFINE_GETIMPL_STORE(
  531. DICompositeType,
  532. (Tag, Line, RuntimeLang, SizeInBits, AlignInBits, OffsetInBits, Flags),
  533. Ops);
  534. }
  535. DICompositeType *DICompositeType::buildODRType(
  536. LLVMContext &Context, MDString &Identifier, unsigned Tag, MDString *Name,
  537. Metadata *File, unsigned Line, Metadata *Scope, Metadata *BaseType,
  538. uint64_t SizeInBits, uint32_t AlignInBits, uint64_t OffsetInBits,
  539. DIFlags Flags, Metadata *Elements, unsigned RuntimeLang,
  540. Metadata *VTableHolder, Metadata *TemplateParams, Metadata *Discriminator,
  541. Metadata *DataLocation, Metadata *Associated, Metadata *Allocated,
  542. Metadata *Rank, Metadata *Annotations) {
  543. assert(!Identifier.getString().empty() && "Expected valid identifier");
  544. if (!Context.isODRUniquingDebugTypes())
  545. return nullptr;
  546. auto *&CT = (*Context.pImpl->DITypeMap)[&Identifier];
  547. if (!CT)
  548. return CT = DICompositeType::getDistinct(
  549. Context, Tag, Name, File, Line, Scope, BaseType, SizeInBits,
  550. AlignInBits, OffsetInBits, Flags, Elements, RuntimeLang,
  551. VTableHolder, TemplateParams, &Identifier, Discriminator,
  552. DataLocation, Associated, Allocated, Rank, Annotations);
  553. if (CT->getTag() != Tag)
  554. return nullptr;
  555. // Only mutate CT if it's a forward declaration and the new operands aren't.
  556. assert(CT->getRawIdentifier() == &Identifier && "Wrong ODR identifier?");
  557. if (!CT->isForwardDecl() || (Flags & DINode::FlagFwdDecl))
  558. return CT;
  559. // Mutate CT in place. Keep this in sync with getImpl.
  560. CT->mutate(Tag, Line, RuntimeLang, SizeInBits, AlignInBits, OffsetInBits,
  561. Flags);
  562. Metadata *Ops[] = {File, Scope, Name, BaseType,
  563. Elements, VTableHolder, TemplateParams, &Identifier,
  564. Discriminator, DataLocation, Associated, Allocated,
  565. Rank, Annotations};
  566. assert((std::end(Ops) - std::begin(Ops)) == (int)CT->getNumOperands() &&
  567. "Mismatched number of operands");
  568. for (unsigned I = 0, E = CT->getNumOperands(); I != E; ++I)
  569. if (Ops[I] != CT->getOperand(I))
  570. CT->setOperand(I, Ops[I]);
  571. return CT;
  572. }
  573. DICompositeType *DICompositeType::getODRType(
  574. LLVMContext &Context, MDString &Identifier, unsigned Tag, MDString *Name,
  575. Metadata *File, unsigned Line, Metadata *Scope, Metadata *BaseType,
  576. uint64_t SizeInBits, uint32_t AlignInBits, uint64_t OffsetInBits,
  577. DIFlags Flags, Metadata *Elements, unsigned RuntimeLang,
  578. Metadata *VTableHolder, Metadata *TemplateParams, Metadata *Discriminator,
  579. Metadata *DataLocation, Metadata *Associated, Metadata *Allocated,
  580. Metadata *Rank, Metadata *Annotations) {
  581. assert(!Identifier.getString().empty() && "Expected valid identifier");
  582. if (!Context.isODRUniquingDebugTypes())
  583. return nullptr;
  584. auto *&CT = (*Context.pImpl->DITypeMap)[&Identifier];
  585. if (!CT) {
  586. CT = DICompositeType::getDistinct(
  587. Context, Tag, Name, File, Line, Scope, BaseType, SizeInBits,
  588. AlignInBits, OffsetInBits, Flags, Elements, RuntimeLang, VTableHolder,
  589. TemplateParams, &Identifier, Discriminator, DataLocation, Associated,
  590. Allocated, Rank, Annotations);
  591. } else {
  592. if (CT->getTag() != Tag)
  593. return nullptr;
  594. }
  595. return CT;
  596. }
  597. DICompositeType *DICompositeType::getODRTypeIfExists(LLVMContext &Context,
  598. MDString &Identifier) {
  599. assert(!Identifier.getString().empty() && "Expected valid identifier");
  600. if (!Context.isODRUniquingDebugTypes())
  601. return nullptr;
  602. return Context.pImpl->DITypeMap->lookup(&Identifier);
  603. }
  604. DISubroutineType *DISubroutineType::getImpl(LLVMContext &Context, DIFlags Flags,
  605. uint8_t CC, Metadata *TypeArray,
  606. StorageType Storage,
  607. bool ShouldCreate) {
  608. DEFINE_GETIMPL_LOOKUP(DISubroutineType, (Flags, CC, TypeArray));
  609. Metadata *Ops[] = {nullptr, nullptr, nullptr, TypeArray};
  610. DEFINE_GETIMPL_STORE(DISubroutineType, (Flags, CC), Ops);
  611. }
  612. // FIXME: Implement this string-enum correspondence with a .def file and macros,
  613. // so that the association is explicit rather than implied.
  614. static const char *ChecksumKindName[DIFile::CSK_Last] = {
  615. "CSK_MD5",
  616. "CSK_SHA1",
  617. "CSK_SHA256",
  618. };
  619. StringRef DIFile::getChecksumKindAsString(ChecksumKind CSKind) {
  620. assert(CSKind <= DIFile::CSK_Last && "Invalid checksum kind");
  621. // The first space was originally the CSK_None variant, which is now
  622. // obsolete, but the space is still reserved in ChecksumKind, so we account
  623. // for it here.
  624. return ChecksumKindName[CSKind - 1];
  625. }
  626. Optional<DIFile::ChecksumKind> DIFile::getChecksumKind(StringRef CSKindStr) {
  627. return StringSwitch<Optional<DIFile::ChecksumKind>>(CSKindStr)
  628. .Case("CSK_MD5", DIFile::CSK_MD5)
  629. .Case("CSK_SHA1", DIFile::CSK_SHA1)
  630. .Case("CSK_SHA256", DIFile::CSK_SHA256)
  631. .Default(None);
  632. }
  633. DIFile *DIFile::getImpl(LLVMContext &Context, MDString *Filename,
  634. MDString *Directory,
  635. Optional<DIFile::ChecksumInfo<MDString *>> CS,
  636. Optional<MDString *> Source, StorageType Storage,
  637. bool ShouldCreate) {
  638. assert(isCanonical(Filename) && "Expected canonical MDString");
  639. assert(isCanonical(Directory) && "Expected canonical MDString");
  640. assert((!CS || isCanonical(CS->Value)) && "Expected canonical MDString");
  641. assert((!Source || isCanonical(*Source)) && "Expected canonical MDString");
  642. DEFINE_GETIMPL_LOOKUP(DIFile, (Filename, Directory, CS, Source));
  643. Metadata *Ops[] = {Filename, Directory, CS ? CS->Value : nullptr,
  644. Source.getValueOr(nullptr)};
  645. DEFINE_GETIMPL_STORE(DIFile, (CS, Source), Ops);
  646. }
  647. DICompileUnit *DICompileUnit::getImpl(
  648. LLVMContext &Context, unsigned SourceLanguage, Metadata *File,
  649. MDString *Producer, bool IsOptimized, MDString *Flags,
  650. unsigned RuntimeVersion, MDString *SplitDebugFilename,
  651. unsigned EmissionKind, Metadata *EnumTypes, Metadata *RetainedTypes,
  652. Metadata *GlobalVariables, Metadata *ImportedEntities, Metadata *Macros,
  653. uint64_t DWOId, bool SplitDebugInlining, bool DebugInfoForProfiling,
  654. unsigned NameTableKind, bool RangesBaseAddress, MDString *SysRoot,
  655. MDString *SDK, StorageType Storage, bool ShouldCreate) {
  656. assert(Storage != Uniqued && "Cannot unique DICompileUnit");
  657. assert(isCanonical(Producer) && "Expected canonical MDString");
  658. assert(isCanonical(Flags) && "Expected canonical MDString");
  659. assert(isCanonical(SplitDebugFilename) && "Expected canonical MDString");
  660. Metadata *Ops[] = {File,
  661. Producer,
  662. Flags,
  663. SplitDebugFilename,
  664. EnumTypes,
  665. RetainedTypes,
  666. GlobalVariables,
  667. ImportedEntities,
  668. Macros,
  669. SysRoot,
  670. SDK};
  671. return storeImpl(new (array_lengthof(Ops)) DICompileUnit(
  672. Context, Storage, SourceLanguage, IsOptimized,
  673. RuntimeVersion, EmissionKind, DWOId, SplitDebugInlining,
  674. DebugInfoForProfiling, NameTableKind, RangesBaseAddress,
  675. Ops),
  676. Storage);
  677. }
  678. Optional<DICompileUnit::DebugEmissionKind>
  679. DICompileUnit::getEmissionKind(StringRef Str) {
  680. return StringSwitch<Optional<DebugEmissionKind>>(Str)
  681. .Case("NoDebug", NoDebug)
  682. .Case("FullDebug", FullDebug)
  683. .Case("LineTablesOnly", LineTablesOnly)
  684. .Case("DebugDirectivesOnly", DebugDirectivesOnly)
  685. .Default(None);
  686. }
  687. Optional<DICompileUnit::DebugNameTableKind>
  688. DICompileUnit::getNameTableKind(StringRef Str) {
  689. return StringSwitch<Optional<DebugNameTableKind>>(Str)
  690. .Case("Default", DebugNameTableKind::Default)
  691. .Case("GNU", DebugNameTableKind::GNU)
  692. .Case("None", DebugNameTableKind::None)
  693. .Default(None);
  694. }
  695. const char *DICompileUnit::emissionKindString(DebugEmissionKind EK) {
  696. switch (EK) {
  697. case NoDebug:
  698. return "NoDebug";
  699. case FullDebug:
  700. return "FullDebug";
  701. case LineTablesOnly:
  702. return "LineTablesOnly";
  703. case DebugDirectivesOnly:
  704. return "DebugDirectivesOnly";
  705. }
  706. return nullptr;
  707. }
  708. const char *DICompileUnit::nameTableKindString(DebugNameTableKind NTK) {
  709. switch (NTK) {
  710. case DebugNameTableKind::Default:
  711. return nullptr;
  712. case DebugNameTableKind::GNU:
  713. return "GNU";
  714. case DebugNameTableKind::None:
  715. return "None";
  716. }
  717. return nullptr;
  718. }
  719. DISubprogram *DILocalScope::getSubprogram() const {
  720. if (auto *Block = dyn_cast<DILexicalBlockBase>(this))
  721. return Block->getScope()->getSubprogram();
  722. return const_cast<DISubprogram *>(cast<DISubprogram>(this));
  723. }
  724. DILocalScope *DILocalScope::getNonLexicalBlockFileScope() const {
  725. if (auto *File = dyn_cast<DILexicalBlockFile>(this))
  726. return File->getScope()->getNonLexicalBlockFileScope();
  727. return const_cast<DILocalScope *>(this);
  728. }
  729. DISubprogram::DISPFlags DISubprogram::getFlag(StringRef Flag) {
  730. return StringSwitch<DISPFlags>(Flag)
  731. #define HANDLE_DISP_FLAG(ID, NAME) .Case("DISPFlag" #NAME, SPFlag##NAME)
  732. #include "llvm/IR/DebugInfoFlags.def"
  733. .Default(SPFlagZero);
  734. }
  735. StringRef DISubprogram::getFlagString(DISPFlags Flag) {
  736. switch (Flag) {
  737. // Appease a warning.
  738. case SPFlagVirtuality:
  739. return "";
  740. #define HANDLE_DISP_FLAG(ID, NAME) \
  741. case SPFlag##NAME: \
  742. return "DISPFlag" #NAME;
  743. #include "llvm/IR/DebugInfoFlags.def"
  744. }
  745. return "";
  746. }
  747. DISubprogram::DISPFlags
  748. DISubprogram::splitFlags(DISPFlags Flags,
  749. SmallVectorImpl<DISPFlags> &SplitFlags) {
  750. // Multi-bit fields can require special handling. In our case, however, the
  751. // only multi-bit field is virtuality, and all its values happen to be
  752. // single-bit values, so the right behavior just falls out.
  753. #define HANDLE_DISP_FLAG(ID, NAME) \
  754. if (DISPFlags Bit = Flags & SPFlag##NAME) { \
  755. SplitFlags.push_back(Bit); \
  756. Flags &= ~Bit; \
  757. }
  758. #include "llvm/IR/DebugInfoFlags.def"
  759. return Flags;
  760. }
  761. DISubprogram *DISubprogram::getImpl(
  762. LLVMContext &Context, Metadata *Scope, MDString *Name,
  763. MDString *LinkageName, Metadata *File, unsigned Line, Metadata *Type,
  764. unsigned ScopeLine, Metadata *ContainingType, unsigned VirtualIndex,
  765. int ThisAdjustment, DIFlags Flags, DISPFlags SPFlags, Metadata *Unit,
  766. Metadata *TemplateParams, Metadata *Declaration, Metadata *RetainedNodes,
  767. Metadata *ThrownTypes, Metadata *Annotations, StorageType Storage,
  768. bool ShouldCreate) {
  769. assert(isCanonical(Name) && "Expected canonical MDString");
  770. assert(isCanonical(LinkageName) && "Expected canonical MDString");
  771. DEFINE_GETIMPL_LOOKUP(DISubprogram,
  772. (Scope, Name, LinkageName, File, Line, Type, ScopeLine,
  773. ContainingType, VirtualIndex, ThisAdjustment, Flags,
  774. SPFlags, Unit, TemplateParams, Declaration,
  775. RetainedNodes, ThrownTypes, Annotations));
  776. SmallVector<Metadata *, 12> Ops = {
  777. File, Scope, Name, LinkageName,
  778. Type, Unit, Declaration, RetainedNodes,
  779. ContainingType, TemplateParams, ThrownTypes, Annotations};
  780. if (!Annotations) {
  781. Ops.pop_back();
  782. if (!ThrownTypes) {
  783. Ops.pop_back();
  784. if (!TemplateParams) {
  785. Ops.pop_back();
  786. if (!ContainingType)
  787. Ops.pop_back();
  788. }
  789. }
  790. }
  791. DEFINE_GETIMPL_STORE_N(
  792. DISubprogram,
  793. (Line, ScopeLine, VirtualIndex, ThisAdjustment, Flags, SPFlags), Ops,
  794. Ops.size());
  795. }
  796. bool DISubprogram::describes(const Function *F) const {
  797. assert(F && "Invalid function");
  798. return F->getSubprogram() == this;
  799. }
  800. DILexicalBlock *DILexicalBlock::getImpl(LLVMContext &Context, Metadata *Scope,
  801. Metadata *File, unsigned Line,
  802. unsigned Column, StorageType Storage,
  803. bool ShouldCreate) {
  804. // Fixup column.
  805. adjustColumn(Column);
  806. assert(Scope && "Expected scope");
  807. DEFINE_GETIMPL_LOOKUP(DILexicalBlock, (Scope, File, Line, Column));
  808. Metadata *Ops[] = {File, Scope};
  809. DEFINE_GETIMPL_STORE(DILexicalBlock, (Line, Column), Ops);
  810. }
  811. DILexicalBlockFile *DILexicalBlockFile::getImpl(LLVMContext &Context,
  812. Metadata *Scope, Metadata *File,
  813. unsigned Discriminator,
  814. StorageType Storage,
  815. bool ShouldCreate) {
  816. assert(Scope && "Expected scope");
  817. DEFINE_GETIMPL_LOOKUP(DILexicalBlockFile, (Scope, File, Discriminator));
  818. Metadata *Ops[] = {File, Scope};
  819. DEFINE_GETIMPL_STORE(DILexicalBlockFile, (Discriminator), Ops);
  820. }
  821. DINamespace *DINamespace::getImpl(LLVMContext &Context, Metadata *Scope,
  822. MDString *Name, bool ExportSymbols,
  823. StorageType Storage, bool ShouldCreate) {
  824. assert(isCanonical(Name) && "Expected canonical MDString");
  825. DEFINE_GETIMPL_LOOKUP(DINamespace, (Scope, Name, ExportSymbols));
  826. // The nullptr is for DIScope's File operand. This should be refactored.
  827. Metadata *Ops[] = {nullptr, Scope, Name};
  828. DEFINE_GETIMPL_STORE(DINamespace, (ExportSymbols), Ops);
  829. }
  830. DICommonBlock *DICommonBlock::getImpl(LLVMContext &Context, Metadata *Scope,
  831. Metadata *Decl, MDString *Name,
  832. Metadata *File, unsigned LineNo,
  833. StorageType Storage, bool ShouldCreate) {
  834. assert(isCanonical(Name) && "Expected canonical MDString");
  835. DEFINE_GETIMPL_LOOKUP(DICommonBlock, (Scope, Decl, Name, File, LineNo));
  836. // The nullptr is for DIScope's File operand. This should be refactored.
  837. Metadata *Ops[] = {Scope, Decl, Name, File};
  838. DEFINE_GETIMPL_STORE(DICommonBlock, (LineNo), Ops);
  839. }
  840. DIModule *DIModule::getImpl(LLVMContext &Context, Metadata *File,
  841. Metadata *Scope, MDString *Name,
  842. MDString *ConfigurationMacros,
  843. MDString *IncludePath, MDString *APINotesFile,
  844. unsigned LineNo, bool IsDecl, StorageType Storage,
  845. bool ShouldCreate) {
  846. assert(isCanonical(Name) && "Expected canonical MDString");
  847. DEFINE_GETIMPL_LOOKUP(DIModule, (File, Scope, Name, ConfigurationMacros,
  848. IncludePath, APINotesFile, LineNo, IsDecl));
  849. Metadata *Ops[] = {File, Scope, Name, ConfigurationMacros,
  850. IncludePath, APINotesFile};
  851. DEFINE_GETIMPL_STORE(DIModule, (LineNo, IsDecl), Ops);
  852. }
  853. DITemplateTypeParameter *
  854. DITemplateTypeParameter::getImpl(LLVMContext &Context, MDString *Name,
  855. Metadata *Type, bool isDefault,
  856. StorageType Storage, bool ShouldCreate) {
  857. assert(isCanonical(Name) && "Expected canonical MDString");
  858. DEFINE_GETIMPL_LOOKUP(DITemplateTypeParameter, (Name, Type, isDefault));
  859. Metadata *Ops[] = {Name, Type};
  860. DEFINE_GETIMPL_STORE(DITemplateTypeParameter, (isDefault), Ops);
  861. }
  862. DITemplateValueParameter *DITemplateValueParameter::getImpl(
  863. LLVMContext &Context, unsigned Tag, MDString *Name, Metadata *Type,
  864. bool isDefault, Metadata *Value, StorageType Storage, bool ShouldCreate) {
  865. assert(isCanonical(Name) && "Expected canonical MDString");
  866. DEFINE_GETIMPL_LOOKUP(DITemplateValueParameter,
  867. (Tag, Name, Type, isDefault, Value));
  868. Metadata *Ops[] = {Name, Type, Value};
  869. DEFINE_GETIMPL_STORE(DITemplateValueParameter, (Tag, isDefault), Ops);
  870. }
  871. DIGlobalVariable *
  872. DIGlobalVariable::getImpl(LLVMContext &Context, Metadata *Scope, MDString *Name,
  873. MDString *LinkageName, Metadata *File, unsigned Line,
  874. Metadata *Type, bool IsLocalToUnit, bool IsDefinition,
  875. Metadata *StaticDataMemberDeclaration,
  876. Metadata *TemplateParams, uint32_t AlignInBits,
  877. Metadata *Annotations, StorageType Storage,
  878. bool ShouldCreate) {
  879. assert(isCanonical(Name) && "Expected canonical MDString");
  880. assert(isCanonical(LinkageName) && "Expected canonical MDString");
  881. DEFINE_GETIMPL_LOOKUP(
  882. DIGlobalVariable,
  883. (Scope, Name, LinkageName, File, Line, Type, IsLocalToUnit, IsDefinition,
  884. StaticDataMemberDeclaration, TemplateParams, AlignInBits, Annotations));
  885. Metadata *Ops[] = {Scope,
  886. Name,
  887. File,
  888. Type,
  889. Name,
  890. LinkageName,
  891. StaticDataMemberDeclaration,
  892. TemplateParams,
  893. Annotations};
  894. DEFINE_GETIMPL_STORE(DIGlobalVariable,
  895. (Line, IsLocalToUnit, IsDefinition, AlignInBits), Ops);
  896. }
  897. DILocalVariable *
  898. DILocalVariable::getImpl(LLVMContext &Context, Metadata *Scope, MDString *Name,
  899. Metadata *File, unsigned Line, Metadata *Type,
  900. unsigned Arg, DIFlags Flags, uint32_t AlignInBits,
  901. Metadata *Annotations, StorageType Storage,
  902. bool ShouldCreate) {
  903. // 64K ought to be enough for any frontend.
  904. assert(Arg <= UINT16_MAX && "Expected argument number to fit in 16-bits");
  905. assert(Scope && "Expected scope");
  906. assert(isCanonical(Name) && "Expected canonical MDString");
  907. DEFINE_GETIMPL_LOOKUP(DILocalVariable, (Scope, Name, File, Line, Type, Arg,
  908. Flags, AlignInBits, Annotations));
  909. Metadata *Ops[] = {Scope, Name, File, Type, Annotations};
  910. DEFINE_GETIMPL_STORE(DILocalVariable, (Line, Arg, Flags, AlignInBits), Ops);
  911. }
  912. Optional<uint64_t> DIVariable::getSizeInBits() const {
  913. // This is used by the Verifier so be mindful of broken types.
  914. const Metadata *RawType = getRawType();
  915. while (RawType) {
  916. // Try to get the size directly.
  917. if (auto *T = dyn_cast<DIType>(RawType))
  918. if (uint64_t Size = T->getSizeInBits())
  919. return Size;
  920. if (auto *DT = dyn_cast<DIDerivedType>(RawType)) {
  921. // Look at the base type.
  922. RawType = DT->getRawBaseType();
  923. continue;
  924. }
  925. // Missing type or size.
  926. break;
  927. }
  928. // Fail gracefully.
  929. return None;
  930. }
  931. DILabel *DILabel::getImpl(LLVMContext &Context, Metadata *Scope, MDString *Name,
  932. Metadata *File, unsigned Line, StorageType Storage,
  933. bool ShouldCreate) {
  934. assert(Scope && "Expected scope");
  935. assert(isCanonical(Name) && "Expected canonical MDString");
  936. DEFINE_GETIMPL_LOOKUP(DILabel, (Scope, Name, File, Line));
  937. Metadata *Ops[] = {Scope, Name, File};
  938. DEFINE_GETIMPL_STORE(DILabel, (Line), Ops);
  939. }
  940. DIExpression *DIExpression::getImpl(LLVMContext &Context,
  941. ArrayRef<uint64_t> Elements,
  942. StorageType Storage, bool ShouldCreate) {
  943. DEFINE_GETIMPL_LOOKUP(DIExpression, (Elements));
  944. DEFINE_GETIMPL_STORE_NO_OPS(DIExpression, (Elements));
  945. }
  946. unsigned DIExpression::ExprOperand::getSize() const {
  947. uint64_t Op = getOp();
  948. if (Op >= dwarf::DW_OP_breg0 && Op <= dwarf::DW_OP_breg31)
  949. return 2;
  950. switch (Op) {
  951. case dwarf::DW_OP_LLVM_convert:
  952. case dwarf::DW_OP_LLVM_fragment:
  953. case dwarf::DW_OP_bregx:
  954. return 3;
  955. case dwarf::DW_OP_constu:
  956. case dwarf::DW_OP_consts:
  957. case dwarf::DW_OP_deref_size:
  958. case dwarf::DW_OP_plus_uconst:
  959. case dwarf::DW_OP_LLVM_tag_offset:
  960. case dwarf::DW_OP_LLVM_entry_value:
  961. case dwarf::DW_OP_LLVM_arg:
  962. case dwarf::DW_OP_regx:
  963. return 2;
  964. default:
  965. return 1;
  966. }
  967. }
  968. bool DIExpression::isValid() const {
  969. for (auto I = expr_op_begin(), E = expr_op_end(); I != E; ++I) {
  970. // Check that there's space for the operand.
  971. if (I->get() + I->getSize() > E->get())
  972. return false;
  973. uint64_t Op = I->getOp();
  974. if ((Op >= dwarf::DW_OP_reg0 && Op <= dwarf::DW_OP_reg31) ||
  975. (Op >= dwarf::DW_OP_breg0 && Op <= dwarf::DW_OP_breg31))
  976. return true;
  977. // Check that the operand is valid.
  978. switch (Op) {
  979. default:
  980. return false;
  981. case dwarf::DW_OP_LLVM_fragment:
  982. // A fragment operator must appear at the end.
  983. return I->get() + I->getSize() == E->get();
  984. case dwarf::DW_OP_stack_value: {
  985. // Must be the last one or followed by a DW_OP_LLVM_fragment.
  986. if (I->get() + I->getSize() == E->get())
  987. break;
  988. auto J = I;
  989. if ((++J)->getOp() != dwarf::DW_OP_LLVM_fragment)
  990. return false;
  991. break;
  992. }
  993. case dwarf::DW_OP_swap: {
  994. // Must be more than one implicit element on the stack.
  995. // FIXME: A better way to implement this would be to add a local variable
  996. // that keeps track of the stack depth and introduce something like a
  997. // DW_LLVM_OP_implicit_location as a placeholder for the location this
  998. // DIExpression is attached to, or else pass the number of implicit stack
  999. // elements into isValid.
  1000. if (getNumElements() == 1)
  1001. return false;
  1002. break;
  1003. }
  1004. case dwarf::DW_OP_LLVM_entry_value: {
  1005. // An entry value operator must appear at the beginning and the number of
  1006. // operations it cover can currently only be 1, because we support only
  1007. // entry values of a simple register location. One reason for this is that
  1008. // we currently can't calculate the size of the resulting DWARF block for
  1009. // other expressions.
  1010. return I->get() == expr_op_begin()->get() && I->getArg(0) == 1;
  1011. }
  1012. case dwarf::DW_OP_LLVM_implicit_pointer:
  1013. case dwarf::DW_OP_LLVM_convert:
  1014. case dwarf::DW_OP_LLVM_arg:
  1015. case dwarf::DW_OP_LLVM_tag_offset:
  1016. case dwarf::DW_OP_constu:
  1017. case dwarf::DW_OP_plus_uconst:
  1018. case dwarf::DW_OP_plus:
  1019. case dwarf::DW_OP_minus:
  1020. case dwarf::DW_OP_mul:
  1021. case dwarf::DW_OP_div:
  1022. case dwarf::DW_OP_mod:
  1023. case dwarf::DW_OP_or:
  1024. case dwarf::DW_OP_and:
  1025. case dwarf::DW_OP_xor:
  1026. case dwarf::DW_OP_shl:
  1027. case dwarf::DW_OP_shr:
  1028. case dwarf::DW_OP_shra:
  1029. case dwarf::DW_OP_deref:
  1030. case dwarf::DW_OP_deref_size:
  1031. case dwarf::DW_OP_xderef:
  1032. case dwarf::DW_OP_lit0:
  1033. case dwarf::DW_OP_not:
  1034. case dwarf::DW_OP_dup:
  1035. case dwarf::DW_OP_regx:
  1036. case dwarf::DW_OP_bregx:
  1037. case dwarf::DW_OP_push_object_address:
  1038. case dwarf::DW_OP_over:
  1039. case dwarf::DW_OP_consts:
  1040. break;
  1041. }
  1042. }
  1043. return true;
  1044. }
  1045. bool DIExpression::isImplicit() const {
  1046. if (!isValid())
  1047. return false;
  1048. if (getNumElements() == 0)
  1049. return false;
  1050. for (const auto &It : expr_ops()) {
  1051. switch (It.getOp()) {
  1052. default:
  1053. break;
  1054. case dwarf::DW_OP_stack_value:
  1055. case dwarf::DW_OP_LLVM_tag_offset:
  1056. return true;
  1057. }
  1058. }
  1059. return false;
  1060. }
  1061. bool DIExpression::isComplex() const {
  1062. if (!isValid())
  1063. return false;
  1064. if (getNumElements() == 0)
  1065. return false;
  1066. // If there are any elements other than fragment or tag_offset, then some
  1067. // kind of complex computation occurs.
  1068. for (const auto &It : expr_ops()) {
  1069. switch (It.getOp()) {
  1070. case dwarf::DW_OP_LLVM_tag_offset:
  1071. case dwarf::DW_OP_LLVM_fragment:
  1072. continue;
  1073. default:
  1074. return true;
  1075. }
  1076. }
  1077. return false;
  1078. }
  1079. Optional<DIExpression::FragmentInfo>
  1080. DIExpression::getFragmentInfo(expr_op_iterator Start, expr_op_iterator End) {
  1081. for (auto I = Start; I != End; ++I)
  1082. if (I->getOp() == dwarf::DW_OP_LLVM_fragment) {
  1083. DIExpression::FragmentInfo Info = {I->getArg(1), I->getArg(0)};
  1084. return Info;
  1085. }
  1086. return None;
  1087. }
  1088. void DIExpression::appendOffset(SmallVectorImpl<uint64_t> &Ops,
  1089. int64_t Offset) {
  1090. if (Offset > 0) {
  1091. Ops.push_back(dwarf::DW_OP_plus_uconst);
  1092. Ops.push_back(Offset);
  1093. } else if (Offset < 0) {
  1094. Ops.push_back(dwarf::DW_OP_constu);
  1095. Ops.push_back(-Offset);
  1096. Ops.push_back(dwarf::DW_OP_minus);
  1097. }
  1098. }
  1099. bool DIExpression::extractIfOffset(int64_t &Offset) const {
  1100. if (getNumElements() == 0) {
  1101. Offset = 0;
  1102. return true;
  1103. }
  1104. if (getNumElements() == 2 && Elements[0] == dwarf::DW_OP_plus_uconst) {
  1105. Offset = Elements[1];
  1106. return true;
  1107. }
  1108. if (getNumElements() == 3 && Elements[0] == dwarf::DW_OP_constu) {
  1109. if (Elements[2] == dwarf::DW_OP_plus) {
  1110. Offset = Elements[1];
  1111. return true;
  1112. }
  1113. if (Elements[2] == dwarf::DW_OP_minus) {
  1114. Offset = -Elements[1];
  1115. return true;
  1116. }
  1117. }
  1118. return false;
  1119. }
  1120. bool DIExpression::hasAllLocationOps(unsigned N) const {
  1121. SmallDenseSet<uint64_t, 4> SeenOps;
  1122. for (auto ExprOp : expr_ops())
  1123. if (ExprOp.getOp() == dwarf::DW_OP_LLVM_arg)
  1124. SeenOps.insert(ExprOp.getArg(0));
  1125. for (uint64_t Idx = 0; Idx < N; ++Idx)
  1126. if (!is_contained(SeenOps, Idx))
  1127. return false;
  1128. return true;
  1129. }
  1130. const DIExpression *DIExpression::extractAddressClass(const DIExpression *Expr,
  1131. unsigned &AddrClass) {
  1132. // FIXME: This seems fragile. Nothing that verifies that these elements
  1133. // actually map to ops and not operands.
  1134. const unsigned PatternSize = 4;
  1135. if (Expr->Elements.size() >= PatternSize &&
  1136. Expr->Elements[PatternSize - 4] == dwarf::DW_OP_constu &&
  1137. Expr->Elements[PatternSize - 2] == dwarf::DW_OP_swap &&
  1138. Expr->Elements[PatternSize - 1] == dwarf::DW_OP_xderef) {
  1139. AddrClass = Expr->Elements[PatternSize - 3];
  1140. if (Expr->Elements.size() == PatternSize)
  1141. return nullptr;
  1142. return DIExpression::get(Expr->getContext(),
  1143. makeArrayRef(&*Expr->Elements.begin(),
  1144. Expr->Elements.size() - PatternSize));
  1145. }
  1146. return Expr;
  1147. }
  1148. DIExpression *DIExpression::prepend(const DIExpression *Expr, uint8_t Flags,
  1149. int64_t Offset) {
  1150. SmallVector<uint64_t, 8> Ops;
  1151. if (Flags & DIExpression::DerefBefore)
  1152. Ops.push_back(dwarf::DW_OP_deref);
  1153. appendOffset(Ops, Offset);
  1154. if (Flags & DIExpression::DerefAfter)
  1155. Ops.push_back(dwarf::DW_OP_deref);
  1156. bool StackValue = Flags & DIExpression::StackValue;
  1157. bool EntryValue = Flags & DIExpression::EntryValue;
  1158. return prependOpcodes(Expr, Ops, StackValue, EntryValue);
  1159. }
  1160. DIExpression *DIExpression::appendOpsToArg(const DIExpression *Expr,
  1161. ArrayRef<uint64_t> Ops,
  1162. unsigned ArgNo, bool StackValue) {
  1163. assert(Expr && "Can't add ops to this expression");
  1164. // Handle non-variadic intrinsics by prepending the opcodes.
  1165. if (!any_of(Expr->expr_ops(),
  1166. [](auto Op) { return Op.getOp() == dwarf::DW_OP_LLVM_arg; })) {
  1167. assert(ArgNo == 0 &&
  1168. "Location Index must be 0 for a non-variadic expression.");
  1169. SmallVector<uint64_t, 8> NewOps(Ops.begin(), Ops.end());
  1170. return DIExpression::prependOpcodes(Expr, NewOps, StackValue);
  1171. }
  1172. SmallVector<uint64_t, 8> NewOps;
  1173. for (auto Op : Expr->expr_ops()) {
  1174. Op.appendToVector(NewOps);
  1175. if (Op.getOp() == dwarf::DW_OP_LLVM_arg && Op.getArg(0) == ArgNo)
  1176. NewOps.insert(NewOps.end(), Ops.begin(), Ops.end());
  1177. }
  1178. return DIExpression::get(Expr->getContext(), NewOps);
  1179. }
  1180. DIExpression *DIExpression::replaceArg(const DIExpression *Expr,
  1181. uint64_t OldArg, uint64_t NewArg) {
  1182. assert(Expr && "Can't replace args in this expression");
  1183. SmallVector<uint64_t, 8> NewOps;
  1184. for (auto Op : Expr->expr_ops()) {
  1185. if (Op.getOp() != dwarf::DW_OP_LLVM_arg || Op.getArg(0) < OldArg) {
  1186. Op.appendToVector(NewOps);
  1187. continue;
  1188. }
  1189. NewOps.push_back(dwarf::DW_OP_LLVM_arg);
  1190. uint64_t Arg = Op.getArg(0) == OldArg ? NewArg : Op.getArg(0);
  1191. // OldArg has been deleted from the Op list, so decrement all indices
  1192. // greater than it.
  1193. if (Arg > OldArg)
  1194. --Arg;
  1195. NewOps.push_back(Arg);
  1196. }
  1197. return DIExpression::get(Expr->getContext(), NewOps);
  1198. }
  1199. DIExpression *DIExpression::prependOpcodes(const DIExpression *Expr,
  1200. SmallVectorImpl<uint64_t> &Ops,
  1201. bool StackValue, bool EntryValue) {
  1202. assert(Expr && "Can't prepend ops to this expression");
  1203. if (EntryValue) {
  1204. Ops.push_back(dwarf::DW_OP_LLVM_entry_value);
  1205. // Use a block size of 1 for the target register operand. The
  1206. // DWARF backend currently cannot emit entry values with a block
  1207. // size > 1.
  1208. Ops.push_back(1);
  1209. }
  1210. // If there are no ops to prepend, do not even add the DW_OP_stack_value.
  1211. if (Ops.empty())
  1212. StackValue = false;
  1213. for (auto Op : Expr->expr_ops()) {
  1214. // A DW_OP_stack_value comes at the end, but before a DW_OP_LLVM_fragment.
  1215. if (StackValue) {
  1216. if (Op.getOp() == dwarf::DW_OP_stack_value)
  1217. StackValue = false;
  1218. else if (Op.getOp() == dwarf::DW_OP_LLVM_fragment) {
  1219. Ops.push_back(dwarf::DW_OP_stack_value);
  1220. StackValue = false;
  1221. }
  1222. }
  1223. Op.appendToVector(Ops);
  1224. }
  1225. if (StackValue)
  1226. Ops.push_back(dwarf::DW_OP_stack_value);
  1227. return DIExpression::get(Expr->getContext(), Ops);
  1228. }
  1229. DIExpression *DIExpression::append(const DIExpression *Expr,
  1230. ArrayRef<uint64_t> Ops) {
  1231. assert(Expr && !Ops.empty() && "Can't append ops to this expression");
  1232. // Copy Expr's current op list.
  1233. SmallVector<uint64_t, 16> NewOps;
  1234. for (auto Op : Expr->expr_ops()) {
  1235. // Append new opcodes before DW_OP_{stack_value, LLVM_fragment}.
  1236. if (Op.getOp() == dwarf::DW_OP_stack_value ||
  1237. Op.getOp() == dwarf::DW_OP_LLVM_fragment) {
  1238. NewOps.append(Ops.begin(), Ops.end());
  1239. // Ensure that the new opcodes are only appended once.
  1240. Ops = None;
  1241. }
  1242. Op.appendToVector(NewOps);
  1243. }
  1244. NewOps.append(Ops.begin(), Ops.end());
  1245. auto *result = DIExpression::get(Expr->getContext(), NewOps);
  1246. assert(result->isValid() && "concatenated expression is not valid");
  1247. return result;
  1248. }
  1249. DIExpression *DIExpression::appendToStack(const DIExpression *Expr,
  1250. ArrayRef<uint64_t> Ops) {
  1251. assert(Expr && !Ops.empty() && "Can't append ops to this expression");
  1252. assert(none_of(Ops,
  1253. [](uint64_t Op) {
  1254. return Op == dwarf::DW_OP_stack_value ||
  1255. Op == dwarf::DW_OP_LLVM_fragment;
  1256. }) &&
  1257. "Can't append this op");
  1258. // Append a DW_OP_deref after Expr's current op list if it's non-empty and
  1259. // has no DW_OP_stack_value.
  1260. //
  1261. // Match .* DW_OP_stack_value (DW_OP_LLVM_fragment A B)?.
  1262. Optional<FragmentInfo> FI = Expr->getFragmentInfo();
  1263. unsigned DropUntilStackValue = FI.hasValue() ? 3 : 0;
  1264. ArrayRef<uint64_t> ExprOpsBeforeFragment =
  1265. Expr->getElements().drop_back(DropUntilStackValue);
  1266. bool NeedsDeref = (Expr->getNumElements() > DropUntilStackValue) &&
  1267. (ExprOpsBeforeFragment.back() != dwarf::DW_OP_stack_value);
  1268. bool NeedsStackValue = NeedsDeref || ExprOpsBeforeFragment.empty();
  1269. // Append a DW_OP_deref after Expr's current op list if needed, then append
  1270. // the new ops, and finally ensure that a single DW_OP_stack_value is present.
  1271. SmallVector<uint64_t, 16> NewOps;
  1272. if (NeedsDeref)
  1273. NewOps.push_back(dwarf::DW_OP_deref);
  1274. NewOps.append(Ops.begin(), Ops.end());
  1275. if (NeedsStackValue)
  1276. NewOps.push_back(dwarf::DW_OP_stack_value);
  1277. return DIExpression::append(Expr, NewOps);
  1278. }
  1279. Optional<DIExpression *> DIExpression::createFragmentExpression(
  1280. const DIExpression *Expr, unsigned OffsetInBits, unsigned SizeInBits) {
  1281. SmallVector<uint64_t, 8> Ops;
  1282. // Copy over the expression, but leave off any trailing DW_OP_LLVM_fragment.
  1283. if (Expr) {
  1284. for (auto Op : Expr->expr_ops()) {
  1285. switch (Op.getOp()) {
  1286. default:
  1287. break;
  1288. case dwarf::DW_OP_shr:
  1289. case dwarf::DW_OP_shra:
  1290. case dwarf::DW_OP_shl:
  1291. case dwarf::DW_OP_plus:
  1292. case dwarf::DW_OP_plus_uconst:
  1293. case dwarf::DW_OP_minus:
  1294. // We can't safely split arithmetic or shift operations into multiple
  1295. // fragments because we can't express carry-over between fragments.
  1296. //
  1297. // FIXME: We *could* preserve the lowest fragment of a constant offset
  1298. // operation if the offset fits into SizeInBits.
  1299. return None;
  1300. case dwarf::DW_OP_LLVM_fragment: {
  1301. // Make the new offset point into the existing fragment.
  1302. uint64_t FragmentOffsetInBits = Op.getArg(0);
  1303. uint64_t FragmentSizeInBits = Op.getArg(1);
  1304. (void)FragmentSizeInBits;
  1305. assert((OffsetInBits + SizeInBits <= FragmentSizeInBits) &&
  1306. "new fragment outside of original fragment");
  1307. OffsetInBits += FragmentOffsetInBits;
  1308. continue;
  1309. }
  1310. }
  1311. Op.appendToVector(Ops);
  1312. }
  1313. }
  1314. assert(Expr && "Unknown DIExpression");
  1315. Ops.push_back(dwarf::DW_OP_LLVM_fragment);
  1316. Ops.push_back(OffsetInBits);
  1317. Ops.push_back(SizeInBits);
  1318. return DIExpression::get(Expr->getContext(), Ops);
  1319. }
  1320. std::pair<DIExpression *, const ConstantInt *>
  1321. DIExpression::constantFold(const ConstantInt *CI) {
  1322. // Copy the APInt so we can modify it.
  1323. APInt NewInt = CI->getValue();
  1324. SmallVector<uint64_t, 8> Ops;
  1325. // Fold operators only at the beginning of the expression.
  1326. bool First = true;
  1327. bool Changed = false;
  1328. for (auto Op : expr_ops()) {
  1329. switch (Op.getOp()) {
  1330. default:
  1331. // We fold only the leading part of the expression; if we get to a part
  1332. // that we're going to copy unchanged, and haven't done any folding,
  1333. // then the entire expression is unchanged and we can return early.
  1334. if (!Changed)
  1335. return {this, CI};
  1336. First = false;
  1337. break;
  1338. case dwarf::DW_OP_LLVM_convert:
  1339. if (!First)
  1340. break;
  1341. Changed = true;
  1342. if (Op.getArg(1) == dwarf::DW_ATE_signed)
  1343. NewInt = NewInt.sextOrTrunc(Op.getArg(0));
  1344. else {
  1345. assert(Op.getArg(1) == dwarf::DW_ATE_unsigned && "Unexpected operand");
  1346. NewInt = NewInt.zextOrTrunc(Op.getArg(0));
  1347. }
  1348. continue;
  1349. }
  1350. Op.appendToVector(Ops);
  1351. }
  1352. if (!Changed)
  1353. return {this, CI};
  1354. return {DIExpression::get(getContext(), Ops),
  1355. ConstantInt::get(getContext(), NewInt)};
  1356. }
  1357. uint64_t DIExpression::getNumLocationOperands() const {
  1358. uint64_t Result = 0;
  1359. for (auto ExprOp : expr_ops())
  1360. if (ExprOp.getOp() == dwarf::DW_OP_LLVM_arg)
  1361. Result = std::max(Result, ExprOp.getArg(0) + 1);
  1362. assert(hasAllLocationOps(Result) &&
  1363. "Expression is missing one or more location operands.");
  1364. return Result;
  1365. }
  1366. llvm::Optional<DIExpression::SignedOrUnsignedConstant>
  1367. DIExpression::isConstant() const {
  1368. // Recognize signed and unsigned constants.
  1369. // An signed constants can be represented as DW_OP_consts C DW_OP_stack_value
  1370. // (DW_OP_LLVM_fragment of Len).
  1371. // An unsigned constant can be represented as
  1372. // DW_OP_constu C DW_OP_stack_value (DW_OP_LLVM_fragment of Len).
  1373. if ((getNumElements() != 2 && getNumElements() != 3 &&
  1374. getNumElements() != 6) ||
  1375. (getElement(0) != dwarf::DW_OP_consts &&
  1376. getElement(0) != dwarf::DW_OP_constu))
  1377. return None;
  1378. if (getNumElements() == 2 && getElement(0) == dwarf::DW_OP_consts)
  1379. return SignedOrUnsignedConstant::SignedConstant;
  1380. if ((getNumElements() == 3 && getElement(2) != dwarf::DW_OP_stack_value) ||
  1381. (getNumElements() == 6 && (getElement(2) != dwarf::DW_OP_stack_value ||
  1382. getElement(3) != dwarf::DW_OP_LLVM_fragment)))
  1383. return None;
  1384. return getElement(0) == dwarf::DW_OP_constu
  1385. ? SignedOrUnsignedConstant::UnsignedConstant
  1386. : SignedOrUnsignedConstant::SignedConstant;
  1387. }
  1388. DIExpression::ExtOps DIExpression::getExtOps(unsigned FromSize, unsigned ToSize,
  1389. bool Signed) {
  1390. dwarf::TypeKind TK = Signed ? dwarf::DW_ATE_signed : dwarf::DW_ATE_unsigned;
  1391. DIExpression::ExtOps Ops{{dwarf::DW_OP_LLVM_convert, FromSize, TK,
  1392. dwarf::DW_OP_LLVM_convert, ToSize, TK}};
  1393. return Ops;
  1394. }
  1395. DIExpression *DIExpression::appendExt(const DIExpression *Expr,
  1396. unsigned FromSize, unsigned ToSize,
  1397. bool Signed) {
  1398. return appendToStack(Expr, getExtOps(FromSize, ToSize, Signed));
  1399. }
  1400. DIGlobalVariableExpression *
  1401. DIGlobalVariableExpression::getImpl(LLVMContext &Context, Metadata *Variable,
  1402. Metadata *Expression, StorageType Storage,
  1403. bool ShouldCreate) {
  1404. DEFINE_GETIMPL_LOOKUP(DIGlobalVariableExpression, (Variable, Expression));
  1405. Metadata *Ops[] = {Variable, Expression};
  1406. DEFINE_GETIMPL_STORE_NO_CONSTRUCTOR_ARGS(DIGlobalVariableExpression, Ops);
  1407. }
  1408. DIObjCProperty *DIObjCProperty::getImpl(
  1409. LLVMContext &Context, MDString *Name, Metadata *File, unsigned Line,
  1410. MDString *GetterName, MDString *SetterName, unsigned Attributes,
  1411. Metadata *Type, StorageType Storage, bool ShouldCreate) {
  1412. assert(isCanonical(Name) && "Expected canonical MDString");
  1413. assert(isCanonical(GetterName) && "Expected canonical MDString");
  1414. assert(isCanonical(SetterName) && "Expected canonical MDString");
  1415. DEFINE_GETIMPL_LOOKUP(DIObjCProperty, (Name, File, Line, GetterName,
  1416. SetterName, Attributes, Type));
  1417. Metadata *Ops[] = {Name, File, GetterName, SetterName, Type};
  1418. DEFINE_GETIMPL_STORE(DIObjCProperty, (Line, Attributes), Ops);
  1419. }
  1420. DIImportedEntity *DIImportedEntity::getImpl(LLVMContext &Context, unsigned Tag,
  1421. Metadata *Scope, Metadata *Entity,
  1422. Metadata *File, unsigned Line,
  1423. MDString *Name, Metadata *Elements,
  1424. StorageType Storage,
  1425. bool ShouldCreate) {
  1426. assert(isCanonical(Name) && "Expected canonical MDString");
  1427. DEFINE_GETIMPL_LOOKUP(DIImportedEntity,
  1428. (Tag, Scope, Entity, File, Line, Name, Elements));
  1429. Metadata *Ops[] = {Scope, Entity, Name, File, Elements};
  1430. DEFINE_GETIMPL_STORE(DIImportedEntity, (Tag, Line), Ops);
  1431. }
  1432. DIMacro *DIMacro::getImpl(LLVMContext &Context, unsigned MIType, unsigned Line,
  1433. MDString *Name, MDString *Value, StorageType Storage,
  1434. bool ShouldCreate) {
  1435. assert(isCanonical(Name) && "Expected canonical MDString");
  1436. DEFINE_GETIMPL_LOOKUP(DIMacro, (MIType, Line, Name, Value));
  1437. Metadata *Ops[] = {Name, Value};
  1438. DEFINE_GETIMPL_STORE(DIMacro, (MIType, Line), Ops);
  1439. }
  1440. DIMacroFile *DIMacroFile::getImpl(LLVMContext &Context, unsigned MIType,
  1441. unsigned Line, Metadata *File,
  1442. Metadata *Elements, StorageType Storage,
  1443. bool ShouldCreate) {
  1444. DEFINE_GETIMPL_LOOKUP(DIMacroFile, (MIType, Line, File, Elements));
  1445. Metadata *Ops[] = {File, Elements};
  1446. DEFINE_GETIMPL_STORE(DIMacroFile, (MIType, Line), Ops);
  1447. }
  1448. DIArgList *DIArgList::getImpl(LLVMContext &Context,
  1449. ArrayRef<ValueAsMetadata *> Args,
  1450. StorageType Storage, bool ShouldCreate) {
  1451. DEFINE_GETIMPL_LOOKUP(DIArgList, (Args));
  1452. DEFINE_GETIMPL_STORE_NO_OPS(DIArgList, (Args));
  1453. }
  1454. void DIArgList::handleChangedOperand(void *Ref, Metadata *New) {
  1455. ValueAsMetadata **OldVMPtr = static_cast<ValueAsMetadata **>(Ref);
  1456. assert((!New || isa<ValueAsMetadata>(New)) &&
  1457. "DIArgList must be passed a ValueAsMetadata");
  1458. untrack();
  1459. bool Uniq = isUniqued();
  1460. if (Uniq) {
  1461. // We need to update the uniqueness once the Args are updated since they
  1462. // form the key to the DIArgLists store.
  1463. eraseFromStore();
  1464. }
  1465. ValueAsMetadata *NewVM = cast_or_null<ValueAsMetadata>(New);
  1466. for (ValueAsMetadata *&VM : Args) {
  1467. if (&VM == OldVMPtr) {
  1468. if (NewVM)
  1469. VM = NewVM;
  1470. else
  1471. VM = ValueAsMetadata::get(UndefValue::get(VM->getValue()->getType()));
  1472. }
  1473. }
  1474. if (Uniq) {
  1475. if (uniquify() != this)
  1476. storeDistinctInContext();
  1477. }
  1478. track();
  1479. }
  1480. void DIArgList::track() {
  1481. for (ValueAsMetadata *&VAM : Args)
  1482. if (VAM)
  1483. MetadataTracking::track(&VAM, *VAM, *this);
  1484. }
  1485. void DIArgList::untrack() {
  1486. for (ValueAsMetadata *&VAM : Args)
  1487. if (VAM)
  1488. MetadataTracking::untrack(&VAM, *VAM);
  1489. }
  1490. void DIArgList::dropAllReferences() {
  1491. untrack();
  1492. Args.clear();
  1493. MDNode::dropAllReferences();
  1494. }