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