IR: Split Metadata from Value
[oota-llvm.git] / include / llvm / IR / Value.h
1 //===-- llvm/Value.h - Definition of the Value class ------------*- C++ -*-===//
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 declares the Value class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #ifndef LLVM_IR_VALUE_H
15 #define LLVM_IR_VALUE_H
16
17 #include "llvm-c/Core.h"
18 #include "llvm/ADT/iterator_range.h"
19 #include "llvm/IR/Use.h"
20 #include "llvm/Support/CBindingWrapping.h"
21 #include "llvm/Support/Casting.h"
22 #include "llvm/Support/Compiler.h"
23
24 namespace llvm {
25
26 class APInt;
27 class Argument;
28 class AssemblyAnnotationWriter;
29 class BasicBlock;
30 class Constant;
31 class DataLayout;
32 class Function;
33 class GlobalAlias;
34 class GlobalObject;
35 class GlobalValue;
36 class GlobalVariable;
37 class InlineAsm;
38 class Instruction;
39 class LLVMContext;
40 class Module;
41 class StringRef;
42 class Twine;
43 class Type;
44 class ValueHandleBase;
45 class ValueSymbolTable;
46 class raw_ostream;
47
48 template<typename ValueTy> class StringMapEntry;
49 typedef StringMapEntry<Value*> ValueName;
50
51 //===----------------------------------------------------------------------===//
52 //                                 Value Class
53 //===----------------------------------------------------------------------===//
54
55 /// \brief LLVM Value Representation
56 ///
57 /// This is a very important LLVM class. It is the base class of all values
58 /// computed by a program that may be used as operands to other values. Value is
59 /// the super class of other important classes such as Instruction and Function.
60 /// All Values have a Type. Type is not a subclass of Value. Some values can
61 /// have a name and they belong to some Module.  Setting the name on the Value
62 /// automatically updates the module's symbol table.
63 ///
64 /// Every value has a "use list" that keeps track of which other Values are
65 /// using this Value.  A Value can also have an arbitrary number of ValueHandle
66 /// objects that watch it and listen to RAUW and Destroy events.  See
67 /// llvm/IR/ValueHandle.h for details.
68 class Value {
69   Type *VTy;
70   Use *UseList;
71
72   friend class ValueAsMetadata; // Allow access to NameAndIsUsedByMD.
73   friend class ValueHandleBase;
74   PointerIntPair<ValueName *, 1> NameAndIsUsedByMD;
75
76   const unsigned char SubclassID;   // Subclass identifier (for isa/dyn_cast)
77   unsigned char HasValueHandle : 1; // Has a ValueHandle pointing to this?
78 protected:
79   /// \brief Hold subclass data that can be dropped.
80   ///
81   /// This member is similar to SubclassData, however it is for holding
82   /// information which may be used to aid optimization, but which may be
83   /// cleared to zero without affecting conservative interpretation.
84   unsigned char SubclassOptionalData : 7;
85
86 private:
87   /// \brief Hold arbitrary subclass data.
88   ///
89   /// This member is defined by this class, but is not used for anything.
90   /// Subclasses can use it to hold whatever state they find useful.  This
91   /// field is initialized to zero by the ctor.
92   unsigned short SubclassData;
93
94 protected:
95   /// \brief The number of operands in the subclass.
96   ///
97   /// This member is defined by this class, but not used for anything.
98   /// Subclasses can use it to store their number of operands, if they have
99   /// any.
100   ///
101   /// This is stored here to save space in User on 64-bit hosts.  Since most
102   /// instances of Value have operands, 32-bit hosts aren't significantly
103   /// affected.
104   unsigned NumOperands;
105
106 private:
107   template <typename UseT> // UseT == 'Use' or 'const Use'
108   class use_iterator_impl
109       : public std::iterator<std::forward_iterator_tag, UseT *, ptrdiff_t> {
110     typedef std::iterator<std::forward_iterator_tag, UseT *, ptrdiff_t> super;
111
112     UseT *U;
113     explicit use_iterator_impl(UseT *u) : U(u) {}
114     friend class Value;
115
116   public:
117     typedef typename super::reference reference;
118     typedef typename super::pointer pointer;
119
120     use_iterator_impl() : U() {}
121
122     bool operator==(const use_iterator_impl &x) const { return U == x.U; }
123     bool operator!=(const use_iterator_impl &x) const { return !operator==(x); }
124
125     use_iterator_impl &operator++() { // Preincrement
126       assert(U && "Cannot increment end iterator!");
127       U = U->getNext();
128       return *this;
129     }
130     use_iterator_impl operator++(int) { // Postincrement
131       auto tmp = *this;
132       ++*this;
133       return tmp;
134     }
135
136     UseT &operator*() const {
137       assert(U && "Cannot dereference end iterator!");
138       return *U;
139     }
140
141     UseT *operator->() const { return &operator*(); }
142
143     operator use_iterator_impl<const UseT>() const {
144       return use_iterator_impl<const UseT>(U);
145     }
146   };
147
148   template <typename UserTy> // UserTy == 'User' or 'const User'
149   class user_iterator_impl
150       : public std::iterator<std::forward_iterator_tag, UserTy *, ptrdiff_t> {
151     typedef std::iterator<std::forward_iterator_tag, UserTy *, ptrdiff_t> super;
152
153     use_iterator_impl<Use> UI;
154     explicit user_iterator_impl(Use *U) : UI(U) {}
155     friend class Value;
156
157   public:
158     typedef typename super::reference reference;
159     typedef typename super::pointer pointer;
160
161     user_iterator_impl() {}
162
163     bool operator==(const user_iterator_impl &x) const { return UI == x.UI; }
164     bool operator!=(const user_iterator_impl &x) const { return !operator==(x); }
165
166     /// \brief Returns true if this iterator is equal to user_end() on the value.
167     bool atEnd() const { return *this == user_iterator_impl(); }
168
169     user_iterator_impl &operator++() { // Preincrement
170       ++UI;
171       return *this;
172     }
173     user_iterator_impl operator++(int) { // Postincrement
174       auto tmp = *this;
175       ++*this;
176       return tmp;
177     }
178
179     // Retrieve a pointer to the current User.
180     UserTy *operator*() const {
181       return UI->getUser();
182     }
183
184     UserTy *operator->() const { return operator*(); }
185
186     operator user_iterator_impl<const UserTy>() const {
187       return user_iterator_impl<const UserTy>(*UI);
188     }
189
190     Use &getUse() const { return *UI; }
191
192     /// \brief Return the operand # of this use in its User.
193     ///
194     /// FIXME: Replace all callers with a direct call to Use::getOperandNo.
195     unsigned getOperandNo() const { return UI->getOperandNo(); }
196   };
197
198   void operator=(const Value &) LLVM_DELETED_FUNCTION;
199   Value(const Value &) LLVM_DELETED_FUNCTION;
200
201 protected:
202   Value(Type *Ty, unsigned scid);
203 public:
204   virtual ~Value();
205
206   /// \brief Support for debugging, callable in GDB: V->dump()
207   void dump() const;
208
209   /// \brief Implement operator<< on Value.
210   void print(raw_ostream &O) const;
211
212   /// \brief Print the name of this Value out to the specified raw_ostream.
213   ///
214   /// This is useful when you just want to print 'int %reg126', not the
215   /// instruction that generated it. If you specify a Module for context, then
216   /// even constanst get pretty-printed; for example, the type of a null
217   /// pointer is printed symbolically.
218   void printAsOperand(raw_ostream &O, bool PrintType = true,
219                       const Module *M = nullptr) const;
220
221   /// \brief All values are typed, get the type of this value.
222   Type *getType() const { return VTy; }
223
224   /// \brief All values hold a context through their type.
225   LLVMContext &getContext() const;
226
227   // \brief All values can potentially be named.
228   bool hasName() const { return getValueName() != nullptr; }
229   ValueName *getValueName() const { return NameAndIsUsedByMD.getPointer(); }
230   void setValueName(ValueName *VN) { NameAndIsUsedByMD.setPointer(VN); }
231
232 private:
233   void destroyValueName();
234
235 public:
236   /// \brief Return a constant reference to the value's name.
237   ///
238   /// This is cheap and guaranteed to return the same reference as long as the
239   /// value is not modified.
240   StringRef getName() const;
241
242   /// \brief Change the name of the value.
243   ///
244   /// Choose a new unique name if the provided name is taken.
245   ///
246   /// \param Name The new name; or "" if the value's name should be removed.
247   void setName(const Twine &Name);
248
249
250   /// \brief Transfer the name from V to this value.
251   ///
252   /// After taking V's name, sets V's name to empty.
253   ///
254   /// \note It is an error to call V->takeName(V).
255   void takeName(Value *V);
256
257   /// \brief Change all uses of this to point to a new Value.
258   ///
259   /// Go through the uses list for this definition and make each use point to
260   /// "V" instead of "this".  After this completes, 'this's use list is
261   /// guaranteed to be empty.
262   void replaceAllUsesWith(Value *V);
263
264   /// replaceUsesOutsideBlock - Go through the uses list for this definition and
265   /// make each use point to "V" instead of "this" when the use is outside the
266   /// block. 'This's use list is expected to have at least one element.
267   /// Unlike replaceAllUsesWith this function does not support basic block
268   /// values or constant users.
269   void replaceUsesOutsideBlock(Value *V, BasicBlock *BB);
270
271   //----------------------------------------------------------------------
272   // Methods for handling the chain of uses of this Value.
273   //
274   bool               use_empty() const { return UseList == nullptr; }
275
276   typedef use_iterator_impl<Use>       use_iterator;
277   typedef use_iterator_impl<const Use> const_use_iterator;
278   use_iterator       use_begin()       { return use_iterator(UseList); }
279   const_use_iterator use_begin() const { return const_use_iterator(UseList); }
280   use_iterator       use_end()         { return use_iterator();   }
281   const_use_iterator use_end()   const { return const_use_iterator();   }
282   iterator_range<use_iterator> uses() {
283     return iterator_range<use_iterator>(use_begin(), use_end());
284   }
285   iterator_range<const_use_iterator> uses() const {
286     return iterator_range<const_use_iterator>(use_begin(), use_end());
287   }
288
289   typedef user_iterator_impl<User>       user_iterator;
290   typedef user_iterator_impl<const User> const_user_iterator;
291   user_iterator       user_begin()       { return user_iterator(UseList); }
292   const_user_iterator user_begin() const { return const_user_iterator(UseList); }
293   user_iterator       user_end()         { return user_iterator();   }
294   const_user_iterator user_end()   const { return const_user_iterator();   }
295   User               *user_back()        { return *user_begin(); }
296   const User         *user_back()  const { return *user_begin(); }
297   iterator_range<user_iterator> users() {
298     return iterator_range<user_iterator>(user_begin(), user_end());
299   }
300   iterator_range<const_user_iterator> users() const {
301     return iterator_range<const_user_iterator>(user_begin(), user_end());
302   }
303
304   /// \brief Return true if there is exactly one user of this value.
305   ///
306   /// This is specialized because it is a common request and does not require
307   /// traversing the whole use list.
308   bool hasOneUse() const {
309     const_use_iterator I = use_begin(), E = use_end();
310     if (I == E) return false;
311     return ++I == E;
312   }
313
314   /// \brief Return true if this Value has exactly N users.
315   bool hasNUses(unsigned N) const;
316
317   /// \brief Return true if this value has N users or more.
318   ///
319   /// This is logically equivalent to getNumUses() >= N.
320   bool hasNUsesOrMore(unsigned N) const;
321
322   /// \brief Check if this value is used in the specified basic block.
323   bool isUsedInBasicBlock(const BasicBlock *BB) const;
324
325   /// \brief This method computes the number of uses of this Value.
326   ///
327   /// This is a linear time operation.  Use hasOneUse, hasNUses, or
328   /// hasNUsesOrMore to check for specific values.
329   unsigned getNumUses() const;
330
331   /// \brief This method should only be used by the Use class.
332   void addUse(Use &U) { U.addToList(&UseList); }
333
334   /// \brief Concrete subclass of this.
335   ///
336   /// An enumeration for keeping track of the concrete subclass of Value that
337   /// is actually instantiated. Values of this enumeration are kept in the
338   /// Value classes SubclassID field. They are used for concrete type
339   /// identification.
340   enum ValueTy {
341     ArgumentVal,              // This is an instance of Argument
342     BasicBlockVal,            // This is an instance of BasicBlock
343     FunctionVal,              // This is an instance of Function
344     GlobalAliasVal,           // This is an instance of GlobalAlias
345     GlobalVariableVal,        // This is an instance of GlobalVariable
346     UndefValueVal,            // This is an instance of UndefValue
347     BlockAddressVal,          // This is an instance of BlockAddress
348     ConstantExprVal,          // This is an instance of ConstantExpr
349     ConstantAggregateZeroVal, // This is an instance of ConstantAggregateZero
350     ConstantDataArrayVal,     // This is an instance of ConstantDataArray
351     ConstantDataVectorVal,    // This is an instance of ConstantDataVector
352     ConstantIntVal,           // This is an instance of ConstantInt
353     ConstantFPVal,            // This is an instance of ConstantFP
354     ConstantArrayVal,         // This is an instance of ConstantArray
355     ConstantStructVal,        // This is an instance of ConstantStruct
356     ConstantVectorVal,        // This is an instance of ConstantVector
357     ConstantPointerNullVal,   // This is an instance of ConstantPointerNull
358     MetadataAsValueVal,       // This is an instance of MetadataAsValue
359     InlineAsmVal,             // This is an instance of InlineAsm
360     InstructionVal,           // This is an instance of Instruction
361     // Enum values starting at InstructionVal are used for Instructions;
362     // don't add new values here!
363
364     // Markers:
365     ConstantFirstVal = FunctionVal,
366     ConstantLastVal  = ConstantPointerNullVal
367   };
368
369   /// \brief Return an ID for the concrete type of this object.
370   ///
371   /// This is used to implement the classof checks.  This should not be used
372   /// for any other purpose, as the values may change as LLVM evolves.  Also,
373   /// note that for instructions, the Instruction's opcode is added to
374   /// InstructionVal. So this means three things:
375   /// # there is no value with code InstructionVal (no opcode==0).
376   /// # there are more possible values for the value type than in ValueTy enum.
377   /// # the InstructionVal enumerator must be the highest valued enumerator in
378   ///   the ValueTy enum.
379   unsigned getValueID() const {
380     return SubclassID;
381   }
382
383   /// \brief Return the raw optional flags value contained in this value.
384   ///
385   /// This should only be used when testing two Values for equivalence.
386   unsigned getRawSubclassOptionalData() const {
387     return SubclassOptionalData;
388   }
389
390   /// \brief Clear the optional flags contained in this value.
391   void clearSubclassOptionalData() {
392     SubclassOptionalData = 0;
393   }
394
395   /// \brief Check the optional flags for equality.
396   bool hasSameSubclassOptionalData(const Value *V) const {
397     return SubclassOptionalData == V->SubclassOptionalData;
398   }
399
400   /// \brief Clear any optional flags not set in the given Value.
401   void intersectOptionalDataWith(const Value *V) {
402     SubclassOptionalData &= V->SubclassOptionalData;
403   }
404
405   /// \brief Return true if there is a value handle associated with this value.
406   bool hasValueHandle() const { return HasValueHandle; }
407
408   /// \brief Return true if there is metadata referencing this value.
409   bool isUsedByMetadata() const { return NameAndIsUsedByMD.getInt(); }
410
411   /// \brief Strip off pointer casts, all-zero GEPs, and aliases.
412   ///
413   /// Returns the original uncasted value.  If this is called on a non-pointer
414   /// value, it returns 'this'.
415   Value *stripPointerCasts();
416   const Value *stripPointerCasts() const {
417     return const_cast<Value*>(this)->stripPointerCasts();
418   }
419
420   /// \brief Strip off pointer casts and all-zero GEPs.
421   ///
422   /// Returns the original uncasted value.  If this is called on a non-pointer
423   /// value, it returns 'this'.
424   Value *stripPointerCastsNoFollowAliases();
425   const Value *stripPointerCastsNoFollowAliases() const {
426     return const_cast<Value*>(this)->stripPointerCastsNoFollowAliases();
427   }
428
429   /// \brief Strip off pointer casts and all-constant inbounds GEPs.
430   ///
431   /// Returns the original pointer value.  If this is called on a non-pointer
432   /// value, it returns 'this'.
433   Value *stripInBoundsConstantOffsets();
434   const Value *stripInBoundsConstantOffsets() const {
435     return const_cast<Value*>(this)->stripInBoundsConstantOffsets();
436   }
437
438   /// \brief Accumulate offsets from \a stripInBoundsConstantOffsets().
439   ///
440   /// Stores the resulting constant offset stripped into the APInt provided.
441   /// The provided APInt will be extended or truncated as needed to be the
442   /// correct bitwidth for an offset of this pointer type.
443   ///
444   /// If this is called on a non-pointer value, it returns 'this'.
445   Value *stripAndAccumulateInBoundsConstantOffsets(const DataLayout &DL,
446                                                    APInt &Offset);
447   const Value *stripAndAccumulateInBoundsConstantOffsets(const DataLayout &DL,
448                                                          APInt &Offset) const {
449     return const_cast<Value *>(this)
450         ->stripAndAccumulateInBoundsConstantOffsets(DL, Offset);
451   }
452
453   /// \brief Strip off pointer casts and inbounds GEPs.
454   ///
455   /// Returns the original pointer value.  If this is called on a non-pointer
456   /// value, it returns 'this'.
457   Value *stripInBoundsOffsets();
458   const Value *stripInBoundsOffsets() const {
459     return const_cast<Value*>(this)->stripInBoundsOffsets();
460   }
461
462   /// \brief Check if this is always a dereferenceable pointer.
463   ///
464   /// Test if this value is always a pointer to allocated and suitably aligned
465   /// memory for a simple load or store.
466   bool isDereferenceablePointer(const DataLayout *DL = nullptr) const;
467
468   /// \brief Translate PHI node to its predecessor from the given basic block.
469   ///
470   /// If this value is a PHI node with CurBB as its parent, return the value in
471   /// the PHI node corresponding to PredBB.  If not, return ourself.  This is
472   /// useful if you want to know the value something has in a predecessor
473   /// block.
474   Value *DoPHITranslation(const BasicBlock *CurBB, const BasicBlock *PredBB);
475
476   const Value *DoPHITranslation(const BasicBlock *CurBB,
477                                 const BasicBlock *PredBB) const{
478     return const_cast<Value*>(this)->DoPHITranslation(CurBB, PredBB);
479   }
480
481   /// \brief The maximum alignment for instructions.
482   ///
483   /// This is the greatest alignment value supported by load, store, and alloca
484   /// instructions, and global values.
485   static const unsigned MaximumAlignment = 1u << 29;
486
487   /// \brief Mutate the type of this Value to be of the specified type.
488   ///
489   /// Note that this is an extremely dangerous operation which can create
490   /// completely invalid IR very easily.  It is strongly recommended that you
491   /// recreate IR objects with the right types instead of mutating them in
492   /// place.
493   void mutateType(Type *Ty) {
494     VTy = Ty;
495   }
496
497   /// \brief Sort the use-list.
498   ///
499   /// Sorts the Value's use-list by Cmp using a stable mergesort.  Cmp is
500   /// expected to compare two \a Use references.
501   template <class Compare> void sortUseList(Compare Cmp);
502
503   /// \brief Reverse the use-list.
504   void reverseUseList();
505
506 private:
507   /// \brief Merge two lists together.
508   ///
509   /// Merges \c L and \c R using \c Cmp.  To enable stable sorts, always pushes
510   /// "equal" items from L before items from R.
511   ///
512   /// \return the first element in the list.
513   ///
514   /// \note Completely ignores \a Use::Prev (doesn't read, doesn't update).
515   template <class Compare>
516   static Use *mergeUseLists(Use *L, Use *R, Compare Cmp) {
517     Use *Merged;
518     mergeUseListsImpl(L, R, &Merged, Cmp);
519     return Merged;
520   }
521
522   /// \brief Tail-recursive helper for \a mergeUseLists().
523   ///
524   /// \param[out] Next the first element in the list.
525   template <class Compare>
526   static void mergeUseListsImpl(Use *L, Use *R, Use **Next, Compare Cmp);
527
528 protected:
529   unsigned short getSubclassDataFromValue() const { return SubclassData; }
530   void setValueSubclassData(unsigned short D) { SubclassData = D; }
531 };
532
533 inline raw_ostream &operator<<(raw_ostream &OS, const Value &V) {
534   V.print(OS);
535   return OS;
536 }
537
538 void Use::set(Value *V) {
539   if (Val) removeFromList();
540   Val = V;
541   if (V) V->addUse(*this);
542 }
543
544 template <class Compare> void Value::sortUseList(Compare Cmp) {
545   if (!UseList || !UseList->Next)
546     // No need to sort 0 or 1 uses.
547     return;
548
549   // Note: this function completely ignores Prev pointers until the end when
550   // they're fixed en masse.
551
552   // Create a binomial vector of sorted lists, visiting uses one at a time and
553   // merging lists as necessary.
554   const unsigned MaxSlots = 32;
555   Use *Slots[MaxSlots];
556
557   // Collect the first use, turning it into a single-item list.
558   Use *Next = UseList->Next;
559   UseList->Next = nullptr;
560   unsigned NumSlots = 1;
561   Slots[0] = UseList;
562
563   // Collect all but the last use.
564   while (Next->Next) {
565     Use *Current = Next;
566     Next = Current->Next;
567
568     // Turn Current into a single-item list.
569     Current->Next = nullptr;
570
571     // Save Current in the first available slot, merging on collisions.
572     unsigned I;
573     for (I = 0; I < NumSlots; ++I) {
574       if (!Slots[I])
575         break;
576
577       // Merge two lists, doubling the size of Current and emptying slot I.
578       //
579       // Since the uses in Slots[I] originally preceded those in Current, send
580       // Slots[I] in as the left parameter to maintain a stable sort.
581       Current = mergeUseLists(Slots[I], Current, Cmp);
582       Slots[I] = nullptr;
583     }
584     // Check if this is a new slot.
585     if (I == NumSlots) {
586       ++NumSlots;
587       assert(NumSlots <= MaxSlots && "Use list bigger than 2^32");
588     }
589
590     // Found an open slot.
591     Slots[I] = Current;
592   }
593
594   // Merge all the lists together.
595   assert(Next && "Expected one more Use");
596   assert(!Next->Next && "Expected only one Use");
597   UseList = Next;
598   for (unsigned I = 0; I < NumSlots; ++I)
599     if (Slots[I])
600       // Since the uses in Slots[I] originally preceded those in UseList, send
601       // Slots[I] in as the left parameter to maintain a stable sort.
602       UseList = mergeUseLists(Slots[I], UseList, Cmp);
603
604   // Fix the Prev pointers.
605   for (Use *I = UseList, **Prev = &UseList; I; I = I->Next) {
606     I->setPrev(Prev);
607     Prev = &I->Next;
608   }
609 }
610
611 template <class Compare>
612 void Value::mergeUseListsImpl(Use *L, Use *R, Use **Next, Compare Cmp) {
613   if (!L) {
614     *Next = R;
615     return;
616   }
617   if (!R) {
618     *Next = L;
619     return;
620   }
621   if (Cmp(*R, *L)) {
622     *Next = R;
623     mergeUseListsImpl(L, R->Next, &R->Next, Cmp);
624     return;
625   }
626   *Next = L;
627   mergeUseListsImpl(L->Next, R, &L->Next, Cmp);
628 }
629
630 // isa - Provide some specializations of isa so that we don't have to include
631 // the subtype header files to test to see if the value is a subclass...
632 //
633 template <> struct isa_impl<Constant, Value> {
634   static inline bool doit(const Value &Val) {
635     return Val.getValueID() >= Value::ConstantFirstVal &&
636       Val.getValueID() <= Value::ConstantLastVal;
637   }
638 };
639
640 template <> struct isa_impl<Argument, Value> {
641   static inline bool doit (const Value &Val) {
642     return Val.getValueID() == Value::ArgumentVal;
643   }
644 };
645
646 template <> struct isa_impl<InlineAsm, Value> {
647   static inline bool doit(const Value &Val) {
648     return Val.getValueID() == Value::InlineAsmVal;
649   }
650 };
651
652 template <> struct isa_impl<Instruction, Value> {
653   static inline bool doit(const Value &Val) {
654     return Val.getValueID() >= Value::InstructionVal;
655   }
656 };
657
658 template <> struct isa_impl<BasicBlock, Value> {
659   static inline bool doit(const Value &Val) {
660     return Val.getValueID() == Value::BasicBlockVal;
661   }
662 };
663
664 template <> struct isa_impl<Function, Value> {
665   static inline bool doit(const Value &Val) {
666     return Val.getValueID() == Value::FunctionVal;
667   }
668 };
669
670 template <> struct isa_impl<GlobalVariable, Value> {
671   static inline bool doit(const Value &Val) {
672     return Val.getValueID() == Value::GlobalVariableVal;
673   }
674 };
675
676 template <> struct isa_impl<GlobalAlias, Value> {
677   static inline bool doit(const Value &Val) {
678     return Val.getValueID() == Value::GlobalAliasVal;
679   }
680 };
681
682 template <> struct isa_impl<GlobalValue, Value> {
683   static inline bool doit(const Value &Val) {
684     return isa<GlobalObject>(Val) || isa<GlobalAlias>(Val);
685   }
686 };
687
688 template <> struct isa_impl<GlobalObject, Value> {
689   static inline bool doit(const Value &Val) {
690     return isa<GlobalVariable>(Val) || isa<Function>(Val);
691   }
692 };
693
694 // Value* is only 4-byte aligned.
695 template<>
696 class PointerLikeTypeTraits<Value*> {
697   typedef Value* PT;
698 public:
699   static inline void *getAsVoidPointer(PT P) { return P; }
700   static inline PT getFromVoidPointer(void *P) {
701     return static_cast<PT>(P);
702   }
703   enum { NumLowBitsAvailable = 2 };
704 };
705
706 // Create wrappers for C Binding types (see CBindingWrapping.h).
707 DEFINE_ISA_CONVERSION_FUNCTIONS(Value, LLVMValueRef)
708
709 /* Specialized opaque value conversions.
710  */
711 inline Value **unwrap(LLVMValueRef *Vals) {
712   return reinterpret_cast<Value**>(Vals);
713 }
714
715 template<typename T>
716 inline T **unwrap(LLVMValueRef *Vals, unsigned Length) {
717 #ifdef DEBUG
718   for (LLVMValueRef *I = Vals, *E = Vals + Length; I != E; ++I)
719     cast<T>(*I);
720 #endif
721   (void)Length;
722   return reinterpret_cast<T**>(Vals);
723 }
724
725 inline LLVMValueRef *wrap(const Value **Vals) {
726   return reinterpret_cast<LLVMValueRef*>(const_cast<Value**>(Vals));
727 }
728
729 } // End llvm namespace
730
731 #endif