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