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