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