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