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