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