Add special 'get' methods to create an Attribute with an alignment. Also do some...
[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 //===----------------------------------------------------------------------===//
578 // AttributeSet Method Implementations
579 //===----------------------------------------------------------------------===//
580
581 AttributeSet AttributeSet::getParamAttributes(unsigned Idx) const {
582   // FIXME: Remove.
583   return pImpl && hasAttributes(Idx) ?
584     AttributeSet::get(pImpl->getContext(),
585                       AttributeWithIndex::get(Idx, getAttributes(Idx))) :
586     AttributeSet();
587 }
588
589 AttributeSet AttributeSet::getRetAttributes() const {
590   // FIXME: Remove.
591   return pImpl && hasAttributes(ReturnIndex) ?
592     AttributeSet::get(pImpl->getContext(),
593                       AttributeWithIndex::get(ReturnIndex,
594                                               getAttributes(ReturnIndex))) :
595     AttributeSet();
596 }
597
598 AttributeSet AttributeSet::getFnAttributes() const {
599   // FIXME: Remove.
600   return pImpl && hasAttributes(FunctionIndex) ?
601     AttributeSet::get(pImpl->getContext(),
602                       AttributeWithIndex::get(FunctionIndex,
603                                               getAttributes(FunctionIndex))) :
604     AttributeSet();
605 }
606
607 AttributeSet AttributeSet::get(LLVMContext &C,
608                                ArrayRef<AttributeWithIndex> Attrs) {
609   // If there are no attributes then return a null AttributesList pointer.
610   if (Attrs.empty())
611     return AttributeSet();
612
613 #ifndef NDEBUG
614   for (unsigned i = 0, e = Attrs.size(); i != e; ++i) {
615     assert(Attrs[i].Attrs.hasAttributes() &&
616            "Pointless attribute!");
617     assert((!i || Attrs[i-1].Index < Attrs[i].Index) &&
618            "Misordered AttributesList!");
619   }
620 #endif
621
622   // Otherwise, build a key to look up the existing attributes.
623   LLVMContextImpl *pImpl = C.pImpl;
624   FoldingSetNodeID ID;
625   AttributeSetImpl::Profile(ID, Attrs);
626
627   void *InsertPoint;
628   AttributeSetImpl *PA = pImpl->AttrsLists.FindNodeOrInsertPos(ID, InsertPoint);
629
630   // If we didn't find any existing attributes of the same shape then
631   // create a new one and insert it.
632   if (!PA) {
633     PA = new AttributeSetImpl(C, Attrs);
634     pImpl->AttrsLists.InsertNode(PA, InsertPoint);
635   }
636
637   // Return the AttributesList that we found or created.
638   return AttributeSet(PA);
639 }
640
641 AttributeSet AttributeSet::get(LLVMContext &C, unsigned Idx, AttrBuilder &B) {
642   // FIXME: This should be implemented as a loop that creates the
643   // AttributeWithIndexes that then are used to create the AttributeSet.
644   if (!B.hasAttributes())
645     return AttributeSet();
646   return get(C, AttributeWithIndex::get(Idx, Attribute::get(C, B)));
647 }
648
649 AttributeSet AttributeSet::get(LLVMContext &C, unsigned Idx,
650                                ArrayRef<Attribute::AttrKind> Kind) {
651   // FIXME: This is temporary. Ultimately, the AttributeWithIndex will be
652   // replaced by an object that holds multiple Attribute::AttrKinds.
653   AttrBuilder B;
654   for (ArrayRef<Attribute::AttrKind>::iterator I = Kind.begin(),
655          E = Kind.end(); I != E; ++I)
656     B.addAttribute(*I);
657   return get(C, Idx, B);
658 }
659
660 AttributeSet AttributeSet::get(LLVMContext &C, ArrayRef<AttributeSet> Attrs) {
661   SmallVector<AttributeWithIndex, 8> AttrList;
662   for (ArrayRef<AttributeSet>::iterator I = Attrs.begin(), E = Attrs.end();
663        I != E; ++I) {
664     AttributeSet AS = *I;
665     if (!AS.pImpl) continue;
666     AttrList.append(AS.pImpl->AttrList.begin(), AS.pImpl->AttrList.end());
667   }
668
669   return get(C, AttrList);
670 }
671
672 const AttributeSet &AttributeSet::operator=(const AttributeSet &RHS) {
673   pImpl = RHS.pImpl;
674   return *this;
675 }
676
677 /// getNumSlots - Return the number of slots used in this attribute list.
678 /// This is the number of arguments that have an attribute set on them
679 /// (including the function itself).
680 unsigned AttributeSet::getNumSlots() const {
681   return pImpl ? pImpl->getNumAttributes() : 0;
682 }
683
684 unsigned AttributeSet::getSlotIndex(unsigned Slot) const {
685   assert(pImpl && Slot < pImpl->getNumAttributes() &&
686          "Slot # out of range!");
687   return pImpl->getSlotIndex(Slot);
688 }
689
690 AttributeSet AttributeSet::getSlotAttributes(unsigned Slot) const {
691   assert(pImpl && Slot < pImpl->getNumAttributes() &&
692          "Slot # out of range!");
693   return pImpl->getSlotAttributes(Slot);
694 }
695
696 bool AttributeSet::hasAttribute(unsigned Index, Attribute::AttrKind Kind) const{
697   return getAttributes(Index).hasAttribute(Kind);
698 }
699
700 bool AttributeSet::hasAttributes(unsigned Index) const {
701   return getAttributes(Index).hasAttributes();
702 }
703
704 std::string AttributeSet::getAsString(unsigned Index) const {
705   return getAttributes(Index).getAsString();
706 }
707
708 unsigned AttributeSet::getParamAlignment(unsigned Idx) const {
709   return getAttributes(Idx).getAlignment();
710 }
711
712 unsigned AttributeSet::getStackAlignment(unsigned Index) const {
713   return getAttributes(Index).getStackAlignment();
714 }
715
716 uint64_t AttributeSet::Raw(unsigned Index) const {
717   // FIXME: Remove this.
718   return getAttributes(Index).Raw();
719 }
720
721 /// getAttributes - The attributes for the specified index are returned.
722 Attribute AttributeSet::getAttributes(unsigned Idx) const {
723   if (pImpl == 0) return Attribute();
724
725   ArrayRef<AttributeWithIndex> Attrs = pImpl->getAttributes();
726   for (unsigned i = 0, e = Attrs.size(); i != e && Attrs[i].Index <= Idx; ++i)
727     if (Attrs[i].Index == Idx)
728       return Attrs[i].Attrs;
729
730   return Attribute();
731 }
732
733 /// hasAttrSomewhere - Return true if the specified attribute is set for at
734 /// least one parameter or for the return value.
735 bool AttributeSet::hasAttrSomewhere(Attribute::AttrKind Attr) const {
736   if (pImpl == 0) return false;
737
738   ArrayRef<AttributeWithIndex> Attrs = pImpl->getAttributes();
739   for (unsigned i = 0, e = Attrs.size(); i != e; ++i)
740     if (Attrs[i].Attrs.hasAttribute(Attr))
741       return true;
742
743   return false;
744 }
745
746 AttributeSet AttributeSet::addAttribute(LLVMContext &C, unsigned Idx,
747                                         Attribute::AttrKind Attr) const {
748   return addAttr(C, Idx, Attribute::get(C, Attr));
749 }
750
751 AttributeSet AttributeSet::addAttributes(LLVMContext &C, unsigned Idx,
752                                          AttributeSet Attrs) const {
753   return addAttr(C, Idx, Attrs.getAttributes(Idx));
754 }
755
756 AttributeSet AttributeSet::addAttr(LLVMContext &C, unsigned Idx,
757                                    Attribute Attrs) const {
758   Attribute OldAttrs = getAttributes(Idx);
759 #ifndef NDEBUG
760   // FIXME it is not obvious how this should work for alignment.
761   // For now, say we can't change a known alignment.
762   unsigned OldAlign = OldAttrs.getAlignment();
763   unsigned NewAlign = Attrs.getAlignment();
764   assert((!OldAlign || !NewAlign || OldAlign == NewAlign) &&
765          "Attempt to change alignment!");
766 #endif
767
768   AttrBuilder NewAttrs =
769     AttrBuilder(OldAttrs).addAttributes(Attrs);
770   if (NewAttrs == AttrBuilder(OldAttrs))
771     return *this;
772
773   SmallVector<AttributeWithIndex, 8> NewAttrList;
774   if (pImpl == 0)
775     NewAttrList.push_back(AttributeWithIndex::get(Idx, Attrs));
776   else {
777     ArrayRef<AttributeWithIndex> OldAttrList = pImpl->getAttributes();
778     unsigned i = 0, e = OldAttrList.size();
779     // Copy attributes for arguments before this one.
780     for (; i != e && OldAttrList[i].Index < Idx; ++i)
781       NewAttrList.push_back(OldAttrList[i]);
782
783     // If there are attributes already at this index, merge them in.
784     if (i != e && OldAttrList[i].Index == Idx) {
785       Attrs =
786         Attribute::get(C, AttrBuilder(Attrs).
787                         addAttributes(OldAttrList[i].Attrs));
788       ++i;
789     }
790
791     NewAttrList.push_back(AttributeWithIndex::get(Idx, Attrs));
792
793     // Copy attributes for arguments after this one.
794     NewAttrList.insert(NewAttrList.end(),
795                        OldAttrList.begin()+i, OldAttrList.end());
796   }
797
798   return get(C, NewAttrList);
799 }
800
801 AttributeSet AttributeSet::removeAttribute(LLVMContext &C, unsigned Idx,
802                                            Attribute::AttrKind Attr) const {
803   return removeAttr(C, Idx, Attribute::get(C, Attr));
804 }
805
806 AttributeSet AttributeSet::removeAttributes(LLVMContext &C, unsigned Idx,
807                                             AttributeSet Attrs) const {
808   return removeAttr(C, Idx, Attrs.getAttributes(Idx));
809 }
810
811 AttributeSet AttributeSet::removeAttr(LLVMContext &C, unsigned Idx,
812                                       Attribute Attrs) const {
813 #ifndef NDEBUG
814   // FIXME it is not obvious how this should work for alignment.
815   // For now, say we can't pass in alignment, which no current use does.
816   assert(!Attrs.hasAttribute(Attribute::Alignment) &&
817          "Attempt to exclude alignment!");
818 #endif
819   if (pImpl == 0) return AttributeSet();
820
821   Attribute OldAttrs = getAttributes(Idx);
822   AttrBuilder NewAttrs =
823     AttrBuilder(OldAttrs).removeAttributes(Attrs);
824   if (NewAttrs == AttrBuilder(OldAttrs))
825     return *this;
826
827   SmallVector<AttributeWithIndex, 8> NewAttrList;
828   ArrayRef<AttributeWithIndex> OldAttrList = pImpl->getAttributes();
829   unsigned i = 0, e = OldAttrList.size();
830
831   // Copy attributes for arguments before this one.
832   for (; i != e && OldAttrList[i].Index < Idx; ++i)
833     NewAttrList.push_back(OldAttrList[i]);
834
835   // If there are attributes already at this index, merge them in.
836   assert(OldAttrList[i].Index == Idx && "Attribute isn't set?");
837   Attrs = Attribute::get(C, AttrBuilder(OldAttrList[i].Attrs).
838                           removeAttributes(Attrs));
839   ++i;
840   if (Attrs.hasAttributes()) // If any attributes left for this param, add them.
841     NewAttrList.push_back(AttributeWithIndex::get(Idx, Attrs));
842
843   // Copy attributes for arguments after this one.
844   NewAttrList.insert(NewAttrList.end(),
845                      OldAttrList.begin()+i, OldAttrList.end());
846
847   return get(C, NewAttrList);
848 }
849
850 void AttributeSet::dump() const {
851   dbgs() << "PAL[ ";
852   for (unsigned i = 0; i < getNumSlots(); ++i) {
853     unsigned Index = getSlotIndex(i);
854     dbgs() << "{ " << Index << " => " << getAsString(Index) << " } ";
855   }
856
857   dbgs() << "]\n";
858 }
859
860 //===----------------------------------------------------------------------===//
861 // AttributeFuncs Function Defintions
862 //===----------------------------------------------------------------------===//
863
864 Attribute AttributeFuncs::typeIncompatible(Type *Ty) {
865   AttrBuilder Incompatible;
866
867   if (!Ty->isIntegerTy())
868     // Attribute that only apply to integers.
869     Incompatible.addAttribute(Attribute::SExt)
870       .addAttribute(Attribute::ZExt);
871
872   if (!Ty->isPointerTy())
873     // Attribute that only apply to pointers.
874     Incompatible.addAttribute(Attribute::ByVal)
875       .addAttribute(Attribute::Nest)
876       .addAttribute(Attribute::NoAlias)
877       .addAttribute(Attribute::NoCapture)
878       .addAttribute(Attribute::StructRet);
879
880   return Attribute::get(Ty->getContext(), Incompatible);
881 }
882
883 /// encodeLLVMAttributesForBitcode - This returns an integer containing an
884 /// encoding of all the LLVM attributes found in the given attribute bitset.
885 /// Any change to this encoding is a breaking change to bitcode compatibility.
886 uint64_t AttributeFuncs::encodeLLVMAttributesForBitcode(AttributeSet Attrs,
887                                                         unsigned Index) {
888   // FIXME: It doesn't make sense to store the alignment information as an
889   // expanded out value, we should store it as a log2 value.  However, we can't
890   // just change that here without breaking bitcode compatibility.  If this ever
891   // becomes a problem in practice, we should introduce new tag numbers in the
892   // bitcode file and have those tags use a more efficiently encoded alignment
893   // field.
894
895   // Store the alignment in the bitcode as a 16-bit raw value instead of a 5-bit
896   // log2 encoded value. Shift the bits above the alignment up by 11 bits.
897   uint64_t EncodedAttrs = Attrs.Raw(Index) & 0xffff;
898   if (Attrs.hasAttribute(Index, Attribute::Alignment))
899     EncodedAttrs |= Attrs.getParamAlignment(Index) << 16;
900   EncodedAttrs |= (Attrs.Raw(Index) & (0xffffULL << 21)) << 11;
901   return EncodedAttrs;
902 }
903
904 /// decodeLLVMAttributesForBitcode - This returns an attribute bitset containing
905 /// the LLVM attributes that have been decoded from the given integer.  This
906 /// function must stay in sync with 'encodeLLVMAttributesForBitcode'.
907 Attribute AttributeFuncs::decodeLLVMAttributesForBitcode(LLVMContext &C,
908                                                          uint64_t EncodedAttrs){
909   // The alignment is stored as a 16-bit raw value from bits 31--16.  We shift
910   // the bits above 31 down by 11 bits.
911   unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
912   assert((!Alignment || isPowerOf2_32(Alignment)) &&
913          "Alignment must be a power of two.");
914
915   AttrBuilder B(EncodedAttrs & 0xffff);
916   if (Alignment)
917     B.addAlignmentAttr(Alignment);
918   B.addRawValue((EncodedAttrs & (0xffffULL << 32)) >> 11);
919   return Attribute::get(C, B);
920 }
921