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