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