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