Value.h 35 KB

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