Globals.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558
  1. //===-- Globals.cpp - Implement the GlobalValue & GlobalVariable class ----===//
  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 implements the GlobalValue & GlobalVariable classes for the IR
  10. // library.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "LLVMContextImpl.h"
  14. #include "llvm/ADT/Triple.h"
  15. #include "llvm/IR/ConstantRange.h"
  16. #include "llvm/IR/Constants.h"
  17. #include "llvm/IR/DerivedTypes.h"
  18. #include "llvm/IR/GlobalAlias.h"
  19. #include "llvm/IR/GlobalValue.h"
  20. #include "llvm/IR/GlobalVariable.h"
  21. #include "llvm/IR/Module.h"
  22. #include "llvm/Support/Error.h"
  23. #include "llvm/Support/ErrorHandling.h"
  24. using namespace llvm;
  25. //===----------------------------------------------------------------------===//
  26. // GlobalValue Class
  27. //===----------------------------------------------------------------------===//
  28. // GlobalValue should be a Constant, plus a type, a module, some flags, and an
  29. // intrinsic ID. Add an assert to prevent people from accidentally growing
  30. // GlobalValue while adding flags.
  31. static_assert(sizeof(GlobalValue) ==
  32. sizeof(Constant) + 2 * sizeof(void *) + 2 * sizeof(unsigned),
  33. "unexpected GlobalValue size growth");
  34. // GlobalObject adds a comdat.
  35. static_assert(sizeof(GlobalObject) == sizeof(GlobalValue) + sizeof(void *),
  36. "unexpected GlobalObject size growth");
  37. bool GlobalValue::isMaterializable() const {
  38. if (const Function *F = dyn_cast<Function>(this))
  39. return F->isMaterializable();
  40. return false;
  41. }
  42. Error GlobalValue::materialize() {
  43. return getParent()->materialize(this);
  44. }
  45. /// Override destroyConstantImpl to make sure it doesn't get called on
  46. /// GlobalValue's because they shouldn't be treated like other constants.
  47. void GlobalValue::destroyConstantImpl() {
  48. llvm_unreachable("You can't GV->destroyConstantImpl()!");
  49. }
  50. Value *GlobalValue::handleOperandChangeImpl(Value *From, Value *To) {
  51. llvm_unreachable("Unsupported class for handleOperandChange()!");
  52. }
  53. /// copyAttributesFrom - copy all additional attributes (those not needed to
  54. /// create a GlobalValue) from the GlobalValue Src to this one.
  55. void GlobalValue::copyAttributesFrom(const GlobalValue *Src) {
  56. setVisibility(Src->getVisibility());
  57. setUnnamedAddr(Src->getUnnamedAddr());
  58. setThreadLocalMode(Src->getThreadLocalMode());
  59. setDLLStorageClass(Src->getDLLStorageClass());
  60. setDSOLocal(Src->isDSOLocal());
  61. setPartition(Src->getPartition());
  62. }
  63. void GlobalValue::removeFromParent() {
  64. switch (getValueID()) {
  65. #define HANDLE_GLOBAL_VALUE(NAME) \
  66. case Value::NAME##Val: \
  67. return static_cast<NAME *>(this)->removeFromParent();
  68. #include "llvm/IR/Value.def"
  69. default:
  70. break;
  71. }
  72. llvm_unreachable("not a global");
  73. }
  74. void GlobalValue::eraseFromParent() {
  75. switch (getValueID()) {
  76. #define HANDLE_GLOBAL_VALUE(NAME) \
  77. case Value::NAME##Val: \
  78. return static_cast<NAME *>(this)->eraseFromParent();
  79. #include "llvm/IR/Value.def"
  80. default:
  81. break;
  82. }
  83. llvm_unreachable("not a global");
  84. }
  85. GlobalObject::~GlobalObject() { setComdat(nullptr); }
  86. bool GlobalValue::isInterposable() const {
  87. if (isInterposableLinkage(getLinkage()))
  88. return true;
  89. return getParent() && getParent()->getSemanticInterposition() &&
  90. !isDSOLocal();
  91. }
  92. bool GlobalValue::canBenefitFromLocalAlias() const {
  93. // See AsmPrinter::getSymbolPreferLocal(). For a deduplicate comdat kind,
  94. // references to a discarded local symbol from outside the group are not
  95. // allowed, so avoid the local alias.
  96. auto isDeduplicateComdat = [](const Comdat *C) {
  97. return C && C->getSelectionKind() != Comdat::NoDeduplicate;
  98. };
  99. return hasDefaultVisibility() &&
  100. GlobalObject::isExternalLinkage(getLinkage()) && !isDeclaration() &&
  101. !isa<GlobalIFunc>(this) && !isDeduplicateComdat(getComdat());
  102. }
  103. unsigned GlobalValue::getAddressSpace() const {
  104. PointerType *PtrTy = getType();
  105. return PtrTy->getAddressSpace();
  106. }
  107. void GlobalObject::setAlignment(MaybeAlign Align) {
  108. assert((!Align || *Align <= MaximumAlignment) &&
  109. "Alignment is greater than MaximumAlignment!");
  110. unsigned AlignmentData = encode(Align);
  111. unsigned OldData = getGlobalValueSubClassData();
  112. setGlobalValueSubClassData((OldData & ~AlignmentMask) | AlignmentData);
  113. assert(MaybeAlign(getAlignment()) == Align &&
  114. "Alignment representation error!");
  115. }
  116. void GlobalObject::copyAttributesFrom(const GlobalObject *Src) {
  117. GlobalValue::copyAttributesFrom(Src);
  118. setAlignment(Src->getAlign());
  119. setSection(Src->getSection());
  120. }
  121. std::string GlobalValue::getGlobalIdentifier(StringRef Name,
  122. GlobalValue::LinkageTypes Linkage,
  123. StringRef FileName) {
  124. // Value names may be prefixed with a binary '1' to indicate
  125. // that the backend should not modify the symbols due to any platform
  126. // naming convention. Do not include that '1' in the PGO profile name.
  127. if (Name[0] == '\1')
  128. Name = Name.substr(1);
  129. std::string NewName = std::string(Name);
  130. if (llvm::GlobalValue::isLocalLinkage(Linkage)) {
  131. // For local symbols, prepend the main file name to distinguish them.
  132. // Do not include the full path in the file name since there's no guarantee
  133. // that it will stay the same, e.g., if the files are checked out from
  134. // version control in different locations.
  135. if (FileName.empty())
  136. NewName = NewName.insert(0, "<unknown>:");
  137. else
  138. NewName = NewName.insert(0, FileName.str() + ":");
  139. }
  140. return NewName;
  141. }
  142. std::string GlobalValue::getGlobalIdentifier() const {
  143. return getGlobalIdentifier(getName(), getLinkage(),
  144. getParent()->getSourceFileName());
  145. }
  146. StringRef GlobalValue::getSection() const {
  147. if (auto *GA = dyn_cast<GlobalAlias>(this)) {
  148. // In general we cannot compute this at the IR level, but we try.
  149. if (const GlobalObject *GO = GA->getAliaseeObject())
  150. return GO->getSection();
  151. return "";
  152. }
  153. return cast<GlobalObject>(this)->getSection();
  154. }
  155. const Comdat *GlobalValue::getComdat() const {
  156. if (auto *GA = dyn_cast<GlobalAlias>(this)) {
  157. // In general we cannot compute this at the IR level, but we try.
  158. if (const GlobalObject *GO = GA->getAliaseeObject())
  159. return const_cast<GlobalObject *>(GO)->getComdat();
  160. return nullptr;
  161. }
  162. // ifunc and its resolver are separate things so don't use resolver comdat.
  163. if (isa<GlobalIFunc>(this))
  164. return nullptr;
  165. return cast<GlobalObject>(this)->getComdat();
  166. }
  167. void GlobalObject::setComdat(Comdat *C) {
  168. if (ObjComdat)
  169. ObjComdat->removeUser(this);
  170. ObjComdat = C;
  171. if (C)
  172. C->addUser(this);
  173. }
  174. StringRef GlobalValue::getPartition() const {
  175. if (!hasPartition())
  176. return "";
  177. return getContext().pImpl->GlobalValuePartitions[this];
  178. }
  179. void GlobalValue::setPartition(StringRef S) {
  180. // Do nothing if we're clearing the partition and it is already empty.
  181. if (!hasPartition() && S.empty())
  182. return;
  183. // Get or create a stable partition name string and put it in the table in the
  184. // context.
  185. if (!S.empty())
  186. S = getContext().pImpl->Saver.save(S);
  187. getContext().pImpl->GlobalValuePartitions[this] = S;
  188. // Update the HasPartition field. Setting the partition to the empty string
  189. // means this global no longer has a partition.
  190. HasPartition = !S.empty();
  191. }
  192. StringRef GlobalObject::getSectionImpl() const {
  193. assert(hasSection());
  194. return getContext().pImpl->GlobalObjectSections[this];
  195. }
  196. void GlobalObject::setSection(StringRef S) {
  197. // Do nothing if we're clearing the section and it is already empty.
  198. if (!hasSection() && S.empty())
  199. return;
  200. // Get or create a stable section name string and put it in the table in the
  201. // context.
  202. if (!S.empty())
  203. S = getContext().pImpl->Saver.save(S);
  204. getContext().pImpl->GlobalObjectSections[this] = S;
  205. // Update the HasSectionHashEntryBit. Setting the section to the empty string
  206. // means this global no longer has a section.
  207. setGlobalObjectFlag(HasSectionHashEntryBit, !S.empty());
  208. }
  209. bool GlobalValue::isDeclaration() const {
  210. // Globals are definitions if they have an initializer.
  211. if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(this))
  212. return GV->getNumOperands() == 0;
  213. // Functions are definitions if they have a body.
  214. if (const Function *F = dyn_cast<Function>(this))
  215. return F->empty() && !F->isMaterializable();
  216. // Aliases and ifuncs are always definitions.
  217. assert(isa<GlobalAlias>(this) || isa<GlobalIFunc>(this));
  218. return false;
  219. }
  220. bool GlobalObject::canIncreaseAlignment() const {
  221. // Firstly, can only increase the alignment of a global if it
  222. // is a strong definition.
  223. if (!isStrongDefinitionForLinker())
  224. return false;
  225. // It also has to either not have a section defined, or, not have
  226. // alignment specified. (If it is assigned a section, the global
  227. // could be densely packed with other objects in the section, and
  228. // increasing the alignment could cause padding issues.)
  229. if (hasSection() && getAlign().hasValue())
  230. return false;
  231. // On ELF platforms, we're further restricted in that we can't
  232. // increase the alignment of any variable which might be emitted
  233. // into a shared library, and which is exported. If the main
  234. // executable accesses a variable found in a shared-lib, the main
  235. // exe actually allocates memory for and exports the symbol ITSELF,
  236. // overriding the symbol found in the library. That is, at link
  237. // time, the observed alignment of the variable is copied into the
  238. // executable binary. (A COPY relocation is also generated, to copy
  239. // the initial data from the shadowed variable in the shared-lib
  240. // into the location in the main binary, before running code.)
  241. //
  242. // And thus, even though you might think you are defining the
  243. // global, and allocating the memory for the global in your object
  244. // file, and thus should be able to set the alignment arbitrarily,
  245. // that's not actually true. Doing so can cause an ABI breakage; an
  246. // executable might have already been built with the previous
  247. // alignment of the variable, and then assuming an increased
  248. // alignment will be incorrect.
  249. // Conservatively assume ELF if there's no parent pointer.
  250. bool isELF =
  251. (!Parent || Triple(Parent->getTargetTriple()).isOSBinFormatELF());
  252. if (isELF && !isDSOLocal())
  253. return false;
  254. return true;
  255. }
  256. static const GlobalObject *
  257. findBaseObject(const Constant *C, DenseSet<const GlobalAlias *> &Aliases) {
  258. if (auto *GO = dyn_cast<GlobalObject>(C))
  259. return GO;
  260. if (auto *GA = dyn_cast<GlobalAlias>(C))
  261. if (Aliases.insert(GA).second)
  262. return findBaseObject(GA->getOperand(0), Aliases);
  263. if (auto *CE = dyn_cast<ConstantExpr>(C)) {
  264. switch (CE->getOpcode()) {
  265. case Instruction::Add: {
  266. auto *LHS = findBaseObject(CE->getOperand(0), Aliases);
  267. auto *RHS = findBaseObject(CE->getOperand(1), Aliases);
  268. if (LHS && RHS)
  269. return nullptr;
  270. return LHS ? LHS : RHS;
  271. }
  272. case Instruction::Sub: {
  273. if (findBaseObject(CE->getOperand(1), Aliases))
  274. return nullptr;
  275. return findBaseObject(CE->getOperand(0), Aliases);
  276. }
  277. case Instruction::IntToPtr:
  278. case Instruction::PtrToInt:
  279. case Instruction::BitCast:
  280. case Instruction::GetElementPtr:
  281. return findBaseObject(CE->getOperand(0), Aliases);
  282. default:
  283. break;
  284. }
  285. }
  286. return nullptr;
  287. }
  288. const GlobalObject *GlobalValue::getAliaseeObject() const {
  289. DenseSet<const GlobalAlias *> Aliases;
  290. return findBaseObject(this, Aliases);
  291. }
  292. bool GlobalValue::isAbsoluteSymbolRef() const {
  293. auto *GO = dyn_cast<GlobalObject>(this);
  294. if (!GO)
  295. return false;
  296. return GO->getMetadata(LLVMContext::MD_absolute_symbol);
  297. }
  298. Optional<ConstantRange> GlobalValue::getAbsoluteSymbolRange() const {
  299. auto *GO = dyn_cast<GlobalObject>(this);
  300. if (!GO)
  301. return None;
  302. MDNode *MD = GO->getMetadata(LLVMContext::MD_absolute_symbol);
  303. if (!MD)
  304. return None;
  305. return getConstantRangeFromMetadata(*MD);
  306. }
  307. bool GlobalValue::canBeOmittedFromSymbolTable() const {
  308. if (!hasLinkOnceODRLinkage())
  309. return false;
  310. // We assume that anyone who sets global unnamed_addr on a non-constant
  311. // knows what they're doing.
  312. if (hasGlobalUnnamedAddr())
  313. return true;
  314. // If it is a non constant variable, it needs to be uniqued across shared
  315. // objects.
  316. if (auto *Var = dyn_cast<GlobalVariable>(this))
  317. if (!Var->isConstant())
  318. return false;
  319. return hasAtLeastLocalUnnamedAddr();
  320. }
  321. //===----------------------------------------------------------------------===//
  322. // GlobalVariable Implementation
  323. //===----------------------------------------------------------------------===//
  324. GlobalVariable::GlobalVariable(Type *Ty, bool constant, LinkageTypes Link,
  325. Constant *InitVal, const Twine &Name,
  326. ThreadLocalMode TLMode, unsigned AddressSpace,
  327. bool isExternallyInitialized)
  328. : GlobalObject(Ty, Value::GlobalVariableVal,
  329. OperandTraits<GlobalVariable>::op_begin(this),
  330. InitVal != nullptr, Link, Name, AddressSpace),
  331. isConstantGlobal(constant),
  332. isExternallyInitializedConstant(isExternallyInitialized) {
  333. assert(!Ty->isFunctionTy() && PointerType::isValidElementType(Ty) &&
  334. "invalid type for global variable");
  335. setThreadLocalMode(TLMode);
  336. if (InitVal) {
  337. assert(InitVal->getType() == Ty &&
  338. "Initializer should be the same type as the GlobalVariable!");
  339. Op<0>() = InitVal;
  340. }
  341. }
  342. GlobalVariable::GlobalVariable(Module &M, Type *Ty, bool constant,
  343. LinkageTypes Link, Constant *InitVal,
  344. const Twine &Name, GlobalVariable *Before,
  345. ThreadLocalMode TLMode,
  346. Optional<unsigned> AddressSpace,
  347. bool isExternallyInitialized)
  348. : GlobalObject(Ty, Value::GlobalVariableVal,
  349. OperandTraits<GlobalVariable>::op_begin(this),
  350. InitVal != nullptr, Link, Name,
  351. AddressSpace
  352. ? *AddressSpace
  353. : M.getDataLayout().getDefaultGlobalsAddressSpace()),
  354. isConstantGlobal(constant),
  355. isExternallyInitializedConstant(isExternallyInitialized) {
  356. assert(!Ty->isFunctionTy() && PointerType::isValidElementType(Ty) &&
  357. "invalid type for global variable");
  358. setThreadLocalMode(TLMode);
  359. if (InitVal) {
  360. assert(InitVal->getType() == Ty &&
  361. "Initializer should be the same type as the GlobalVariable!");
  362. Op<0>() = InitVal;
  363. }
  364. if (Before)
  365. Before->getParent()->getGlobalList().insert(Before->getIterator(), this);
  366. else
  367. M.getGlobalList().push_back(this);
  368. }
  369. void GlobalVariable::removeFromParent() {
  370. getParent()->getGlobalList().remove(getIterator());
  371. }
  372. void GlobalVariable::eraseFromParent() {
  373. getParent()->getGlobalList().erase(getIterator());
  374. }
  375. void GlobalVariable::setInitializer(Constant *InitVal) {
  376. if (!InitVal) {
  377. if (hasInitializer()) {
  378. // Note, the num operands is used to compute the offset of the operand, so
  379. // the order here matters. Clearing the operand then clearing the num
  380. // operands ensures we have the correct offset to the operand.
  381. Op<0>().set(nullptr);
  382. setGlobalVariableNumOperands(0);
  383. }
  384. } else {
  385. assert(InitVal->getType() == getValueType() &&
  386. "Initializer type must match GlobalVariable type");
  387. // Note, the num operands is used to compute the offset of the operand, so
  388. // the order here matters. We need to set num operands to 1 first so that
  389. // we get the correct offset to the first operand when we set it.
  390. if (!hasInitializer())
  391. setGlobalVariableNumOperands(1);
  392. Op<0>().set(InitVal);
  393. }
  394. }
  395. /// Copy all additional attributes (those not needed to create a GlobalVariable)
  396. /// from the GlobalVariable Src to this one.
  397. void GlobalVariable::copyAttributesFrom(const GlobalVariable *Src) {
  398. GlobalObject::copyAttributesFrom(Src);
  399. setExternallyInitialized(Src->isExternallyInitialized());
  400. setAttributes(Src->getAttributes());
  401. }
  402. void GlobalVariable::dropAllReferences() {
  403. User::dropAllReferences();
  404. clearMetadata();
  405. }
  406. //===----------------------------------------------------------------------===//
  407. // GlobalAlias Implementation
  408. //===----------------------------------------------------------------------===//
  409. GlobalAlias::GlobalAlias(Type *Ty, unsigned AddressSpace, LinkageTypes Link,
  410. const Twine &Name, Constant *Aliasee,
  411. Module *ParentModule)
  412. : GlobalValue(Ty, Value::GlobalAliasVal, &Op<0>(), 1, Link, Name,
  413. AddressSpace) {
  414. setAliasee(Aliasee);
  415. if (ParentModule)
  416. ParentModule->getAliasList().push_back(this);
  417. }
  418. GlobalAlias *GlobalAlias::create(Type *Ty, unsigned AddressSpace,
  419. LinkageTypes Link, const Twine &Name,
  420. Constant *Aliasee, Module *ParentModule) {
  421. return new GlobalAlias(Ty, AddressSpace, Link, Name, Aliasee, ParentModule);
  422. }
  423. GlobalAlias *GlobalAlias::create(Type *Ty, unsigned AddressSpace,
  424. LinkageTypes Linkage, const Twine &Name,
  425. Module *Parent) {
  426. return create(Ty, AddressSpace, Linkage, Name, nullptr, Parent);
  427. }
  428. GlobalAlias *GlobalAlias::create(Type *Ty, unsigned AddressSpace,
  429. LinkageTypes Linkage, const Twine &Name,
  430. GlobalValue *Aliasee) {
  431. return create(Ty, AddressSpace, Linkage, Name, Aliasee, Aliasee->getParent());
  432. }
  433. GlobalAlias *GlobalAlias::create(LinkageTypes Link, const Twine &Name,
  434. GlobalValue *Aliasee) {
  435. return create(Aliasee->getValueType(), Aliasee->getAddressSpace(), Link, Name,
  436. Aliasee);
  437. }
  438. GlobalAlias *GlobalAlias::create(const Twine &Name, GlobalValue *Aliasee) {
  439. return create(Aliasee->getLinkage(), Name, Aliasee);
  440. }
  441. void GlobalAlias::removeFromParent() {
  442. getParent()->getAliasList().remove(getIterator());
  443. }
  444. void GlobalAlias::eraseFromParent() {
  445. getParent()->getAliasList().erase(getIterator());
  446. }
  447. void GlobalAlias::setAliasee(Constant *Aliasee) {
  448. assert((!Aliasee || Aliasee->getType() == getType()) &&
  449. "Alias and aliasee types should match!");
  450. Op<0>().set(Aliasee);
  451. }
  452. const GlobalObject *GlobalAlias::getAliaseeObject() const {
  453. DenseSet<const GlobalAlias *> Aliases;
  454. return findBaseObject(getOperand(0), Aliases);
  455. }
  456. //===----------------------------------------------------------------------===//
  457. // GlobalIFunc Implementation
  458. //===----------------------------------------------------------------------===//
  459. GlobalIFunc::GlobalIFunc(Type *Ty, unsigned AddressSpace, LinkageTypes Link,
  460. const Twine &Name, Constant *Resolver,
  461. Module *ParentModule)
  462. : GlobalObject(Ty, Value::GlobalIFuncVal, &Op<0>(), 1, Link, Name,
  463. AddressSpace) {
  464. setResolver(Resolver);
  465. if (ParentModule)
  466. ParentModule->getIFuncList().push_back(this);
  467. }
  468. GlobalIFunc *GlobalIFunc::create(Type *Ty, unsigned AddressSpace,
  469. LinkageTypes Link, const Twine &Name,
  470. Constant *Resolver, Module *ParentModule) {
  471. return new GlobalIFunc(Ty, AddressSpace, Link, Name, Resolver, ParentModule);
  472. }
  473. void GlobalIFunc::removeFromParent() {
  474. getParent()->getIFuncList().remove(getIterator());
  475. }
  476. void GlobalIFunc::eraseFromParent() {
  477. getParent()->getIFuncList().erase(getIterator());
  478. }
  479. const Function *GlobalIFunc::getResolverFunction() const {
  480. DenseSet<const GlobalAlias *> Aliases;
  481. return dyn_cast<Function>(findBaseObject(getResolver(), Aliases));
  482. }