1 //===-- llvm/GlobalValue.h - Class to represent a global value --*- C++ -*-===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file is a common base class of all globally definable objects. As such, 11 // it is subclassed by GlobalVariable, GlobalAlias and by Function. This is 12 // used because you can do certain things with these global objects that you 13 // can't do to anything else. For example, use the address of one as a 14 // constant. 15 // 16 //===----------------------------------------------------------------------===// 17 18 #ifndef LLVM_IR_GLOBALVALUE_H 19 #define LLVM_IR_GLOBALVALUE_H 20 21 #include "llvm/ADT/StringRef.h" 22 #include "llvm/ADT/Twine.h" 23 #include "llvm/IR/Constant.h" 24 #include "llvm/IR/DerivedTypes.h" 25 #include "llvm/IR/Value.h" 26 #include "llvm/Support/MD5.h" 27 #include "llvm/Support/Casting.h" 28 #include "llvm/Support/ErrorHandling.h" 29 #include <cassert> 30 #include <cstdint> 31 #include <string> 32 33 namespace llvm { 34 35 class Comdat; 36 class ConstantRange; 37 class Error; 38 class GlobalObject; 39 class Module; 40 41 namespace Intrinsic { 42 enum ID : unsigned; 43 } // end namespace Intrinsic 44 45 class GlobalValue : public Constant { 46 public: 47 /// @brief An enumeration for the kinds of linkage for global values. 48 enum LinkageTypes { 49 ExternalLinkage = 0,///< Externally visible function 50 AvailableExternallyLinkage, ///< Available for inspection, not emission. 51 LinkOnceAnyLinkage, ///< Keep one copy of function when linking (inline) 52 LinkOnceODRLinkage, ///< Same, but only replaced by something equivalent. 53 WeakAnyLinkage, ///< Keep one copy of named function when linking (weak) 54 WeakODRLinkage, ///< Same, but only replaced by something equivalent. 55 AppendingLinkage, ///< Special purpose, only applies to global arrays 56 InternalLinkage, ///< Rename collisions when linking (static functions). 57 PrivateLinkage, ///< Like Internal, but omit from symbol table. 58 ExternalWeakLinkage,///< ExternalWeak linkage description. 59 CommonLinkage ///< Tentative definitions. 60 }; 61 62 /// @brief An enumeration for the kinds of visibility of global values. 63 enum VisibilityTypes { 64 DefaultVisibility = 0, ///< The GV is visible 65 HiddenVisibility, ///< The GV is hidden 66 ProtectedVisibility ///< The GV is protected 67 }; 68 69 /// @brief Storage classes of global values for PE targets. 70 enum DLLStorageClassTypes { 71 DefaultStorageClass = 0, 72 DLLImportStorageClass = 1, ///< Function to be imported from DLL 73 DLLExportStorageClass = 2 ///< Function to be accessible from DLL. 74 }; 75 76 protected: GlobalValue(Type * Ty,ValueTy VTy,Use * Ops,unsigned NumOps,LinkageTypes Linkage,const Twine & Name,unsigned AddressSpace)77 GlobalValue(Type *Ty, ValueTy VTy, Use *Ops, unsigned NumOps, 78 LinkageTypes Linkage, const Twine &Name, unsigned AddressSpace) 79 : Constant(PointerType::get(Ty, AddressSpace), VTy, Ops, NumOps), 80 ValueType(Ty), Linkage(Linkage), Visibility(DefaultVisibility), 81 UnnamedAddrVal(unsigned(UnnamedAddr::None)), 82 DllStorageClass(DefaultStorageClass), ThreadLocal(NotThreadLocal), 83 IntID((Intrinsic::ID)0U), Parent(nullptr) { 84 setName(Name); 85 } 86 87 Type *ValueType; 88 // All bitfields use unsigned as the underlying type so that MSVC will pack 89 // them. 90 unsigned Linkage : 4; // The linkage of this global 91 unsigned Visibility : 2; // The visibility style of this global 92 unsigned UnnamedAddrVal : 2; // This value's address is not significant 93 unsigned DllStorageClass : 2; // DLL storage class 94 95 unsigned ThreadLocal : 3; // Is this symbol "Thread Local", if so, what is 96 // the desired model? 97 static const unsigned GlobalValueSubClassDataBits = 19; 98 99 private: 100 friend class Constant; 101 102 // Give subclasses access to what otherwise would be wasted padding. 103 // (19 + 4 + 2 + 2 + 2 + 3) == 32. 104 unsigned SubClassData : GlobalValueSubClassDataBits; 105 106 void destroyConstantImpl(); 107 Value *handleOperandChangeImpl(Value *From, Value *To); 108 109 /// Returns true if the definition of this global may be replaced by a 110 /// differently optimized variant of the same source level function at link 111 /// time. mayBeDerefined()112 bool mayBeDerefined() const { 113 switch (getLinkage()) { 114 case WeakODRLinkage: 115 case LinkOnceODRLinkage: 116 case AvailableExternallyLinkage: 117 return true; 118 119 case WeakAnyLinkage: 120 case LinkOnceAnyLinkage: 121 case CommonLinkage: 122 case ExternalWeakLinkage: 123 case ExternalLinkage: 124 case AppendingLinkage: 125 case InternalLinkage: 126 case PrivateLinkage: 127 return isInterposable(); 128 } 129 130 llvm_unreachable("Fully covered switch above!"); 131 } 132 133 protected: 134 /// \brief The intrinsic ID for this subclass (which must be a Function). 135 /// 136 /// This member is defined by this class, but not used for anything. 137 /// Subclasses can use it to store their intrinsic ID, if they have one. 138 /// 139 /// This is stored here to save space in Function on 64-bit hosts. 140 Intrinsic::ID IntID; 141 getGlobalValueSubClassData()142 unsigned getGlobalValueSubClassData() const { 143 return SubClassData; 144 } setGlobalValueSubClassData(unsigned V)145 void setGlobalValueSubClassData(unsigned V) { 146 assert(V < (1 << GlobalValueSubClassDataBits) && "It will not fit"); 147 SubClassData = V; 148 } 149 150 Module *Parent; // The containing module. 151 152 // Used by SymbolTableListTraits. setParent(Module * parent)153 void setParent(Module *parent) { 154 Parent = parent; 155 } 156 157 public: 158 enum ThreadLocalMode { 159 NotThreadLocal = 0, 160 GeneralDynamicTLSModel, 161 LocalDynamicTLSModel, 162 InitialExecTLSModel, 163 LocalExecTLSModel 164 }; 165 166 GlobalValue(const GlobalValue &) = delete; 167 ~GlobalValue()168 ~GlobalValue() override { 169 removeDeadConstantUsers(); // remove any dead constants using this. 170 } 171 172 unsigned getAlignment() const; 173 174 enum class UnnamedAddr { 175 None, 176 Local, 177 Global, 178 }; 179 hasGlobalUnnamedAddr()180 bool hasGlobalUnnamedAddr() const { 181 return getUnnamedAddr() == UnnamedAddr::Global; 182 } 183 184 /// Returns true if this value's address is not significant in this module. 185 /// This attribute is intended to be used only by the code generator and LTO 186 /// to allow the linker to decide whether the global needs to be in the symbol 187 /// table. It should probably not be used in optimizations, as the value may 188 /// have uses outside the module; use hasGlobalUnnamedAddr() instead. hasAtLeastLocalUnnamedAddr()189 bool hasAtLeastLocalUnnamedAddr() const { 190 return getUnnamedAddr() != UnnamedAddr::None; 191 } 192 getUnnamedAddr()193 UnnamedAddr getUnnamedAddr() const { 194 return UnnamedAddr(UnnamedAddrVal); 195 } setUnnamedAddr(UnnamedAddr Val)196 void setUnnamedAddr(UnnamedAddr Val) { UnnamedAddrVal = unsigned(Val); } 197 getMinUnnamedAddr(UnnamedAddr A,UnnamedAddr B)198 static UnnamedAddr getMinUnnamedAddr(UnnamedAddr A, UnnamedAddr B) { 199 if (A == UnnamedAddr::None || B == UnnamedAddr::None) 200 return UnnamedAddr::None; 201 if (A == UnnamedAddr::Local || B == UnnamedAddr::Local) 202 return UnnamedAddr::Local; 203 return UnnamedAddr::Global; 204 } 205 hasComdat()206 bool hasComdat() const { return getComdat() != nullptr; } 207 Comdat *getComdat(); getComdat()208 const Comdat *getComdat() const { 209 return const_cast<GlobalValue *>(this)->getComdat(); 210 } 211 getVisibility()212 VisibilityTypes getVisibility() const { return VisibilityTypes(Visibility); } hasDefaultVisibility()213 bool hasDefaultVisibility() const { return Visibility == DefaultVisibility; } hasHiddenVisibility()214 bool hasHiddenVisibility() const { return Visibility == HiddenVisibility; } hasProtectedVisibility()215 bool hasProtectedVisibility() const { 216 return Visibility == ProtectedVisibility; 217 } setVisibility(VisibilityTypes V)218 void setVisibility(VisibilityTypes V) { 219 assert((!hasLocalLinkage() || V == DefaultVisibility) && 220 "local linkage requires default visibility"); 221 Visibility = V; 222 } 223 224 /// If the value is "Thread Local", its value isn't shared by the threads. isThreadLocal()225 bool isThreadLocal() const { return getThreadLocalMode() != NotThreadLocal; } setThreadLocal(bool Val)226 void setThreadLocal(bool Val) { 227 setThreadLocalMode(Val ? GeneralDynamicTLSModel : NotThreadLocal); 228 } setThreadLocalMode(ThreadLocalMode Val)229 void setThreadLocalMode(ThreadLocalMode Val) { 230 assert(Val == NotThreadLocal || getValueID() != Value::FunctionVal); 231 ThreadLocal = Val; 232 } getThreadLocalMode()233 ThreadLocalMode getThreadLocalMode() const { 234 return static_cast<ThreadLocalMode>(ThreadLocal); 235 } 236 getDLLStorageClass()237 DLLStorageClassTypes getDLLStorageClass() const { 238 return DLLStorageClassTypes(DllStorageClass); 239 } hasDLLImportStorageClass()240 bool hasDLLImportStorageClass() const { 241 return DllStorageClass == DLLImportStorageClass; 242 } hasDLLExportStorageClass()243 bool hasDLLExportStorageClass() const { 244 return DllStorageClass == DLLExportStorageClass; 245 } setDLLStorageClass(DLLStorageClassTypes C)246 void setDLLStorageClass(DLLStorageClassTypes C) { DllStorageClass = C; } 247 hasSection()248 bool hasSection() const { return !getSection().empty(); } 249 StringRef getSection() const; 250 251 /// Global values are always pointers. getType()252 PointerType *getType() const { return cast<PointerType>(User::getType()); } 253 getValueType()254 Type *getValueType() const { return ValueType; } 255 getLinkOnceLinkage(bool ODR)256 static LinkageTypes getLinkOnceLinkage(bool ODR) { 257 return ODR ? LinkOnceODRLinkage : LinkOnceAnyLinkage; 258 } getWeakLinkage(bool ODR)259 static LinkageTypes getWeakLinkage(bool ODR) { 260 return ODR ? WeakODRLinkage : WeakAnyLinkage; 261 } 262 isExternalLinkage(LinkageTypes Linkage)263 static bool isExternalLinkage(LinkageTypes Linkage) { 264 return Linkage == ExternalLinkage; 265 } isAvailableExternallyLinkage(LinkageTypes Linkage)266 static bool isAvailableExternallyLinkage(LinkageTypes Linkage) { 267 return Linkage == AvailableExternallyLinkage; 268 } isLinkOnceODRLinkage(LinkageTypes Linkage)269 static bool isLinkOnceODRLinkage(LinkageTypes Linkage) { 270 return Linkage == LinkOnceODRLinkage; 271 } isLinkOnceLinkage(LinkageTypes Linkage)272 static bool isLinkOnceLinkage(LinkageTypes Linkage) { 273 return Linkage == LinkOnceAnyLinkage || Linkage == LinkOnceODRLinkage; 274 } isWeakAnyLinkage(LinkageTypes Linkage)275 static bool isWeakAnyLinkage(LinkageTypes Linkage) { 276 return Linkage == WeakAnyLinkage; 277 } isWeakODRLinkage(LinkageTypes Linkage)278 static bool isWeakODRLinkage(LinkageTypes Linkage) { 279 return Linkage == WeakODRLinkage; 280 } isWeakLinkage(LinkageTypes Linkage)281 static bool isWeakLinkage(LinkageTypes Linkage) { 282 return isWeakAnyLinkage(Linkage) || isWeakODRLinkage(Linkage); 283 } isAppendingLinkage(LinkageTypes Linkage)284 static bool isAppendingLinkage(LinkageTypes Linkage) { 285 return Linkage == AppendingLinkage; 286 } isInternalLinkage(LinkageTypes Linkage)287 static bool isInternalLinkage(LinkageTypes Linkage) { 288 return Linkage == InternalLinkage; 289 } isPrivateLinkage(LinkageTypes Linkage)290 static bool isPrivateLinkage(LinkageTypes Linkage) { 291 return Linkage == PrivateLinkage; 292 } isLocalLinkage(LinkageTypes Linkage)293 static bool isLocalLinkage(LinkageTypes Linkage) { 294 return isInternalLinkage(Linkage) || isPrivateLinkage(Linkage); 295 } isExternalWeakLinkage(LinkageTypes Linkage)296 static bool isExternalWeakLinkage(LinkageTypes Linkage) { 297 return Linkage == ExternalWeakLinkage; 298 } isCommonLinkage(LinkageTypes Linkage)299 static bool isCommonLinkage(LinkageTypes Linkage) { 300 return Linkage == CommonLinkage; 301 } isValidDeclarationLinkage(LinkageTypes Linkage)302 static bool isValidDeclarationLinkage(LinkageTypes Linkage) { 303 return isExternalWeakLinkage(Linkage) || isExternalLinkage(Linkage); 304 } 305 306 /// Whether the definition of this global may be replaced by something 307 /// non-equivalent at link time. For example, if a function has weak linkage 308 /// then the code defining it may be replaced by different code. isInterposableLinkage(LinkageTypes Linkage)309 static bool isInterposableLinkage(LinkageTypes Linkage) { 310 switch (Linkage) { 311 case WeakAnyLinkage: 312 case LinkOnceAnyLinkage: 313 case CommonLinkage: 314 case ExternalWeakLinkage: 315 return true; 316 317 case AvailableExternallyLinkage: 318 case LinkOnceODRLinkage: 319 case WeakODRLinkage: 320 // The above three cannot be overridden but can be de-refined. 321 322 case ExternalLinkage: 323 case AppendingLinkage: 324 case InternalLinkage: 325 case PrivateLinkage: 326 return false; 327 } 328 llvm_unreachable("Fully covered switch above!"); 329 } 330 331 /// Whether the definition of this global may be discarded if it is not used 332 /// in its compilation unit. isDiscardableIfUnused(LinkageTypes Linkage)333 static bool isDiscardableIfUnused(LinkageTypes Linkage) { 334 return isLinkOnceLinkage(Linkage) || isLocalLinkage(Linkage) || 335 isAvailableExternallyLinkage(Linkage); 336 } 337 338 /// Whether the definition of this global may be replaced at link time. NB: 339 /// Using this method outside of the code generators is almost always a 340 /// mistake: when working at the IR level use isInterposable instead as it 341 /// knows about ODR semantics. isWeakForLinker(LinkageTypes Linkage)342 static bool isWeakForLinker(LinkageTypes Linkage) { 343 return Linkage == WeakAnyLinkage || Linkage == WeakODRLinkage || 344 Linkage == LinkOnceAnyLinkage || Linkage == LinkOnceODRLinkage || 345 Linkage == CommonLinkage || Linkage == ExternalWeakLinkage; 346 } 347 348 /// Return true if the currently visible definition of this global (if any) is 349 /// exactly the definition we will see at runtime. 350 /// 351 /// Non-exact linkage types inhibits most non-inlining IPO, since a 352 /// differently optimized variant of the same function can have different 353 /// observable or undefined behavior than in the variant currently visible. 354 /// For instance, we could have started with 355 /// 356 /// void foo(int *v) { 357 /// int t = 5 / v[0]; 358 /// (void) t; 359 /// } 360 /// 361 /// and "refined" it to 362 /// 363 /// void foo(int *v) { } 364 /// 365 /// However, we cannot infer readnone for `foo`, since that would justify 366 /// DSE'ing a store to `v[0]` across a call to `foo`, which can cause 367 /// undefined behavior if the linker replaces the actual call destination with 368 /// the unoptimized `foo`. 369 /// 370 /// Inlining is okay across non-exact linkage types as long as they're not 371 /// interposable (see \c isInterposable), since in such cases the currently 372 /// visible variant is *a* correct implementation of the original source 373 /// function; it just isn't the *only* correct implementation. isDefinitionExact()374 bool isDefinitionExact() const { 375 return !mayBeDerefined(); 376 } 377 378 /// Return true if this global has an exact defintion. hasExactDefinition()379 bool hasExactDefinition() const { 380 // While this computes exactly the same thing as 381 // isStrongDefinitionForLinker, the intended uses are different. This 382 // function is intended to help decide if specific inter-procedural 383 // transforms are correct, while isStrongDefinitionForLinker's intended use 384 // is in low level code generation. 385 return !isDeclaration() && isDefinitionExact(); 386 } 387 388 /// Return true if this global's definition can be substituted with an 389 /// *arbitrary* definition at link time. We cannot do any IPO or inlinining 390 /// across interposable call edges, since the callee can be replaced with 391 /// something arbitrary at link time. isInterposable()392 bool isInterposable() const { return isInterposableLinkage(getLinkage()); } 393 hasExternalLinkage()394 bool hasExternalLinkage() const { return isExternalLinkage(getLinkage()); } hasAvailableExternallyLinkage()395 bool hasAvailableExternallyLinkage() const { 396 return isAvailableExternallyLinkage(getLinkage()); 397 } hasLinkOnceLinkage()398 bool hasLinkOnceLinkage() const { return isLinkOnceLinkage(getLinkage()); } hasLinkOnceODRLinkage()399 bool hasLinkOnceODRLinkage() const { 400 return isLinkOnceODRLinkage(getLinkage()); 401 } hasWeakLinkage()402 bool hasWeakLinkage() const { return isWeakLinkage(getLinkage()); } hasWeakAnyLinkage()403 bool hasWeakAnyLinkage() const { return isWeakAnyLinkage(getLinkage()); } hasWeakODRLinkage()404 bool hasWeakODRLinkage() const { return isWeakODRLinkage(getLinkage()); } hasAppendingLinkage()405 bool hasAppendingLinkage() const { return isAppendingLinkage(getLinkage()); } hasInternalLinkage()406 bool hasInternalLinkage() const { return isInternalLinkage(getLinkage()); } hasPrivateLinkage()407 bool hasPrivateLinkage() const { return isPrivateLinkage(getLinkage()); } hasLocalLinkage()408 bool hasLocalLinkage() const { return isLocalLinkage(getLinkage()); } hasExternalWeakLinkage()409 bool hasExternalWeakLinkage() const { 410 return isExternalWeakLinkage(getLinkage()); 411 } hasCommonLinkage()412 bool hasCommonLinkage() const { return isCommonLinkage(getLinkage()); } hasValidDeclarationLinkage()413 bool hasValidDeclarationLinkage() const { 414 return isValidDeclarationLinkage(getLinkage()); 415 } 416 setLinkage(LinkageTypes LT)417 void setLinkage(LinkageTypes LT) { 418 if (isLocalLinkage(LT)) 419 Visibility = DefaultVisibility; 420 Linkage = LT; 421 } getLinkage()422 LinkageTypes getLinkage() const { return LinkageTypes(Linkage); } 423 isDiscardableIfUnused()424 bool isDiscardableIfUnused() const { 425 return isDiscardableIfUnused(getLinkage()); 426 } 427 isWeakForLinker()428 bool isWeakForLinker() const { return isWeakForLinker(getLinkage()); } 429 430 /// Copy all additional attributes (those not needed to create a GlobalValue) 431 /// from the GlobalValue Src to this one. 432 virtual void copyAttributesFrom(const GlobalValue *Src); 433 434 /// If special LLVM prefix that is used to inform the asm printer to not emit 435 /// usual symbol prefix before the symbol name is used then return linkage 436 /// name after skipping this special LLVM prefix. getRealLinkageName(StringRef Name)437 static StringRef getRealLinkageName(StringRef Name) { 438 if (!Name.empty() && Name[0] == '\1') 439 return Name.substr(1); 440 return Name; 441 } 442 443 /// Return the modified name for a global value suitable to be 444 /// used as the key for a global lookup (e.g. profile or ThinLTO). 445 /// The value's original name is \c Name and has linkage of type 446 /// \c Linkage. The value is defined in module \c FileName. 447 static std::string getGlobalIdentifier(StringRef Name, 448 GlobalValue::LinkageTypes Linkage, 449 StringRef FileName); 450 451 /// Return the modified name for this global value suitable to be 452 /// used as the key for a global lookup (e.g. profile or ThinLTO). 453 std::string getGlobalIdentifier() const; 454 455 /// Declare a type to represent a global unique identifier for a global value. 456 /// This is a 64 bits hash that is used by PGO and ThinLTO to have a compact 457 /// unique way to identify a symbol. 458 using GUID = uint64_t; 459 460 /// Return a 64-bit global unique ID constructed from global value name 461 /// (i.e. returned by getGlobalIdentifier()). getGUID(StringRef GlobalName)462 static GUID getGUID(StringRef GlobalName) { return MD5Hash(GlobalName); } 463 464 /// Return a 64-bit global unique ID constructed from global value name 465 /// (i.e. returned by getGlobalIdentifier()). getGUID()466 GUID getGUID() const { return getGUID(getGlobalIdentifier()); } 467 468 /// @name Materialization 469 /// Materialization is used to construct functions only as they're needed. 470 /// This 471 /// is useful to reduce memory usage in LLVM or parsing work done by the 472 /// BitcodeReader to load the Module. 473 /// @{ 474 475 /// If this function's Module is being lazily streamed in functions from disk 476 /// or some other source, this method can be used to check to see if the 477 /// function has been read in yet or not. 478 bool isMaterializable() const; 479 480 /// Make sure this GlobalValue is fully read. 481 Error materialize(); 482 483 /// @} 484 485 /// Return true if the primary definition of this global value is outside of 486 /// the current translation unit. 487 bool isDeclaration() const; 488 isDeclarationForLinker()489 bool isDeclarationForLinker() const { 490 if (hasAvailableExternallyLinkage()) 491 return true; 492 493 return isDeclaration(); 494 } 495 496 /// Returns true if this global's definition will be the one chosen by the 497 /// linker. 498 /// 499 /// NB! Ideally this should not be used at the IR level at all. If you're 500 /// interested in optimization constraints implied by the linker's ability to 501 /// choose an implementation, prefer using \c hasExactDefinition. isStrongDefinitionForLinker()502 bool isStrongDefinitionForLinker() const { 503 return !(isDeclarationForLinker() || isWeakForLinker()); 504 } 505 506 // Returns true if the alignment of the value can be unilaterally 507 // increased. 508 bool canIncreaseAlignment() const; 509 getBaseObject()510 const GlobalObject *getBaseObject() const { 511 return const_cast<GlobalValue *>(this)->getBaseObject(); 512 } 513 GlobalObject *getBaseObject(); 514 515 /// Returns whether this is a reference to an absolute symbol. 516 bool isAbsoluteSymbolRef() const; 517 518 /// If this is an absolute symbol reference, returns the range of the symbol, 519 /// otherwise returns None. 520 Optional<ConstantRange> getAbsoluteSymbolRange() const; 521 522 /// This method unlinks 'this' from the containing module, but does not delete 523 /// it. 524 virtual void removeFromParent() = 0; 525 526 /// This method unlinks 'this' from the containing module and deletes it. 527 virtual void eraseFromParent() = 0; 528 529 /// Get the module that this global value is contained inside of... getParent()530 Module *getParent() { return Parent; } getParent()531 const Module *getParent() const { return Parent; } 532 533 // Methods for support type inquiry through isa, cast, and dyn_cast: classof(const Value * V)534 static bool classof(const Value *V) { 535 return V->getValueID() == Value::FunctionVal || 536 V->getValueID() == Value::GlobalVariableVal || 537 V->getValueID() == Value::GlobalAliasVal || 538 V->getValueID() == Value::GlobalIFuncVal; 539 } 540 }; 541 542 } // end namespace llvm 543 544 #endif // LLVM_IR_GLOBALVALUE_H 545