Value.h 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071
  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. // Return true if this value is only transitively referenced by metadata.
  480. bool isTransitiveUsedByMetadataOnly() const;
  481. protected:
  482. /// Get the current metadata attachments for the given kind, if any.
  483. ///
  484. /// These functions require that the value have at most a single attachment
  485. /// of the given kind, and return \c nullptr if such an attachment is missing.
  486. /// @{
  487. MDNode *getMetadata(unsigned KindID) const;
  488. MDNode *getMetadata(StringRef Kind) const;
  489. /// @}
  490. /// Appends all attachments with the given ID to \c MDs in insertion order.
  491. /// If the Value has no attachments with the given ID, or if ID is invalid,
  492. /// leaves MDs unchanged.
  493. /// @{
  494. void getMetadata(unsigned KindID, SmallVectorImpl<MDNode *> &MDs) const;
  495. void getMetadata(StringRef Kind, SmallVectorImpl<MDNode *> &MDs) const;
  496. /// @}
  497. /// Appends all metadata attached to this value to \c MDs, sorting by
  498. /// KindID. The first element of each pair returned is the KindID, the second
  499. /// element is the metadata value. Attachments with the same ID appear in
  500. /// insertion order.
  501. void
  502. getAllMetadata(SmallVectorImpl<std::pair<unsigned, MDNode *>> &MDs) const;
  503. /// Return true if this value has any metadata attached to it.
  504. bool hasMetadata() const { return (bool)HasMetadata; }
  505. /// Return true if this value has the given type of metadata attached.
  506. /// @{
  507. bool hasMetadata(unsigned KindID) const {
  508. return getMetadata(KindID) != nullptr;
  509. }
  510. bool hasMetadata(StringRef Kind) const {
  511. return getMetadata(Kind) != nullptr;
  512. }
  513. /// @}
  514. /// Set a particular kind of metadata attachment.
  515. ///
  516. /// Sets the given attachment to \c MD, erasing it if \c MD is \c nullptr or
  517. /// replacing it if it already exists.
  518. /// @{
  519. void setMetadata(unsigned KindID, MDNode *Node);
  520. void setMetadata(StringRef Kind, MDNode *Node);
  521. /// @}
  522. /// Add a metadata attachment.
  523. /// @{
  524. void addMetadata(unsigned KindID, MDNode &MD);
  525. void addMetadata(StringRef Kind, MDNode &MD);
  526. /// @}
  527. /// Erase all metadata attachments with the given kind.
  528. ///
  529. /// \returns true if any metadata was removed.
  530. bool eraseMetadata(unsigned KindID);
  531. /// Erase all metadata attached to this Value.
  532. void clearMetadata();
  533. public:
  534. /// Return true if this value is a swifterror value.
  535. ///
  536. /// swifterror values can be either a function argument or an alloca with a
  537. /// swifterror attribute.
  538. bool isSwiftError() const;
  539. /// Strip off pointer casts, all-zero GEPs and address space casts.
  540. ///
  541. /// Returns the original uncasted value. If this is called on a non-pointer
  542. /// value, it returns 'this'.
  543. const Value *stripPointerCasts() const;
  544. Value *stripPointerCasts() {
  545. return const_cast<Value *>(
  546. static_cast<const Value *>(this)->stripPointerCasts());
  547. }
  548. /// Strip off pointer casts, all-zero GEPs, address space casts, and aliases.
  549. ///
  550. /// Returns the original uncasted value. If this is called on a non-pointer
  551. /// value, it returns 'this'.
  552. const Value *stripPointerCastsAndAliases() const;
  553. Value *stripPointerCastsAndAliases() {
  554. return const_cast<Value *>(
  555. static_cast<const Value *>(this)->stripPointerCastsAndAliases());
  556. }
  557. /// Strip off pointer casts, all-zero GEPs and address space casts
  558. /// but ensures the representation of the result stays the same.
  559. ///
  560. /// Returns the original uncasted value with the same representation. If this
  561. /// is called on a non-pointer value, it returns 'this'.
  562. const Value *stripPointerCastsSameRepresentation() const;
  563. Value *stripPointerCastsSameRepresentation() {
  564. return const_cast<Value *>(static_cast<const Value *>(this)
  565. ->stripPointerCastsSameRepresentation());
  566. }
  567. /// Strip off pointer casts, all-zero GEPs, single-argument phi nodes and
  568. /// invariant group info.
  569. ///
  570. /// Returns the original uncasted value. If this is called on a non-pointer
  571. /// value, it returns 'this'. This function should be used only in
  572. /// Alias analysis.
  573. const Value *stripPointerCastsForAliasAnalysis() const;
  574. Value *stripPointerCastsForAliasAnalysis() {
  575. return const_cast<Value *>(static_cast<const Value *>(this)
  576. ->stripPointerCastsForAliasAnalysis());
  577. }
  578. /// Strip off pointer casts and all-constant inbounds GEPs.
  579. ///
  580. /// Returns the original pointer value. If this is called on a non-pointer
  581. /// value, it returns 'this'.
  582. const Value *stripInBoundsConstantOffsets() const;
  583. Value *stripInBoundsConstantOffsets() {
  584. return const_cast<Value *>(
  585. static_cast<const Value *>(this)->stripInBoundsConstantOffsets());
  586. }
  587. /// Accumulate the constant offset this value has compared to a base pointer.
  588. /// Only 'getelementptr' instructions (GEPs) are accumulated but other
  589. /// instructions, e.g., casts, are stripped away as well.
  590. /// The accumulated constant offset is added to \p Offset and the base
  591. /// pointer is returned.
  592. ///
  593. /// The APInt \p Offset has to have a bit-width equal to the IntPtr type for
  594. /// the address space of 'this' pointer value, e.g., use
  595. /// DataLayout::getIndexTypeSizeInBits(Ty).
  596. ///
  597. /// If \p AllowNonInbounds is true, offsets in GEPs are stripped and
  598. /// accumulated even if the GEP is not "inbounds".
  599. ///
  600. /// If \p AllowInvariantGroup is true then this method also looks through
  601. /// strip.invariant.group and launder.invariant.group intrinsics.
  602. ///
  603. /// If \p ExternalAnalysis is provided it will be used to calculate a offset
  604. /// when a operand of GEP is not constant.
  605. /// For example, for a value \p ExternalAnalysis might try to calculate a
  606. /// lower bound. If \p ExternalAnalysis is successful, it should return true.
  607. ///
  608. /// If this is called on a non-pointer value, it returns 'this' and the
  609. /// \p Offset is not modified.
  610. ///
  611. /// Note that this function will never return a nullptr. It will also never
  612. /// manipulate the \p Offset in a way that would not match the difference
  613. /// between the underlying value and the returned one. Thus, if no constant
  614. /// offset was found, the returned value is the underlying one and \p Offset
  615. /// is unchanged.
  616. const Value *stripAndAccumulateConstantOffsets(
  617. const DataLayout &DL, APInt &Offset, bool AllowNonInbounds,
  618. bool AllowInvariantGroup = false,
  619. function_ref<bool(Value &Value, APInt &Offset)> ExternalAnalysis =
  620. nullptr) const;
  621. Value *stripAndAccumulateConstantOffsets(const DataLayout &DL, APInt &Offset,
  622. bool AllowNonInbounds,
  623. bool AllowInvariantGroup = false) {
  624. return const_cast<Value *>(
  625. static_cast<const Value *>(this)->stripAndAccumulateConstantOffsets(
  626. DL, Offset, AllowNonInbounds, AllowInvariantGroup));
  627. }
  628. /// This is a wrapper around stripAndAccumulateConstantOffsets with the
  629. /// in-bounds requirement set to false.
  630. const Value *stripAndAccumulateInBoundsConstantOffsets(const DataLayout &DL,
  631. APInt &Offset) const {
  632. return stripAndAccumulateConstantOffsets(DL, Offset,
  633. /* AllowNonInbounds */ false);
  634. }
  635. Value *stripAndAccumulateInBoundsConstantOffsets(const DataLayout &DL,
  636. APInt &Offset) {
  637. return stripAndAccumulateConstantOffsets(DL, Offset,
  638. /* AllowNonInbounds */ false);
  639. }
  640. /// Strip off pointer casts and inbounds GEPs.
  641. ///
  642. /// Returns the original pointer value. If this is called on a non-pointer
  643. /// value, it returns 'this'.
  644. const Value *stripInBoundsOffsets(function_ref<void(const Value *)> Func =
  645. [](const Value *) {}) const;
  646. inline Value *stripInBoundsOffsets(function_ref<void(const Value *)> Func =
  647. [](const Value *) {}) {
  648. return const_cast<Value *>(
  649. static_cast<const Value *>(this)->stripInBoundsOffsets(Func));
  650. }
  651. /// Return true if the memory object referred to by V can by freed in the
  652. /// scope for which the SSA value defining the allocation is statically
  653. /// defined. E.g. deallocation after the static scope of a value does not
  654. /// count, but a deallocation before that does.
  655. bool canBeFreed() const;
  656. /// Returns the number of bytes known to be dereferenceable for the
  657. /// pointer value.
  658. ///
  659. /// If CanBeNull is set by this function the pointer can either be null or be
  660. /// dereferenceable up to the returned number of bytes.
  661. ///
  662. /// IF CanBeFreed is true, the pointer is known to be dereferenceable at
  663. /// point of definition only. Caller must prove that allocation is not
  664. /// deallocated between point of definition and use.
  665. uint64_t getPointerDereferenceableBytes(const DataLayout &DL,
  666. bool &CanBeNull,
  667. bool &CanBeFreed) const;
  668. /// Returns an alignment of the pointer value.
  669. ///
  670. /// Returns an alignment which is either specified explicitly, e.g. via
  671. /// align attribute of a function argument, or guaranteed by DataLayout.
  672. Align getPointerAlignment(const DataLayout &DL) const;
  673. /// Translate PHI node to its predecessor from the given basic block.
  674. ///
  675. /// If this value is a PHI node with CurBB as its parent, return the value in
  676. /// the PHI node corresponding to PredBB. If not, return ourself. This is
  677. /// useful if you want to know the value something has in a predecessor
  678. /// block.
  679. const Value *DoPHITranslation(const BasicBlock *CurBB,
  680. const BasicBlock *PredBB) const;
  681. Value *DoPHITranslation(const BasicBlock *CurBB, const BasicBlock *PredBB) {
  682. return const_cast<Value *>(
  683. static_cast<const Value *>(this)->DoPHITranslation(CurBB, PredBB));
  684. }
  685. /// The maximum alignment for instructions.
  686. ///
  687. /// This is the greatest alignment value supported by load, store, and alloca
  688. /// instructions, and global values.
  689. static constexpr unsigned MaxAlignmentExponent = 32;
  690. static constexpr uint64_t MaximumAlignment = 1ULL << MaxAlignmentExponent;
  691. /// Mutate the type of this Value to be of the specified type.
  692. ///
  693. /// Note that this is an extremely dangerous operation which can create
  694. /// completely invalid IR very easily. It is strongly recommended that you
  695. /// recreate IR objects with the right types instead of mutating them in
  696. /// place.
  697. void mutateType(Type *Ty) {
  698. VTy = Ty;
  699. }
  700. /// Sort the use-list.
  701. ///
  702. /// Sorts the Value's use-list by Cmp using a stable mergesort. Cmp is
  703. /// expected to compare two \a Use references.
  704. template <class Compare> void sortUseList(Compare Cmp);
  705. /// Reverse the use-list.
  706. void reverseUseList();
  707. private:
  708. /// Merge two lists together.
  709. ///
  710. /// Merges \c L and \c R using \c Cmp. To enable stable sorts, always pushes
  711. /// "equal" items from L before items from R.
  712. ///
  713. /// \return the first element in the list.
  714. ///
  715. /// \note Completely ignores \a Use::Prev (doesn't read, doesn't update).
  716. template <class Compare>
  717. static Use *mergeUseLists(Use *L, Use *R, Compare Cmp) {
  718. Use *Merged;
  719. Use **Next = &Merged;
  720. while (true) {
  721. if (!L) {
  722. *Next = R;
  723. break;
  724. }
  725. if (!R) {
  726. *Next = L;
  727. break;
  728. }
  729. if (Cmp(*R, *L)) {
  730. *Next = R;
  731. Next = &R->Next;
  732. R = R->Next;
  733. } else {
  734. *Next = L;
  735. Next = &L->Next;
  736. L = L->Next;
  737. }
  738. }
  739. return Merged;
  740. }
  741. protected:
  742. unsigned short getSubclassDataFromValue() const { return SubclassData; }
  743. void setValueSubclassData(unsigned short D) { SubclassData = D; }
  744. };
  745. struct ValueDeleter { void operator()(Value *V) { V->deleteValue(); } };
  746. /// Use this instead of std::unique_ptr<Value> or std::unique_ptr<Instruction>.
  747. /// Those don't work because Value and Instruction's destructors are protected,
  748. /// aren't virtual, and won't destroy the complete object.
  749. using unique_value = std::unique_ptr<Value, ValueDeleter>;
  750. inline raw_ostream &operator<<(raw_ostream &OS, const Value &V) {
  751. V.print(OS);
  752. return OS;
  753. }
  754. void Use::set(Value *V) {
  755. if (Val) removeFromList();
  756. Val = V;
  757. if (V) V->addUse(*this);
  758. }
  759. Value *Use::operator=(Value *RHS) {
  760. set(RHS);
  761. return RHS;
  762. }
  763. const Use &Use::operator=(const Use &RHS) {
  764. set(RHS.Val);
  765. return *this;
  766. }
  767. template <class Compare> void Value::sortUseList(Compare Cmp) {
  768. if (!UseList || !UseList->Next)
  769. // No need to sort 0 or 1 uses.
  770. return;
  771. // Note: this function completely ignores Prev pointers until the end when
  772. // they're fixed en masse.
  773. // Create a binomial vector of sorted lists, visiting uses one at a time and
  774. // merging lists as necessary.
  775. const unsigned MaxSlots = 32;
  776. Use *Slots[MaxSlots];
  777. // Collect the first use, turning it into a single-item list.
  778. Use *Next = UseList->Next;
  779. UseList->Next = nullptr;
  780. unsigned NumSlots = 1;
  781. Slots[0] = UseList;
  782. // Collect all but the last use.
  783. while (Next->Next) {
  784. Use *Current = Next;
  785. Next = Current->Next;
  786. // Turn Current into a single-item list.
  787. Current->Next = nullptr;
  788. // Save Current in the first available slot, merging on collisions.
  789. unsigned I;
  790. for (I = 0; I < NumSlots; ++I) {
  791. if (!Slots[I])
  792. break;
  793. // Merge two lists, doubling the size of Current and emptying slot I.
  794. //
  795. // Since the uses in Slots[I] originally preceded those in Current, send
  796. // Slots[I] in as the left parameter to maintain a stable sort.
  797. Current = mergeUseLists(Slots[I], Current, Cmp);
  798. Slots[I] = nullptr;
  799. }
  800. // Check if this is a new slot.
  801. if (I == NumSlots) {
  802. ++NumSlots;
  803. assert(NumSlots <= MaxSlots && "Use list bigger than 2^32");
  804. }
  805. // Found an open slot.
  806. Slots[I] = Current;
  807. }
  808. // Merge all the lists together.
  809. assert(Next && "Expected one more Use");
  810. assert(!Next->Next && "Expected only one Use");
  811. UseList = Next;
  812. for (unsigned I = 0; I < NumSlots; ++I)
  813. if (Slots[I])
  814. // Since the uses in Slots[I] originally preceded those in UseList, send
  815. // Slots[I] in as the left parameter to maintain a stable sort.
  816. UseList = mergeUseLists(Slots[I], UseList, Cmp);
  817. // Fix the Prev pointers.
  818. for (Use *I = UseList, **Prev = &UseList; I; I = I->Next) {
  819. I->Prev = Prev;
  820. Prev = &I->Next;
  821. }
  822. }
  823. // isa - Provide some specializations of isa so that we don't have to include
  824. // the subtype header files to test to see if the value is a subclass...
  825. //
  826. template <> struct isa_impl<Constant, Value> {
  827. static inline bool doit(const Value &Val) {
  828. static_assert(Value::ConstantFirstVal == 0, "Val.getValueID() >= Value::ConstantFirstVal");
  829. return Val.getValueID() <= Value::ConstantLastVal;
  830. }
  831. };
  832. template <> struct isa_impl<ConstantData, Value> {
  833. static inline bool doit(const Value &Val) {
  834. return Val.getValueID() >= Value::ConstantDataFirstVal &&
  835. Val.getValueID() <= Value::ConstantDataLastVal;
  836. }
  837. };
  838. template <> struct isa_impl<ConstantAggregate, Value> {
  839. static inline bool doit(const Value &Val) {
  840. return Val.getValueID() >= Value::ConstantAggregateFirstVal &&
  841. Val.getValueID() <= Value::ConstantAggregateLastVal;
  842. }
  843. };
  844. template <> struct isa_impl<Argument, Value> {
  845. static inline bool doit (const Value &Val) {
  846. return Val.getValueID() == Value::ArgumentVal;
  847. }
  848. };
  849. template <> struct isa_impl<InlineAsm, Value> {
  850. static inline bool doit(const Value &Val) {
  851. return Val.getValueID() == Value::InlineAsmVal;
  852. }
  853. };
  854. template <> struct isa_impl<Instruction, Value> {
  855. static inline bool doit(const Value &Val) {
  856. return Val.getValueID() >= Value::InstructionVal;
  857. }
  858. };
  859. template <> struct isa_impl<BasicBlock, Value> {
  860. static inline bool doit(const Value &Val) {
  861. return Val.getValueID() == Value::BasicBlockVal;
  862. }
  863. };
  864. template <> struct isa_impl<Function, Value> {
  865. static inline bool doit(const Value &Val) {
  866. return Val.getValueID() == Value::FunctionVal;
  867. }
  868. };
  869. template <> struct isa_impl<GlobalVariable, Value> {
  870. static inline bool doit(const Value &Val) {
  871. return Val.getValueID() == Value::GlobalVariableVal;
  872. }
  873. };
  874. template <> struct isa_impl<GlobalAlias, Value> {
  875. static inline bool doit(const Value &Val) {
  876. return Val.getValueID() == Value::GlobalAliasVal;
  877. }
  878. };
  879. template <> struct isa_impl<GlobalIFunc, Value> {
  880. static inline bool doit(const Value &Val) {
  881. return Val.getValueID() == Value::GlobalIFuncVal;
  882. }
  883. };
  884. template <> struct isa_impl<GlobalValue, Value> {
  885. static inline bool doit(const Value &Val) {
  886. return isa<GlobalObject>(Val) || isa<GlobalAlias>(Val);
  887. }
  888. };
  889. template <> struct isa_impl<GlobalObject, Value> {
  890. static inline bool doit(const Value &Val) {
  891. return isa<GlobalVariable>(Val) || isa<Function>(Val) ||
  892. isa<GlobalIFunc>(Val);
  893. }
  894. };
  895. // Create wrappers for C Binding types (see CBindingWrapping.h).
  896. DEFINE_ISA_CONVERSION_FUNCTIONS(Value, LLVMValueRef)
  897. // Specialized opaque value conversions.
  898. inline Value **unwrap(LLVMValueRef *Vals) {
  899. return reinterpret_cast<Value**>(Vals);
  900. }
  901. template<typename T>
  902. inline T **unwrap(LLVMValueRef *Vals, unsigned Length) {
  903. #ifndef NDEBUG
  904. for (LLVMValueRef *I = Vals, *E = Vals + Length; I != E; ++I)
  905. unwrap<T>(*I); // For side effect of calling assert on invalid usage.
  906. #endif
  907. (void)Length;
  908. return reinterpret_cast<T**>(Vals);
  909. }
  910. inline LLVMValueRef *wrap(const Value **Vals) {
  911. return reinterpret_cast<LLVMValueRef*>(const_cast<Value**>(Vals));
  912. }
  913. } // end namespace llvm
  914. #endif // LLVM_IR_VALUE_H
  915. #ifdef __GNUC__
  916. #pragma GCC diagnostic pop
  917. #endif