1 //===-- llvm/GlobalValue.h - Class to represent a global value --*- 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 is a common base class of all globally definable objects. As such, 10 // it is subclassed by GlobalVariable, GlobalAlias and by Function. This is 11 // used because you can do certain things with these global objects that you 12 // can't do to anything else. For example, use the address of one as a 13 // constant. 14 // 15 //===----------------------------------------------------------------------===// 16 17 #ifndef LLVM_IR_GLOBALVALUE_H 18 #define LLVM_IR_GLOBALVALUE_H 19 20 #include "llvm/ADT/StringRef.h" 21 #include "llvm/ADT/Twine.h" 22 #include "llvm/IR/Constant.h" 23 #include "llvm/IR/DerivedTypes.h" 24 #include "llvm/IR/Value.h" 25 #include "llvm/Support/Casting.h" 26 #include "llvm/Support/Compiler.h" 27 #include "llvm/Support/ErrorHandling.h" 28 #include <cassert> 29 #include <cstdint> 30 #include <string> 31 32 namespace llvm { 33 34 class Comdat; 35 class ConstantRange; 36 class DataLayout; 37 class Error; 38 class GlobalObject; 39 class Module; 40 41 namespace Intrinsic { 42 typedef unsigned ID; 43 } // end namespace Intrinsic 44 45 // Choose ';' as the delimiter. ':' was used once but it doesn't work well for 46 // Objective-C functions which commonly have :'s in their names. 47 inline constexpr char GlobalIdentifierDelimiter = ';'; 48 49 class GlobalValue : public Constant { 50 public: 51 /// An enumeration for the kinds of linkage for global values. 52 enum LinkageTypes { 53 ExternalLinkage = 0,///< Externally visible function 54 AvailableExternallyLinkage, ///< Available for inspection, not emission. 55 LinkOnceAnyLinkage, ///< Keep one copy of function when linking (inline) 56 LinkOnceODRLinkage, ///< Same, but only replaced by something equivalent. 57 WeakAnyLinkage, ///< Keep one copy of named function when linking (weak) 58 WeakODRLinkage, ///< Same, but only replaced by something equivalent. 59 AppendingLinkage, ///< Special purpose, only applies to global arrays 60 InternalLinkage, ///< Rename collisions when linking (static functions). 61 PrivateLinkage, ///< Like Internal, but omit from symbol table. 62 ExternalWeakLinkage,///< ExternalWeak linkage description. 63 CommonLinkage ///< Tentative definitions. 64 }; 65 66 /// An enumeration for the kinds of visibility of global values. 67 enum VisibilityTypes { 68 DefaultVisibility = 0, ///< The GV is visible 69 HiddenVisibility, ///< The GV is hidden 70 ProtectedVisibility ///< The GV is protected 71 }; 72 73 /// Storage classes of global values for PE targets. 74 enum DLLStorageClassTypes { 75 DefaultStorageClass = 0, 76 DLLImportStorageClass = 1, ///< Function to be imported from DLL 77 DLLExportStorageClass = 2 ///< Function to be accessible from DLL. 78 }; 79 80 protected: GlobalValue(Type * Ty,ValueTy VTy,AllocInfo AllocInfo,LinkageTypes Linkage,const Twine & Name,unsigned AddressSpace)81 GlobalValue(Type *Ty, ValueTy VTy, AllocInfo AllocInfo, LinkageTypes Linkage, 82 const Twine &Name, unsigned AddressSpace) 83 : Constant(PointerType::get(Ty->getContext(), AddressSpace), VTy, 84 AllocInfo), 85 ValueType(Ty), Visibility(DefaultVisibility), 86 UnnamedAddrVal(unsigned(UnnamedAddr::None)), 87 DllStorageClass(DefaultStorageClass), ThreadLocal(NotThreadLocal), 88 HasLLVMReservedName(false), IsDSOLocal(false), HasPartition(false), 89 HasSanitizerMetadata(false) { 90 setLinkage(Linkage); 91 setName(Name); 92 } 93 94 Type *ValueType; 95 96 static const unsigned GlobalValueSubClassDataBits = 15; 97 98 // All bitfields use unsigned as the underlying type so that MSVC will pack 99 // them. 100 unsigned Linkage : 4; // The linkage of this global 101 unsigned Visibility : 2; // The visibility style of this global 102 unsigned UnnamedAddrVal : 2; // This value's address is not significant 103 unsigned DllStorageClass : 2; // DLL storage class 104 105 unsigned ThreadLocal : 3; // Is this symbol "Thread Local", if so, what is 106 // the desired model? 107 108 /// True if the function's name starts with "llvm.". This corresponds to the 109 /// value of Function::isIntrinsic(), which may be true even if 110 /// Function::intrinsicID() returns Intrinsic::not_intrinsic. 111 unsigned HasLLVMReservedName : 1; 112 113 /// If true then there is a definition within the same linkage unit and that 114 /// definition cannot be runtime preempted. 115 unsigned IsDSOLocal : 1; 116 117 /// True if this symbol has a partition name assigned (see 118 /// https://lld.llvm.org/Partitions.html). 119 unsigned HasPartition : 1; 120 121 /// True if this symbol has sanitizer metadata available. Should only happen 122 /// if sanitizers were enabled when building the translation unit which 123 /// contains this GV. 124 unsigned HasSanitizerMetadata : 1; 125 126 private: 127 // Give subclasses access to what otherwise would be wasted padding. 128 // (15 + 4 + 2 + 2 + 2 + 3 + 1 + 1 + 1 + 1) == 32. 129 unsigned SubClassData : GlobalValueSubClassDataBits; 130 131 friend class Constant; 132 133 void destroyConstantImpl(); 134 Value *handleOperandChangeImpl(Value *From, Value *To); 135 136 /// Returns true if the definition of this global may be replaced by a 137 /// differently optimized variant of the same source level function at link 138 /// time. mayBeDerefined()139 bool mayBeDerefined() const { 140 switch (getLinkage()) { 141 case WeakODRLinkage: 142 case LinkOnceODRLinkage: 143 case AvailableExternallyLinkage: 144 return true; 145 146 case WeakAnyLinkage: 147 case LinkOnceAnyLinkage: 148 case CommonLinkage: 149 case ExternalWeakLinkage: 150 case ExternalLinkage: 151 case AppendingLinkage: 152 case InternalLinkage: 153 case PrivateLinkage: 154 // Optimizations may assume builtin semantics for functions defined as 155 // nobuiltin due to attributes at call-sites. To avoid applying IPO based 156 // on nobuiltin semantics, treat such function definitions as maybe 157 // derefined. 158 return isInterposable() || isNobuiltinFnDef(); 159 } 160 161 llvm_unreachable("Fully covered switch above!"); 162 } 163 164 /// Returns true if the global is a function definition with the nobuiltin 165 /// attribute. 166 LLVM_ABI bool isNobuiltinFnDef() const; 167 168 protected: 169 /// The intrinsic ID for this subclass (which must be a Function). 170 /// 171 /// This member is defined by this class, but not used for anything. 172 /// Subclasses can use it to store their intrinsic ID, if they have one. 173 /// 174 /// This is stored here to save space in Function on 64-bit hosts. 175 Intrinsic::ID IntID = (Intrinsic::ID)0U; 176 getGlobalValueSubClassData()177 unsigned getGlobalValueSubClassData() const { 178 return SubClassData; 179 } setGlobalValueSubClassData(unsigned V)180 void setGlobalValueSubClassData(unsigned V) { 181 assert(V < (1 << GlobalValueSubClassDataBits) && "It will not fit"); 182 SubClassData = V; 183 } 184 185 Module *Parent = nullptr; // The containing module. 186 187 // Used by SymbolTableListTraits. setParent(Module * parent)188 void setParent(Module *parent) { 189 Parent = parent; 190 } 191 ~GlobalValue()192 ~GlobalValue() { 193 removeDeadConstantUsers(); // remove any dead constants using this. 194 } 195 196 public: 197 enum ThreadLocalMode { 198 NotThreadLocal = 0, 199 GeneralDynamicTLSModel, 200 LocalDynamicTLSModel, 201 InitialExecTLSModel, 202 LocalExecTLSModel 203 }; 204 205 GlobalValue(const GlobalValue &) = delete; 206 getAddressSpace()207 unsigned getAddressSpace() const { 208 return getType()->getAddressSpace(); 209 } 210 211 enum class UnnamedAddr { 212 None, 213 Local, 214 Global, 215 }; 216 hasGlobalUnnamedAddr()217 bool hasGlobalUnnamedAddr() const { 218 return getUnnamedAddr() == UnnamedAddr::Global; 219 } 220 221 /// Returns true if this value's address is not significant in this module. 222 /// This attribute is intended to be used only by the code generator and LTO 223 /// to allow the linker to decide whether the global needs to be in the symbol 224 /// table. It should probably not be used in optimizations, as the value may 225 /// have uses outside the module; use hasGlobalUnnamedAddr() instead. hasAtLeastLocalUnnamedAddr()226 bool hasAtLeastLocalUnnamedAddr() const { 227 return getUnnamedAddr() != UnnamedAddr::None; 228 } 229 getUnnamedAddr()230 UnnamedAddr getUnnamedAddr() const { 231 return UnnamedAddr(UnnamedAddrVal); 232 } setUnnamedAddr(UnnamedAddr Val)233 void setUnnamedAddr(UnnamedAddr Val) { UnnamedAddrVal = unsigned(Val); } 234 getMinUnnamedAddr(UnnamedAddr A,UnnamedAddr B)235 static UnnamedAddr getMinUnnamedAddr(UnnamedAddr A, UnnamedAddr B) { 236 if (A == UnnamedAddr::None || B == UnnamedAddr::None) 237 return UnnamedAddr::None; 238 if (A == UnnamedAddr::Local || B == UnnamedAddr::Local) 239 return UnnamedAddr::Local; 240 return UnnamedAddr::Global; 241 } 242 hasComdat()243 bool hasComdat() const { return getComdat() != nullptr; } 244 LLVM_ABI const Comdat *getComdat() const; getComdat()245 Comdat *getComdat() { 246 return const_cast<Comdat *>( 247 static_cast<const GlobalValue *>(this)->getComdat()); 248 } 249 getVisibility()250 VisibilityTypes getVisibility() const { return VisibilityTypes(Visibility); } hasDefaultVisibility()251 bool hasDefaultVisibility() const { return Visibility == DefaultVisibility; } hasHiddenVisibility()252 bool hasHiddenVisibility() const { return Visibility == HiddenVisibility; } hasProtectedVisibility()253 bool hasProtectedVisibility() const { 254 return Visibility == ProtectedVisibility; 255 } setVisibility(VisibilityTypes V)256 void setVisibility(VisibilityTypes V) { 257 assert((!hasLocalLinkage() || V == DefaultVisibility) && 258 "local linkage requires default visibility"); 259 Visibility = V; 260 if (isImplicitDSOLocal()) 261 setDSOLocal(true); 262 } 263 264 /// If the value is "Thread Local", its value isn't shared by the threads. isThreadLocal()265 bool isThreadLocal() const { return getThreadLocalMode() != NotThreadLocal; } setThreadLocal(bool Val)266 void setThreadLocal(bool Val) { 267 setThreadLocalMode(Val ? GeneralDynamicTLSModel : NotThreadLocal); 268 } setThreadLocalMode(ThreadLocalMode Val)269 void setThreadLocalMode(ThreadLocalMode Val) { 270 assert(Val == NotThreadLocal || getValueID() != Value::FunctionVal); 271 ThreadLocal = Val; 272 } getThreadLocalMode()273 ThreadLocalMode getThreadLocalMode() const { 274 return static_cast<ThreadLocalMode>(ThreadLocal); 275 } 276 getDLLStorageClass()277 DLLStorageClassTypes getDLLStorageClass() const { 278 return DLLStorageClassTypes(DllStorageClass); 279 } hasDLLImportStorageClass()280 bool hasDLLImportStorageClass() const { 281 return DllStorageClass == DLLImportStorageClass; 282 } hasDLLExportStorageClass()283 bool hasDLLExportStorageClass() const { 284 return DllStorageClass == DLLExportStorageClass; 285 } setDLLStorageClass(DLLStorageClassTypes C)286 void setDLLStorageClass(DLLStorageClassTypes C) { 287 assert((!hasLocalLinkage() || C == DefaultStorageClass) && 288 "local linkage requires DefaultStorageClass"); 289 DllStorageClass = C; 290 } 291 hasSection()292 bool hasSection() const { return !getSection().empty(); } 293 LLVM_ABI StringRef getSection() const; 294 295 /// Global values are always pointers. getType()296 PointerType *getType() const { return cast<PointerType>(User::getType()); } 297 getValueType()298 Type *getValueType() const { return ValueType; } 299 isImplicitDSOLocal()300 bool isImplicitDSOLocal() const { 301 return hasLocalLinkage() || 302 (!hasDefaultVisibility() && !hasExternalWeakLinkage()); 303 } 304 setDSOLocal(bool Local)305 void setDSOLocal(bool Local) { IsDSOLocal = Local; } 306 isDSOLocal()307 bool isDSOLocal() const { 308 return IsDSOLocal; 309 } 310 hasPartition()311 bool hasPartition() const { 312 return HasPartition; 313 } 314 LLVM_ABI StringRef getPartition() const; 315 LLVM_ABI void setPartition(StringRef Part); 316 317 // ASan, HWASan and Memtag sanitizers have some instrumentation that applies 318 // specifically to global variables. 319 struct SanitizerMetadata { SanitizerMetadataSanitizerMetadata320 SanitizerMetadata() 321 : NoAddress(false), NoHWAddress(false), 322 Memtag(false), IsDynInit(false) {} 323 // For ASan and HWASan, this instrumentation is implicitly applied to all 324 // global variables when built with -fsanitize=*. What we need is a way to 325 // persist the information that a certain global variable should *not* have 326 // sanitizers applied, which occurs if: 327 // 1. The global variable is in the sanitizer ignore list, or 328 // 2. The global variable is created by the sanitizers itself for internal 329 // usage, or 330 // 3. The global variable has __attribute__((no_sanitize("..."))) or 331 // __attribute__((disable_sanitizer_instrumentation)). 332 // 333 // This is important, a some IR passes like GlobalMerge can delete global 334 // variables and replace them with new ones. If the old variables were 335 // marked to be unsanitized, then the new ones should also be. 336 unsigned NoAddress : 1; 337 unsigned NoHWAddress : 1; 338 339 // Memtag sanitization works differently: sanitization is requested by clang 340 // when `-fsanitize=memtag-globals` is provided, and the request can be 341 // denied (and the attribute removed) by the AArch64 global tagging pass if 342 // it can't be fulfilled (e.g. the global variable is a TLS variable). 343 // Memtag sanitization has to interact with other parts of LLVM (like 344 // supressing certain optimisations, emitting assembly directives, or 345 // creating special relocation sections). 346 // 347 // Use `GlobalValue::isTagged()` to check whether tagging should be enabled 348 // for a global variable. 349 unsigned Memtag : 1; 350 351 // ASan-specific metadata. Is this global variable dynamically initialized 352 // (from a C++ language perspective), and should therefore be checked for 353 // ODR violations. 354 unsigned IsDynInit : 1; 355 }; 356 hasSanitizerMetadata()357 bool hasSanitizerMetadata() const { return HasSanitizerMetadata; } 358 LLVM_ABI const SanitizerMetadata &getSanitizerMetadata() const; 359 // Note: Not byref as it's a POD and otherwise it's too easy to call 360 // G.setSanitizerMetadata(G2.getSanitizerMetadata()), and the argument becomes 361 // dangling when the backing storage allocates the metadata for `G`, as the 362 // storage is shared between `G1` and `G2`. 363 LLVM_ABI void setSanitizerMetadata(SanitizerMetadata Meta); 364 LLVM_ABI void removeSanitizerMetadata(); 365 LLVM_ABI void setNoSanitizeMetadata(); 366 isTagged()367 bool isTagged() const { 368 return hasSanitizerMetadata() && getSanitizerMetadata().Memtag; 369 } 370 getLinkOnceLinkage(bool ODR)371 static LinkageTypes getLinkOnceLinkage(bool ODR) { 372 return ODR ? LinkOnceODRLinkage : LinkOnceAnyLinkage; 373 } getWeakLinkage(bool ODR)374 static LinkageTypes getWeakLinkage(bool ODR) { 375 return ODR ? WeakODRLinkage : WeakAnyLinkage; 376 } 377 isExternalLinkage(LinkageTypes Linkage)378 static bool isExternalLinkage(LinkageTypes Linkage) { 379 return Linkage == ExternalLinkage; 380 } isAvailableExternallyLinkage(LinkageTypes Linkage)381 static bool isAvailableExternallyLinkage(LinkageTypes Linkage) { 382 return Linkage == AvailableExternallyLinkage; 383 } isLinkOnceAnyLinkage(LinkageTypes Linkage)384 static bool isLinkOnceAnyLinkage(LinkageTypes Linkage) { 385 return Linkage == LinkOnceAnyLinkage; 386 } isLinkOnceODRLinkage(LinkageTypes Linkage)387 static bool isLinkOnceODRLinkage(LinkageTypes Linkage) { 388 return Linkage == LinkOnceODRLinkage; 389 } isLinkOnceLinkage(LinkageTypes Linkage)390 static bool isLinkOnceLinkage(LinkageTypes Linkage) { 391 return isLinkOnceAnyLinkage(Linkage) || isLinkOnceODRLinkage(Linkage); 392 } isWeakAnyLinkage(LinkageTypes Linkage)393 static bool isWeakAnyLinkage(LinkageTypes Linkage) { 394 return Linkage == WeakAnyLinkage; 395 } isWeakODRLinkage(LinkageTypes Linkage)396 static bool isWeakODRLinkage(LinkageTypes Linkage) { 397 return Linkage == WeakODRLinkage; 398 } isWeakLinkage(LinkageTypes Linkage)399 static bool isWeakLinkage(LinkageTypes Linkage) { 400 return isWeakAnyLinkage(Linkage) || isWeakODRLinkage(Linkage); 401 } isAppendingLinkage(LinkageTypes Linkage)402 static bool isAppendingLinkage(LinkageTypes Linkage) { 403 return Linkage == AppendingLinkage; 404 } isInternalLinkage(LinkageTypes Linkage)405 static bool isInternalLinkage(LinkageTypes Linkage) { 406 return Linkage == InternalLinkage; 407 } isPrivateLinkage(LinkageTypes Linkage)408 static bool isPrivateLinkage(LinkageTypes Linkage) { 409 return Linkage == PrivateLinkage; 410 } isLocalLinkage(LinkageTypes Linkage)411 static bool isLocalLinkage(LinkageTypes Linkage) { 412 return isInternalLinkage(Linkage) || isPrivateLinkage(Linkage); 413 } isExternalWeakLinkage(LinkageTypes Linkage)414 static bool isExternalWeakLinkage(LinkageTypes Linkage) { 415 return Linkage == ExternalWeakLinkage; 416 } isCommonLinkage(LinkageTypes Linkage)417 static bool isCommonLinkage(LinkageTypes Linkage) { 418 return Linkage == CommonLinkage; 419 } isValidDeclarationLinkage(LinkageTypes Linkage)420 static bool isValidDeclarationLinkage(LinkageTypes Linkage) { 421 return isExternalWeakLinkage(Linkage) || isExternalLinkage(Linkage); 422 } 423 424 /// Whether the definition of this global may be replaced by something 425 /// non-equivalent at link time. For example, if a function has weak linkage 426 /// then the code defining it may be replaced by different code. isInterposableLinkage(LinkageTypes Linkage)427 static bool isInterposableLinkage(LinkageTypes Linkage) { 428 switch (Linkage) { 429 case WeakAnyLinkage: 430 case LinkOnceAnyLinkage: 431 case CommonLinkage: 432 case ExternalWeakLinkage: 433 return true; 434 435 case AvailableExternallyLinkage: 436 case LinkOnceODRLinkage: 437 case WeakODRLinkage: 438 // The above three cannot be overridden but can be de-refined. 439 440 case ExternalLinkage: 441 case AppendingLinkage: 442 case InternalLinkage: 443 case PrivateLinkage: 444 return false; 445 } 446 llvm_unreachable("Fully covered switch above!"); 447 } 448 449 /// Whether the definition of this global may be discarded if it is not used 450 /// in its compilation unit. isDiscardableIfUnused(LinkageTypes Linkage)451 static bool isDiscardableIfUnused(LinkageTypes Linkage) { 452 return isLinkOnceLinkage(Linkage) || isLocalLinkage(Linkage) || 453 isAvailableExternallyLinkage(Linkage); 454 } 455 456 /// Whether the definition of this global may be replaced at link time. NB: 457 /// Using this method outside of the code generators is almost always a 458 /// mistake: when working at the IR level use isInterposable instead as it 459 /// knows about ODR semantics. isWeakForLinker(LinkageTypes Linkage)460 static bool isWeakForLinker(LinkageTypes Linkage) { 461 return Linkage == WeakAnyLinkage || Linkage == WeakODRLinkage || 462 Linkage == LinkOnceAnyLinkage || Linkage == LinkOnceODRLinkage || 463 Linkage == CommonLinkage || Linkage == ExternalWeakLinkage; 464 } 465 466 /// Return true if the currently visible definition of this global (if any) is 467 /// exactly the definition we will see at runtime. 468 /// 469 /// Non-exact linkage types inhibits most non-inlining IPO, since a 470 /// differently optimized variant of the same function can have different 471 /// observable or undefined behavior than in the variant currently visible. 472 /// For instance, we could have started with 473 /// 474 /// void foo(int *v) { 475 /// int t = 5 / v[0]; 476 /// (void) t; 477 /// } 478 /// 479 /// and "refined" it to 480 /// 481 /// void foo(int *v) { } 482 /// 483 /// However, we cannot infer readnone for `foo`, since that would justify 484 /// DSE'ing a store to `v[0]` across a call to `foo`, which can cause 485 /// undefined behavior if the linker replaces the actual call destination with 486 /// the unoptimized `foo`. 487 /// 488 /// Inlining is okay across non-exact linkage types as long as they're not 489 /// interposable (see \c isInterposable), since in such cases the currently 490 /// visible variant is *a* correct implementation of the original source 491 /// function; it just isn't the *only* correct implementation. isDefinitionExact()492 bool isDefinitionExact() const { 493 return !mayBeDerefined(); 494 } 495 496 /// Return true if this global has an exact defintion. hasExactDefinition()497 bool hasExactDefinition() const { 498 // While this computes exactly the same thing as 499 // isStrongDefinitionForLinker, the intended uses are different. This 500 // function is intended to help decide if specific inter-procedural 501 // transforms are correct, while isStrongDefinitionForLinker's intended use 502 // is in low level code generation. 503 return !isDeclaration() && isDefinitionExact(); 504 } 505 506 /// Return true if this global's definition can be substituted with an 507 /// *arbitrary* definition at link time or load time. We cannot do any IPO or 508 /// inlining across interposable call edges, since the callee can be 509 /// replaced with something arbitrary. 510 LLVM_ABI bool isInterposable() const; 511 LLVM_ABI bool canBenefitFromLocalAlias() const; 512 hasExternalLinkage()513 bool hasExternalLinkage() const { return isExternalLinkage(getLinkage()); } hasAvailableExternallyLinkage()514 bool hasAvailableExternallyLinkage() const { 515 return isAvailableExternallyLinkage(getLinkage()); 516 } hasLinkOnceLinkage()517 bool hasLinkOnceLinkage() const { return isLinkOnceLinkage(getLinkage()); } hasLinkOnceAnyLinkage()518 bool hasLinkOnceAnyLinkage() const { 519 return isLinkOnceAnyLinkage(getLinkage()); 520 } hasLinkOnceODRLinkage()521 bool hasLinkOnceODRLinkage() const { 522 return isLinkOnceODRLinkage(getLinkage()); 523 } hasWeakLinkage()524 bool hasWeakLinkage() const { return isWeakLinkage(getLinkage()); } hasWeakAnyLinkage()525 bool hasWeakAnyLinkage() const { return isWeakAnyLinkage(getLinkage()); } hasWeakODRLinkage()526 bool hasWeakODRLinkage() const { return isWeakODRLinkage(getLinkage()); } hasAppendingLinkage()527 bool hasAppendingLinkage() const { return isAppendingLinkage(getLinkage()); } hasInternalLinkage()528 bool hasInternalLinkage() const { return isInternalLinkage(getLinkage()); } hasPrivateLinkage()529 bool hasPrivateLinkage() const { return isPrivateLinkage(getLinkage()); } hasLocalLinkage()530 bool hasLocalLinkage() const { return isLocalLinkage(getLinkage()); } hasExternalWeakLinkage()531 bool hasExternalWeakLinkage() const { 532 return isExternalWeakLinkage(getLinkage()); 533 } hasCommonLinkage()534 bool hasCommonLinkage() const { return isCommonLinkage(getLinkage()); } hasValidDeclarationLinkage()535 bool hasValidDeclarationLinkage() const { 536 return isValidDeclarationLinkage(getLinkage()); 537 } 538 setLinkage(LinkageTypes LT)539 void setLinkage(LinkageTypes LT) { 540 if (isLocalLinkage(LT)) { 541 Visibility = DefaultVisibility; 542 DllStorageClass = DefaultStorageClass; 543 } 544 Linkage = LT; 545 if (isImplicitDSOLocal()) 546 setDSOLocal(true); 547 } getLinkage()548 LinkageTypes getLinkage() const { return LinkageTypes(Linkage); } 549 isDiscardableIfUnused()550 bool isDiscardableIfUnused() const { 551 return isDiscardableIfUnused(getLinkage()); 552 } 553 isWeakForLinker()554 bool isWeakForLinker() const { return isWeakForLinker(getLinkage()); } 555 556 protected: 557 /// Copy all additional attributes (those not needed to create a GlobalValue) 558 /// from the GlobalValue Src to this one. 559 LLVM_ABI void copyAttributesFrom(const GlobalValue *Src); 560 561 public: 562 /// If the given string begins with the GlobalValue name mangling escape 563 /// character '\1', drop it. 564 /// 565 /// This function applies a specific mangling that is used in PGO profiles, 566 /// among other things. If you're trying to get a symbol name for an 567 /// arbitrary GlobalValue, this is not the function you're looking for; see 568 /// Mangler.h. dropLLVMManglingEscape(StringRef Name)569 static StringRef dropLLVMManglingEscape(StringRef Name) { 570 Name.consume_front("\1"); 571 return Name; 572 } 573 574 /// Declare a type to represent a global unique identifier for a global value. 575 /// This is a 64 bits hash that is used by PGO and ThinLTO to have a compact 576 /// unique way to identify a symbol. 577 using GUID = uint64_t; 578 579 /// Return the modified name for a global value suitable to be 580 /// used as the key for a global lookup (e.g. profile or ThinLTO). 581 /// The value's original name is \c Name and has linkage of type 582 /// \c Linkage. The value is defined in module \c FileName. 583 LLVM_ABI static std::string 584 getGlobalIdentifier(StringRef Name, GlobalValue::LinkageTypes Linkage, 585 StringRef FileName); 586 587 private: 588 /// Return the modified name for this global value suitable to be 589 /// used as the key for a global lookup (e.g. profile or ThinLTO). 590 LLVM_ABI std::string getGlobalIdentifier() const; 591 592 public: 593 /// Return a 64-bit global unique ID constructed from the name of a global 594 /// symbol. Since this call doesn't supply the linkage or defining filename, 595 /// the GUID computation will assume that the global has external linkage. 596 LLVM_ABI static GUID getGUIDAssumingExternalLinkage(StringRef GlobalName); 597 598 /// Return a 64-bit global unique ID constructed from global value name 599 /// (i.e. returned by getGlobalIdentifier()). getGUID()600 GUID getGUID() const { 601 return getGUIDAssumingExternalLinkage(getGlobalIdentifier()); 602 } 603 604 /// @name Materialization 605 /// Materialization is used to construct functions only as they're needed. 606 /// This 607 /// is useful to reduce memory usage in LLVM or parsing work done by the 608 /// BitcodeReader to load the Module. 609 /// @{ 610 611 /// If this function's Module is being lazily streamed in functions from disk 612 /// or some other source, this method can be used to check to see if the 613 /// function has been read in yet or not. 614 LLVM_ABI bool isMaterializable() const; 615 616 /// Make sure this GlobalValue is fully read. 617 LLVM_ABI Error materialize(); 618 619 /// @} 620 621 /// Return true if the primary definition of this global value is outside of 622 /// the current translation unit. 623 LLVM_ABI bool isDeclaration() const; 624 isDeclarationForLinker()625 bool isDeclarationForLinker() const { 626 if (hasAvailableExternallyLinkage()) 627 return true; 628 629 return isDeclaration(); 630 } 631 632 /// Returns true if this global's definition will be the one chosen by the 633 /// linker. 634 /// 635 /// NB! Ideally this should not be used at the IR level at all. If you're 636 /// interested in optimization constraints implied by the linker's ability to 637 /// choose an implementation, prefer using \c hasExactDefinition. isStrongDefinitionForLinker()638 bool isStrongDefinitionForLinker() const { 639 return !(isDeclarationForLinker() || isWeakForLinker()); 640 } 641 642 LLVM_ABI const GlobalObject *getAliaseeObject() const; getAliaseeObject()643 GlobalObject *getAliaseeObject() { 644 return const_cast<GlobalObject *>( 645 static_cast<const GlobalValue *>(this)->getAliaseeObject()); 646 } 647 648 /// Returns whether this is a reference to an absolute symbol. 649 LLVM_ABI bool isAbsoluteSymbolRef() const; 650 651 /// If this is an absolute symbol reference, returns the range of the symbol, 652 /// otherwise returns std::nullopt. 653 LLVM_ABI std::optional<ConstantRange> getAbsoluteSymbolRange() const; 654 655 /// This method unlinks 'this' from the containing module, but does not delete 656 /// it. 657 LLVM_ABI void removeFromParent(); 658 659 /// This method unlinks 'this' from the containing module and deletes it. 660 LLVM_ABI void eraseFromParent(); 661 662 /// Get the module that this global value is contained inside of... getParent()663 Module *getParent() { return Parent; } getParent()664 const Module *getParent() const { return Parent; } 665 666 /// Get the data layout of the module this global belongs to. 667 /// 668 /// Requires the global to have a parent module. 669 LLVM_ABI const DataLayout &getDataLayout() const; 670 671 // Methods for support type inquiry through isa, cast, and dyn_cast: classof(const Value * V)672 static bool classof(const Value *V) { 673 return V->getValueID() == Value::FunctionVal || 674 V->getValueID() == Value::GlobalVariableVal || 675 V->getValueID() == Value::GlobalAliasVal || 676 V->getValueID() == Value::GlobalIFuncVal; 677 } 678 679 /// True if GV can be left out of the object symbol table. This is the case 680 /// for linkonce_odr values whose address is not significant. While legal, it 681 /// is not normally profitable to omit them from the .o symbol table. Using 682 /// this analysis makes sense when the information can be passed down to the 683 /// linker or we are in LTO. 684 LLVM_ABI bool canBeOmittedFromSymbolTable() const; 685 }; 686 687 } // end namespace llvm 688 689 #endif // LLVM_IR_GLOBALVALUE_H 690