Value.h 36 KB

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