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