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