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