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