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