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