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