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