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