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