1 //===- Attributes.cpp - Implement AttributesList --------------------------===// 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 // \file 10 // This file implements the Attribute, AttributeImpl, AttrBuilder, 11 // AttributeListImpl, and AttributeList classes. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "llvm/IR/Attributes.h" 16 #include "AttributeImpl.h" 17 #include "LLVMContextImpl.h" 18 #include "llvm/ADT/ArrayRef.h" 19 #include "llvm/ADT/FoldingSet.h" 20 #include "llvm/ADT/Optional.h" 21 #include "llvm/ADT/STLExtras.h" 22 #include "llvm/ADT/SmallVector.h" 23 #include "llvm/ADT/StringExtras.h" 24 #include "llvm/ADT/StringRef.h" 25 #include "llvm/ADT/StringSwitch.h" 26 #include "llvm/Config/llvm-config.h" 27 #include "llvm/IR/Function.h" 28 #include "llvm/IR/LLVMContext.h" 29 #include "llvm/IR/Type.h" 30 #include "llvm/Support/Compiler.h" 31 #include "llvm/Support/ErrorHandling.h" 32 #include "llvm/Support/raw_ostream.h" 33 #include <algorithm> 34 #include <cassert> 35 #include <cstddef> 36 #include <cstdint> 37 #include <limits> 38 #include <string> 39 #include <tuple> 40 #include <utility> 41 42 using namespace llvm; 43 44 //===----------------------------------------------------------------------===// 45 // Attribute Construction Methods 46 //===----------------------------------------------------------------------===// 47 48 // allocsize has two integer arguments, but because they're both 32 bits, we can 49 // pack them into one 64-bit value, at the cost of making said value 50 // nonsensical. 51 // 52 // In order to do this, we need to reserve one value of the second (optional) 53 // allocsize argument to signify "not present." 54 static const unsigned AllocSizeNumElemsNotPresent = -1; 55 56 static uint64_t packAllocSizeArgs(unsigned ElemSizeArg, 57 const Optional<unsigned> &NumElemsArg) { 58 assert((!NumElemsArg.hasValue() || 59 *NumElemsArg != AllocSizeNumElemsNotPresent) && 60 "Attempting to pack a reserved value"); 61 62 return uint64_t(ElemSizeArg) << 32 | 63 NumElemsArg.getValueOr(AllocSizeNumElemsNotPresent); 64 } 65 66 static std::pair<unsigned, Optional<unsigned>> 67 unpackAllocSizeArgs(uint64_t Num) { 68 unsigned NumElems = Num & std::numeric_limits<unsigned>::max(); 69 unsigned ElemSizeArg = Num >> 32; 70 71 Optional<unsigned> NumElemsArg; 72 if (NumElems != AllocSizeNumElemsNotPresent) 73 NumElemsArg = NumElems; 74 return std::make_pair(ElemSizeArg, NumElemsArg); 75 } 76 77 static uint64_t packVScaleRangeArgs(unsigned MinValue, 78 Optional<unsigned> MaxValue) { 79 return uint64_t(MinValue) << 32 | MaxValue.getValueOr(0); 80 } 81 82 static std::pair<unsigned, Optional<unsigned>> 83 unpackVScaleRangeArgs(uint64_t Value) { 84 unsigned MaxValue = Value & std::numeric_limits<unsigned>::max(); 85 unsigned MinValue = Value >> 32; 86 87 return std::make_pair(MinValue, 88 MaxValue > 0 ? MaxValue : Optional<unsigned>()); 89 } 90 91 Attribute Attribute::get(LLVMContext &Context, Attribute::AttrKind Kind, 92 uint64_t Val) { 93 if (Val) 94 assert(Attribute::isIntAttrKind(Kind) && "Not an int attribute"); 95 else 96 assert(Attribute::isEnumAttrKind(Kind) && "Not an enum attribute"); 97 98 LLVMContextImpl *pImpl = Context.pImpl; 99 FoldingSetNodeID ID; 100 ID.AddInteger(Kind); 101 if (Val) ID.AddInteger(Val); 102 103 void *InsertPoint; 104 AttributeImpl *PA = pImpl->AttrsSet.FindNodeOrInsertPos(ID, InsertPoint); 105 106 if (!PA) { 107 // If we didn't find any existing attributes of the same shape then create a 108 // new one and insert it. 109 if (!Val) 110 PA = new (pImpl->Alloc) EnumAttributeImpl(Kind); 111 else 112 PA = new (pImpl->Alloc) IntAttributeImpl(Kind, Val); 113 pImpl->AttrsSet.InsertNode(PA, InsertPoint); 114 } 115 116 // Return the Attribute that we found or created. 117 return Attribute(PA); 118 } 119 120 Attribute Attribute::get(LLVMContext &Context, StringRef Kind, StringRef Val) { 121 LLVMContextImpl *pImpl = Context.pImpl; 122 FoldingSetNodeID ID; 123 ID.AddString(Kind); 124 if (!Val.empty()) ID.AddString(Val); 125 126 void *InsertPoint; 127 AttributeImpl *PA = pImpl->AttrsSet.FindNodeOrInsertPos(ID, InsertPoint); 128 129 if (!PA) { 130 // If we didn't find any existing attributes of the same shape then create a 131 // new one and insert it. 132 void *Mem = 133 pImpl->Alloc.Allocate(StringAttributeImpl::totalSizeToAlloc(Kind, Val), 134 alignof(StringAttributeImpl)); 135 PA = new (Mem) StringAttributeImpl(Kind, Val); 136 pImpl->AttrsSet.InsertNode(PA, InsertPoint); 137 } 138 139 // Return the Attribute that we found or created. 140 return Attribute(PA); 141 } 142 143 Attribute Attribute::get(LLVMContext &Context, Attribute::AttrKind Kind, 144 Type *Ty) { 145 assert(Attribute::isTypeAttrKind(Kind) && "Not a type attribute"); 146 LLVMContextImpl *pImpl = Context.pImpl; 147 FoldingSetNodeID ID; 148 ID.AddInteger(Kind); 149 ID.AddPointer(Ty); 150 151 void *InsertPoint; 152 AttributeImpl *PA = pImpl->AttrsSet.FindNodeOrInsertPos(ID, InsertPoint); 153 154 if (!PA) { 155 // If we didn't find any existing attributes of the same shape then create a 156 // new one and insert it. 157 PA = new (pImpl->Alloc) TypeAttributeImpl(Kind, Ty); 158 pImpl->AttrsSet.InsertNode(PA, InsertPoint); 159 } 160 161 // Return the Attribute that we found or created. 162 return Attribute(PA); 163 } 164 165 Attribute Attribute::getWithAlignment(LLVMContext &Context, Align A) { 166 assert(A <= llvm::Value::MaximumAlignment && "Alignment too large."); 167 return get(Context, Alignment, A.value()); 168 } 169 170 Attribute Attribute::getWithStackAlignment(LLVMContext &Context, Align A) { 171 assert(A <= 0x100 && "Alignment too large."); 172 return get(Context, StackAlignment, A.value()); 173 } 174 175 Attribute Attribute::getWithDereferenceableBytes(LLVMContext &Context, 176 uint64_t Bytes) { 177 assert(Bytes && "Bytes must be non-zero."); 178 return get(Context, Dereferenceable, Bytes); 179 } 180 181 Attribute Attribute::getWithDereferenceableOrNullBytes(LLVMContext &Context, 182 uint64_t Bytes) { 183 assert(Bytes && "Bytes must be non-zero."); 184 return get(Context, DereferenceableOrNull, Bytes); 185 } 186 187 Attribute Attribute::getWithByValType(LLVMContext &Context, Type *Ty) { 188 return get(Context, ByVal, Ty); 189 } 190 191 Attribute Attribute::getWithStructRetType(LLVMContext &Context, Type *Ty) { 192 return get(Context, StructRet, Ty); 193 } 194 195 Attribute Attribute::getWithByRefType(LLVMContext &Context, Type *Ty) { 196 return get(Context, ByRef, Ty); 197 } 198 199 Attribute Attribute::getWithPreallocatedType(LLVMContext &Context, Type *Ty) { 200 return get(Context, Preallocated, Ty); 201 } 202 203 Attribute Attribute::getWithInAllocaType(LLVMContext &Context, Type *Ty) { 204 return get(Context, InAlloca, Ty); 205 } 206 207 Attribute Attribute::getWithUWTableKind(LLVMContext &Context, 208 UWTableKind Kind) { 209 return get(Context, UWTable, uint64_t(Kind)); 210 } 211 212 Attribute 213 Attribute::getWithAllocSizeArgs(LLVMContext &Context, unsigned ElemSizeArg, 214 const Optional<unsigned> &NumElemsArg) { 215 assert(!(ElemSizeArg == 0 && NumElemsArg && *NumElemsArg == 0) && 216 "Invalid allocsize arguments -- given allocsize(0, 0)"); 217 return get(Context, AllocSize, packAllocSizeArgs(ElemSizeArg, NumElemsArg)); 218 } 219 220 Attribute Attribute::getWithVScaleRangeArgs(LLVMContext &Context, 221 unsigned MinValue, 222 unsigned MaxValue) { 223 return get(Context, VScaleRange, packVScaleRangeArgs(MinValue, MaxValue)); 224 } 225 226 Attribute::AttrKind Attribute::getAttrKindFromName(StringRef AttrName) { 227 return StringSwitch<Attribute::AttrKind>(AttrName) 228 #define GET_ATTR_NAMES 229 #define ATTRIBUTE_ENUM(ENUM_NAME, DISPLAY_NAME) \ 230 .Case(#DISPLAY_NAME, Attribute::ENUM_NAME) 231 #include "llvm/IR/Attributes.inc" 232 .Default(Attribute::None); 233 } 234 235 StringRef Attribute::getNameFromAttrKind(Attribute::AttrKind AttrKind) { 236 switch (AttrKind) { 237 #define GET_ATTR_NAMES 238 #define ATTRIBUTE_ENUM(ENUM_NAME, DISPLAY_NAME) \ 239 case Attribute::ENUM_NAME: \ 240 return #DISPLAY_NAME; 241 #include "llvm/IR/Attributes.inc" 242 case Attribute::None: 243 return "none"; 244 default: 245 llvm_unreachable("invalid Kind"); 246 } 247 } 248 249 bool Attribute::isExistingAttribute(StringRef Name) { 250 return StringSwitch<bool>(Name) 251 #define GET_ATTR_NAMES 252 #define ATTRIBUTE_ALL(ENUM_NAME, DISPLAY_NAME) .Case(#DISPLAY_NAME, true) 253 #include "llvm/IR/Attributes.inc" 254 .Default(false); 255 } 256 257 //===----------------------------------------------------------------------===// 258 // Attribute Accessor Methods 259 //===----------------------------------------------------------------------===// 260 261 bool Attribute::isEnumAttribute() const { 262 return pImpl && pImpl->isEnumAttribute(); 263 } 264 265 bool Attribute::isIntAttribute() const { 266 return pImpl && pImpl->isIntAttribute(); 267 } 268 269 bool Attribute::isStringAttribute() const { 270 return pImpl && pImpl->isStringAttribute(); 271 } 272 273 bool Attribute::isTypeAttribute() const { 274 return pImpl && pImpl->isTypeAttribute(); 275 } 276 277 Attribute::AttrKind Attribute::getKindAsEnum() const { 278 if (!pImpl) return None; 279 assert((isEnumAttribute() || isIntAttribute() || isTypeAttribute()) && 280 "Invalid attribute type to get the kind as an enum!"); 281 return pImpl->getKindAsEnum(); 282 } 283 284 uint64_t Attribute::getValueAsInt() const { 285 if (!pImpl) return 0; 286 assert(isIntAttribute() && 287 "Expected the attribute to be an integer attribute!"); 288 return pImpl->getValueAsInt(); 289 } 290 291 bool Attribute::getValueAsBool() const { 292 if (!pImpl) return false; 293 assert(isStringAttribute() && 294 "Expected the attribute to be a string attribute!"); 295 return pImpl->getValueAsBool(); 296 } 297 298 StringRef Attribute::getKindAsString() const { 299 if (!pImpl) return {}; 300 assert(isStringAttribute() && 301 "Invalid attribute type to get the kind as a string!"); 302 return pImpl->getKindAsString(); 303 } 304 305 StringRef Attribute::getValueAsString() const { 306 if (!pImpl) return {}; 307 assert(isStringAttribute() && 308 "Invalid attribute type to get the value as a string!"); 309 return pImpl->getValueAsString(); 310 } 311 312 Type *Attribute::getValueAsType() const { 313 if (!pImpl) return {}; 314 assert(isTypeAttribute() && 315 "Invalid attribute type to get the value as a type!"); 316 return pImpl->getValueAsType(); 317 } 318 319 320 bool Attribute::hasAttribute(AttrKind Kind) const { 321 return (pImpl && pImpl->hasAttribute(Kind)) || (!pImpl && Kind == None); 322 } 323 324 bool Attribute::hasAttribute(StringRef Kind) const { 325 if (!isStringAttribute()) return false; 326 return pImpl && pImpl->hasAttribute(Kind); 327 } 328 329 MaybeAlign Attribute::getAlignment() const { 330 assert(hasAttribute(Attribute::Alignment) && 331 "Trying to get alignment from non-alignment attribute!"); 332 return MaybeAlign(pImpl->getValueAsInt()); 333 } 334 335 MaybeAlign Attribute::getStackAlignment() const { 336 assert(hasAttribute(Attribute::StackAlignment) && 337 "Trying to get alignment from non-alignment attribute!"); 338 return MaybeAlign(pImpl->getValueAsInt()); 339 } 340 341 uint64_t Attribute::getDereferenceableBytes() const { 342 assert(hasAttribute(Attribute::Dereferenceable) && 343 "Trying to get dereferenceable bytes from " 344 "non-dereferenceable attribute!"); 345 return pImpl->getValueAsInt(); 346 } 347 348 uint64_t Attribute::getDereferenceableOrNullBytes() const { 349 assert(hasAttribute(Attribute::DereferenceableOrNull) && 350 "Trying to get dereferenceable bytes from " 351 "non-dereferenceable attribute!"); 352 return pImpl->getValueAsInt(); 353 } 354 355 std::pair<unsigned, Optional<unsigned>> Attribute::getAllocSizeArgs() const { 356 assert(hasAttribute(Attribute::AllocSize) && 357 "Trying to get allocsize args from non-allocsize attribute"); 358 return unpackAllocSizeArgs(pImpl->getValueAsInt()); 359 } 360 361 unsigned Attribute::getVScaleRangeMin() const { 362 assert(hasAttribute(Attribute::VScaleRange) && 363 "Trying to get vscale args from non-vscale attribute"); 364 return unpackVScaleRangeArgs(pImpl->getValueAsInt()).first; 365 } 366 367 Optional<unsigned> Attribute::getVScaleRangeMax() const { 368 assert(hasAttribute(Attribute::VScaleRange) && 369 "Trying to get vscale args from non-vscale attribute"); 370 return unpackVScaleRangeArgs(pImpl->getValueAsInt()).second; 371 } 372 373 UWTableKind Attribute::getUWTableKind() const { 374 assert(hasAttribute(Attribute::UWTable) && 375 "Trying to get unwind table kind from non-uwtable attribute"); 376 return UWTableKind(pImpl->getValueAsInt()); 377 } 378 379 std::string Attribute::getAsString(bool InAttrGrp) const { 380 if (!pImpl) return {}; 381 382 if (isEnumAttribute()) 383 return getNameFromAttrKind(getKindAsEnum()).str(); 384 385 if (isTypeAttribute()) { 386 std::string Result = getNameFromAttrKind(getKindAsEnum()).str(); 387 Result += '('; 388 raw_string_ostream OS(Result); 389 getValueAsType()->print(OS, false, true); 390 OS.flush(); 391 Result += ')'; 392 return Result; 393 } 394 395 // FIXME: These should be output like this: 396 // 397 // align=4 398 // alignstack=8 399 // 400 if (hasAttribute(Attribute::Alignment)) 401 return (InAttrGrp ? "align=" + Twine(getValueAsInt()) 402 : "align " + Twine(getValueAsInt())) 403 .str(); 404 405 auto AttrWithBytesToString = [&](const char *Name) { 406 return (InAttrGrp ? Name + ("=" + Twine(getValueAsInt())) 407 : Name + ("(" + Twine(getValueAsInt())) + ")") 408 .str(); 409 }; 410 411 if (hasAttribute(Attribute::StackAlignment)) 412 return AttrWithBytesToString("alignstack"); 413 414 if (hasAttribute(Attribute::Dereferenceable)) 415 return AttrWithBytesToString("dereferenceable"); 416 417 if (hasAttribute(Attribute::DereferenceableOrNull)) 418 return AttrWithBytesToString("dereferenceable_or_null"); 419 420 if (hasAttribute(Attribute::AllocSize)) { 421 unsigned ElemSize; 422 Optional<unsigned> NumElems; 423 std::tie(ElemSize, NumElems) = getAllocSizeArgs(); 424 425 return (NumElems 426 ? "allocsize(" + Twine(ElemSize) + "," + Twine(*NumElems) + ")" 427 : "allocsize(" + Twine(ElemSize) + ")") 428 .str(); 429 } 430 431 if (hasAttribute(Attribute::VScaleRange)) { 432 unsigned MinValue = getVScaleRangeMin(); 433 Optional<unsigned> MaxValue = getVScaleRangeMax(); 434 return ("vscale_range(" + Twine(MinValue) + "," + 435 Twine(MaxValue.getValueOr(0)) + ")") 436 .str(); 437 } 438 439 if (hasAttribute(Attribute::UWTable)) { 440 UWTableKind Kind = getUWTableKind(); 441 if (Kind != UWTableKind::None) { 442 return Kind == UWTableKind::Default 443 ? "uwtable" 444 : ("uwtable(" + 445 Twine(Kind == UWTableKind::Sync ? "sync" : "async") + ")") 446 .str(); 447 } 448 } 449 450 // Convert target-dependent attributes to strings of the form: 451 // 452 // "kind" 453 // "kind" = "value" 454 // 455 if (isStringAttribute()) { 456 std::string Result; 457 { 458 raw_string_ostream OS(Result); 459 OS << '"' << getKindAsString() << '"'; 460 461 // Since some attribute strings contain special characters that cannot be 462 // printable, those have to be escaped to make the attribute value 463 // printable as is. e.g. "\01__gnu_mcount_nc" 464 const auto &AttrVal = pImpl->getValueAsString(); 465 if (!AttrVal.empty()) { 466 OS << "=\""; 467 printEscapedString(AttrVal, OS); 468 OS << "\""; 469 } 470 } 471 return Result; 472 } 473 474 llvm_unreachable("Unknown attribute"); 475 } 476 477 bool Attribute::hasParentContext(LLVMContext &C) const { 478 assert(isValid() && "invalid Attribute doesn't refer to any context"); 479 FoldingSetNodeID ID; 480 pImpl->Profile(ID); 481 void *Unused; 482 return C.pImpl->AttrsSet.FindNodeOrInsertPos(ID, Unused) == pImpl; 483 } 484 485 bool Attribute::operator<(Attribute A) const { 486 if (!pImpl && !A.pImpl) return false; 487 if (!pImpl) return true; 488 if (!A.pImpl) return false; 489 return *pImpl < *A.pImpl; 490 } 491 492 void Attribute::Profile(FoldingSetNodeID &ID) const { 493 ID.AddPointer(pImpl); 494 } 495 496 enum AttributeProperty { 497 FnAttr = (1 << 0), 498 ParamAttr = (1 << 1), 499 RetAttr = (1 << 2), 500 }; 501 502 #define GET_ATTR_PROP_TABLE 503 #include "llvm/IR/Attributes.inc" 504 505 static bool hasAttributeProperty(Attribute::AttrKind Kind, 506 AttributeProperty Prop) { 507 unsigned Index = Kind - 1; 508 assert(Index < sizeof(AttrPropTable) / sizeof(AttrPropTable[0]) && 509 "Invalid attribute kind"); 510 return AttrPropTable[Index] & Prop; 511 } 512 513 bool Attribute::canUseAsFnAttr(AttrKind Kind) { 514 return hasAttributeProperty(Kind, AttributeProperty::FnAttr); 515 } 516 517 bool Attribute::canUseAsParamAttr(AttrKind Kind) { 518 return hasAttributeProperty(Kind, AttributeProperty::ParamAttr); 519 } 520 521 bool Attribute::canUseAsRetAttr(AttrKind Kind) { 522 return hasAttributeProperty(Kind, AttributeProperty::RetAttr); 523 } 524 525 //===----------------------------------------------------------------------===// 526 // AttributeImpl Definition 527 //===----------------------------------------------------------------------===// 528 529 bool AttributeImpl::hasAttribute(Attribute::AttrKind A) const { 530 if (isStringAttribute()) return false; 531 return getKindAsEnum() == A; 532 } 533 534 bool AttributeImpl::hasAttribute(StringRef Kind) const { 535 if (!isStringAttribute()) return false; 536 return getKindAsString() == Kind; 537 } 538 539 Attribute::AttrKind AttributeImpl::getKindAsEnum() const { 540 assert(isEnumAttribute() || isIntAttribute() || isTypeAttribute()); 541 return static_cast<const EnumAttributeImpl *>(this)->getEnumKind(); 542 } 543 544 uint64_t AttributeImpl::getValueAsInt() const { 545 assert(isIntAttribute()); 546 return static_cast<const IntAttributeImpl *>(this)->getValue(); 547 } 548 549 bool AttributeImpl::getValueAsBool() const { 550 assert(getValueAsString().empty() || getValueAsString() == "false" || getValueAsString() == "true"); 551 return getValueAsString() == "true"; 552 } 553 554 StringRef AttributeImpl::getKindAsString() const { 555 assert(isStringAttribute()); 556 return static_cast<const StringAttributeImpl *>(this)->getStringKind(); 557 } 558 559 StringRef AttributeImpl::getValueAsString() const { 560 assert(isStringAttribute()); 561 return static_cast<const StringAttributeImpl *>(this)->getStringValue(); 562 } 563 564 Type *AttributeImpl::getValueAsType() const { 565 assert(isTypeAttribute()); 566 return static_cast<const TypeAttributeImpl *>(this)->getTypeValue(); 567 } 568 569 bool AttributeImpl::operator<(const AttributeImpl &AI) const { 570 if (this == &AI) 571 return false; 572 573 // This sorts the attributes with Attribute::AttrKinds coming first (sorted 574 // relative to their enum value) and then strings. 575 if (!isStringAttribute()) { 576 if (AI.isStringAttribute()) 577 return true; 578 if (getKindAsEnum() != AI.getKindAsEnum()) 579 return getKindAsEnum() < AI.getKindAsEnum(); 580 assert(!AI.isEnumAttribute() && "Non-unique attribute"); 581 assert(!AI.isTypeAttribute() && "Comparison of types would be unstable"); 582 // TODO: Is this actually needed? 583 assert(AI.isIntAttribute() && "Only possibility left"); 584 return getValueAsInt() < AI.getValueAsInt(); 585 } 586 587 if (!AI.isStringAttribute()) 588 return false; 589 if (getKindAsString() == AI.getKindAsString()) 590 return getValueAsString() < AI.getValueAsString(); 591 return getKindAsString() < AI.getKindAsString(); 592 } 593 594 //===----------------------------------------------------------------------===// 595 // AttributeSet Definition 596 //===----------------------------------------------------------------------===// 597 598 AttributeSet AttributeSet::get(LLVMContext &C, const AttrBuilder &B) { 599 return AttributeSet(AttributeSetNode::get(C, B)); 600 } 601 602 AttributeSet AttributeSet::get(LLVMContext &C, ArrayRef<Attribute> Attrs) { 603 return AttributeSet(AttributeSetNode::get(C, Attrs)); 604 } 605 606 AttributeSet AttributeSet::addAttribute(LLVMContext &C, 607 Attribute::AttrKind Kind) const { 608 if (hasAttribute(Kind)) return *this; 609 AttrBuilder B(C); 610 B.addAttribute(Kind); 611 return addAttributes(C, AttributeSet::get(C, B)); 612 } 613 614 AttributeSet AttributeSet::addAttribute(LLVMContext &C, StringRef Kind, 615 StringRef Value) const { 616 AttrBuilder B(C); 617 B.addAttribute(Kind, Value); 618 return addAttributes(C, AttributeSet::get(C, B)); 619 } 620 621 AttributeSet AttributeSet::addAttributes(LLVMContext &C, 622 const AttributeSet AS) const { 623 if (!hasAttributes()) 624 return AS; 625 626 if (!AS.hasAttributes()) 627 return *this; 628 629 AttrBuilder B(C, *this); 630 B.merge(AttrBuilder(C, AS)); 631 return get(C, B); 632 } 633 634 AttributeSet AttributeSet::removeAttribute(LLVMContext &C, 635 Attribute::AttrKind Kind) const { 636 if (!hasAttribute(Kind)) return *this; 637 AttrBuilder B(C, *this); 638 B.removeAttribute(Kind); 639 return get(C, B); 640 } 641 642 AttributeSet AttributeSet::removeAttribute(LLVMContext &C, 643 StringRef Kind) const { 644 if (!hasAttribute(Kind)) return *this; 645 AttrBuilder B(C, *this); 646 B.removeAttribute(Kind); 647 return get(C, B); 648 } 649 650 AttributeSet AttributeSet::removeAttributes(LLVMContext &C, 651 const AttributeMask &Attrs) const { 652 AttrBuilder B(C, *this); 653 // If there is nothing to remove, directly return the original set. 654 if (!B.overlaps(Attrs)) 655 return *this; 656 657 B.remove(Attrs); 658 return get(C, B); 659 } 660 661 unsigned AttributeSet::getNumAttributes() const { 662 return SetNode ? SetNode->getNumAttributes() : 0; 663 } 664 665 bool AttributeSet::hasAttribute(Attribute::AttrKind Kind) const { 666 return SetNode ? SetNode->hasAttribute(Kind) : false; 667 } 668 669 bool AttributeSet::hasAttribute(StringRef Kind) const { 670 return SetNode ? SetNode->hasAttribute(Kind) : false; 671 } 672 673 Attribute AttributeSet::getAttribute(Attribute::AttrKind Kind) const { 674 return SetNode ? SetNode->getAttribute(Kind) : Attribute(); 675 } 676 677 Attribute AttributeSet::getAttribute(StringRef Kind) const { 678 return SetNode ? SetNode->getAttribute(Kind) : Attribute(); 679 } 680 681 MaybeAlign AttributeSet::getAlignment() const { 682 return SetNode ? SetNode->getAlignment() : None; 683 } 684 685 MaybeAlign AttributeSet::getStackAlignment() const { 686 return SetNode ? SetNode->getStackAlignment() : None; 687 } 688 689 uint64_t AttributeSet::getDereferenceableBytes() const { 690 return SetNode ? SetNode->getDereferenceableBytes() : 0; 691 } 692 693 uint64_t AttributeSet::getDereferenceableOrNullBytes() const { 694 return SetNode ? SetNode->getDereferenceableOrNullBytes() : 0; 695 } 696 697 Type *AttributeSet::getByRefType() const { 698 return SetNode ? SetNode->getAttributeType(Attribute::ByRef) : nullptr; 699 } 700 701 Type *AttributeSet::getByValType() const { 702 return SetNode ? SetNode->getAttributeType(Attribute::ByVal) : nullptr; 703 } 704 705 Type *AttributeSet::getStructRetType() const { 706 return SetNode ? SetNode->getAttributeType(Attribute::StructRet) : nullptr; 707 } 708 709 Type *AttributeSet::getPreallocatedType() const { 710 return SetNode ? SetNode->getAttributeType(Attribute::Preallocated) : nullptr; 711 } 712 713 Type *AttributeSet::getInAllocaType() const { 714 return SetNode ? SetNode->getAttributeType(Attribute::InAlloca) : nullptr; 715 } 716 717 Type *AttributeSet::getElementType() const { 718 return SetNode ? SetNode->getAttributeType(Attribute::ElementType) : nullptr; 719 } 720 721 std::pair<unsigned, Optional<unsigned>> AttributeSet::getAllocSizeArgs() const { 722 return SetNode ? SetNode->getAllocSizeArgs() 723 : std::pair<unsigned, Optional<unsigned>>(0, 0); 724 } 725 726 unsigned AttributeSet::getVScaleRangeMin() const { 727 return SetNode ? SetNode->getVScaleRangeMin() : 1; 728 } 729 730 Optional<unsigned> AttributeSet::getVScaleRangeMax() const { 731 return SetNode ? SetNode->getVScaleRangeMax() : None; 732 } 733 734 UWTableKind AttributeSet::getUWTableKind() const { 735 return SetNode ? SetNode->getUWTableKind() : UWTableKind::None; 736 } 737 738 std::string AttributeSet::getAsString(bool InAttrGrp) const { 739 return SetNode ? SetNode->getAsString(InAttrGrp) : ""; 740 } 741 742 bool AttributeSet::hasParentContext(LLVMContext &C) const { 743 assert(hasAttributes() && "empty AttributeSet doesn't refer to any context"); 744 FoldingSetNodeID ID; 745 SetNode->Profile(ID); 746 void *Unused; 747 return C.pImpl->AttrsSetNodes.FindNodeOrInsertPos(ID, Unused) == SetNode; 748 } 749 750 AttributeSet::iterator AttributeSet::begin() const { 751 return SetNode ? SetNode->begin() : nullptr; 752 } 753 754 AttributeSet::iterator AttributeSet::end() const { 755 return SetNode ? SetNode->end() : nullptr; 756 } 757 758 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 759 LLVM_DUMP_METHOD void AttributeSet::dump() const { 760 dbgs() << "AS =\n"; 761 dbgs() << " { "; 762 dbgs() << getAsString(true) << " }\n"; 763 } 764 #endif 765 766 //===----------------------------------------------------------------------===// 767 // AttributeSetNode Definition 768 //===----------------------------------------------------------------------===// 769 770 AttributeSetNode::AttributeSetNode(ArrayRef<Attribute> Attrs) 771 : NumAttrs(Attrs.size()) { 772 // There's memory after the node where we can store the entries in. 773 llvm::copy(Attrs, getTrailingObjects<Attribute>()); 774 775 for (const auto &I : *this) { 776 if (I.isStringAttribute()) 777 StringAttrs.insert({ I.getKindAsString(), I }); 778 else 779 AvailableAttrs.addAttribute(I.getKindAsEnum()); 780 } 781 } 782 783 AttributeSetNode *AttributeSetNode::get(LLVMContext &C, 784 ArrayRef<Attribute> Attrs) { 785 SmallVector<Attribute, 8> SortedAttrs(Attrs.begin(), Attrs.end()); 786 llvm::sort(SortedAttrs); 787 return getSorted(C, SortedAttrs); 788 } 789 790 AttributeSetNode *AttributeSetNode::getSorted(LLVMContext &C, 791 ArrayRef<Attribute> SortedAttrs) { 792 if (SortedAttrs.empty()) 793 return nullptr; 794 795 // Build a key to look up the existing attributes. 796 LLVMContextImpl *pImpl = C.pImpl; 797 FoldingSetNodeID ID; 798 799 assert(llvm::is_sorted(SortedAttrs) && "Expected sorted attributes!"); 800 for (const auto &Attr : SortedAttrs) 801 Attr.Profile(ID); 802 803 void *InsertPoint; 804 AttributeSetNode *PA = 805 pImpl->AttrsSetNodes.FindNodeOrInsertPos(ID, InsertPoint); 806 807 // If we didn't find any existing attributes of the same shape then create a 808 // new one and insert it. 809 if (!PA) { 810 // Coallocate entries after the AttributeSetNode itself. 811 void *Mem = ::operator new(totalSizeToAlloc<Attribute>(SortedAttrs.size())); 812 PA = new (Mem) AttributeSetNode(SortedAttrs); 813 pImpl->AttrsSetNodes.InsertNode(PA, InsertPoint); 814 } 815 816 // Return the AttributeSetNode that we found or created. 817 return PA; 818 } 819 820 AttributeSetNode *AttributeSetNode::get(LLVMContext &C, const AttrBuilder &B) { 821 return getSorted(C, B.attrs()); 822 } 823 824 bool AttributeSetNode::hasAttribute(StringRef Kind) const { 825 return StringAttrs.count(Kind); 826 } 827 828 Optional<Attribute> 829 AttributeSetNode::findEnumAttribute(Attribute::AttrKind Kind) const { 830 // Do a quick presence check. 831 if (!hasAttribute(Kind)) 832 return None; 833 834 // Attributes in a set are sorted by enum value, followed by string 835 // attributes. Binary search the one we want. 836 const Attribute *I = 837 std::lower_bound(begin(), end() - StringAttrs.size(), Kind, 838 [](Attribute A, Attribute::AttrKind Kind) { 839 return A.getKindAsEnum() < Kind; 840 }); 841 assert(I != end() && I->hasAttribute(Kind) && "Presence check failed?"); 842 return *I; 843 } 844 845 Attribute AttributeSetNode::getAttribute(Attribute::AttrKind Kind) const { 846 if (auto A = findEnumAttribute(Kind)) 847 return *A; 848 return {}; 849 } 850 851 Attribute AttributeSetNode::getAttribute(StringRef Kind) const { 852 return StringAttrs.lookup(Kind); 853 } 854 855 MaybeAlign AttributeSetNode::getAlignment() const { 856 if (auto A = findEnumAttribute(Attribute::Alignment)) 857 return A->getAlignment(); 858 return None; 859 } 860 861 MaybeAlign AttributeSetNode::getStackAlignment() const { 862 if (auto A = findEnumAttribute(Attribute::StackAlignment)) 863 return A->getStackAlignment(); 864 return None; 865 } 866 867 Type *AttributeSetNode::getAttributeType(Attribute::AttrKind Kind) const { 868 if (auto A = findEnumAttribute(Kind)) 869 return A->getValueAsType(); 870 return nullptr; 871 } 872 873 uint64_t AttributeSetNode::getDereferenceableBytes() const { 874 if (auto A = findEnumAttribute(Attribute::Dereferenceable)) 875 return A->getDereferenceableBytes(); 876 return 0; 877 } 878 879 uint64_t AttributeSetNode::getDereferenceableOrNullBytes() const { 880 if (auto A = findEnumAttribute(Attribute::DereferenceableOrNull)) 881 return A->getDereferenceableOrNullBytes(); 882 return 0; 883 } 884 885 std::pair<unsigned, Optional<unsigned>> 886 AttributeSetNode::getAllocSizeArgs() const { 887 if (auto A = findEnumAttribute(Attribute::AllocSize)) 888 return A->getAllocSizeArgs(); 889 return std::make_pair(0, 0); 890 } 891 892 unsigned AttributeSetNode::getVScaleRangeMin() const { 893 if (auto A = findEnumAttribute(Attribute::VScaleRange)) 894 return A->getVScaleRangeMin(); 895 return 1; 896 } 897 898 Optional<unsigned> AttributeSetNode::getVScaleRangeMax() const { 899 if (auto A = findEnumAttribute(Attribute::VScaleRange)) 900 return A->getVScaleRangeMax(); 901 return None; 902 } 903 904 UWTableKind AttributeSetNode::getUWTableKind() const { 905 if (auto A = findEnumAttribute(Attribute::UWTable)) 906 return A->getUWTableKind(); 907 return UWTableKind::None; 908 } 909 910 std::string AttributeSetNode::getAsString(bool InAttrGrp) const { 911 std::string Str; 912 for (iterator I = begin(), E = end(); I != E; ++I) { 913 if (I != begin()) 914 Str += ' '; 915 Str += I->getAsString(InAttrGrp); 916 } 917 return Str; 918 } 919 920 //===----------------------------------------------------------------------===// 921 // AttributeListImpl Definition 922 //===----------------------------------------------------------------------===// 923 924 /// Map from AttributeList index to the internal array index. Adding one happens 925 /// to work, because -1 wraps around to 0. 926 static unsigned attrIdxToArrayIdx(unsigned Index) { 927 return Index + 1; 928 } 929 930 AttributeListImpl::AttributeListImpl(ArrayRef<AttributeSet> Sets) 931 : NumAttrSets(Sets.size()) { 932 assert(!Sets.empty() && "pointless AttributeListImpl"); 933 934 // There's memory after the node where we can store the entries in. 935 llvm::copy(Sets, getTrailingObjects<AttributeSet>()); 936 937 // Initialize AvailableFunctionAttrs and AvailableSomewhereAttrs 938 // summary bitsets. 939 for (const auto &I : Sets[attrIdxToArrayIdx(AttributeList::FunctionIndex)]) 940 if (!I.isStringAttribute()) 941 AvailableFunctionAttrs.addAttribute(I.getKindAsEnum()); 942 943 for (const auto &Set : Sets) 944 for (const auto &I : Set) 945 if (!I.isStringAttribute()) 946 AvailableSomewhereAttrs.addAttribute(I.getKindAsEnum()); 947 } 948 949 void AttributeListImpl::Profile(FoldingSetNodeID &ID) const { 950 Profile(ID, makeArrayRef(begin(), end())); 951 } 952 953 void AttributeListImpl::Profile(FoldingSetNodeID &ID, 954 ArrayRef<AttributeSet> Sets) { 955 for (const auto &Set : Sets) 956 ID.AddPointer(Set.SetNode); 957 } 958 959 bool AttributeListImpl::hasAttrSomewhere(Attribute::AttrKind Kind, 960 unsigned *Index) const { 961 if (!AvailableSomewhereAttrs.hasAttribute(Kind)) 962 return false; 963 964 if (Index) { 965 for (unsigned I = 0, E = NumAttrSets; I != E; ++I) { 966 if (begin()[I].hasAttribute(Kind)) { 967 *Index = I - 1; 968 break; 969 } 970 } 971 } 972 973 return true; 974 } 975 976 977 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 978 LLVM_DUMP_METHOD void AttributeListImpl::dump() const { 979 AttributeList(const_cast<AttributeListImpl *>(this)).dump(); 980 } 981 #endif 982 983 //===----------------------------------------------------------------------===// 984 // AttributeList Construction and Mutation Methods 985 //===----------------------------------------------------------------------===// 986 987 AttributeList AttributeList::getImpl(LLVMContext &C, 988 ArrayRef<AttributeSet> AttrSets) { 989 assert(!AttrSets.empty() && "pointless AttributeListImpl"); 990 991 LLVMContextImpl *pImpl = C.pImpl; 992 FoldingSetNodeID ID; 993 AttributeListImpl::Profile(ID, AttrSets); 994 995 void *InsertPoint; 996 AttributeListImpl *PA = 997 pImpl->AttrsLists.FindNodeOrInsertPos(ID, InsertPoint); 998 999 // If we didn't find any existing attributes of the same shape then 1000 // create a new one and insert it. 1001 if (!PA) { 1002 // Coallocate entries after the AttributeListImpl itself. 1003 void *Mem = pImpl->Alloc.Allocate( 1004 AttributeListImpl::totalSizeToAlloc<AttributeSet>(AttrSets.size()), 1005 alignof(AttributeListImpl)); 1006 PA = new (Mem) AttributeListImpl(AttrSets); 1007 pImpl->AttrsLists.InsertNode(PA, InsertPoint); 1008 } 1009 1010 // Return the AttributesList that we found or created. 1011 return AttributeList(PA); 1012 } 1013 1014 AttributeList 1015 AttributeList::get(LLVMContext &C, 1016 ArrayRef<std::pair<unsigned, Attribute>> Attrs) { 1017 // If there are no attributes then return a null AttributesList pointer. 1018 if (Attrs.empty()) 1019 return {}; 1020 1021 assert(llvm::is_sorted(Attrs, 1022 [](const std::pair<unsigned, Attribute> &LHS, 1023 const std::pair<unsigned, Attribute> &RHS) { 1024 return LHS.first < RHS.first; 1025 }) && 1026 "Misordered Attributes list!"); 1027 assert(llvm::all_of(Attrs, 1028 [](const std::pair<unsigned, Attribute> &Pair) { 1029 return Pair.second.isValid(); 1030 }) && 1031 "Pointless attribute!"); 1032 1033 // Create a vector if (unsigned, AttributeSetNode*) pairs from the attributes 1034 // list. 1035 SmallVector<std::pair<unsigned, AttributeSet>, 8> AttrPairVec; 1036 for (ArrayRef<std::pair<unsigned, Attribute>>::iterator I = Attrs.begin(), 1037 E = Attrs.end(); I != E; ) { 1038 unsigned Index = I->first; 1039 SmallVector<Attribute, 4> AttrVec; 1040 while (I != E && I->first == Index) { 1041 AttrVec.push_back(I->second); 1042 ++I; 1043 } 1044 1045 AttrPairVec.emplace_back(Index, AttributeSet::get(C, AttrVec)); 1046 } 1047 1048 return get(C, AttrPairVec); 1049 } 1050 1051 AttributeList 1052 AttributeList::get(LLVMContext &C, 1053 ArrayRef<std::pair<unsigned, AttributeSet>> Attrs) { 1054 // If there are no attributes then return a null AttributesList pointer. 1055 if (Attrs.empty()) 1056 return {}; 1057 1058 assert(llvm::is_sorted(Attrs, 1059 [](const std::pair<unsigned, AttributeSet> &LHS, 1060 const std::pair<unsigned, AttributeSet> &RHS) { 1061 return LHS.first < RHS.first; 1062 }) && 1063 "Misordered Attributes list!"); 1064 assert(llvm::none_of(Attrs, 1065 [](const std::pair<unsigned, AttributeSet> &Pair) { 1066 return !Pair.second.hasAttributes(); 1067 }) && 1068 "Pointless attribute!"); 1069 1070 unsigned MaxIndex = Attrs.back().first; 1071 // If the MaxIndex is FunctionIndex and there are other indices in front 1072 // of it, we need to use the largest of those to get the right size. 1073 if (MaxIndex == FunctionIndex && Attrs.size() > 1) 1074 MaxIndex = Attrs[Attrs.size() - 2].first; 1075 1076 SmallVector<AttributeSet, 4> AttrVec(attrIdxToArrayIdx(MaxIndex) + 1); 1077 for (const auto &Pair : Attrs) 1078 AttrVec[attrIdxToArrayIdx(Pair.first)] = Pair.second; 1079 1080 return getImpl(C, AttrVec); 1081 } 1082 1083 AttributeList AttributeList::get(LLVMContext &C, AttributeSet FnAttrs, 1084 AttributeSet RetAttrs, 1085 ArrayRef<AttributeSet> ArgAttrs) { 1086 // Scan from the end to find the last argument with attributes. Most 1087 // arguments don't have attributes, so it's nice if we can have fewer unique 1088 // AttributeListImpls by dropping empty attribute sets at the end of the list. 1089 unsigned NumSets = 0; 1090 for (size_t I = ArgAttrs.size(); I != 0; --I) { 1091 if (ArgAttrs[I - 1].hasAttributes()) { 1092 NumSets = I + 2; 1093 break; 1094 } 1095 } 1096 if (NumSets == 0) { 1097 // Check function and return attributes if we didn't have argument 1098 // attributes. 1099 if (RetAttrs.hasAttributes()) 1100 NumSets = 2; 1101 else if (FnAttrs.hasAttributes()) 1102 NumSets = 1; 1103 } 1104 1105 // If all attribute sets were empty, we can use the empty attribute list. 1106 if (NumSets == 0) 1107 return {}; 1108 1109 SmallVector<AttributeSet, 8> AttrSets; 1110 AttrSets.reserve(NumSets); 1111 // If we have any attributes, we always have function attributes. 1112 AttrSets.push_back(FnAttrs); 1113 if (NumSets > 1) 1114 AttrSets.push_back(RetAttrs); 1115 if (NumSets > 2) { 1116 // Drop the empty argument attribute sets at the end. 1117 ArgAttrs = ArgAttrs.take_front(NumSets - 2); 1118 llvm::append_range(AttrSets, ArgAttrs); 1119 } 1120 1121 return getImpl(C, AttrSets); 1122 } 1123 1124 AttributeList AttributeList::get(LLVMContext &C, unsigned Index, 1125 AttributeSet Attrs) { 1126 if (!Attrs.hasAttributes()) 1127 return {}; 1128 Index = attrIdxToArrayIdx(Index); 1129 SmallVector<AttributeSet, 8> AttrSets(Index + 1); 1130 AttrSets[Index] = Attrs; 1131 return getImpl(C, AttrSets); 1132 } 1133 1134 AttributeList AttributeList::get(LLVMContext &C, unsigned Index, 1135 const AttrBuilder &B) { 1136 return get(C, Index, AttributeSet::get(C, B)); 1137 } 1138 1139 AttributeList AttributeList::get(LLVMContext &C, unsigned Index, 1140 ArrayRef<Attribute::AttrKind> Kinds) { 1141 SmallVector<std::pair<unsigned, Attribute>, 8> Attrs; 1142 for (const auto K : Kinds) 1143 Attrs.emplace_back(Index, Attribute::get(C, K)); 1144 return get(C, Attrs); 1145 } 1146 1147 AttributeList AttributeList::get(LLVMContext &C, unsigned Index, 1148 ArrayRef<Attribute::AttrKind> Kinds, 1149 ArrayRef<uint64_t> Values) { 1150 assert(Kinds.size() == Values.size() && "Mismatched attribute values."); 1151 SmallVector<std::pair<unsigned, Attribute>, 8> Attrs; 1152 auto VI = Values.begin(); 1153 for (const auto K : Kinds) 1154 Attrs.emplace_back(Index, Attribute::get(C, K, *VI++)); 1155 return get(C, Attrs); 1156 } 1157 1158 AttributeList AttributeList::get(LLVMContext &C, unsigned Index, 1159 ArrayRef<StringRef> Kinds) { 1160 SmallVector<std::pair<unsigned, Attribute>, 8> Attrs; 1161 for (const auto &K : Kinds) 1162 Attrs.emplace_back(Index, Attribute::get(C, K)); 1163 return get(C, Attrs); 1164 } 1165 1166 AttributeList AttributeList::get(LLVMContext &C, 1167 ArrayRef<AttributeList> Attrs) { 1168 if (Attrs.empty()) 1169 return {}; 1170 if (Attrs.size() == 1) 1171 return Attrs[0]; 1172 1173 unsigned MaxSize = 0; 1174 for (const auto &List : Attrs) 1175 MaxSize = std::max(MaxSize, List.getNumAttrSets()); 1176 1177 // If every list was empty, there is no point in merging the lists. 1178 if (MaxSize == 0) 1179 return {}; 1180 1181 SmallVector<AttributeSet, 8> NewAttrSets(MaxSize); 1182 for (unsigned I = 0; I < MaxSize; ++I) { 1183 AttrBuilder CurBuilder(C); 1184 for (const auto &List : Attrs) 1185 CurBuilder.merge(AttrBuilder(C, List.getAttributes(I - 1))); 1186 NewAttrSets[I] = AttributeSet::get(C, CurBuilder); 1187 } 1188 1189 return getImpl(C, NewAttrSets); 1190 } 1191 1192 AttributeList 1193 AttributeList::addAttributeAtIndex(LLVMContext &C, unsigned Index, 1194 Attribute::AttrKind Kind) const { 1195 if (hasAttributeAtIndex(Index, Kind)) 1196 return *this; 1197 AttributeSet Attrs = getAttributes(Index); 1198 // TODO: Insert at correct position and avoid sort. 1199 SmallVector<Attribute, 8> NewAttrs(Attrs.begin(), Attrs.end()); 1200 NewAttrs.push_back(Attribute::get(C, Kind)); 1201 return setAttributesAtIndex(C, Index, AttributeSet::get(C, NewAttrs)); 1202 } 1203 1204 AttributeList AttributeList::addAttributeAtIndex(LLVMContext &C, unsigned Index, 1205 StringRef Kind, 1206 StringRef Value) const { 1207 AttrBuilder B(C); 1208 B.addAttribute(Kind, Value); 1209 return addAttributesAtIndex(C, Index, B); 1210 } 1211 1212 AttributeList AttributeList::addAttributeAtIndex(LLVMContext &C, unsigned Index, 1213 Attribute A) const { 1214 AttrBuilder B(C); 1215 B.addAttribute(A); 1216 return addAttributesAtIndex(C, Index, B); 1217 } 1218 1219 AttributeList AttributeList::setAttributesAtIndex(LLVMContext &C, 1220 unsigned Index, 1221 AttributeSet Attrs) const { 1222 Index = attrIdxToArrayIdx(Index); 1223 SmallVector<AttributeSet, 4> AttrSets(this->begin(), this->end()); 1224 if (Index >= AttrSets.size()) 1225 AttrSets.resize(Index + 1); 1226 AttrSets[Index] = Attrs; 1227 return AttributeList::getImpl(C, AttrSets); 1228 } 1229 1230 AttributeList AttributeList::addAttributesAtIndex(LLVMContext &C, 1231 unsigned Index, 1232 const AttrBuilder &B) const { 1233 if (!B.hasAttributes()) 1234 return *this; 1235 1236 if (!pImpl) 1237 return AttributeList::get(C, {{Index, AttributeSet::get(C, B)}}); 1238 1239 AttrBuilder Merged(C, getAttributes(Index)); 1240 Merged.merge(B); 1241 return setAttributesAtIndex(C, Index, AttributeSet::get(C, Merged)); 1242 } 1243 1244 AttributeList AttributeList::addParamAttribute(LLVMContext &C, 1245 ArrayRef<unsigned> ArgNos, 1246 Attribute A) const { 1247 assert(llvm::is_sorted(ArgNos)); 1248 1249 SmallVector<AttributeSet, 4> AttrSets(this->begin(), this->end()); 1250 unsigned MaxIndex = attrIdxToArrayIdx(ArgNos.back() + FirstArgIndex); 1251 if (MaxIndex >= AttrSets.size()) 1252 AttrSets.resize(MaxIndex + 1); 1253 1254 for (unsigned ArgNo : ArgNos) { 1255 unsigned Index = attrIdxToArrayIdx(ArgNo + FirstArgIndex); 1256 AttrBuilder B(C, AttrSets[Index]); 1257 B.addAttribute(A); 1258 AttrSets[Index] = AttributeSet::get(C, B); 1259 } 1260 1261 return getImpl(C, AttrSets); 1262 } 1263 1264 AttributeList 1265 AttributeList::removeAttributeAtIndex(LLVMContext &C, unsigned Index, 1266 Attribute::AttrKind Kind) const { 1267 if (!hasAttributeAtIndex(Index, Kind)) 1268 return *this; 1269 1270 Index = attrIdxToArrayIdx(Index); 1271 SmallVector<AttributeSet, 4> AttrSets(this->begin(), this->end()); 1272 assert(Index < AttrSets.size()); 1273 1274 AttrSets[Index] = AttrSets[Index].removeAttribute(C, Kind); 1275 1276 return getImpl(C, AttrSets); 1277 } 1278 1279 AttributeList AttributeList::removeAttributeAtIndex(LLVMContext &C, 1280 unsigned Index, 1281 StringRef Kind) const { 1282 if (!hasAttributeAtIndex(Index, Kind)) 1283 return *this; 1284 1285 Index = attrIdxToArrayIdx(Index); 1286 SmallVector<AttributeSet, 4> AttrSets(this->begin(), this->end()); 1287 assert(Index < AttrSets.size()); 1288 1289 AttrSets[Index] = AttrSets[Index].removeAttribute(C, Kind); 1290 1291 return getImpl(C, AttrSets); 1292 } 1293 1294 AttributeList AttributeList::removeAttributesAtIndex( 1295 LLVMContext &C, unsigned Index, const AttributeMask &AttrsToRemove) const { 1296 AttributeSet Attrs = getAttributes(Index); 1297 AttributeSet NewAttrs = Attrs.removeAttributes(C, AttrsToRemove); 1298 // If nothing was removed, return the original list. 1299 if (Attrs == NewAttrs) 1300 return *this; 1301 return setAttributesAtIndex(C, Index, NewAttrs); 1302 } 1303 1304 AttributeList 1305 AttributeList::removeAttributesAtIndex(LLVMContext &C, 1306 unsigned WithoutIndex) const { 1307 if (!pImpl) 1308 return {}; 1309 WithoutIndex = attrIdxToArrayIdx(WithoutIndex); 1310 if (WithoutIndex >= getNumAttrSets()) 1311 return *this; 1312 SmallVector<AttributeSet, 4> AttrSets(this->begin(), this->end()); 1313 AttrSets[WithoutIndex] = AttributeSet(); 1314 return getImpl(C, AttrSets); 1315 } 1316 1317 AttributeList AttributeList::addDereferenceableRetAttr(LLVMContext &C, 1318 uint64_t Bytes) const { 1319 AttrBuilder B(C); 1320 B.addDereferenceableAttr(Bytes); 1321 return addRetAttributes(C, B); 1322 } 1323 1324 AttributeList AttributeList::addDereferenceableParamAttr(LLVMContext &C, 1325 unsigned Index, 1326 uint64_t Bytes) const { 1327 AttrBuilder B(C); 1328 B.addDereferenceableAttr(Bytes); 1329 return addParamAttributes(C, Index, B); 1330 } 1331 1332 AttributeList 1333 AttributeList::addDereferenceableOrNullParamAttr(LLVMContext &C, unsigned Index, 1334 uint64_t Bytes) const { 1335 AttrBuilder B(C); 1336 B.addDereferenceableOrNullAttr(Bytes); 1337 return addParamAttributes(C, Index, B); 1338 } 1339 1340 AttributeList 1341 AttributeList::addAllocSizeParamAttr(LLVMContext &C, unsigned Index, 1342 unsigned ElemSizeArg, 1343 const Optional<unsigned> &NumElemsArg) { 1344 AttrBuilder B(C); 1345 B.addAllocSizeAttr(ElemSizeArg, NumElemsArg); 1346 return addParamAttributes(C, Index, B); 1347 } 1348 1349 //===----------------------------------------------------------------------===// 1350 // AttributeList Accessor Methods 1351 //===----------------------------------------------------------------------===// 1352 1353 AttributeSet AttributeList::getParamAttrs(unsigned ArgNo) const { 1354 return getAttributes(ArgNo + FirstArgIndex); 1355 } 1356 1357 AttributeSet AttributeList::getRetAttrs() const { 1358 return getAttributes(ReturnIndex); 1359 } 1360 1361 AttributeSet AttributeList::getFnAttrs() const { 1362 return getAttributes(FunctionIndex); 1363 } 1364 1365 bool AttributeList::hasAttributeAtIndex(unsigned Index, 1366 Attribute::AttrKind Kind) const { 1367 return getAttributes(Index).hasAttribute(Kind); 1368 } 1369 1370 bool AttributeList::hasAttributeAtIndex(unsigned Index, StringRef Kind) const { 1371 return getAttributes(Index).hasAttribute(Kind); 1372 } 1373 1374 bool AttributeList::hasAttributesAtIndex(unsigned Index) const { 1375 return getAttributes(Index).hasAttributes(); 1376 } 1377 1378 bool AttributeList::hasFnAttr(Attribute::AttrKind Kind) const { 1379 return pImpl && pImpl->hasFnAttribute(Kind); 1380 } 1381 1382 bool AttributeList::hasFnAttr(StringRef Kind) const { 1383 return hasAttributeAtIndex(AttributeList::FunctionIndex, Kind); 1384 } 1385 1386 bool AttributeList::hasAttrSomewhere(Attribute::AttrKind Attr, 1387 unsigned *Index) const { 1388 return pImpl && pImpl->hasAttrSomewhere(Attr, Index); 1389 } 1390 1391 Attribute AttributeList::getAttributeAtIndex(unsigned Index, 1392 Attribute::AttrKind Kind) const { 1393 return getAttributes(Index).getAttribute(Kind); 1394 } 1395 1396 Attribute AttributeList::getAttributeAtIndex(unsigned Index, 1397 StringRef Kind) const { 1398 return getAttributes(Index).getAttribute(Kind); 1399 } 1400 1401 MaybeAlign AttributeList::getRetAlignment() const { 1402 return getAttributes(ReturnIndex).getAlignment(); 1403 } 1404 1405 MaybeAlign AttributeList::getParamAlignment(unsigned ArgNo) const { 1406 return getAttributes(ArgNo + FirstArgIndex).getAlignment(); 1407 } 1408 1409 MaybeAlign AttributeList::getParamStackAlignment(unsigned ArgNo) const { 1410 return getAttributes(ArgNo + FirstArgIndex).getStackAlignment(); 1411 } 1412 1413 Type *AttributeList::getParamByValType(unsigned Index) const { 1414 return getAttributes(Index+FirstArgIndex).getByValType(); 1415 } 1416 1417 Type *AttributeList::getParamStructRetType(unsigned Index) const { 1418 return getAttributes(Index + FirstArgIndex).getStructRetType(); 1419 } 1420 1421 Type *AttributeList::getParamByRefType(unsigned Index) const { 1422 return getAttributes(Index + FirstArgIndex).getByRefType(); 1423 } 1424 1425 Type *AttributeList::getParamPreallocatedType(unsigned Index) const { 1426 return getAttributes(Index + FirstArgIndex).getPreallocatedType(); 1427 } 1428 1429 Type *AttributeList::getParamInAllocaType(unsigned Index) const { 1430 return getAttributes(Index + FirstArgIndex).getInAllocaType(); 1431 } 1432 1433 Type *AttributeList::getParamElementType(unsigned Index) const { 1434 return getAttributes(Index + FirstArgIndex).getElementType(); 1435 } 1436 1437 MaybeAlign AttributeList::getFnStackAlignment() const { 1438 return getFnAttrs().getStackAlignment(); 1439 } 1440 1441 MaybeAlign AttributeList::getRetStackAlignment() const { 1442 return getRetAttrs().getStackAlignment(); 1443 } 1444 1445 uint64_t AttributeList::getRetDereferenceableBytes() const { 1446 return getRetAttrs().getDereferenceableBytes(); 1447 } 1448 1449 uint64_t AttributeList::getParamDereferenceableBytes(unsigned Index) const { 1450 return getParamAttrs(Index).getDereferenceableBytes(); 1451 } 1452 1453 uint64_t AttributeList::getRetDereferenceableOrNullBytes() const { 1454 return getRetAttrs().getDereferenceableOrNullBytes(); 1455 } 1456 1457 uint64_t 1458 AttributeList::getParamDereferenceableOrNullBytes(unsigned Index) const { 1459 return getParamAttrs(Index).getDereferenceableOrNullBytes(); 1460 } 1461 1462 UWTableKind AttributeList::getUWTableKind() const { 1463 return getFnAttrs().getUWTableKind(); 1464 } 1465 1466 std::string AttributeList::getAsString(unsigned Index, bool InAttrGrp) const { 1467 return getAttributes(Index).getAsString(InAttrGrp); 1468 } 1469 1470 AttributeSet AttributeList::getAttributes(unsigned Index) const { 1471 Index = attrIdxToArrayIdx(Index); 1472 if (!pImpl || Index >= getNumAttrSets()) 1473 return {}; 1474 return pImpl->begin()[Index]; 1475 } 1476 1477 bool AttributeList::hasParentContext(LLVMContext &C) const { 1478 assert(!isEmpty() && "an empty attribute list has no parent context"); 1479 FoldingSetNodeID ID; 1480 pImpl->Profile(ID); 1481 void *Unused; 1482 return C.pImpl->AttrsLists.FindNodeOrInsertPos(ID, Unused) == pImpl; 1483 } 1484 1485 AttributeList::iterator AttributeList::begin() const { 1486 return pImpl ? pImpl->begin() : nullptr; 1487 } 1488 1489 AttributeList::iterator AttributeList::end() const { 1490 return pImpl ? pImpl->end() : nullptr; 1491 } 1492 1493 //===----------------------------------------------------------------------===// 1494 // AttributeList Introspection Methods 1495 //===----------------------------------------------------------------------===// 1496 1497 unsigned AttributeList::getNumAttrSets() const { 1498 return pImpl ? pImpl->NumAttrSets : 0; 1499 } 1500 1501 void AttributeList::print(raw_ostream &O) const { 1502 O << "AttributeList[\n"; 1503 1504 for (unsigned i : indexes()) { 1505 if (!getAttributes(i).hasAttributes()) 1506 continue; 1507 O << " { "; 1508 switch (i) { 1509 case AttrIndex::ReturnIndex: 1510 O << "return"; 1511 break; 1512 case AttrIndex::FunctionIndex: 1513 O << "function"; 1514 break; 1515 default: 1516 O << "arg(" << i - AttrIndex::FirstArgIndex << ")"; 1517 } 1518 O << " => " << getAsString(i) << " }\n"; 1519 } 1520 1521 O << "]\n"; 1522 } 1523 1524 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1525 LLVM_DUMP_METHOD void AttributeList::dump() const { print(dbgs()); } 1526 #endif 1527 1528 //===----------------------------------------------------------------------===// 1529 // AttrBuilder Method Implementations 1530 //===----------------------------------------------------------------------===// 1531 1532 AttrBuilder::AttrBuilder(LLVMContext &Ctx, AttributeSet AS) : Ctx(Ctx) { 1533 append_range(Attrs, AS); 1534 assert(is_sorted(Attrs) && "AttributeSet should be sorted"); 1535 } 1536 1537 void AttrBuilder::clear() { Attrs.clear(); } 1538 1539 /// Attribute comparator that only compares attribute keys. Enum attributes are 1540 /// sorted before string attributes. 1541 struct AttributeComparator { 1542 bool operator()(Attribute A0, Attribute A1) const { 1543 bool A0IsString = A0.isStringAttribute(); 1544 bool A1IsString = A1.isStringAttribute(); 1545 if (A0IsString) { 1546 if (A1IsString) 1547 return A0.getKindAsString() < A1.getKindAsString(); 1548 else 1549 return false; 1550 } 1551 if (A1IsString) 1552 return true; 1553 return A0.getKindAsEnum() < A1.getKindAsEnum(); 1554 } 1555 bool operator()(Attribute A0, Attribute::AttrKind Kind) const { 1556 if (A0.isStringAttribute()) 1557 return false; 1558 return A0.getKindAsEnum() < Kind; 1559 } 1560 bool operator()(Attribute A0, StringRef Kind) const { 1561 if (A0.isStringAttribute()) 1562 return A0.getKindAsString() < Kind; 1563 return true; 1564 } 1565 }; 1566 1567 template <typename K> 1568 static void addAttributeImpl(SmallVectorImpl<Attribute> &Attrs, K Kind, 1569 Attribute Attr) { 1570 auto It = lower_bound(Attrs, Kind, AttributeComparator()); 1571 if (It != Attrs.end() && It->hasAttribute(Kind)) 1572 std::swap(*It, Attr); 1573 else 1574 Attrs.insert(It, Attr); 1575 } 1576 1577 AttrBuilder &AttrBuilder::addAttribute(Attribute Attr) { 1578 if (Attr.isStringAttribute()) 1579 addAttributeImpl(Attrs, Attr.getKindAsString(), Attr); 1580 else 1581 addAttributeImpl(Attrs, Attr.getKindAsEnum(), Attr); 1582 return *this; 1583 } 1584 1585 AttrBuilder &AttrBuilder::addAttribute(Attribute::AttrKind Kind) { 1586 addAttributeImpl(Attrs, Kind, Attribute::get(Ctx, Kind)); 1587 return *this; 1588 } 1589 1590 AttrBuilder &AttrBuilder::addAttribute(StringRef A, StringRef V) { 1591 addAttributeImpl(Attrs, A, Attribute::get(Ctx, A, V)); 1592 return *this; 1593 } 1594 1595 AttrBuilder &AttrBuilder::removeAttribute(Attribute::AttrKind Val) { 1596 assert((unsigned)Val < Attribute::EndAttrKinds && "Attribute out of range!"); 1597 auto It = lower_bound(Attrs, Val, AttributeComparator()); 1598 if (It != Attrs.end() && It->hasAttribute(Val)) 1599 Attrs.erase(It); 1600 return *this; 1601 } 1602 1603 AttrBuilder &AttrBuilder::removeAttribute(StringRef A) { 1604 auto It = lower_bound(Attrs, A, AttributeComparator()); 1605 if (It != Attrs.end() && It->hasAttribute(A)) 1606 Attrs.erase(It); 1607 return *this; 1608 } 1609 1610 uint64_t AttrBuilder::getRawIntAttr(Attribute::AttrKind Kind) const { 1611 assert(Attribute::isIntAttrKind(Kind) && "Not an int attribute"); 1612 Attribute A = getAttribute(Kind); 1613 return A.isValid() ? A.getValueAsInt() : 0; 1614 } 1615 1616 AttrBuilder &AttrBuilder::addRawIntAttr(Attribute::AttrKind Kind, 1617 uint64_t Value) { 1618 return addAttribute(Attribute::get(Ctx, Kind, Value)); 1619 } 1620 1621 std::pair<unsigned, Optional<unsigned>> AttrBuilder::getAllocSizeArgs() const { 1622 return unpackAllocSizeArgs(getRawIntAttr(Attribute::AllocSize)); 1623 } 1624 1625 unsigned AttrBuilder::getVScaleRangeMin() const { 1626 return unpackVScaleRangeArgs(getRawIntAttr(Attribute::VScaleRange)).first; 1627 } 1628 1629 Optional<unsigned> AttrBuilder::getVScaleRangeMax() const { 1630 return unpackVScaleRangeArgs(getRawIntAttr(Attribute::VScaleRange)).second; 1631 } 1632 1633 AttrBuilder &AttrBuilder::addAlignmentAttr(MaybeAlign Align) { 1634 if (!Align) 1635 return *this; 1636 1637 assert(*Align <= llvm::Value::MaximumAlignment && "Alignment too large."); 1638 return addRawIntAttr(Attribute::Alignment, Align->value()); 1639 } 1640 1641 AttrBuilder &AttrBuilder::addStackAlignmentAttr(MaybeAlign Align) { 1642 // Default alignment, allow the target to define how to align it. 1643 if (!Align) 1644 return *this; 1645 1646 assert(*Align <= 0x100 && "Alignment too large."); 1647 return addRawIntAttr(Attribute::StackAlignment, Align->value()); 1648 } 1649 1650 AttrBuilder &AttrBuilder::addDereferenceableAttr(uint64_t Bytes) { 1651 if (Bytes == 0) return *this; 1652 1653 return addRawIntAttr(Attribute::Dereferenceable, Bytes); 1654 } 1655 1656 AttrBuilder &AttrBuilder::addDereferenceableOrNullAttr(uint64_t Bytes) { 1657 if (Bytes == 0) 1658 return *this; 1659 1660 return addRawIntAttr(Attribute::DereferenceableOrNull, Bytes); 1661 } 1662 1663 AttrBuilder &AttrBuilder::addAllocSizeAttr(unsigned ElemSize, 1664 const Optional<unsigned> &NumElems) { 1665 return addAllocSizeAttrFromRawRepr(packAllocSizeArgs(ElemSize, NumElems)); 1666 } 1667 1668 AttrBuilder &AttrBuilder::addAllocSizeAttrFromRawRepr(uint64_t RawArgs) { 1669 // (0, 0) is our "not present" value, so we need to check for it here. 1670 assert(RawArgs && "Invalid allocsize arguments -- given allocsize(0, 0)"); 1671 return addRawIntAttr(Attribute::AllocSize, RawArgs); 1672 } 1673 1674 AttrBuilder &AttrBuilder::addVScaleRangeAttr(unsigned MinValue, 1675 Optional<unsigned> MaxValue) { 1676 return addVScaleRangeAttrFromRawRepr(packVScaleRangeArgs(MinValue, MaxValue)); 1677 } 1678 1679 AttrBuilder &AttrBuilder::addVScaleRangeAttrFromRawRepr(uint64_t RawArgs) { 1680 // (0, 0) is not present hence ignore this case 1681 if (RawArgs == 0) 1682 return *this; 1683 1684 return addRawIntAttr(Attribute::VScaleRange, RawArgs); 1685 } 1686 1687 AttrBuilder &AttrBuilder::addUWTableAttr(UWTableKind Kind) { 1688 if (Kind == UWTableKind::None) 1689 return *this; 1690 return addRawIntAttr(Attribute::UWTable, uint64_t(Kind)); 1691 } 1692 1693 Type *AttrBuilder::getTypeAttr(Attribute::AttrKind Kind) const { 1694 assert(Attribute::isTypeAttrKind(Kind) && "Not a type attribute"); 1695 Attribute A = getAttribute(Kind); 1696 return A.isValid() ? A.getValueAsType() : nullptr; 1697 } 1698 1699 AttrBuilder &AttrBuilder::addTypeAttr(Attribute::AttrKind Kind, Type *Ty) { 1700 return addAttribute(Attribute::get(Ctx, Kind, Ty)); 1701 } 1702 1703 AttrBuilder &AttrBuilder::addByValAttr(Type *Ty) { 1704 return addTypeAttr(Attribute::ByVal, Ty); 1705 } 1706 1707 AttrBuilder &AttrBuilder::addStructRetAttr(Type *Ty) { 1708 return addTypeAttr(Attribute::StructRet, Ty); 1709 } 1710 1711 AttrBuilder &AttrBuilder::addByRefAttr(Type *Ty) { 1712 return addTypeAttr(Attribute::ByRef, Ty); 1713 } 1714 1715 AttrBuilder &AttrBuilder::addPreallocatedAttr(Type *Ty) { 1716 return addTypeAttr(Attribute::Preallocated, Ty); 1717 } 1718 1719 AttrBuilder &AttrBuilder::addInAllocaAttr(Type *Ty) { 1720 return addTypeAttr(Attribute::InAlloca, Ty); 1721 } 1722 1723 AttrBuilder &AttrBuilder::merge(const AttrBuilder &B) { 1724 // TODO: Could make this O(n) as we're merging two sorted lists. 1725 for (const auto &I : B.attrs()) 1726 addAttribute(I); 1727 1728 return *this; 1729 } 1730 1731 AttrBuilder &AttrBuilder::remove(const AttributeMask &AM) { 1732 erase_if(Attrs, [&](Attribute A) { return AM.contains(A); }); 1733 return *this; 1734 } 1735 1736 bool AttrBuilder::overlaps(const AttributeMask &AM) const { 1737 return any_of(Attrs, [&](Attribute A) { return AM.contains(A); }); 1738 } 1739 1740 Attribute AttrBuilder::getAttribute(Attribute::AttrKind A) const { 1741 assert((unsigned)A < Attribute::EndAttrKinds && "Attribute out of range!"); 1742 auto It = lower_bound(Attrs, A, AttributeComparator()); 1743 if (It != Attrs.end() && It->hasAttribute(A)) 1744 return *It; 1745 return {}; 1746 } 1747 1748 Attribute AttrBuilder::getAttribute(StringRef A) const { 1749 auto It = lower_bound(Attrs, A, AttributeComparator()); 1750 if (It != Attrs.end() && It->hasAttribute(A)) 1751 return *It; 1752 return {}; 1753 } 1754 1755 bool AttrBuilder::contains(Attribute::AttrKind A) const { 1756 return getAttribute(A).isValid(); 1757 } 1758 1759 bool AttrBuilder::contains(StringRef A) const { 1760 return getAttribute(A).isValid(); 1761 } 1762 1763 bool AttrBuilder::hasAlignmentAttr() const { 1764 return getRawIntAttr(Attribute::Alignment) != 0; 1765 } 1766 1767 bool AttrBuilder::operator==(const AttrBuilder &B) const { 1768 return Attrs == B.Attrs; 1769 } 1770 1771 //===----------------------------------------------------------------------===// 1772 // AttributeFuncs Function Defintions 1773 //===----------------------------------------------------------------------===// 1774 1775 /// Which attributes cannot be applied to a type. 1776 AttributeMask AttributeFuncs::typeIncompatible(Type *Ty, 1777 AttributeSafetyKind ASK) { 1778 AttributeMask Incompatible; 1779 1780 if (!Ty->isIntegerTy()) { 1781 // Attributes that only apply to integers. 1782 if (ASK & ASK_SAFE_TO_DROP) 1783 Incompatible.addAttribute(Attribute::AllocAlign); 1784 if (ASK & ASK_UNSAFE_TO_DROP) 1785 Incompatible.addAttribute(Attribute::SExt).addAttribute(Attribute::ZExt); 1786 } 1787 1788 if (!Ty->isPointerTy()) { 1789 // Attributes that only apply to pointers. 1790 if (ASK & ASK_SAFE_TO_DROP) 1791 Incompatible.addAttribute(Attribute::NoAlias) 1792 .addAttribute(Attribute::NoCapture) 1793 .addAttribute(Attribute::NonNull) 1794 .addAttribute(Attribute::ReadNone) 1795 .addAttribute(Attribute::ReadOnly) 1796 .addAttribute(Attribute::Dereferenceable) 1797 .addAttribute(Attribute::DereferenceableOrNull); 1798 if (ASK & ASK_UNSAFE_TO_DROP) 1799 Incompatible.addAttribute(Attribute::Nest) 1800 .addAttribute(Attribute::SwiftError) 1801 .addAttribute(Attribute::Preallocated) 1802 .addAttribute(Attribute::InAlloca) 1803 .addAttribute(Attribute::ByVal) 1804 .addAttribute(Attribute::StructRet) 1805 .addAttribute(Attribute::ByRef) 1806 .addAttribute(Attribute::ElementType); 1807 } 1808 1809 // Attributes that only apply to pointers or vectors of pointers. 1810 if (!Ty->isPtrOrPtrVectorTy()) { 1811 if (ASK & ASK_SAFE_TO_DROP) 1812 Incompatible.addAttribute(Attribute::Alignment); 1813 } 1814 1815 // Some attributes can apply to all "values" but there are no `void` values. 1816 if (Ty->isVoidTy()) { 1817 if (ASK & ASK_SAFE_TO_DROP) 1818 Incompatible.addAttribute(Attribute::NoUndef); 1819 } 1820 1821 return Incompatible; 1822 } 1823 1824 AttributeMask AttributeFuncs::getUBImplyingAttributes() { 1825 AttributeMask AM; 1826 AM.addAttribute(Attribute::NoUndef); 1827 AM.addAttribute(Attribute::Dereferenceable); 1828 AM.addAttribute(Attribute::DereferenceableOrNull); 1829 return AM; 1830 } 1831 1832 template<typename AttrClass> 1833 static bool isEqual(const Function &Caller, const Function &Callee) { 1834 return Caller.getFnAttribute(AttrClass::getKind()) == 1835 Callee.getFnAttribute(AttrClass::getKind()); 1836 } 1837 1838 /// Compute the logical AND of the attributes of the caller and the 1839 /// callee. 1840 /// 1841 /// This function sets the caller's attribute to false if the callee's attribute 1842 /// is false. 1843 template<typename AttrClass> 1844 static void setAND(Function &Caller, const Function &Callee) { 1845 if (AttrClass::isSet(Caller, AttrClass::getKind()) && 1846 !AttrClass::isSet(Callee, AttrClass::getKind())) 1847 AttrClass::set(Caller, AttrClass::getKind(), false); 1848 } 1849 1850 /// Compute the logical OR of the attributes of the caller and the 1851 /// callee. 1852 /// 1853 /// This function sets the caller's attribute to true if the callee's attribute 1854 /// is true. 1855 template<typename AttrClass> 1856 static void setOR(Function &Caller, const Function &Callee) { 1857 if (!AttrClass::isSet(Caller, AttrClass::getKind()) && 1858 AttrClass::isSet(Callee, AttrClass::getKind())) 1859 AttrClass::set(Caller, AttrClass::getKind(), true); 1860 } 1861 1862 /// If the inlined function had a higher stack protection level than the 1863 /// calling function, then bump up the caller's stack protection level. 1864 static void adjustCallerSSPLevel(Function &Caller, const Function &Callee) { 1865 // If the calling function has *no* stack protection level (e.g. it was built 1866 // with Clang's -fno-stack-protector or no_stack_protector attribute), don't 1867 // change it as that could change the program's semantics. 1868 if (!Caller.hasStackProtectorFnAttr()) 1869 return; 1870 1871 // If upgrading the SSP attribute, clear out the old SSP Attributes first. 1872 // Having multiple SSP attributes doesn't actually hurt, but it adds useless 1873 // clutter to the IR. 1874 AttributeMask OldSSPAttr; 1875 OldSSPAttr.addAttribute(Attribute::StackProtect) 1876 .addAttribute(Attribute::StackProtectStrong) 1877 .addAttribute(Attribute::StackProtectReq); 1878 1879 if (Callee.hasFnAttribute(Attribute::StackProtectReq)) { 1880 Caller.removeFnAttrs(OldSSPAttr); 1881 Caller.addFnAttr(Attribute::StackProtectReq); 1882 } else if (Callee.hasFnAttribute(Attribute::StackProtectStrong) && 1883 !Caller.hasFnAttribute(Attribute::StackProtectReq)) { 1884 Caller.removeFnAttrs(OldSSPAttr); 1885 Caller.addFnAttr(Attribute::StackProtectStrong); 1886 } else if (Callee.hasFnAttribute(Attribute::StackProtect) && 1887 !Caller.hasFnAttribute(Attribute::StackProtectReq) && 1888 !Caller.hasFnAttribute(Attribute::StackProtectStrong)) 1889 Caller.addFnAttr(Attribute::StackProtect); 1890 } 1891 1892 /// If the inlined function required stack probes, then ensure that 1893 /// the calling function has those too. 1894 static void adjustCallerStackProbes(Function &Caller, const Function &Callee) { 1895 if (!Caller.hasFnAttribute("probe-stack") && 1896 Callee.hasFnAttribute("probe-stack")) { 1897 Caller.addFnAttr(Callee.getFnAttribute("probe-stack")); 1898 } 1899 } 1900 1901 /// If the inlined function defines the size of guard region 1902 /// on the stack, then ensure that the calling function defines a guard region 1903 /// that is no larger. 1904 static void 1905 adjustCallerStackProbeSize(Function &Caller, const Function &Callee) { 1906 Attribute CalleeAttr = Callee.getFnAttribute("stack-probe-size"); 1907 if (CalleeAttr.isValid()) { 1908 Attribute CallerAttr = Caller.getFnAttribute("stack-probe-size"); 1909 if (CallerAttr.isValid()) { 1910 uint64_t CallerStackProbeSize, CalleeStackProbeSize; 1911 CallerAttr.getValueAsString().getAsInteger(0, CallerStackProbeSize); 1912 CalleeAttr.getValueAsString().getAsInteger(0, CalleeStackProbeSize); 1913 1914 if (CallerStackProbeSize > CalleeStackProbeSize) { 1915 Caller.addFnAttr(CalleeAttr); 1916 } 1917 } else { 1918 Caller.addFnAttr(CalleeAttr); 1919 } 1920 } 1921 } 1922 1923 /// If the inlined function defines a min legal vector width, then ensure 1924 /// the calling function has the same or larger min legal vector width. If the 1925 /// caller has the attribute, but the callee doesn't, we need to remove the 1926 /// attribute from the caller since we can't make any guarantees about the 1927 /// caller's requirements. 1928 /// This function is called after the inlining decision has been made so we have 1929 /// to merge the attribute this way. Heuristics that would use 1930 /// min-legal-vector-width to determine inline compatibility would need to be 1931 /// handled as part of inline cost analysis. 1932 static void 1933 adjustMinLegalVectorWidth(Function &Caller, const Function &Callee) { 1934 Attribute CallerAttr = Caller.getFnAttribute("min-legal-vector-width"); 1935 if (CallerAttr.isValid()) { 1936 Attribute CalleeAttr = Callee.getFnAttribute("min-legal-vector-width"); 1937 if (CalleeAttr.isValid()) { 1938 uint64_t CallerVectorWidth, CalleeVectorWidth; 1939 CallerAttr.getValueAsString().getAsInteger(0, CallerVectorWidth); 1940 CalleeAttr.getValueAsString().getAsInteger(0, CalleeVectorWidth); 1941 if (CallerVectorWidth < CalleeVectorWidth) 1942 Caller.addFnAttr(CalleeAttr); 1943 } else { 1944 // If the callee doesn't have the attribute then we don't know anything 1945 // and must drop the attribute from the caller. 1946 Caller.removeFnAttr("min-legal-vector-width"); 1947 } 1948 } 1949 } 1950 1951 /// If the inlined function has null_pointer_is_valid attribute, 1952 /// set this attribute in the caller post inlining. 1953 static void 1954 adjustNullPointerValidAttr(Function &Caller, const Function &Callee) { 1955 if (Callee.nullPointerIsDefined() && !Caller.nullPointerIsDefined()) { 1956 Caller.addFnAttr(Attribute::NullPointerIsValid); 1957 } 1958 } 1959 1960 struct EnumAttr { 1961 static bool isSet(const Function &Fn, 1962 Attribute::AttrKind Kind) { 1963 return Fn.hasFnAttribute(Kind); 1964 } 1965 1966 static void set(Function &Fn, 1967 Attribute::AttrKind Kind, bool Val) { 1968 if (Val) 1969 Fn.addFnAttr(Kind); 1970 else 1971 Fn.removeFnAttr(Kind); 1972 } 1973 }; 1974 1975 struct StrBoolAttr { 1976 static bool isSet(const Function &Fn, 1977 StringRef Kind) { 1978 auto A = Fn.getFnAttribute(Kind); 1979 return A.getValueAsString().equals("true"); 1980 } 1981 1982 static void set(Function &Fn, 1983 StringRef Kind, bool Val) { 1984 Fn.addFnAttr(Kind, Val ? "true" : "false"); 1985 } 1986 }; 1987 1988 #define GET_ATTR_NAMES 1989 #define ATTRIBUTE_ENUM(ENUM_NAME, DISPLAY_NAME) \ 1990 struct ENUM_NAME##Attr : EnumAttr { \ 1991 static enum Attribute::AttrKind getKind() { \ 1992 return llvm::Attribute::ENUM_NAME; \ 1993 } \ 1994 }; 1995 #define ATTRIBUTE_STRBOOL(ENUM_NAME, DISPLAY_NAME) \ 1996 struct ENUM_NAME##Attr : StrBoolAttr { \ 1997 static StringRef getKind() { return #DISPLAY_NAME; } \ 1998 }; 1999 #include "llvm/IR/Attributes.inc" 2000 2001 #define GET_ATTR_COMPAT_FUNC 2002 #include "llvm/IR/Attributes.inc" 2003 2004 bool AttributeFuncs::areInlineCompatible(const Function &Caller, 2005 const Function &Callee) { 2006 return hasCompatibleFnAttrs(Caller, Callee); 2007 } 2008 2009 bool AttributeFuncs::areOutlineCompatible(const Function &A, 2010 const Function &B) { 2011 return hasCompatibleFnAttrs(A, B); 2012 } 2013 2014 void AttributeFuncs::mergeAttributesForInlining(Function &Caller, 2015 const Function &Callee) { 2016 mergeFnAttrs(Caller, Callee); 2017 } 2018 2019 void AttributeFuncs::mergeAttributesForOutlining(Function &Base, 2020 const Function &ToMerge) { 2021 2022 // We merge functions so that they meet the most general case. 2023 // For example, if the NoNansFPMathAttr is set in one function, but not in 2024 // the other, in the merged function we can say that the NoNansFPMathAttr 2025 // is not set. 2026 // However if we have the SpeculativeLoadHardeningAttr set true in one 2027 // function, but not the other, we make sure that the function retains 2028 // that aspect in the merged function. 2029 mergeFnAttrs(Base, ToMerge); 2030 } 2031