Add an accessor method to get the slot's index. This will limit the use of AttributeW...
[oota-llvm.git] / lib / IR / Attributes.cpp
1 //===-- Attribute.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 // This file implements the Attribute, AttributeImpl, AttrBuilder,
11 // AttributeSetImpl, and AttributeSet classes.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "llvm/IR/Attributes.h"
16 #include "AttributeImpl.h"
17 #include "LLVMContextImpl.h"
18 #include "llvm/ADT/FoldingSet.h"
19 #include "llvm/ADT/StringExtras.h"
20 #include "llvm/IR/Type.h"
21 #include "llvm/Support/Atomic.h"
22 #include "llvm/Support/Debug.h"
23 #include "llvm/Support/ManagedStatic.h"
24 #include "llvm/Support/Mutex.h"
25 #include "llvm/Support/raw_ostream.h"
26 #include <algorithm>
27 using namespace llvm;
28
29 //===----------------------------------------------------------------------===//
30 // Attribute Implementation
31 //===----------------------------------------------------------------------===//
32
33 Attribute Attribute::get(LLVMContext &Context, ArrayRef<AttrKind> Vals) {
34   AttrBuilder B;
35   for (ArrayRef<AttrKind>::iterator I = Vals.begin(), E = Vals.end();
36        I != E; ++I)
37     B.addAttribute(*I);
38   return Attribute::get(Context, B);
39 }
40
41 Attribute Attribute::get(LLVMContext &Context, AttrBuilder &B) {
42   // If there are no attributes, return an empty Attribute class.
43   if (!B.hasAttributes())
44     return Attribute();
45
46   // Otherwise, build a key to look up the existing attributes.
47   LLVMContextImpl *pImpl = Context.pImpl;
48   FoldingSetNodeID ID;
49   ID.AddInteger(B.Raw());
50
51   void *InsertPoint;
52   AttributeImpl *PA = pImpl->AttrsSet.FindNodeOrInsertPos(ID, InsertPoint);
53
54   if (!PA) {
55     // If we didn't find any existing attributes of the same shape then create a
56     // new one and insert it.
57     PA = new AttributeImpl(Context, B.Raw());
58     pImpl->AttrsSet.InsertNode(PA, InsertPoint);
59   }
60
61   // Return the AttributesList that we found or created.
62   return Attribute(PA);
63 }
64
65 bool Attribute::hasAttribute(AttrKind Val) const {
66   return pImpl && pImpl->hasAttribute(Val);
67 }
68
69 bool Attribute::hasAttributes() const {
70   return pImpl && pImpl->hasAttributes();
71 }
72
73 /// This returns the alignment field of an attribute as a byte alignment value.
74 unsigned Attribute::getAlignment() const {
75   if (!hasAttribute(Attribute::Alignment))
76     return 0;
77   return pImpl->getAlignment();
78 }
79
80 /// This returns the stack alignment field of an attribute as a byte alignment
81 /// value.
82 unsigned Attribute::getStackAlignment() const {
83   if (!hasAttribute(Attribute::StackAlignment))
84     return 0;
85   return pImpl->getStackAlignment();
86 }
87
88 bool Attribute::operator==(AttrKind K) const {
89   return pImpl && *pImpl == K;
90 }
91 bool Attribute::operator!=(AttrKind K) const {
92   return !(*this == K);
93 }
94
95 bool Attribute::operator<(Attribute A) const {
96   if (!pImpl && !A.pImpl) return false;
97   if (!pImpl) return true;
98   if (!A.pImpl) return false;
99   return *pImpl < *A.pImpl;
100 }
101
102 uint64_t Attribute::Raw() const {
103   return pImpl ? pImpl->Raw() : 0;
104 }
105
106 Attribute Attribute::typeIncompatible(Type *Ty) {
107   AttrBuilder Incompatible;
108
109   if (!Ty->isIntegerTy())
110     // Attribute that only apply to integers.
111     Incompatible.addAttribute(Attribute::SExt)
112       .addAttribute(Attribute::ZExt);
113
114   if (!Ty->isPointerTy())
115     // Attribute that only apply to pointers.
116     Incompatible.addAttribute(Attribute::ByVal)
117       .addAttribute(Attribute::Nest)
118       .addAttribute(Attribute::NoAlias)
119       .addAttribute(Attribute::NoCapture)
120       .addAttribute(Attribute::StructRet);
121
122   return Attribute::get(Ty->getContext(), Incompatible);
123 }
124
125 /// encodeLLVMAttributesForBitcode - This returns an integer containing an
126 /// encoding of all the LLVM attributes found in the given attribute bitset.
127 /// Any change to this encoding is a breaking change to bitcode compatibility.
128 uint64_t Attribute::encodeLLVMAttributesForBitcode(Attribute Attrs) {
129   // FIXME: It doesn't make sense to store the alignment information as an
130   // expanded out value, we should store it as a log2 value.  However, we can't
131   // just change that here without breaking bitcode compatibility.  If this ever
132   // becomes a problem in practice, we should introduce new tag numbers in the
133   // bitcode file and have those tags use a more efficiently encoded alignment
134   // field.
135
136   // Store the alignment in the bitcode as a 16-bit raw value instead of a 5-bit
137   // log2 encoded value. Shift the bits above the alignment up by 11 bits.
138   uint64_t EncodedAttrs = Attrs.Raw() & 0xffff;
139   if (Attrs.hasAttribute(Attribute::Alignment))
140     EncodedAttrs |= Attrs.getAlignment() << 16;
141   EncodedAttrs |= (Attrs.Raw() & (0xffffULL << 21)) << 11;
142   return EncodedAttrs;
143 }
144
145 /// decodeLLVMAttributesForBitcode - This returns an attribute bitset containing
146 /// the LLVM attributes that have been decoded from the given integer.  This
147 /// function must stay in sync with 'encodeLLVMAttributesForBitcode'.
148 Attribute Attribute::decodeLLVMAttributesForBitcode(LLVMContext &C,
149                                                     uint64_t EncodedAttrs) {
150   // The alignment is stored as a 16-bit raw value from bits 31--16.  We shift
151   // the bits above 31 down by 11 bits.
152   unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
153   assert((!Alignment || isPowerOf2_32(Alignment)) &&
154          "Alignment must be a power of two.");
155
156   AttrBuilder B(EncodedAttrs & 0xffff);
157   if (Alignment)
158     B.addAlignmentAttr(Alignment);
159   B.addRawValue((EncodedAttrs & (0xffffULL << 32)) >> 11);
160   return Attribute::get(C, B);
161 }
162
163 std::string Attribute::getAsString() const {
164   std::string Result;
165   if (hasAttribute(Attribute::ZExt))
166     Result += "zeroext ";
167   if (hasAttribute(Attribute::SExt))
168     Result += "signext ";
169   if (hasAttribute(Attribute::NoReturn))
170     Result += "noreturn ";
171   if (hasAttribute(Attribute::NoUnwind))
172     Result += "nounwind ";
173   if (hasAttribute(Attribute::UWTable))
174     Result += "uwtable ";
175   if (hasAttribute(Attribute::ReturnsTwice))
176     Result += "returns_twice ";
177   if (hasAttribute(Attribute::InReg))
178     Result += "inreg ";
179   if (hasAttribute(Attribute::NoAlias))
180     Result += "noalias ";
181   if (hasAttribute(Attribute::NoCapture))
182     Result += "nocapture ";
183   if (hasAttribute(Attribute::StructRet))
184     Result += "sret ";
185   if (hasAttribute(Attribute::ByVal))
186     Result += "byval ";
187   if (hasAttribute(Attribute::Nest))
188     Result += "nest ";
189   if (hasAttribute(Attribute::ReadNone))
190     Result += "readnone ";
191   if (hasAttribute(Attribute::ReadOnly))
192     Result += "readonly ";
193   if (hasAttribute(Attribute::OptimizeForSize))
194     Result += "optsize ";
195   if (hasAttribute(Attribute::NoInline))
196     Result += "noinline ";
197   if (hasAttribute(Attribute::InlineHint))
198     Result += "inlinehint ";
199   if (hasAttribute(Attribute::AlwaysInline))
200     Result += "alwaysinline ";
201   if (hasAttribute(Attribute::StackProtect))
202     Result += "ssp ";
203   if (hasAttribute(Attribute::StackProtectReq))
204     Result += "sspreq ";
205   if (hasAttribute(Attribute::StackProtectStrong))
206     Result += "sspstrong ";
207   if (hasAttribute(Attribute::NoRedZone))
208     Result += "noredzone ";
209   if (hasAttribute(Attribute::NoImplicitFloat))
210     Result += "noimplicitfloat ";
211   if (hasAttribute(Attribute::Naked))
212     Result += "naked ";
213   if (hasAttribute(Attribute::NonLazyBind))
214     Result += "nonlazybind ";
215   if (hasAttribute(Attribute::AddressSafety))
216     Result += "address_safety ";
217   if (hasAttribute(Attribute::MinSize))
218     Result += "minsize ";
219   if (hasAttribute(Attribute::StackAlignment)) {
220     Result += "alignstack(";
221     Result += utostr(getStackAlignment());
222     Result += ") ";
223   }
224   if (hasAttribute(Attribute::Alignment)) {
225     Result += "align ";
226     Result += utostr(getAlignment());
227     Result += " ";
228   }
229   if (hasAttribute(Attribute::NoDuplicate))
230     Result += "noduplicate ";
231   // Trim the trailing space.
232   assert(!Result.empty() && "Unknown attribute!");
233   Result.erase(Result.end()-1);
234   return Result;
235 }
236
237 //===----------------------------------------------------------------------===//
238 // AttrBuilder Method Implementations
239 //===----------------------------------------------------------------------===//
240
241 AttrBuilder::AttrBuilder(AttributeSet AS, unsigned Idx)
242   : Alignment(0), StackAlignment(0) {
243   AttributeSetImpl *pImpl = AS.AttrList;
244   if (!pImpl) return;
245
246   ArrayRef<AttributeWithIndex> AttrList = pImpl->getAttributes();
247   const AttributeWithIndex *AWI = 0;
248   for (unsigned I = 0, E = AttrList.size(); I != E; ++I)
249     if (AttrList[I].Index == Idx) {
250       AWI = &AttrList[I];
251       break;
252     }
253
254   if (!AWI) return;
255
256   uint64_t Mask = AWI->Attrs.Raw();
257
258   for (Attribute::AttrKind I = Attribute::None; I != Attribute::EndAttrKinds;
259        I = Attribute::AttrKind(I + 1)) {
260     if (uint64_t A = (Mask & AttributeImpl::getAttrMask(I))) {
261       Attrs.insert(I);
262
263       if (I == Attribute::Alignment)
264         Alignment = 1ULL << ((A >> 16) - 1);
265       else if (I == Attribute::StackAlignment)
266         StackAlignment = 1ULL << ((A >> 26)-1);
267     }
268   }
269 }
270
271 void AttrBuilder::clear() {
272   Attrs.clear();
273   Alignment = StackAlignment = 0;
274 }
275
276 AttrBuilder &AttrBuilder::addAttribute(Attribute::AttrKind Val) {
277   Attrs.insert(Val);
278   return *this;
279 }
280
281 AttrBuilder &AttrBuilder::removeAttribute(Attribute::AttrKind Val) {
282   Attrs.erase(Val);
283   if (Val == Attribute::Alignment)
284     Alignment = 0;
285   else if (Val == Attribute::StackAlignment)
286     StackAlignment = 0;
287
288   return *this;
289 }
290
291 AttrBuilder &AttrBuilder::addAlignmentAttr(unsigned Align) {
292   if (Align == 0) return *this;
293
294   assert(isPowerOf2_32(Align) && "Alignment must be a power of two.");
295   assert(Align <= 0x40000000 && "Alignment too large.");
296
297   Attrs.insert(Attribute::Alignment);
298   Alignment = Align;
299   return *this;
300 }
301
302 AttrBuilder &AttrBuilder::addStackAlignmentAttr(unsigned Align) {
303   // Default alignment, allow the target to define how to align it.
304   if (Align == 0) return *this;
305
306   assert(isPowerOf2_32(Align) && "Alignment must be a power of two.");
307   assert(Align <= 0x100 && "Alignment too large.");
308
309   Attrs.insert(Attribute::StackAlignment);
310   StackAlignment = Align;
311   return *this;
312 }
313
314 AttrBuilder &AttrBuilder::addRawValue(uint64_t Val) {
315   for (Attribute::AttrKind I = Attribute::None; I != Attribute::EndAttrKinds;
316        I = Attribute::AttrKind(I + 1)) {
317     if (uint64_t A = (Val & AttributeImpl::getAttrMask(I))) {
318       Attrs.insert(I);
319  
320       if (I == Attribute::Alignment)
321         Alignment = 1ULL << ((A >> 16) - 1);
322       else if (I == Attribute::StackAlignment)
323         StackAlignment = 1ULL << ((A >> 26)-1);
324     }
325   }
326  
327   return *this;
328 }
329
330 AttrBuilder &AttrBuilder::addAttributes(const Attribute &Attr) {
331   uint64_t Mask = Attr.Raw();
332
333   for (Attribute::AttrKind I = Attribute::None; I != Attribute::EndAttrKinds;
334        I = Attribute::AttrKind(I + 1))
335     if ((Mask & AttributeImpl::getAttrMask(I)) != 0)
336       Attrs.insert(I);
337
338   if (Attr.getAlignment())
339     Alignment = Attr.getAlignment();
340   if (Attr.getStackAlignment())
341     StackAlignment = Attr.getStackAlignment();
342   return *this;
343 }
344
345 AttrBuilder &AttrBuilder::removeAttributes(const Attribute &A){
346   uint64_t Mask = A.Raw();
347
348   for (Attribute::AttrKind I = Attribute::None; I != Attribute::EndAttrKinds;
349        I = Attribute::AttrKind(I + 1)) {
350     if (Mask & AttributeImpl::getAttrMask(I)) {
351       Attrs.erase(I);
352
353       if (I == Attribute::Alignment)
354         Alignment = 0;
355       else if (I == Attribute::StackAlignment)
356         StackAlignment = 0;
357     }
358   }
359
360   return *this;
361 }
362
363 bool AttrBuilder::contains(Attribute::AttrKind A) const {
364   return Attrs.count(A);
365 }
366
367 bool AttrBuilder::hasAttributes() const {
368   return !Attrs.empty();
369 }
370
371 bool AttrBuilder::hasAttributes(const Attribute &A) const {
372   return Raw() & A.Raw();
373 }
374
375 bool AttrBuilder::hasAlignmentAttr() const {
376   return Alignment != 0;
377 }
378
379 uint64_t AttrBuilder::Raw() const {
380   uint64_t Mask = 0;
381
382   for (DenseSet<Attribute::AttrKind>::const_iterator I = Attrs.begin(),
383          E = Attrs.end(); I != E; ++I) {
384     Attribute::AttrKind Kind = *I;
385
386     if (Kind == Attribute::Alignment)
387       Mask |= (Log2_32(Alignment) + 1) << 16;
388     else if (Kind == Attribute::StackAlignment)
389       Mask |= (Log2_32(StackAlignment) + 1) << 26;
390     else
391       Mask |= AttributeImpl::getAttrMask(Kind);
392   }
393
394   return Mask;
395 }
396
397 bool AttrBuilder::operator==(const AttrBuilder &B) {
398   SmallVector<Attribute::AttrKind, 8> This(Attrs.begin(), Attrs.end());
399   SmallVector<Attribute::AttrKind, 8> That(B.Attrs.begin(), B.Attrs.end());
400   return This == That;
401 }
402
403 //===----------------------------------------------------------------------===//
404 // AttributeImpl Definition
405 //===----------------------------------------------------------------------===//
406
407 AttributeImpl::AttributeImpl(LLVMContext &C, uint64_t data)
408   : Context(C) {
409   Data = ConstantInt::get(Type::getInt64Ty(C), data);
410 }
411 AttributeImpl::AttributeImpl(LLVMContext &C, Attribute::AttrKind data)
412   : Context(C) {
413   Data = ConstantInt::get(Type::getInt64Ty(C), data);
414 }
415 AttributeImpl::AttributeImpl(LLVMContext &C, Attribute::AttrKind data,
416                              ArrayRef<Constant*> values)
417   : Context(C) {
418   Data = ConstantInt::get(Type::getInt64Ty(C), data);
419   Vals.reserve(values.size());
420   Vals.append(values.begin(), values.end());
421 }
422 AttributeImpl::AttributeImpl(LLVMContext &C, StringRef data)
423   : Context(C) {
424   Data = ConstantDataArray::getString(C, data);
425 }
426
427 bool AttributeImpl::operator==(Attribute::AttrKind Kind) const {
428   if (ConstantInt *CI = dyn_cast<ConstantInt>(Data))
429     return CI->getZExtValue() == Kind;
430   return false;
431 }
432 bool AttributeImpl::operator!=(Attribute::AttrKind Kind) const {
433   return !(*this == Kind);
434 }
435
436 bool AttributeImpl::operator==(StringRef Kind) const {
437   if (ConstantDataArray *CDA = dyn_cast<ConstantDataArray>(Data))
438     if (CDA->isString())
439       return CDA->getAsString() == Kind;
440   return false;
441 }
442
443 bool AttributeImpl::operator!=(StringRef Kind) const {
444   return !(*this == Kind);
445 }
446
447 bool AttributeImpl::operator<(const AttributeImpl &AI) const {
448   if (!Data && !AI.Data) return false;
449   if (!Data && AI.Data) return true;
450   if (Data && !AI.Data) return false;
451
452   ConstantInt *ThisCI = dyn_cast<ConstantInt>(Data);
453   ConstantInt *ThatCI = dyn_cast<ConstantInt>(AI.Data);
454
455   ConstantDataArray *ThisCDA = dyn_cast<ConstantDataArray>(Data);
456   ConstantDataArray *ThatCDA = dyn_cast<ConstantDataArray>(AI.Data);
457
458   if (ThisCI && ThatCI)
459     return ThisCI->getZExtValue() < ThatCI->getZExtValue();
460
461   if (ThisCI && ThatCDA)
462     return true;
463
464   if (ThisCDA && ThatCI)
465     return false;
466
467   return ThisCDA->getAsString() < ThatCDA->getAsString();
468 }
469
470 uint64_t AttributeImpl::Raw() const {
471   // FIXME: Remove this.
472   return cast<ConstantInt>(Data)->getZExtValue();
473 }
474
475 uint64_t AttributeImpl::getAttrMask(Attribute::AttrKind Val) {
476   switch (Val) {
477   case Attribute::EndAttrKinds:
478   case Attribute::AttrKindEmptyKey:
479   case Attribute::AttrKindTombstoneKey:
480     llvm_unreachable("Synthetic enumerators which should never get here");
481
482   case Attribute::None:            return 0;
483   case Attribute::ZExt:            return 1 << 0;
484   case Attribute::SExt:            return 1 << 1;
485   case Attribute::NoReturn:        return 1 << 2;
486   case Attribute::InReg:           return 1 << 3;
487   case Attribute::StructRet:       return 1 << 4;
488   case Attribute::NoUnwind:        return 1 << 5;
489   case Attribute::NoAlias:         return 1 << 6;
490   case Attribute::ByVal:           return 1 << 7;
491   case Attribute::Nest:            return 1 << 8;
492   case Attribute::ReadNone:        return 1 << 9;
493   case Attribute::ReadOnly:        return 1 << 10;
494   case Attribute::NoInline:        return 1 << 11;
495   case Attribute::AlwaysInline:    return 1 << 12;
496   case Attribute::OptimizeForSize: return 1 << 13;
497   case Attribute::StackProtect:    return 1 << 14;
498   case Attribute::StackProtectReq: return 1 << 15;
499   case Attribute::Alignment:       return 31 << 16;
500   case Attribute::NoCapture:       return 1 << 21;
501   case Attribute::NoRedZone:       return 1 << 22;
502   case Attribute::NoImplicitFloat: return 1 << 23;
503   case Attribute::Naked:           return 1 << 24;
504   case Attribute::InlineHint:      return 1 << 25;
505   case Attribute::StackAlignment:  return 7 << 26;
506   case Attribute::ReturnsTwice:    return 1 << 29;
507   case Attribute::UWTable:         return 1 << 30;
508   case Attribute::NonLazyBind:     return 1U << 31;
509   case Attribute::AddressSafety:   return 1ULL << 32;
510   case Attribute::MinSize:         return 1ULL << 33;
511   case Attribute::NoDuplicate:     return 1ULL << 34;
512   case Attribute::StackProtectStrong: return 1ULL << 35;
513   }
514   llvm_unreachable("Unsupported attribute type");
515 }
516
517 bool AttributeImpl::hasAttribute(Attribute::AttrKind A) const {
518   return (Raw() & getAttrMask(A)) != 0;
519 }
520
521 bool AttributeImpl::hasAttributes() const {
522   return Raw() != 0;
523 }
524
525 uint64_t AttributeImpl::getAlignment() const {
526   uint64_t Mask = Raw() & getAttrMask(Attribute::Alignment);
527   return 1ULL << ((Mask >> 16) - 1);
528 }
529
530 uint64_t AttributeImpl::getStackAlignment() const {
531   uint64_t Mask = Raw() & getAttrMask(Attribute::StackAlignment);
532   return 1ULL << ((Mask >> 26) - 1);
533 }
534
535 void AttributeImpl::Profile(FoldingSetNodeID &ID, Constant *Data,
536                             ArrayRef<Constant*> Vals) {
537   ID.AddInteger(cast<ConstantInt>(Data)->getZExtValue());
538 #if 0
539   // FIXME: Not yet supported.
540   for (ArrayRef<Constant*>::iterator I = Vals.begin(), E = Vals.end();
541        I != E; ++I)
542     ID.AddPointer(*I);
543 #endif
544 }
545
546 //===----------------------------------------------------------------------===//
547 // AttributeWithIndex Definition
548 //===----------------------------------------------------------------------===//
549
550 AttributeWithIndex AttributeWithIndex::get(LLVMContext &C, unsigned Idx,
551                                            AttributeSet AS) {
552   // FIXME: This is temporary, but necessary for the conversion.
553   AttrBuilder B(AS, Idx);
554   return get(Idx, Attribute::get(C, B));
555 }
556
557 //===----------------------------------------------------------------------===//
558 // AttributeSetNode Definition
559 //===----------------------------------------------------------------------===//
560
561 AttributeSetNode *AttributeSetNode::get(LLVMContext &C,
562                                         ArrayRef<Attribute> Attrs) {
563   if (Attrs.empty())
564     return 0;
565
566   // Otherwise, build a key to look up the existing attributes.
567   LLVMContextImpl *pImpl = C.pImpl;
568   FoldingSetNodeID ID;
569
570   SmallVector<Attribute, 8> SortedAttrs(Attrs.begin(), Attrs.end());
571   std::sort(SortedAttrs.begin(), SortedAttrs.end());
572
573   for (SmallVectorImpl<Attribute>::iterator I = SortedAttrs.begin(),
574          E = SortedAttrs.end(); I != E; ++I)
575     I->Profile(ID);
576
577   void *InsertPoint;
578   AttributeSetNode *PA =
579     pImpl->AttrsSetNodes.FindNodeOrInsertPos(ID, InsertPoint);
580
581   // If we didn't find any existing attributes of the same shape then create a
582   // new one and insert it.
583   if (!PA) {
584     PA = new AttributeSetNode(SortedAttrs);
585     pImpl->AttrsSetNodes.InsertNode(PA, InsertPoint);
586   }
587
588   // Return the AttributesListNode that we found or created.
589   return PA;
590 }
591
592 //===----------------------------------------------------------------------===//
593 // AttributeSetImpl Definition
594 //===----------------------------------------------------------------------===//
595
596 AttributeSet AttributeSet::getParamAttributes(unsigned Idx) const {
597   // FIXME: Remove.
598   return AttrList && hasAttributes(Idx) ?
599     AttributeSet::get(AttrList->getContext(),
600                       AttributeWithIndex::get(Idx, getAttributes(Idx))) :
601     AttributeSet();
602 }
603
604 AttributeSet AttributeSet::getRetAttributes() const {
605   // FIXME: Remove.
606   return AttrList && hasAttributes(ReturnIndex) ?
607     AttributeSet::get(AttrList->getContext(),
608                       AttributeWithIndex::get(ReturnIndex,
609                                               getAttributes(ReturnIndex))) :
610     AttributeSet();
611 }
612
613 AttributeSet AttributeSet::getFnAttributes() const {
614   // FIXME: Remove.
615   return AttrList && hasAttributes(FunctionIndex) ?
616     AttributeSet::get(AttrList->getContext(),
617                       AttributeWithIndex::get(FunctionIndex,
618                                               getAttributes(FunctionIndex))) :
619     AttributeSet();
620 }
621
622 AttributeSet AttributeSet::get(LLVMContext &C,
623                                ArrayRef<AttributeWithIndex> Attrs) {
624   // If there are no attributes then return a null AttributesList pointer.
625   if (Attrs.empty())
626     return AttributeSet();
627
628 #ifndef NDEBUG
629   for (unsigned i = 0, e = Attrs.size(); i != e; ++i) {
630     assert(Attrs[i].Attrs.hasAttributes() &&
631            "Pointless attribute!");
632     assert((!i || Attrs[i-1].Index < Attrs[i].Index) &&
633            "Misordered AttributesList!");
634   }
635 #endif
636
637   // Otherwise, build a key to look up the existing attributes.
638   LLVMContextImpl *pImpl = C.pImpl;
639   FoldingSetNodeID ID;
640   AttributeSetImpl::Profile(ID, Attrs);
641
642   void *InsertPoint;
643   AttributeSetImpl *PA = pImpl->AttrsLists.FindNodeOrInsertPos(ID, InsertPoint);
644
645   // If we didn't find any existing attributes of the same shape then
646   // create a new one and insert it.
647   if (!PA) {
648     PA = new AttributeSetImpl(C, Attrs);
649     pImpl->AttrsLists.InsertNode(PA, InsertPoint);
650   }
651
652   // Return the AttributesList that we found or created.
653   return AttributeSet(PA);
654 }
655
656 AttributeSet AttributeSet::get(LLVMContext &C, unsigned Idx, AttrBuilder &B) {
657   // FIXME: This should be implemented as a loop that creates the
658   // AttributeWithIndexes that then are used to create the AttributeSet.
659   if (!B.hasAttributes())
660     return AttributeSet();
661   return get(C, AttributeWithIndex::get(Idx, Attribute::get(C, B)));
662 }
663
664 AttributeSet AttributeSet::get(LLVMContext &C, unsigned Idx,
665                                Attribute::AttrKind Kind) {
666   return get(C, AttributeWithIndex::get(Idx, Attribute::get(C, Kind)));
667 }
668
669 //===----------------------------------------------------------------------===//
670 // AttributeSet Method Implementations
671 //===----------------------------------------------------------------------===//
672
673 const AttributeSet &AttributeSet::operator=(const AttributeSet &RHS) {
674   AttrList = RHS.AttrList;
675   return *this;
676 }
677
678 /// getNumSlots - Return the number of slots used in this attribute list.
679 /// This is the number of arguments that have an attribute set on them
680 /// (including the function itself).
681 unsigned AttributeSet::getNumSlots() const {
682   return AttrList ? AttrList->getNumAttributes() : 0;
683 }
684
685 unsigned AttributeSet::getSlotIndex(unsigned Slot) const {
686   assert(AttrList && Slot < AttrList->getNumAttributes() &&
687          "Slot # out of range!");
688   return AttrList->getSlotIndex(Slot);
689 }
690
691 /// getSlot - Return the AttributeWithIndex at the specified slot.  This
692 /// holds a number plus a set of attributes.
693 const AttributeWithIndex &AttributeSet::getSlot(unsigned Slot) const {
694   assert(AttrList && Slot < AttrList->getNumAttributes() &&
695          "Slot # out of range!");
696   return AttrList->getAttributes()[Slot];
697 }
698
699 bool AttributeSet::hasAttribute(unsigned Index, Attribute::AttrKind Kind) const{
700   return getAttributes(Index).hasAttribute(Kind);
701 }
702
703 bool AttributeSet::hasAttributes(unsigned Index) const {
704   return getAttributes(Index).hasAttributes();
705 }
706
707 std::string AttributeSet::getAsString(unsigned Index) const {
708   return getAttributes(Index).getAsString();
709 }
710
711 unsigned AttributeSet::getParamAlignment(unsigned Idx) const {
712   return getAttributes(Idx).getAlignment();
713 }
714
715 unsigned AttributeSet::getStackAlignment(unsigned Index) const {
716   return getAttributes(Index).getStackAlignment();
717 }
718
719 uint64_t AttributeSet::Raw(unsigned Index) const {
720   // FIXME: Remove this.
721   return getAttributes(Index).Raw();
722 }
723
724 /// getAttributes - The attributes for the specified index are returned.
725 Attribute AttributeSet::getAttributes(unsigned Idx) const {
726   if (AttrList == 0) return Attribute();
727
728   ArrayRef<AttributeWithIndex> Attrs = AttrList->getAttributes();
729   for (unsigned i = 0, e = Attrs.size(); i != e && Attrs[i].Index <= Idx; ++i)
730     if (Attrs[i].Index == Idx)
731       return Attrs[i].Attrs;
732
733   return Attribute();
734 }
735
736 /// hasAttrSomewhere - Return true if the specified attribute is set for at
737 /// least one parameter or for the return value.
738 bool AttributeSet::hasAttrSomewhere(Attribute::AttrKind Attr) const {
739   if (AttrList == 0) return false;
740
741   ArrayRef<AttributeWithIndex> Attrs = AttrList->getAttributes();
742   for (unsigned i = 0, e = Attrs.size(); i != e; ++i)
743     if (Attrs[i].Attrs.hasAttribute(Attr))
744       return true;
745
746   return false;
747 }
748
749 AttributeSet AttributeSet::addAttribute(LLVMContext &C, unsigned Idx,
750                                         Attribute::AttrKind Attr) const {
751   return addAttr(C, Idx, Attribute::get(C, Attr));
752 }
753
754 AttributeSet AttributeSet::addAttributes(LLVMContext &C, unsigned Idx,
755                                          AttributeSet Attrs) const {
756   return addAttr(C, Idx, Attrs.getAttributes(Idx));
757 }
758
759 AttributeSet AttributeSet::addAttr(LLVMContext &C, unsigned Idx,
760                                    Attribute Attrs) const {
761   Attribute OldAttrs = getAttributes(Idx);
762 #ifndef NDEBUG
763   // FIXME it is not obvious how this should work for alignment.
764   // For now, say we can't change a known alignment.
765   unsigned OldAlign = OldAttrs.getAlignment();
766   unsigned NewAlign = Attrs.getAlignment();
767   assert((!OldAlign || !NewAlign || OldAlign == NewAlign) &&
768          "Attempt to change alignment!");
769 #endif
770
771   AttrBuilder NewAttrs =
772     AttrBuilder(OldAttrs).addAttributes(Attrs);
773   if (NewAttrs == AttrBuilder(OldAttrs))
774     return *this;
775
776   SmallVector<AttributeWithIndex, 8> NewAttrList;
777   if (AttrList == 0)
778     NewAttrList.push_back(AttributeWithIndex::get(Idx, Attrs));
779   else {
780     ArrayRef<AttributeWithIndex> OldAttrList = AttrList->getAttributes();
781     unsigned i = 0, e = OldAttrList.size();
782     // Copy attributes for arguments before this one.
783     for (; i != e && OldAttrList[i].Index < Idx; ++i)
784       NewAttrList.push_back(OldAttrList[i]);
785
786     // If there are attributes already at this index, merge them in.
787     if (i != e && OldAttrList[i].Index == Idx) {
788       Attrs =
789         Attribute::get(C, AttrBuilder(Attrs).
790                         addAttributes(OldAttrList[i].Attrs));
791       ++i;
792     }
793
794     NewAttrList.push_back(AttributeWithIndex::get(Idx, Attrs));
795
796     // Copy attributes for arguments after this one.
797     NewAttrList.insert(NewAttrList.end(),
798                        OldAttrList.begin()+i, OldAttrList.end());
799   }
800
801   return get(C, NewAttrList);
802 }
803
804 AttributeSet AttributeSet::removeAttribute(LLVMContext &C, unsigned Idx,
805                                            Attribute::AttrKind Attr) const {
806   return removeAttr(C, Idx, Attribute::get(C, Attr));
807 }
808
809 AttributeSet AttributeSet::removeAttributes(LLVMContext &C, unsigned Idx,
810                                             AttributeSet Attrs) const {
811   return removeAttr(C, Idx, Attrs.getAttributes(Idx));
812 }
813
814 AttributeSet AttributeSet::removeAttr(LLVMContext &C, unsigned Idx,
815                                       Attribute Attrs) const {
816 #ifndef NDEBUG
817   // FIXME it is not obvious how this should work for alignment.
818   // For now, say we can't pass in alignment, which no current use does.
819   assert(!Attrs.hasAttribute(Attribute::Alignment) &&
820          "Attempt to exclude alignment!");
821 #endif
822   if (AttrList == 0) return AttributeSet();
823
824   Attribute OldAttrs = getAttributes(Idx);
825   AttrBuilder NewAttrs =
826     AttrBuilder(OldAttrs).removeAttributes(Attrs);
827   if (NewAttrs == AttrBuilder(OldAttrs))
828     return *this;
829
830   SmallVector<AttributeWithIndex, 8> NewAttrList;
831   ArrayRef<AttributeWithIndex> OldAttrList = AttrList->getAttributes();
832   unsigned i = 0, e = OldAttrList.size();
833
834   // Copy attributes for arguments before this one.
835   for (; i != e && OldAttrList[i].Index < Idx; ++i)
836     NewAttrList.push_back(OldAttrList[i]);
837
838   // If there are attributes already at this index, merge them in.
839   assert(OldAttrList[i].Index == Idx && "Attribute isn't set?");
840   Attrs = Attribute::get(C, AttrBuilder(OldAttrList[i].Attrs).
841                           removeAttributes(Attrs));
842   ++i;
843   if (Attrs.hasAttributes()) // If any attributes left for this param, add them.
844     NewAttrList.push_back(AttributeWithIndex::get(Idx, Attrs));
845
846   // Copy attributes for arguments after this one.
847   NewAttrList.insert(NewAttrList.end(),
848                      OldAttrList.begin()+i, OldAttrList.end());
849
850   return get(C, NewAttrList);
851 }
852
853 void AttributeSet::dump() const {
854   dbgs() << "PAL[ ";
855   for (unsigned i = 0; i < getNumSlots(); ++i) {
856     const AttributeWithIndex &PAWI = getSlot(i);
857     dbgs() << "{ " << PAWI.Index << ", " << PAWI.Attrs.getAsString() << " } ";
858   }
859
860   dbgs() << "]\n";
861 }