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