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