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/Twine.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/Debug.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Support/MathExtras.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include <algorithm>
36 #include <cassert>
37 #include <climits>
38 #include <cstddef>
39 #include <cstdint>
40 #include <limits>
41 #include <string>
42 #include <tuple>
43 #include <utility>
44 
45 using namespace llvm;
46 
47 //===----------------------------------------------------------------------===//
48 // Attribute Construction Methods
49 //===----------------------------------------------------------------------===//
50 
51 // allocsize has two integer arguments, but because they're both 32 bits, we can
52 // pack them into one 64-bit value, at the cost of making said value
53 // nonsensical.
54 //
55 // In order to do this, we need to reserve one value of the second (optional)
56 // allocsize argument to signify "not present."
57 static const unsigned AllocSizeNumElemsNotPresent = -1;
58 
59 static uint64_t packAllocSizeArgs(unsigned ElemSizeArg,
60                                   const Optional<unsigned> &NumElemsArg) {
61   assert((!NumElemsArg.hasValue() ||
62           *NumElemsArg != AllocSizeNumElemsNotPresent) &&
63          "Attempting to pack a reserved value");
64 
65   return uint64_t(ElemSizeArg) << 32 |
66          NumElemsArg.getValueOr(AllocSizeNumElemsNotPresent);
67 }
68 
69 static std::pair<unsigned, Optional<unsigned>>
70 unpackAllocSizeArgs(uint64_t Num) {
71   unsigned NumElems = Num & std::numeric_limits<unsigned>::max();
72   unsigned ElemSizeArg = Num >> 32;
73 
74   Optional<unsigned> NumElemsArg;
75   if (NumElems != AllocSizeNumElemsNotPresent)
76     NumElemsArg = NumElems;
77   return std::make_pair(ElemSizeArg, NumElemsArg);
78 }
79 
80 Attribute Attribute::get(LLVMContext &Context, Attribute::AttrKind Kind,
81                          uint64_t Val) {
82   LLVMContextImpl *pImpl = Context.pImpl;
83   FoldingSetNodeID ID;
84   ID.AddInteger(Kind);
85   if (Val) ID.AddInteger(Val);
86 
87   void *InsertPoint;
88   AttributeImpl *PA = pImpl->AttrsSet.FindNodeOrInsertPos(ID, InsertPoint);
89 
90   if (!PA) {
91     // If we didn't find any existing attributes of the same shape then create a
92     // new one and insert it.
93     if (!Val)
94       PA = new EnumAttributeImpl(Kind);
95     else
96       PA = new IntAttributeImpl(Kind, Val);
97     pImpl->AttrsSet.InsertNode(PA, InsertPoint);
98   }
99 
100   // Return the Attribute that we found or created.
101   return Attribute(PA);
102 }
103 
104 Attribute Attribute::get(LLVMContext &Context, StringRef Kind, StringRef Val) {
105   LLVMContextImpl *pImpl = Context.pImpl;
106   FoldingSetNodeID ID;
107   ID.AddString(Kind);
108   if (!Val.empty()) ID.AddString(Val);
109 
110   void *InsertPoint;
111   AttributeImpl *PA = pImpl->AttrsSet.FindNodeOrInsertPos(ID, InsertPoint);
112 
113   if (!PA) {
114     // If we didn't find any existing attributes of the same shape then create a
115     // new one and insert it.
116     PA = new StringAttributeImpl(Kind, Val);
117     pImpl->AttrsSet.InsertNode(PA, InsertPoint);
118   }
119 
120   // Return the Attribute that we found or created.
121   return Attribute(PA);
122 }
123 
124 Attribute Attribute::get(LLVMContext &Context, Attribute::AttrKind Kind,
125                          Type *Ty) {
126   LLVMContextImpl *pImpl = Context.pImpl;
127   FoldingSetNodeID ID;
128   ID.AddInteger(Kind);
129   ID.AddPointer(Ty);
130 
131   void *InsertPoint;
132   AttributeImpl *PA = pImpl->AttrsSet.FindNodeOrInsertPos(ID, InsertPoint);
133 
134   if (!PA) {
135     // If we didn't find any existing attributes of the same shape then create a
136     // new one and insert it.
137     PA = new TypeAttributeImpl(Kind, Ty);
138     pImpl->AttrsSet.InsertNode(PA, InsertPoint);
139   }
140 
141   // Return the Attribute that we found or created.
142   return Attribute(PA);
143 }
144 
145 Attribute Attribute::getWithAlignment(LLVMContext &Context, uint64_t Align) {
146   assert(isPowerOf2_32(Align) && "Alignment must be a power of two.");
147   assert(Align <= 0x40000000 && "Alignment too large.");
148   return get(Context, Alignment, Align);
149 }
150 
151 Attribute Attribute::getWithStackAlignment(LLVMContext &Context,
152                                            uint64_t Align) {
153   assert(isPowerOf2_32(Align) && "Alignment must be a power of two.");
154   assert(Align <= 0x100 && "Alignment too large.");
155   return get(Context, StackAlignment, Align);
156 }
157 
158 Attribute Attribute::getWithDereferenceableBytes(LLVMContext &Context,
159                                                 uint64_t Bytes) {
160   assert(Bytes && "Bytes must be non-zero.");
161   return get(Context, Dereferenceable, Bytes);
162 }
163 
164 Attribute Attribute::getWithDereferenceableOrNullBytes(LLVMContext &Context,
165                                                        uint64_t Bytes) {
166   assert(Bytes && "Bytes must be non-zero.");
167   return get(Context, DereferenceableOrNull, Bytes);
168 }
169 
170 Attribute Attribute::getWithByValType(LLVMContext &Context, Type *Ty) {
171   return get(Context, ByVal, Ty);
172 }
173 
174 Attribute
175 Attribute::getWithAllocSizeArgs(LLVMContext &Context, unsigned ElemSizeArg,
176                                 const Optional<unsigned> &NumElemsArg) {
177   assert(!(ElemSizeArg == 0 && NumElemsArg && *NumElemsArg == 0) &&
178          "Invalid allocsize arguments -- given allocsize(0, 0)");
179   return get(Context, AllocSize, packAllocSizeArgs(ElemSizeArg, NumElemsArg));
180 }
181 
182 //===----------------------------------------------------------------------===//
183 // Attribute Accessor Methods
184 //===----------------------------------------------------------------------===//
185 
186 bool Attribute::isEnumAttribute() const {
187   return pImpl && pImpl->isEnumAttribute();
188 }
189 
190 bool Attribute::isIntAttribute() const {
191   return pImpl && pImpl->isIntAttribute();
192 }
193 
194 bool Attribute::isStringAttribute() const {
195   return pImpl && pImpl->isStringAttribute();
196 }
197 
198 bool Attribute::isTypeAttribute() const {
199   return pImpl && pImpl->isTypeAttribute();
200 }
201 
202 Attribute::AttrKind Attribute::getKindAsEnum() const {
203   if (!pImpl) return None;
204   assert((isEnumAttribute() || isIntAttribute() || isTypeAttribute()) &&
205          "Invalid attribute type to get the kind as an enum!");
206   return pImpl->getKindAsEnum();
207 }
208 
209 uint64_t Attribute::getValueAsInt() const {
210   if (!pImpl) return 0;
211   assert(isIntAttribute() &&
212          "Expected the attribute to be an integer attribute!");
213   return pImpl->getValueAsInt();
214 }
215 
216 StringRef Attribute::getKindAsString() const {
217   if (!pImpl) return {};
218   assert(isStringAttribute() &&
219          "Invalid attribute type to get the kind as a string!");
220   return pImpl->getKindAsString();
221 }
222 
223 StringRef Attribute::getValueAsString() const {
224   if (!pImpl) return {};
225   assert(isStringAttribute() &&
226          "Invalid attribute type to get the value as a string!");
227   return pImpl->getValueAsString();
228 }
229 
230 Type *Attribute::getValueAsType() const {
231   if (!pImpl) return {};
232   assert(isTypeAttribute() &&
233          "Invalid attribute type to get the value as a type!");
234   return pImpl->getValueAsType();
235 }
236 
237 
238 bool Attribute::hasAttribute(AttrKind Kind) const {
239   return (pImpl && pImpl->hasAttribute(Kind)) || (!pImpl && Kind == None);
240 }
241 
242 bool Attribute::hasAttribute(StringRef Kind) const {
243   if (!isStringAttribute()) return false;
244   return pImpl && pImpl->hasAttribute(Kind);
245 }
246 
247 unsigned Attribute::getAlignment() const {
248   assert(hasAttribute(Attribute::Alignment) &&
249          "Trying to get alignment from non-alignment attribute!");
250   return pImpl->getValueAsInt();
251 }
252 
253 unsigned Attribute::getStackAlignment() const {
254   assert(hasAttribute(Attribute::StackAlignment) &&
255          "Trying to get alignment from non-alignment attribute!");
256   return pImpl->getValueAsInt();
257 }
258 
259 uint64_t Attribute::getDereferenceableBytes() const {
260   assert(hasAttribute(Attribute::Dereferenceable) &&
261          "Trying to get dereferenceable bytes from "
262          "non-dereferenceable attribute!");
263   return pImpl->getValueAsInt();
264 }
265 
266 uint64_t Attribute::getDereferenceableOrNullBytes() const {
267   assert(hasAttribute(Attribute::DereferenceableOrNull) &&
268          "Trying to get dereferenceable bytes from "
269          "non-dereferenceable attribute!");
270   return pImpl->getValueAsInt();
271 }
272 
273 std::pair<unsigned, Optional<unsigned>> Attribute::getAllocSizeArgs() const {
274   assert(hasAttribute(Attribute::AllocSize) &&
275          "Trying to get allocsize args from non-allocsize attribute");
276   return unpackAllocSizeArgs(pImpl->getValueAsInt());
277 }
278 
279 std::string Attribute::getAsString(bool InAttrGrp) const {
280   if (!pImpl) return {};
281 
282   if (hasAttribute(Attribute::SanitizeAddress))
283     return "sanitize_address";
284   if (hasAttribute(Attribute::SanitizeHWAddress))
285     return "sanitize_hwaddress";
286   if (hasAttribute(Attribute::AlwaysInline))
287     return "alwaysinline";
288   if (hasAttribute(Attribute::ArgMemOnly))
289     return "argmemonly";
290   if (hasAttribute(Attribute::Builtin))
291     return "builtin";
292   if (hasAttribute(Attribute::Convergent))
293     return "convergent";
294   if (hasAttribute(Attribute::SwiftError))
295     return "swifterror";
296   if (hasAttribute(Attribute::SwiftSelf))
297     return "swiftself";
298   if (hasAttribute(Attribute::InaccessibleMemOnly))
299     return "inaccessiblememonly";
300   if (hasAttribute(Attribute::InaccessibleMemOrArgMemOnly))
301     return "inaccessiblemem_or_argmemonly";
302   if (hasAttribute(Attribute::InAlloca))
303     return "inalloca";
304   if (hasAttribute(Attribute::InlineHint))
305     return "inlinehint";
306   if (hasAttribute(Attribute::InReg))
307     return "inreg";
308   if (hasAttribute(Attribute::JumpTable))
309     return "jumptable";
310   if (hasAttribute(Attribute::MinSize))
311     return "minsize";
312   if (hasAttribute(Attribute::Naked))
313     return "naked";
314   if (hasAttribute(Attribute::Nest))
315     return "nest";
316   if (hasAttribute(Attribute::NoAlias))
317     return "noalias";
318   if (hasAttribute(Attribute::NoBuiltin))
319     return "nobuiltin";
320   if (hasAttribute(Attribute::NoCapture))
321     return "nocapture";
322   if (hasAttribute(Attribute::NoDuplicate))
323     return "noduplicate";
324   if (hasAttribute(Attribute::NoFree))
325     return "nofree";
326   if (hasAttribute(Attribute::NoImplicitFloat))
327     return "noimplicitfloat";
328   if (hasAttribute(Attribute::NoInline))
329     return "noinline";
330   if (hasAttribute(Attribute::NonLazyBind))
331     return "nonlazybind";
332   if (hasAttribute(Attribute::NonNull))
333     return "nonnull";
334   if (hasAttribute(Attribute::NoRedZone))
335     return "noredzone";
336   if (hasAttribute(Attribute::NoReturn))
337     return "noreturn";
338   if (hasAttribute(Attribute::WillReturn))
339     return "willreturn";
340   if (hasAttribute(Attribute::NoCfCheck))
341     return "nocf_check";
342   if (hasAttribute(Attribute::NoRecurse))
343     return "norecurse";
344   if (hasAttribute(Attribute::NoUnwind))
345     return "nounwind";
346   if (hasAttribute(Attribute::OptForFuzzing))
347     return "optforfuzzing";
348   if (hasAttribute(Attribute::OptimizeNone))
349     return "optnone";
350   if (hasAttribute(Attribute::OptimizeForSize))
351     return "optsize";
352   if (hasAttribute(Attribute::ReadNone))
353     return "readnone";
354   if (hasAttribute(Attribute::ReadOnly))
355     return "readonly";
356   if (hasAttribute(Attribute::WriteOnly))
357     return "writeonly";
358   if (hasAttribute(Attribute::Returned))
359     return "returned";
360   if (hasAttribute(Attribute::ReturnsTwice))
361     return "returns_twice";
362   if (hasAttribute(Attribute::SExt))
363     return "signext";
364   if (hasAttribute(Attribute::SpeculativeLoadHardening))
365     return "speculative_load_hardening";
366   if (hasAttribute(Attribute::Speculatable))
367     return "speculatable";
368   if (hasAttribute(Attribute::StackProtect))
369     return "ssp";
370   if (hasAttribute(Attribute::StackProtectReq))
371     return "sspreq";
372   if (hasAttribute(Attribute::StackProtectStrong))
373     return "sspstrong";
374   if (hasAttribute(Attribute::SafeStack))
375     return "safestack";
376   if (hasAttribute(Attribute::ShadowCallStack))
377     return "shadowcallstack";
378   if (hasAttribute(Attribute::StrictFP))
379     return "strictfp";
380   if (hasAttribute(Attribute::StructRet))
381     return "sret";
382   if (hasAttribute(Attribute::SanitizeThread))
383     return "sanitize_thread";
384   if (hasAttribute(Attribute::SanitizeMemory))
385     return "sanitize_memory";
386   if (hasAttribute(Attribute::UWTable))
387     return "uwtable";
388   if (hasAttribute(Attribute::ZExt))
389     return "zeroext";
390   if (hasAttribute(Attribute::Cold))
391     return "cold";
392   if (hasAttribute(Attribute::ImmArg))
393     return "immarg";
394 
395   if (hasAttribute(Attribute::ByVal)) {
396     std::string Result;
397     Result += "byval";
398     if (Type *Ty = getValueAsType()) {
399       raw_string_ostream OS(Result);
400       Result += '(';
401       Ty->print(OS, false, true);
402       OS.flush();
403       Result += ')';
404     }
405     return Result;
406   }
407 
408   // FIXME: These should be output like this:
409   //
410   //   align=4
411   //   alignstack=8
412   //
413   if (hasAttribute(Attribute::Alignment)) {
414     std::string Result;
415     Result += "align";
416     Result += (InAttrGrp) ? "=" : " ";
417     Result += utostr(getValueAsInt());
418     return Result;
419   }
420 
421   auto AttrWithBytesToString = [&](const char *Name) {
422     std::string Result;
423     Result += Name;
424     if (InAttrGrp) {
425       Result += "=";
426       Result += utostr(getValueAsInt());
427     } else {
428       Result += "(";
429       Result += utostr(getValueAsInt());
430       Result += ")";
431     }
432     return Result;
433   };
434 
435   if (hasAttribute(Attribute::StackAlignment))
436     return AttrWithBytesToString("alignstack");
437 
438   if (hasAttribute(Attribute::Dereferenceable))
439     return AttrWithBytesToString("dereferenceable");
440 
441   if (hasAttribute(Attribute::DereferenceableOrNull))
442     return AttrWithBytesToString("dereferenceable_or_null");
443 
444   if (hasAttribute(Attribute::AllocSize)) {
445     unsigned ElemSize;
446     Optional<unsigned> NumElems;
447     std::tie(ElemSize, NumElems) = getAllocSizeArgs();
448 
449     std::string Result = "allocsize(";
450     Result += utostr(ElemSize);
451     if (NumElems.hasValue()) {
452       Result += ',';
453       Result += utostr(*NumElems);
454     }
455     Result += ')';
456     return Result;
457   }
458 
459   // Convert target-dependent attributes to strings of the form:
460   //
461   //   "kind"
462   //   "kind" = "value"
463   //
464   if (isStringAttribute()) {
465     std::string Result;
466     Result += (Twine('"') + getKindAsString() + Twine('"')).str();
467 
468     std::string AttrVal = pImpl->getValueAsString();
469     if (AttrVal.empty()) return Result;
470 
471     // Since some attribute strings contain special characters that cannot be
472     // printable, those have to be escaped to make the attribute value printable
473     // as is.  e.g. "\01__gnu_mcount_nc"
474     {
475       raw_string_ostream OS(Result);
476       OS << "=\"";
477       printEscapedString(AttrVal, OS);
478       OS << "\"";
479     }
480     return Result;
481   }
482 
483   llvm_unreachable("Unknown attribute");
484 }
485 
486 bool Attribute::operator<(Attribute A) const {
487   if (!pImpl && !A.pImpl) return false;
488   if (!pImpl) return true;
489   if (!A.pImpl) return false;
490   return *pImpl < *A.pImpl;
491 }
492 
493 //===----------------------------------------------------------------------===//
494 // AttributeImpl Definition
495 //===----------------------------------------------------------------------===//
496 
497 // Pin the vtables to this file.
498 AttributeImpl::~AttributeImpl() = default;
499 
500 void EnumAttributeImpl::anchor() {}
501 
502 void IntAttributeImpl::anchor() {}
503 
504 void StringAttributeImpl::anchor() {}
505 
506 void TypeAttributeImpl::anchor() {}
507 
508 bool AttributeImpl::hasAttribute(Attribute::AttrKind A) const {
509   if (isStringAttribute()) return false;
510   return getKindAsEnum() == A;
511 }
512 
513 bool AttributeImpl::hasAttribute(StringRef Kind) const {
514   if (!isStringAttribute()) return false;
515   return getKindAsString() == Kind;
516 }
517 
518 Attribute::AttrKind AttributeImpl::getKindAsEnum() const {
519   assert(isEnumAttribute() || isIntAttribute() || isTypeAttribute());
520   return static_cast<const EnumAttributeImpl *>(this)->getEnumKind();
521 }
522 
523 uint64_t AttributeImpl::getValueAsInt() const {
524   assert(isIntAttribute());
525   return static_cast<const IntAttributeImpl *>(this)->getValue();
526 }
527 
528 StringRef AttributeImpl::getKindAsString() const {
529   assert(isStringAttribute());
530   return static_cast<const StringAttributeImpl *>(this)->getStringKind();
531 }
532 
533 StringRef AttributeImpl::getValueAsString() const {
534   assert(isStringAttribute());
535   return static_cast<const StringAttributeImpl *>(this)->getStringValue();
536 }
537 
538 Type *AttributeImpl::getValueAsType() const {
539   assert(isTypeAttribute());
540   return static_cast<const TypeAttributeImpl *>(this)->getTypeValue();
541 }
542 
543 bool AttributeImpl::operator<(const AttributeImpl &AI) const {
544   // This sorts the attributes with Attribute::AttrKinds coming first (sorted
545   // relative to their enum value) and then strings.
546   if (isEnumAttribute()) {
547     if (AI.isEnumAttribute()) return getKindAsEnum() < AI.getKindAsEnum();
548     if (AI.isIntAttribute()) return true;
549     if (AI.isStringAttribute()) return true;
550     if (AI.isTypeAttribute()) return true;
551   }
552 
553   if (isTypeAttribute()) {
554     if (AI.isEnumAttribute()) return false;
555     if (AI.isTypeAttribute()) {
556       assert(getKindAsEnum() != AI.getKindAsEnum() &&
557              "Comparison of types would be unstable");
558       return getKindAsEnum() < AI.getKindAsEnum();
559     }
560     if (AI.isIntAttribute()) return true;
561     if (AI.isStringAttribute()) return true;
562   }
563 
564   if (isIntAttribute()) {
565     if (AI.isEnumAttribute()) return false;
566     if (AI.isTypeAttribute()) return false;
567     if (AI.isIntAttribute()) {
568       if (getKindAsEnum() == AI.getKindAsEnum())
569         return getValueAsInt() < AI.getValueAsInt();
570       return getKindAsEnum() < AI.getKindAsEnum();
571     }
572     if (AI.isStringAttribute()) return true;
573   }
574 
575   assert(isStringAttribute());
576   if (AI.isEnumAttribute()) return false;
577   if (AI.isTypeAttribute()) return false;
578   if (AI.isIntAttribute()) return false;
579   if (getKindAsString() == AI.getKindAsString())
580     return getValueAsString() < AI.getValueAsString();
581   return getKindAsString() < AI.getKindAsString();
582 }
583 
584 //===----------------------------------------------------------------------===//
585 // AttributeSet Definition
586 //===----------------------------------------------------------------------===//
587 
588 AttributeSet AttributeSet::get(LLVMContext &C, const AttrBuilder &B) {
589   return AttributeSet(AttributeSetNode::get(C, B));
590 }
591 
592 AttributeSet AttributeSet::get(LLVMContext &C, ArrayRef<Attribute> Attrs) {
593   return AttributeSet(AttributeSetNode::get(C, Attrs));
594 }
595 
596 AttributeSet AttributeSet::addAttribute(LLVMContext &C,
597                                         Attribute::AttrKind Kind) const {
598   if (hasAttribute(Kind)) return *this;
599   AttrBuilder B;
600   B.addAttribute(Kind);
601   return addAttributes(C, AttributeSet::get(C, B));
602 }
603 
604 AttributeSet AttributeSet::addAttribute(LLVMContext &C, StringRef Kind,
605                                         StringRef Value) const {
606   AttrBuilder B;
607   B.addAttribute(Kind, Value);
608   return addAttributes(C, AttributeSet::get(C, B));
609 }
610 
611 AttributeSet AttributeSet::addAttributes(LLVMContext &C,
612                                          const AttributeSet AS) const {
613   if (!hasAttributes())
614     return AS;
615 
616   if (!AS.hasAttributes())
617     return *this;
618 
619   AttrBuilder B(AS);
620   for (const auto I : *this)
621     B.addAttribute(I);
622 
623  return get(C, B);
624 }
625 
626 AttributeSet AttributeSet::removeAttribute(LLVMContext &C,
627                                              Attribute::AttrKind Kind) const {
628   if (!hasAttribute(Kind)) return *this;
629   AttrBuilder B(*this);
630   B.removeAttribute(Kind);
631   return get(C, B);
632 }
633 
634 AttributeSet AttributeSet::removeAttribute(LLVMContext &C,
635                                              StringRef Kind) const {
636   if (!hasAttribute(Kind)) return *this;
637   AttrBuilder B(*this);
638   B.removeAttribute(Kind);
639   return get(C, B);
640 }
641 
642 AttributeSet AttributeSet::removeAttributes(LLVMContext &C,
643                                               const AttrBuilder &Attrs) const {
644   AttrBuilder B(*this);
645   B.remove(Attrs);
646   return get(C, B);
647 }
648 
649 unsigned AttributeSet::getNumAttributes() const {
650   return SetNode ? SetNode->getNumAttributes() : 0;
651 }
652 
653 bool AttributeSet::hasAttribute(Attribute::AttrKind Kind) const {
654   return SetNode ? SetNode->hasAttribute(Kind) : false;
655 }
656 
657 bool AttributeSet::hasAttribute(StringRef Kind) const {
658   return SetNode ? SetNode->hasAttribute(Kind) : false;
659 }
660 
661 Attribute AttributeSet::getAttribute(Attribute::AttrKind Kind) const {
662   return SetNode ? SetNode->getAttribute(Kind) : Attribute();
663 }
664 
665 Attribute AttributeSet::getAttribute(StringRef Kind) const {
666   return SetNode ? SetNode->getAttribute(Kind) : Attribute();
667 }
668 
669 unsigned AttributeSet::getAlignment() const {
670   return SetNode ? SetNode->getAlignment() : 0;
671 }
672 
673 unsigned AttributeSet::getStackAlignment() const {
674   return SetNode ? SetNode->getStackAlignment() : 0;
675 }
676 
677 uint64_t AttributeSet::getDereferenceableBytes() const {
678   return SetNode ? SetNode->getDereferenceableBytes() : 0;
679 }
680 
681 uint64_t AttributeSet::getDereferenceableOrNullBytes() const {
682   return SetNode ? SetNode->getDereferenceableOrNullBytes() : 0;
683 }
684 
685 Type *AttributeSet::getByValType() const {
686   return SetNode ? SetNode->getByValType() : nullptr;
687 }
688 
689 std::pair<unsigned, Optional<unsigned>> AttributeSet::getAllocSizeArgs() const {
690   return SetNode ? SetNode->getAllocSizeArgs()
691                  : std::pair<unsigned, Optional<unsigned>>(0, 0);
692 }
693 
694 std::string AttributeSet::getAsString(bool InAttrGrp) const {
695   return SetNode ? SetNode->getAsString(InAttrGrp) : "";
696 }
697 
698 AttributeSet::iterator AttributeSet::begin() const {
699   return SetNode ? SetNode->begin() : nullptr;
700 }
701 
702 AttributeSet::iterator AttributeSet::end() const {
703   return SetNode ? SetNode->end() : nullptr;
704 }
705 
706 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
707 LLVM_DUMP_METHOD void AttributeSet::dump() const {
708   dbgs() << "AS =\n";
709     dbgs() << "  { ";
710     dbgs() << getAsString(true) << " }\n";
711 }
712 #endif
713 
714 //===----------------------------------------------------------------------===//
715 // AttributeSetNode Definition
716 //===----------------------------------------------------------------------===//
717 
718 AttributeSetNode::AttributeSetNode(ArrayRef<Attribute> Attrs)
719     : AvailableAttrs(0), NumAttrs(Attrs.size()) {
720   // There's memory after the node where we can store the entries in.
721   llvm::copy(Attrs, getTrailingObjects<Attribute>());
722 
723   for (const auto I : *this) {
724     if (!I.isStringAttribute()) {
725       AvailableAttrs |= ((uint64_t)1) << I.getKindAsEnum();
726     }
727   }
728 }
729 
730 AttributeSetNode *AttributeSetNode::get(LLVMContext &C,
731                                         ArrayRef<Attribute> Attrs) {
732   if (Attrs.empty())
733     return nullptr;
734 
735   // Otherwise, build a key to look up the existing attributes.
736   LLVMContextImpl *pImpl = C.pImpl;
737   FoldingSetNodeID ID;
738 
739   SmallVector<Attribute, 8> SortedAttrs(Attrs.begin(), Attrs.end());
740   llvm::sort(SortedAttrs);
741 
742   for (const auto Attr : SortedAttrs)
743     Attr.Profile(ID);
744 
745   void *InsertPoint;
746   AttributeSetNode *PA =
747     pImpl->AttrsSetNodes.FindNodeOrInsertPos(ID, InsertPoint);
748 
749   // If we didn't find any existing attributes of the same shape then create a
750   // new one and insert it.
751   if (!PA) {
752     // Coallocate entries after the AttributeSetNode itself.
753     void *Mem = ::operator new(totalSizeToAlloc<Attribute>(SortedAttrs.size()));
754     PA = new (Mem) AttributeSetNode(SortedAttrs);
755     pImpl->AttrsSetNodes.InsertNode(PA, InsertPoint);
756   }
757 
758   // Return the AttributeSetNode that we found or created.
759   return PA;
760 }
761 
762 AttributeSetNode *AttributeSetNode::get(LLVMContext &C, const AttrBuilder &B) {
763   // Add target-independent attributes.
764   SmallVector<Attribute, 8> Attrs;
765   for (Attribute::AttrKind Kind = Attribute::None;
766        Kind != Attribute::EndAttrKinds; Kind = Attribute::AttrKind(Kind + 1)) {
767     if (!B.contains(Kind))
768       continue;
769 
770     Attribute Attr;
771     switch (Kind) {
772     case Attribute::ByVal:
773       Attr = Attribute::getWithByValType(C, B.getByValType());
774       break;
775     case Attribute::Alignment:
776       Attr = Attribute::getWithAlignment(C, B.getAlignment());
777       break;
778     case Attribute::StackAlignment:
779       Attr = Attribute::getWithStackAlignment(C, B.getStackAlignment());
780       break;
781     case Attribute::Dereferenceable:
782       Attr = Attribute::getWithDereferenceableBytes(
783           C, B.getDereferenceableBytes());
784       break;
785     case Attribute::DereferenceableOrNull:
786       Attr = Attribute::getWithDereferenceableOrNullBytes(
787           C, B.getDereferenceableOrNullBytes());
788       break;
789     case Attribute::AllocSize: {
790       auto A = B.getAllocSizeArgs();
791       Attr = Attribute::getWithAllocSizeArgs(C, A.first, A.second);
792       break;
793     }
794     default:
795       Attr = Attribute::get(C, Kind);
796     }
797     Attrs.push_back(Attr);
798   }
799 
800   // Add target-dependent (string) attributes.
801   for (const auto &TDA : B.td_attrs())
802     Attrs.emplace_back(Attribute::get(C, TDA.first, TDA.second));
803 
804   return get(C, Attrs);
805 }
806 
807 bool AttributeSetNode::hasAttribute(StringRef Kind) const {
808   for (const auto I : *this)
809     if (I.hasAttribute(Kind))
810       return true;
811   return false;
812 }
813 
814 Attribute AttributeSetNode::getAttribute(Attribute::AttrKind Kind) const {
815   if (hasAttribute(Kind)) {
816     for (const auto I : *this)
817       if (I.hasAttribute(Kind))
818         return I;
819   }
820   return {};
821 }
822 
823 Attribute AttributeSetNode::getAttribute(StringRef Kind) const {
824   for (const auto I : *this)
825     if (I.hasAttribute(Kind))
826       return I;
827   return {};
828 }
829 
830 unsigned AttributeSetNode::getAlignment() const {
831   for (const auto I : *this)
832     if (I.hasAttribute(Attribute::Alignment))
833       return I.getAlignment();
834   return 0;
835 }
836 
837 unsigned AttributeSetNode::getStackAlignment() const {
838   for (const auto I : *this)
839     if (I.hasAttribute(Attribute::StackAlignment))
840       return I.getStackAlignment();
841   return 0;
842 }
843 
844 Type *AttributeSetNode::getByValType() const {
845   for (const auto I : *this)
846     if (I.hasAttribute(Attribute::ByVal))
847       return I.getValueAsType();
848   return 0;
849 }
850 
851 uint64_t AttributeSetNode::getDereferenceableBytes() const {
852   for (const auto I : *this)
853     if (I.hasAttribute(Attribute::Dereferenceable))
854       return I.getDereferenceableBytes();
855   return 0;
856 }
857 
858 uint64_t AttributeSetNode::getDereferenceableOrNullBytes() const {
859   for (const auto I : *this)
860     if (I.hasAttribute(Attribute::DereferenceableOrNull))
861       return I.getDereferenceableOrNullBytes();
862   return 0;
863 }
864 
865 std::pair<unsigned, Optional<unsigned>>
866 AttributeSetNode::getAllocSizeArgs() const {
867   for (const auto I : *this)
868     if (I.hasAttribute(Attribute::AllocSize))
869       return I.getAllocSizeArgs();
870   return std::make_pair(0, 0);
871 }
872 
873 std::string AttributeSetNode::getAsString(bool InAttrGrp) const {
874   std::string Str;
875   for (iterator I = begin(), E = end(); I != E; ++I) {
876     if (I != begin())
877       Str += ' ';
878     Str += I->getAsString(InAttrGrp);
879   }
880   return Str;
881 }
882 
883 //===----------------------------------------------------------------------===//
884 // AttributeListImpl Definition
885 //===----------------------------------------------------------------------===//
886 
887 /// Map from AttributeList index to the internal array index. Adding one happens
888 /// to work, but it relies on unsigned integer wrapping. MSVC warns about
889 /// unsigned wrapping in constexpr functions, so write out the conditional. LLVM
890 /// folds it to add anyway.
891 static constexpr unsigned attrIdxToArrayIdx(unsigned Index) {
892   return Index == AttributeList::FunctionIndex ? 0 : Index + 1;
893 }
894 
895 AttributeListImpl::AttributeListImpl(LLVMContext &C,
896                                      ArrayRef<AttributeSet> Sets)
897     : AvailableFunctionAttrs(0), Context(C), NumAttrSets(Sets.size()) {
898   assert(!Sets.empty() && "pointless AttributeListImpl");
899 
900   // There's memory after the node where we can store the entries in.
901   llvm::copy(Sets, getTrailingObjects<AttributeSet>());
902 
903   // Initialize AvailableFunctionAttrs summary bitset.
904   static_assert(Attribute::EndAttrKinds <=
905                     sizeof(AvailableFunctionAttrs) * CHAR_BIT,
906                 "Too many attributes");
907   static_assert(attrIdxToArrayIdx(AttributeList::FunctionIndex) == 0U,
908                 "function should be stored in slot 0");
909   for (const auto I : Sets[0]) {
910     if (!I.isStringAttribute())
911       AvailableFunctionAttrs |= 1ULL << I.getKindAsEnum();
912   }
913 }
914 
915 void AttributeListImpl::Profile(FoldingSetNodeID &ID) const {
916   Profile(ID, makeArrayRef(begin(), end()));
917 }
918 
919 void AttributeListImpl::Profile(FoldingSetNodeID &ID,
920                                 ArrayRef<AttributeSet> Sets) {
921   for (const auto &Set : Sets)
922     ID.AddPointer(Set.SetNode);
923 }
924 
925 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
926 LLVM_DUMP_METHOD void AttributeListImpl::dump() const {
927   AttributeList(const_cast<AttributeListImpl *>(this)).dump();
928 }
929 #endif
930 
931 //===----------------------------------------------------------------------===//
932 // AttributeList Construction and Mutation Methods
933 //===----------------------------------------------------------------------===//
934 
935 AttributeList AttributeList::getImpl(LLVMContext &C,
936                                      ArrayRef<AttributeSet> AttrSets) {
937   assert(!AttrSets.empty() && "pointless AttributeListImpl");
938 
939   LLVMContextImpl *pImpl = C.pImpl;
940   FoldingSetNodeID ID;
941   AttributeListImpl::Profile(ID, AttrSets);
942 
943   void *InsertPoint;
944   AttributeListImpl *PA =
945       pImpl->AttrsLists.FindNodeOrInsertPos(ID, InsertPoint);
946 
947   // If we didn't find any existing attributes of the same shape then
948   // create a new one and insert it.
949   if (!PA) {
950     // Coallocate entries after the AttributeListImpl itself.
951     void *Mem = ::operator new(
952         AttributeListImpl::totalSizeToAlloc<AttributeSet>(AttrSets.size()));
953     PA = new (Mem) AttributeListImpl(C, AttrSets);
954     pImpl->AttrsLists.InsertNode(PA, InsertPoint);
955   }
956 
957   // Return the AttributesList that we found or created.
958   return AttributeList(PA);
959 }
960 
961 AttributeList
962 AttributeList::get(LLVMContext &C,
963                    ArrayRef<std::pair<unsigned, Attribute>> Attrs) {
964   // If there are no attributes then return a null AttributesList pointer.
965   if (Attrs.empty())
966     return {};
967 
968   assert(std::is_sorted(Attrs.begin(), Attrs.end(),
969                         [](const std::pair<unsigned, Attribute> &LHS,
970                            const std::pair<unsigned, Attribute> &RHS) {
971                           return LHS.first < RHS.first;
972                         }) && "Misordered Attributes list!");
973   assert(llvm::none_of(Attrs,
974                        [](const std::pair<unsigned, Attribute> &Pair) {
975                          return Pair.second.hasAttribute(Attribute::None);
976                        }) &&
977          "Pointless attribute!");
978 
979   // Create a vector if (unsigned, AttributeSetNode*) pairs from the attributes
980   // list.
981   SmallVector<std::pair<unsigned, AttributeSet>, 8> AttrPairVec;
982   for (ArrayRef<std::pair<unsigned, Attribute>>::iterator I = Attrs.begin(),
983          E = Attrs.end(); I != E; ) {
984     unsigned Index = I->first;
985     SmallVector<Attribute, 4> AttrVec;
986     while (I != E && I->first == Index) {
987       AttrVec.push_back(I->second);
988       ++I;
989     }
990 
991     AttrPairVec.emplace_back(Index, AttributeSet::get(C, AttrVec));
992   }
993 
994   return get(C, AttrPairVec);
995 }
996 
997 AttributeList
998 AttributeList::get(LLVMContext &C,
999                    ArrayRef<std::pair<unsigned, AttributeSet>> Attrs) {
1000   // If there are no attributes then return a null AttributesList pointer.
1001   if (Attrs.empty())
1002     return {};
1003 
1004   assert(std::is_sorted(Attrs.begin(), Attrs.end(),
1005                         [](const std::pair<unsigned, AttributeSet> &LHS,
1006                            const std::pair<unsigned, AttributeSet> &RHS) {
1007                           return LHS.first < RHS.first;
1008                         }) &&
1009          "Misordered Attributes list!");
1010   assert(llvm::none_of(Attrs,
1011                        [](const std::pair<unsigned, AttributeSet> &Pair) {
1012                          return !Pair.second.hasAttributes();
1013                        }) &&
1014          "Pointless attribute!");
1015 
1016   unsigned MaxIndex = Attrs.back().first;
1017   // If the MaxIndex is FunctionIndex and there are other indices in front
1018   // of it, we need to use the largest of those to get the right size.
1019   if (MaxIndex == FunctionIndex && Attrs.size() > 1)
1020     MaxIndex = Attrs[Attrs.size() - 2].first;
1021 
1022   SmallVector<AttributeSet, 4> AttrVec(attrIdxToArrayIdx(MaxIndex) + 1);
1023   for (const auto Pair : Attrs)
1024     AttrVec[attrIdxToArrayIdx(Pair.first)] = Pair.second;
1025 
1026   return getImpl(C, AttrVec);
1027 }
1028 
1029 AttributeList AttributeList::get(LLVMContext &C, AttributeSet FnAttrs,
1030                                  AttributeSet RetAttrs,
1031                                  ArrayRef<AttributeSet> ArgAttrs) {
1032   // Scan from the end to find the last argument with attributes.  Most
1033   // arguments don't have attributes, so it's nice if we can have fewer unique
1034   // AttributeListImpls by dropping empty attribute sets at the end of the list.
1035   unsigned NumSets = 0;
1036   for (size_t I = ArgAttrs.size(); I != 0; --I) {
1037     if (ArgAttrs[I - 1].hasAttributes()) {
1038       NumSets = I + 2;
1039       break;
1040     }
1041   }
1042   if (NumSets == 0) {
1043     // Check function and return attributes if we didn't have argument
1044     // attributes.
1045     if (RetAttrs.hasAttributes())
1046       NumSets = 2;
1047     else if (FnAttrs.hasAttributes())
1048       NumSets = 1;
1049   }
1050 
1051   // If all attribute sets were empty, we can use the empty attribute list.
1052   if (NumSets == 0)
1053     return {};
1054 
1055   SmallVector<AttributeSet, 8> AttrSets;
1056   AttrSets.reserve(NumSets);
1057   // If we have any attributes, we always have function attributes.
1058   AttrSets.push_back(FnAttrs);
1059   if (NumSets > 1)
1060     AttrSets.push_back(RetAttrs);
1061   if (NumSets > 2) {
1062     // Drop the empty argument attribute sets at the end.
1063     ArgAttrs = ArgAttrs.take_front(NumSets - 2);
1064     AttrSets.insert(AttrSets.end(), ArgAttrs.begin(), ArgAttrs.end());
1065   }
1066 
1067   return getImpl(C, AttrSets);
1068 }
1069 
1070 AttributeList AttributeList::get(LLVMContext &C, unsigned Index,
1071                                  const AttrBuilder &B) {
1072   if (!B.hasAttributes())
1073     return {};
1074   Index = attrIdxToArrayIdx(Index);
1075   SmallVector<AttributeSet, 8> AttrSets(Index + 1);
1076   AttrSets[Index] = AttributeSet::get(C, B);
1077   return getImpl(C, AttrSets);
1078 }
1079 
1080 AttributeList AttributeList::get(LLVMContext &C, unsigned Index,
1081                                  ArrayRef<Attribute::AttrKind> Kinds) {
1082   SmallVector<std::pair<unsigned, Attribute>, 8> Attrs;
1083   for (const auto K : Kinds)
1084     Attrs.emplace_back(Index, Attribute::get(C, K));
1085   return get(C, Attrs);
1086 }
1087 
1088 AttributeList AttributeList::get(LLVMContext &C, unsigned Index,
1089                                  ArrayRef<StringRef> Kinds) {
1090   SmallVector<std::pair<unsigned, Attribute>, 8> Attrs;
1091   for (const auto K : Kinds)
1092     Attrs.emplace_back(Index, Attribute::get(C, K));
1093   return get(C, Attrs);
1094 }
1095 
1096 AttributeList AttributeList::get(LLVMContext &C,
1097                                  ArrayRef<AttributeList> Attrs) {
1098   if (Attrs.empty())
1099     return {};
1100   if (Attrs.size() == 1)
1101     return Attrs[0];
1102 
1103   unsigned MaxSize = 0;
1104   for (const auto List : Attrs)
1105     MaxSize = std::max(MaxSize, List.getNumAttrSets());
1106 
1107   // If every list was empty, there is no point in merging the lists.
1108   if (MaxSize == 0)
1109     return {};
1110 
1111   SmallVector<AttributeSet, 8> NewAttrSets(MaxSize);
1112   for (unsigned I = 0; I < MaxSize; ++I) {
1113     AttrBuilder CurBuilder;
1114     for (const auto List : Attrs)
1115       CurBuilder.merge(List.getAttributes(I - 1));
1116     NewAttrSets[I] = AttributeSet::get(C, CurBuilder);
1117   }
1118 
1119   return getImpl(C, NewAttrSets);
1120 }
1121 
1122 AttributeList AttributeList::addAttribute(LLVMContext &C, unsigned Index,
1123                                           Attribute::AttrKind Kind) const {
1124   if (hasAttribute(Index, Kind)) return *this;
1125   AttrBuilder B;
1126   B.addAttribute(Kind);
1127   return addAttributes(C, Index, B);
1128 }
1129 
1130 AttributeList AttributeList::addAttribute(LLVMContext &C, unsigned Index,
1131                                           StringRef Kind,
1132                                           StringRef Value) const {
1133   AttrBuilder B;
1134   B.addAttribute(Kind, Value);
1135   return addAttributes(C, Index, B);
1136 }
1137 
1138 AttributeList AttributeList::addAttribute(LLVMContext &C, unsigned Index,
1139                                           Attribute A) const {
1140   AttrBuilder B;
1141   B.addAttribute(A);
1142   return addAttributes(C, Index, B);
1143 }
1144 
1145 AttributeList AttributeList::addAttributes(LLVMContext &C, unsigned Index,
1146                                            const AttrBuilder &B) const {
1147   if (!B.hasAttributes())
1148     return *this;
1149 
1150   if (!pImpl)
1151     return AttributeList::get(C, {{Index, AttributeSet::get(C, B)}});
1152 
1153 #ifndef NDEBUG
1154   // FIXME it is not obvious how this should work for alignment. For now, say
1155   // we can't change a known alignment.
1156   unsigned OldAlign = getAttributes(Index).getAlignment();
1157   unsigned NewAlign = B.getAlignment();
1158   assert((!OldAlign || !NewAlign || OldAlign == NewAlign) &&
1159          "Attempt to change alignment!");
1160 #endif
1161 
1162   Index = attrIdxToArrayIdx(Index);
1163   SmallVector<AttributeSet, 4> AttrSets(this->begin(), this->end());
1164   if (Index >= AttrSets.size())
1165     AttrSets.resize(Index + 1);
1166 
1167   AttrBuilder Merged(AttrSets[Index]);
1168   Merged.merge(B);
1169   AttrSets[Index] = AttributeSet::get(C, Merged);
1170 
1171   return getImpl(C, AttrSets);
1172 }
1173 
1174 AttributeList AttributeList::addParamAttribute(LLVMContext &C,
1175                                                ArrayRef<unsigned> ArgNos,
1176                                                Attribute A) const {
1177   assert(std::is_sorted(ArgNos.begin(), ArgNos.end()));
1178 
1179   SmallVector<AttributeSet, 4> AttrSets(this->begin(), this->end());
1180   unsigned MaxIndex = attrIdxToArrayIdx(ArgNos.back() + FirstArgIndex);
1181   if (MaxIndex >= AttrSets.size())
1182     AttrSets.resize(MaxIndex + 1);
1183 
1184   for (unsigned ArgNo : ArgNos) {
1185     unsigned Index = attrIdxToArrayIdx(ArgNo + FirstArgIndex);
1186     AttrBuilder B(AttrSets[Index]);
1187     B.addAttribute(A);
1188     AttrSets[Index] = AttributeSet::get(C, B);
1189   }
1190 
1191   return getImpl(C, AttrSets);
1192 }
1193 
1194 AttributeList AttributeList::removeAttribute(LLVMContext &C, unsigned Index,
1195                                              Attribute::AttrKind Kind) const {
1196   if (!hasAttribute(Index, Kind)) return *this;
1197 
1198   Index = attrIdxToArrayIdx(Index);
1199   SmallVector<AttributeSet, 4> AttrSets(this->begin(), this->end());
1200   assert(Index < AttrSets.size());
1201 
1202   AttrSets[Index] = AttrSets[Index].removeAttribute(C, Kind);
1203 
1204   return getImpl(C, AttrSets);
1205 }
1206 
1207 AttributeList AttributeList::removeAttribute(LLVMContext &C, unsigned Index,
1208                                              StringRef Kind) const {
1209   if (!hasAttribute(Index, Kind)) return *this;
1210 
1211   Index = attrIdxToArrayIdx(Index);
1212   SmallVector<AttributeSet, 4> AttrSets(this->begin(), this->end());
1213   assert(Index < AttrSets.size());
1214 
1215   AttrSets[Index] = AttrSets[Index].removeAttribute(C, Kind);
1216 
1217   return getImpl(C, AttrSets);
1218 }
1219 
1220 AttributeList
1221 AttributeList::removeAttributes(LLVMContext &C, unsigned Index,
1222                                 const AttrBuilder &AttrsToRemove) const {
1223   if (!pImpl)
1224     return {};
1225 
1226   Index = attrIdxToArrayIdx(Index);
1227   SmallVector<AttributeSet, 4> AttrSets(this->begin(), this->end());
1228   if (Index >= AttrSets.size())
1229     AttrSets.resize(Index + 1);
1230 
1231   AttrSets[Index] = AttrSets[Index].removeAttributes(C, AttrsToRemove);
1232 
1233   return getImpl(C, AttrSets);
1234 }
1235 
1236 AttributeList AttributeList::removeAttributes(LLVMContext &C,
1237                                               unsigned WithoutIndex) const {
1238   if (!pImpl)
1239     return {};
1240   WithoutIndex = attrIdxToArrayIdx(WithoutIndex);
1241   if (WithoutIndex >= getNumAttrSets())
1242     return *this;
1243   SmallVector<AttributeSet, 4> AttrSets(this->begin(), this->end());
1244   AttrSets[WithoutIndex] = AttributeSet();
1245   return getImpl(C, AttrSets);
1246 }
1247 
1248 AttributeList AttributeList::addDereferenceableAttr(LLVMContext &C,
1249                                                     unsigned Index,
1250                                                     uint64_t Bytes) const {
1251   AttrBuilder B;
1252   B.addDereferenceableAttr(Bytes);
1253   return addAttributes(C, Index, B);
1254 }
1255 
1256 AttributeList
1257 AttributeList::addDereferenceableOrNullAttr(LLVMContext &C, unsigned Index,
1258                                             uint64_t Bytes) const {
1259   AttrBuilder B;
1260   B.addDereferenceableOrNullAttr(Bytes);
1261   return addAttributes(C, Index, B);
1262 }
1263 
1264 AttributeList
1265 AttributeList::addAllocSizeAttr(LLVMContext &C, unsigned Index,
1266                                 unsigned ElemSizeArg,
1267                                 const Optional<unsigned> &NumElemsArg) {
1268   AttrBuilder B;
1269   B.addAllocSizeAttr(ElemSizeArg, NumElemsArg);
1270   return addAttributes(C, Index, B);
1271 }
1272 
1273 //===----------------------------------------------------------------------===//
1274 // AttributeList Accessor Methods
1275 //===----------------------------------------------------------------------===//
1276 
1277 LLVMContext &AttributeList::getContext() const { return pImpl->getContext(); }
1278 
1279 AttributeSet AttributeList::getParamAttributes(unsigned ArgNo) const {
1280   return getAttributes(ArgNo + FirstArgIndex);
1281 }
1282 
1283 AttributeSet AttributeList::getRetAttributes() const {
1284   return getAttributes(ReturnIndex);
1285 }
1286 
1287 AttributeSet AttributeList::getFnAttributes() const {
1288   return getAttributes(FunctionIndex);
1289 }
1290 
1291 bool AttributeList::hasAttribute(unsigned Index,
1292                                  Attribute::AttrKind Kind) const {
1293   return getAttributes(Index).hasAttribute(Kind);
1294 }
1295 
1296 bool AttributeList::hasAttribute(unsigned Index, StringRef Kind) const {
1297   return getAttributes(Index).hasAttribute(Kind);
1298 }
1299 
1300 bool AttributeList::hasAttributes(unsigned Index) const {
1301   return getAttributes(Index).hasAttributes();
1302 }
1303 
1304 bool AttributeList::hasFnAttribute(Attribute::AttrKind Kind) const {
1305   return pImpl && pImpl->hasFnAttribute(Kind);
1306 }
1307 
1308 bool AttributeList::hasFnAttribute(StringRef Kind) const {
1309   return hasAttribute(AttributeList::FunctionIndex, Kind);
1310 }
1311 
1312 bool AttributeList::hasParamAttribute(unsigned ArgNo,
1313                                       Attribute::AttrKind Kind) const {
1314   return hasAttribute(ArgNo + FirstArgIndex, Kind);
1315 }
1316 
1317 bool AttributeList::hasAttrSomewhere(Attribute::AttrKind Attr,
1318                                      unsigned *Index) const {
1319   if (!pImpl) return false;
1320 
1321   for (unsigned I = index_begin(), E = index_end(); I != E; ++I) {
1322     if (hasAttribute(I, Attr)) {
1323       if (Index)
1324         *Index = I;
1325       return true;
1326     }
1327   }
1328 
1329   return false;
1330 }
1331 
1332 Attribute AttributeList::getAttribute(unsigned Index,
1333                                       Attribute::AttrKind Kind) const {
1334   return getAttributes(Index).getAttribute(Kind);
1335 }
1336 
1337 Attribute AttributeList::getAttribute(unsigned Index, StringRef Kind) const {
1338   return getAttributes(Index).getAttribute(Kind);
1339 }
1340 
1341 unsigned AttributeList::getRetAlignment() const {
1342   return getAttributes(ReturnIndex).getAlignment();
1343 }
1344 
1345 unsigned AttributeList::getParamAlignment(unsigned ArgNo) const {
1346   return getAttributes(ArgNo + FirstArgIndex).getAlignment();
1347 }
1348 
1349 Type *AttributeList::getParamByValType(unsigned Index) const {
1350   return getAttributes(Index+FirstArgIndex).getByValType();
1351 }
1352 
1353 
1354 unsigned AttributeList::getStackAlignment(unsigned Index) const {
1355   return getAttributes(Index).getStackAlignment();
1356 }
1357 
1358 uint64_t AttributeList::getDereferenceableBytes(unsigned Index) const {
1359   return getAttributes(Index).getDereferenceableBytes();
1360 }
1361 
1362 uint64_t AttributeList::getDereferenceableOrNullBytes(unsigned Index) const {
1363   return getAttributes(Index).getDereferenceableOrNullBytes();
1364 }
1365 
1366 std::pair<unsigned, Optional<unsigned>>
1367 AttributeList::getAllocSizeArgs(unsigned Index) const {
1368   return getAttributes(Index).getAllocSizeArgs();
1369 }
1370 
1371 std::string AttributeList::getAsString(unsigned Index, bool InAttrGrp) const {
1372   return getAttributes(Index).getAsString(InAttrGrp);
1373 }
1374 
1375 AttributeSet AttributeList::getAttributes(unsigned Index) const {
1376   Index = attrIdxToArrayIdx(Index);
1377   if (!pImpl || Index >= getNumAttrSets())
1378     return {};
1379   return pImpl->begin()[Index];
1380 }
1381 
1382 AttributeList::iterator AttributeList::begin() const {
1383   return pImpl ? pImpl->begin() : nullptr;
1384 }
1385 
1386 AttributeList::iterator AttributeList::end() const {
1387   return pImpl ? pImpl->end() : nullptr;
1388 }
1389 
1390 //===----------------------------------------------------------------------===//
1391 // AttributeList Introspection Methods
1392 //===----------------------------------------------------------------------===//
1393 
1394 unsigned AttributeList::getNumAttrSets() const {
1395   return pImpl ? pImpl->NumAttrSets : 0;
1396 }
1397 
1398 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1399 LLVM_DUMP_METHOD void AttributeList::dump() const {
1400   dbgs() << "PAL[\n";
1401 
1402   for (unsigned i = index_begin(), e = index_end(); i != e; ++i) {
1403     if (getAttributes(i).hasAttributes())
1404       dbgs() << "  { " << i << " => " << getAsString(i) << " }\n";
1405   }
1406 
1407   dbgs() << "]\n";
1408 }
1409 #endif
1410 
1411 //===----------------------------------------------------------------------===//
1412 // AttrBuilder Method Implementations
1413 //===----------------------------------------------------------------------===//
1414 
1415 // FIXME: Remove this ctor, use AttributeSet.
1416 AttrBuilder::AttrBuilder(AttributeList AL, unsigned Index) {
1417   AttributeSet AS = AL.getAttributes(Index);
1418   for (const auto &A : AS)
1419     addAttribute(A);
1420 }
1421 
1422 AttrBuilder::AttrBuilder(AttributeSet AS) {
1423   for (const auto &A : AS)
1424     addAttribute(A);
1425 }
1426 
1427 void AttrBuilder::clear() {
1428   Attrs.reset();
1429   TargetDepAttrs.clear();
1430   Alignment = StackAlignment = DerefBytes = DerefOrNullBytes = 0;
1431   AllocSizeArgs = 0;
1432   ByValType = nullptr;
1433 }
1434 
1435 AttrBuilder &AttrBuilder::addAttribute(Attribute::AttrKind Val) {
1436   assert((unsigned)Val < Attribute::EndAttrKinds && "Attribute out of range!");
1437   assert(Val != Attribute::Alignment && Val != Attribute::StackAlignment &&
1438          Val != Attribute::Dereferenceable && Val != Attribute::AllocSize &&
1439          "Adding integer attribute without adding a value!");
1440   Attrs[Val] = true;
1441   return *this;
1442 }
1443 
1444 AttrBuilder &AttrBuilder::addAttribute(Attribute Attr) {
1445   if (Attr.isStringAttribute()) {
1446     addAttribute(Attr.getKindAsString(), Attr.getValueAsString());
1447     return *this;
1448   }
1449 
1450   Attribute::AttrKind Kind = Attr.getKindAsEnum();
1451   Attrs[Kind] = true;
1452 
1453   if (Kind == Attribute::Alignment)
1454     Alignment = Attr.getAlignment();
1455   else if (Kind == Attribute::StackAlignment)
1456     StackAlignment = Attr.getStackAlignment();
1457   else if (Kind == Attribute::ByVal)
1458     ByValType = Attr.getValueAsType();
1459   else if (Kind == Attribute::Dereferenceable)
1460     DerefBytes = Attr.getDereferenceableBytes();
1461   else if (Kind == Attribute::DereferenceableOrNull)
1462     DerefOrNullBytes = Attr.getDereferenceableOrNullBytes();
1463   else if (Kind == Attribute::AllocSize)
1464     AllocSizeArgs = Attr.getValueAsInt();
1465   return *this;
1466 }
1467 
1468 AttrBuilder &AttrBuilder::addAttribute(StringRef A, StringRef V) {
1469   TargetDepAttrs[A] = V;
1470   return *this;
1471 }
1472 
1473 AttrBuilder &AttrBuilder::removeAttribute(Attribute::AttrKind Val) {
1474   assert((unsigned)Val < Attribute::EndAttrKinds && "Attribute out of range!");
1475   Attrs[Val] = false;
1476 
1477   if (Val == Attribute::Alignment)
1478     Alignment = 0;
1479   else if (Val == Attribute::StackAlignment)
1480     StackAlignment = 0;
1481   else if (Val == Attribute::ByVal)
1482     ByValType = nullptr;
1483   else if (Val == Attribute::Dereferenceable)
1484     DerefBytes = 0;
1485   else if (Val == Attribute::DereferenceableOrNull)
1486     DerefOrNullBytes = 0;
1487   else if (Val == Attribute::AllocSize)
1488     AllocSizeArgs = 0;
1489 
1490   return *this;
1491 }
1492 
1493 AttrBuilder &AttrBuilder::removeAttributes(AttributeList A, uint64_t Index) {
1494   remove(A.getAttributes(Index));
1495   return *this;
1496 }
1497 
1498 AttrBuilder &AttrBuilder::removeAttribute(StringRef A) {
1499   auto I = TargetDepAttrs.find(A);
1500   if (I != TargetDepAttrs.end())
1501     TargetDepAttrs.erase(I);
1502   return *this;
1503 }
1504 
1505 std::pair<unsigned, Optional<unsigned>> AttrBuilder::getAllocSizeArgs() const {
1506   return unpackAllocSizeArgs(AllocSizeArgs);
1507 }
1508 
1509 AttrBuilder &AttrBuilder::addAlignmentAttr(unsigned Align) {
1510   if (Align == 0) return *this;
1511 
1512   assert(isPowerOf2_32(Align) && "Alignment must be a power of two.");
1513   assert(Align <= 0x40000000 && "Alignment too large.");
1514 
1515   Attrs[Attribute::Alignment] = true;
1516   Alignment = Align;
1517   return *this;
1518 }
1519 
1520 AttrBuilder &AttrBuilder::addStackAlignmentAttr(unsigned Align) {
1521   // Default alignment, allow the target to define how to align it.
1522   if (Align == 0) return *this;
1523 
1524   assert(isPowerOf2_32(Align) && "Alignment must be a power of two.");
1525   assert(Align <= 0x100 && "Alignment too large.");
1526 
1527   Attrs[Attribute::StackAlignment] = true;
1528   StackAlignment = Align;
1529   return *this;
1530 }
1531 
1532 AttrBuilder &AttrBuilder::addDereferenceableAttr(uint64_t Bytes) {
1533   if (Bytes == 0) return *this;
1534 
1535   Attrs[Attribute::Dereferenceable] = true;
1536   DerefBytes = Bytes;
1537   return *this;
1538 }
1539 
1540 AttrBuilder &AttrBuilder::addDereferenceableOrNullAttr(uint64_t Bytes) {
1541   if (Bytes == 0)
1542     return *this;
1543 
1544   Attrs[Attribute::DereferenceableOrNull] = true;
1545   DerefOrNullBytes = Bytes;
1546   return *this;
1547 }
1548 
1549 AttrBuilder &AttrBuilder::addAllocSizeAttr(unsigned ElemSize,
1550                                            const Optional<unsigned> &NumElems) {
1551   return addAllocSizeAttrFromRawRepr(packAllocSizeArgs(ElemSize, NumElems));
1552 }
1553 
1554 AttrBuilder &AttrBuilder::addAllocSizeAttrFromRawRepr(uint64_t RawArgs) {
1555   // (0, 0) is our "not present" value, so we need to check for it here.
1556   assert(RawArgs && "Invalid allocsize arguments -- given allocsize(0, 0)");
1557 
1558   Attrs[Attribute::AllocSize] = true;
1559   // Reuse existing machinery to store this as a single 64-bit integer so we can
1560   // save a few bytes over using a pair<unsigned, Optional<unsigned>>.
1561   AllocSizeArgs = RawArgs;
1562   return *this;
1563 }
1564 
1565 AttrBuilder &AttrBuilder::addByValAttr(Type *Ty) {
1566   Attrs[Attribute::ByVal] = true;
1567   ByValType = Ty;
1568   return *this;
1569 }
1570 
1571 AttrBuilder &AttrBuilder::merge(const AttrBuilder &B) {
1572   // FIXME: What if both have alignments, but they don't match?!
1573   if (!Alignment)
1574     Alignment = B.Alignment;
1575 
1576   if (!StackAlignment)
1577     StackAlignment = B.StackAlignment;
1578 
1579   if (!DerefBytes)
1580     DerefBytes = B.DerefBytes;
1581 
1582   if (!DerefOrNullBytes)
1583     DerefOrNullBytes = B.DerefOrNullBytes;
1584 
1585   if (!AllocSizeArgs)
1586     AllocSizeArgs = B.AllocSizeArgs;
1587 
1588   if (!ByValType)
1589     ByValType = B.ByValType;
1590 
1591   Attrs |= B.Attrs;
1592 
1593   for (auto I : B.td_attrs())
1594     TargetDepAttrs[I.first] = I.second;
1595 
1596   return *this;
1597 }
1598 
1599 AttrBuilder &AttrBuilder::remove(const AttrBuilder &B) {
1600   // FIXME: What if both have alignments, but they don't match?!
1601   if (B.Alignment)
1602     Alignment = 0;
1603 
1604   if (B.StackAlignment)
1605     StackAlignment = 0;
1606 
1607   if (B.DerefBytes)
1608     DerefBytes = 0;
1609 
1610   if (B.DerefOrNullBytes)
1611     DerefOrNullBytes = 0;
1612 
1613   if (B.AllocSizeArgs)
1614     AllocSizeArgs = 0;
1615 
1616   if (B.ByValType)
1617     ByValType = nullptr;
1618 
1619   Attrs &= ~B.Attrs;
1620 
1621   for (auto I : B.td_attrs())
1622     TargetDepAttrs.erase(I.first);
1623 
1624   return *this;
1625 }
1626 
1627 bool AttrBuilder::overlaps(const AttrBuilder &B) const {
1628   // First check if any of the target independent attributes overlap.
1629   if ((Attrs & B.Attrs).any())
1630     return true;
1631 
1632   // Then check if any target dependent ones do.
1633   for (const auto &I : td_attrs())
1634     if (B.contains(I.first))
1635       return true;
1636 
1637   return false;
1638 }
1639 
1640 bool AttrBuilder::contains(StringRef A) const {
1641   return TargetDepAttrs.find(A) != TargetDepAttrs.end();
1642 }
1643 
1644 bool AttrBuilder::hasAttributes() const {
1645   return !Attrs.none() || !TargetDepAttrs.empty();
1646 }
1647 
1648 bool AttrBuilder::hasAttributes(AttributeList AL, uint64_t Index) const {
1649   AttributeSet AS = AL.getAttributes(Index);
1650 
1651   for (const auto Attr : AS) {
1652     if (Attr.isEnumAttribute() || Attr.isIntAttribute()) {
1653       if (contains(Attr.getKindAsEnum()))
1654         return true;
1655     } else {
1656       assert(Attr.isStringAttribute() && "Invalid attribute kind!");
1657       return contains(Attr.getKindAsString());
1658     }
1659   }
1660 
1661   return false;
1662 }
1663 
1664 bool AttrBuilder::hasAlignmentAttr() const {
1665   return Alignment != 0;
1666 }
1667 
1668 bool AttrBuilder::operator==(const AttrBuilder &B) {
1669   if (Attrs != B.Attrs)
1670     return false;
1671 
1672   for (td_const_iterator I = TargetDepAttrs.begin(),
1673          E = TargetDepAttrs.end(); I != E; ++I)
1674     if (B.TargetDepAttrs.find(I->first) == B.TargetDepAttrs.end())
1675       return false;
1676 
1677   return Alignment == B.Alignment && StackAlignment == B.StackAlignment &&
1678          DerefBytes == B.DerefBytes && ByValType == B.ByValType;
1679 }
1680 
1681 //===----------------------------------------------------------------------===//
1682 // AttributeFuncs Function Defintions
1683 //===----------------------------------------------------------------------===//
1684 
1685 /// Which attributes cannot be applied to a type.
1686 AttrBuilder AttributeFuncs::typeIncompatible(Type *Ty) {
1687   AttrBuilder Incompatible;
1688 
1689   if (!Ty->isIntegerTy())
1690     // Attribute that only apply to integers.
1691     Incompatible.addAttribute(Attribute::SExt)
1692       .addAttribute(Attribute::ZExt);
1693 
1694   if (!Ty->isPointerTy())
1695     // Attribute that only apply to pointers.
1696     Incompatible.addAttribute(Attribute::ByVal)
1697       .addAttribute(Attribute::Nest)
1698       .addAttribute(Attribute::NoAlias)
1699       .addAttribute(Attribute::NoCapture)
1700       .addAttribute(Attribute::NonNull)
1701       .addDereferenceableAttr(1) // the int here is ignored
1702       .addDereferenceableOrNullAttr(1) // the int here is ignored
1703       .addAttribute(Attribute::ReadNone)
1704       .addAttribute(Attribute::ReadOnly)
1705       .addAttribute(Attribute::StructRet)
1706       .addAttribute(Attribute::InAlloca);
1707 
1708   return Incompatible;
1709 }
1710 
1711 template<typename AttrClass>
1712 static bool isEqual(const Function &Caller, const Function &Callee) {
1713   return Caller.getFnAttribute(AttrClass::getKind()) ==
1714          Callee.getFnAttribute(AttrClass::getKind());
1715 }
1716 
1717 /// Compute the logical AND of the attributes of the caller and the
1718 /// callee.
1719 ///
1720 /// This function sets the caller's attribute to false if the callee's attribute
1721 /// is false.
1722 template<typename AttrClass>
1723 static void setAND(Function &Caller, const Function &Callee) {
1724   if (AttrClass::isSet(Caller, AttrClass::getKind()) &&
1725       !AttrClass::isSet(Callee, AttrClass::getKind()))
1726     AttrClass::set(Caller, AttrClass::getKind(), false);
1727 }
1728 
1729 /// Compute the logical OR of the attributes of the caller and the
1730 /// callee.
1731 ///
1732 /// This function sets the caller's attribute to true if the callee's attribute
1733 /// is true.
1734 template<typename AttrClass>
1735 static void setOR(Function &Caller, const Function &Callee) {
1736   if (!AttrClass::isSet(Caller, AttrClass::getKind()) &&
1737       AttrClass::isSet(Callee, AttrClass::getKind()))
1738     AttrClass::set(Caller, AttrClass::getKind(), true);
1739 }
1740 
1741 /// If the inlined function had a higher stack protection level than the
1742 /// calling function, then bump up the caller's stack protection level.
1743 static void adjustCallerSSPLevel(Function &Caller, const Function &Callee) {
1744   // If upgrading the SSP attribute, clear out the old SSP Attributes first.
1745   // Having multiple SSP attributes doesn't actually hurt, but it adds useless
1746   // clutter to the IR.
1747   AttrBuilder OldSSPAttr;
1748   OldSSPAttr.addAttribute(Attribute::StackProtect)
1749       .addAttribute(Attribute::StackProtectStrong)
1750       .addAttribute(Attribute::StackProtectReq);
1751 
1752   if (Callee.hasFnAttribute(Attribute::StackProtectReq)) {
1753     Caller.removeAttributes(AttributeList::FunctionIndex, OldSSPAttr);
1754     Caller.addFnAttr(Attribute::StackProtectReq);
1755   } else if (Callee.hasFnAttribute(Attribute::StackProtectStrong) &&
1756              !Caller.hasFnAttribute(Attribute::StackProtectReq)) {
1757     Caller.removeAttributes(AttributeList::FunctionIndex, OldSSPAttr);
1758     Caller.addFnAttr(Attribute::StackProtectStrong);
1759   } else if (Callee.hasFnAttribute(Attribute::StackProtect) &&
1760              !Caller.hasFnAttribute(Attribute::StackProtectReq) &&
1761              !Caller.hasFnAttribute(Attribute::StackProtectStrong))
1762     Caller.addFnAttr(Attribute::StackProtect);
1763 }
1764 
1765 /// If the inlined function required stack probes, then ensure that
1766 /// the calling function has those too.
1767 static void adjustCallerStackProbes(Function &Caller, const Function &Callee) {
1768   if (!Caller.hasFnAttribute("probe-stack") &&
1769       Callee.hasFnAttribute("probe-stack")) {
1770     Caller.addFnAttr(Callee.getFnAttribute("probe-stack"));
1771   }
1772 }
1773 
1774 /// If the inlined function defines the size of guard region
1775 /// on the stack, then ensure that the calling function defines a guard region
1776 /// that is no larger.
1777 static void
1778 adjustCallerStackProbeSize(Function &Caller, const Function &Callee) {
1779   if (Callee.hasFnAttribute("stack-probe-size")) {
1780     uint64_t CalleeStackProbeSize;
1781     Callee.getFnAttribute("stack-probe-size")
1782           .getValueAsString()
1783           .getAsInteger(0, CalleeStackProbeSize);
1784     if (Caller.hasFnAttribute("stack-probe-size")) {
1785       uint64_t CallerStackProbeSize;
1786       Caller.getFnAttribute("stack-probe-size")
1787             .getValueAsString()
1788             .getAsInteger(0, CallerStackProbeSize);
1789       if (CallerStackProbeSize > CalleeStackProbeSize) {
1790         Caller.addFnAttr(Callee.getFnAttribute("stack-probe-size"));
1791       }
1792     } else {
1793       Caller.addFnAttr(Callee.getFnAttribute("stack-probe-size"));
1794     }
1795   }
1796 }
1797 
1798 /// If the inlined function defines a min legal vector width, then ensure
1799 /// the calling function has the same or larger min legal vector width. If the
1800 /// caller has the attribute, but the callee doesn't, we need to remove the
1801 /// attribute from the caller since we can't make any guarantees about the
1802 /// caller's requirements.
1803 /// This function is called after the inlining decision has been made so we have
1804 /// to merge the attribute this way. Heuristics that would use
1805 /// min-legal-vector-width to determine inline compatibility would need to be
1806 /// handled as part of inline cost analysis.
1807 static void
1808 adjustMinLegalVectorWidth(Function &Caller, const Function &Callee) {
1809   if (Caller.hasFnAttribute("min-legal-vector-width")) {
1810     if (Callee.hasFnAttribute("min-legal-vector-width")) {
1811       uint64_t CallerVectorWidth;
1812       Caller.getFnAttribute("min-legal-vector-width")
1813             .getValueAsString()
1814             .getAsInteger(0, CallerVectorWidth);
1815       uint64_t CalleeVectorWidth;
1816       Callee.getFnAttribute("min-legal-vector-width")
1817             .getValueAsString()
1818             .getAsInteger(0, CalleeVectorWidth);
1819       if (CallerVectorWidth < CalleeVectorWidth)
1820         Caller.addFnAttr(Callee.getFnAttribute("min-legal-vector-width"));
1821     } else {
1822       // If the callee doesn't have the attribute then we don't know anything
1823       // and must drop the attribute from the caller.
1824       Caller.removeFnAttr("min-legal-vector-width");
1825     }
1826   }
1827 }
1828 
1829 /// If the inlined function has "null-pointer-is-valid=true" attribute,
1830 /// set this attribute in the caller post inlining.
1831 static void
1832 adjustNullPointerValidAttr(Function &Caller, const Function &Callee) {
1833   if (Callee.nullPointerIsDefined() && !Caller.nullPointerIsDefined()) {
1834     Caller.addFnAttr(Callee.getFnAttribute("null-pointer-is-valid"));
1835   }
1836 }
1837 
1838 #define GET_ATTR_COMPAT_FUNC
1839 #include "AttributesCompatFunc.inc"
1840 
1841 bool AttributeFuncs::areInlineCompatible(const Function &Caller,
1842                                          const Function &Callee) {
1843   return hasCompatibleFnAttrs(Caller, Callee);
1844 }
1845 
1846 void AttributeFuncs::mergeAttributesForInlining(Function &Caller,
1847                                                 const Function &Callee) {
1848   mergeFnAttrs(Caller, Callee);
1849 }
1850