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