[C++11] Replace LLVM atomics with std::atomic.
[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/Debug.h"
22 #include "llvm/Support/ManagedStatic.h"
23 #include "llvm/Support/Mutex.h"
24 #include "llvm/Support/raw_ostream.h"
25 #include <algorithm>
26 using namespace llvm;
27
28 //===----------------------------------------------------------------------===//
29 // Attribute Construction Methods
30 //===----------------------------------------------------------------------===//
31
32 Attribute Attribute::get(LLVMContext &Context, Attribute::AttrKind Kind,
33                          uint64_t Val) {
34   LLVMContextImpl *pImpl = Context.pImpl;
35   FoldingSetNodeID ID;
36   ID.AddInteger(Kind);
37   if (Val) ID.AddInteger(Val);
38
39   void *InsertPoint;
40   AttributeImpl *PA = pImpl->AttrsSet.FindNodeOrInsertPos(ID, InsertPoint);
41
42   if (!PA) {
43     // If we didn't find any existing attributes of the same shape then create a
44     // new one and insert it.
45     if (!Val)
46       PA = new EnumAttributeImpl(Kind);
47     else
48       PA = new AlignAttributeImpl(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 StringAttributeImpl(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   if (!pImpl) return None;
107   assert((isEnumAttribute() || isAlignAttribute()) &&
108          "Invalid attribute type to get the kind as an enum!");
109   return pImpl ? pImpl->getKindAsEnum() : None;
110 }
111
112 uint64_t Attribute::getValueAsInt() const {
113   if (!pImpl) return 0;
114   assert(isAlignAttribute() &&
115          "Expected the attribute to be an alignment attribute!");
116   return pImpl ? pImpl->getValueAsInt() : 0;
117 }
118
119 StringRef Attribute::getKindAsString() const {
120   if (!pImpl) return StringRef();
121   assert(isStringAttribute() &&
122          "Invalid attribute type to get the kind as a string!");
123   return pImpl ? pImpl->getKindAsString() : StringRef();
124 }
125
126 StringRef Attribute::getValueAsString() const {
127   if (!pImpl) return StringRef();
128   assert(isStringAttribute() &&
129          "Invalid attribute type to get the value as a string!");
130   return pImpl ? pImpl->getValueAsString() : StringRef();
131 }
132
133 bool Attribute::hasAttribute(AttrKind Kind) const {
134   return (pImpl && pImpl->hasAttribute(Kind)) || (!pImpl && Kind == None);
135 }
136
137 bool Attribute::hasAttribute(StringRef Kind) const {
138   if (!isStringAttribute()) return false;
139   return pImpl && pImpl->hasAttribute(Kind);
140 }
141
142 /// This returns the alignment field of an attribute as a byte alignment value.
143 unsigned Attribute::getAlignment() const {
144   assert(hasAttribute(Attribute::Alignment) &&
145          "Trying to get alignment from non-alignment attribute!");
146   return pImpl->getValueAsInt();
147 }
148
149 /// This returns the stack alignment field of an attribute as a byte alignment
150 /// value.
151 unsigned Attribute::getStackAlignment() const {
152   assert(hasAttribute(Attribute::StackAlignment) &&
153          "Trying to get alignment from non-alignment attribute!");
154   return pImpl->getValueAsInt();
155 }
156
157 std::string Attribute::getAsString(bool InAttrGrp) const {
158   if (!pImpl) return "";
159
160   if (hasAttribute(Attribute::SanitizeAddress))
161     return "sanitize_address";
162   if (hasAttribute(Attribute::AlwaysInline))
163     return "alwaysinline";
164   if (hasAttribute(Attribute::Builtin))
165     return "builtin";
166   if (hasAttribute(Attribute::ByVal))
167     return "byval";
168   if (hasAttribute(Attribute::InAlloca))
169     return "inalloca";
170   if (hasAttribute(Attribute::InlineHint))
171     return "inlinehint";
172   if (hasAttribute(Attribute::InReg))
173     return "inreg";
174   if (hasAttribute(Attribute::MinSize))
175     return "minsize";
176   if (hasAttribute(Attribute::Naked))
177     return "naked";
178   if (hasAttribute(Attribute::Nest))
179     return "nest";
180   if (hasAttribute(Attribute::NoAlias))
181     return "noalias";
182   if (hasAttribute(Attribute::NoBuiltin))
183     return "nobuiltin";
184   if (hasAttribute(Attribute::NoCapture))
185     return "nocapture";
186   if (hasAttribute(Attribute::NoDuplicate))
187     return "noduplicate";
188   if (hasAttribute(Attribute::NoImplicitFloat))
189     return "noimplicitfloat";
190   if (hasAttribute(Attribute::NoInline))
191     return "noinline";
192   if (hasAttribute(Attribute::NonLazyBind))
193     return "nonlazybind";
194   if (hasAttribute(Attribute::NoRedZone))
195     return "noredzone";
196   if (hasAttribute(Attribute::NoReturn))
197     return "noreturn";
198   if (hasAttribute(Attribute::NoUnwind))
199     return "nounwind";
200   if (hasAttribute(Attribute::OptimizeNone))
201     return "optnone";
202   if (hasAttribute(Attribute::OptimizeForSize))
203     return "optsize";
204   if (hasAttribute(Attribute::ReadNone))
205     return "readnone";
206   if (hasAttribute(Attribute::ReadOnly))
207     return "readonly";
208   if (hasAttribute(Attribute::Returned))
209     return "returned";
210   if (hasAttribute(Attribute::ReturnsTwice))
211     return "returns_twice";
212   if (hasAttribute(Attribute::SExt))
213     return "signext";
214   if (hasAttribute(Attribute::StackProtect))
215     return "ssp";
216   if (hasAttribute(Attribute::StackProtectReq))
217     return "sspreq";
218   if (hasAttribute(Attribute::StackProtectStrong))
219     return "sspstrong";
220   if (hasAttribute(Attribute::StructRet))
221     return "sret";
222   if (hasAttribute(Attribute::SanitizeThread))
223     return "sanitize_thread";
224   if (hasAttribute(Attribute::SanitizeMemory))
225     return "sanitize_memory";
226   if (hasAttribute(Attribute::UWTable))
227     return "uwtable";
228   if (hasAttribute(Attribute::ZExt))
229     return "zeroext";
230   if (hasAttribute(Attribute::Cold))
231     return "cold";
232
233   // FIXME: These should be output like this:
234   //
235   //   align=4
236   //   alignstack=8
237   //
238   if (hasAttribute(Attribute::Alignment)) {
239     std::string Result;
240     Result += "align";
241     Result += (InAttrGrp) ? "=" : " ";
242     Result += utostr(getValueAsInt());
243     return Result;
244   }
245
246   if (hasAttribute(Attribute::StackAlignment)) {
247     std::string Result;
248     Result += "alignstack";
249     if (InAttrGrp) {
250       Result += "=";
251       Result += utostr(getValueAsInt());
252     } else {
253       Result += "(";
254       Result += utostr(getValueAsInt());
255       Result += ")";
256     }
257     return Result;
258   }
259
260   // Convert target-dependent attributes to strings of the form:
261   //
262   //   "kind"
263   //   "kind" = "value"
264   //
265   if (isStringAttribute()) {
266     std::string Result;
267     Result += '\"' + getKindAsString().str() + '"';
268
269     StringRef Val = pImpl->getValueAsString();
270     if (Val.empty()) return Result;
271
272     Result += "=\"" + Val.str() + '"';
273     return Result;
274   }
275
276   llvm_unreachable("Unknown attribute");
277 }
278
279 bool Attribute::operator<(Attribute A) const {
280   if (!pImpl && !A.pImpl) return false;
281   if (!pImpl) return true;
282   if (!A.pImpl) return false;
283   return *pImpl < *A.pImpl;
284 }
285
286 //===----------------------------------------------------------------------===//
287 // AttributeImpl Definition
288 //===----------------------------------------------------------------------===//
289
290 // Pin the vtabels to this file.
291 AttributeImpl::~AttributeImpl() {}
292 void EnumAttributeImpl::anchor() {}
293 void AlignAttributeImpl::anchor() {}
294 void StringAttributeImpl::anchor() {}
295
296 bool AttributeImpl::hasAttribute(Attribute::AttrKind A) const {
297   if (isStringAttribute()) return false;
298   return getKindAsEnum() == A;
299 }
300
301 bool AttributeImpl::hasAttribute(StringRef Kind) const {
302   if (!isStringAttribute()) return false;
303   return getKindAsString() == Kind;
304 }
305
306 Attribute::AttrKind AttributeImpl::getKindAsEnum() const {
307   assert(isEnumAttribute() || isAlignAttribute());
308   return static_cast<const EnumAttributeImpl *>(this)->getEnumKind();
309 }
310
311 uint64_t AttributeImpl::getValueAsInt() const {
312   assert(isAlignAttribute());
313   return static_cast<const AlignAttributeImpl *>(this)->getAlignment();
314 }
315
316 StringRef AttributeImpl::getKindAsString() const {
317   assert(isStringAttribute());
318   return static_cast<const StringAttributeImpl *>(this)->getStringKind();
319 }
320
321 StringRef AttributeImpl::getValueAsString() const {
322   assert(isStringAttribute());
323   return static_cast<const StringAttributeImpl *>(this)->getStringValue();
324 }
325
326 bool AttributeImpl::operator<(const AttributeImpl &AI) const {
327   // This sorts the attributes with Attribute::AttrKinds coming first (sorted
328   // relative to their enum value) and then strings.
329   if (isEnumAttribute()) {
330     if (AI.isEnumAttribute()) return getKindAsEnum() < AI.getKindAsEnum();
331     if (AI.isAlignAttribute()) return true;
332     if (AI.isStringAttribute()) return true;
333   }
334
335   if (isAlignAttribute()) {
336     if (AI.isEnumAttribute()) return false;
337     if (AI.isAlignAttribute()) return getValueAsInt() < AI.getValueAsInt();
338     if (AI.isStringAttribute()) return true;
339   }
340
341   if (AI.isEnumAttribute()) return false;
342   if (AI.isAlignAttribute()) return false;
343   if (getKindAsString() == AI.getKindAsString())
344     return getValueAsString() < AI.getValueAsString();
345   return getKindAsString() < AI.getKindAsString();
346 }
347
348 uint64_t AttributeImpl::getAttrMask(Attribute::AttrKind Val) {
349   // FIXME: Remove this.
350   switch (Val) {
351   case Attribute::EndAttrKinds:
352     llvm_unreachable("Synthetic enumerators which should never get here");
353
354   case Attribute::None:            return 0;
355   case Attribute::ZExt:            return 1 << 0;
356   case Attribute::SExt:            return 1 << 1;
357   case Attribute::NoReturn:        return 1 << 2;
358   case Attribute::InReg:           return 1 << 3;
359   case Attribute::StructRet:       return 1 << 4;
360   case Attribute::NoUnwind:        return 1 << 5;
361   case Attribute::NoAlias:         return 1 << 6;
362   case Attribute::ByVal:           return 1 << 7;
363   case Attribute::Nest:            return 1 << 8;
364   case Attribute::ReadNone:        return 1 << 9;
365   case Attribute::ReadOnly:        return 1 << 10;
366   case Attribute::NoInline:        return 1 << 11;
367   case Attribute::AlwaysInline:    return 1 << 12;
368   case Attribute::OptimizeForSize: return 1 << 13;
369   case Attribute::StackProtect:    return 1 << 14;
370   case Attribute::StackProtectReq: return 1 << 15;
371   case Attribute::Alignment:       return 31 << 16;
372   case Attribute::NoCapture:       return 1 << 21;
373   case Attribute::NoRedZone:       return 1 << 22;
374   case Attribute::NoImplicitFloat: return 1 << 23;
375   case Attribute::Naked:           return 1 << 24;
376   case Attribute::InlineHint:      return 1 << 25;
377   case Attribute::StackAlignment:  return 7 << 26;
378   case Attribute::ReturnsTwice:    return 1 << 29;
379   case Attribute::UWTable:         return 1 << 30;
380   case Attribute::NonLazyBind:     return 1U << 31;
381   case Attribute::SanitizeAddress: return 1ULL << 32;
382   case Attribute::MinSize:         return 1ULL << 33;
383   case Attribute::NoDuplicate:     return 1ULL << 34;
384   case Attribute::StackProtectStrong: return 1ULL << 35;
385   case Attribute::SanitizeThread:  return 1ULL << 36;
386   case Attribute::SanitizeMemory:  return 1ULL << 37;
387   case Attribute::NoBuiltin:       return 1ULL << 38;
388   case Attribute::Returned:        return 1ULL << 39;
389   case Attribute::Cold:            return 1ULL << 40;
390   case Attribute::Builtin:         return 1ULL << 41;
391   case Attribute::OptimizeNone:    return 1ULL << 42;
392   case Attribute::InAlloca:        return 1ULL << 43;
393   }
394   llvm_unreachable("Unsupported attribute type");
395 }
396
397 //===----------------------------------------------------------------------===//
398 // AttributeSetNode Definition
399 //===----------------------------------------------------------------------===//
400
401 AttributeSetNode *AttributeSetNode::get(LLVMContext &C,
402                                         ArrayRef<Attribute> Attrs) {
403   if (Attrs.empty())
404     return 0;
405
406   // Otherwise, build a key to look up the existing attributes.
407   LLVMContextImpl *pImpl = C.pImpl;
408   FoldingSetNodeID ID;
409
410   SmallVector<Attribute, 8> SortedAttrs(Attrs.begin(), Attrs.end());
411   array_pod_sort(SortedAttrs.begin(), SortedAttrs.end());
412
413   for (SmallVectorImpl<Attribute>::iterator I = SortedAttrs.begin(),
414          E = SortedAttrs.end(); I != E; ++I)
415     I->Profile(ID);
416
417   void *InsertPoint;
418   AttributeSetNode *PA =
419     pImpl->AttrsSetNodes.FindNodeOrInsertPos(ID, InsertPoint);
420
421   // If we didn't find any existing attributes of the same shape then create a
422   // new one and insert it.
423   if (!PA) {
424     // Coallocate entries after the AttributeSetNode itself.
425     void *Mem = ::operator new(sizeof(AttributeSetNode) +
426                                sizeof(Attribute) * SortedAttrs.size());
427     PA = new (Mem) AttributeSetNode(SortedAttrs);
428     pImpl->AttrsSetNodes.InsertNode(PA, InsertPoint);
429   }
430
431   // Return the AttributesListNode that we found or created.
432   return PA;
433 }
434
435 bool AttributeSetNode::hasAttribute(Attribute::AttrKind Kind) const {
436   for (iterator I = begin(), E = end(); I != E; ++I)
437     if (I->hasAttribute(Kind))
438       return true;
439   return false;
440 }
441
442 bool AttributeSetNode::hasAttribute(StringRef Kind) const {
443   for (iterator I = begin(), E = end(); I != E; ++I)
444     if (I->hasAttribute(Kind))
445       return true;
446   return false;
447 }
448
449 Attribute AttributeSetNode::getAttribute(Attribute::AttrKind Kind) const {
450   for (iterator I = begin(), E = end(); I != E; ++I)
451     if (I->hasAttribute(Kind))
452       return *I;
453   return Attribute();
454 }
455
456 Attribute AttributeSetNode::getAttribute(StringRef Kind) const {
457   for (iterator I = begin(), E = end(); I != E; ++I)
458     if (I->hasAttribute(Kind))
459       return *I;
460   return Attribute();
461 }
462
463 unsigned AttributeSetNode::getAlignment() const {
464   for (iterator I = begin(), E = end(); I != E; ++I)
465     if (I->hasAttribute(Attribute::Alignment))
466       return I->getAlignment();
467   return 0;
468 }
469
470 unsigned AttributeSetNode::getStackAlignment() const {
471   for (iterator I = begin(), E = end(); I != E; ++I)
472     if (I->hasAttribute(Attribute::StackAlignment))
473       return I->getStackAlignment();
474   return 0;
475 }
476
477 std::string AttributeSetNode::getAsString(bool InAttrGrp) const {
478   std::string Str;
479   for (iterator I = begin(), E = end(); I != E; ++I) {
480     if (I != begin())
481       Str += ' ';
482     Str += I->getAsString(InAttrGrp);
483   }
484   return Str;
485 }
486
487 //===----------------------------------------------------------------------===//
488 // AttributeSetImpl Definition
489 //===----------------------------------------------------------------------===//
490
491 uint64_t AttributeSetImpl::Raw(unsigned Index) const {
492   for (unsigned I = 0, E = getNumAttributes(); I != E; ++I) {
493     if (getSlotIndex(I) != Index) continue;
494     const AttributeSetNode *ASN = getSlotNode(I);
495     uint64_t Mask = 0;
496
497     for (AttributeSetNode::iterator II = ASN->begin(),
498            IE = ASN->end(); II != IE; ++II) {
499       Attribute Attr = *II;
500
501       // This cannot handle string attributes.
502       if (Attr.isStringAttribute()) continue;
503
504       Attribute::AttrKind Kind = Attr.getKindAsEnum();
505
506       if (Kind == Attribute::Alignment)
507         Mask |= (Log2_32(ASN->getAlignment()) + 1) << 16;
508       else if (Kind == Attribute::StackAlignment)
509         Mask |= (Log2_32(ASN->getStackAlignment()) + 1) << 26;
510       else
511         Mask |= AttributeImpl::getAttrMask(Kind);
512     }
513
514     return Mask;
515   }
516
517   return 0;
518 }
519
520 void AttributeSetImpl::dump() const {
521   AttributeSet(const_cast<AttributeSetImpl *>(this)).dump();
522 }
523
524 //===----------------------------------------------------------------------===//
525 // AttributeSet Construction and Mutation Methods
526 //===----------------------------------------------------------------------===//
527
528 AttributeSet
529 AttributeSet::getImpl(LLVMContext &C,
530                       ArrayRef<std::pair<unsigned, AttributeSetNode*> > Attrs) {
531   LLVMContextImpl *pImpl = C.pImpl;
532   FoldingSetNodeID ID;
533   AttributeSetImpl::Profile(ID, Attrs);
534
535   void *InsertPoint;
536   AttributeSetImpl *PA = pImpl->AttrsLists.FindNodeOrInsertPos(ID, InsertPoint);
537
538   // If we didn't find any existing attributes of the same shape then
539   // create a new one and insert it.
540   if (!PA) {
541     // Coallocate entries after the AttributeSetImpl itself.
542     void *Mem = ::operator new(sizeof(AttributeSetImpl) +
543                                sizeof(std::pair<unsigned, AttributeSetNode *>) *
544                                    Attrs.size());
545     PA = new (Mem) AttributeSetImpl(C, Attrs);
546     pImpl->AttrsLists.InsertNode(PA, InsertPoint);
547   }
548
549   // Return the AttributesList that we found or created.
550   return AttributeSet(PA);
551 }
552
553 AttributeSet AttributeSet::get(LLVMContext &C,
554                                ArrayRef<std::pair<unsigned, Attribute> > Attrs){
555   // If there are no attributes then return a null AttributesList pointer.
556   if (Attrs.empty())
557     return AttributeSet();
558
559 #ifndef NDEBUG
560   for (unsigned i = 0, e = Attrs.size(); i != e; ++i) {
561     assert((!i || Attrs[i-1].first <= Attrs[i].first) &&
562            "Misordered Attributes list!");
563     assert(!Attrs[i].second.hasAttribute(Attribute::None) &&
564            "Pointless attribute!");
565   }
566 #endif
567
568   // Create a vector if (unsigned, AttributeSetNode*) pairs from the attributes
569   // list.
570   SmallVector<std::pair<unsigned, AttributeSetNode*>, 8> AttrPairVec;
571   for (ArrayRef<std::pair<unsigned, Attribute> >::iterator I = Attrs.begin(),
572          E = Attrs.end(); I != E; ) {
573     unsigned Index = I->first;
574     SmallVector<Attribute, 4> AttrVec;
575     while (I != E && I->first == Index) {
576       AttrVec.push_back(I->second);
577       ++I;
578     }
579
580     AttrPairVec.push_back(std::make_pair(Index,
581                                          AttributeSetNode::get(C, AttrVec)));
582   }
583
584   return getImpl(C, AttrPairVec);
585 }
586
587 AttributeSet AttributeSet::get(LLVMContext &C,
588                                ArrayRef<std::pair<unsigned,
589                                                   AttributeSetNode*> > Attrs) {
590   // If there are no attributes then return a null AttributesList pointer.
591   if (Attrs.empty())
592     return AttributeSet();
593
594   return getImpl(C, Attrs);
595 }
596
597 AttributeSet AttributeSet::get(LLVMContext &C, unsigned Index, AttrBuilder &B) {
598   if (!B.hasAttributes())
599     return AttributeSet();
600
601   // Add target-independent attributes.
602   SmallVector<std::pair<unsigned, Attribute>, 8> Attrs;
603   for (Attribute::AttrKind Kind = Attribute::None;
604        Kind != Attribute::EndAttrKinds; Kind = Attribute::AttrKind(Kind + 1)) {
605     if (!B.contains(Kind))
606       continue;
607
608     if (Kind == Attribute::Alignment)
609       Attrs.push_back(std::make_pair(Index, Attribute::
610                                      getWithAlignment(C, B.getAlignment())));
611     else if (Kind == Attribute::StackAlignment)
612       Attrs.push_back(std::make_pair(Index, Attribute::
613                               getWithStackAlignment(C, B.getStackAlignment())));
614     else
615       Attrs.push_back(std::make_pair(Index, Attribute::get(C, Kind)));
616   }
617
618   // Add target-dependent (string) attributes.
619   for (AttrBuilder::td_iterator I = B.td_begin(), E = B.td_end();
620        I != E; ++I)
621     Attrs.push_back(std::make_pair(Index, Attribute::get(C, I->first,I->second)));
622
623   return get(C, Attrs);
624 }
625
626 AttributeSet AttributeSet::get(LLVMContext &C, unsigned Index,
627                                ArrayRef<Attribute::AttrKind> Kind) {
628   SmallVector<std::pair<unsigned, Attribute>, 8> Attrs;
629   for (ArrayRef<Attribute::AttrKind>::iterator I = Kind.begin(),
630          E = Kind.end(); I != E; ++I)
631     Attrs.push_back(std::make_pair(Index, Attribute::get(C, *I)));
632   return get(C, Attrs);
633 }
634
635 AttributeSet AttributeSet::get(LLVMContext &C, ArrayRef<AttributeSet> Attrs) {
636   if (Attrs.empty()) return AttributeSet();
637   if (Attrs.size() == 1) return Attrs[0];
638
639   SmallVector<std::pair<unsigned, AttributeSetNode*>, 8> AttrNodeVec;
640   AttributeSetImpl *A0 = Attrs[0].pImpl;
641   if (A0)
642     AttrNodeVec.append(A0->getNode(0), A0->getNode(A0->getNumAttributes()));
643   // Copy all attributes from Attrs into AttrNodeVec while keeping AttrNodeVec
644   // ordered by index.  Because we know that each list in Attrs is ordered by
645   // index we only need to merge each successive list in rather than doing a
646   // full sort.
647   for (unsigned I = 1, E = Attrs.size(); I != E; ++I) {
648     AttributeSetImpl *AS = Attrs[I].pImpl;
649     if (!AS) continue;
650     SmallVector<std::pair<unsigned, AttributeSetNode *>, 8>::iterator
651       ANVI = AttrNodeVec.begin(), ANVE;
652     for (const AttributeSetImpl::IndexAttrPair
653              *AI = AS->getNode(0),
654              *AE = AS->getNode(AS->getNumAttributes());
655          AI != AE; ++AI) {
656       ANVE = AttrNodeVec.end();
657       while (ANVI != ANVE && ANVI->first <= AI->first)
658         ++ANVI;
659       ANVI = AttrNodeVec.insert(ANVI, *AI) + 1;
660     }
661   }
662
663   return getImpl(C, AttrNodeVec);
664 }
665
666 AttributeSet AttributeSet::addAttribute(LLVMContext &C, unsigned Index,
667                                         Attribute::AttrKind Attr) const {
668   if (hasAttribute(Index, Attr)) return *this;
669   return addAttributes(C, Index, AttributeSet::get(C, Index, Attr));
670 }
671
672 AttributeSet AttributeSet::addAttribute(LLVMContext &C, unsigned Index,
673                                         StringRef Kind) const {
674   llvm::AttrBuilder B;
675   B.addAttribute(Kind);
676   return addAttributes(C, Index, AttributeSet::get(C, Index, B));
677 }
678
679 AttributeSet AttributeSet::addAttribute(LLVMContext &C, unsigned Index,
680                                         StringRef Kind, StringRef Value) const {
681   llvm::AttrBuilder B;
682   B.addAttribute(Kind, Value);
683   return addAttributes(C, Index, AttributeSet::get(C, Index, B));
684 }
685
686 AttributeSet AttributeSet::addAttributes(LLVMContext &C, unsigned Index,
687                                          AttributeSet Attrs) const {
688   if (!pImpl) return Attrs;
689   if (!Attrs.pImpl) return *this;
690
691 #ifndef NDEBUG
692   // FIXME it is not obvious how this should work for alignment. For now, say
693   // we can't change a known alignment.
694   unsigned OldAlign = getParamAlignment(Index);
695   unsigned NewAlign = Attrs.getParamAlignment(Index);
696   assert((!OldAlign || !NewAlign || OldAlign == NewAlign) &&
697          "Attempt to change alignment!");
698 #endif
699
700   // Add the attribute slots before the one we're trying to add.
701   SmallVector<AttributeSet, 4> AttrSet;
702   uint64_t NumAttrs = pImpl->getNumAttributes();
703   AttributeSet AS;
704   uint64_t LastIndex = 0;
705   for (unsigned I = 0, E = NumAttrs; I != E; ++I) {
706     if (getSlotIndex(I) >= Index) {
707       if (getSlotIndex(I) == Index) AS = getSlotAttributes(LastIndex++);
708       break;
709     }
710     LastIndex = I + 1;
711     AttrSet.push_back(getSlotAttributes(I));
712   }
713
714   // Now add the attribute into the correct slot. There may already be an
715   // AttributeSet there.
716   AttrBuilder B(AS, Index);
717
718   for (unsigned I = 0, E = Attrs.pImpl->getNumAttributes(); I != E; ++I)
719     if (Attrs.getSlotIndex(I) == Index) {
720       for (AttributeSetImpl::iterator II = Attrs.pImpl->begin(I),
721              IE = Attrs.pImpl->end(I); II != IE; ++II)
722         B.addAttribute(*II);
723       break;
724     }
725
726   AttrSet.push_back(AttributeSet::get(C, Index, B));
727
728   // Add the remaining attribute slots.
729   for (unsigned I = LastIndex, E = NumAttrs; I < E; ++I)
730     AttrSet.push_back(getSlotAttributes(I));
731
732   return get(C, AttrSet);
733 }
734
735 AttributeSet AttributeSet::removeAttribute(LLVMContext &C, unsigned Index,
736                                            Attribute::AttrKind Attr) const {
737   if (!hasAttribute(Index, Attr)) return *this;
738   return removeAttributes(C, Index, AttributeSet::get(C, Index, Attr));
739 }
740
741 AttributeSet AttributeSet::removeAttributes(LLVMContext &C, unsigned Index,
742                                             AttributeSet Attrs) const {
743   if (!pImpl) return AttributeSet();
744   if (!Attrs.pImpl) return *this;
745
746 #ifndef NDEBUG
747   // FIXME it is not obvious how this should work for alignment.
748   // For now, say we can't pass in alignment, which no current use does.
749   assert(!Attrs.hasAttribute(Index, Attribute::Alignment) &&
750          "Attempt to change alignment!");
751 #endif
752
753   // Add the attribute slots before the one we're trying to add.
754   SmallVector<AttributeSet, 4> AttrSet;
755   uint64_t NumAttrs = pImpl->getNumAttributes();
756   AttributeSet AS;
757   uint64_t LastIndex = 0;
758   for (unsigned I = 0, E = NumAttrs; I != E; ++I) {
759     if (getSlotIndex(I) >= Index) {
760       if (getSlotIndex(I) == Index) AS = getSlotAttributes(LastIndex++);
761       break;
762     }
763     LastIndex = I + 1;
764     AttrSet.push_back(getSlotAttributes(I));
765   }
766
767   // Now remove the attribute from the correct slot. There may already be an
768   // AttributeSet there.
769   AttrBuilder B(AS, Index);
770
771   for (unsigned I = 0, E = Attrs.pImpl->getNumAttributes(); I != E; ++I)
772     if (Attrs.getSlotIndex(I) == Index) {
773       B.removeAttributes(Attrs.pImpl->getSlotAttributes(I), Index);
774       break;
775     }
776
777   AttrSet.push_back(AttributeSet::get(C, Index, B));
778
779   // Add the remaining attribute slots.
780   for (unsigned I = LastIndex, E = NumAttrs; I < E; ++I)
781     AttrSet.push_back(getSlotAttributes(I));
782
783   return get(C, AttrSet);
784 }
785
786 //===----------------------------------------------------------------------===//
787 // AttributeSet Accessor Methods
788 //===----------------------------------------------------------------------===//
789
790 LLVMContext &AttributeSet::getContext() const {
791   return pImpl->getContext();
792 }
793
794 AttributeSet AttributeSet::getParamAttributes(unsigned Index) const {
795   return pImpl && hasAttributes(Index) ?
796     AttributeSet::get(pImpl->getContext(),
797                       ArrayRef<std::pair<unsigned, AttributeSetNode*> >(
798                         std::make_pair(Index, getAttributes(Index)))) :
799     AttributeSet();
800 }
801
802 AttributeSet AttributeSet::getRetAttributes() const {
803   return pImpl && hasAttributes(ReturnIndex) ?
804     AttributeSet::get(pImpl->getContext(),
805                       ArrayRef<std::pair<unsigned, AttributeSetNode*> >(
806                         std::make_pair(ReturnIndex,
807                                        getAttributes(ReturnIndex)))) :
808     AttributeSet();
809 }
810
811 AttributeSet AttributeSet::getFnAttributes() const {
812   return pImpl && hasAttributes(FunctionIndex) ?
813     AttributeSet::get(pImpl->getContext(),
814                       ArrayRef<std::pair<unsigned, AttributeSetNode*> >(
815                         std::make_pair(FunctionIndex,
816                                        getAttributes(FunctionIndex)))) :
817     AttributeSet();
818 }
819
820 bool AttributeSet::hasAttribute(unsigned Index, Attribute::AttrKind Kind) const{
821   AttributeSetNode *ASN = getAttributes(Index);
822   return ASN ? ASN->hasAttribute(Kind) : false;
823 }
824
825 bool AttributeSet::hasAttribute(unsigned Index, StringRef Kind) const {
826   AttributeSetNode *ASN = getAttributes(Index);
827   return ASN ? ASN->hasAttribute(Kind) : false;
828 }
829
830 bool AttributeSet::hasAttributes(unsigned Index) const {
831   AttributeSetNode *ASN = getAttributes(Index);
832   return ASN ? ASN->hasAttributes() : false;
833 }
834
835 /// \brief Return true if the specified attribute is set for at least one
836 /// parameter or for the return value.
837 bool AttributeSet::hasAttrSomewhere(Attribute::AttrKind Attr) const {
838   if (pImpl == 0) return false;
839
840   for (unsigned I = 0, E = pImpl->getNumAttributes(); I != E; ++I)
841     for (AttributeSetImpl::iterator II = pImpl->begin(I),
842            IE = pImpl->end(I); II != IE; ++II)
843       if (II->hasAttribute(Attr))
844         return true;
845
846   return false;
847 }
848
849 Attribute AttributeSet::getAttribute(unsigned Index,
850                                      Attribute::AttrKind Kind) const {
851   AttributeSetNode *ASN = getAttributes(Index);
852   return ASN ? ASN->getAttribute(Kind) : Attribute();
853 }
854
855 Attribute AttributeSet::getAttribute(unsigned Index,
856                                      StringRef Kind) const {
857   AttributeSetNode *ASN = getAttributes(Index);
858   return ASN ? ASN->getAttribute(Kind) : Attribute();
859 }
860
861 unsigned AttributeSet::getParamAlignment(unsigned Index) const {
862   AttributeSetNode *ASN = getAttributes(Index);
863   return ASN ? ASN->getAlignment() : 0;
864 }
865
866 unsigned AttributeSet::getStackAlignment(unsigned Index) const {
867   AttributeSetNode *ASN = getAttributes(Index);
868   return ASN ? ASN->getStackAlignment() : 0;
869 }
870
871 std::string AttributeSet::getAsString(unsigned Index,
872                                       bool InAttrGrp) const {
873   AttributeSetNode *ASN = getAttributes(Index);
874   return ASN ? ASN->getAsString(InAttrGrp) : std::string("");
875 }
876
877 /// \brief The attributes for the specified index are returned.
878 AttributeSetNode *AttributeSet::getAttributes(unsigned Index) const {
879   if (!pImpl) return 0;
880
881   // Loop through to find the attribute node we want.
882   for (unsigned I = 0, E = pImpl->getNumAttributes(); I != E; ++I)
883     if (pImpl->getSlotIndex(I) == Index)
884       return pImpl->getSlotNode(I);
885
886   return 0;
887 }
888
889 AttributeSet::iterator AttributeSet::begin(unsigned Slot) const {
890   if (!pImpl)
891     return ArrayRef<Attribute>().begin();
892   return pImpl->begin(Slot);
893 }
894
895 AttributeSet::iterator AttributeSet::end(unsigned Slot) const {
896   if (!pImpl)
897     return ArrayRef<Attribute>().end();
898   return pImpl->end(Slot);
899 }
900
901 //===----------------------------------------------------------------------===//
902 // AttributeSet Introspection Methods
903 //===----------------------------------------------------------------------===//
904
905 /// \brief Return the number of slots used in this attribute list.  This is the
906 /// number of arguments that have an attribute set on them (including the
907 /// function itself).
908 unsigned AttributeSet::getNumSlots() const {
909   return pImpl ? pImpl->getNumAttributes() : 0;
910 }
911
912 unsigned AttributeSet::getSlotIndex(unsigned Slot) const {
913   assert(pImpl && Slot < pImpl->getNumAttributes() &&
914          "Slot # out of range!");
915   return pImpl->getSlotIndex(Slot);
916 }
917
918 AttributeSet AttributeSet::getSlotAttributes(unsigned Slot) const {
919   assert(pImpl && Slot < pImpl->getNumAttributes() &&
920          "Slot # out of range!");
921   return pImpl->getSlotAttributes(Slot);
922 }
923
924 uint64_t AttributeSet::Raw(unsigned Index) const {
925   // FIXME: Remove this.
926   return pImpl ? pImpl->Raw(Index) : 0;
927 }
928
929 void AttributeSet::dump() const {
930   dbgs() << "PAL[\n";
931
932   for (unsigned i = 0, e = getNumSlots(); i < e; ++i) {
933     uint64_t Index = getSlotIndex(i);
934     dbgs() << "  { ";
935     if (Index == ~0U)
936       dbgs() << "~0U";
937     else
938       dbgs() << Index;
939     dbgs() << " => " << getAsString(Index) << " }\n";
940   }
941
942   dbgs() << "]\n";
943 }
944
945 //===----------------------------------------------------------------------===//
946 // AttrBuilder Method Implementations
947 //===----------------------------------------------------------------------===//
948
949 AttrBuilder::AttrBuilder(AttributeSet AS, unsigned Index)
950   : Attrs(0), Alignment(0), StackAlignment(0) {
951   AttributeSetImpl *pImpl = AS.pImpl;
952   if (!pImpl) return;
953
954   for (unsigned I = 0, E = pImpl->getNumAttributes(); I != E; ++I) {
955     if (pImpl->getSlotIndex(I) != Index) continue;
956
957     for (AttributeSetImpl::iterator II = pImpl->begin(I),
958            IE = pImpl->end(I); II != IE; ++II)
959       addAttribute(*II);
960
961     break;
962   }
963 }
964
965 void AttrBuilder::clear() {
966   Attrs.reset();
967   Alignment = StackAlignment = 0;
968 }
969
970 AttrBuilder &AttrBuilder::addAttribute(Attribute::AttrKind Val) {
971   assert((unsigned)Val < Attribute::EndAttrKinds && "Attribute out of range!");
972   assert(Val != Attribute::Alignment && Val != Attribute::StackAlignment &&
973          "Adding alignment attribute without adding alignment value!");
974   Attrs[Val] = true;
975   return *this;
976 }
977
978 AttrBuilder &AttrBuilder::addAttribute(Attribute Attr) {
979   if (Attr.isStringAttribute()) {
980     addAttribute(Attr.getKindAsString(), Attr.getValueAsString());
981     return *this;
982   }
983
984   Attribute::AttrKind Kind = Attr.getKindAsEnum();
985   Attrs[Kind] = true;
986
987   if (Kind == Attribute::Alignment)
988     Alignment = Attr.getAlignment();
989   else if (Kind == Attribute::StackAlignment)
990     StackAlignment = Attr.getStackAlignment();
991   return *this;
992 }
993
994 AttrBuilder &AttrBuilder::addAttribute(StringRef A, StringRef V) {
995   TargetDepAttrs[A] = V;
996   return *this;
997 }
998
999 AttrBuilder &AttrBuilder::removeAttribute(Attribute::AttrKind Val) {
1000   assert((unsigned)Val < Attribute::EndAttrKinds && "Attribute out of range!");
1001   Attrs[Val] = false;
1002
1003   if (Val == Attribute::Alignment)
1004     Alignment = 0;
1005   else if (Val == Attribute::StackAlignment)
1006     StackAlignment = 0;
1007
1008   return *this;
1009 }
1010
1011 AttrBuilder &AttrBuilder::removeAttributes(AttributeSet A, uint64_t Index) {
1012   unsigned Slot = ~0U;
1013   for (unsigned I = 0, E = A.getNumSlots(); I != E; ++I)
1014     if (A.getSlotIndex(I) == Index) {
1015       Slot = I;
1016       break;
1017     }
1018
1019   assert(Slot != ~0U && "Couldn't find index in AttributeSet!");
1020
1021   for (AttributeSet::iterator I = A.begin(Slot), E = A.end(Slot); I != E; ++I) {
1022     Attribute Attr = *I;
1023     if (Attr.isEnumAttribute() || Attr.isAlignAttribute()) {
1024       Attribute::AttrKind Kind = I->getKindAsEnum();
1025       Attrs[Kind] = false;
1026
1027       if (Kind == Attribute::Alignment)
1028         Alignment = 0;
1029       else if (Kind == Attribute::StackAlignment)
1030         StackAlignment = 0;
1031     } else {
1032       assert(Attr.isStringAttribute() && "Invalid attribute type!");
1033       std::map<std::string, std::string>::iterator
1034         Iter = TargetDepAttrs.find(Attr.getKindAsString());
1035       if (Iter != TargetDepAttrs.end())
1036         TargetDepAttrs.erase(Iter);
1037     }
1038   }
1039
1040   return *this;
1041 }
1042
1043 AttrBuilder &AttrBuilder::removeAttribute(StringRef A) {
1044   std::map<std::string, std::string>::iterator I = TargetDepAttrs.find(A);
1045   if (I != TargetDepAttrs.end())
1046     TargetDepAttrs.erase(I);
1047   return *this;
1048 }
1049
1050 AttrBuilder &AttrBuilder::addAlignmentAttr(unsigned Align) {
1051   if (Align == 0) return *this;
1052
1053   assert(isPowerOf2_32(Align) && "Alignment must be a power of two.");
1054   assert(Align <= 0x40000000 && "Alignment too large.");
1055
1056   Attrs[Attribute::Alignment] = true;
1057   Alignment = Align;
1058   return *this;
1059 }
1060
1061 AttrBuilder &AttrBuilder::addStackAlignmentAttr(unsigned Align) {
1062   // Default alignment, allow the target to define how to align it.
1063   if (Align == 0) return *this;
1064
1065   assert(isPowerOf2_32(Align) && "Alignment must be a power of two.");
1066   assert(Align <= 0x100 && "Alignment too large.");
1067
1068   Attrs[Attribute::StackAlignment] = true;
1069   StackAlignment = Align;
1070   return *this;
1071 }
1072
1073 AttrBuilder &AttrBuilder::merge(const AttrBuilder &B) {
1074   // FIXME: What if both have alignments, but they don't match?!
1075   if (!Alignment)
1076     Alignment = B.Alignment;
1077
1078   if (!StackAlignment)
1079     StackAlignment = B.StackAlignment;
1080
1081   Attrs |= B.Attrs;
1082
1083   for (td_const_iterator I = B.TargetDepAttrs.begin(),
1084          E = B.TargetDepAttrs.end(); I != E; ++I)
1085     TargetDepAttrs[I->first] = I->second;
1086
1087   return *this;
1088 }
1089
1090 bool AttrBuilder::contains(StringRef A) const {
1091   return TargetDepAttrs.find(A) != TargetDepAttrs.end();
1092 }
1093
1094 bool AttrBuilder::hasAttributes() const {
1095   return !Attrs.none() || !TargetDepAttrs.empty();
1096 }
1097
1098 bool AttrBuilder::hasAttributes(AttributeSet A, uint64_t Index) const {
1099   unsigned Slot = ~0U;
1100   for (unsigned I = 0, E = A.getNumSlots(); I != E; ++I)
1101     if (A.getSlotIndex(I) == Index) {
1102       Slot = I;
1103       break;
1104     }
1105
1106   assert(Slot != ~0U && "Couldn't find the index!");
1107
1108   for (AttributeSet::iterator I = A.begin(Slot), E = A.end(Slot);
1109        I != E; ++I) {
1110     Attribute Attr = *I;
1111     if (Attr.isEnumAttribute() || Attr.isAlignAttribute()) {
1112       if (Attrs[I->getKindAsEnum()])
1113         return true;
1114     } else {
1115       assert(Attr.isStringAttribute() && "Invalid attribute kind!");
1116       return TargetDepAttrs.find(Attr.getKindAsString())!=TargetDepAttrs.end();
1117     }
1118   }
1119
1120   return false;
1121 }
1122
1123 bool AttrBuilder::hasAlignmentAttr() const {
1124   return Alignment != 0;
1125 }
1126
1127 bool AttrBuilder::operator==(const AttrBuilder &B) {
1128   if (Attrs != B.Attrs)
1129     return false;
1130
1131   for (td_const_iterator I = TargetDepAttrs.begin(),
1132          E = TargetDepAttrs.end(); I != E; ++I)
1133     if (B.TargetDepAttrs.find(I->first) == B.TargetDepAttrs.end())
1134       return false;
1135
1136   return Alignment == B.Alignment && StackAlignment == B.StackAlignment;
1137 }
1138
1139 AttrBuilder &AttrBuilder::addRawValue(uint64_t Val) {
1140   // FIXME: Remove this in 4.0.
1141   if (!Val) return *this;
1142
1143   for (Attribute::AttrKind I = Attribute::None; I != Attribute::EndAttrKinds;
1144        I = Attribute::AttrKind(I + 1)) {
1145     if (uint64_t A = (Val & AttributeImpl::getAttrMask(I))) {
1146       Attrs[I] = true;
1147  
1148       if (I == Attribute::Alignment)
1149         Alignment = 1ULL << ((A >> 16) - 1);
1150       else if (I == Attribute::StackAlignment)
1151         StackAlignment = 1ULL << ((A >> 26)-1);
1152     }
1153   }
1154  
1155   return *this;
1156 }
1157
1158 //===----------------------------------------------------------------------===//
1159 // AttributeFuncs Function Defintions
1160 //===----------------------------------------------------------------------===//
1161
1162 /// \brief Which attributes cannot be applied to a type.
1163 AttributeSet AttributeFuncs::typeIncompatible(Type *Ty, uint64_t Index) {
1164   AttrBuilder Incompatible;
1165
1166   if (!Ty->isIntegerTy())
1167     // Attribute that only apply to integers.
1168     Incompatible.addAttribute(Attribute::SExt)
1169       .addAttribute(Attribute::ZExt);
1170
1171   if (!Ty->isPointerTy())
1172     // Attribute that only apply to pointers.
1173     Incompatible.addAttribute(Attribute::ByVal)
1174       .addAttribute(Attribute::Nest)
1175       .addAttribute(Attribute::NoAlias)
1176       .addAttribute(Attribute::NoCapture)
1177       .addAttribute(Attribute::ReadNone)
1178       .addAttribute(Attribute::ReadOnly)
1179       .addAttribute(Attribute::StructRet)
1180       .addAttribute(Attribute::InAlloca);
1181
1182   return AttributeSet::get(Ty->getContext(), Index, Incompatible);
1183 }