Value.h 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===- llvm/Value.h - Definition of the Value class -------------*- C++ -*-===//
  7. //
  8. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  9. // See https://llvm.org/LICENSE.txt for license information.
  10. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  11. //
  12. //===----------------------------------------------------------------------===//
  13. //
  14. // This file declares the Value class.
  15. //
  16. //===----------------------------------------------------------------------===//
  17. #ifndef LLVM_IR_VALUE_H
  18. #define LLVM_IR_VALUE_H
  19. #include "llvm-c/Types.h"
  20. #include "llvm/ADT/STLExtras.h"
  21. #include "llvm/ADT/StringRef.h"
  22. #include "llvm/ADT/iterator_range.h"
  23. #include "llvm/IR/Use.h"
  24. #include "llvm/Support/Alignment.h"
  25. #include "llvm/Support/CBindingWrapping.h"
  26. #include "llvm/Support/Casting.h"
  27. #include <cassert>
  28. #include <iterator>
  29. #include <memory>
  30. namespace llvm {
  31. class APInt;
  32. class Argument;
  33. class BasicBlock;
  34. class Constant;
  35. class ConstantData;
  36. class ConstantAggregate;
  37. class DataLayout;
  38. class Function;
  39. class GlobalAlias;
  40. class GlobalIFunc;
  41. class GlobalObject;
  42. class GlobalValue;
  43. class GlobalVariable;
  44. class InlineAsm;
  45. class Instruction;
  46. class LLVMContext;
  47. class MDNode;
  48. class Module;
  49. class ModuleSlotTracker;
  50. class raw_ostream;
  51. template<typename ValueTy> class StringMapEntry;
  52. class Twine;
  53. class Type;
  54. class User;
  55. using ValueName = StringMapEntry<Value *>;
  56. //===----------------------------------------------------------------------===//
  57. // Value Class
  58. //===----------------------------------------------------------------------===//
  59. /// LLVM Value Representation
  60. ///
  61. /// This is a very important LLVM class. It is the base class of all values
  62. /// computed by a program that may be used as operands to other values. Value is
  63. /// the super class of other important classes such as Instruction and Function.
  64. /// All Values have a Type. Type is not a subclass of Value. Some values can
  65. /// have a name and they belong to some Module. Setting the name on the Value
  66. /// automatically updates the module's symbol table.
  67. ///
  68. /// Every value has a "use list" that keeps track of which other Values are
  69. /// using this Value. A Value can also have an arbitrary number of ValueHandle
  70. /// objects that watch it and listen to RAUW and Destroy events. See
  71. /// llvm/IR/ValueHandle.h for details.
  72. class Value {
  73. Type *VTy;
  74. Use *UseList;
  75. friend class ValueAsMetadata; // Allow access to IsUsedByMD.
  76. friend class ValueHandleBase;
  77. const unsigned char SubclassID; // Subclass identifier (for isa/dyn_cast)
  78. unsigned char HasValueHandle : 1; // Has a ValueHandle pointing to this?
  79. protected:
  80. /// Hold subclass data that can be dropped.
  81. ///
  82. /// This member is similar to SubclassData, however it is for holding
  83. /// information which may be used to aid optimization, but which may be
  84. /// cleared to zero without affecting conservative interpretation.
  85. unsigned char SubclassOptionalData : 7;
  86. private:
  87. /// Hold arbitrary subclass data.
  88. ///
  89. /// This member is defined by this class, but is not used for anything.
  90. /// Subclasses can use it to hold whatever state they find useful. This
  91. /// field is initialized to zero by the ctor.
  92. unsigned short SubclassData;
  93. protected:
  94. /// The number of operands in the subclass.
  95. ///
  96. /// This member is defined by this class, but not used for anything.
  97. /// Subclasses can use it to store their number of operands, if they have
  98. /// any.
  99. ///
  100. /// This is stored here to save space in User on 64-bit hosts. Since most
  101. /// instances of Value have operands, 32-bit hosts aren't significantly
  102. /// affected.
  103. ///
  104. /// Note, this should *NOT* be used directly by any class other than User.
  105. /// User uses this value to find the Use list.
  106. enum : unsigned { NumUserOperandsBits = 27 };
  107. unsigned NumUserOperands : NumUserOperandsBits;
  108. // Use the same type as the bitfield above so that MSVC will pack them.
  109. unsigned IsUsedByMD : 1;
  110. unsigned HasName : 1;
  111. unsigned HasMetadata : 1; // Has metadata attached to this?
  112. unsigned HasHungOffUses : 1;
  113. unsigned HasDescriptor : 1;
  114. private:
  115. template <typename UseT> // UseT == 'Use' or 'const Use'
  116. class use_iterator_impl {
  117. friend class Value;
  118. UseT *U;
  119. explicit use_iterator_impl(UseT *u) : U(u) {}
  120. public:
  121. using iterator_category = std::forward_iterator_tag;
  122. using value_type = UseT *;
  123. using difference_type = std::ptrdiff_t;
  124. using pointer = value_type *;
  125. using reference = value_type &;
  126. use_iterator_impl() : U() {}
  127. bool operator==(const use_iterator_impl &x) const { return U == x.U; }
  128. bool operator!=(const use_iterator_impl &x) const { return !operator==(x); }
  129. use_iterator_impl &operator++() { // Preincrement
  130. assert(U && "Cannot increment end iterator!");
  131. U = U->getNext();
  132. return *this;
  133. }
  134. use_iterator_impl operator++(int) { // Postincrement
  135. auto tmp = *this;
  136. ++*this;
  137. return tmp;
  138. }
  139. UseT &operator*() const {
  140. assert(U && "Cannot dereference end iterator!");
  141. return *U;
  142. }
  143. UseT *operator->() const { return &operator*(); }
  144. operator use_iterator_impl<const UseT>() const {
  145. return use_iterator_impl<const UseT>(U);
  146. }
  147. };
  148. template <typename UserTy> // UserTy == 'User' or 'const User'
  149. class user_iterator_impl {
  150. use_iterator_impl<Use> UI;
  151. explicit user_iterator_impl(Use *U) : UI(U) {}
  152. friend class Value;
  153. public:
  154. using iterator_category = std::forward_iterator_tag;
  155. using value_type = UserTy *;
  156. using difference_type = std::ptrdiff_t;
  157. using pointer = value_type *;
  158. using reference = value_type &;
  159. user_iterator_impl() = default;
  160. bool operator==(const user_iterator_impl &x) const { return UI == x.UI; }
  161. bool operator!=(const user_iterator_impl &x) const { return !operator==(x); }
  162. /// Returns true if this iterator is equal to user_end() on the value.
  163. bool atEnd() const { return *this == user_iterator_impl(); }
  164. user_iterator_impl &operator++() { // Preincrement
  165. ++UI;
  166. return *this;
  167. }
  168. user_iterator_impl operator++(int) { // Postincrement
  169. auto tmp = *this;
  170. ++*this;
  171. return tmp;
  172. }
  173. // Retrieve a pointer to the current User.
  174. UserTy *operator*() const {
  175. return UI->getUser();
  176. }
  177. UserTy *operator->() const { return operator*(); }
  178. operator user_iterator_impl<const UserTy>() const {
  179. return user_iterator_impl<const UserTy>(*UI);
  180. }
  181. Use &getUse() const { return *UI; }
  182. };
  183. protected:
  184. Value(Type *Ty, unsigned scid);
  185. /// Value's destructor should be virtual by design, but that would require
  186. /// that Value and all of its subclasses have a vtable that effectively
  187. /// duplicates the information in the value ID. As a size optimization, the
  188. /// destructor has been protected, and the caller should manually call
  189. /// deleteValue.
  190. ~Value(); // Use deleteValue() to delete a generic Value.
  191. public:
  192. Value(const Value &) = delete;
  193. Value &operator=(const Value &) = delete;
  194. /// Delete a pointer to a generic Value.
  195. void deleteValue();
  196. /// Support for debugging, callable in GDB: V->dump()
  197. void dump() const;
  198. /// Implement operator<< on Value.
  199. /// @{
  200. void print(raw_ostream &O, bool IsForDebug = false) const;
  201. void print(raw_ostream &O, ModuleSlotTracker &MST,
  202. bool IsForDebug = false) const;
  203. /// @}
  204. /// Print the name of this Value out to the specified raw_ostream.
  205. ///
  206. /// This is useful when you just want to print 'int %reg126', not the
  207. /// instruction that generated it. If you specify a Module for context, then
  208. /// even constanst get pretty-printed; for example, the type of a null
  209. /// pointer is printed symbolically.
  210. /// @{
  211. void printAsOperand(raw_ostream &O, bool PrintType = true,
  212. const Module *M = nullptr) const;
  213. void printAsOperand(raw_ostream &O, bool PrintType,
  214. ModuleSlotTracker &MST) const;
  215. /// @}
  216. /// All values are typed, get the type of this value.
  217. Type *getType() const { return VTy; }
  218. /// All values hold a context through their type.
  219. LLVMContext &getContext() const;
  220. // All values can potentially be named.
  221. bool hasName() const { return HasName; }
  222. ValueName *getValueName() const;
  223. void setValueName(ValueName *VN);
  224. private:
  225. void destroyValueName();
  226. enum class ReplaceMetadataUses { No, Yes };
  227. void doRAUW(Value *New, ReplaceMetadataUses);
  228. void setNameImpl(const Twine &Name);
  229. public:
  230. /// Return a constant reference to the value's name.
  231. ///
  232. /// This guaranteed to return the same reference as long as the value is not
  233. /// modified. If the value has a name, this does a hashtable lookup, so it's
  234. /// not free.
  235. StringRef getName() const;
  236. /// Change the name of the value.
  237. ///
  238. /// Choose a new unique name if the provided name is taken.
  239. ///
  240. /// \param Name The new name; or "" if the value's name should be removed.
  241. void setName(const Twine &Name);
  242. /// Transfer the name from V to this value.
  243. ///
  244. /// After taking V's name, sets V's name to empty.
  245. ///
  246. /// \note It is an error to call V->takeName(V).
  247. void takeName(Value *V);
  248. #ifndef NDEBUG
  249. std::string getNameOrAsOperand() const;
  250. #endif
  251. /// Change all uses of this to point to a new Value.
  252. ///
  253. /// Go through the uses list for this definition and make each use point to
  254. /// "V" instead of "this". After this completes, 'this's use list is
  255. /// guaranteed to be empty.
  256. void replaceAllUsesWith(Value *V);
  257. /// Change non-metadata uses of this to point to a new Value.
  258. ///
  259. /// Go through the uses list for this definition and make each use point to
  260. /// "V" instead of "this". This function skips metadata entries in the list.
  261. void replaceNonMetadataUsesWith(Value *V);
  262. /// Go through the uses list for this definition and make each use point
  263. /// to "V" if the callback ShouldReplace returns true for the given Use.
  264. /// Unlike replaceAllUsesWith() this function does not support basic block
  265. /// values.
  266. void replaceUsesWithIf(Value *New,
  267. llvm::function_ref<bool(Use &U)> ShouldReplace);
  268. /// replaceUsesOutsideBlock - Go through the uses list for this definition and
  269. /// make each use point to "V" instead of "this" when the use is outside the
  270. /// block. 'This's use list is expected to have at least one element.
  271. /// Unlike replaceAllUsesWith() this function does not support basic block
  272. /// values.
  273. void replaceUsesOutsideBlock(Value *V, BasicBlock *BB);
  274. //----------------------------------------------------------------------
  275. // Methods for handling the chain of uses of this Value.
  276. //
  277. // Materializing a function can introduce new uses, so these methods come in
  278. // two variants:
  279. // The methods that start with materialized_ check the uses that are
  280. // currently known given which functions are materialized. Be very careful
  281. // when using them since you might not get all uses.
  282. // The methods that don't start with materialized_ assert that modules is
  283. // fully materialized.
  284. void assertModuleIsMaterializedImpl() const;
  285. // This indirection exists so we can keep assertModuleIsMaterializedImpl()
  286. // around in release builds of Value.cpp to be linked with other code built
  287. // in debug mode. But this avoids calling it in any of the release built code.
  288. void assertModuleIsMaterialized() const {
  289. #ifndef NDEBUG
  290. assertModuleIsMaterializedImpl();
  291. #endif
  292. }
  293. bool use_empty() const {
  294. assertModuleIsMaterialized();
  295. return UseList == nullptr;
  296. }
  297. bool materialized_use_empty() const {
  298. return UseList == nullptr;
  299. }
  300. using use_iterator = use_iterator_impl<Use>;
  301. using const_use_iterator = use_iterator_impl<const Use>;
  302. use_iterator materialized_use_begin() { return use_iterator(UseList); }
  303. const_use_iterator materialized_use_begin() const {
  304. return const_use_iterator(UseList);
  305. }
  306. use_iterator use_begin() {
  307. assertModuleIsMaterialized();
  308. return materialized_use_begin();
  309. }
  310. const_use_iterator use_begin() const {
  311. assertModuleIsMaterialized();
  312. return materialized_use_begin();
  313. }
  314. use_iterator use_end() { return use_iterator(); }
  315. const_use_iterator use_end() const { return const_use_iterator(); }
  316. iterator_range<use_iterator> materialized_uses() {
  317. return make_range(materialized_use_begin(), use_end());
  318. }
  319. iterator_range<const_use_iterator> materialized_uses() const {
  320. return make_range(materialized_use_begin(), use_end());
  321. }
  322. iterator_range<use_iterator> uses() {
  323. assertModuleIsMaterialized();
  324. return materialized_uses();
  325. }
  326. iterator_range<const_use_iterator> uses() const {
  327. assertModuleIsMaterialized();
  328. return materialized_uses();
  329. }
  330. bool user_empty() const {
  331. assertModuleIsMaterialized();
  332. return UseList == nullptr;
  333. }
  334. using user_iterator = user_iterator_impl<User>;
  335. using const_user_iterator = user_iterator_impl<const User>;
  336. user_iterator materialized_user_begin() { return user_iterator(UseList); }
  337. const_user_iterator materialized_user_begin() const {
  338. return const_user_iterator(UseList);
  339. }
  340. user_iterator user_begin() {
  341. assertModuleIsMaterialized();
  342. return materialized_user_begin();
  343. }
  344. const_user_iterator user_begin() const {
  345. assertModuleIsMaterialized();
  346. return materialized_user_begin();
  347. }
  348. user_iterator user_end() { return user_iterator(); }
  349. const_user_iterator user_end() const { return const_user_iterator(); }
  350. User *user_back() {
  351. assertModuleIsMaterialized();
  352. return *materialized_user_begin();
  353. }
  354. const User *user_back() const {
  355. assertModuleIsMaterialized();
  356. return *materialized_user_begin();
  357. }
  358. iterator_range<user_iterator> materialized_users() {
  359. return make_range(materialized_user_begin(), user_end());
  360. }
  361. iterator_range<const_user_iterator> materialized_users() const {
  362. return make_range(materialized_user_begin(), user_end());
  363. }
  364. iterator_range<user_iterator> users() {
  365. assertModuleIsMaterialized();
  366. return materialized_users();
  367. }
  368. iterator_range<const_user_iterator> users() const {
  369. assertModuleIsMaterialized();
  370. return materialized_users();
  371. }
  372. /// Return true if there is exactly one use of this value.
  373. ///
  374. /// This is specialized because it is a common request and does not require
  375. /// traversing the whole use list.
  376. bool hasOneUse() const { return hasSingleElement(uses()); }
  377. /// Return true if this Value has exactly N uses.
  378. bool hasNUses(unsigned N) const;
  379. /// Return true if this value has N uses or more.
  380. ///
  381. /// This is logically equivalent to getNumUses() >= N.
  382. bool hasNUsesOrMore(unsigned N) const;
  383. /// Return true if there is exactly one user of this value.
  384. ///
  385. /// Note that this is not the same as "has one use". If a value has one use,
  386. /// then there certainly is a single user. But if value has several uses,
  387. /// it is possible that all uses are in a single user, or not.
  388. ///
  389. /// This check is potentially costly, since it requires traversing,
  390. /// in the worst case, the whole use list of a value.
  391. bool hasOneUser() const;
  392. /// Return true if there is exactly one use of this value that cannot be
  393. /// dropped.
  394. Use *getSingleUndroppableUse();
  395. const Use *getSingleUndroppableUse() const {
  396. return const_cast<Value *>(this)->getSingleUndroppableUse();
  397. }
  398. /// Return true if there is exactly one unique user of this value that cannot be
  399. /// dropped (that user can have multiple uses of this value).
  400. User *getUniqueUndroppableUser();
  401. const User *getUniqueUndroppableUser() const {
  402. return const_cast<Value *>(this)->getUniqueUndroppableUser();
  403. }
  404. /// Return true if there this value.
  405. ///
  406. /// This is specialized because it is a common request and does not require
  407. /// traversing the whole use list.
  408. bool hasNUndroppableUses(unsigned N) const;
  409. /// Return true if this value has N uses or more.
  410. ///
  411. /// This is logically equivalent to getNumUses() >= N.
  412. bool hasNUndroppableUsesOrMore(unsigned N) const;
  413. /// Remove every uses that can safely be removed.
  414. ///
  415. /// This will remove for example uses in llvm.assume.
  416. /// This should be used when performing want to perform a tranformation but
  417. /// some Droppable uses pervent it.
  418. /// This function optionally takes a filter to only remove some droppable
  419. /// uses.
  420. void dropDroppableUses(llvm::function_ref<bool(const Use *)> ShouldDrop =
  421. [](const Use *) { return true; });
  422. /// Remove every use of this value in \p User that can safely be removed.
  423. void dropDroppableUsesIn(User &Usr);
  424. /// Remove the droppable use \p U.
  425. static void dropDroppableUse(Use &U);
  426. /// Check if this value is used in the specified basic block.
  427. bool isUsedInBasicBlock(const BasicBlock *BB) const;
  428. /// This method computes the number of uses of this Value.
  429. ///
  430. /// This is a linear time operation. Use hasOneUse, hasNUses, or
  431. /// hasNUsesOrMore to check for specific values.
  432. unsigned getNumUses() const;
  433. /// This method should only be used by the Use class.
  434. void addUse(Use &U) { U.addToList(&UseList); }
  435. /// Concrete subclass of this.
  436. ///
  437. /// An enumeration for keeping track of the concrete subclass of Value that
  438. /// is actually instantiated. Values of this enumeration are kept in the
  439. /// Value classes SubclassID field. They are used for concrete type
  440. /// identification.
  441. enum ValueTy {
  442. #define HANDLE_VALUE(Name) Name##Val,
  443. #include "llvm/IR/Value.def"
  444. // Markers:
  445. #define HANDLE_CONSTANT_MARKER(Marker, Constant) Marker = Constant##Val,
  446. #include "llvm/IR/Value.def"
  447. };
  448. /// Return an ID for the concrete type of this object.
  449. ///
  450. /// This is used to implement the classof checks. This should not be used
  451. /// for any other purpose, as the values may change as LLVM evolves. Also,
  452. /// note that for instructions, the Instruction's opcode is added to
  453. /// InstructionVal. So this means three things:
  454. /// # there is no value with code InstructionVal (no opcode==0).
  455. /// # there are more possible values for the value type than in ValueTy enum.
  456. /// # the InstructionVal enumerator must be the highest valued enumerator in
  457. /// the ValueTy enum.
  458. unsigned getValueID() const {
  459. return SubclassID;
  460. }
  461. /// Return the raw optional flags value contained in this value.
  462. ///
  463. /// This should only be used when testing two Values for equivalence.
  464. unsigned getRawSubclassOptionalData() const {
  465. return SubclassOptionalData;
  466. }
  467. /// Clear the optional flags contained in this value.
  468. void clearSubclassOptionalData() {
  469. SubclassOptionalData = 0;
  470. }
  471. /// Check the optional flags for equality.
  472. bool hasSameSubclassOptionalData(const Value *V) const {
  473. return SubclassOptionalData == V->SubclassOptionalData;
  474. }
  475. /// Return true if there is a value handle associated with this value.
  476. bool hasValueHandle() const { return HasValueHandle; }
  477. /// Return true if there is metadata referencing this value.
  478. bool isUsedByMetadata() const { return IsUsedByMD; }
  479. protected:
  480. /// Get the current metadata attachments for the given kind, if any.
  481. ///
  482. /// These functions require that the value have at most a single attachment
  483. /// of the given kind, and return \c nullptr if such an attachment is missing.
  484. /// @{
  485. MDNode *getMetadata(unsigned KindID) const;
  486. MDNode *getMetadata(StringRef Kind) const;
  487. /// @}
  488. /// Appends all attachments with the given ID to \c MDs in insertion order.
  489. /// If the Value has no attachments with the given ID, or if ID is invalid,
  490. /// leaves MDs unchanged.
  491. /// @{
  492. void getMetadata(unsigned KindID, SmallVectorImpl<MDNode *> &MDs) const;
  493. void getMetadata(StringRef Kind, SmallVectorImpl<MDNode *> &MDs) const;
  494. /// @}
  495. /// Appends all metadata attached to this value to \c MDs, sorting by
  496. /// KindID. The first element of each pair returned is the KindID, the second
  497. /// element is the metadata value. Attachments with the same ID appear in
  498. /// insertion order.
  499. void
  500. getAllMetadata(SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs) const;
  501. /// Return true if this value has any metadata attached to it.
  502. bool hasMetadata() const { return (bool)HasMetadata; }
  503. /// Return true if this value has the given type of metadata attached.
  504. /// @{
  505. bool hasMetadata(unsigned KindID) const {
  506. return getMetadata(KindID) != nullptr;
  507. }
  508. bool hasMetadata(StringRef Kind) const {
  509. return getMetadata(Kind) != nullptr;
  510. }
  511. /// @}
  512. /// Set a particular kind of metadata attachment.
  513. ///
  514. /// Sets the given attachment to \c MD, erasing it if \c MD is \c nullptr or
  515. /// replacing it if it already exists.
  516. /// @{
  517. void setMetadata(unsigned KindID, MDNode *Node);
  518. void setMetadata(StringRef Kind, MDNode *Node);
  519. /// @}
  520. /// Add a metadata attachment.
  521. /// @{
  522. void addMetadata(unsigned KindID, MDNode &MD);
  523. void addMetadata(StringRef Kind, MDNode &MD);
  524. /// @}
  525. /// Erase all metadata attachments with the given kind.
  526. ///
  527. /// \returns true if any metadata was removed.
  528. bool eraseMetadata(unsigned KindID);
  529. /// Erase all metadata attached to this Value.
  530. void clearMetadata();
  531. public:
  532. /// Return true if this value is a swifterror value.
  533. ///
  534. /// swifterror values can be either a function argument or an alloca with a
  535. /// swifterror attribute.
  536. bool isSwiftError() const;
  537. /// Strip off pointer casts, all-zero GEPs and address space casts.
  538. ///
  539. /// Returns the original uncasted value. If this is called on a non-pointer
  540. /// value, it returns 'this'.
  541. const Value *stripPointerCasts() const;
  542. Value *stripPointerCasts() {
  543. return const_cast<Value *>(
  544. static_cast<const Value *>(this)->stripPointerCasts());
  545. }
  546. /// Strip off pointer casts, all-zero GEPs, address space casts, and aliases.
  547. ///
  548. /// Returns the original uncasted value. If this is called on a non-pointer
  549. /// value, it returns 'this'.
  550. const Value *stripPointerCastsAndAliases() const;
  551. Value *stripPointerCastsAndAliases() {
  552. return const_cast<Value *>(
  553. static_cast<const Value *>(this)->stripPointerCastsAndAliases());
  554. }
  555. /// Strip off pointer casts, all-zero GEPs and address space casts
  556. /// but ensures the representation of the result stays the same.
  557. ///
  558. /// Returns the original uncasted value with the same representation. If this
  559. /// is called on a non-pointer value, it returns 'this'.
  560. const Value *stripPointerCastsSameRepresentation() const;
  561. Value *stripPointerCastsSameRepresentation() {
  562. return const_cast<Value *>(static_cast<const Value *>(this)
  563. ->stripPointerCastsSameRepresentation());
  564. }
  565. /// Strip off pointer casts, all-zero GEPs, single-argument phi nodes and
  566. /// invariant group info.
  567. ///
  568. /// Returns the original uncasted value. If this is called on a non-pointer
  569. /// value, it returns 'this'. This function should be used only in
  570. /// Alias analysis.
  571. const Value *stripPointerCastsForAliasAnalysis() const;
  572. Value *stripPointerCastsForAliasAnalysis() {
  573. return const_cast<Value *>(static_cast<const Value *>(this)
  574. ->stripPointerCastsForAliasAnalysis());
  575. }
  576. /// Strip off pointer casts and all-constant inbounds GEPs.
  577. ///
  578. /// Returns the original pointer value. If this is called on a non-pointer
  579. /// value, it returns 'this'.
  580. const Value *stripInBoundsConstantOffsets() const;
  581. Value *stripInBoundsConstantOffsets() {
  582. return const_cast<Value *>(
  583. static_cast<const Value *>(this)->stripInBoundsConstantOffsets());
  584. }
  585. /// Accumulate the constant offset this value has compared to a base pointer.
  586. /// Only 'getelementptr' instructions (GEPs) are accumulated but other
  587. /// instructions, e.g., casts, are stripped away as well.
  588. /// The accumulated constant offset is added to \p Offset and the base
  589. /// pointer is returned.
  590. ///
  591. /// The APInt \p Offset has to have a bit-width equal to the IntPtr type for
  592. /// the address space of 'this' pointer value, e.g., use
  593. /// DataLayout::getIndexTypeSizeInBits(Ty).
  594. ///
  595. /// If \p AllowNonInbounds is true, offsets in GEPs are stripped and
  596. /// accumulated even if the GEP is not "inbounds".
  597. ///
  598. /// If \p AllowInvariantGroup is true then this method also looks through
  599. /// strip.invariant.group and launder.invariant.group intrinsics.
  600. ///
  601. /// If \p ExternalAnalysis is provided it will be used to calculate a offset
  602. /// when a operand of GEP is not constant.
  603. /// For example, for a value \p ExternalAnalysis might try to calculate a
  604. /// lower bound. If \p ExternalAnalysis is successful, it should return true.
  605. ///
  606. /// If this is called on a non-pointer value, it returns 'this' and the
  607. /// \p Offset is not modified.
  608. ///
  609. /// Note that this function will never return a nullptr. It will also never
  610. /// manipulate the \p Offset in a way that would not match the difference
  611. /// between the underlying value and the returned one. Thus, if no constant
  612. /// offset was found, the returned value is the underlying one and \p Offset
  613. /// is unchanged.
  614. const Value *stripAndAccumulateConstantOffsets(
  615. const DataLayout &DL, APInt &Offset, bool AllowNonInbounds,
  616. bool AllowInvariantGroup = false,
  617. function_ref<bool(Value &Value, APInt &Offset)> ExternalAnalysis =
  618. nullptr) const;
  619. Value *stripAndAccumulateConstantOffsets(const DataLayout &DL, APInt &Offset,
  620. bool AllowNonInbounds,
  621. bool AllowInvariantGroup = false) {
  622. return const_cast<Value *>(
  623. static_cast<const Value *>(this)->stripAndAccumulateConstantOffsets(
  624. DL, Offset, AllowNonInbounds, AllowInvariantGroup));
  625. }
  626. /// This is a wrapper around stripAndAccumulateConstantOffsets with the
  627. /// in-bounds requirement set to false.
  628. const Value *stripAndAccumulateInBoundsConstantOffsets(const DataLayout &DL,
  629. APInt &Offset) const {
  630. return stripAndAccumulateConstantOffsets(DL, Offset,
  631. /* AllowNonInbounds */ false);
  632. }
  633. Value *stripAndAccumulateInBoundsConstantOffsets(const DataLayout &DL,
  634. APInt &Offset) {
  635. return stripAndAccumulateConstantOffsets(DL, Offset,
  636. /* AllowNonInbounds */ false);
  637. }
  638. /// Strip off pointer casts and inbounds GEPs.
  639. ///
  640. /// Returns the original pointer value. If this is called on a non-pointer
  641. /// value, it returns 'this'.
  642. const Value *stripInBoundsOffsets(function_ref<void(const Value *)> Func =
  643. [](const Value *) {}) const;
  644. inline Value *stripInBoundsOffsets(function_ref<void(const Value *)> Func =
  645. [](const Value *) {}) {
  646. return const_cast<Value *>(
  647. static_cast<const Value *>(this)->stripInBoundsOffsets(Func));
  648. }
  649. /// Return true if the memory object referred to by V can by freed in the
  650. /// scope for which the SSA value defining the allocation is statically
  651. /// defined. E.g. deallocation after the static scope of a value does not
  652. /// count, but a deallocation before that does.
  653. bool canBeFreed() const;
  654. /// Returns the number of bytes known to be dereferenceable for the
  655. /// pointer value.
  656. ///
  657. /// If CanBeNull is set by this function the pointer can either be null or be
  658. /// dereferenceable up to the returned number of bytes.
  659. ///
  660. /// IF CanBeFreed is true, the pointer is known to be dereferenceable at
  661. /// point of definition only. Caller must prove that allocation is not
  662. /// deallocated between point of definition and use.
  663. uint64_t getPointerDereferenceableBytes(const DataLayout &DL,
  664. bool &CanBeNull,
  665. bool &CanBeFreed) const;
  666. /// Returns an alignment of the pointer value.
  667. ///
  668. /// Returns an alignment which is either specified explicitly, e.g. via
  669. /// align attribute of a function argument, or guaranteed by DataLayout.
  670. Align getPointerAlignment(const DataLayout &DL) const;
  671. /// Translate PHI node to its predecessor from the given basic block.
  672. ///
  673. /// If this value is a PHI node with CurBB as its parent, return the value in
  674. /// the PHI node corresponding to PredBB. If not, return ourself. This is
  675. /// useful if you want to know the value something has in a predecessor
  676. /// block.
  677. const Value *DoPHITranslation(const BasicBlock *CurBB,
  678. const BasicBlock *PredBB) const;
  679. Value *DoPHITranslation(const BasicBlock *CurBB, const BasicBlock *PredBB) {
  680. return const_cast<Value *>(
  681. static_cast<const Value *>(this)->DoPHITranslation(CurBB, PredBB));
  682. }
  683. /// The maximum alignment for instructions.
  684. ///
  685. /// This is the greatest alignment value supported by load, store, and alloca
  686. /// instructions, and global values.
  687. static constexpr unsigned MaxAlignmentExponent = 32;
  688. static constexpr uint64_t MaximumAlignment = 1ULL << MaxAlignmentExponent;
  689. /// Mutate the type of this Value to be of the specified type.
  690. ///
  691. /// Note that this is an extremely dangerous operation which can create
  692. /// completely invalid IR very easily. It is strongly recommended that you
  693. /// recreate IR objects with the right types instead of mutating them in
  694. /// place.
  695. void mutateType(Type *Ty) {
  696. VTy = Ty;
  697. }
  698. /// Sort the use-list.
  699. ///
  700. /// Sorts the Value's use-list by Cmp using a stable mergesort. Cmp is
  701. /// expected to compare two \a Use references.
  702. template <class Compare> void sortUseList(Compare Cmp);
  703. /// Reverse the use-list.
  704. void reverseUseList();
  705. private:
  706. /// Merge two lists together.
  707. ///
  708. /// Merges \c L and \c R using \c Cmp. To enable stable sorts, always pushes
  709. /// "equal" items from L before items from R.
  710. ///
  711. /// \return the first element in the list.
  712. ///
  713. /// \note Completely ignores \a Use::Prev (doesn't read, doesn't update).
  714. template <class Compare>
  715. static Use *mergeUseLists(Use *L, Use *R, Compare Cmp) {
  716. Use *Merged;
  717. Use **Next = &Merged;
  718. while (true) {
  719. if (!L) {
  720. *Next = R;
  721. break;
  722. }
  723. if (!R) {
  724. *Next = L;
  725. break;
  726. }
  727. if (Cmp(*R, *L)) {
  728. *Next = R;
  729. Next = &R->Next;
  730. R = R->Next;
  731. } else {
  732. *Next = L;
  733. Next = &L->Next;
  734. L = L->Next;
  735. }
  736. }
  737. return Merged;
  738. }
  739. protected:
  740. unsigned short getSubclassDataFromValue() const { return SubclassData; }
  741. void setValueSubclassData(unsigned short D) { SubclassData = D; }
  742. };
  743. struct ValueDeleter { void operator()(Value *V) { V->deleteValue(); } };
  744. /// Use this instead of std::unique_ptr<Value> or std::unique_ptr<Instruction>.
  745. /// Those don't work because Value and Instruction's destructors are protected,
  746. /// aren't virtual, and won't destroy the complete object.
  747. using unique_value = std::unique_ptr<Value, ValueDeleter>;
  748. inline raw_ostream &operator<<(raw_ostream &OS, const Value &V) {
  749. V.print(OS);
  750. return OS;
  751. }
  752. void Use::set(Value *V) {
  753. if (Val) removeFromList();
  754. Val = V;
  755. if (V) V->addUse(*this);
  756. }
  757. Value *Use::operator=(Value *RHS) {
  758. set(RHS);
  759. return RHS;
  760. }
  761. const Use &Use::operator=(const Use &RHS) {
  762. set(RHS.Val);
  763. return *this;
  764. }
  765. template <class Compare> void Value::sortUseList(Compare Cmp) {
  766. if (!UseList || !UseList->Next)
  767. // No need to sort 0 or 1 uses.
  768. return;
  769. // Note: this function completely ignores Prev pointers until the end when
  770. // they're fixed en masse.
  771. // Create a binomial vector of sorted lists, visiting uses one at a time and
  772. // merging lists as necessary.
  773. const unsigned MaxSlots = 32;
  774. Use *Slots[MaxSlots];
  775. // Collect the first use, turning it into a single-item list.
  776. Use *Next = UseList->Next;
  777. UseList->Next = nullptr;
  778. unsigned NumSlots = 1;
  779. Slots[0] = UseList;
  780. // Collect all but the last use.
  781. while (Next->Next) {
  782. Use *Current = Next;
  783. Next = Current->Next;
  784. // Turn Current into a single-item list.
  785. Current->Next = nullptr;
  786. // Save Current in the first available slot, merging on collisions.
  787. unsigned I;
  788. for (I = 0; I < NumSlots; ++I) {
  789. if (!Slots[I])
  790. break;
  791. // Merge two lists, doubling the size of Current and emptying slot I.
  792. //
  793. // Since the uses in Slots[I] originally preceded those in Current, send
  794. // Slots[I] in as the left parameter to maintain a stable sort.
  795. Current = mergeUseLists(Slots[I], Current, Cmp);
  796. Slots[I] = nullptr;
  797. }
  798. // Check if this is a new slot.
  799. if (I == NumSlots) {
  800. ++NumSlots;
  801. assert(NumSlots <= MaxSlots && "Use list bigger than 2^32");
  802. }
  803. // Found an open slot.
  804. Slots[I] = Current;
  805. }
  806. // Merge all the lists together.
  807. assert(Next && "Expected one more Use");
  808. assert(!Next->Next && "Expected only one Use");
  809. UseList = Next;
  810. for (unsigned I = 0; I < NumSlots; ++I)
  811. if (Slots[I])
  812. // Since the uses in Slots[I] originally preceded those in UseList, send
  813. // Slots[I] in as the left parameter to maintain a stable sort.
  814. UseList = mergeUseLists(Slots[I], UseList, Cmp);
  815. // Fix the Prev pointers.
  816. for (Use *I = UseList, **Prev = &UseList; I; I = I->Next) {
  817. I->Prev = Prev;
  818. Prev = &I->Next;
  819. }
  820. }
  821. // isa - Provide some specializations of isa so that we don't have to include
  822. // the subtype header files to test to see if the value is a subclass...
  823. //
  824. template <> struct isa_impl<Constant, Value> {
  825. static inline bool doit(const Value &Val) {
  826. static_assert(Value::ConstantFirstVal == 0, "Val.getValueID() >= Value::ConstantFirstVal");
  827. return Val.getValueID() <= Value::ConstantLastVal;
  828. }
  829. };
  830. template <> struct isa_impl<ConstantData, Value> {
  831. static inline bool doit(const Value &Val) {
  832. return Val.getValueID() >= Value::ConstantDataFirstVal &&
  833. Val.getValueID() <= Value::ConstantDataLastVal;
  834. }
  835. };
  836. template <> struct isa_impl<ConstantAggregate, Value> {
  837. static inline bool doit(const Value &Val) {
  838. return Val.getValueID() >= Value::ConstantAggregateFirstVal &&
  839. Val.getValueID() <= Value::ConstantAggregateLastVal;
  840. }
  841. };
  842. template <> struct isa_impl<Argument, Value> {
  843. static inline bool doit (const Value &Val) {
  844. return Val.getValueID() == Value::ArgumentVal;
  845. }
  846. };
  847. template <> struct isa_impl<InlineAsm, Value> {
  848. static inline bool doit(const Value &Val) {
  849. return Val.getValueID() == Value::InlineAsmVal;
  850. }
  851. };
  852. template <> struct isa_impl<Instruction, Value> {
  853. static inline bool doit(const Value &Val) {
  854. return Val.getValueID() >= Value::InstructionVal;
  855. }
  856. };
  857. template <> struct isa_impl<BasicBlock, Value> {
  858. static inline bool doit(const Value &Val) {
  859. return Val.getValueID() == Value::BasicBlockVal;
  860. }
  861. };
  862. template <> struct isa_impl<Function, Value> {
  863. static inline bool doit(const Value &Val) {
  864. return Val.getValueID() == Value::FunctionVal;
  865. }
  866. };
  867. template <> struct isa_impl<GlobalVariable, Value> {
  868. static inline bool doit(const Value &Val) {
  869. return Val.getValueID() == Value::GlobalVariableVal;
  870. }
  871. };
  872. template <> struct isa_impl<GlobalAlias, Value> {
  873. static inline bool doit(const Value &Val) {
  874. return Val.getValueID() == Value::GlobalAliasVal;
  875. }
  876. };
  877. template <> struct isa_impl<GlobalIFunc, Value> {
  878. static inline bool doit(const Value &Val) {
  879. return Val.getValueID() == Value::GlobalIFuncVal;
  880. }
  881. };
  882. template <> struct isa_impl<GlobalValue, Value> {
  883. static inline bool doit(const Value &Val) {
  884. return isa<GlobalObject>(Val) || isa<GlobalAlias>(Val);
  885. }
  886. };
  887. template <> struct isa_impl<GlobalObject, Value> {
  888. static inline bool doit(const Value &Val) {
  889. return isa<GlobalVariable>(Val) || isa<Function>(Val) ||
  890. isa<GlobalIFunc>(Val);
  891. }
  892. };
  893. // Create wrappers for C Binding types (see CBindingWrapping.h).
  894. DEFINE_ISA_CONVERSION_FUNCTIONS(Value, LLVMValueRef)
  895. // Specialized opaque value conversions.
  896. inline Value **unwrap(LLVMValueRef *Vals) {
  897. return reinterpret_cast<Value**>(Vals);
  898. }
  899. template<typename T>
  900. inline T **unwrap(LLVMValueRef *Vals, unsigned Length) {
  901. #ifndef NDEBUG
  902. for (LLVMValueRef *I = Vals, *E = Vals + Length; I != E; ++I)
  903. unwrap<T>(*I); // For side effect of calling assert on invalid usage.
  904. #endif
  905. (void)Length;
  906. return reinterpret_cast<T**>(Vals);
  907. }
  908. inline LLVMValueRef *wrap(const Value **Vals) {
  909. return reinterpret_cast<LLVMValueRef*>(const_cast<Value**>(Vals));
  910. }
  911. } // end namespace llvm
  912. #endif // LLVM_IR_VALUE_H
  913. #ifdef __GNUC__
  914. #pragma GCC diagnostic pop
  915. #endif