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