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