Support a common idiom on how to build an Attributes class with a single attribute.
[oota-llvm.git] / lib / VMCore / 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 // This file implements the AttributesList class and Attribute utilities.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/Attributes.h"
15 #include "LLVMContextImpl.h"
16 #include "llvm/Type.h"
17 #include "llvm/ADT/StringExtras.h"
18 #include "llvm/ADT/FoldingSet.h"
19 #include "llvm/Support/Atomic.h"
20 #include "llvm/Support/Mutex.h"
21 #include "llvm/Support/Debug.h"
22 #include "llvm/Support/ManagedStatic.h"
23 #include "llvm/Support/raw_ostream.h"
24 using namespace llvm;
25
26 //===----------------------------------------------------------------------===//
27 // Attributes Implementation
28 //===----------------------------------------------------------------------===//
29
30 Attributes::Attributes(uint64_t Val) : Attrs(Val) {}
31
32 Attributes::Attributes(AttrVal Val)
33   : Attrs(Attributes::get(Attributes::Builder().addAttribute(Val)).Attrs) {}
34
35 Attributes::Attributes(AttributesImpl *A) : Attrs(A->Bits) {}
36
37 Attributes::Attributes(const Attributes &A) : Attrs(A.Attrs) {}
38
39 // FIXME: This is temporary until we have implemented the uniquified version of
40 // AttributesImpl.
41 Attributes Attributes::get(Attributes::Builder &B) {
42   return Attributes(B.Bits);
43 }
44
45 Attributes Attributes::get(LLVMContext &Context, Attributes::Builder &B) {
46   // If there are no attributes, return an empty Attributes class.
47   if (B.Bits == 0)
48     return Attributes();
49
50   // Otherwise, build a key to look up the existing attributes.
51   LLVMContextImpl *pImpl = Context.pImpl;
52   FoldingSetNodeID ID;
53   ID.AddInteger(B.Bits);
54
55   void *InsertPoint;
56   AttributesImpl *PA = pImpl->AttrsSet.FindNodeOrInsertPos(ID, InsertPoint);
57
58   if (!PA) {
59     // If we didn't find any existing attributes of the same shape then create a
60     // new one and insert it.
61     PA = new AttributesImpl(B.Bits);
62     pImpl->AttrsSet.InsertNode(PA, InsertPoint);
63   }
64
65   // Return the AttributesList that we found or created.
66   return Attributes(PA);
67 }
68
69 bool Attributes::hasAttribute(AttrVal Val) const {
70   return Attrs.hasAttribute(Val);
71 }
72
73 bool Attributes::hasAttributes(const Attributes &A) const {
74   return Attrs.hasAttributes(A);
75 }
76
77 /// This returns the alignment field of an attribute as a byte alignment value.
78 unsigned Attributes::getAlignment() const {
79   if (!hasAttribute(Attributes::Alignment))
80     return 0;
81   return 1U << ((Attrs.getAlignment() >> 16) - 1);
82 }
83
84 /// This returns the stack alignment field of an attribute as a byte alignment
85 /// value.
86 unsigned Attributes::getStackAlignment() const {
87   if (!hasAttribute(Attributes::StackAlignment))
88     return 0;
89   return 1U << ((Attrs.getStackAlignment() >> 26) - 1);
90 }
91
92 bool Attributes::isEmptyOrSingleton() const {
93   return Attrs.isEmptyOrSingleton();
94 }
95
96 Attributes Attributes::operator | (const Attributes &A) const {
97   return Attributes(Raw() | A.Raw());
98 }
99 Attributes Attributes::operator & (const Attributes &A) const {
100   return Attributes(Raw() & A.Raw());
101 }
102 Attributes Attributes::operator ^ (const Attributes &A) const {
103   return Attributes(Raw() ^ A.Raw());
104 }
105 Attributes &Attributes::operator |= (const Attributes &A) {
106   Attrs.Bits |= A.Raw();
107   return *this;
108 }
109 Attributes &Attributes::operator &= (const Attributes &A) {
110   Attrs.Bits &= A.Raw();
111   return *this;
112 }
113 Attributes Attributes::operator ~ () const {
114   return Attributes(~Raw());
115 }
116
117 uint64_t Attributes::Raw() const {
118   return Attrs.Bits;
119 }
120
121 Attributes Attributes::typeIncompatible(Type *Ty) {
122   Attributes::Builder Incompatible;
123   
124   if (!Ty->isIntegerTy())
125     // Attributes that only apply to integers.
126     Incompatible.addAttribute(Attributes::SExt)
127       .addAttribute(Attributes::ZExt);
128   
129   if (!Ty->isPointerTy())
130     // Attributes that only apply to pointers.
131     Incompatible.addAttribute(Attributes::ByVal)
132       .addAttribute(Attributes::Nest)
133       .addAttribute(Attributes::NoAlias)
134       .addAttribute(Attributes::NoCapture)
135       .addAttribute(Attributes::StructRet);
136   
137   return Attributes(Incompatible.Bits); // FIXME: Use Attributes::get().
138 }
139
140 std::string Attributes::getAsString() const {
141   std::string Result;
142   if (hasAttribute(Attributes::ZExt))
143     Result += "zeroext ";
144   if (hasAttribute(Attributes::SExt))
145     Result += "signext ";
146   if (hasAttribute(Attributes::NoReturn))
147     Result += "noreturn ";
148   if (hasAttribute(Attributes::NoUnwind))
149     Result += "nounwind ";
150   if (hasAttribute(Attributes::UWTable))
151     Result += "uwtable ";
152   if (hasAttribute(Attributes::ReturnsTwice))
153     Result += "returns_twice ";
154   if (hasAttribute(Attributes::InReg))
155     Result += "inreg ";
156   if (hasAttribute(Attributes::NoAlias))
157     Result += "noalias ";
158   if (hasAttribute(Attributes::NoCapture))
159     Result += "nocapture ";
160   if (hasAttribute(Attributes::StructRet))
161     Result += "sret ";
162   if (hasAttribute(Attributes::ByVal))
163     Result += "byval ";
164   if (hasAttribute(Attributes::Nest))
165     Result += "nest ";
166   if (hasAttribute(Attributes::ReadNone))
167     Result += "readnone ";
168   if (hasAttribute(Attributes::ReadOnly))
169     Result += "readonly ";
170   if (hasAttribute(Attributes::OptimizeForSize))
171     Result += "optsize ";
172   if (hasAttribute(Attributes::NoInline))
173     Result += "noinline ";
174   if (hasAttribute(Attributes::InlineHint))
175     Result += "inlinehint ";
176   if (hasAttribute(Attributes::AlwaysInline))
177     Result += "alwaysinline ";
178   if (hasAttribute(Attributes::StackProtect))
179     Result += "ssp ";
180   if (hasAttribute(Attributes::StackProtectReq))
181     Result += "sspreq ";
182   if (hasAttribute(Attributes::NoRedZone))
183     Result += "noredzone ";
184   if (hasAttribute(Attributes::NoImplicitFloat))
185     Result += "noimplicitfloat ";
186   if (hasAttribute(Attributes::Naked))
187     Result += "naked ";
188   if (hasAttribute(Attributes::NonLazyBind))
189     Result += "nonlazybind ";
190   if (hasAttribute(Attributes::AddressSafety))
191     Result += "address_safety ";
192   if (hasAttribute(Attributes::StackAlignment)) {
193     Result += "alignstack(";
194     Result += utostr(getStackAlignment());
195     Result += ") ";
196   }
197   if (hasAttribute(Attributes::Alignment)) {
198     Result += "align ";
199     Result += utostr(getAlignment());
200     Result += " ";
201   }
202   // Trim the trailing space.
203   assert(!Result.empty() && "Unknown attribute!");
204   Result.erase(Result.end()-1);
205   return Result;
206 }
207
208 //===----------------------------------------------------------------------===//
209 // Attributes::Builder Implementation
210 //===----------------------------------------------------------------------===//
211
212 Attributes::Builder &Attributes::Builder::
213 addAttribute(Attributes::AttrVal Val) {
214   Bits |= AttributesImpl::getAttrMask(Val);
215   return *this;
216 }
217
218 void Attributes::Builder::addAlignmentAttr(unsigned Align) {
219   if (Align == 0) return;
220   assert(isPowerOf2_32(Align) && "Alignment must be a power of two.");
221   assert(Align <= 0x40000000 && "Alignment too large.");
222   Bits |= (Log2_32(Align) + 1) << 16;
223 }
224 void Attributes::Builder::addStackAlignmentAttr(unsigned Align) {
225   // Default alignment, allow the target to define how to align it.
226   if (Align == 0) return;
227   assert(isPowerOf2_32(Align) && "Alignment must be a power of two.");
228   assert(Align <= 0x100 && "Alignment too large.");
229   Bits |= (Log2_32(Align) + 1) << 26;
230 }
231
232 Attributes::Builder &Attributes::Builder::
233 removeAttribute(Attributes::AttrVal Val) {
234   Bits &= ~AttributesImpl::getAttrMask(Val);
235   return *this;
236 }
237
238 void Attributes::Builder::removeAttributes(const Attributes &A) {
239   Bits &= ~A.Raw();
240 }
241
242 bool Attributes::Builder::hasAttribute(Attributes::AttrVal A) const {
243   return Bits & AttributesImpl::getAttrMask(A);
244 }
245
246 bool Attributes::Builder::hasAttributes() const {
247   return Bits != 0;
248 }
249 bool Attributes::Builder::hasAttributes(const Attributes &A) const {
250   return Bits & A.Raw();
251 }
252 bool Attributes::Builder::hasAlignmentAttr() const {
253   return Bits & AttributesImpl::getAttrMask(Attributes::Alignment);
254 }
255
256 uint64_t Attributes::Builder::getAlignment() const {
257   if (!hasAlignmentAttr())
258     return 0;
259   return 1U <<
260     (((Bits & AttributesImpl::getAttrMask(Attributes::Alignment)) >> 16) - 1);
261 }
262
263 uint64_t Attributes::Builder::getStackAlignment() const {
264   if (!hasAlignmentAttr())
265     return 0;
266   return 1U <<
267     (((Bits & AttributesImpl::getAttrMask(Attributes::StackAlignment))>>26)-1);
268 }
269
270 //===----------------------------------------------------------------------===//
271 // AttributeImpl Definition
272 //===----------------------------------------------------------------------===//
273
274 uint64_t AttributesImpl::getAttrMask(uint64_t Val) {
275   switch (Val) {
276   case Attributes::None:            return 0;
277   case Attributes::ZExt:            return 1 << 0;
278   case Attributes::SExt:            return 1 << 1;
279   case Attributes::NoReturn:        return 1 << 2;
280   case Attributes::InReg:           return 1 << 3;
281   case Attributes::StructRet:       return 1 << 4;
282   case Attributes::NoUnwind:        return 1 << 5;
283   case Attributes::NoAlias:         return 1 << 6;
284   case Attributes::ByVal:           return 1 << 7;
285   case Attributes::Nest:            return 1 << 8;
286   case Attributes::ReadNone:        return 1 << 9;
287   case Attributes::ReadOnly:        return 1 << 10;
288   case Attributes::NoInline:        return 1 << 11;
289   case Attributes::AlwaysInline:    return 1 << 12;
290   case Attributes::OptimizeForSize: return 1 << 13;
291   case Attributes::StackProtect:    return 1 << 14;
292   case Attributes::StackProtectReq: return 1 << 15;
293   case Attributes::Alignment:       return 31 << 16;
294   case Attributes::NoCapture:       return 1 << 21;
295   case Attributes::NoRedZone:       return 1 << 22;
296   case Attributes::NoImplicitFloat: return 1 << 23;
297   case Attributes::Naked:           return 1 << 24;
298   case Attributes::InlineHint:      return 1 << 25;
299   case Attributes::StackAlignment:  return 7 << 26;
300   case Attributes::ReturnsTwice:    return 1 << 29;
301   case Attributes::UWTable:         return 1 << 30;
302   case Attributes::NonLazyBind:     return 1U << 31;
303   case Attributes::AddressSafety:   return 1ULL << 32;
304   }
305   llvm_unreachable("Unsupported attribute type");
306 }
307
308 bool AttributesImpl::hasAttribute(uint64_t A) const {
309   return (Bits & getAttrMask(A)) != 0;
310 }
311
312 bool AttributesImpl::hasAttributes() const {
313   return Bits != 0;
314 }
315
316 bool AttributesImpl::hasAttributes(const Attributes &A) const {
317   return Bits & A.Raw();        // FIXME: Raw() won't work here in the future.
318 }
319
320 uint64_t AttributesImpl::getAlignment() const {
321   return Bits & getAttrMask(Attributes::Alignment);
322 }
323
324 uint64_t AttributesImpl::getStackAlignment() const {
325   return Bits & getAttrMask(Attributes::StackAlignment);
326 }
327
328 bool AttributesImpl::isEmptyOrSingleton() const {
329   return (Bits & (Bits - 1)) == 0;
330 }
331
332 //===----------------------------------------------------------------------===//
333 // AttributeListImpl Definition
334 //===----------------------------------------------------------------------===//
335
336 namespace llvm {
337   class AttributeListImpl;
338 }
339
340 static ManagedStatic<FoldingSet<AttributeListImpl> > AttributesLists;
341
342 namespace llvm {
343 static ManagedStatic<sys::SmartMutex<true> > ALMutex;
344
345 class AttributeListImpl : public FoldingSetNode {
346   sys::cas_flag RefCount;
347   
348   // AttributesList is uniqued, these should not be publicly available.
349   void operator=(const AttributeListImpl &) LLVM_DELETED_FUNCTION;
350   AttributeListImpl(const AttributeListImpl &) LLVM_DELETED_FUNCTION;
351   ~AttributeListImpl();                        // Private implementation
352 public:
353   SmallVector<AttributeWithIndex, 4> Attrs;
354   
355   AttributeListImpl(ArrayRef<AttributeWithIndex> attrs)
356     : Attrs(attrs.begin(), attrs.end()) {
357     RefCount = 0;
358   }
359   
360   void AddRef() {
361     sys::SmartScopedLock<true> Lock(*ALMutex);
362     ++RefCount;
363   }
364   void DropRef() {
365     sys::SmartScopedLock<true> Lock(*ALMutex);
366     if (!AttributesLists.isConstructed())
367       return;
368     sys::cas_flag new_val = --RefCount;
369     if (new_val == 0)
370       delete this;
371   }
372   
373   void Profile(FoldingSetNodeID &ID) const {
374     Profile(ID, Attrs);
375   }
376   static void Profile(FoldingSetNodeID &ID, ArrayRef<AttributeWithIndex> Attrs){
377     for (unsigned i = 0, e = Attrs.size(); i != e; ++i) {
378       ID.AddInteger(Attrs[i].Attrs.Raw());
379       ID.AddInteger(Attrs[i].Index);
380     }
381   }
382 };
383 }
384
385 AttributeListImpl::~AttributeListImpl() {
386   // NOTE: Lock must be acquired by caller.
387   AttributesLists->RemoveNode(this);
388 }
389
390
391 AttrListPtr AttrListPtr::get(ArrayRef<AttributeWithIndex> Attrs) {
392   // If there are no attributes then return a null AttributesList pointer.
393   if (Attrs.empty())
394     return AttrListPtr();
395   
396 #ifndef NDEBUG
397   for (unsigned i = 0, e = Attrs.size(); i != e; ++i) {
398     assert(Attrs[i].Attrs.hasAttributes() && 
399            "Pointless attribute!");
400     assert((!i || Attrs[i-1].Index < Attrs[i].Index) &&
401            "Misordered AttributesList!");
402   }
403 #endif
404   
405   // Otherwise, build a key to look up the existing attributes.
406   FoldingSetNodeID ID;
407   AttributeListImpl::Profile(ID, Attrs);
408   void *InsertPos;
409   
410   sys::SmartScopedLock<true> Lock(*ALMutex);
411   
412   AttributeListImpl *PAL =
413     AttributesLists->FindNodeOrInsertPos(ID, InsertPos);
414   
415   // If we didn't find any existing attributes of the same shape then
416   // create a new one and insert it.
417   if (!PAL) {
418     PAL = new AttributeListImpl(Attrs);
419     AttributesLists->InsertNode(PAL, InsertPos);
420   }
421   
422   // Return the AttributesList that we found or created.
423   return AttrListPtr(PAL);
424 }
425
426
427 //===----------------------------------------------------------------------===//
428 // AttrListPtr Method Implementations
429 //===----------------------------------------------------------------------===//
430
431 AttrListPtr::AttrListPtr(AttributeListImpl *LI) : AttrList(LI) {
432   if (LI) LI->AddRef();
433 }
434
435 AttrListPtr::AttrListPtr(const AttrListPtr &P) : AttrList(P.AttrList) {
436   if (AttrList) AttrList->AddRef();  
437 }
438
439 const AttrListPtr &AttrListPtr::operator=(const AttrListPtr &RHS) {
440   sys::SmartScopedLock<true> Lock(*ALMutex);
441   if (AttrList == RHS.AttrList) return *this;
442   if (AttrList) AttrList->DropRef();
443   AttrList = RHS.AttrList;
444   if (AttrList) AttrList->AddRef();
445   return *this;
446 }
447
448 AttrListPtr::~AttrListPtr() {
449   if (AttrList) AttrList->DropRef();
450 }
451
452 /// getNumSlots - Return the number of slots used in this attribute list. 
453 /// This is the number of arguments that have an attribute set on them
454 /// (including the function itself).
455 unsigned AttrListPtr::getNumSlots() const {
456   return AttrList ? AttrList->Attrs.size() : 0;
457 }
458
459 /// getSlot - Return the AttributeWithIndex at the specified slot.  This
460 /// holds a number plus a set of attributes.
461 const AttributeWithIndex &AttrListPtr::getSlot(unsigned Slot) const {
462   assert(AttrList && Slot < AttrList->Attrs.size() && "Slot # out of range!");
463   return AttrList->Attrs[Slot];
464 }
465
466
467 /// getAttributes - The attributes for the specified index are
468 /// returned.  Attributes for the result are denoted with Idx = 0.
469 /// Function notes are denoted with idx = ~0.
470 Attributes AttrListPtr::getAttributes(unsigned Idx) const {
471   if (AttrList == 0) return Attributes();
472   
473   const SmallVector<AttributeWithIndex, 4> &Attrs = AttrList->Attrs;
474   for (unsigned i = 0, e = Attrs.size(); i != e && Attrs[i].Index <= Idx; ++i)
475     if (Attrs[i].Index == Idx)
476       return Attrs[i].Attrs;
477
478   return Attributes();
479 }
480
481 /// hasAttrSomewhere - Return true if the specified attribute is set for at
482 /// least one parameter or for the return value.
483 bool AttrListPtr::hasAttrSomewhere(Attributes::AttrVal Attr) const {
484   if (AttrList == 0) return false;
485
486   const SmallVector<AttributeWithIndex, 4> &Attrs = AttrList->Attrs;
487   for (unsigned i = 0, e = Attrs.size(); i != e; ++i)
488     if (Attrs[i].Attrs.hasAttribute(Attr))
489       return true;
490   return false;
491 }
492
493 unsigned AttrListPtr::getNumAttrs() const {
494   return AttrList ? AttrList->Attrs.size() : 0;
495 }
496
497 Attributes &AttrListPtr::getAttributesAtIndex(unsigned i) const {
498   assert(AttrList && "Trying to get an attribute from an empty list!");
499   assert(i < AttrList->Attrs.size() && "Index out of range!");
500   return AttrList->Attrs[i].Attrs;
501 }
502
503 AttrListPtr AttrListPtr::addAttr(unsigned Idx, Attributes Attrs) const {
504   Attributes OldAttrs = getAttributes(Idx);
505 #ifndef NDEBUG
506   // FIXME it is not obvious how this should work for alignment.
507   // For now, say we can't change a known alignment.
508   unsigned OldAlign = OldAttrs.getAlignment();
509   unsigned NewAlign = Attrs.getAlignment();
510   assert((!OldAlign || !NewAlign || OldAlign == NewAlign) &&
511          "Attempt to change alignment!");
512 #endif
513   
514   Attributes NewAttrs = OldAttrs | Attrs;
515   if (NewAttrs == OldAttrs)
516     return *this;
517   
518   SmallVector<AttributeWithIndex, 8> NewAttrList;
519   if (AttrList == 0)
520     NewAttrList.push_back(AttributeWithIndex::get(Idx, Attrs));
521   else {
522     const SmallVector<AttributeWithIndex, 4> &OldAttrList = AttrList->Attrs;
523     unsigned i = 0, e = OldAttrList.size();
524     // Copy attributes for arguments before this one.
525     for (; i != e && OldAttrList[i].Index < Idx; ++i)
526       NewAttrList.push_back(OldAttrList[i]);
527
528     // If there are attributes already at this index, merge them in.
529     if (i != e && OldAttrList[i].Index == Idx) {
530       Attrs |= OldAttrList[i].Attrs;
531       ++i;
532     }
533     
534     NewAttrList.push_back(AttributeWithIndex::get(Idx, Attrs));
535     
536     // Copy attributes for arguments after this one.
537     NewAttrList.insert(NewAttrList.end(), 
538                        OldAttrList.begin()+i, OldAttrList.end());
539   }
540   
541   return get(NewAttrList);
542 }
543
544 AttrListPtr AttrListPtr::removeAttr(unsigned Idx, Attributes Attrs) const {
545 #ifndef NDEBUG
546   // FIXME it is not obvious how this should work for alignment.
547   // For now, say we can't pass in alignment, which no current use does.
548   assert(!Attrs.hasAttribute(Attributes::Alignment) &&
549          "Attempt to exclude alignment!");
550 #endif
551   if (AttrList == 0) return AttrListPtr();
552   
553   Attributes OldAttrs = getAttributes(Idx);
554   Attributes NewAttrs = OldAttrs & ~Attrs;
555   if (NewAttrs == OldAttrs)
556     return *this;
557
558   SmallVector<AttributeWithIndex, 8> NewAttrList;
559   const SmallVector<AttributeWithIndex, 4> &OldAttrList = AttrList->Attrs;
560   unsigned i = 0, e = OldAttrList.size();
561   
562   // Copy attributes for arguments before this one.
563   for (; i != e && OldAttrList[i].Index < Idx; ++i)
564     NewAttrList.push_back(OldAttrList[i]);
565   
566   // If there are attributes already at this index, merge them in.
567   assert(OldAttrList[i].Index == Idx && "Attribute isn't set?");
568   Attrs = OldAttrList[i].Attrs & ~Attrs;
569   ++i;
570   if (Attrs)  // If any attributes left for this parameter, add them.
571     NewAttrList.push_back(AttributeWithIndex::get(Idx, Attrs));
572   
573   // Copy attributes for arguments after this one.
574   NewAttrList.insert(NewAttrList.end(), 
575                      OldAttrList.begin()+i, OldAttrList.end());
576   
577   return get(NewAttrList);
578 }
579
580 void AttrListPtr::dump() const {
581   dbgs() << "PAL[ ";
582   for (unsigned i = 0; i < getNumSlots(); ++i) {
583     const AttributeWithIndex &PAWI = getSlot(i);
584     dbgs() << "{" << PAWI.Index << "," << PAWI.Attrs << "} ";
585   }
586   
587   dbgs() << "]\n";
588 }