1 //===- Function.cpp - Implement the Global object classes -----------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements the Function class for the IR library. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "llvm/IR/Function.h" 14 #include "SymbolTableListTraitsImpl.h" 15 #include "llvm/ADT/ArrayRef.h" 16 #include "llvm/ADT/DenseSet.h" 17 #include "llvm/ADT/None.h" 18 #include "llvm/ADT/STLExtras.h" 19 #include "llvm/ADT/SmallString.h" 20 #include "llvm/ADT/SmallVector.h" 21 #include "llvm/ADT/StringExtras.h" 22 #include "llvm/ADT/StringRef.h" 23 #include "llvm/IR/Argument.h" 24 #include "llvm/IR/Attributes.h" 25 #include "llvm/IR/BasicBlock.h" 26 #include "llvm/IR/Constant.h" 27 #include "llvm/IR/Constants.h" 28 #include "llvm/IR/DerivedTypes.h" 29 #include "llvm/IR/GlobalValue.h" 30 #include "llvm/IR/InstIterator.h" 31 #include "llvm/IR/Instruction.h" 32 #include "llvm/IR/Instructions.h" 33 #include "llvm/IR/IntrinsicInst.h" 34 #include "llvm/IR/Intrinsics.h" 35 #include "llvm/IR/LLVMContext.h" 36 #include "llvm/IR/MDBuilder.h" 37 #include "llvm/IR/Metadata.h" 38 #include "llvm/IR/Module.h" 39 #include "llvm/IR/SymbolTableListTraits.h" 40 #include "llvm/IR/Type.h" 41 #include "llvm/IR/Use.h" 42 #include "llvm/IR/User.h" 43 #include "llvm/IR/Value.h" 44 #include "llvm/IR/ValueSymbolTable.h" 45 #include "llvm/Support/Casting.h" 46 #include "llvm/Support/Compiler.h" 47 #include "llvm/Support/ErrorHandling.h" 48 #include <algorithm> 49 #include <cassert> 50 #include <cstddef> 51 #include <cstdint> 52 #include <cstring> 53 #include <string> 54 55 using namespace llvm; 56 using ProfileCount = Function::ProfileCount; 57 58 // Explicit instantiations of SymbolTableListTraits since some of the methods 59 // are not in the public header file... 60 template class llvm::SymbolTableListTraits<BasicBlock>; 61 62 //===----------------------------------------------------------------------===// 63 // Argument Implementation 64 //===----------------------------------------------------------------------===// 65 66 Argument::Argument(Type *Ty, const Twine &Name, Function *Par, unsigned ArgNo) 67 : Value(Ty, Value::ArgumentVal), Parent(Par), ArgNo(ArgNo) { 68 setName(Name); 69 } 70 71 void Argument::setParent(Function *parent) { 72 Parent = parent; 73 } 74 75 bool Argument::hasNonNullAttr() const { 76 if (!getType()->isPointerTy()) return false; 77 if (getParent()->hasParamAttribute(getArgNo(), Attribute::NonNull)) 78 return true; 79 else if (getDereferenceableBytes() > 0 && 80 !NullPointerIsDefined(getParent(), 81 getType()->getPointerAddressSpace())) 82 return true; 83 return false; 84 } 85 86 bool Argument::hasByValAttr() const { 87 if (!getType()->isPointerTy()) return false; 88 return hasAttribute(Attribute::ByVal); 89 } 90 91 bool Argument::hasSwiftSelfAttr() const { 92 return getParent()->hasParamAttribute(getArgNo(), Attribute::SwiftSelf); 93 } 94 95 bool Argument::hasSwiftErrorAttr() const { 96 return getParent()->hasParamAttribute(getArgNo(), Attribute::SwiftError); 97 } 98 99 bool Argument::hasInAllocaAttr() const { 100 if (!getType()->isPointerTy()) return false; 101 return hasAttribute(Attribute::InAlloca); 102 } 103 104 bool Argument::hasByValOrInAllocaAttr() const { 105 if (!getType()->isPointerTy()) return false; 106 AttributeList Attrs = getParent()->getAttributes(); 107 return Attrs.hasParamAttribute(getArgNo(), Attribute::ByVal) || 108 Attrs.hasParamAttribute(getArgNo(), Attribute::InAlloca); 109 } 110 111 unsigned Argument::getParamAlignment() const { 112 assert(getType()->isPointerTy() && "Only pointers have alignments"); 113 return getParent()->getParamAlignment(getArgNo()); 114 } 115 116 Type *Argument::getParamByValType() const { 117 assert(getType()->isPointerTy() && "Only pointers have byval types"); 118 return getParent()->getParamByValType(getArgNo()); 119 } 120 121 uint64_t Argument::getDereferenceableBytes() const { 122 assert(getType()->isPointerTy() && 123 "Only pointers have dereferenceable bytes"); 124 return getParent()->getParamDereferenceableBytes(getArgNo()); 125 } 126 127 uint64_t Argument::getDereferenceableOrNullBytes() const { 128 assert(getType()->isPointerTy() && 129 "Only pointers have dereferenceable bytes"); 130 return getParent()->getParamDereferenceableOrNullBytes(getArgNo()); 131 } 132 133 bool Argument::hasNestAttr() const { 134 if (!getType()->isPointerTy()) return false; 135 return hasAttribute(Attribute::Nest); 136 } 137 138 bool Argument::hasNoAliasAttr() const { 139 if (!getType()->isPointerTy()) return false; 140 return hasAttribute(Attribute::NoAlias); 141 } 142 143 bool Argument::hasNoCaptureAttr() const { 144 if (!getType()->isPointerTy()) return false; 145 return hasAttribute(Attribute::NoCapture); 146 } 147 148 bool Argument::hasStructRetAttr() const { 149 if (!getType()->isPointerTy()) return false; 150 return hasAttribute(Attribute::StructRet); 151 } 152 153 bool Argument::hasInRegAttr() const { 154 return hasAttribute(Attribute::InReg); 155 } 156 157 bool Argument::hasReturnedAttr() const { 158 return hasAttribute(Attribute::Returned); 159 } 160 161 bool Argument::hasZExtAttr() const { 162 return hasAttribute(Attribute::ZExt); 163 } 164 165 bool Argument::hasSExtAttr() const { 166 return hasAttribute(Attribute::SExt); 167 } 168 169 bool Argument::onlyReadsMemory() const { 170 AttributeList Attrs = getParent()->getAttributes(); 171 return Attrs.hasParamAttribute(getArgNo(), Attribute::ReadOnly) || 172 Attrs.hasParamAttribute(getArgNo(), Attribute::ReadNone); 173 } 174 175 void Argument::addAttrs(AttrBuilder &B) { 176 AttributeList AL = getParent()->getAttributes(); 177 AL = AL.addParamAttributes(Parent->getContext(), getArgNo(), B); 178 getParent()->setAttributes(AL); 179 } 180 181 void Argument::addAttr(Attribute::AttrKind Kind) { 182 getParent()->addParamAttr(getArgNo(), Kind); 183 } 184 185 void Argument::addAttr(Attribute Attr) { 186 getParent()->addParamAttr(getArgNo(), Attr); 187 } 188 189 void Argument::removeAttr(Attribute::AttrKind Kind) { 190 getParent()->removeParamAttr(getArgNo(), Kind); 191 } 192 193 bool Argument::hasAttribute(Attribute::AttrKind Kind) const { 194 return getParent()->hasParamAttribute(getArgNo(), Kind); 195 } 196 197 Attribute Argument::getAttribute(Attribute::AttrKind Kind) const { 198 return getParent()->getParamAttribute(getArgNo(), Kind); 199 } 200 201 //===----------------------------------------------------------------------===// 202 // Helper Methods in Function 203 //===----------------------------------------------------------------------===// 204 205 LLVMContext &Function::getContext() const { 206 return getType()->getContext(); 207 } 208 209 unsigned Function::getInstructionCount() const { 210 unsigned NumInstrs = 0; 211 for (const BasicBlock &BB : BasicBlocks) 212 NumInstrs += std::distance(BB.instructionsWithoutDebug().begin(), 213 BB.instructionsWithoutDebug().end()); 214 return NumInstrs; 215 } 216 217 Function *Function::Create(FunctionType *Ty, LinkageTypes Linkage, 218 const Twine &N, Module &M) { 219 return Create(Ty, Linkage, M.getDataLayout().getProgramAddressSpace(), N, &M); 220 } 221 222 void Function::removeFromParent() { 223 getParent()->getFunctionList().remove(getIterator()); 224 } 225 226 void Function::eraseFromParent() { 227 getParent()->getFunctionList().erase(getIterator()); 228 } 229 230 //===----------------------------------------------------------------------===// 231 // Function Implementation 232 //===----------------------------------------------------------------------===// 233 234 static unsigned computeAddrSpace(unsigned AddrSpace, Module *M) { 235 // If AS == -1 and we are passed a valid module pointer we place the function 236 // in the program address space. Otherwise we default to AS0. 237 if (AddrSpace == static_cast<unsigned>(-1)) 238 return M ? M->getDataLayout().getProgramAddressSpace() : 0; 239 return AddrSpace; 240 } 241 242 Function::Function(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, 243 const Twine &name, Module *ParentModule) 244 : GlobalObject(Ty, Value::FunctionVal, 245 OperandTraits<Function>::op_begin(this), 0, Linkage, name, 246 computeAddrSpace(AddrSpace, ParentModule)), 247 NumArgs(Ty->getNumParams()) { 248 assert(FunctionType::isValidReturnType(getReturnType()) && 249 "invalid return type"); 250 setGlobalObjectSubClassData(0); 251 252 // We only need a symbol table for a function if the context keeps value names 253 if (!getContext().shouldDiscardValueNames()) 254 SymTab = std::make_unique<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 HasLLVMReservedName = getName().startswith("llvm."); 264 // Ensure intrinsics have the right parameter attributes. 265 // Note, the IntID field will have been set in Value::setName if this function 266 // name is a valid intrinsic ID. 267 if (IntID) 268 setAttributes(Intrinsic::getAttributes(getContext(), IntID)); 269 } 270 271 Function::~Function() { 272 dropAllReferences(); // After this it is safe to delete instructions. 273 274 // Delete all of the method arguments and unlink from symbol table... 275 if (Arguments) 276 clearArguments(); 277 278 // Remove the function from the on-the-side GC table. 279 clearGC(); 280 } 281 282 void Function::BuildLazyArguments() const { 283 // Create the arguments vector, all arguments start out unnamed. 284 auto *FT = getFunctionType(); 285 if (NumArgs > 0) { 286 Arguments = std::allocator<Argument>().allocate(NumArgs); 287 for (unsigned i = 0, e = NumArgs; i != e; ++i) { 288 Type *ArgTy = FT->getParamType(i); 289 assert(!ArgTy->isVoidTy() && "Cannot have void typed arguments!"); 290 new (Arguments + i) Argument(ArgTy, "", const_cast<Function *>(this), i); 291 } 292 } 293 294 // Clear the lazy arguments bit. 295 unsigned SDC = getSubclassDataFromValue(); 296 SDC &= ~(1 << 0); 297 const_cast<Function*>(this)->setValueSubclassData(SDC); 298 assert(!hasLazyArguments()); 299 } 300 301 static MutableArrayRef<Argument> makeArgArray(Argument *Args, size_t Count) { 302 return MutableArrayRef<Argument>(Args, Count); 303 } 304 305 void Function::clearArguments() { 306 for (Argument &A : makeArgArray(Arguments, NumArgs)) { 307 A.setName(""); 308 A.~Argument(); 309 } 310 std::allocator<Argument>().deallocate(Arguments, NumArgs); 311 Arguments = nullptr; 312 } 313 314 void Function::stealArgumentListFrom(Function &Src) { 315 assert(isDeclaration() && "Expected no references to current arguments"); 316 317 // Drop the current arguments, if any, and set the lazy argument bit. 318 if (!hasLazyArguments()) { 319 assert(llvm::all_of(makeArgArray(Arguments, NumArgs), 320 [](const Argument &A) { return A.use_empty(); }) && 321 "Expected arguments to be unused in declaration"); 322 clearArguments(); 323 setValueSubclassData(getSubclassDataFromValue() | (1 << 0)); 324 } 325 326 // Nothing to steal if Src has lazy arguments. 327 if (Src.hasLazyArguments()) 328 return; 329 330 // Steal arguments from Src, and fix the lazy argument bits. 331 assert(arg_size() == Src.arg_size()); 332 Arguments = Src.Arguments; 333 Src.Arguments = nullptr; 334 for (Argument &A : makeArgArray(Arguments, NumArgs)) { 335 // FIXME: This does the work of transferNodesFromList inefficiently. 336 SmallString<128> Name; 337 if (A.hasName()) 338 Name = A.getName(); 339 if (!Name.empty()) 340 A.setName(""); 341 A.setParent(this); 342 if (!Name.empty()) 343 A.setName(Name); 344 } 345 346 setValueSubclassData(getSubclassDataFromValue() & ~(1 << 0)); 347 assert(!hasLazyArguments()); 348 Src.setValueSubclassData(Src.getSubclassDataFromValue() | (1 << 0)); 349 } 350 351 // dropAllReferences() - This function causes all the subinstructions to "let 352 // go" of all references that they are maintaining. This allows one to 353 // 'delete' a whole class at a time, even though there may be circular 354 // references... first all references are dropped, and all use counts go to 355 // zero. Then everything is deleted for real. Note that no operations are 356 // valid on an object that has "dropped all references", except operator 357 // delete. 358 // 359 void Function::dropAllReferences() { 360 setIsMaterializable(false); 361 362 for (BasicBlock &BB : *this) 363 BB.dropAllReferences(); 364 365 // Delete all basic blocks. They are now unused, except possibly by 366 // blockaddresses, but BasicBlock's destructor takes care of those. 367 while (!BasicBlocks.empty()) 368 BasicBlocks.begin()->eraseFromParent(); 369 370 // Drop uses of any optional data (real or placeholder). 371 if (getNumOperands()) { 372 User::dropAllReferences(); 373 setNumHungOffUseOperands(0); 374 setValueSubclassData(getSubclassDataFromValue() & ~0xe); 375 } 376 377 // Metadata is stored in a side-table. 378 clearMetadata(); 379 } 380 381 void Function::addAttribute(unsigned i, Attribute::AttrKind Kind) { 382 AttributeList PAL = getAttributes(); 383 PAL = PAL.addAttribute(getContext(), i, Kind); 384 setAttributes(PAL); 385 } 386 387 void Function::addAttribute(unsigned i, Attribute Attr) { 388 AttributeList PAL = getAttributes(); 389 PAL = PAL.addAttribute(getContext(), i, Attr); 390 setAttributes(PAL); 391 } 392 393 void Function::addAttributes(unsigned i, const AttrBuilder &Attrs) { 394 AttributeList PAL = getAttributes(); 395 PAL = PAL.addAttributes(getContext(), i, Attrs); 396 setAttributes(PAL); 397 } 398 399 void Function::addParamAttr(unsigned ArgNo, Attribute::AttrKind Kind) { 400 AttributeList PAL = getAttributes(); 401 PAL = PAL.addParamAttribute(getContext(), ArgNo, Kind); 402 setAttributes(PAL); 403 } 404 405 void Function::addParamAttr(unsigned ArgNo, Attribute Attr) { 406 AttributeList PAL = getAttributes(); 407 PAL = PAL.addParamAttribute(getContext(), ArgNo, Attr); 408 setAttributes(PAL); 409 } 410 411 void Function::addParamAttrs(unsigned ArgNo, const AttrBuilder &Attrs) { 412 AttributeList PAL = getAttributes(); 413 PAL = PAL.addParamAttributes(getContext(), ArgNo, Attrs); 414 setAttributes(PAL); 415 } 416 417 void Function::removeAttribute(unsigned i, Attribute::AttrKind Kind) { 418 AttributeList PAL = getAttributes(); 419 PAL = PAL.removeAttribute(getContext(), i, Kind); 420 setAttributes(PAL); 421 } 422 423 void Function::removeAttribute(unsigned i, StringRef Kind) { 424 AttributeList PAL = getAttributes(); 425 PAL = PAL.removeAttribute(getContext(), i, Kind); 426 setAttributes(PAL); 427 } 428 429 void Function::removeAttributes(unsigned i, const AttrBuilder &Attrs) { 430 AttributeList PAL = getAttributes(); 431 PAL = PAL.removeAttributes(getContext(), i, Attrs); 432 setAttributes(PAL); 433 } 434 435 void Function::removeParamAttr(unsigned ArgNo, Attribute::AttrKind Kind) { 436 AttributeList PAL = getAttributes(); 437 PAL = PAL.removeParamAttribute(getContext(), ArgNo, Kind); 438 setAttributes(PAL); 439 } 440 441 void Function::removeParamAttr(unsigned ArgNo, StringRef Kind) { 442 AttributeList PAL = getAttributes(); 443 PAL = PAL.removeParamAttribute(getContext(), ArgNo, Kind); 444 setAttributes(PAL); 445 } 446 447 void Function::removeParamAttrs(unsigned ArgNo, const AttrBuilder &Attrs) { 448 AttributeList PAL = getAttributes(); 449 PAL = PAL.removeParamAttributes(getContext(), ArgNo, Attrs); 450 setAttributes(PAL); 451 } 452 453 void Function::addDereferenceableAttr(unsigned i, uint64_t Bytes) { 454 AttributeList PAL = getAttributes(); 455 PAL = PAL.addDereferenceableAttr(getContext(), i, Bytes); 456 setAttributes(PAL); 457 } 458 459 void Function::addDereferenceableParamAttr(unsigned ArgNo, uint64_t Bytes) { 460 AttributeList PAL = getAttributes(); 461 PAL = PAL.addDereferenceableParamAttr(getContext(), ArgNo, Bytes); 462 setAttributes(PAL); 463 } 464 465 void Function::addDereferenceableOrNullAttr(unsigned i, uint64_t Bytes) { 466 AttributeList PAL = getAttributes(); 467 PAL = PAL.addDereferenceableOrNullAttr(getContext(), i, Bytes); 468 setAttributes(PAL); 469 } 470 471 void Function::addDereferenceableOrNullParamAttr(unsigned ArgNo, 472 uint64_t Bytes) { 473 AttributeList PAL = getAttributes(); 474 PAL = PAL.addDereferenceableOrNullParamAttr(getContext(), ArgNo, Bytes); 475 setAttributes(PAL); 476 } 477 478 const std::string &Function::getGC() const { 479 assert(hasGC() && "Function has no collector"); 480 return getContext().getGC(*this); 481 } 482 483 void Function::setGC(std::string Str) { 484 setValueSubclassDataBit(14, !Str.empty()); 485 getContext().setGC(*this, std::move(Str)); 486 } 487 488 void Function::clearGC() { 489 if (!hasGC()) 490 return; 491 getContext().deleteGC(*this); 492 setValueSubclassDataBit(14, false); 493 } 494 495 /// Copy all additional attributes (those not needed to create a Function) from 496 /// the Function Src to this one. 497 void Function::copyAttributesFrom(const Function *Src) { 498 GlobalObject::copyAttributesFrom(Src); 499 setCallingConv(Src->getCallingConv()); 500 setAttributes(Src->getAttributes()); 501 if (Src->hasGC()) 502 setGC(Src->getGC()); 503 else 504 clearGC(); 505 if (Src->hasPersonalityFn()) 506 setPersonalityFn(Src->getPersonalityFn()); 507 if (Src->hasPrefixData()) 508 setPrefixData(Src->getPrefixData()); 509 if (Src->hasPrologueData()) 510 setPrologueData(Src->getPrologueData()); 511 } 512 513 /// Table of string intrinsic names indexed by enum value. 514 static const char * const IntrinsicNameTable[] = { 515 "not_intrinsic", 516 #define GET_INTRINSIC_NAME_TABLE 517 #include "llvm/IR/IntrinsicImpl.inc" 518 #undef GET_INTRINSIC_NAME_TABLE 519 }; 520 521 /// Table of per-target intrinsic name tables. 522 #define GET_INTRINSIC_TARGET_DATA 523 #include "llvm/IR/IntrinsicImpl.inc" 524 #undef GET_INTRINSIC_TARGET_DATA 525 526 /// Find the segment of \c IntrinsicNameTable for intrinsics with the same 527 /// target as \c Name, or the generic table if \c Name is not target specific. 528 /// 529 /// Returns the relevant slice of \c IntrinsicNameTable 530 static ArrayRef<const char *> findTargetSubtable(StringRef Name) { 531 assert(Name.startswith("llvm.")); 532 533 ArrayRef<IntrinsicTargetInfo> Targets(TargetInfos); 534 // Drop "llvm." and take the first dotted component. That will be the target 535 // if this is target specific. 536 StringRef Target = Name.drop_front(5).split('.').first; 537 auto It = partition_point( 538 Targets, [=](const IntrinsicTargetInfo &TI) { return TI.Name < Target; }); 539 // We've either found the target or just fall back to the generic set, which 540 // is always first. 541 const auto &TI = It != Targets.end() && It->Name == Target ? *It : Targets[0]; 542 return makeArrayRef(&IntrinsicNameTable[1] + TI.Offset, TI.Count); 543 } 544 545 /// This does the actual lookup of an intrinsic ID which 546 /// matches the given function name. 547 Intrinsic::ID Function::lookupIntrinsicID(StringRef Name) { 548 ArrayRef<const char *> NameTable = findTargetSubtable(Name); 549 int Idx = Intrinsic::lookupLLVMIntrinsicByName(NameTable, Name); 550 if (Idx == -1) 551 return Intrinsic::not_intrinsic; 552 553 // Intrinsic IDs correspond to the location in IntrinsicNameTable, but we have 554 // an index into a sub-table. 555 int Adjust = NameTable.data() - IntrinsicNameTable; 556 Intrinsic::ID ID = static_cast<Intrinsic::ID>(Idx + Adjust); 557 558 // If the intrinsic is not overloaded, require an exact match. If it is 559 // overloaded, require either exact or prefix match. 560 const auto MatchSize = strlen(NameTable[Idx]); 561 assert(Name.size() >= MatchSize && "Expected either exact or prefix match"); 562 bool IsExactMatch = Name.size() == MatchSize; 563 return IsExactMatch || isOverloaded(ID) ? ID : Intrinsic::not_intrinsic; 564 } 565 566 void Function::recalculateIntrinsicID() { 567 StringRef Name = getName(); 568 if (!Name.startswith("llvm.")) { 569 HasLLVMReservedName = false; 570 IntID = Intrinsic::not_intrinsic; 571 return; 572 } 573 HasLLVMReservedName = true; 574 IntID = lookupIntrinsicID(Name); 575 } 576 577 /// Returns a stable mangling for the type specified for use in the name 578 /// mangling scheme used by 'any' types in intrinsic signatures. The mangling 579 /// of named types is simply their name. Manglings for unnamed types consist 580 /// of a prefix ('p' for pointers, 'a' for arrays, 'f_' for functions) 581 /// combined with the mangling of their component types. A vararg function 582 /// type will have a suffix of 'vararg'. Since function types can contain 583 /// other function types, we close a function type mangling with suffix 'f' 584 /// which can't be confused with it's prefix. This ensures we don't have 585 /// collisions between two unrelated function types. Otherwise, you might 586 /// parse ffXX as f(fXX) or f(fX)X. (X is a placeholder for any other type.) 587 /// 588 static std::string getMangledTypeStr(Type* Ty) { 589 std::string Result; 590 if (PointerType* PTyp = dyn_cast<PointerType>(Ty)) { 591 Result += "p" + utostr(PTyp->getAddressSpace()) + 592 getMangledTypeStr(PTyp->getElementType()); 593 } else if (ArrayType* ATyp = dyn_cast<ArrayType>(Ty)) { 594 Result += "a" + utostr(ATyp->getNumElements()) + 595 getMangledTypeStr(ATyp->getElementType()); 596 } else if (StructType *STyp = dyn_cast<StructType>(Ty)) { 597 if (!STyp->isLiteral()) { 598 Result += "s_"; 599 Result += STyp->getName(); 600 } else { 601 Result += "sl_"; 602 for (auto Elem : STyp->elements()) 603 Result += getMangledTypeStr(Elem); 604 } 605 // Ensure nested structs are distinguishable. 606 Result += "s"; 607 } else if (FunctionType *FT = dyn_cast<FunctionType>(Ty)) { 608 Result += "f_" + getMangledTypeStr(FT->getReturnType()); 609 for (size_t i = 0; i < FT->getNumParams(); i++) 610 Result += getMangledTypeStr(FT->getParamType(i)); 611 if (FT->isVarArg()) 612 Result += "vararg"; 613 // Ensure nested function types are distinguishable. 614 Result += "f"; 615 } else if (VectorType* VTy = dyn_cast<VectorType>(Ty)) { 616 if (VTy->isScalable()) 617 Result += "nx"; 618 Result += "v" + utostr(VTy->getVectorNumElements()) + 619 getMangledTypeStr(VTy->getVectorElementType()); 620 } else if (Ty) { 621 switch (Ty->getTypeID()) { 622 default: llvm_unreachable("Unhandled type"); 623 case Type::VoidTyID: Result += "isVoid"; break; 624 case Type::MetadataTyID: Result += "Metadata"; break; 625 case Type::HalfTyID: Result += "f16"; break; 626 case Type::FloatTyID: Result += "f32"; break; 627 case Type::DoubleTyID: Result += "f64"; break; 628 case Type::X86_FP80TyID: Result += "f80"; break; 629 case Type::FP128TyID: Result += "f128"; break; 630 case Type::PPC_FP128TyID: Result += "ppcf128"; break; 631 case Type::X86_MMXTyID: Result += "x86mmx"; break; 632 case Type::IntegerTyID: 633 Result += "i" + utostr(cast<IntegerType>(Ty)->getBitWidth()); 634 break; 635 } 636 } 637 return Result; 638 } 639 640 StringRef Intrinsic::getName(ID id) { 641 assert(id < num_intrinsics && "Invalid intrinsic ID!"); 642 assert(!isOverloaded(id) && 643 "This version of getName does not support overloading"); 644 return IntrinsicNameTable[id]; 645 } 646 647 std::string Intrinsic::getName(ID id, ArrayRef<Type*> Tys) { 648 assert(id < num_intrinsics && "Invalid intrinsic ID!"); 649 std::string Result(IntrinsicNameTable[id]); 650 for (Type *Ty : Tys) { 651 Result += "." + getMangledTypeStr(Ty); 652 } 653 return Result; 654 } 655 656 /// IIT_Info - These are enumerators that describe the entries returned by the 657 /// getIntrinsicInfoTableEntries function. 658 /// 659 /// NOTE: This must be kept in synch with the copy in TblGen/IntrinsicEmitter! 660 enum IIT_Info { 661 // Common values should be encoded with 0-15. 662 IIT_Done = 0, 663 IIT_I1 = 1, 664 IIT_I8 = 2, 665 IIT_I16 = 3, 666 IIT_I32 = 4, 667 IIT_I64 = 5, 668 IIT_F16 = 6, 669 IIT_F32 = 7, 670 IIT_F64 = 8, 671 IIT_V2 = 9, 672 IIT_V4 = 10, 673 IIT_V8 = 11, 674 IIT_V16 = 12, 675 IIT_V32 = 13, 676 IIT_PTR = 14, 677 IIT_ARG = 15, 678 679 // Values from 16+ are only encodable with the inefficient encoding. 680 IIT_V64 = 16, 681 IIT_MMX = 17, 682 IIT_TOKEN = 18, 683 IIT_METADATA = 19, 684 IIT_EMPTYSTRUCT = 20, 685 IIT_STRUCT2 = 21, 686 IIT_STRUCT3 = 22, 687 IIT_STRUCT4 = 23, 688 IIT_STRUCT5 = 24, 689 IIT_EXTEND_ARG = 25, 690 IIT_TRUNC_ARG = 26, 691 IIT_ANYPTR = 27, 692 IIT_V1 = 28, 693 IIT_VARARG = 29, 694 IIT_HALF_VEC_ARG = 30, 695 IIT_SAME_VEC_WIDTH_ARG = 31, 696 IIT_PTR_TO_ARG = 32, 697 IIT_PTR_TO_ELT = 33, 698 IIT_VEC_OF_ANYPTRS_TO_ELT = 34, 699 IIT_I128 = 35, 700 IIT_V512 = 36, 701 IIT_V1024 = 37, 702 IIT_STRUCT6 = 38, 703 IIT_STRUCT7 = 39, 704 IIT_STRUCT8 = 40, 705 IIT_F128 = 41, 706 IIT_VEC_ELEMENT = 42, 707 IIT_SCALABLE_VEC = 43, 708 IIT_SUBDIVIDE2_ARG = 44, 709 IIT_SUBDIVIDE4_ARG = 45 710 }; 711 712 static void DecodeIITType(unsigned &NextElt, ArrayRef<unsigned char> Infos, 713 SmallVectorImpl<Intrinsic::IITDescriptor> &OutputTable) { 714 using namespace Intrinsic; 715 716 IIT_Info Info = IIT_Info(Infos[NextElt++]); 717 unsigned StructElts = 2; 718 719 switch (Info) { 720 case IIT_Done: 721 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Void, 0)); 722 return; 723 case IIT_VARARG: 724 OutputTable.push_back(IITDescriptor::get(IITDescriptor::VarArg, 0)); 725 return; 726 case IIT_MMX: 727 OutputTable.push_back(IITDescriptor::get(IITDescriptor::MMX, 0)); 728 return; 729 case IIT_TOKEN: 730 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Token, 0)); 731 return; 732 case IIT_METADATA: 733 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Metadata, 0)); 734 return; 735 case IIT_F16: 736 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Half, 0)); 737 return; 738 case IIT_F32: 739 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Float, 0)); 740 return; 741 case IIT_F64: 742 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Double, 0)); 743 return; 744 case IIT_F128: 745 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Quad, 0)); 746 return; 747 case IIT_I1: 748 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 1)); 749 return; 750 case IIT_I8: 751 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 8)); 752 return; 753 case IIT_I16: 754 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer,16)); 755 return; 756 case IIT_I32: 757 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 32)); 758 return; 759 case IIT_I64: 760 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 64)); 761 return; 762 case IIT_I128: 763 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Integer, 128)); 764 return; 765 case IIT_V1: 766 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 1)); 767 DecodeIITType(NextElt, Infos, OutputTable); 768 return; 769 case IIT_V2: 770 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 2)); 771 DecodeIITType(NextElt, Infos, OutputTable); 772 return; 773 case IIT_V4: 774 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 4)); 775 DecodeIITType(NextElt, Infos, OutputTable); 776 return; 777 case IIT_V8: 778 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 8)); 779 DecodeIITType(NextElt, Infos, OutputTable); 780 return; 781 case IIT_V16: 782 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 16)); 783 DecodeIITType(NextElt, Infos, OutputTable); 784 return; 785 case IIT_V32: 786 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 32)); 787 DecodeIITType(NextElt, Infos, OutputTable); 788 return; 789 case IIT_V64: 790 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 64)); 791 DecodeIITType(NextElt, Infos, OutputTable); 792 return; 793 case IIT_V512: 794 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 512)); 795 DecodeIITType(NextElt, Infos, OutputTable); 796 return; 797 case IIT_V1024: 798 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Vector, 1024)); 799 DecodeIITType(NextElt, Infos, OutputTable); 800 return; 801 case IIT_PTR: 802 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Pointer, 0)); 803 DecodeIITType(NextElt, Infos, OutputTable); 804 return; 805 case IIT_ANYPTR: { // [ANYPTR addrspace, subtype] 806 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Pointer, 807 Infos[NextElt++])); 808 DecodeIITType(NextElt, Infos, OutputTable); 809 return; 810 } 811 case IIT_ARG: { 812 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]); 813 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Argument, ArgInfo)); 814 return; 815 } 816 case IIT_EXTEND_ARG: { 817 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]); 818 OutputTable.push_back(IITDescriptor::get(IITDescriptor::ExtendArgument, 819 ArgInfo)); 820 return; 821 } 822 case IIT_TRUNC_ARG: { 823 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]); 824 OutputTable.push_back(IITDescriptor::get(IITDescriptor::TruncArgument, 825 ArgInfo)); 826 return; 827 } 828 case IIT_HALF_VEC_ARG: { 829 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]); 830 OutputTable.push_back(IITDescriptor::get(IITDescriptor::HalfVecArgument, 831 ArgInfo)); 832 return; 833 } 834 case IIT_SAME_VEC_WIDTH_ARG: { 835 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]); 836 OutputTable.push_back(IITDescriptor::get(IITDescriptor::SameVecWidthArgument, 837 ArgInfo)); 838 return; 839 } 840 case IIT_PTR_TO_ARG: { 841 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]); 842 OutputTable.push_back(IITDescriptor::get(IITDescriptor::PtrToArgument, 843 ArgInfo)); 844 return; 845 } 846 case IIT_PTR_TO_ELT: { 847 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]); 848 OutputTable.push_back(IITDescriptor::get(IITDescriptor::PtrToElt, ArgInfo)); 849 return; 850 } 851 case IIT_VEC_OF_ANYPTRS_TO_ELT: { 852 unsigned short ArgNo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]); 853 unsigned short RefNo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]); 854 OutputTable.push_back( 855 IITDescriptor::get(IITDescriptor::VecOfAnyPtrsToElt, ArgNo, RefNo)); 856 return; 857 } 858 case IIT_EMPTYSTRUCT: 859 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Struct, 0)); 860 return; 861 case IIT_STRUCT8: ++StructElts; LLVM_FALLTHROUGH; 862 case IIT_STRUCT7: ++StructElts; LLVM_FALLTHROUGH; 863 case IIT_STRUCT6: ++StructElts; LLVM_FALLTHROUGH; 864 case IIT_STRUCT5: ++StructElts; LLVM_FALLTHROUGH; 865 case IIT_STRUCT4: ++StructElts; LLVM_FALLTHROUGH; 866 case IIT_STRUCT3: ++StructElts; LLVM_FALLTHROUGH; 867 case IIT_STRUCT2: { 868 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Struct,StructElts)); 869 870 for (unsigned i = 0; i != StructElts; ++i) 871 DecodeIITType(NextElt, Infos, OutputTable); 872 return; 873 } 874 case IIT_SUBDIVIDE2_ARG: { 875 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]); 876 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Subdivide2Argument, 877 ArgInfo)); 878 return; 879 } 880 case IIT_SUBDIVIDE4_ARG: { 881 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]); 882 OutputTable.push_back(IITDescriptor::get(IITDescriptor::Subdivide4Argument, 883 ArgInfo)); 884 return; 885 } 886 case IIT_VEC_ELEMENT: { 887 unsigned ArgInfo = (NextElt == Infos.size() ? 0 : Infos[NextElt++]); 888 OutputTable.push_back(IITDescriptor::get(IITDescriptor::VecElementArgument, 889 ArgInfo)); 890 return; 891 } 892 case IIT_SCALABLE_VEC: { 893 OutputTable.push_back(IITDescriptor::get(IITDescriptor::ScalableVecArgument, 894 0)); 895 DecodeIITType(NextElt, Infos, OutputTable); 896 return; 897 } 898 } 899 llvm_unreachable("unhandled"); 900 } 901 902 #define GET_INTRINSIC_GENERATOR_GLOBAL 903 #include "llvm/IR/IntrinsicImpl.inc" 904 #undef GET_INTRINSIC_GENERATOR_GLOBAL 905 906 void Intrinsic::getIntrinsicInfoTableEntries(ID id, 907 SmallVectorImpl<IITDescriptor> &T){ 908 // Check to see if the intrinsic's type was expressible by the table. 909 unsigned TableVal = IIT_Table[id-1]; 910 911 // Decode the TableVal into an array of IITValues. 912 SmallVector<unsigned char, 8> IITValues; 913 ArrayRef<unsigned char> IITEntries; 914 unsigned NextElt = 0; 915 if ((TableVal >> 31) != 0) { 916 // This is an offset into the IIT_LongEncodingTable. 917 IITEntries = IIT_LongEncodingTable; 918 919 // Strip sentinel bit. 920 NextElt = (TableVal << 1) >> 1; 921 } else { 922 // Decode the TableVal into an array of IITValues. If the entry was encoded 923 // into a single word in the table itself, decode it now. 924 do { 925 IITValues.push_back(TableVal & 0xF); 926 TableVal >>= 4; 927 } while (TableVal); 928 929 IITEntries = IITValues; 930 NextElt = 0; 931 } 932 933 // Okay, decode the table into the output vector of IITDescriptors. 934 DecodeIITType(NextElt, IITEntries, T); 935 while (NextElt != IITEntries.size() && IITEntries[NextElt] != 0) 936 DecodeIITType(NextElt, IITEntries, T); 937 } 938 939 static Type *DecodeFixedType(ArrayRef<Intrinsic::IITDescriptor> &Infos, 940 ArrayRef<Type*> Tys, LLVMContext &Context) { 941 using namespace Intrinsic; 942 943 IITDescriptor D = Infos.front(); 944 Infos = Infos.slice(1); 945 946 switch (D.Kind) { 947 case IITDescriptor::Void: return Type::getVoidTy(Context); 948 case IITDescriptor::VarArg: return Type::getVoidTy(Context); 949 case IITDescriptor::MMX: return Type::getX86_MMXTy(Context); 950 case IITDescriptor::Token: return Type::getTokenTy(Context); 951 case IITDescriptor::Metadata: return Type::getMetadataTy(Context); 952 case IITDescriptor::Half: return Type::getHalfTy(Context); 953 case IITDescriptor::Float: return Type::getFloatTy(Context); 954 case IITDescriptor::Double: return Type::getDoubleTy(Context); 955 case IITDescriptor::Quad: return Type::getFP128Ty(Context); 956 957 case IITDescriptor::Integer: 958 return IntegerType::get(Context, D.Integer_Width); 959 case IITDescriptor::Vector: 960 return VectorType::get(DecodeFixedType(Infos, Tys, Context),D.Vector_Width); 961 case IITDescriptor::Pointer: 962 return PointerType::get(DecodeFixedType(Infos, Tys, Context), 963 D.Pointer_AddressSpace); 964 case IITDescriptor::Struct: { 965 SmallVector<Type *, 8> Elts; 966 for (unsigned i = 0, e = D.Struct_NumElements; i != e; ++i) 967 Elts.push_back(DecodeFixedType(Infos, Tys, Context)); 968 return StructType::get(Context, Elts); 969 } 970 case IITDescriptor::Argument: 971 return Tys[D.getArgumentNumber()]; 972 case IITDescriptor::ExtendArgument: { 973 Type *Ty = Tys[D.getArgumentNumber()]; 974 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) 975 return VectorType::getExtendedElementVectorType(VTy); 976 977 return IntegerType::get(Context, 2 * cast<IntegerType>(Ty)->getBitWidth()); 978 } 979 case IITDescriptor::TruncArgument: { 980 Type *Ty = Tys[D.getArgumentNumber()]; 981 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) 982 return VectorType::getTruncatedElementVectorType(VTy); 983 984 IntegerType *ITy = cast<IntegerType>(Ty); 985 assert(ITy->getBitWidth() % 2 == 0); 986 return IntegerType::get(Context, ITy->getBitWidth() / 2); 987 } 988 case IITDescriptor::Subdivide2Argument: 989 case IITDescriptor::Subdivide4Argument: { 990 Type *Ty = Tys[D.getArgumentNumber()]; 991 VectorType *VTy = dyn_cast<VectorType>(Ty); 992 assert(VTy && "Expected an argument of Vector Type"); 993 int SubDivs = D.Kind == IITDescriptor::Subdivide2Argument ? 1 : 2; 994 return VectorType::getSubdividedVectorType(VTy, SubDivs); 995 } 996 case IITDescriptor::HalfVecArgument: 997 return VectorType::getHalfElementsVectorType(cast<VectorType>( 998 Tys[D.getArgumentNumber()])); 999 case IITDescriptor::SameVecWidthArgument: { 1000 Type *EltTy = DecodeFixedType(Infos, Tys, Context); 1001 Type *Ty = Tys[D.getArgumentNumber()]; 1002 if (auto *VTy = dyn_cast<VectorType>(Ty)) 1003 return VectorType::get(EltTy, VTy->getElementCount()); 1004 return EltTy; 1005 } 1006 case IITDescriptor::PtrToArgument: { 1007 Type *Ty = Tys[D.getArgumentNumber()]; 1008 return PointerType::getUnqual(Ty); 1009 } 1010 case IITDescriptor::PtrToElt: { 1011 Type *Ty = Tys[D.getArgumentNumber()]; 1012 VectorType *VTy = dyn_cast<VectorType>(Ty); 1013 if (!VTy) 1014 llvm_unreachable("Expected an argument of Vector Type"); 1015 Type *EltTy = VTy->getVectorElementType(); 1016 return PointerType::getUnqual(EltTy); 1017 } 1018 case IITDescriptor::VecElementArgument: { 1019 Type *Ty = Tys[D.getArgumentNumber()]; 1020 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) 1021 return VTy->getElementType(); 1022 llvm_unreachable("Expected an argument of Vector Type"); 1023 } 1024 case IITDescriptor::VecOfAnyPtrsToElt: 1025 // Return the overloaded type (which determines the pointers address space) 1026 return Tys[D.getOverloadArgNumber()]; 1027 case IITDescriptor::ScalableVecArgument: { 1028 Type *Ty = DecodeFixedType(Infos, Tys, Context); 1029 return VectorType::get(Ty->getVectorElementType(), 1030 { Ty->getVectorNumElements(), true }); 1031 } 1032 } 1033 llvm_unreachable("unhandled"); 1034 } 1035 1036 FunctionType *Intrinsic::getType(LLVMContext &Context, 1037 ID id, ArrayRef<Type*> Tys) { 1038 SmallVector<IITDescriptor, 8> Table; 1039 getIntrinsicInfoTableEntries(id, Table); 1040 1041 ArrayRef<IITDescriptor> TableRef = Table; 1042 Type *ResultTy = DecodeFixedType(TableRef, Tys, Context); 1043 1044 SmallVector<Type*, 8> ArgTys; 1045 while (!TableRef.empty()) 1046 ArgTys.push_back(DecodeFixedType(TableRef, Tys, Context)); 1047 1048 // DecodeFixedType returns Void for IITDescriptor::Void and IITDescriptor::VarArg 1049 // If we see void type as the type of the last argument, it is vararg intrinsic 1050 if (!ArgTys.empty() && ArgTys.back()->isVoidTy()) { 1051 ArgTys.pop_back(); 1052 return FunctionType::get(ResultTy, ArgTys, true); 1053 } 1054 return FunctionType::get(ResultTy, ArgTys, false); 1055 } 1056 1057 bool Intrinsic::isOverloaded(ID id) { 1058 #define GET_INTRINSIC_OVERLOAD_TABLE 1059 #include "llvm/IR/IntrinsicImpl.inc" 1060 #undef GET_INTRINSIC_OVERLOAD_TABLE 1061 } 1062 1063 bool Intrinsic::isLeaf(ID id) { 1064 switch (id) { 1065 default: 1066 return true; 1067 1068 case Intrinsic::experimental_gc_statepoint: 1069 case Intrinsic::experimental_patchpoint_void: 1070 case Intrinsic::experimental_patchpoint_i64: 1071 return false; 1072 } 1073 } 1074 1075 /// This defines the "Intrinsic::getAttributes(ID id)" method. 1076 #define GET_INTRINSIC_ATTRIBUTES 1077 #include "llvm/IR/IntrinsicImpl.inc" 1078 #undef GET_INTRINSIC_ATTRIBUTES 1079 1080 Function *Intrinsic::getDeclaration(Module *M, ID id, ArrayRef<Type*> Tys) { 1081 // There can never be multiple globals with the same name of different types, 1082 // because intrinsics must be a specific type. 1083 return cast<Function>( 1084 M->getOrInsertFunction(getName(id, Tys), 1085 getType(M->getContext(), id, Tys)) 1086 .getCallee()); 1087 } 1088 1089 // This defines the "Intrinsic::getIntrinsicForGCCBuiltin()" method. 1090 #define GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN 1091 #include "llvm/IR/IntrinsicImpl.inc" 1092 #undef GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN 1093 1094 // This defines the "Intrinsic::getIntrinsicForMSBuiltin()" method. 1095 #define GET_LLVM_INTRINSIC_FOR_MS_BUILTIN 1096 #include "llvm/IR/IntrinsicImpl.inc" 1097 #undef GET_LLVM_INTRINSIC_FOR_MS_BUILTIN 1098 1099 using DeferredIntrinsicMatchPair = 1100 std::pair<Type *, ArrayRef<Intrinsic::IITDescriptor>>; 1101 1102 static bool matchIntrinsicType( 1103 Type *Ty, ArrayRef<Intrinsic::IITDescriptor> &Infos, 1104 SmallVectorImpl<Type *> &ArgTys, 1105 SmallVectorImpl<DeferredIntrinsicMatchPair> &DeferredChecks, 1106 bool IsDeferredCheck) { 1107 using namespace Intrinsic; 1108 1109 // If we ran out of descriptors, there are too many arguments. 1110 if (Infos.empty()) return true; 1111 1112 // Do this before slicing off the 'front' part 1113 auto InfosRef = Infos; 1114 auto DeferCheck = [&DeferredChecks, &InfosRef](Type *T) { 1115 DeferredChecks.emplace_back(T, InfosRef); 1116 return false; 1117 }; 1118 1119 IITDescriptor D = Infos.front(); 1120 Infos = Infos.slice(1); 1121 1122 switch (D.Kind) { 1123 case IITDescriptor::Void: return !Ty->isVoidTy(); 1124 case IITDescriptor::VarArg: return true; 1125 case IITDescriptor::MMX: return !Ty->isX86_MMXTy(); 1126 case IITDescriptor::Token: return !Ty->isTokenTy(); 1127 case IITDescriptor::Metadata: return !Ty->isMetadataTy(); 1128 case IITDescriptor::Half: return !Ty->isHalfTy(); 1129 case IITDescriptor::Float: return !Ty->isFloatTy(); 1130 case IITDescriptor::Double: return !Ty->isDoubleTy(); 1131 case IITDescriptor::Quad: return !Ty->isFP128Ty(); 1132 case IITDescriptor::Integer: return !Ty->isIntegerTy(D.Integer_Width); 1133 case IITDescriptor::Vector: { 1134 VectorType *VT = dyn_cast<VectorType>(Ty); 1135 return !VT || VT->getNumElements() != D.Vector_Width || 1136 matchIntrinsicType(VT->getElementType(), Infos, ArgTys, 1137 DeferredChecks, IsDeferredCheck); 1138 } 1139 case IITDescriptor::Pointer: { 1140 PointerType *PT = dyn_cast<PointerType>(Ty); 1141 return !PT || PT->getAddressSpace() != D.Pointer_AddressSpace || 1142 matchIntrinsicType(PT->getElementType(), Infos, ArgTys, 1143 DeferredChecks, IsDeferredCheck); 1144 } 1145 1146 case IITDescriptor::Struct: { 1147 StructType *ST = dyn_cast<StructType>(Ty); 1148 if (!ST || ST->getNumElements() != D.Struct_NumElements) 1149 return true; 1150 1151 for (unsigned i = 0, e = D.Struct_NumElements; i != e; ++i) 1152 if (matchIntrinsicType(ST->getElementType(i), Infos, ArgTys, 1153 DeferredChecks, IsDeferredCheck)) 1154 return true; 1155 return false; 1156 } 1157 1158 case IITDescriptor::Argument: 1159 // If this is the second occurrence of an argument, 1160 // verify that the later instance matches the previous instance. 1161 if (D.getArgumentNumber() < ArgTys.size()) 1162 return Ty != ArgTys[D.getArgumentNumber()]; 1163 1164 if (D.getArgumentNumber() > ArgTys.size() || 1165 D.getArgumentKind() == IITDescriptor::AK_MatchType) 1166 return IsDeferredCheck || DeferCheck(Ty); 1167 1168 assert(D.getArgumentNumber() == ArgTys.size() && !IsDeferredCheck && 1169 "Table consistency error"); 1170 ArgTys.push_back(Ty); 1171 1172 switch (D.getArgumentKind()) { 1173 case IITDescriptor::AK_Any: return false; // Success 1174 case IITDescriptor::AK_AnyInteger: return !Ty->isIntOrIntVectorTy(); 1175 case IITDescriptor::AK_AnyFloat: return !Ty->isFPOrFPVectorTy(); 1176 case IITDescriptor::AK_AnyVector: return !isa<VectorType>(Ty); 1177 case IITDescriptor::AK_AnyPointer: return !isa<PointerType>(Ty); 1178 default: break; 1179 } 1180 llvm_unreachable("all argument kinds not covered"); 1181 1182 case IITDescriptor::ExtendArgument: { 1183 // If this is a forward reference, defer the check for later. 1184 if (D.getArgumentNumber() >= ArgTys.size()) 1185 return IsDeferredCheck || DeferCheck(Ty); 1186 1187 Type *NewTy = ArgTys[D.getArgumentNumber()]; 1188 if (VectorType *VTy = dyn_cast<VectorType>(NewTy)) 1189 NewTy = VectorType::getExtendedElementVectorType(VTy); 1190 else if (IntegerType *ITy = dyn_cast<IntegerType>(NewTy)) 1191 NewTy = IntegerType::get(ITy->getContext(), 2 * ITy->getBitWidth()); 1192 else 1193 return true; 1194 1195 return Ty != NewTy; 1196 } 1197 case IITDescriptor::TruncArgument: { 1198 // If this is a forward reference, defer the check for later. 1199 if (D.getArgumentNumber() >= ArgTys.size()) 1200 return IsDeferredCheck || DeferCheck(Ty); 1201 1202 Type *NewTy = ArgTys[D.getArgumentNumber()]; 1203 if (VectorType *VTy = dyn_cast<VectorType>(NewTy)) 1204 NewTy = VectorType::getTruncatedElementVectorType(VTy); 1205 else if (IntegerType *ITy = dyn_cast<IntegerType>(NewTy)) 1206 NewTy = IntegerType::get(ITy->getContext(), ITy->getBitWidth() / 2); 1207 else 1208 return true; 1209 1210 return Ty != NewTy; 1211 } 1212 case IITDescriptor::HalfVecArgument: 1213 // If this is a forward reference, defer the check for later. 1214 if (D.getArgumentNumber() >= ArgTys.size()) 1215 return IsDeferredCheck || DeferCheck(Ty); 1216 return !isa<VectorType>(ArgTys[D.getArgumentNumber()]) || 1217 VectorType::getHalfElementsVectorType( 1218 cast<VectorType>(ArgTys[D.getArgumentNumber()])) != Ty; 1219 case IITDescriptor::SameVecWidthArgument: { 1220 if (D.getArgumentNumber() >= ArgTys.size()) { 1221 // Defer check and subsequent check for the vector element type. 1222 Infos = Infos.slice(1); 1223 return IsDeferredCheck || DeferCheck(Ty); 1224 } 1225 auto *ReferenceType = dyn_cast<VectorType>(ArgTys[D.getArgumentNumber()]); 1226 auto *ThisArgType = dyn_cast<VectorType>(Ty); 1227 // Both must be vectors of the same number of elements or neither. 1228 if ((ReferenceType != nullptr) != (ThisArgType != nullptr)) 1229 return true; 1230 Type *EltTy = Ty; 1231 if (ThisArgType) { 1232 if (ReferenceType->getElementCount() != 1233 ThisArgType->getElementCount()) 1234 return true; 1235 EltTy = ThisArgType->getVectorElementType(); 1236 } 1237 return matchIntrinsicType(EltTy, Infos, ArgTys, DeferredChecks, 1238 IsDeferredCheck); 1239 } 1240 case IITDescriptor::PtrToArgument: { 1241 if (D.getArgumentNumber() >= ArgTys.size()) 1242 return IsDeferredCheck || DeferCheck(Ty); 1243 Type * ReferenceType = ArgTys[D.getArgumentNumber()]; 1244 PointerType *ThisArgType = dyn_cast<PointerType>(Ty); 1245 return (!ThisArgType || ThisArgType->getElementType() != ReferenceType); 1246 } 1247 case IITDescriptor::PtrToElt: { 1248 if (D.getArgumentNumber() >= ArgTys.size()) 1249 return IsDeferredCheck || DeferCheck(Ty); 1250 VectorType * ReferenceType = 1251 dyn_cast<VectorType> (ArgTys[D.getArgumentNumber()]); 1252 PointerType *ThisArgType = dyn_cast<PointerType>(Ty); 1253 1254 return (!ThisArgType || !ReferenceType || 1255 ThisArgType->getElementType() != ReferenceType->getElementType()); 1256 } 1257 case IITDescriptor::VecOfAnyPtrsToElt: { 1258 unsigned RefArgNumber = D.getRefArgNumber(); 1259 if (RefArgNumber >= ArgTys.size()) { 1260 if (IsDeferredCheck) 1261 return true; 1262 // If forward referencing, already add the pointer-vector type and 1263 // defer the checks for later. 1264 ArgTys.push_back(Ty); 1265 return DeferCheck(Ty); 1266 } 1267 1268 if (!IsDeferredCheck){ 1269 assert(D.getOverloadArgNumber() == ArgTys.size() && 1270 "Table consistency error"); 1271 ArgTys.push_back(Ty); 1272 } 1273 1274 // Verify the overloaded type "matches" the Ref type. 1275 // i.e. Ty is a vector with the same width as Ref. 1276 // Composed of pointers to the same element type as Ref. 1277 VectorType *ReferenceType = dyn_cast<VectorType>(ArgTys[RefArgNumber]); 1278 VectorType *ThisArgVecTy = dyn_cast<VectorType>(Ty); 1279 if (!ThisArgVecTy || !ReferenceType || 1280 (ReferenceType->getVectorNumElements() != 1281 ThisArgVecTy->getVectorNumElements())) 1282 return true; 1283 PointerType *ThisArgEltTy = 1284 dyn_cast<PointerType>(ThisArgVecTy->getVectorElementType()); 1285 if (!ThisArgEltTy) 1286 return true; 1287 return ThisArgEltTy->getElementType() != 1288 ReferenceType->getVectorElementType(); 1289 } 1290 case IITDescriptor::VecElementArgument: { 1291 if (D.getArgumentNumber() >= ArgTys.size()) 1292 return IsDeferredCheck ? true : DeferCheck(Ty); 1293 auto *ReferenceType = dyn_cast<VectorType>(ArgTys[D.getArgumentNumber()]); 1294 return !ReferenceType || Ty != ReferenceType->getElementType(); 1295 } 1296 case IITDescriptor::Subdivide2Argument: 1297 case IITDescriptor::Subdivide4Argument: { 1298 // If this is a forward reference, defer the check for later. 1299 if (D.getArgumentNumber() >= ArgTys.size()) 1300 return IsDeferredCheck || DeferCheck(Ty); 1301 1302 Type *NewTy = ArgTys[D.getArgumentNumber()]; 1303 if (auto *VTy = dyn_cast<VectorType>(NewTy)) { 1304 int SubDivs = D.Kind == IITDescriptor::Subdivide2Argument ? 1 : 2; 1305 NewTy = VectorType::getSubdividedVectorType(VTy, SubDivs); 1306 return Ty != NewTy; 1307 } 1308 return true; 1309 } 1310 case IITDescriptor::ScalableVecArgument: { 1311 VectorType *VTy = dyn_cast<VectorType>(Ty); 1312 if (!VTy || !VTy->isScalable()) 1313 return true; 1314 return matchIntrinsicType(VTy, Infos, ArgTys, DeferredChecks, 1315 IsDeferredCheck); 1316 } 1317 } 1318 llvm_unreachable("unhandled"); 1319 } 1320 1321 Intrinsic::MatchIntrinsicTypesResult 1322 Intrinsic::matchIntrinsicSignature(FunctionType *FTy, 1323 ArrayRef<Intrinsic::IITDescriptor> &Infos, 1324 SmallVectorImpl<Type *> &ArgTys) { 1325 SmallVector<DeferredIntrinsicMatchPair, 2> DeferredChecks; 1326 if (matchIntrinsicType(FTy->getReturnType(), Infos, ArgTys, DeferredChecks, 1327 false)) 1328 return MatchIntrinsicTypes_NoMatchRet; 1329 1330 unsigned NumDeferredReturnChecks = DeferredChecks.size(); 1331 1332 for (auto Ty : FTy->params()) 1333 if (matchIntrinsicType(Ty, Infos, ArgTys, DeferredChecks, false)) 1334 return MatchIntrinsicTypes_NoMatchArg; 1335 1336 for (unsigned I = 0, E = DeferredChecks.size(); I != E; ++I) { 1337 DeferredIntrinsicMatchPair &Check = DeferredChecks[I]; 1338 if (matchIntrinsicType(Check.first, Check.second, ArgTys, DeferredChecks, 1339 true)) 1340 return I < NumDeferredReturnChecks ? MatchIntrinsicTypes_NoMatchRet 1341 : MatchIntrinsicTypes_NoMatchArg; 1342 } 1343 1344 return MatchIntrinsicTypes_Match; 1345 } 1346 1347 bool 1348 Intrinsic::matchIntrinsicVarArg(bool isVarArg, 1349 ArrayRef<Intrinsic::IITDescriptor> &Infos) { 1350 // If there are no descriptors left, then it can't be a vararg. 1351 if (Infos.empty()) 1352 return isVarArg; 1353 1354 // There should be only one descriptor remaining at this point. 1355 if (Infos.size() != 1) 1356 return true; 1357 1358 // Check and verify the descriptor. 1359 IITDescriptor D = Infos.front(); 1360 Infos = Infos.slice(1); 1361 if (D.Kind == IITDescriptor::VarArg) 1362 return !isVarArg; 1363 1364 return true; 1365 } 1366 1367 Optional<Function*> Intrinsic::remangleIntrinsicFunction(Function *F) { 1368 Intrinsic::ID ID = F->getIntrinsicID(); 1369 if (!ID) 1370 return None; 1371 1372 FunctionType *FTy = F->getFunctionType(); 1373 // Accumulate an array of overloaded types for the given intrinsic 1374 SmallVector<Type *, 4> ArgTys; 1375 { 1376 SmallVector<Intrinsic::IITDescriptor, 8> Table; 1377 getIntrinsicInfoTableEntries(ID, Table); 1378 ArrayRef<Intrinsic::IITDescriptor> TableRef = Table; 1379 1380 if (Intrinsic::matchIntrinsicSignature(FTy, TableRef, ArgTys)) 1381 return None; 1382 if (Intrinsic::matchIntrinsicVarArg(FTy->isVarArg(), TableRef)) 1383 return None; 1384 } 1385 1386 StringRef Name = F->getName(); 1387 if (Name == Intrinsic::getName(ID, ArgTys)) 1388 return None; 1389 1390 auto NewDecl = Intrinsic::getDeclaration(F->getParent(), ID, ArgTys); 1391 NewDecl->setCallingConv(F->getCallingConv()); 1392 assert(NewDecl->getFunctionType() == FTy && "Shouldn't change the signature"); 1393 return NewDecl; 1394 } 1395 1396 /// hasAddressTaken - returns true if there are any uses of this function 1397 /// other than direct calls or invokes to it. 1398 bool Function::hasAddressTaken(const User* *PutOffender) const { 1399 for (const Use &U : uses()) { 1400 const User *FU = U.getUser(); 1401 if (isa<BlockAddress>(FU)) 1402 continue; 1403 const auto *Call = dyn_cast<CallBase>(FU); 1404 if (!Call) { 1405 if (PutOffender) 1406 *PutOffender = FU; 1407 return true; 1408 } 1409 if (!Call->isCallee(&U)) { 1410 if (PutOffender) 1411 *PutOffender = FU; 1412 return true; 1413 } 1414 } 1415 return false; 1416 } 1417 1418 bool Function::isDefTriviallyDead() const { 1419 // Check the linkage 1420 if (!hasLinkOnceLinkage() && !hasLocalLinkage() && 1421 !hasAvailableExternallyLinkage()) 1422 return false; 1423 1424 // Check if the function is used by anything other than a blockaddress. 1425 for (const User *U : users()) 1426 if (!isa<BlockAddress>(U)) 1427 return false; 1428 1429 return true; 1430 } 1431 1432 /// callsFunctionThatReturnsTwice - Return true if the function has a call to 1433 /// setjmp or other function that gcc recognizes as "returning twice". 1434 bool Function::callsFunctionThatReturnsTwice() const { 1435 for (const Instruction &I : instructions(this)) 1436 if (const auto *Call = dyn_cast<CallBase>(&I)) 1437 if (Call->hasFnAttr(Attribute::ReturnsTwice)) 1438 return true; 1439 1440 return false; 1441 } 1442 1443 Constant *Function::getPersonalityFn() const { 1444 assert(hasPersonalityFn() && getNumOperands()); 1445 return cast<Constant>(Op<0>()); 1446 } 1447 1448 void Function::setPersonalityFn(Constant *Fn) { 1449 setHungoffOperand<0>(Fn); 1450 setValueSubclassDataBit(3, Fn != nullptr); 1451 } 1452 1453 Constant *Function::getPrefixData() const { 1454 assert(hasPrefixData() && getNumOperands()); 1455 return cast<Constant>(Op<1>()); 1456 } 1457 1458 void Function::setPrefixData(Constant *PrefixData) { 1459 setHungoffOperand<1>(PrefixData); 1460 setValueSubclassDataBit(1, PrefixData != nullptr); 1461 } 1462 1463 Constant *Function::getPrologueData() const { 1464 assert(hasPrologueData() && getNumOperands()); 1465 return cast<Constant>(Op<2>()); 1466 } 1467 1468 void Function::setPrologueData(Constant *PrologueData) { 1469 setHungoffOperand<2>(PrologueData); 1470 setValueSubclassDataBit(2, PrologueData != nullptr); 1471 } 1472 1473 void Function::allocHungoffUselist() { 1474 // If we've already allocated a uselist, stop here. 1475 if (getNumOperands()) 1476 return; 1477 1478 allocHungoffUses(3, /*IsPhi=*/ false); 1479 setNumHungOffUseOperands(3); 1480 1481 // Initialize the uselist with placeholder operands to allow traversal. 1482 auto *CPN = ConstantPointerNull::get(Type::getInt1PtrTy(getContext(), 0)); 1483 Op<0>().set(CPN); 1484 Op<1>().set(CPN); 1485 Op<2>().set(CPN); 1486 } 1487 1488 template <int Idx> 1489 void Function::setHungoffOperand(Constant *C) { 1490 if (C) { 1491 allocHungoffUselist(); 1492 Op<Idx>().set(C); 1493 } else if (getNumOperands()) { 1494 Op<Idx>().set( 1495 ConstantPointerNull::get(Type::getInt1PtrTy(getContext(), 0))); 1496 } 1497 } 1498 1499 void Function::setValueSubclassDataBit(unsigned Bit, bool On) { 1500 assert(Bit < 16 && "SubclassData contains only 16 bits"); 1501 if (On) 1502 setValueSubclassData(getSubclassDataFromValue() | (1 << Bit)); 1503 else 1504 setValueSubclassData(getSubclassDataFromValue() & ~(1 << Bit)); 1505 } 1506 1507 void Function::setEntryCount(ProfileCount Count, 1508 const DenseSet<GlobalValue::GUID> *S) { 1509 assert(Count.hasValue()); 1510 #if !defined(NDEBUG) 1511 auto PrevCount = getEntryCount(); 1512 assert(!PrevCount.hasValue() || PrevCount.getType() == Count.getType()); 1513 #endif 1514 MDBuilder MDB(getContext()); 1515 setMetadata( 1516 LLVMContext::MD_prof, 1517 MDB.createFunctionEntryCount(Count.getCount(), Count.isSynthetic(), S)); 1518 } 1519 1520 void Function::setEntryCount(uint64_t Count, Function::ProfileCountType Type, 1521 const DenseSet<GlobalValue::GUID> *Imports) { 1522 setEntryCount(ProfileCount(Count, Type), Imports); 1523 } 1524 1525 ProfileCount Function::getEntryCount(bool AllowSynthetic) const { 1526 MDNode *MD = getMetadata(LLVMContext::MD_prof); 1527 if (MD && MD->getOperand(0)) 1528 if (MDString *MDS = dyn_cast<MDString>(MD->getOperand(0))) { 1529 if (MDS->getString().equals("function_entry_count")) { 1530 ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(1)); 1531 uint64_t Count = CI->getValue().getZExtValue(); 1532 // A value of -1 is used for SamplePGO when there were no samples. 1533 // Treat this the same as unknown. 1534 if (Count == (uint64_t)-1) 1535 return ProfileCount::getInvalid(); 1536 return ProfileCount(Count, PCT_Real); 1537 } else if (AllowSynthetic && 1538 MDS->getString().equals("synthetic_function_entry_count")) { 1539 ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(1)); 1540 uint64_t Count = CI->getValue().getZExtValue(); 1541 return ProfileCount(Count, PCT_Synthetic); 1542 } 1543 } 1544 return ProfileCount::getInvalid(); 1545 } 1546 1547 DenseSet<GlobalValue::GUID> Function::getImportGUIDs() const { 1548 DenseSet<GlobalValue::GUID> R; 1549 if (MDNode *MD = getMetadata(LLVMContext::MD_prof)) 1550 if (MDString *MDS = dyn_cast<MDString>(MD->getOperand(0))) 1551 if (MDS->getString().equals("function_entry_count")) 1552 for (unsigned i = 2; i < MD->getNumOperands(); i++) 1553 R.insert(mdconst::extract<ConstantInt>(MD->getOperand(i)) 1554 ->getValue() 1555 .getZExtValue()); 1556 return R; 1557 } 1558 1559 void Function::setSectionPrefix(StringRef Prefix) { 1560 MDBuilder MDB(getContext()); 1561 setMetadata(LLVMContext::MD_section_prefix, 1562 MDB.createFunctionSectionPrefix(Prefix)); 1563 } 1564 1565 Optional<StringRef> Function::getSectionPrefix() const { 1566 if (MDNode *MD = getMetadata(LLVMContext::MD_section_prefix)) { 1567 assert(cast<MDString>(MD->getOperand(0)) 1568 ->getString() 1569 .equals("function_section_prefix") && 1570 "Metadata not match"); 1571 return cast<MDString>(MD->getOperand(1))->getString(); 1572 } 1573 return None; 1574 } 1575 1576 bool Function::nullPointerIsDefined() const { 1577 return getFnAttribute("null-pointer-is-valid") 1578 .getValueAsString() 1579 .equals("true"); 1580 } 1581 1582 bool llvm::NullPointerIsDefined(const Function *F, unsigned AS) { 1583 if (F && F->nullPointerIsDefined()) 1584 return true; 1585 1586 if (AS != 0) 1587 return true; 1588 1589 return false; 1590 } 1591