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