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/STLExtras.h" 18 #include "llvm/ADT/StringExtras.h" 19 #include "llvm/CodeGen/ValueTypes.h" 20 #include "llvm/IR/CallSite.h" 21 #include "llvm/IR/Constants.h" 22 #include "llvm/IR/DerivedTypes.h" 23 #include "llvm/IR/InstIterator.h" 24 #include "llvm/IR/IntrinsicInst.h" 25 #include "llvm/IR/LLVMContext.h" 26 #include "llvm/IR/MDBuilder.h" 27 #include "llvm/IR/Metadata.h" 28 #include "llvm/IR/Module.h" 29 using namespace llvm; 30 31 // Explicit instantiations of SymbolTableListTraits since some of the methods 32 // are not in the public header file... 33 template class llvm::SymbolTableListTraits<BasicBlock>; 34 35 //===----------------------------------------------------------------------===// 36 // Argument Implementation 37 //===----------------------------------------------------------------------===// 38 39 void Argument::anchor() { } 40 41 Argument::Argument(Type *Ty, const Twine &Name, Function *Par, unsigned ArgNo) 42 : Value(Ty, Value::ArgumentVal), Parent(Par), ArgNo(ArgNo) { 43 setName(Name); 44 } 45 46 void Argument::setParent(Function *parent) { 47 Parent = parent; 48 } 49 50 bool Argument::hasNonNullAttr() const { 51 if (!getType()->isPointerTy()) return false; 52 if (getParent()->getAttributes(). 53 hasAttribute(getArgNo()+1, Attribute::NonNull)) 54 return true; 55 else if (getDereferenceableBytes() > 0 && 56 getType()->getPointerAddressSpace() == 0) 57 return true; 58 return false; 59 } 60 61 bool Argument::hasByValAttr() const { 62 if (!getType()->isPointerTy()) return false; 63 return hasAttribute(Attribute::ByVal); 64 } 65 66 bool Argument::hasSwiftSelfAttr() const { 67 return getParent()->getAttributes(). 68 hasAttribute(getArgNo()+1, Attribute::SwiftSelf); 69 } 70 71 bool Argument::hasSwiftErrorAttr() const { 72 return getParent()->getAttributes(). 73 hasAttribute(getArgNo()+1, Attribute::SwiftError); 74 } 75 76 bool Argument::hasInAllocaAttr() const { 77 if (!getType()->isPointerTy()) return false; 78 return hasAttribute(Attribute::InAlloca); 79 } 80 81 bool Argument::hasByValOrInAllocaAttr() const { 82 if (!getType()->isPointerTy()) return false; 83 AttributeSet Attrs = getParent()->getAttributes(); 84 return Attrs.hasAttribute(getArgNo() + 1, Attribute::ByVal) || 85 Attrs.hasAttribute(getArgNo() + 1, Attribute::InAlloca); 86 } 87 88 unsigned Argument::getParamAlignment() const { 89 assert(getType()->isPointerTy() && "Only pointers have alignments"); 90 return getParent()->getParamAlignment(getArgNo()+1); 91 92 } 93 94 uint64_t Argument::getDereferenceableBytes() const { 95 assert(getType()->isPointerTy() && 96 "Only pointers have dereferenceable bytes"); 97 return getParent()->getDereferenceableBytes(getArgNo()+1); 98 } 99 100 uint64_t Argument::getDereferenceableOrNullBytes() const { 101 assert(getType()->isPointerTy() && 102 "Only pointers have dereferenceable bytes"); 103 return getParent()->getDereferenceableOrNullBytes(getArgNo()+1); 104 } 105 106 bool Argument::hasNestAttr() const { 107 if (!getType()->isPointerTy()) return false; 108 return hasAttribute(Attribute::Nest); 109 } 110 111 bool Argument::hasNoAliasAttr() const { 112 if (!getType()->isPointerTy()) return false; 113 return hasAttribute(Attribute::NoAlias); 114 } 115 116 bool Argument::hasNoCaptureAttr() const { 117 if (!getType()->isPointerTy()) return false; 118 return hasAttribute(Attribute::NoCapture); 119 } 120 121 bool Argument::hasStructRetAttr() const { 122 if (!getType()->isPointerTy()) return false; 123 return hasAttribute(Attribute::StructRet); 124 } 125 126 bool Argument::hasReturnedAttr() const { 127 return hasAttribute(Attribute::Returned); 128 } 129 130 bool Argument::hasZExtAttr() const { 131 return hasAttribute(Attribute::ZExt); 132 } 133 134 bool Argument::hasSExtAttr() const { 135 return hasAttribute(Attribute::SExt); 136 } 137 138 bool Argument::onlyReadsMemory() const { 139 return getParent()->getAttributes(). 140 hasAttribute(getArgNo()+1, Attribute::ReadOnly) || 141 getParent()->getAttributes(). 142 hasAttribute(getArgNo()+1, Attribute::ReadNone); 143 } 144 145 void Argument::addAttr(AttributeSet AS) { 146 assert(AS.getNumSlots() <= 1 && 147 "Trying to add more than one attribute set to an argument!"); 148 AttrBuilder B(AS, AS.getSlotIndex(0)); 149 getParent()->addAttributes(getArgNo() + 1, 150 AttributeSet::get(Parent->getContext(), 151 getArgNo() + 1, B)); 152 } 153 154 void Argument::removeAttr(AttributeSet AS) { 155 assert(AS.getNumSlots() <= 1 && 156 "Trying to remove more than one attribute set from an argument!"); 157 AttrBuilder B(AS, AS.getSlotIndex(0)); 158 getParent()->removeAttributes(getArgNo() + 1, 159 AttributeSet::get(Parent->getContext(), 160 getArgNo() + 1, B)); 161 } 162 163 bool Argument::hasAttribute(Attribute::AttrKind Kind) const { 164 return getParent()->hasAttribute(getArgNo() + 1, Kind); 165 } 166 167 //===----------------------------------------------------------------------===// 168 // Helper Methods in Function 169 //===----------------------------------------------------------------------===// 170 171 LLVMContext &Function::getContext() const { 172 return getType()->getContext(); 173 } 174 175 void Function::removeFromParent() { 176 getParent()->getFunctionList().remove(getIterator()); 177 } 178 179 void Function::eraseFromParent() { 180 getParent()->getFunctionList().erase(getIterator()); 181 } 182 183 //===----------------------------------------------------------------------===// 184 // Function Implementation 185 //===----------------------------------------------------------------------===// 186 187 Function::Function(FunctionType *Ty, LinkageTypes Linkage, const Twine &name, 188 Module *ParentModule) 189 : GlobalObject(Ty, Value::FunctionVal, 190 OperandTraits<Function>::op_begin(this), 0, Linkage, name), 191 Arguments(nullptr), NumArgs(Ty->getNumParams()) { 192 assert(FunctionType::isValidReturnType(getReturnType()) && 193 "invalid return type"); 194 setGlobalObjectSubClassData(0); 195 196 // We only need a symbol table for a function if the context keeps value names 197 if (!getContext().shouldDiscardValueNames()) 198 SymTab = make_unique<ValueSymbolTable>(); 199 200 // If the function has arguments, mark them as lazily built. 201 if (Ty->getNumParams()) 202 setValueSubclassData(1); // Set the "has lazy arguments" bit. 203 204 if (ParentModule) 205 ParentModule->getFunctionList().push_back(this); 206 207 HasLLVMReservedName = getName().startswith("llvm."); 208 // Ensure intrinsics have the right parameter attributes. 209 // Note, the IntID field will have been set in Value::setName if this function 210 // name is a valid intrinsic ID. 211 if (IntID) 212 setAttributes(Intrinsic::getAttributes(getContext(), IntID)); 213 } 214 215 Function::~Function() { 216 dropAllReferences(); // After this it is safe to delete instructions. 217 218 // Delete all of the method arguments and unlink from symbol table... 219 if (Arguments) 220 clearArguments(); 221 222 // Remove the function from the on-the-side GC table. 223 clearGC(); 224 } 225 226 void Function::BuildLazyArguments() const { 227 // Create the arguments vector, all arguments start out unnamed. 228 auto *FT = getFunctionType(); 229 if (NumArgs > 0) { 230 Arguments = std::allocator<Argument>().allocate(NumArgs); 231 for (unsigned i = 0, e = NumArgs; i != e; ++i) { 232 Type *ArgTy = FT->getParamType(i); 233 assert(!ArgTy->isVoidTy() && "Cannot have void typed arguments!"); 234 new (Arguments + i) Argument(ArgTy, "", const_cast<Function *>(this), i); 235 } 236 } 237 238 // Clear the lazy arguments bit. 239 unsigned SDC = getSubclassDataFromValue(); 240 const_cast<Function*>(this)->setValueSubclassData(SDC &= ~(1<<0)); 241 assert(!hasLazyArguments()); 242 } 243 244 static MutableArrayRef<Argument> makeArgArray(Argument *Args, size_t Count) { 245 return MutableArrayRef<Argument>(Args, Count); 246 } 247 248 void Function::clearArguments() { 249 for (Argument &A : makeArgArray(Arguments, NumArgs)) { 250 A.setName(""); 251 A.~Argument(); 252 } 253 std::allocator<Argument>().deallocate(Arguments, NumArgs); 254 Arguments = nullptr; 255 } 256 257 void Function::stealArgumentListFrom(Function &Src) { 258 assert(isDeclaration() && "Expected no references to current arguments"); 259 260 // Drop the current arguments, if any, and set the lazy argument bit. 261 if (!hasLazyArguments()) { 262 assert(llvm::all_of(makeArgArray(Arguments, NumArgs), 263 [](const Argument &A) { return A.use_empty(); }) && 264 "Expected arguments to be unused in declaration"); 265 clearArguments(); 266 setValueSubclassData(getSubclassDataFromValue() | (1 << 0)); 267 } 268 269 // Nothing to steal if Src has lazy arguments. 270 if (Src.hasLazyArguments()) 271 return; 272 273 // Steal arguments from Src, and fix the lazy argument bits. 274 assert(arg_size() == Src.arg_size()); 275 Arguments = Src.Arguments; 276 Src.Arguments = nullptr; 277 for (Argument &A : makeArgArray(Arguments, NumArgs)) { 278 // FIXME: This does the work of transferNodesFromList inefficiently. 279 SmallString<128> Name; 280 if (A.hasName()) 281 Name = A.getName(); 282 if (!Name.empty()) 283 A.setName(""); 284 A.setParent(this); 285 if (!Name.empty()) 286 A.setName(Name); 287 } 288 289 setValueSubclassData(getSubclassDataFromValue() & ~(1 << 0)); 290 assert(!hasLazyArguments()); 291 Src.setValueSubclassData(Src.getSubclassDataFromValue() | (1 << 0)); 292 } 293 294 // dropAllReferences() - This function causes all the subinstructions to "let 295 // go" of all references that they are maintaining. This allows one to 296 // 'delete' a whole class at a time, even though there may be circular 297 // references... first all references are dropped, and all use counts go to 298 // zero. Then everything is deleted for real. Note that no operations are 299 // valid on an object that has "dropped all references", except operator 300 // delete. 301 // 302 void Function::dropAllReferences() { 303 setIsMaterializable(false); 304 305 for (BasicBlock &BB : *this) 306 BB.dropAllReferences(); 307 308 // Delete all basic blocks. They are now unused, except possibly by 309 // blockaddresses, but BasicBlock's destructor takes care of those. 310 while (!BasicBlocks.empty()) 311 BasicBlocks.begin()->eraseFromParent(); 312 313 // Drop uses of any optional data (real or placeholder). 314 if (getNumOperands()) { 315 User::dropAllReferences(); 316 setNumHungOffUseOperands(0); 317 setValueSubclassData(getSubclassDataFromValue() & ~0xe); 318 } 319 320 // Metadata is stored in a side-table. 321 clearMetadata(); 322 } 323 324 void Function::addAttribute(unsigned i, Attribute::AttrKind Kind) { 325 AttributeSet PAL = getAttributes(); 326 PAL = PAL.addAttribute(getContext(), i, Kind); 327 setAttributes(PAL); 328 } 329 330 void Function::addAttribute(unsigned i, Attribute Attr) { 331 AttributeSet PAL = getAttributes(); 332 PAL = PAL.addAttribute(getContext(), i, Attr); 333 setAttributes(PAL); 334 } 335 336 void Function::addAttributes(unsigned i, AttributeSet Attrs) { 337 AttributeSet PAL = getAttributes(); 338 PAL = PAL.addAttributes(getContext(), i, Attrs); 339 setAttributes(PAL); 340 } 341 342 void Function::removeAttribute(unsigned i, Attribute::AttrKind Kind) { 343 AttributeSet PAL = getAttributes(); 344 PAL = PAL.removeAttribute(getContext(), i, Kind); 345 setAttributes(PAL); 346 } 347 348 void Function::removeAttribute(unsigned i, StringRef Kind) { 349 AttributeSet PAL = getAttributes(); 350 PAL = PAL.removeAttribute(getContext(), i, Kind); 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(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 /// Table of per-target intrinsic name tables. 420 #define GET_INTRINSIC_TARGET_DATA 421 #include "llvm/IR/Intrinsics.gen" 422 #undef GET_INTRINSIC_TARGET_DATA 423 424 /// Find the segment of \c IntrinsicNameTable for intrinsics with the same 425 /// target as \c Name, or the generic table if \c Name is not target specific. 426 /// 427 /// Returns the relevant slice of \c IntrinsicNameTable 428 static ArrayRef<const char *> findTargetSubtable(StringRef Name) { 429 assert(Name.startswith("llvm.")); 430 431 ArrayRef<IntrinsicTargetInfo> Targets(TargetInfos); 432 // Drop "llvm." and take the first dotted component. That will be the target 433 // if this is target specific. 434 StringRef Target = Name.drop_front(5).split('.').first; 435 auto It = std::lower_bound(Targets.begin(), Targets.end(), Target, 436 [](const IntrinsicTargetInfo &TI, 437 StringRef Target) { return TI.Name < Target; }); 438 // We've either found the target or just fall back to the generic set, which 439 // is always first. 440 const auto &TI = It != Targets.end() && It->Name == Target ? *It : Targets[0]; 441 return makeArrayRef(&IntrinsicNameTable[1] + TI.Offset, TI.Count); 442 } 443 444 /// \brief This does the actual lookup of an intrinsic ID which 445 /// matches the given function name. 446 Intrinsic::ID Function::lookupIntrinsicID(StringRef Name) { 447 ArrayRef<const char *> NameTable = findTargetSubtable(Name); 448 int Idx = Intrinsic::lookupLLVMIntrinsicByName(NameTable, Name); 449 if (Idx == -1) 450 return Intrinsic::not_intrinsic; 451 452 // Intrinsic IDs correspond to the location in IntrinsicNameTable, but we have 453 // an index into a sub-table. 454 int Adjust = NameTable.data() - IntrinsicNameTable; 455 Intrinsic::ID ID = static_cast<Intrinsic::ID>(Idx + Adjust); 456 457 // If the intrinsic is not overloaded, require an exact match. If it is 458 // overloaded, require a prefix match. 459 bool IsPrefixMatch = Name.size() > strlen(NameTable[Idx]); 460 return IsPrefixMatch == isOverloaded(ID) ? ID : Intrinsic::not_intrinsic; 461 } 462 463 void Function::recalculateIntrinsicID() { 464 StringRef Name = getName(); 465 if (!Name.startswith("llvm.")) { 466 HasLLVMReservedName = false; 467 IntID = Intrinsic::not_intrinsic; 468 return; 469 } 470 HasLLVMReservedName = true; 471 IntID = lookupIntrinsicID(Name); 472 } 473 474 /// Returns a stable mangling for the type specified for use in the name 475 /// mangling scheme used by 'any' types in intrinsic signatures. The mangling 476 /// of named types is simply their name. Manglings for unnamed types consist 477 /// of a prefix ('p' for pointers, 'a' for arrays, 'f_' for functions) 478 /// combined with the mangling of their component types. A vararg function 479 /// type will have a suffix of 'vararg'. Since function types can contain 480 /// other function types, we close a function type mangling with suffix 'f' 481 /// which can't be confused with it's prefix. This ensures we don't have 482 /// collisions between two unrelated function types. Otherwise, you might 483 /// parse ffXX as f(fXX) or f(fX)X. (X is a placeholder for any other type.) 484 /// Manglings of integers, floats, and vectors ('i', 'f', and 'v' prefix in most 485 /// cases) fall back to the MVT codepath, where they could be mangled to 486 /// 'x86mmx', for example; matching on derived types is not sufficient to mangle 487 /// everything. 488 static std::string getMangledTypeStr(Type* Ty) { 489 std::string Result; 490 if (PointerType* PTyp = dyn_cast<PointerType>(Ty)) { 491 Result += "p" + llvm::utostr(PTyp->getAddressSpace()) + 492 getMangledTypeStr(PTyp->getElementType()); 493 } else if (ArrayType* ATyp = dyn_cast<ArrayType>(Ty)) { 494 Result += "a" + llvm::utostr(ATyp->getNumElements()) + 495 getMangledTypeStr(ATyp->getElementType()); 496 } else if (StructType *STyp = dyn_cast<StructType>(Ty)) { 497 if (!STyp->isLiteral()) { 498 Result += "s_"; 499 Result += STyp->getName(); 500 } else { 501 Result += "sl_"; 502 for (auto Elem : STyp->elements()) 503 Result += getMangledTypeStr(Elem); 504 } 505 // Ensure nested structs are distinguishable. 506 Result += "s"; 507 } else if (FunctionType *FT = dyn_cast<FunctionType>(Ty)) { 508 Result += "f_" + getMangledTypeStr(FT->getReturnType()); 509 for (size_t i = 0; i < FT->getNumParams(); i++) 510 Result += getMangledTypeStr(FT->getParamType(i)); 511 if (FT->isVarArg()) 512 Result += "vararg"; 513 // Ensure nested function types are distinguishable. 514 Result += "f"; 515 } else if (isa<VectorType>(Ty)) 516 Result += "v" + utostr(Ty->getVectorNumElements()) + 517 getMangledTypeStr(Ty->getVectorElementType()); 518 else if (Ty) 519 Result += EVT::getEVT(Ty).getEVTString(); 520 return Result; 521 } 522 523 StringRef Intrinsic::getName(ID id) { 524 assert(id < num_intrinsics && "Invalid intrinsic ID!"); 525 assert(!isOverloaded(id) && 526 "This version of getName does not support overloading"); 527 return IntrinsicNameTable[id]; 528 } 529 530 std::string Intrinsic::getName(ID id, ArrayRef<Type*> Tys) { 531 assert(id < num_intrinsics && "Invalid intrinsic ID!"); 532 std::string Result(IntrinsicNameTable[id]); 533 for (Type *Ty : Tys) { 534 Result += "." + getMangledTypeStr(Ty); 535 } 536 return Result; 537 } 538 539 540 /// IIT_Info - These are enumerators that describe the entries returned by the 541 /// getIntrinsicInfoTableEntries function. 542 /// 543 /// NOTE: This must be kept in synch with the copy in TblGen/IntrinsicEmitter! 544 enum IIT_Info { 545 // Common values should be encoded with 0-15. 546 IIT_Done = 0, 547 IIT_I1 = 1, 548 IIT_I8 = 2, 549 IIT_I16 = 3, 550 IIT_I32 = 4, 551 IIT_I64 = 5, 552 IIT_F16 = 6, 553 IIT_F32 = 7, 554 IIT_F64 = 8, 555 IIT_V2 = 9, 556 IIT_V4 = 10, 557 IIT_V8 = 11, 558 IIT_V16 = 12, 559 IIT_V32 = 13, 560 IIT_PTR = 14, 561 IIT_ARG = 15, 562 563 // Values from 16+ are only encodable with the inefficient encoding. 564 IIT_V64 = 16, 565 IIT_MMX = 17, 566 IIT_TOKEN = 18, 567 IIT_METADATA = 19, 568 IIT_EMPTYSTRUCT = 20, 569 IIT_STRUCT2 = 21, 570 IIT_STRUCT3 = 22, 571 IIT_STRUCT4 = 23, 572 IIT_STRUCT5 = 24, 573 IIT_EXTEND_ARG = 25, 574 IIT_TRUNC_ARG = 26, 575 IIT_ANYPTR = 27, 576 IIT_V1 = 28, 577 IIT_VARARG = 29, 578 IIT_HALF_VEC_ARG = 30, 579 IIT_SAME_VEC_WIDTH_ARG = 31, 580 IIT_PTR_TO_ARG = 32, 581 IIT_PTR_TO_ELT = 33, 582 IIT_VEC_OF_PTRS_TO_ELT = 34, 583 IIT_I128 = 35, 584 IIT_V512 = 36, 585 IIT_V1024 = 37 586 }; 587 588 589 static void DecodeIITType(unsigned &NextElt, ArrayRef<unsigned char> Infos, 590 SmallVectorImpl<Intrinsic::IITDescriptor> &OutputTable) { 591 IIT_Info Info = IIT_Info(Infos[NextElt++]); 592 unsigned StructElts = 2; 593 using namespace Intrinsic; 594 595 switch (Info) { 596 case IIT_Done: 597 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Void, 0)); 598 return; 599 case IIT_VARARG: 600 OutputTable.push_back(IITDescriptor::get(IITDescriptor::VarArg, 0)); 601 return; 602 case IIT_MMX: 603 OutputTable.push_back(IITDescriptor::get(IITDescriptor::MMX, 0)); 604 return; 605 case IIT_TOKEN: 606 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Token, 0)); 607 return; 608 case IIT_METADATA: 609 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Metadata, 0)); 610 return; 611 case IIT_F16: 612 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Half, 0)); 613 return; 614 case IIT_F32: 615 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Float, 0)); 616 return; 617 case IIT_F64: 618 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Double, 0)); 619 return; 620 case IIT_I1: 621 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 1)); 622 return; 623 case IIT_I8: 624 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 8)); 625 return; 626 case IIT_I16: 627 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer,16)); 628 return; 629 case IIT_I32: 630 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 32)); 631 return; 632 case IIT_I64: 633 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 64)); 634 return; 635 case IIT_I128: 636 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 128)); 637 return; 638 case IIT_V1: 639 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 1)); 640 DecodeIITType(NextElt, Infos, OutputTable); 641 return; 642 case IIT_V2: 643 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 2)); 644 DecodeIITType(NextElt, Infos, OutputTable); 645 return; 646 case IIT_V4: 647 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 4)); 648 DecodeIITType(NextElt, Infos, OutputTable); 649 return; 650 case IIT_V8: 651 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 8)); 652 DecodeIITType(NextElt, Infos, OutputTable); 653 return; 654 case IIT_V16: 655 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 16)); 656 DecodeIITType(NextElt, Infos, OutputTable); 657 return; 658 case IIT_V32: 659 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 32)); 660 DecodeIITType(NextElt, Infos, OutputTable); 661 return; 662 case IIT_V64: 663 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 64)); 664 DecodeIITType(NextElt, Infos, OutputTable); 665 return; 666 case IIT_V512: 667 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 512)); 668 DecodeIITType(NextElt, Infos, OutputTable); 669 return; 670 case IIT_V1024: 671 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 1024)); 672 DecodeIITType(NextElt, Infos, OutputTable); 673 return; 674 case IIT_PTR: 675 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Pointer, 0)); 676 DecodeIITType(NextElt, Infos, OutputTable); 677 return; 678 case IIT_ANYPTR: { // [ANYPTR addrspace, subtype] 679 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Pointer, 680 Infos[NextElt++])); 681 DecodeIITType(NextElt, Infos, OutputTable); 682 return; 683 } 684 case IIT_ARG: { 685 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]); 686 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Argument, ArgInfo)); 687 return; 688 } 689 case IIT_EXTEND_ARG: { 690 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]); 691 OutputTable.push_back(IITDescriptor::get(IITDescriptor::ExtendArgument, 692 ArgInfo)); 693 return; 694 } 695 case IIT_TRUNC_ARG: { 696 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]); 697 OutputTable.push_back(IITDescriptor::get(IITDescriptor::TruncArgument, 698 ArgInfo)); 699 return; 700 } 701 case IIT_HALF_VEC_ARG: { 702 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]); 703 OutputTable.push_back(IITDescriptor::get(IITDescriptor::HalfVecArgument, 704 ArgInfo)); 705 return; 706 } 707 case IIT_SAME_VEC_WIDTH_ARG: { 708 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]); 709 OutputTable.push_back(IITDescriptor::get(IITDescriptor::SameVecWidthArgument, 710 ArgInfo)); 711 return; 712 } 713 case IIT_PTR_TO_ARG: { 714 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]); 715 OutputTable.push_back(IITDescriptor::get(IITDescriptor::PtrToArgument, 716 ArgInfo)); 717 return; 718 } 719 case IIT_PTR_TO_ELT: { 720 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]); 721 OutputTable.push_back(IITDescriptor::get(IITDescriptor::PtrToElt, ArgInfo)); 722 return; 723 } 724 case IIT_VEC_OF_PTRS_TO_ELT: { 725 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]); 726 OutputTable.push_back(IITDescriptor::get(IITDescriptor::VecOfPtrsToElt, 727 ArgInfo)); 728 return; 729 } 730 case IIT_EMPTYSTRUCT: 731 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Struct, 0)); 732 return; 733 case IIT_STRUCT5: ++StructElts; LLVM_FALLTHROUGH; 734 case IIT_STRUCT4: ++StructElts; LLVM_FALLTHROUGH; 735 case IIT_STRUCT3: ++StructElts; LLVM_FALLTHROUGH; 736 case IIT_STRUCT2: { 737 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Struct,StructElts)); 738 739 for (unsigned i = 0; i != StructElts; ++i) 740 DecodeIITType(NextElt, Infos, OutputTable); 741 return; 742 } 743 } 744 llvm_unreachable("unhandled"); 745 } 746 747 748 #define GET_INTRINSIC_GENERATOR_GLOBAL 749 #include "llvm/IR/Intrinsics.gen" 750 #undef GET_INTRINSIC_GENERATOR_GLOBAL 751 752 void Intrinsic::getIntrinsicInfoTableEntries(ID id, 753 SmallVectorImpl<IITDescriptor> &T){ 754 // Check to see if the intrinsic's type was expressible by the table. 755 unsigned TableVal = IIT_Table[id-1]; 756 757 // Decode the TableVal into an array of IITValues. 758 SmallVector<unsigned char, 8> IITValues; 759 ArrayRef<unsigned char> IITEntries; 760 unsigned NextElt = 0; 761 if ((TableVal >> 31) != 0) { 762 // This is an offset into the IIT_LongEncodingTable. 763 IITEntries = IIT_LongEncodingTable; 764 765 // Strip sentinel bit. 766 NextElt = (TableVal << 1) >> 1; 767 } else { 768 // Decode the TableVal into an array of IITValues. If the entry was encoded 769 // into a single word in the table itself, decode it now. 770 do { 771 IITValues.push_back(TableVal & 0xF); 772 TableVal >>= 4; 773 } while (TableVal); 774 775 IITEntries = IITValues; 776 NextElt = 0; 777 } 778 779 // Okay, decode the table into the output vector of IITDescriptors. 780 DecodeIITType(NextElt, IITEntries, T); 781 while (NextElt != IITEntries.size() && IITEntries[NextElt] != 0) 782 DecodeIITType(NextElt, IITEntries, T); 783 } 784 785 786 static Type *DecodeFixedType(ArrayRef<Intrinsic::IITDescriptor> &Infos, 787 ArrayRef<Type*> Tys, LLVMContext &Context) { 788 using namespace Intrinsic; 789 IITDescriptor D = Infos.front(); 790 Infos = Infos.slice(1); 791 792 switch (D.Kind) { 793 case IITDescriptor::Void: return Type::getVoidTy(Context); 794 case IITDescriptor::VarArg: return Type::getVoidTy(Context); 795 case IITDescriptor::MMX: return Type::getX86_MMXTy(Context); 796 case IITDescriptor::Token: return Type::getTokenTy(Context); 797 case IITDescriptor::Metadata: return Type::getMetadataTy(Context); 798 case IITDescriptor::Half: return Type::getHalfTy(Context); 799 case IITDescriptor::Float: return Type::getFloatTy(Context); 800 case IITDescriptor::Double: return Type::getDoubleTy(Context); 801 802 case IITDescriptor::Integer: 803 return IntegerType::get(Context, D.Integer_Width); 804 case IITDescriptor::Vector: 805 return VectorType::get(DecodeFixedType(Infos, Tys, Context),D.Vector_Width); 806 case IITDescriptor::Pointer: 807 return PointerType::get(DecodeFixedType(Infos, Tys, Context), 808 D.Pointer_AddressSpace); 809 case IITDescriptor::Struct: { 810 Type *Elts[5]; 811 assert(D.Struct_NumElements <= 5 && "Can't handle this yet"); 812 for (unsigned i = 0, e = D.Struct_NumElements; i != e; ++i) 813 Elts[i] = DecodeFixedType(Infos, Tys, Context); 814 return StructType::get(Context, makeArrayRef(Elts,D.Struct_NumElements)); 815 } 816 817 case IITDescriptor::Argument: 818 return Tys[D.getArgumentNumber()]; 819 case IITDescriptor::ExtendArgument: { 820 Type *Ty = Tys[D.getArgumentNumber()]; 821 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) 822 return VectorType::getExtendedElementVectorType(VTy); 823 824 return IntegerType::get(Context, 2 * cast<IntegerType>(Ty)->getBitWidth()); 825 } 826 case IITDescriptor::TruncArgument: { 827 Type *Ty = Tys[D.getArgumentNumber()]; 828 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) 829 return VectorType::getTruncatedElementVectorType(VTy); 830 831 IntegerType *ITy = cast<IntegerType>(Ty); 832 assert(ITy->getBitWidth() % 2 == 0); 833 return IntegerType::get(Context, ITy->getBitWidth() / 2); 834 } 835 case IITDescriptor::HalfVecArgument: 836 return VectorType::getHalfElementsVectorType(cast<VectorType>( 837 Tys[D.getArgumentNumber()])); 838 case IITDescriptor::SameVecWidthArgument: { 839 Type *EltTy = DecodeFixedType(Infos, Tys, Context); 840 Type *Ty = Tys[D.getArgumentNumber()]; 841 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) { 842 return VectorType::get(EltTy, VTy->getNumElements()); 843 } 844 llvm_unreachable("unhandled"); 845 } 846 case IITDescriptor::PtrToArgument: { 847 Type *Ty = Tys[D.getArgumentNumber()]; 848 return PointerType::getUnqual(Ty); 849 } 850 case IITDescriptor::PtrToElt: { 851 Type *Ty = Tys[D.getArgumentNumber()]; 852 VectorType *VTy = dyn_cast<VectorType>(Ty); 853 if (!VTy) 854 llvm_unreachable("Expected an argument of Vector Type"); 855 Type *EltTy = VTy->getVectorElementType(); 856 return PointerType::getUnqual(EltTy); 857 } 858 case IITDescriptor::VecOfPtrsToElt: { 859 Type *Ty = Tys[D.getArgumentNumber()]; 860 VectorType *VTy = dyn_cast<VectorType>(Ty); 861 if (!VTy) 862 llvm_unreachable("Expected an argument of Vector Type"); 863 Type *EltTy = VTy->getVectorElementType(); 864 return VectorType::get(PointerType::getUnqual(EltTy), 865 VTy->getNumElements()); 866 } 867 } 868 llvm_unreachable("unhandled"); 869 } 870 871 872 873 FunctionType *Intrinsic::getType(LLVMContext &Context, 874 ID id, ArrayRef<Type*> Tys) { 875 SmallVector<IITDescriptor, 8> Table; 876 getIntrinsicInfoTableEntries(id, Table); 877 878 ArrayRef<IITDescriptor> TableRef = Table; 879 Type *ResultTy = DecodeFixedType(TableRef, Tys, Context); 880 881 SmallVector<Type*, 8> ArgTys; 882 while (!TableRef.empty()) 883 ArgTys.push_back(DecodeFixedType(TableRef, Tys, Context)); 884 885 // DecodeFixedType returns Void for IITDescriptor::Void and IITDescriptor::VarArg 886 // If we see void type as the type of the last argument, it is vararg intrinsic 887 if (!ArgTys.empty() && ArgTys.back()->isVoidTy()) { 888 ArgTys.pop_back(); 889 return FunctionType::get(ResultTy, ArgTys, true); 890 } 891 return FunctionType::get(ResultTy, ArgTys, false); 892 } 893 894 bool Intrinsic::isOverloaded(ID id) { 895 #define GET_INTRINSIC_OVERLOAD_TABLE 896 #include "llvm/IR/Intrinsics.gen" 897 #undef GET_INTRINSIC_OVERLOAD_TABLE 898 } 899 900 bool Intrinsic::isLeaf(ID id) { 901 switch (id) { 902 default: 903 return true; 904 905 case Intrinsic::experimental_gc_statepoint: 906 case Intrinsic::experimental_patchpoint_void: 907 case Intrinsic::experimental_patchpoint_i64: 908 return false; 909 } 910 } 911 912 /// This defines the "Intrinsic::getAttributes(ID id)" method. 913 #define GET_INTRINSIC_ATTRIBUTES 914 #include "llvm/IR/Intrinsics.gen" 915 #undef GET_INTRINSIC_ATTRIBUTES 916 917 Function *Intrinsic::getDeclaration(Module *M, ID id, ArrayRef<Type*> Tys) { 918 // There can never be multiple globals with the same name of different types, 919 // because intrinsics must be a specific type. 920 return 921 cast<Function>(M->getOrInsertFunction(getName(id, Tys), 922 getType(M->getContext(), id, Tys))); 923 } 924 925 // This defines the "Intrinsic::getIntrinsicForGCCBuiltin()" method. 926 #define GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN 927 #include "llvm/IR/Intrinsics.gen" 928 #undef GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN 929 930 // This defines the "Intrinsic::getIntrinsicForMSBuiltin()" method. 931 #define GET_LLVM_INTRINSIC_FOR_MS_BUILTIN 932 #include "llvm/IR/Intrinsics.gen" 933 #undef GET_LLVM_INTRINSIC_FOR_MS_BUILTIN 934 935 bool Intrinsic::matchIntrinsicType(Type *Ty, ArrayRef<Intrinsic::IITDescriptor> &Infos, 936 SmallVectorImpl<Type*> &ArgTys) { 937 using namespace Intrinsic; 938 939 // If we ran out of descriptors, there are too many arguments. 940 if (Infos.empty()) return true; 941 IITDescriptor D = Infos.front(); 942 Infos = Infos.slice(1); 943 944 switch (D.Kind) { 945 case IITDescriptor::Void: return !Ty->isVoidTy(); 946 case IITDescriptor::VarArg: return true; 947 case IITDescriptor::MMX: return !Ty->isX86_MMXTy(); 948 case IITDescriptor::Token: return !Ty->isTokenTy(); 949 case IITDescriptor::Metadata: return !Ty->isMetadataTy(); 950 case IITDescriptor::Half: return !Ty->isHalfTy(); 951 case IITDescriptor::Float: return !Ty->isFloatTy(); 952 case IITDescriptor::Double: return !Ty->isDoubleTy(); 953 case IITDescriptor::Integer: return !Ty->isIntegerTy(D.Integer_Width); 954 case IITDescriptor::Vector: { 955 VectorType *VT = dyn_cast<VectorType>(Ty); 956 return !VT || VT->getNumElements() != D.Vector_Width || 957 matchIntrinsicType(VT->getElementType(), Infos, ArgTys); 958 } 959 case IITDescriptor::Pointer: { 960 PointerType *PT = dyn_cast<PointerType>(Ty); 961 return !PT || PT->getAddressSpace() != D.Pointer_AddressSpace || 962 matchIntrinsicType(PT->getElementType(), Infos, ArgTys); 963 } 964 965 case IITDescriptor::Struct: { 966 StructType *ST = dyn_cast<StructType>(Ty); 967 if (!ST || ST->getNumElements() != D.Struct_NumElements) 968 return true; 969 970 for (unsigned i = 0, e = D.Struct_NumElements; i != e; ++i) 971 if (matchIntrinsicType(ST->getElementType(i), Infos, ArgTys)) 972 return true; 973 return false; 974 } 975 976 case IITDescriptor::Argument: 977 // Two cases here - If this is the second occurrence of an argument, verify 978 // that the later instance matches the previous instance. 979 if (D.getArgumentNumber() < ArgTys.size()) 980 return Ty != ArgTys[D.getArgumentNumber()]; 981 982 // Otherwise, if this is the first instance of an argument, record it and 983 // verify the "Any" kind. 984 assert(D.getArgumentNumber() == ArgTys.size() && "Table consistency error"); 985 ArgTys.push_back(Ty); 986 987 switch (D.getArgumentKind()) { 988 case IITDescriptor::AK_Any: return false; // Success 989 case IITDescriptor::AK_AnyInteger: return !Ty->isIntOrIntVectorTy(); 990 case IITDescriptor::AK_AnyFloat: return !Ty->isFPOrFPVectorTy(); 991 case IITDescriptor::AK_AnyVector: return !isa<VectorType>(Ty); 992 case IITDescriptor::AK_AnyPointer: return !isa<PointerType>(Ty); 993 } 994 llvm_unreachable("all argument kinds not covered"); 995 996 case IITDescriptor::ExtendArgument: { 997 // This may only be used when referring to a previous vector argument. 998 if (D.getArgumentNumber() >= ArgTys.size()) 999 return true; 1000 1001 Type *NewTy = ArgTys[D.getArgumentNumber()]; 1002 if (VectorType *VTy = dyn_cast<VectorType>(NewTy)) 1003 NewTy = VectorType::getExtendedElementVectorType(VTy); 1004 else if (IntegerType *ITy = dyn_cast<IntegerType>(NewTy)) 1005 NewTy = IntegerType::get(ITy->getContext(), 2 * ITy->getBitWidth()); 1006 else 1007 return true; 1008 1009 return Ty != NewTy; 1010 } 1011 case IITDescriptor::TruncArgument: { 1012 // This may only be used when referring to a previous vector argument. 1013 if (D.getArgumentNumber() >= ArgTys.size()) 1014 return true; 1015 1016 Type *NewTy = ArgTys[D.getArgumentNumber()]; 1017 if (VectorType *VTy = dyn_cast<VectorType>(NewTy)) 1018 NewTy = VectorType::getTruncatedElementVectorType(VTy); 1019 else if (IntegerType *ITy = dyn_cast<IntegerType>(NewTy)) 1020 NewTy = IntegerType::get(ITy->getContext(), ITy->getBitWidth() / 2); 1021 else 1022 return true; 1023 1024 return Ty != NewTy; 1025 } 1026 case IITDescriptor::HalfVecArgument: 1027 // This may only be used when referring to a previous vector argument. 1028 return D.getArgumentNumber() >= ArgTys.size() || 1029 !isa<VectorType>(ArgTys[D.getArgumentNumber()]) || 1030 VectorType::getHalfElementsVectorType( 1031 cast<VectorType>(ArgTys[D.getArgumentNumber()])) != Ty; 1032 case IITDescriptor::SameVecWidthArgument: { 1033 if (D.getArgumentNumber() >= ArgTys.size()) 1034 return true; 1035 VectorType * ReferenceType = 1036 dyn_cast<VectorType>(ArgTys[D.getArgumentNumber()]); 1037 VectorType *ThisArgType = dyn_cast<VectorType>(Ty); 1038 if (!ThisArgType || !ReferenceType || 1039 (ReferenceType->getVectorNumElements() != 1040 ThisArgType->getVectorNumElements())) 1041 return true; 1042 return matchIntrinsicType(ThisArgType->getVectorElementType(), 1043 Infos, ArgTys); 1044 } 1045 case IITDescriptor::PtrToArgument: { 1046 if (D.getArgumentNumber() >= ArgTys.size()) 1047 return true; 1048 Type * ReferenceType = ArgTys[D.getArgumentNumber()]; 1049 PointerType *ThisArgType = dyn_cast<PointerType>(Ty); 1050 return (!ThisArgType || ThisArgType->getElementType() != ReferenceType); 1051 } 1052 case IITDescriptor::PtrToElt: { 1053 if (D.getArgumentNumber() >= ArgTys.size()) 1054 return true; 1055 VectorType * ReferenceType = 1056 dyn_cast<VectorType> (ArgTys[D.getArgumentNumber()]); 1057 PointerType *ThisArgType = dyn_cast<PointerType>(Ty); 1058 1059 return (!ThisArgType || !ReferenceType || 1060 ThisArgType->getElementType() != ReferenceType->getElementType()); 1061 } 1062 case IITDescriptor::VecOfPtrsToElt: { 1063 if (D.getArgumentNumber() >= ArgTys.size()) 1064 return true; 1065 VectorType * ReferenceType = 1066 dyn_cast<VectorType> (ArgTys[D.getArgumentNumber()]); 1067 VectorType *ThisArgVecTy = dyn_cast<VectorType>(Ty); 1068 if (!ThisArgVecTy || !ReferenceType || 1069 (ReferenceType->getVectorNumElements() != 1070 ThisArgVecTy->getVectorNumElements())) 1071 return true; 1072 PointerType *ThisArgEltTy = 1073 dyn_cast<PointerType>(ThisArgVecTy->getVectorElementType()); 1074 if (!ThisArgEltTy) 1075 return true; 1076 return ThisArgEltTy->getElementType() != 1077 ReferenceType->getVectorElementType(); 1078 } 1079 } 1080 llvm_unreachable("unhandled"); 1081 } 1082 1083 bool 1084 Intrinsic::matchIntrinsicVarArg(bool isVarArg, 1085 ArrayRef<Intrinsic::IITDescriptor> &Infos) { 1086 // If there are no descriptors left, then it can't be a vararg. 1087 if (Infos.empty()) 1088 return isVarArg; 1089 1090 // There should be only one descriptor remaining at this point. 1091 if (Infos.size() != 1) 1092 return true; 1093 1094 // Check and verify the descriptor. 1095 IITDescriptor D = Infos.front(); 1096 Infos = Infos.slice(1); 1097 if (D.Kind == IITDescriptor::VarArg) 1098 return !isVarArg; 1099 1100 return true; 1101 } 1102 1103 Optional<Function*> Intrinsic::remangleIntrinsicFunction(Function *F) { 1104 Intrinsic::ID ID = F->getIntrinsicID(); 1105 if (!ID) 1106 return None; 1107 1108 FunctionType *FTy = F->getFunctionType(); 1109 // Accumulate an array of overloaded types for the given intrinsic 1110 SmallVector<Type *, 4> ArgTys; 1111 { 1112 SmallVector<Intrinsic::IITDescriptor, 8> Table; 1113 getIntrinsicInfoTableEntries(ID, Table); 1114 ArrayRef<Intrinsic::IITDescriptor> TableRef = Table; 1115 1116 // If we encounter any problems matching the signature with the descriptor 1117 // just give up remangling. It's up to verifier to report the discrepancy. 1118 if (Intrinsic::matchIntrinsicType(FTy->getReturnType(), TableRef, ArgTys)) 1119 return None; 1120 for (auto Ty : FTy->params()) 1121 if (Intrinsic::matchIntrinsicType(Ty, TableRef, ArgTys)) 1122 return None; 1123 if (Intrinsic::matchIntrinsicVarArg(FTy->isVarArg(), TableRef)) 1124 return None; 1125 } 1126 1127 StringRef Name = F->getName(); 1128 if (Name == Intrinsic::getName(ID, ArgTys)) 1129 return None; 1130 1131 auto NewDecl = Intrinsic::getDeclaration(F->getParent(), ID, ArgTys); 1132 NewDecl->setCallingConv(F->getCallingConv()); 1133 assert(NewDecl->getFunctionType() == FTy && "Shouldn't change the signature"); 1134 return NewDecl; 1135 } 1136 1137 /// hasAddressTaken - returns true if there are any uses of this function 1138 /// other than direct calls or invokes to it. 1139 bool Function::hasAddressTaken(const User* *PutOffender) const { 1140 for (const Use &U : uses()) { 1141 const User *FU = U.getUser(); 1142 if (isa<BlockAddress>(FU)) 1143 continue; 1144 if (!isa<CallInst>(FU) && !isa<InvokeInst>(FU)) { 1145 if (PutOffender) 1146 *PutOffender = FU; 1147 return true; 1148 } 1149 ImmutableCallSite CS(cast<Instruction>(FU)); 1150 if (!CS.isCallee(&U)) { 1151 if (PutOffender) 1152 *PutOffender = FU; 1153 return true; 1154 } 1155 } 1156 return false; 1157 } 1158 1159 bool Function::isDefTriviallyDead() const { 1160 // Check the linkage 1161 if (!hasLinkOnceLinkage() && !hasLocalLinkage() && 1162 !hasAvailableExternallyLinkage()) 1163 return false; 1164 1165 // Check if the function is used by anything other than a blockaddress. 1166 for (const User *U : users()) 1167 if (!isa<BlockAddress>(U)) 1168 return false; 1169 1170 return true; 1171 } 1172 1173 /// callsFunctionThatReturnsTwice - Return true if the function has a call to 1174 /// setjmp or other function that gcc recognizes as "returning twice". 1175 bool Function::callsFunctionThatReturnsTwice() const { 1176 for (const_inst_iterator 1177 I = inst_begin(this), E = inst_end(this); I != E; ++I) { 1178 ImmutableCallSite CS(&*I); 1179 if (CS && CS.hasFnAttr(Attribute::ReturnsTwice)) 1180 return true; 1181 } 1182 1183 return false; 1184 } 1185 1186 Constant *Function::getPersonalityFn() const { 1187 assert(hasPersonalityFn() && getNumOperands()); 1188 return cast<Constant>(Op<0>()); 1189 } 1190 1191 void Function::setPersonalityFn(Constant *Fn) { 1192 setHungoffOperand<0>(Fn); 1193 setValueSubclassDataBit(3, Fn != nullptr); 1194 } 1195 1196 Constant *Function::getPrefixData() const { 1197 assert(hasPrefixData() && getNumOperands()); 1198 return cast<Constant>(Op<1>()); 1199 } 1200 1201 void Function::setPrefixData(Constant *PrefixData) { 1202 setHungoffOperand<1>(PrefixData); 1203 setValueSubclassDataBit(1, PrefixData != nullptr); 1204 } 1205 1206 Constant *Function::getPrologueData() const { 1207 assert(hasPrologueData() && getNumOperands()); 1208 return cast<Constant>(Op<2>()); 1209 } 1210 1211 void Function::setPrologueData(Constant *PrologueData) { 1212 setHungoffOperand<2>(PrologueData); 1213 setValueSubclassDataBit(2, PrologueData != nullptr); 1214 } 1215 1216 void Function::allocHungoffUselist() { 1217 // If we've already allocated a uselist, stop here. 1218 if (getNumOperands()) 1219 return; 1220 1221 allocHungoffUses(3, /*IsPhi=*/ false); 1222 setNumHungOffUseOperands(3); 1223 1224 // Initialize the uselist with placeholder operands to allow traversal. 1225 auto *CPN = ConstantPointerNull::get(Type::getInt1PtrTy(getContext(), 0)); 1226 Op<0>().set(CPN); 1227 Op<1>().set(CPN); 1228 Op<2>().set(CPN); 1229 } 1230 1231 template <int Idx> 1232 void Function::setHungoffOperand(Constant *C) { 1233 if (C) { 1234 allocHungoffUselist(); 1235 Op<Idx>().set(C); 1236 } else if (getNumOperands()) { 1237 Op<Idx>().set( 1238 ConstantPointerNull::get(Type::getInt1PtrTy(getContext(), 0))); 1239 } 1240 } 1241 1242 void Function::setValueSubclassDataBit(unsigned Bit, bool On) { 1243 assert(Bit < 16 && "SubclassData contains only 16 bits"); 1244 if (On) 1245 setValueSubclassData(getSubclassDataFromValue() | (1 << Bit)); 1246 else 1247 setValueSubclassData(getSubclassDataFromValue() & ~(1 << Bit)); 1248 } 1249 1250 void Function::setEntryCount(uint64_t Count, 1251 const DenseSet<GlobalValue::GUID> *S) { 1252 MDBuilder MDB(getContext()); 1253 setMetadata(LLVMContext::MD_prof, MDB.createFunctionEntryCount(Count, S)); 1254 } 1255 1256 Optional<uint64_t> Function::getEntryCount() const { 1257 MDNode *MD = getMetadata(LLVMContext::MD_prof); 1258 if (MD && MD->getOperand(0)) 1259 if (MDString *MDS = dyn_cast<MDString>(MD->getOperand(0))) 1260 if (MDS->getString().equals("function_entry_count")) { 1261 ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(1)); 1262 uint64_t Count = CI->getValue().getZExtValue(); 1263 if (Count == 0) 1264 return None; 1265 return Count; 1266 } 1267 return None; 1268 } 1269 1270 DenseSet<GlobalValue::GUID> Function::getImportGUIDs() const { 1271 DenseSet<GlobalValue::GUID> R; 1272 if (MDNode *MD = getMetadata(LLVMContext::MD_prof)) 1273 if (MDString *MDS = dyn_cast<MDString>(MD->getOperand(0))) 1274 if (MDS->getString().equals("function_entry_count")) 1275 for (unsigned i = 2; i < MD->getNumOperands(); i++) 1276 R.insert(mdconst::extract<ConstantInt>(MD->getOperand(i)) 1277 ->getValue() 1278 .getZExtValue()); 1279 return R; 1280 } 1281 1282 void Function::setSectionPrefix(StringRef Prefix) { 1283 MDBuilder MDB(getContext()); 1284 setMetadata(LLVMContext::MD_section_prefix, 1285 MDB.createFunctionSectionPrefix(Prefix)); 1286 } 1287 1288 Optional<StringRef> Function::getSectionPrefix() const { 1289 if (MDNode *MD = getMetadata(LLVMContext::MD_section_prefix)) { 1290 assert(dyn_cast<MDString>(MD->getOperand(0)) 1291 ->getString() 1292 .equals("function_section_prefix") && 1293 "Metadata not match"); 1294 return dyn_cast<MDString>(MD->getOperand(1))->getString(); 1295 } 1296 return None; 1297 } 1298