Convert to storing the attribute's internals as enums, integers, and strings.
[oota-llvm.git] / lib / IR / Attributes.cpp
1 //===-- Attributes.cpp - Implement AttributesList -------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // \file
11 // \brief This file implements the Attribute, AttributeImpl, AttrBuilder,
12 // AttributeSetImpl, and AttributeSet classes.
13 //
14 //===----------------------------------------------------------------------===//
15
16 #include "llvm/IR/Attributes.h"
17 #include "AttributeImpl.h"
18 #include "LLVMContextImpl.h"
19 #include "llvm/ADT/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 Construction Methods
31 //===----------------------------------------------------------------------===//
32
33 Attribute Attribute::get(LLVMContext &Context, Attribute::AttrKind Kind,
34                          uint64_t Val) {
35   LLVMContextImpl *pImpl = Context.pImpl;
36   FoldingSetNodeID ID;
37   ID.AddInteger(Kind);
38   if (Val) ID.AddInteger(Val);
39
40   void *InsertPoint;
41   AttributeImpl *PA = pImpl->AttrsSet.FindNodeOrInsertPos(ID, InsertPoint);
42
43   if (!PA) {
44     // If we didn't find any existing attributes of the same shape then create a
45     // new one and insert it.
46     PA = !Val ?
47       new AttributeImpl(Context, Kind) :
48       new AttributeImpl(Context, Kind, Val);
49     pImpl->AttrsSet.InsertNode(PA, InsertPoint);
50   }
51
52   // Return the Attribute that we found or created.
53   return Attribute(PA);
54 }
55
56 Attribute Attribute::get(LLVMContext &Context, StringRef Kind, StringRef Val) {
57   LLVMContextImpl *pImpl = Context.pImpl;
58   FoldingSetNodeID ID;
59   ID.AddString(Kind);
60   if (!Val.empty()) ID.AddString(Val);
61
62   void *InsertPoint;
63   AttributeImpl *PA = pImpl->AttrsSet.FindNodeOrInsertPos(ID, InsertPoint);
64
65   if (!PA) {
66     // If we didn't find any existing attributes of the same shape then create a
67     // new one and insert it.
68     PA = new AttributeImpl(Context, Kind, Val);
69     pImpl->AttrsSet.InsertNode(PA, InsertPoint);
70   }
71
72   // Return the Attribute that we found or created.
73   return Attribute(PA);
74 }
75
76 Attribute Attribute::getWithAlignment(LLVMContext &Context, uint64_t Align) {
77   assert(isPowerOf2_32(Align) && "Alignment must be a power of two.");
78   assert(Align <= 0x40000000 && "Alignment too large.");
79   return get(Context, Alignment, Align);
80 }
81
82 Attribute Attribute::getWithStackAlignment(LLVMContext &Context,
83                                            uint64_t Align) {
84   assert(isPowerOf2_32(Align) && "Alignment must be a power of two.");
85   assert(Align <= 0x100 && "Alignment too large.");
86   return get(Context, StackAlignment, Align);
87 }
88
89 //===----------------------------------------------------------------------===//
90 // Attribute Accessor Methods
91 //===----------------------------------------------------------------------===//
92
93 bool Attribute::isEnumAttribute() const {
94   return pImpl && pImpl->isEnumAttribute();
95 }
96
97 bool Attribute::isAlignAttribute() const {
98   return pImpl && pImpl->isAlignAttribute();
99 }
100
101 bool Attribute::isStringAttribute() const {
102   return pImpl && pImpl->isStringAttribute();
103 }
104
105 Attribute::AttrKind Attribute::getKindAsEnum() const {
106   assert((isEnumAttribute() || isAlignAttribute()) &&
107          "Invalid attribute type to get the kind as an enum!");
108   return pImpl ? pImpl->getKindAsEnum() : None;
109 }
110
111 uint64_t Attribute::getValueAsInt() const {
112   assert(isAlignAttribute() &&
113          "Expected the attribute to be an alignment attribute!");
114   return pImpl ? pImpl->getValueAsInt() : 0;
115 }
116
117 StringRef Attribute::getKindAsString() const {
118   assert(isStringAttribute() &&
119          "Invalid attribute type to get the kind as a string!");
120   return pImpl ? pImpl->getKindAsString() : StringRef();
121 }
122
123 StringRef Attribute::getValueAsString() const {
124   assert(isStringAttribute() &&
125          "Invalid attribute type to get the value as a string!");
126   return pImpl ? pImpl->getValueAsString() : StringRef();
127 }
128
129 bool Attribute::hasAttribute(AttrKind Val) const {
130   return (pImpl && pImpl->hasAttribute(Val)) || (!pImpl && Val == None);
131 }
132
133 /// This returns the alignment field of an attribute as a byte alignment value.
134 unsigned Attribute::getAlignment() const {
135   assert(hasAttribute(Attribute::Alignment) &&
136          "Trying to get alignment from non-alignment attribute!");
137   return pImpl->getValueAsInt();
138 }
139
140 /// This returns the stack alignment field of an attribute as a byte alignment
141 /// value.
142 unsigned Attribute::getStackAlignment() const {
143   assert(hasAttribute(Attribute::StackAlignment) &&
144          "Trying to get alignment from non-alignment attribute!");
145   return pImpl->getValueAsInt();
146 }
147
148 std::string Attribute::getAsString() const {
149   if (!pImpl) return "";
150
151   if (hasAttribute(Attribute::AddressSafety))
152     return "address_safety";
153   if (hasAttribute(Attribute::AlwaysInline))
154     return "alwaysinline";
155   if (hasAttribute(Attribute::ByVal))
156     return "byval";
157   if (hasAttribute(Attribute::InlineHint))
158     return "inlinehint";
159   if (hasAttribute(Attribute::InReg))
160     return "inreg";
161   if (hasAttribute(Attribute::MinSize))
162     return "minsize";
163   if (hasAttribute(Attribute::Naked))
164     return "naked";
165   if (hasAttribute(Attribute::Nest))
166     return "nest";
167   if (hasAttribute(Attribute::NoAlias))
168     return "noalias";
169   if (hasAttribute(Attribute::NoCapture))
170     return "nocapture";
171   if (hasAttribute(Attribute::NoDuplicate))
172     return "noduplicate";
173   if (hasAttribute(Attribute::NoImplicitFloat))
174     return "noimplicitfloat";
175   if (hasAttribute(Attribute::NoInline))
176     return "noinline";
177   if (hasAttribute(Attribute::NonLazyBind))
178     return "nonlazybind";
179   if (hasAttribute(Attribute::NoRedZone))
180     return "noredzone";
181   if (hasAttribute(Attribute::NoReturn))
182     return "noreturn";
183   if (hasAttribute(Attribute::NoUnwind))
184     return "nounwind";
185   if (hasAttribute(Attribute::OptimizeForSize))
186     return "optsize";
187   if (hasAttribute(Attribute::ReadNone))
188     return "readnone";
189   if (hasAttribute(Attribute::ReadOnly))
190     return "readonly";
191   if (hasAttribute(Attribute::ReturnsTwice))
192     return "returns_twice";
193   if (hasAttribute(Attribute::SExt))
194     return "signext";
195   if (hasAttribute(Attribute::StackProtect))
196     return "ssp";
197   if (hasAttribute(Attribute::StackProtectReq))
198     return "sspreq";
199   if (hasAttribute(Attribute::StackProtectStrong))
200     return "sspstrong";
201   if (hasAttribute(Attribute::StructRet))
202     return "sret";
203   if (hasAttribute(Attribute::UWTable))
204     return "uwtable";
205   if (hasAttribute(Attribute::ZExt))
206     return "zeroext";
207
208   // FIXME: These should be output like this:
209   //
210   //   align=4
211   //   alignstack=8
212   //
213   if (hasAttribute(Attribute::Alignment)) {
214     std::string Result;
215     Result += "align ";
216     Result += utostr(getValueAsInt());
217     return Result;
218   }
219   if (hasAttribute(Attribute::StackAlignment)) {
220     std::string Result;
221     Result += "alignstack(";
222     Result += utostr(getValueAsInt());
223     Result += ")";
224     return Result;
225   }
226
227   // Convert target-dependent attributes to strings of the form:
228   //
229   //   "kind"
230   //   "kind" = "value"
231   //   "kind" = ( "value1" "value2" "value3" )
232   //
233   if (isStringAttribute()) {
234     std::string Result;
235     Result += '\"' + getKindAsString().str() + '"';
236
237     StringRef Val = pImpl->getValueAsString();
238     if (Val.empty()) return Result;
239
240     Result += " = ";
241     Result += '\"' + Val.str() + '"';
242     return Result;
243   }
244
245   llvm_unreachable("Unknown attribute");
246 }
247
248 bool Attribute::operator<(Attribute A) const {
249   if (!pImpl && !A.pImpl) return false;
250   if (!pImpl) return true;
251   if (!A.pImpl) return false;
252   return *pImpl < *A.pImpl;
253 }
254
255 //===----------------------------------------------------------------------===//
256 // AttributeImpl Definition
257 //===----------------------------------------------------------------------===//
258
259 AttributeImpl::AttributeImpl(LLVMContext &C, Attribute::AttrKind Kind)
260   : Context(C), Entry(new EnumAttributeEntry(Kind)) {}
261
262 AttributeImpl::AttributeImpl(LLVMContext &C, Attribute::AttrKind Kind,
263                              unsigned Align)
264   : Context(C) {
265   assert((Kind == Attribute::Alignment || Kind == Attribute::StackAlignment) &&
266          "Wrong kind for alignment attribute!");
267   Entry = new AlignAttributeEntry(Kind, Align);
268 }
269
270 AttributeImpl::AttributeImpl(LLVMContext &C, StringRef Kind, StringRef Val)
271   : Context(C), Entry(new StringAttributeEntry(Kind, Val)) {}
272
273 AttributeImpl::~AttributeImpl() {
274   delete Entry;
275 }
276
277 bool AttributeImpl::isEnumAttribute() const {
278   return isa<EnumAttributeEntry>(Entry);
279 }
280
281 bool AttributeImpl::isAlignAttribute() const {
282   return isa<AlignAttributeEntry>(Entry);
283 }
284
285 bool AttributeImpl::isStringAttribute() const {
286   return isa<StringAttributeEntry>(Entry);
287 }
288
289 bool AttributeImpl::hasAttribute(Attribute::AttrKind A) const {
290   if (isStringAttribute()) return false;
291   return getKindAsEnum() == A;
292 }
293
294 bool AttributeImpl::hasAttribute(StringRef Kind) const {
295   if (!isStringAttribute()) return false;
296   return getKindAsString() == Kind;
297 }
298
299 Attribute::AttrKind AttributeImpl::getKindAsEnum() const {
300   if (EnumAttributeEntry *E = dyn_cast<EnumAttributeEntry>(Entry))
301     return E->getEnumKind();
302   return cast<AlignAttributeEntry>(Entry)->getEnumKind();
303 }
304
305 uint64_t AttributeImpl::getValueAsInt() const {
306   return cast<AlignAttributeEntry>(Entry)->getAlignment();
307 }
308
309 StringRef AttributeImpl::getKindAsString() const {
310   return cast<StringAttributeEntry>(Entry)->getStringKind();
311 }
312
313 StringRef AttributeImpl::getValueAsString() const {
314   return cast<StringAttributeEntry>(Entry)->getStringValue();
315 }
316
317 bool AttributeImpl::operator<(const AttributeImpl &AI) const {
318   // This sorts the attributes with Attribute::AttrKinds coming first (sorted
319   // relative to their enum value) and then strings.
320   if (isEnumAttribute())
321     if (AI.isAlignAttribute() || AI.isEnumAttribute())
322       return getKindAsEnum() < AI.getKindAsEnum();
323
324   if (isAlignAttribute()) {
325     if (!AI.isStringAttribute() && getKindAsEnum() < AI.getKindAsEnum())
326       return true;
327     if (AI.isAlignAttribute())
328       return getValueAsInt() < AI.getValueAsInt();
329   }
330
331   if (isStringAttribute()) {
332     if (!AI.isStringAttribute()) return false;
333     if (getKindAsString() < AI.getKindAsString()) return true;
334     if (getKindAsString() == AI.getKindAsString())
335       return getValueAsString() < AI.getValueAsString();
336   }
337
338   return false;
339 }
340
341 uint64_t AttributeImpl::getAttrMask(Attribute::AttrKind Val) {
342   // FIXME: Remove this.
343   switch (Val) {
344   case Attribute::EndAttrKinds:
345   case Attribute::AttrKindEmptyKey:
346   case Attribute::AttrKindTombstoneKey:
347     llvm_unreachable("Synthetic enumerators which should never get here");
348
349   case Attribute::None:            return 0;
350   case Attribute::ZExt:            return 1 << 0;
351   case Attribute::SExt:            return 1 << 1;
352   case Attribute::NoReturn:        return 1 << 2;
353   case Attribute::InReg:           return 1 << 3;
354   case Attribute::StructRet:       return 1 << 4;
355   case Attribute::NoUnwind:        return 1 << 5;
356   case Attribute::NoAlias:         return 1 << 6;
357   case Attribute::ByVal:           return 1 << 7;
358   case Attribute::Nest:            return 1 << 8;
359   case Attribute::ReadNone:        return 1 << 9;
360   case Attribute::ReadOnly:        return 1 << 10;
361   case Attribute::NoInline:        return 1 << 11;
362   case Attribute::AlwaysInline:    return 1 << 12;
363   case Attribute::OptimizeForSize: return 1 << 13;
364   case Attribute::StackProtect:    return 1 << 14;
365   case Attribute::StackProtectReq: return 1 << 15;
366   case Attribute::Alignment:       return 31 << 16;
367   case Attribute::NoCapture:       return 1 << 21;
368   case Attribute::NoRedZone:       return 1 << 22;
369   case Attribute::NoImplicitFloat: return 1 << 23;
370   case Attribute::Naked:           return 1 << 24;
371   case Attribute::InlineHint:      return 1 << 25;
372   case Attribute::StackAlignment:  return 7 << 26;
373   case Attribute::ReturnsTwice:    return 1 << 29;
374   case Attribute::UWTable:         return 1 << 30;
375   case Attribute::NonLazyBind:     return 1U << 31;
376   case Attribute::AddressSafety:   return 1ULL << 32;
377   case Attribute::MinSize:         return 1ULL << 33;
378   case Attribute::NoDuplicate:     return 1ULL << 34;
379   case Attribute::StackProtectStrong: return 1ULL << 35;
380   }
381   llvm_unreachable("Unsupported attribute type");
382 }
383
384 //===----------------------------------------------------------------------===//
385 // AttributeSetNode Definition
386 //===----------------------------------------------------------------------===//
387
388 AttributeSetNode *AttributeSetNode::get(LLVMContext &C,
389                                         ArrayRef<Attribute> Attrs) {
390   if (Attrs.empty())
391     return 0;
392
393   // Otherwise, build a key to look up the existing attributes.
394   LLVMContextImpl *pImpl = C.pImpl;
395   FoldingSetNodeID ID;
396
397   SmallVector<Attribute, 8> SortedAttrs(Attrs.begin(), Attrs.end());
398   std::sort(SortedAttrs.begin(), SortedAttrs.end());
399
400   for (SmallVectorImpl<Attribute>::iterator I = SortedAttrs.begin(),
401          E = SortedAttrs.end(); I != E; ++I)
402     I->Profile(ID);
403
404   void *InsertPoint;
405   AttributeSetNode *PA =
406     pImpl->AttrsSetNodes.FindNodeOrInsertPos(ID, InsertPoint);
407
408   // If we didn't find any existing attributes of the same shape then create a
409   // new one and insert it.
410   if (!PA) {
411     PA = new AttributeSetNode(SortedAttrs);
412     pImpl->AttrsSetNodes.InsertNode(PA, InsertPoint);
413   }
414
415   // Return the AttributesListNode that we found or created.
416   return PA;
417 }
418
419 bool AttributeSetNode::hasAttribute(Attribute::AttrKind Kind) const {
420   for (SmallVectorImpl<Attribute>::const_iterator I = AttrList.begin(),
421          E = AttrList.end(); I != E; ++I)
422     if (I->hasAttribute(Kind))
423       return true;
424   return false;
425 }
426
427 unsigned AttributeSetNode::getAlignment() const {
428   for (SmallVectorImpl<Attribute>::const_iterator I = AttrList.begin(),
429          E = AttrList.end(); I != E; ++I)
430     if (I->hasAttribute(Attribute::Alignment))
431       return I->getAlignment();
432   return 0;
433 }
434
435 unsigned AttributeSetNode::getStackAlignment() const {
436   for (SmallVectorImpl<Attribute>::const_iterator I = AttrList.begin(),
437          E = AttrList.end(); I != E; ++I)
438     if (I->hasAttribute(Attribute::StackAlignment))
439       return I->getStackAlignment();
440   return 0;
441 }
442
443 std::string AttributeSetNode::getAsString() const {
444   std::string Str = "";
445   for (SmallVectorImpl<Attribute>::const_iterator I = AttrList.begin(),
446          E = AttrList.end(); I != E; ) {
447     Str += I->getAsString();
448     if (++I != E) Str += " ";
449   }
450   return Str;
451 }
452
453 //===----------------------------------------------------------------------===//
454 // AttributeSetImpl Definition
455 //===----------------------------------------------------------------------===//
456
457 uint64_t AttributeSetImpl::Raw(uint64_t Index) const {
458   for (unsigned I = 0, E = getNumAttributes(); I != E; ++I) {
459     if (getSlotIndex(I) != Index) continue;
460     const AttributeSetNode *ASN = AttrNodes[I].second;
461     uint64_t Mask = 0;
462
463     for (AttributeSetNode::const_iterator II = ASN->begin(),
464            IE = ASN->end(); II != IE; ++II) {
465       Attribute Attr = *II;
466       Attribute::AttrKind Kind = Attr.getKindAsEnum();
467
468       if (Kind == Attribute::Alignment)
469         Mask |= (Log2_32(ASN->getAlignment()) + 1) << 16;
470       else if (Kind == Attribute::StackAlignment)
471         Mask |= (Log2_32(ASN->getStackAlignment()) + 1) << 26;
472       else
473         Mask |= AttributeImpl::getAttrMask(Kind);
474     }
475
476     return Mask;
477   }
478
479   return 0;
480 }
481
482 //===----------------------------------------------------------------------===//
483 // AttributeSet Construction and Mutation Methods
484 //===----------------------------------------------------------------------===//
485
486 AttributeSet
487 AttributeSet::getImpl(LLVMContext &C,
488                       ArrayRef<std::pair<unsigned, AttributeSetNode*> > Attrs) {
489   LLVMContextImpl *pImpl = C.pImpl;
490   FoldingSetNodeID ID;
491   AttributeSetImpl::Profile(ID, Attrs);
492
493   void *InsertPoint;
494   AttributeSetImpl *PA = pImpl->AttrsLists.FindNodeOrInsertPos(ID, InsertPoint);
495
496   // If we didn't find any existing attributes of the same shape then
497   // create a new one and insert it.
498   if (!PA) {
499     PA = new AttributeSetImpl(C, Attrs);
500     pImpl->AttrsLists.InsertNode(PA, InsertPoint);
501   }
502
503   // Return the AttributesList that we found or created.
504   return AttributeSet(PA);
505 }
506
507 AttributeSet AttributeSet::get(LLVMContext &C,
508                                ArrayRef<std::pair<unsigned, Attribute> > Attrs){
509   // If there are no attributes then return a null AttributesList pointer.
510   if (Attrs.empty())
511     return AttributeSet();
512
513 #ifndef NDEBUG
514   for (unsigned i = 0, e = Attrs.size(); i != e; ++i) {
515     assert((!i || Attrs[i-1].first <= Attrs[i].first) &&
516            "Misordered Attributes list!");
517     assert(!Attrs[i].second.hasAttribute(Attribute::None) &&
518            "Pointless attribute!");
519   }
520 #endif
521
522   // Create a vector if (unsigned, AttributeSetNode*) pairs from the attributes
523   // list.
524   SmallVector<std::pair<unsigned, AttributeSetNode*>, 8> AttrPairVec;
525   for (ArrayRef<std::pair<unsigned, Attribute> >::iterator I = Attrs.begin(),
526          E = Attrs.end(); I != E; ) {
527     unsigned Index = I->first;
528     SmallVector<Attribute, 4> AttrVec;
529     while (I != E && I->first == Index) {
530       AttrVec.push_back(I->second);
531       ++I;
532     }
533
534     AttrPairVec.push_back(std::make_pair(Index,
535                                          AttributeSetNode::get(C, AttrVec)));
536   }
537
538   return getImpl(C, AttrPairVec);
539 }
540
541 AttributeSet AttributeSet::get(LLVMContext &C,
542                                ArrayRef<std::pair<unsigned,
543                                                   AttributeSetNode*> > Attrs) {
544   // If there are no attributes then return a null AttributesList pointer.
545   if (Attrs.empty())
546     return AttributeSet();
547
548   return getImpl(C, Attrs);
549 }
550
551 AttributeSet AttributeSet::get(LLVMContext &C, unsigned Idx, AttrBuilder &B) {
552   if (!B.hasAttributes())
553     return AttributeSet();
554
555   SmallVector<std::pair<unsigned, Attribute>, 8> Attrs;
556   for (AttrBuilder::iterator I = B.begin(), E = B.end(); I != E; ++I) {
557     Attribute::AttrKind Kind = *I;
558     if (Kind == Attribute::Alignment)
559       Attrs.push_back(std::make_pair(Idx, Attribute::
560                                      getWithAlignment(C, B.getAlignment())));
561     else if (Kind == Attribute::StackAlignment)
562       Attrs.push_back(std::make_pair(Idx, Attribute::
563                               getWithStackAlignment(C, B.getStackAlignment())));
564     else
565       Attrs.push_back(std::make_pair(Idx, Attribute::get(C, Kind)));
566   }
567
568   return get(C, Attrs);
569 }
570
571 AttributeSet AttributeSet::get(LLVMContext &C, unsigned Idx,
572                                ArrayRef<Attribute::AttrKind> Kind) {
573   SmallVector<std::pair<unsigned, Attribute>, 8> Attrs;
574   for (ArrayRef<Attribute::AttrKind>::iterator I = Kind.begin(),
575          E = Kind.end(); I != E; ++I)
576     Attrs.push_back(std::make_pair(Idx, Attribute::get(C, *I)));
577   return get(C, Attrs);
578 }
579
580 AttributeSet AttributeSet::get(LLVMContext &C, ArrayRef<AttributeSet> Attrs) {
581   if (Attrs.empty()) return AttributeSet();
582
583   SmallVector<std::pair<unsigned, AttributeSetNode*>, 8> AttrNodeVec;
584   for (unsigned I = 0, E = Attrs.size(); I != E; ++I) {
585     AttributeSet AS = Attrs[I];
586     if (!AS.pImpl) continue;
587     AttrNodeVec.append(AS.pImpl->AttrNodes.begin(), AS.pImpl->AttrNodes.end());
588   }
589
590   return getImpl(C, AttrNodeVec);
591 }
592
593 AttributeSet AttributeSet::addAttribute(LLVMContext &C, unsigned Idx,
594                                         Attribute::AttrKind Attr) const {
595   return addAttributes(C, Idx, AttributeSet::get(C, Idx, Attr));
596 }
597
598 AttributeSet AttributeSet::addAttributes(LLVMContext &C, unsigned Idx,
599                                          AttributeSet Attrs) const {
600   if (!pImpl) return Attrs;
601   if (!Attrs.pImpl) return *this;
602
603 #ifndef NDEBUG
604   // FIXME it is not obvious how this should work for alignment. For now, say
605   // we can't change a known alignment.
606   unsigned OldAlign = getParamAlignment(Idx);
607   unsigned NewAlign = Attrs.getParamAlignment(Idx);
608   assert((!OldAlign || !NewAlign || OldAlign == NewAlign) &&
609          "Attempt to change alignment!");
610 #endif
611
612   // Add the attribute slots before the one we're trying to add.
613   SmallVector<AttributeSet, 4> AttrSet;
614   uint64_t NumAttrs = pImpl->getNumAttributes();
615   AttributeSet AS;
616   uint64_t LastIndex = 0;
617   for (unsigned I = 0, E = NumAttrs; I != E; ++I) {
618     if (getSlotIndex(I) >= Idx) {
619       if (getSlotIndex(I) == Idx) AS = getSlotAttributes(LastIndex++);
620       break;
621     }
622     LastIndex = I + 1;
623     AttrSet.push_back(getSlotAttributes(I));
624   }
625
626   // Now add the attribute into the correct slot. There may already be an
627   // AttributeSet there.
628   AttrBuilder B(AS, Idx);
629
630   for (unsigned I = 0, E = Attrs.pImpl->getNumAttributes(); I != E; ++I)
631     if (Attrs.getSlotIndex(I) == Idx) {
632       for (AttributeSetImpl::const_iterator II = Attrs.pImpl->begin(I),
633              IE = Attrs.pImpl->end(I); II != IE; ++II)
634         B.addAttribute(*II);
635       break;
636     }
637
638   AttrSet.push_back(AttributeSet::get(C, Idx, B));
639
640   // Add the remaining attribute slots.
641   for (unsigned I = LastIndex, E = NumAttrs; I < E; ++I)
642     AttrSet.push_back(getSlotAttributes(I));
643
644   return get(C, AttrSet);
645 }
646
647 AttributeSet AttributeSet::removeAttribute(LLVMContext &C, unsigned Idx,
648                                            Attribute::AttrKind Attr) const {
649   return removeAttributes(C, Idx, AttributeSet::get(C, Idx, Attr));
650 }
651
652 AttributeSet AttributeSet::removeAttributes(LLVMContext &C, unsigned Idx,
653                                             AttributeSet Attrs) const {
654   if (!pImpl) return AttributeSet();
655   if (!Attrs.pImpl) return *this;
656
657 #ifndef NDEBUG
658   // FIXME it is not obvious how this should work for alignment.
659   // For now, say we can't pass in alignment, which no current use does.
660   assert(!Attrs.hasAttribute(Idx, Attribute::Alignment) &&
661          "Attempt to change alignment!");
662 #endif
663
664   // Add the attribute slots before the one we're trying to add.
665   SmallVector<AttributeSet, 4> AttrSet;
666   uint64_t NumAttrs = pImpl->getNumAttributes();
667   AttributeSet AS;
668   uint64_t LastIndex = 0;
669   for (unsigned I = 0, E = NumAttrs; I != E; ++I) {
670     if (getSlotIndex(I) >= Idx) {
671       if (getSlotIndex(I) == Idx) AS = getSlotAttributes(LastIndex++);
672       break;
673     }
674     LastIndex = I + 1;
675     AttrSet.push_back(getSlotAttributes(I));
676   }
677
678   // Now remove the attribute from the correct slot. There may already be an
679   // AttributeSet there.
680   AttrBuilder B(AS, Idx);
681
682   for (unsigned I = 0, E = Attrs.pImpl->getNumAttributes(); I != E; ++I)
683     if (Attrs.getSlotIndex(I) == Idx) {
684       B.removeAttributes(Attrs.pImpl->getSlotAttributes(I), Idx);
685       break;
686     }
687
688   AttrSet.push_back(AttributeSet::get(C, Idx, B));
689
690   // Add the remaining attribute slots.
691   for (unsigned I = LastIndex, E = NumAttrs; I < E; ++I)
692     AttrSet.push_back(getSlotAttributes(I));
693
694   return get(C, AttrSet);
695 }
696
697 //===----------------------------------------------------------------------===//
698 // AttributeSet Accessor Methods
699 //===----------------------------------------------------------------------===//
700
701 AttributeSet AttributeSet::getParamAttributes(unsigned Idx) const {
702   return pImpl && hasAttributes(Idx) ?
703     AttributeSet::get(pImpl->getContext(),
704                       ArrayRef<std::pair<unsigned, AttributeSetNode*> >(
705                         std::make_pair(Idx, getAttributes(Idx)))) :
706     AttributeSet();
707 }
708
709 AttributeSet AttributeSet::getRetAttributes() const {
710   return pImpl && hasAttributes(ReturnIndex) ?
711     AttributeSet::get(pImpl->getContext(),
712                       ArrayRef<std::pair<unsigned, AttributeSetNode*> >(
713                         std::make_pair(ReturnIndex,
714                                        getAttributes(ReturnIndex)))) :
715     AttributeSet();
716 }
717
718 AttributeSet AttributeSet::getFnAttributes() const {
719   return pImpl && hasAttributes(FunctionIndex) ?
720     AttributeSet::get(pImpl->getContext(),
721                       ArrayRef<std::pair<unsigned, AttributeSetNode*> >(
722                         std::make_pair(FunctionIndex,
723                                        getAttributes(FunctionIndex)))) :
724     AttributeSet();
725 }
726
727 bool AttributeSet::hasAttribute(unsigned Index, Attribute::AttrKind Kind) const{
728   AttributeSetNode *ASN = getAttributes(Index);
729   return ASN ? ASN->hasAttribute(Kind) : false;
730 }
731
732 bool AttributeSet::hasAttributes(unsigned Index) const {
733   AttributeSetNode *ASN = getAttributes(Index);
734   return ASN ? ASN->hasAttributes() : false;
735 }
736
737 /// \brief Return true if the specified attribute is set for at least one
738 /// parameter or for the return value.
739 bool AttributeSet::hasAttrSomewhere(Attribute::AttrKind Attr) const {
740   if (pImpl == 0) return false;
741
742   for (unsigned I = 0, E = pImpl->getNumAttributes(); I != E; ++I)
743     for (AttributeSetImpl::const_iterator II = pImpl->begin(I),
744            IE = pImpl->end(I); II != IE; ++II)
745       if (II->hasAttribute(Attr))
746         return true;
747
748   return false;
749 }
750
751 unsigned AttributeSet::getParamAlignment(unsigned Index) const {
752   AttributeSetNode *ASN = getAttributes(Index);
753   return ASN ? ASN->getAlignment() : 0;
754 }
755
756 unsigned AttributeSet::getStackAlignment(unsigned Index) const {
757   AttributeSetNode *ASN = getAttributes(Index);
758   return ASN ? ASN->getStackAlignment() : 0;
759 }
760
761 std::string AttributeSet::getAsString(unsigned Index) const {
762   AttributeSetNode *ASN = getAttributes(Index);
763   return ASN ? ASN->getAsString() : std::string("");
764 }
765
766 /// \brief The attributes for the specified index are returned.
767 AttributeSetNode *AttributeSet::getAttributes(unsigned Idx) const {
768   if (!pImpl) return 0;
769
770   // Loop through to find the attribute node we want.
771   for (unsigned I = 0, E = pImpl->getNumAttributes(); I != E; ++I)
772     if (pImpl->getSlotIndex(I) == Idx)
773       return pImpl->getSlotNode(I);
774
775   return 0;
776 }
777
778 AttributeSet::iterator AttributeSet::begin(unsigned Idx) const {
779   if (!pImpl)
780     return ArrayRef<Attribute>().begin();
781   return pImpl->begin(Idx);
782 }
783
784 AttributeSet::iterator AttributeSet::end(unsigned Idx) const {
785   if (!pImpl)
786     return ArrayRef<Attribute>().end();
787   return pImpl->end(Idx);
788 }
789
790 //===----------------------------------------------------------------------===//
791 // AttributeSet Introspection Methods
792 //===----------------------------------------------------------------------===//
793
794 /// \brief Return the number of slots used in this attribute list.  This is the
795 /// number of arguments that have an attribute set on them (including the
796 /// function itself).
797 unsigned AttributeSet::getNumSlots() const {
798   return pImpl ? pImpl->getNumAttributes() : 0;
799 }
800
801 uint64_t AttributeSet::getSlotIndex(unsigned Slot) const {
802   assert(pImpl && Slot < pImpl->getNumAttributes() &&
803          "Slot # out of range!");
804   return pImpl->getSlotIndex(Slot);
805 }
806
807 AttributeSet AttributeSet::getSlotAttributes(unsigned Slot) const {
808   assert(pImpl && Slot < pImpl->getNumAttributes() &&
809          "Slot # out of range!");
810   return pImpl->getSlotAttributes(Slot);
811 }
812
813 uint64_t AttributeSet::Raw(unsigned Index) const {
814   // FIXME: Remove this.
815   return pImpl ? pImpl->Raw(Index) : 0;
816 }
817
818 void AttributeSet::dump() const {
819   dbgs() << "PAL[\n";
820
821   for (unsigned i = 0, e = getNumSlots(); i < e; ++i) {
822     uint64_t Index = getSlotIndex(i);
823     dbgs() << "  { ";
824     if (Index == ~0U)
825       dbgs() << "~0U";
826     else
827       dbgs() << Index;
828     dbgs() << " => " << getAsString(Index) << " }\n";
829   }
830
831   dbgs() << "]\n";
832 }
833
834 //===----------------------------------------------------------------------===//
835 // AttrBuilder Method Implementations
836 //===----------------------------------------------------------------------===//
837
838 AttrBuilder::AttrBuilder(AttributeSet AS, unsigned Idx)
839   : Alignment(0), StackAlignment(0) {
840   AttributeSetImpl *pImpl = AS.pImpl;
841   if (!pImpl) return;
842
843   for (unsigned I = 0, E = pImpl->getNumAttributes(); I != E; ++I) {
844     if (pImpl->getSlotIndex(I) != Idx) continue;
845
846     for (AttributeSetImpl::const_iterator II = pImpl->begin(I),
847            IE = pImpl->end(I); II != IE; ++II)
848       addAttribute(*II);
849
850     break;
851   }
852 }
853
854 void AttrBuilder::clear() {
855   Attrs.clear();
856   Alignment = StackAlignment = 0;
857 }
858
859 AttrBuilder &AttrBuilder::addAttribute(Attribute::AttrKind Val) {
860   assert(Val != Attribute::Alignment && Val != Attribute::StackAlignment &&
861          "Adding alignment attribute without adding alignment value!");
862   Attrs.insert(Val);
863   return *this;
864 }
865
866 AttrBuilder &AttrBuilder::addAttribute(Attribute Attr) {
867   // FIXME: Handle string attributes.
868   Attribute::AttrKind Kind = Attr.getKindAsEnum();
869   Attrs.insert(Kind);
870
871   if (Kind == Attribute::Alignment)
872     Alignment = Attr.getAlignment();
873   else if (Kind == Attribute::StackAlignment)
874     StackAlignment = Attr.getStackAlignment();
875   return *this;
876 }
877
878 AttrBuilder &AttrBuilder::addAttribute(StringRef A, StringRef V) {
879   TargetDepAttrs[A] = V;
880   return *this;
881 }
882
883 AttrBuilder &AttrBuilder::removeAttribute(Attribute::AttrKind Val) {
884   Attrs.erase(Val);
885
886   if (Val == Attribute::Alignment)
887     Alignment = 0;
888   else if (Val == Attribute::StackAlignment)
889     StackAlignment = 0;
890
891   return *this;
892 }
893
894 AttrBuilder &AttrBuilder::removeAttributes(AttributeSet A, uint64_t Index) {
895   unsigned Idx = ~0U;
896   for (unsigned I = 0, E = A.getNumSlots(); I != E; ++I)
897     if (A.getSlotIndex(I) == Index) {
898       Idx = I;
899       break;
900     }
901
902   assert(Idx != ~0U && "Couldn't find index in AttributeSet!");
903
904   for (AttributeSet::iterator I = A.begin(Idx), E = A.end(Idx); I != E; ++I) {
905     // FIXME: Support string attributes.
906     Attribute::AttrKind Kind = I->getKindAsEnum();
907     Attrs.erase(Kind);
908
909     if (Kind == Attribute::Alignment)
910       Alignment = 0;
911     else if (Kind == Attribute::StackAlignment)
912       StackAlignment = 0;
913   }
914
915   return *this;
916 }
917
918 AttrBuilder &AttrBuilder::removeAttribute(StringRef A) {
919   std::map<std::string, std::string>::iterator I = TargetDepAttrs.find(A);
920   if (I != TargetDepAttrs.end())
921     TargetDepAttrs.erase(I);
922   return *this;
923 }
924
925 AttrBuilder &AttrBuilder::addAlignmentAttr(unsigned Align) {
926   if (Align == 0) return *this;
927
928   assert(isPowerOf2_32(Align) && "Alignment must be a power of two.");
929   assert(Align <= 0x40000000 && "Alignment too large.");
930
931   Attrs.insert(Attribute::Alignment);
932   Alignment = Align;
933   return *this;
934 }
935
936 AttrBuilder &AttrBuilder::addStackAlignmentAttr(unsigned Align) {
937   // Default alignment, allow the target to define how to align it.
938   if (Align == 0) return *this;
939
940   assert(isPowerOf2_32(Align) && "Alignment must be a power of two.");
941   assert(Align <= 0x100 && "Alignment too large.");
942
943   Attrs.insert(Attribute::StackAlignment);
944   StackAlignment = Align;
945   return *this;
946 }
947
948 bool AttrBuilder::contains(Attribute::AttrKind A) const {
949   return Attrs.count(A);
950 }
951
952 bool AttrBuilder::hasAttributes() const {
953   return !Attrs.empty();
954 }
955
956 bool AttrBuilder::hasAttributes(AttributeSet A, uint64_t Index) const {
957   unsigned Idx = ~0U;
958   for (unsigned I = 0, E = A.getNumSlots(); I != E; ++I)
959     if (A.getSlotIndex(I) == Index) {
960       Idx = I;
961       break;
962     }
963
964   assert(Idx != ~0U && "Couldn't find the index!");
965
966   for (AttributeSet::iterator I = A.begin(Idx), E = A.end(Idx);
967        I != E; ++I)
968     // FIXME: Support string attributes.
969     if (Attrs.count(I->getKindAsEnum()))
970       return true;
971
972   return false;
973 }
974
975 bool AttrBuilder::hasAlignmentAttr() const {
976   return Alignment != 0;
977 }
978
979 bool AttrBuilder::operator==(const AttrBuilder &B) {
980   SmallVector<Attribute::AttrKind, 8> This(Attrs.begin(), Attrs.end());
981   SmallVector<Attribute::AttrKind, 8> That(B.Attrs.begin(), B.Attrs.end());
982   return This == That;
983 }
984
985 AttrBuilder &AttrBuilder::addRawValue(uint64_t Val) {
986   // FIXME: Remove this in 4.0.
987   if (!Val) return *this;
988
989   for (Attribute::AttrKind I = Attribute::None; I != Attribute::EndAttrKinds;
990        I = Attribute::AttrKind(I + 1)) {
991     if (uint64_t A = (Val & AttributeImpl::getAttrMask(I))) {
992       Attrs.insert(I);
993  
994       if (I == Attribute::Alignment)
995         Alignment = 1ULL << ((A >> 16) - 1);
996       else if (I == Attribute::StackAlignment)
997         StackAlignment = 1ULL << ((A >> 26)-1);
998     }
999   }
1000  
1001   return *this;
1002 }
1003
1004 //===----------------------------------------------------------------------===//
1005 // AttributeFuncs Function Defintions
1006 //===----------------------------------------------------------------------===//
1007
1008 /// \brief Which attributes cannot be applied to a type.
1009 AttributeSet AttributeFuncs::typeIncompatible(Type *Ty, uint64_t Index) {
1010   AttrBuilder Incompatible;
1011
1012   if (!Ty->isIntegerTy())
1013     // Attribute that only apply to integers.
1014     Incompatible.addAttribute(Attribute::SExt)
1015       .addAttribute(Attribute::ZExt);
1016
1017   if (!Ty->isPointerTy())
1018     // Attribute that only apply to pointers.
1019     Incompatible.addAttribute(Attribute::ByVal)
1020       .addAttribute(Attribute::Nest)
1021       .addAttribute(Attribute::NoAlias)
1022       .addAttribute(Attribute::NoCapture)
1023       .addAttribute(Attribute::StructRet);
1024
1025   return AttributeSet::get(Ty->getContext(), Index, Incompatible);
1026 }