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