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