1 //===-- Function.cpp - Implement the Global object classes ----------------===// 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 Function class for the IR library. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "llvm/IR/Function.h" 15 #include "LLVMContextImpl.h" 16 #include "SymbolTableListTraitsImpl.h" 17 #include "llvm/ADT/DenseMap.h" 18 #include "llvm/ADT/STLExtras.h" 19 #include "llvm/ADT/StringExtras.h" 20 #include "llvm/CodeGen/ValueTypes.h" 21 #include "llvm/IR/CallSite.h" 22 #include "llvm/IR/Constants.h" 23 #include "llvm/IR/DerivedTypes.h" 24 #include "llvm/IR/InstIterator.h" 25 #include "llvm/IR/IntrinsicInst.h" 26 #include "llvm/IR/LLVMContext.h" 27 #include "llvm/IR/MDBuilder.h" 28 #include "llvm/IR/Metadata.h" 29 #include "llvm/IR/Module.h" 30 #include "llvm/Support/ManagedStatic.h" 31 #include "llvm/Support/RWMutex.h" 32 #include "llvm/Support/StringPool.h" 33 #include "llvm/Support/Threading.h" 34 using namespace llvm; 35 36 // Explicit instantiations of SymbolTableListTraits since some of the methods 37 // are not in the public header file... 38 template class llvm::SymbolTableListTraits<Argument>; 39 template class llvm::SymbolTableListTraits<BasicBlock>; 40 41 //===----------------------------------------------------------------------===// 42 // Argument Implementation 43 //===----------------------------------------------------------------------===// 44 45 void Argument::anchor() { } 46 47 Argument::Argument(Type *Ty, const Twine &Name, Function *Par) 48 : Value(Ty, Value::ArgumentVal) { 49 Parent = nullptr; 50 51 if (Par) 52 Par->getArgumentList().push_back(this); 53 setName(Name); 54 } 55 56 void Argument::setParent(Function *parent) { 57 Parent = parent; 58 } 59 60 /// getArgNo - Return the index of this formal argument in its containing 61 /// function. For example in "void foo(int a, float b)" a is 0 and b is 1. 62 unsigned Argument::getArgNo() const { 63 const Function *F = getParent(); 64 assert(F && "Argument is not in a function"); 65 66 Function::const_arg_iterator AI = F->arg_begin(); 67 unsigned ArgIdx = 0; 68 for (; &*AI != this; ++AI) 69 ++ArgIdx; 70 71 return ArgIdx; 72 } 73 74 /// hasNonNullAttr - Return true if this argument has the nonnull attribute on 75 /// it in its containing function. Also returns true if at least one byte is 76 /// known to be dereferenceable and the pointer is in addrspace(0). 77 bool Argument::hasNonNullAttr() const { 78 if (!getType()->isPointerTy()) return false; 79 if (getParent()->getAttributes(). 80 hasAttribute(getArgNo()+1, Attribute::NonNull)) 81 return true; 82 else if (getDereferenceableBytes() > 0 && 83 getType()->getPointerAddressSpace() == 0) 84 return true; 85 return false; 86 } 87 88 /// hasByValAttr - Return true if this argument has the byval attribute on it 89 /// in its containing function. 90 bool Argument::hasByValAttr() const { 91 if (!getType()->isPointerTy()) return false; 92 return hasAttribute(Attribute::ByVal); 93 } 94 95 /// \brief Return true if this argument has the inalloca attribute on it in 96 /// its containing function. 97 bool Argument::hasInAllocaAttr() const { 98 if (!getType()->isPointerTy()) return false; 99 return hasAttribute(Attribute::InAlloca); 100 } 101 102 bool Argument::hasByValOrInAllocaAttr() const { 103 if (!getType()->isPointerTy()) return false; 104 AttributeSet Attrs = getParent()->getAttributes(); 105 return Attrs.hasAttribute(getArgNo() + 1, Attribute::ByVal) || 106 Attrs.hasAttribute(getArgNo() + 1, Attribute::InAlloca); 107 } 108 109 unsigned Argument::getParamAlignment() const { 110 assert(getType()->isPointerTy() && "Only pointers have alignments"); 111 return getParent()->getParamAlignment(getArgNo()+1); 112 113 } 114 115 uint64_t Argument::getDereferenceableBytes() const { 116 assert(getType()->isPointerTy() && 117 "Only pointers have dereferenceable bytes"); 118 return getParent()->getDereferenceableBytes(getArgNo()+1); 119 } 120 121 uint64_t Argument::getDereferenceableOrNullBytes() const { 122 assert(getType()->isPointerTy() && 123 "Only pointers have dereferenceable bytes"); 124 return getParent()->getDereferenceableOrNullBytes(getArgNo()+1); 125 } 126 127 /// hasNestAttr - Return true if this argument has the nest attribute on 128 /// it in its containing function. 129 bool Argument::hasNestAttr() const { 130 if (!getType()->isPointerTy()) return false; 131 return hasAttribute(Attribute::Nest); 132 } 133 134 /// hasNoAliasAttr - Return true if this argument has the noalias attribute on 135 /// it in its containing function. 136 bool Argument::hasNoAliasAttr() const { 137 if (!getType()->isPointerTy()) return false; 138 return hasAttribute(Attribute::NoAlias); 139 } 140 141 /// hasNoCaptureAttr - Return true if this argument has the nocapture attribute 142 /// on it in its containing function. 143 bool Argument::hasNoCaptureAttr() const { 144 if (!getType()->isPointerTy()) return false; 145 return hasAttribute(Attribute::NoCapture); 146 } 147 148 /// hasSRetAttr - Return true if this argument has the sret attribute on 149 /// it in its containing function. 150 bool Argument::hasStructRetAttr() const { 151 if (!getType()->isPointerTy()) return false; 152 return hasAttribute(Attribute::StructRet); 153 } 154 155 /// hasReturnedAttr - Return true if this argument has the returned attribute on 156 /// it in its containing function. 157 bool Argument::hasReturnedAttr() const { 158 return hasAttribute(Attribute::Returned); 159 } 160 161 /// hasZExtAttr - Return true if this argument has the zext attribute on it in 162 /// its containing function. 163 bool Argument::hasZExtAttr() const { 164 return hasAttribute(Attribute::ZExt); 165 } 166 167 /// hasSExtAttr Return true if this argument has the sext attribute on it in its 168 /// containing function. 169 bool Argument::hasSExtAttr() const { 170 return hasAttribute(Attribute::SExt); 171 } 172 173 /// Return true if this argument has the readonly or readnone attribute on it 174 /// in its containing function. 175 bool Argument::onlyReadsMemory() const { 176 return getParent()->getAttributes(). 177 hasAttribute(getArgNo()+1, Attribute::ReadOnly) || 178 getParent()->getAttributes(). 179 hasAttribute(getArgNo()+1, Attribute::ReadNone); 180 } 181 182 /// addAttr - Add attributes to an argument. 183 void Argument::addAttr(AttributeSet AS) { 184 assert(AS.getNumSlots() <= 1 && 185 "Trying to add more than one attribute set to an argument!"); 186 AttrBuilder B(AS, AS.getSlotIndex(0)); 187 getParent()->addAttributes(getArgNo() + 1, 188 AttributeSet::get(Parent->getContext(), 189 getArgNo() + 1, B)); 190 } 191 192 /// removeAttr - Remove attributes from an argument. 193 void Argument::removeAttr(AttributeSet AS) { 194 assert(AS.getNumSlots() <= 1 && 195 "Trying to remove more than one attribute set from an argument!"); 196 AttrBuilder B(AS, AS.getSlotIndex(0)); 197 getParent()->removeAttributes(getArgNo() + 1, 198 AttributeSet::get(Parent->getContext(), 199 getArgNo() + 1, B)); 200 } 201 202 /// hasAttribute - Checks if an argument has a given attribute. 203 bool Argument::hasAttribute(Attribute::AttrKind Kind) const { 204 return getParent()->hasAttribute(getArgNo() + 1, Kind); 205 } 206 207 //===----------------------------------------------------------------------===// 208 // Helper Methods in Function 209 //===----------------------------------------------------------------------===// 210 211 bool Function::isMaterializable() const { 212 return getGlobalObjectSubClassData() & IsMaterializableBit; 213 } 214 215 void Function::setIsMaterializable(bool V) { 216 setGlobalObjectBit(IsMaterializableBit, V); 217 } 218 219 LLVMContext &Function::getContext() const { 220 return getType()->getContext(); 221 } 222 223 FunctionType *Function::getFunctionType() const { 224 return cast<FunctionType>(getValueType()); 225 } 226 227 bool Function::isVarArg() const { 228 return getFunctionType()->isVarArg(); 229 } 230 231 Type *Function::getReturnType() const { 232 return getFunctionType()->getReturnType(); 233 } 234 235 void Function::removeFromParent() { 236 getParent()->getFunctionList().remove(getIterator()); 237 } 238 239 void Function::eraseFromParent() { 240 getParent()->getFunctionList().erase(getIterator()); 241 } 242 243 //===----------------------------------------------------------------------===// 244 // Function Implementation 245 //===----------------------------------------------------------------------===// 246 247 Function::Function(FunctionType *Ty, LinkageTypes Linkage, const Twine &name, 248 Module *ParentModule) 249 : GlobalObject(Ty, Value::FunctionVal, 250 OperandTraits<Function>::op_begin(this), 0, Linkage, name) { 251 assert(FunctionType::isValidReturnType(getReturnType()) && 252 "invalid return type"); 253 setGlobalObjectSubClassData(0); 254 SymTab = new ValueSymbolTable(); 255 256 // If the function has arguments, mark them as lazily built. 257 if (Ty->getNumParams()) 258 setValueSubclassData(1); // Set the "has lazy arguments" bit. 259 260 if (ParentModule) 261 ParentModule->getFunctionList().push_back(this); 262 263 // Ensure intrinsics have the right parameter attributes. 264 // Note, the IntID field will have been set in Value::setName if this function 265 // name is a valid intrinsic ID. 266 if (IntID) 267 setAttributes(Intrinsic::getAttributes(getContext(), IntID)); 268 } 269 270 Function::~Function() { 271 dropAllReferences(); // After this it is safe to delete instructions. 272 273 // Delete all of the method arguments and unlink from symbol table... 274 ArgumentList.clear(); 275 delete SymTab; 276 277 // Remove the function from the on-the-side GC table. 278 clearGC(); 279 } 280 281 void Function::BuildLazyArguments() const { 282 // Create the arguments vector, all arguments start out unnamed. 283 FunctionType *FT = getFunctionType(); 284 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 285 assert(!FT->getParamType(i)->isVoidTy() && 286 "Cannot have void typed arguments!"); 287 ArgumentList.push_back(new Argument(FT->getParamType(i))); 288 } 289 290 // Clear the lazy arguments bit. 291 unsigned SDC = getSubclassDataFromValue(); 292 const_cast<Function*>(this)->setValueSubclassData(SDC &= ~(1<<0)); 293 } 294 295 size_t Function::arg_size() const { 296 return getFunctionType()->getNumParams(); 297 } 298 bool Function::arg_empty() const { 299 return getFunctionType()->getNumParams() == 0; 300 } 301 302 void Function::setParent(Module *parent) { 303 Parent = parent; 304 } 305 306 // dropAllReferences() - This function causes all the subinstructions to "let 307 // go" of all references that they are maintaining. This allows one to 308 // 'delete' a whole class at a time, even though there may be circular 309 // references... first all references are dropped, and all use counts go to 310 // zero. Then everything is deleted for real. Note that no operations are 311 // valid on an object that has "dropped all references", except operator 312 // delete. 313 // 314 void Function::dropAllReferences() { 315 setIsMaterializable(false); 316 317 for (iterator I = begin(), E = end(); I != E; ++I) 318 I->dropAllReferences(); 319 320 // Delete all basic blocks. They are now unused, except possibly by 321 // blockaddresses, but BasicBlock's destructor takes care of those. 322 while (!BasicBlocks.empty()) 323 BasicBlocks.begin()->eraseFromParent(); 324 325 // Drop uses of any optional data (real or placeholder). 326 if (getNumOperands()) { 327 User::dropAllReferences(); 328 setNumHungOffUseOperands(0); 329 setValueSubclassData(getSubclassDataFromValue() & ~0xe); 330 } 331 332 // Metadata is stored in a side-table. 333 clearMetadata(); 334 } 335 336 void Function::addAttribute(unsigned i, Attribute::AttrKind attr) { 337 AttributeSet PAL = getAttributes(); 338 PAL = PAL.addAttribute(getContext(), i, attr); 339 setAttributes(PAL); 340 } 341 342 void Function::addAttributes(unsigned i, AttributeSet attrs) { 343 AttributeSet PAL = getAttributes(); 344 PAL = PAL.addAttributes(getContext(), i, attrs); 345 setAttributes(PAL); 346 } 347 348 void Function::removeAttribute(unsigned i, Attribute::AttrKind attr) { 349 AttributeSet PAL = getAttributes(); 350 PAL = PAL.removeAttribute(getContext(), i, attr); 351 setAttributes(PAL); 352 } 353 354 void Function::removeAttributes(unsigned i, AttributeSet attrs) { 355 AttributeSet PAL = getAttributes(); 356 PAL = PAL.removeAttributes(getContext(), i, attrs); 357 setAttributes(PAL); 358 } 359 360 void Function::addDereferenceableAttr(unsigned i, uint64_t Bytes) { 361 AttributeSet PAL = getAttributes(); 362 PAL = PAL.addDereferenceableAttr(getContext(), i, Bytes); 363 setAttributes(PAL); 364 } 365 366 void Function::addDereferenceableOrNullAttr(unsigned i, uint64_t Bytes) { 367 AttributeSet PAL = getAttributes(); 368 PAL = PAL.addDereferenceableOrNullAttr(getContext(), i, Bytes); 369 setAttributes(PAL); 370 } 371 372 const std::string &Function::getGC() const { 373 assert(hasGC() && "Function has no collector"); 374 return getContext().getGC(*this); 375 } 376 377 void Function::setGC(const std::string Str) { 378 setValueSubclassDataBit(14, !Str.empty()); 379 getContext().setGC(*this, std::move(Str)); 380 } 381 382 void Function::clearGC() { 383 if (!hasGC()) 384 return; 385 getContext().deleteGC(*this); 386 setValueSubclassDataBit(14, false); 387 } 388 389 /// Copy all additional attributes (those not needed to create a Function) from 390 /// the Function Src to this one. 391 void Function::copyAttributesFrom(const GlobalValue *Src) { 392 GlobalObject::copyAttributesFrom(Src); 393 const Function *SrcF = dyn_cast<Function>(Src); 394 if (!SrcF) 395 return; 396 397 setCallingConv(SrcF->getCallingConv()); 398 setAttributes(SrcF->getAttributes()); 399 if (SrcF->hasGC()) 400 setGC(SrcF->getGC()); 401 else 402 clearGC(); 403 if (SrcF->hasPersonalityFn()) 404 setPersonalityFn(SrcF->getPersonalityFn()); 405 if (SrcF->hasPrefixData()) 406 setPrefixData(SrcF->getPrefixData()); 407 if (SrcF->hasPrologueData()) 408 setPrologueData(SrcF->getPrologueData()); 409 } 410 411 /// Table of string intrinsic names indexed by enum value. 412 static const char * const IntrinsicNameTable[] = { 413 "not_intrinsic", 414 #define GET_INTRINSIC_NAME_TABLE 415 #include "llvm/IR/Intrinsics.gen" 416 #undef GET_INTRINSIC_NAME_TABLE 417 }; 418 419 /// \brief This does the actual lookup of an intrinsic ID which 420 /// matches the given function name. 421 static Intrinsic::ID lookupIntrinsicID(const ValueName *ValName) { 422 StringRef Name = ValName->getKey(); 423 424 ArrayRef<const char *> NameTable(&IntrinsicNameTable[1], 425 std::end(IntrinsicNameTable)); 426 int Idx = Intrinsic::lookupLLVMIntrinsicByName(NameTable, Name); 427 Intrinsic::ID ID = static_cast<Intrinsic::ID>(Idx + 1); 428 if (ID == Intrinsic::not_intrinsic) 429 return ID; 430 431 // If the intrinsic is not overloaded, require an exact match. If it is 432 // overloaded, require a prefix match. 433 bool IsPrefixMatch = Name.size() > strlen(NameTable[Idx]); 434 return IsPrefixMatch == isOverloaded(ID) ? ID : Intrinsic::not_intrinsic; 435 } 436 437 void Function::recalculateIntrinsicID() { 438 const ValueName *ValName = this->getValueName(); 439 if (!ValName || !isIntrinsic()) { 440 IntID = Intrinsic::not_intrinsic; 441 return; 442 } 443 IntID = lookupIntrinsicID(ValName); 444 } 445 446 /// Returns a stable mangling for the type specified for use in the name 447 /// mangling scheme used by 'any' types in intrinsic signatures. The mangling 448 /// of named types is simply their name. Manglings for unnamed types consist 449 /// of a prefix ('p' for pointers, 'a' for arrays, 'f_' for functions) 450 /// combined with the mangling of their component types. A vararg function 451 /// type will have a suffix of 'vararg'. Since function types can contain 452 /// other function types, we close a function type mangling with suffix 'f' 453 /// which can't be confused with it's prefix. This ensures we don't have 454 /// collisions between two unrelated function types. Otherwise, you might 455 /// parse ffXX as f(fXX) or f(fX)X. (X is a placeholder for any other type.) 456 /// Manglings of integers, floats, and vectors ('i', 'f', and 'v' prefix in most 457 /// cases) fall back to the MVT codepath, where they could be mangled to 458 /// 'x86mmx', for example; matching on derived types is not sufficient to mangle 459 /// everything. 460 static std::string getMangledTypeStr(Type* Ty) { 461 std::string Result; 462 if (PointerType* PTyp = dyn_cast<PointerType>(Ty)) { 463 Result += "p" + llvm::utostr(PTyp->getAddressSpace()) + 464 getMangledTypeStr(PTyp->getElementType()); 465 } else if (ArrayType* ATyp = dyn_cast<ArrayType>(Ty)) { 466 Result += "a" + llvm::utostr(ATyp->getNumElements()) + 467 getMangledTypeStr(ATyp->getElementType()); 468 } else if (StructType* STyp = dyn_cast<StructType>(Ty)) { 469 assert(!STyp->isLiteral() && "TODO: implement literal types"); 470 Result += STyp->getName(); 471 } else if (FunctionType* FT = dyn_cast<FunctionType>(Ty)) { 472 Result += "f_" + getMangledTypeStr(FT->getReturnType()); 473 for (size_t i = 0; i < FT->getNumParams(); i++) 474 Result += getMangledTypeStr(FT->getParamType(i)); 475 if (FT->isVarArg()) 476 Result += "vararg"; 477 // Ensure nested function types are distinguishable. 478 Result += "f"; 479 } else if (isa<VectorType>(Ty)) 480 Result += "v" + utostr(Ty->getVectorNumElements()) + 481 getMangledTypeStr(Ty->getVectorElementType()); 482 else if (Ty) 483 Result += EVT::getEVT(Ty).getEVTString(); 484 return Result; 485 } 486 487 std::string Intrinsic::getName(ID id, ArrayRef<Type*> Tys) { 488 assert(id < num_intrinsics && "Invalid intrinsic ID!"); 489 if (Tys.empty()) 490 return IntrinsicNameTable[id]; 491 std::string Result(IntrinsicNameTable[id]); 492 for (unsigned i = 0; i < Tys.size(); ++i) { 493 Result += "." + getMangledTypeStr(Tys[i]); 494 } 495 return Result; 496 } 497 498 499 /// IIT_Info - These are enumerators that describe the entries returned by the 500 /// getIntrinsicInfoTableEntries function. 501 /// 502 /// NOTE: This must be kept in synch with the copy in TblGen/IntrinsicEmitter! 503 enum IIT_Info { 504 // Common values should be encoded with 0-15. 505 IIT_Done = 0, 506 IIT_I1 = 1, 507 IIT_I8 = 2, 508 IIT_I16 = 3, 509 IIT_I32 = 4, 510 IIT_I64 = 5, 511 IIT_F16 = 6, 512 IIT_F32 = 7, 513 IIT_F64 = 8, 514 IIT_V2 = 9, 515 IIT_V4 = 10, 516 IIT_V8 = 11, 517 IIT_V16 = 12, 518 IIT_V32 = 13, 519 IIT_PTR = 14, 520 IIT_ARG = 15, 521 522 // Values from 16+ are only encodable with the inefficient encoding. 523 IIT_V64 = 16, 524 IIT_MMX = 17, 525 IIT_TOKEN = 18, 526 IIT_METADATA = 19, 527 IIT_EMPTYSTRUCT = 20, 528 IIT_STRUCT2 = 21, 529 IIT_STRUCT3 = 22, 530 IIT_STRUCT4 = 23, 531 IIT_STRUCT5 = 24, 532 IIT_EXTEND_ARG = 25, 533 IIT_TRUNC_ARG = 26, 534 IIT_ANYPTR = 27, 535 IIT_V1 = 28, 536 IIT_VARARG = 29, 537 IIT_HALF_VEC_ARG = 30, 538 IIT_SAME_VEC_WIDTH_ARG = 31, 539 IIT_PTR_TO_ARG = 32, 540 IIT_VEC_OF_PTRS_TO_ELT = 33, 541 IIT_I128 = 34, 542 IIT_V512 = 35, 543 IIT_V1024 = 36 544 }; 545 546 547 static void DecodeIITType(unsigned &NextElt, ArrayRef<unsigned char> Infos, 548 SmallVectorImpl<Intrinsic::IITDescriptor> &OutputTable) { 549 IIT_Info Info = IIT_Info(Infos[NextElt++]); 550 unsigned StructElts = 2; 551 using namespace Intrinsic; 552 553 switch (Info) { 554 case IIT_Done: 555 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Void, 0)); 556 return; 557 case IIT_VARARG: 558 OutputTable.push_back(IITDescriptor::get(IITDescriptor::VarArg, 0)); 559 return; 560 case IIT_MMX: 561 OutputTable.push_back(IITDescriptor::get(IITDescriptor::MMX, 0)); 562 return; 563 case IIT_TOKEN: 564 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Token, 0)); 565 return; 566 case IIT_METADATA: 567 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Metadata, 0)); 568 return; 569 case IIT_F16: 570 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Half, 0)); 571 return; 572 case IIT_F32: 573 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Float, 0)); 574 return; 575 case IIT_F64: 576 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Double, 0)); 577 return; 578 case IIT_I1: 579 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 1)); 580 return; 581 case IIT_I8: 582 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 8)); 583 return; 584 case IIT_I16: 585 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer,16)); 586 return; 587 case IIT_I32: 588 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 32)); 589 return; 590 case IIT_I64: 591 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 64)); 592 return; 593 case IIT_I128: 594 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 128)); 595 return; 596 case IIT_V1: 597 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 1)); 598 DecodeIITType(NextElt, Infos, OutputTable); 599 return; 600 case IIT_V2: 601 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 2)); 602 DecodeIITType(NextElt, Infos, OutputTable); 603 return; 604 case IIT_V4: 605 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 4)); 606 DecodeIITType(NextElt, Infos, OutputTable); 607 return; 608 case IIT_V8: 609 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 8)); 610 DecodeIITType(NextElt, Infos, OutputTable); 611 return; 612 case IIT_V16: 613 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 16)); 614 DecodeIITType(NextElt, Infos, OutputTable); 615 return; 616 case IIT_V32: 617 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 32)); 618 DecodeIITType(NextElt, Infos, OutputTable); 619 return; 620 case IIT_V64: 621 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 64)); 622 DecodeIITType(NextElt, Infos, OutputTable); 623 return; 624 case IIT_V512: 625 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 512)); 626 DecodeIITType(NextElt, Infos, OutputTable); 627 return; 628 case IIT_V1024: 629 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 1024)); 630 DecodeIITType(NextElt, Infos, OutputTable); 631 return; 632 case IIT_PTR: 633 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Pointer, 0)); 634 DecodeIITType(NextElt, Infos, OutputTable); 635 return; 636 case IIT_ANYPTR: { // [ANYPTR addrspace, subtype] 637 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Pointer, 638 Infos[NextElt++])); 639 DecodeIITType(NextElt, Infos, OutputTable); 640 return; 641 } 642 case IIT_ARG: { 643 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]); 644 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Argument, ArgInfo)); 645 return; 646 } 647 case IIT_EXTEND_ARG: { 648 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]); 649 OutputTable.push_back(IITDescriptor::get(IITDescriptor::ExtendArgument, 650 ArgInfo)); 651 return; 652 } 653 case IIT_TRUNC_ARG: { 654 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]); 655 OutputTable.push_back(IITDescriptor::get(IITDescriptor::TruncArgument, 656 ArgInfo)); 657 return; 658 } 659 case IIT_HALF_VEC_ARG: { 660 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]); 661 OutputTable.push_back(IITDescriptor::get(IITDescriptor::HalfVecArgument, 662 ArgInfo)); 663 return; 664 } 665 case IIT_SAME_VEC_WIDTH_ARG: { 666 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]); 667 OutputTable.push_back(IITDescriptor::get(IITDescriptor::SameVecWidthArgument, 668 ArgInfo)); 669 return; 670 } 671 case IIT_PTR_TO_ARG: { 672 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]); 673 OutputTable.push_back(IITDescriptor::get(IITDescriptor::PtrToArgument, 674 ArgInfo)); 675 return; 676 } 677 case IIT_VEC_OF_PTRS_TO_ELT: { 678 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]); 679 OutputTable.push_back(IITDescriptor::get(IITDescriptor::VecOfPtrsToElt, 680 ArgInfo)); 681 return; 682 } 683 case IIT_EMPTYSTRUCT: 684 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Struct, 0)); 685 return; 686 case IIT_STRUCT5: ++StructElts; // FALL THROUGH. 687 case IIT_STRUCT4: ++StructElts; // FALL THROUGH. 688 case IIT_STRUCT3: ++StructElts; // FALL THROUGH. 689 case IIT_STRUCT2: { 690 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Struct,StructElts)); 691 692 for (unsigned i = 0; i != StructElts; ++i) 693 DecodeIITType(NextElt, Infos, OutputTable); 694 return; 695 } 696 } 697 llvm_unreachable("unhandled"); 698 } 699 700 701 #define GET_INTRINSIC_GENERATOR_GLOBAL 702 #include "llvm/IR/Intrinsics.gen" 703 #undef GET_INTRINSIC_GENERATOR_GLOBAL 704 705 void Intrinsic::getIntrinsicInfoTableEntries(ID id, 706 SmallVectorImpl<IITDescriptor> &T){ 707 // Check to see if the intrinsic's type was expressible by the table. 708 unsigned TableVal = IIT_Table[id-1]; 709 710 // Decode the TableVal into an array of IITValues. 711 SmallVector<unsigned char, 8> IITValues; 712 ArrayRef<unsigned char> IITEntries; 713 unsigned NextElt = 0; 714 if ((TableVal >> 31) != 0) { 715 // This is an offset into the IIT_LongEncodingTable. 716 IITEntries = IIT_LongEncodingTable; 717 718 // Strip sentinel bit. 719 NextElt = (TableVal << 1) >> 1; 720 } else { 721 // Decode the TableVal into an array of IITValues. If the entry was encoded 722 // into a single word in the table itself, decode it now. 723 do { 724 IITValues.push_back(TableVal & 0xF); 725 TableVal >>= 4; 726 } while (TableVal); 727 728 IITEntries = IITValues; 729 NextElt = 0; 730 } 731 732 // Okay, decode the table into the output vector of IITDescriptors. 733 DecodeIITType(NextElt, IITEntries, T); 734 while (NextElt != IITEntries.size() && IITEntries[NextElt] != 0) 735 DecodeIITType(NextElt, IITEntries, T); 736 } 737 738 739 static Type *DecodeFixedType(ArrayRef<Intrinsic::IITDescriptor> &Infos, 740 ArrayRef<Type*> Tys, LLVMContext &Context) { 741 using namespace Intrinsic; 742 IITDescriptor D = Infos.front(); 743 Infos = Infos.slice(1); 744 745 switch (D.Kind) { 746 case IITDescriptor::Void: return Type::getVoidTy(Context); 747 case IITDescriptor::VarArg: return Type::getVoidTy(Context); 748 case IITDescriptor::MMX: return Type::getX86_MMXTy(Context); 749 case IITDescriptor::Token: return Type::getTokenTy(Context); 750 case IITDescriptor::Metadata: return Type::getMetadataTy(Context); 751 case IITDescriptor::Half: return Type::getHalfTy(Context); 752 case IITDescriptor::Float: return Type::getFloatTy(Context); 753 case IITDescriptor::Double: return Type::getDoubleTy(Context); 754 755 case IITDescriptor::Integer: 756 return IntegerType::get(Context, D.Integer_Width); 757 case IITDescriptor::Vector: 758 return VectorType::get(DecodeFixedType(Infos, Tys, Context),D.Vector_Width); 759 case IITDescriptor::Pointer: 760 return PointerType::get(DecodeFixedType(Infos, Tys, Context), 761 D.Pointer_AddressSpace); 762 case IITDescriptor::Struct: { 763 Type *Elts[5]; 764 assert(D.Struct_NumElements <= 5 && "Can't handle this yet"); 765 for (unsigned i = 0, e = D.Struct_NumElements; i != e; ++i) 766 Elts[i] = DecodeFixedType(Infos, Tys, Context); 767 return StructType::get(Context, makeArrayRef(Elts,D.Struct_NumElements)); 768 } 769 770 case IITDescriptor::Argument: 771 return Tys[D.getArgumentNumber()]; 772 case IITDescriptor::ExtendArgument: { 773 Type *Ty = Tys[D.getArgumentNumber()]; 774 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) 775 return VectorType::getExtendedElementVectorType(VTy); 776 777 return IntegerType::get(Context, 2 * cast<IntegerType>(Ty)->getBitWidth()); 778 } 779 case IITDescriptor::TruncArgument: { 780 Type *Ty = Tys[D.getArgumentNumber()]; 781 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) 782 return VectorType::getTruncatedElementVectorType(VTy); 783 784 IntegerType *ITy = cast<IntegerType>(Ty); 785 assert(ITy->getBitWidth() % 2 == 0); 786 return IntegerType::get(Context, ITy->getBitWidth() / 2); 787 } 788 case IITDescriptor::HalfVecArgument: 789 return VectorType::getHalfElementsVectorType(cast<VectorType>( 790 Tys[D.getArgumentNumber()])); 791 case IITDescriptor::SameVecWidthArgument: { 792 Type *EltTy = DecodeFixedType(Infos, Tys, Context); 793 Type *Ty = Tys[D.getArgumentNumber()]; 794 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) { 795 return VectorType::get(EltTy, VTy->getNumElements()); 796 } 797 llvm_unreachable("unhandled"); 798 } 799 case IITDescriptor::PtrToArgument: { 800 Type *Ty = Tys[D.getArgumentNumber()]; 801 return PointerType::getUnqual(Ty); 802 } 803 case IITDescriptor::VecOfPtrsToElt: { 804 Type *Ty = Tys[D.getArgumentNumber()]; 805 VectorType *VTy = dyn_cast<VectorType>(Ty); 806 if (!VTy) 807 llvm_unreachable("Expected an argument of Vector Type"); 808 Type *EltTy = VTy->getVectorElementType(); 809 return VectorType::get(PointerType::getUnqual(EltTy), 810 VTy->getNumElements()); 811 } 812 } 813 llvm_unreachable("unhandled"); 814 } 815 816 817 818 FunctionType *Intrinsic::getType(LLVMContext &Context, 819 ID id, ArrayRef<Type*> Tys) { 820 SmallVector<IITDescriptor, 8> Table; 821 getIntrinsicInfoTableEntries(id, Table); 822 823 ArrayRef<IITDescriptor> TableRef = Table; 824 Type *ResultTy = DecodeFixedType(TableRef, Tys, Context); 825 826 SmallVector<Type*, 8> ArgTys; 827 while (!TableRef.empty()) 828 ArgTys.push_back(DecodeFixedType(TableRef, Tys, Context)); 829 830 // DecodeFixedType returns Void for IITDescriptor::Void and IITDescriptor::VarArg 831 // If we see void type as the type of the last argument, it is vararg intrinsic 832 if (!ArgTys.empty() && ArgTys.back()->isVoidTy()) { 833 ArgTys.pop_back(); 834 return FunctionType::get(ResultTy, ArgTys, true); 835 } 836 return FunctionType::get(ResultTy, ArgTys, false); 837 } 838 839 bool Intrinsic::isOverloaded(ID id) { 840 #define GET_INTRINSIC_OVERLOAD_TABLE 841 #include "llvm/IR/Intrinsics.gen" 842 #undef GET_INTRINSIC_OVERLOAD_TABLE 843 } 844 845 bool Intrinsic::isLeaf(ID id) { 846 switch (id) { 847 default: 848 return true; 849 850 case Intrinsic::experimental_gc_statepoint: 851 case Intrinsic::experimental_patchpoint_void: 852 case Intrinsic::experimental_patchpoint_i64: 853 return false; 854 } 855 } 856 857 /// This defines the "Intrinsic::getAttributes(ID id)" method. 858 #define GET_INTRINSIC_ATTRIBUTES 859 #include "llvm/IR/Intrinsics.gen" 860 #undef GET_INTRINSIC_ATTRIBUTES 861 862 Function *Intrinsic::getDeclaration(Module *M, ID id, ArrayRef<Type*> Tys) { 863 // There can never be multiple globals with the same name of different types, 864 // because intrinsics must be a specific type. 865 return 866 cast<Function>(M->getOrInsertFunction(getName(id, Tys), 867 getType(M->getContext(), id, Tys))); 868 } 869 870 // This defines the "Intrinsic::getIntrinsicForGCCBuiltin()" method. 871 #define GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN 872 #include "llvm/IR/Intrinsics.gen" 873 #undef GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN 874 875 // This defines the "Intrinsic::getIntrinsicForMSBuiltin()" method. 876 #define GET_LLVM_INTRINSIC_FOR_MS_BUILTIN 877 #include "llvm/IR/Intrinsics.gen" 878 #undef GET_LLVM_INTRINSIC_FOR_MS_BUILTIN 879 880 /// hasAddressTaken - returns true if there are any uses of this function 881 /// other than direct calls or invokes to it. 882 bool Function::hasAddressTaken(const User* *PutOffender) const { 883 for (const Use &U : uses()) { 884 const User *FU = U.getUser(); 885 if (isa<BlockAddress>(FU)) 886 continue; 887 if (!isa<CallInst>(FU) && !isa<InvokeInst>(FU)) { 888 if (PutOffender) 889 *PutOffender = FU; 890 return true; 891 } 892 ImmutableCallSite CS(cast<Instruction>(FU)); 893 if (!CS.isCallee(&U)) { 894 if (PutOffender) 895 *PutOffender = FU; 896 return true; 897 } 898 } 899 return false; 900 } 901 902 bool Function::isDefTriviallyDead() const { 903 // Check the linkage 904 if (!hasLinkOnceLinkage() && !hasLocalLinkage() && 905 !hasAvailableExternallyLinkage()) 906 return false; 907 908 // Check if the function is used by anything other than a blockaddress. 909 for (const User *U : users()) 910 if (!isa<BlockAddress>(U)) 911 return false; 912 913 return true; 914 } 915 916 /// callsFunctionThatReturnsTwice - Return true if the function has a call to 917 /// setjmp or other function that gcc recognizes as "returning twice". 918 bool Function::callsFunctionThatReturnsTwice() const { 919 for (const_inst_iterator 920 I = inst_begin(this), E = inst_end(this); I != E; ++I) { 921 ImmutableCallSite CS(&*I); 922 if (CS && CS.hasFnAttr(Attribute::ReturnsTwice)) 923 return true; 924 } 925 926 return false; 927 } 928 929 Constant *Function::getPersonalityFn() const { 930 assert(hasPersonalityFn() && getNumOperands()); 931 return cast<Constant>(Op<0>()); 932 } 933 934 void Function::setPersonalityFn(Constant *Fn) { 935 setHungoffOperand<0>(Fn); 936 setValueSubclassDataBit(3, Fn != nullptr); 937 } 938 939 Constant *Function::getPrefixData() const { 940 assert(hasPrefixData() && getNumOperands()); 941 return cast<Constant>(Op<1>()); 942 } 943 944 void Function::setPrefixData(Constant *PrefixData) { 945 setHungoffOperand<1>(PrefixData); 946 setValueSubclassDataBit(1, PrefixData != nullptr); 947 } 948 949 Constant *Function::getPrologueData() const { 950 assert(hasPrologueData() && getNumOperands()); 951 return cast<Constant>(Op<2>()); 952 } 953 954 void Function::setPrologueData(Constant *PrologueData) { 955 setHungoffOperand<2>(PrologueData); 956 setValueSubclassDataBit(2, PrologueData != nullptr); 957 } 958 959 void Function::allocHungoffUselist() { 960 // If we've already allocated a uselist, stop here. 961 if (getNumOperands()) 962 return; 963 964 allocHungoffUses(3, /*IsPhi=*/ false); 965 setNumHungOffUseOperands(3); 966 967 // Initialize the uselist with placeholder operands to allow traversal. 968 auto *CPN = ConstantPointerNull::get(Type::getInt1PtrTy(getContext(), 0)); 969 Op<0>().set(CPN); 970 Op<1>().set(CPN); 971 Op<2>().set(CPN); 972 } 973 974 template <int Idx> 975 void Function::setHungoffOperand(Constant *C) { 976 if (C) { 977 allocHungoffUselist(); 978 Op<Idx>().set(C); 979 } else if (getNumOperands()) { 980 Op<Idx>().set( 981 ConstantPointerNull::get(Type::getInt1PtrTy(getContext(), 0))); 982 } 983 } 984 985 void Function::setValueSubclassDataBit(unsigned Bit, bool On) { 986 assert(Bit < 16 && "SubclassData contains only 16 bits"); 987 if (On) 988 setValueSubclassData(getSubclassDataFromValue() | (1 << Bit)); 989 else 990 setValueSubclassData(getSubclassDataFromValue() & ~(1 << Bit)); 991 } 992 993 void Function::setEntryCount(uint64_t Count) { 994 MDBuilder MDB(getContext()); 995 setMetadata(LLVMContext::MD_prof, MDB.createFunctionEntryCount(Count)); 996 } 997 998 Optional<uint64_t> Function::getEntryCount() const { 999 MDNode *MD = getMetadata(LLVMContext::MD_prof); 1000 if (MD && MD->getOperand(0)) 1001 if (MDString *MDS = dyn_cast<MDString>(MD->getOperand(0))) 1002 if (MDS->getString().equals("function_entry_count")) { 1003 ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(1)); 1004 return CI->getValue().getZExtValue(); 1005 } 1006 return None; 1007 } 1008 1009 std::string Function::getGlobalIdentifier(StringRef FuncName, 1010 GlobalValue::LinkageTypes Linkage, 1011 StringRef FileName) { 1012 1013 // Function names may be prefixed with a binary '1' to indicate 1014 // that the backend should not modify the symbols due to any platform 1015 // naming convention. Do not include that '1' in the PGO profile name. 1016 if (FuncName[0] == '\1') 1017 FuncName = FuncName.substr(1); 1018 1019 std::string NewFuncName = FuncName; 1020 if (llvm::GlobalValue::isLocalLinkage(Linkage)) { 1021 // For local symbols, prepend the main file name to distinguish them. 1022 // Do not include the full path in the file name since there's no guarantee 1023 // that it will stay the same, e.g., if the files are checked out from 1024 // version control in different locations. 1025 if (FileName.empty()) 1026 NewFuncName = NewFuncName.insert(0, "<unknown>:"); 1027 else 1028 NewFuncName = NewFuncName.insert(0, FileName.str() + ":"); 1029 } 1030 return NewFuncName; 1031 } 1032