Add in the first iteration of support for llvm/clang/lldb to allow variable per addre...
[oota-llvm.git] / include / llvm / Instructions.h
1 //===-- llvm/Instructions.h - Instruction subclass definitions --*- 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 exposes the class definitions of all of the subclasses of the
11 // Instruction class.  This is meant to be an easy way to get access to all
12 // instruction subclasses.
13 //
14 //===----------------------------------------------------------------------===//
15
16 #ifndef LLVM_INSTRUCTIONS_H
17 #define LLVM_INSTRUCTIONS_H
18
19 #include "llvm/InstrTypes.h"
20 #include "llvm/DerivedTypes.h"
21 #include "llvm/Attributes.h"
22 #include "llvm/CallingConv.h"
23 #include "llvm/Support/IntegersSubset.h"
24 #include "llvm/Support/IntegersSubsetMapping.h"
25 #include "llvm/ADT/ArrayRef.h"
26 #include "llvm/ADT/SmallVector.h"
27 #include "llvm/Support/ErrorHandling.h"
28 #include <iterator>
29
30 namespace llvm {
31
32 class ConstantInt;
33 class ConstantRange;
34 class APInt;
35 class LLVMContext;
36
37 enum AtomicOrdering {
38   NotAtomic = 0,
39   Unordered = 1,
40   Monotonic = 2,
41   // Consume = 3,  // Not specified yet.
42   Acquire = 4,
43   Release = 5,
44   AcquireRelease = 6,
45   SequentiallyConsistent = 7
46 };
47
48 enum SynchronizationScope {
49   SingleThread = 0,
50   CrossThread = 1
51 };
52
53 //===----------------------------------------------------------------------===//
54 //                                AllocaInst Class
55 //===----------------------------------------------------------------------===//
56
57 /// AllocaInst - an instruction to allocate memory on the stack
58 ///
59 class AllocaInst : public UnaryInstruction {
60 protected:
61   virtual AllocaInst *clone_impl() const;
62 public:
63   explicit AllocaInst(Type *Ty, Value *ArraySize = 0,
64                       const Twine &Name = "", Instruction *InsertBefore = 0);
65   AllocaInst(Type *Ty, Value *ArraySize,
66              const Twine &Name, BasicBlock *InsertAtEnd);
67
68   AllocaInst(Type *Ty, const Twine &Name, Instruction *InsertBefore = 0);
69   AllocaInst(Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd);
70
71   AllocaInst(Type *Ty, Value *ArraySize, unsigned Align,
72              const Twine &Name = "", Instruction *InsertBefore = 0);
73   AllocaInst(Type *Ty, Value *ArraySize, unsigned Align,
74              const Twine &Name, BasicBlock *InsertAtEnd);
75
76   // Out of line virtual method, so the vtable, etc. has a home.
77   virtual ~AllocaInst();
78
79   /// isArrayAllocation - Return true if there is an allocation size parameter
80   /// to the allocation instruction that is not 1.
81   ///
82   bool isArrayAllocation() const;
83
84   /// getArraySize - Get the number of elements allocated. For a simple
85   /// allocation of a single element, this will return a constant 1 value.
86   ///
87   const Value *getArraySize() const { return getOperand(0); }
88   Value *getArraySize() { return getOperand(0); }
89
90   /// getType - Overload to return most specific pointer type
91   ///
92   PointerType *getType() const {
93     return reinterpret_cast<PointerType*>(Instruction::getType());
94   }
95
96   /// getAllocatedType - Return the type that is being allocated by the
97   /// instruction.
98   ///
99   Type *getAllocatedType() const;
100
101   /// getAlignment - Return the alignment of the memory that is being allocated
102   /// by the instruction.
103   ///
104   unsigned getAlignment() const {
105     return (1u << getSubclassDataFromInstruction()) >> 1;
106   }
107   void setAlignment(unsigned Align);
108
109   /// isStaticAlloca - Return true if this alloca is in the entry block of the
110   /// function and is a constant size.  If so, the code generator will fold it
111   /// into the prolog/epilog code, so it is basically free.
112   bool isStaticAlloca() const;
113
114   // Methods for support type inquiry through isa, cast, and dyn_cast:
115   static inline bool classof(const AllocaInst *) { return true; }
116   static inline bool classof(const Instruction *I) {
117     return (I->getOpcode() == Instruction::Alloca);
118   }
119   static inline bool classof(const Value *V) {
120     return isa<Instruction>(V) && classof(cast<Instruction>(V));
121   }
122 private:
123   // Shadow Instruction::setInstructionSubclassData with a private forwarding
124   // method so that subclasses cannot accidentally use it.
125   void setInstructionSubclassData(unsigned short D) {
126     Instruction::setInstructionSubclassData(D);
127   }
128 };
129
130
131 //===----------------------------------------------------------------------===//
132 //                                LoadInst Class
133 //===----------------------------------------------------------------------===//
134
135 /// LoadInst - an instruction for reading from memory.  This uses the
136 /// SubclassData field in Value to store whether or not the load is volatile.
137 ///
138 class LoadInst : public UnaryInstruction {
139   void AssertOK();
140 protected:
141   virtual LoadInst *clone_impl() const;
142 public:
143   LoadInst(Value *Ptr, const Twine &NameStr, Instruction *InsertBefore);
144   LoadInst(Value *Ptr, const Twine &NameStr, BasicBlock *InsertAtEnd);
145   LoadInst(Value *Ptr, const Twine &NameStr, bool isVolatile = false,
146            Instruction *InsertBefore = 0);
147   LoadInst(Value *Ptr, const Twine &NameStr, bool isVolatile,
148            BasicBlock *InsertAtEnd);
149   LoadInst(Value *Ptr, const Twine &NameStr, bool isVolatile,
150            unsigned Align, Instruction *InsertBefore = 0);
151   LoadInst(Value *Ptr, const Twine &NameStr, bool isVolatile,
152            unsigned Align, BasicBlock *InsertAtEnd);
153   LoadInst(Value *Ptr, const Twine &NameStr, bool isVolatile,
154            unsigned Align, AtomicOrdering Order,
155            SynchronizationScope SynchScope = CrossThread,
156            Instruction *InsertBefore = 0);
157   LoadInst(Value *Ptr, const Twine &NameStr, bool isVolatile,
158            unsigned Align, AtomicOrdering Order,
159            SynchronizationScope SynchScope,
160            BasicBlock *InsertAtEnd);
161
162   LoadInst(Value *Ptr, const char *NameStr, Instruction *InsertBefore);
163   LoadInst(Value *Ptr, const char *NameStr, BasicBlock *InsertAtEnd);
164   explicit LoadInst(Value *Ptr, const char *NameStr = 0,
165                     bool isVolatile = false,  Instruction *InsertBefore = 0);
166   LoadInst(Value *Ptr, const char *NameStr, bool isVolatile,
167            BasicBlock *InsertAtEnd);
168
169   /// isVolatile - Return true if this is a load from a volatile memory
170   /// location.
171   ///
172   bool isVolatile() const { return getSubclassDataFromInstruction() & 1; }
173
174   /// setVolatile - Specify whether this is a volatile load or not.
175   ///
176   void setVolatile(bool V) {
177     setInstructionSubclassData((getSubclassDataFromInstruction() & ~1) |
178                                (V ? 1 : 0));
179   }
180
181   /// getAlignment - Return the alignment of the access that is being performed
182   ///
183   unsigned getAlignment() const {
184     return (1 << ((getSubclassDataFromInstruction() >> 1) & 31)) >> 1;
185   }
186
187   void setAlignment(unsigned Align);
188
189   /// Returns the ordering effect of this fence.
190   AtomicOrdering getOrdering() const {
191     return AtomicOrdering((getSubclassDataFromInstruction() >> 7) & 7);
192   }
193
194   /// Set the ordering constraint on this load. May not be Release or
195   /// AcquireRelease.
196   void setOrdering(AtomicOrdering Ordering) {
197     setInstructionSubclassData((getSubclassDataFromInstruction() & ~(7 << 7)) |
198                                (Ordering << 7));
199   }
200
201   SynchronizationScope getSynchScope() const {
202     return SynchronizationScope((getSubclassDataFromInstruction() >> 6) & 1);
203   }
204
205   /// Specify whether this load is ordered with respect to all
206   /// concurrently executing threads, or only with respect to signal handlers
207   /// executing in the same thread.
208   void setSynchScope(SynchronizationScope xthread) {
209     setInstructionSubclassData((getSubclassDataFromInstruction() & ~(1 << 6)) |
210                                (xthread << 6));
211   }
212
213   bool isAtomic() const { return getOrdering() != NotAtomic; }
214   void setAtomic(AtomicOrdering Ordering,
215                  SynchronizationScope SynchScope = CrossThread) {
216     setOrdering(Ordering);
217     setSynchScope(SynchScope);
218   }
219
220   bool isSimple() const { return !isAtomic() && !isVolatile(); }
221   bool isUnordered() const {
222     return getOrdering() <= Unordered && !isVolatile();
223   }
224
225   Value *getPointerOperand() { return getOperand(0); }
226   const Value *getPointerOperand() const { return getOperand(0); }
227   static unsigned getPointerOperandIndex() { return 0U; }
228
229   unsigned getPointerAddressSpace() const {
230     return cast<PointerType>(getPointerOperand()->getType())->getAddressSpace();
231   }
232
233
234   // Methods for support type inquiry through isa, cast, and dyn_cast:
235   static inline bool classof(const LoadInst *) { return true; }
236   static inline bool classof(const Instruction *I) {
237     return I->getOpcode() == Instruction::Load;
238   }
239   static inline bool classof(const Value *V) {
240     return isa<Instruction>(V) && classof(cast<Instruction>(V));
241   }
242 private:
243   // Shadow Instruction::setInstructionSubclassData with a private forwarding
244   // method so that subclasses cannot accidentally use it.
245   void setInstructionSubclassData(unsigned short D) {
246     Instruction::setInstructionSubclassData(D);
247   }
248 };
249
250
251 //===----------------------------------------------------------------------===//
252 //                                StoreInst Class
253 //===----------------------------------------------------------------------===//
254
255 /// StoreInst - an instruction for storing to memory
256 ///
257 class StoreInst : public Instruction {
258   void *operator new(size_t, unsigned) LLVM_DELETED_FUNCTION;
259   void AssertOK();
260 protected:
261   virtual StoreInst *clone_impl() const;
262 public:
263   // allocate space for exactly two operands
264   void *operator new(size_t s) {
265     return User::operator new(s, 2);
266   }
267   StoreInst(Value *Val, Value *Ptr, Instruction *InsertBefore);
268   StoreInst(Value *Val, Value *Ptr, BasicBlock *InsertAtEnd);
269   StoreInst(Value *Val, Value *Ptr, bool isVolatile = false,
270             Instruction *InsertBefore = 0);
271   StoreInst(Value *Val, Value *Ptr, bool isVolatile, BasicBlock *InsertAtEnd);
272   StoreInst(Value *Val, Value *Ptr, bool isVolatile,
273             unsigned Align, Instruction *InsertBefore = 0);
274   StoreInst(Value *Val, Value *Ptr, bool isVolatile,
275             unsigned Align, BasicBlock *InsertAtEnd);
276   StoreInst(Value *Val, Value *Ptr, bool isVolatile,
277             unsigned Align, AtomicOrdering Order,
278             SynchronizationScope SynchScope = CrossThread,
279             Instruction *InsertBefore = 0);
280   StoreInst(Value *Val, Value *Ptr, bool isVolatile,
281             unsigned Align, AtomicOrdering Order,
282             SynchronizationScope SynchScope,
283             BasicBlock *InsertAtEnd);
284           
285
286   /// isVolatile - Return true if this is a store to a volatile memory
287   /// location.
288   ///
289   bool isVolatile() const { return getSubclassDataFromInstruction() & 1; }
290
291   /// setVolatile - Specify whether this is a volatile store or not.
292   ///
293   void setVolatile(bool V) {
294     setInstructionSubclassData((getSubclassDataFromInstruction() & ~1) |
295                                (V ? 1 : 0));
296   }
297
298   /// Transparently provide more efficient getOperand methods.
299   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
300
301   /// getAlignment - Return the alignment of the access that is being performed
302   ///
303   unsigned getAlignment() const {
304     return (1 << ((getSubclassDataFromInstruction() >> 1) & 31)) >> 1;
305   }
306
307   void setAlignment(unsigned Align);
308
309   /// Returns the ordering effect of this store.
310   AtomicOrdering getOrdering() const {
311     return AtomicOrdering((getSubclassDataFromInstruction() >> 7) & 7);
312   }
313
314   /// Set the ordering constraint on this store.  May not be Acquire or
315   /// AcquireRelease.
316   void setOrdering(AtomicOrdering Ordering) {
317     setInstructionSubclassData((getSubclassDataFromInstruction() & ~(7 << 7)) |
318                                (Ordering << 7));
319   }
320
321   SynchronizationScope getSynchScope() const {
322     return SynchronizationScope((getSubclassDataFromInstruction() >> 6) & 1);
323   }
324
325   /// Specify whether this store instruction is ordered with respect to all
326   /// concurrently executing threads, or only with respect to signal handlers
327   /// executing in the same thread.
328   void setSynchScope(SynchronizationScope xthread) {
329     setInstructionSubclassData((getSubclassDataFromInstruction() & ~(1 << 6)) |
330                                (xthread << 6));
331   }
332
333   bool isAtomic() const { return getOrdering() != NotAtomic; }
334   void setAtomic(AtomicOrdering Ordering,
335                  SynchronizationScope SynchScope = CrossThread) {
336     setOrdering(Ordering);
337     setSynchScope(SynchScope);
338   }
339
340   bool isSimple() const { return !isAtomic() && !isVolatile(); }
341   bool isUnordered() const {
342     return getOrdering() <= Unordered && !isVolatile();
343   }
344
345   Value *getValueOperand() { return getOperand(0); }
346   const Value *getValueOperand() const { return getOperand(0); }
347
348   Value *getPointerOperand() { return getOperand(1); }
349   const Value *getPointerOperand() const { return getOperand(1); }
350   static unsigned getPointerOperandIndex() { return 1U; }
351
352   unsigned getPointerAddressSpace() const {
353     if (getPointerOperand()->getType()->isPointerTy())
354       return cast<PointerType>(getPointerOperand()->getType())
355         ->getAddressSpace();
356     if (getPointerOperand()->getType()->isVectorTy()
357         && cast<VectorType>(getPointerOperand()->getType())->isPointerTy())
358       return cast<PointerType>(cast<VectorType>(
359             getPointerOperand()->getType())->getElementType())
360         ->getAddressSpace();
361     llvm_unreachable("Only a vector of pointers or pointers can be used!");
362     return 0;
363   }
364
365   // Methods for support type inquiry through isa, cast, and dyn_cast:
366   static inline bool classof(const StoreInst *) { return true; }
367   static inline bool classof(const Instruction *I) {
368     return I->getOpcode() == Instruction::Store;
369   }
370   static inline bool classof(const Value *V) {
371     return isa<Instruction>(V) && classof(cast<Instruction>(V));
372   }
373 private:
374   // Shadow Instruction::setInstructionSubclassData with a private forwarding
375   // method so that subclasses cannot accidentally use it.
376   void setInstructionSubclassData(unsigned short D) {
377     Instruction::setInstructionSubclassData(D);
378   }
379 };
380
381 template <>
382 struct OperandTraits<StoreInst> : public FixedNumOperandTraits<StoreInst, 2> {
383 };
384
385 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(StoreInst, Value)
386
387 //===----------------------------------------------------------------------===//
388 //                                FenceInst Class
389 //===----------------------------------------------------------------------===//
390
391 /// FenceInst - an instruction for ordering other memory operations
392 ///
393 class FenceInst : public Instruction {
394   void *operator new(size_t, unsigned) LLVM_DELETED_FUNCTION;
395   void Init(AtomicOrdering Ordering, SynchronizationScope SynchScope);
396 protected:
397   virtual FenceInst *clone_impl() const;
398 public:
399   // allocate space for exactly zero operands
400   void *operator new(size_t s) {
401     return User::operator new(s, 0);
402   }
403
404   // Ordering may only be Acquire, Release, AcquireRelease, or
405   // SequentiallyConsistent.
406   FenceInst(LLVMContext &C, AtomicOrdering Ordering,
407             SynchronizationScope SynchScope = CrossThread,
408             Instruction *InsertBefore = 0);
409   FenceInst(LLVMContext &C, AtomicOrdering Ordering,
410             SynchronizationScope SynchScope,
411             BasicBlock *InsertAtEnd);
412
413   /// Returns the ordering effect of this fence.
414   AtomicOrdering getOrdering() const {
415     return AtomicOrdering(getSubclassDataFromInstruction() >> 1);
416   }
417
418   /// Set the ordering constraint on this fence.  May only be Acquire, Release,
419   /// AcquireRelease, or SequentiallyConsistent.
420   void setOrdering(AtomicOrdering Ordering) {
421     setInstructionSubclassData((getSubclassDataFromInstruction() & 1) |
422                                (Ordering << 1));
423   }
424
425   SynchronizationScope getSynchScope() const {
426     return SynchronizationScope(getSubclassDataFromInstruction() & 1);
427   }
428
429   /// Specify whether this fence orders other operations with respect to all
430   /// concurrently executing threads, or only with respect to signal handlers
431   /// executing in the same thread.
432   void setSynchScope(SynchronizationScope xthread) {
433     setInstructionSubclassData((getSubclassDataFromInstruction() & ~1) |
434                                xthread);
435   }
436
437   // Methods for support type inquiry through isa, cast, and dyn_cast:
438   static inline bool classof(const FenceInst *) { return true; }
439   static inline bool classof(const Instruction *I) {
440     return I->getOpcode() == Instruction::Fence;
441   }
442   static inline bool classof(const Value *V) {
443     return isa<Instruction>(V) && classof(cast<Instruction>(V));
444   }
445 private:
446   // Shadow Instruction::setInstructionSubclassData with a private forwarding
447   // method so that subclasses cannot accidentally use it.
448   void setInstructionSubclassData(unsigned short D) {
449     Instruction::setInstructionSubclassData(D);
450   }
451 };
452
453 //===----------------------------------------------------------------------===//
454 //                                AtomicCmpXchgInst Class
455 //===----------------------------------------------------------------------===//
456
457 /// AtomicCmpXchgInst - an instruction that atomically checks whether a
458 /// specified value is in a memory location, and, if it is, stores a new value
459 /// there.  Returns the value that was loaded.
460 ///
461 class AtomicCmpXchgInst : public Instruction {
462   void *operator new(size_t, unsigned) LLVM_DELETED_FUNCTION;
463   void Init(Value *Ptr, Value *Cmp, Value *NewVal,
464             AtomicOrdering Ordering, SynchronizationScope SynchScope);
465 protected:
466   virtual AtomicCmpXchgInst *clone_impl() const;
467 public:
468   // allocate space for exactly three operands
469   void *operator new(size_t s) {
470     return User::operator new(s, 3);
471   }
472   AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal,
473                     AtomicOrdering Ordering, SynchronizationScope SynchScope,
474                     Instruction *InsertBefore = 0);
475   AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal,
476                     AtomicOrdering Ordering, SynchronizationScope SynchScope,
477                     BasicBlock *InsertAtEnd);
478
479   /// isVolatile - Return true if this is a cmpxchg from a volatile memory
480   /// location.
481   ///
482   bool isVolatile() const {
483     return getSubclassDataFromInstruction() & 1;
484   }
485
486   /// setVolatile - Specify whether this is a volatile cmpxchg.
487   ///
488   void setVolatile(bool V) {
489      setInstructionSubclassData((getSubclassDataFromInstruction() & ~1) |
490                                 (unsigned)V);
491   }
492
493   /// Transparently provide more efficient getOperand methods.
494   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
495
496   /// Set the ordering constraint on this cmpxchg.
497   void setOrdering(AtomicOrdering Ordering) {
498     assert(Ordering != NotAtomic &&
499            "CmpXchg instructions can only be atomic.");
500     setInstructionSubclassData((getSubclassDataFromInstruction() & 3) |
501                                (Ordering << 2));
502   }
503
504   /// Specify whether this cmpxchg is atomic and orders other operations with
505   /// respect to all concurrently executing threads, or only with respect to
506   /// signal handlers executing in the same thread.
507   void setSynchScope(SynchronizationScope SynchScope) {
508     setInstructionSubclassData((getSubclassDataFromInstruction() & ~2) |
509                                (SynchScope << 1));
510   }
511
512   /// Returns the ordering constraint on this cmpxchg.
513   AtomicOrdering getOrdering() const {
514     return AtomicOrdering(getSubclassDataFromInstruction() >> 2);
515   }
516
517   /// Returns whether this cmpxchg is atomic between threads or only within a
518   /// single thread.
519   SynchronizationScope getSynchScope() const {
520     return SynchronizationScope((getSubclassDataFromInstruction() & 2) >> 1);
521   }
522
523   Value *getPointerOperand() { return getOperand(0); }
524   const Value *getPointerOperand() const { return getOperand(0); }
525   static unsigned getPointerOperandIndex() { return 0U; }
526
527   Value *getCompareOperand() { return getOperand(1); }
528   const Value *getCompareOperand() const { return getOperand(1); }
529   
530   Value *getNewValOperand() { return getOperand(2); }
531   const Value *getNewValOperand() const { return getOperand(2); }
532   
533   unsigned getPointerAddressSpace() const {
534     return cast<PointerType>(getPointerOperand()->getType())->getAddressSpace();
535   }
536   
537   // Methods for support type inquiry through isa, cast, and dyn_cast:
538   static inline bool classof(const AtomicCmpXchgInst *) { return true; }
539   static inline bool classof(const Instruction *I) {
540     return I->getOpcode() == Instruction::AtomicCmpXchg;
541   }
542   static inline bool classof(const Value *V) {
543     return isa<Instruction>(V) && classof(cast<Instruction>(V));
544   }
545 private:
546   // Shadow Instruction::setInstructionSubclassData with a private forwarding
547   // method so that subclasses cannot accidentally use it.
548   void setInstructionSubclassData(unsigned short D) {
549     Instruction::setInstructionSubclassData(D);
550   }
551 };
552
553 template <>
554 struct OperandTraits<AtomicCmpXchgInst> :
555     public FixedNumOperandTraits<AtomicCmpXchgInst, 3> {
556 };
557
558 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(AtomicCmpXchgInst, Value)
559
560 //===----------------------------------------------------------------------===//
561 //                                AtomicRMWInst Class
562 //===----------------------------------------------------------------------===//
563
564 /// AtomicRMWInst - an instruction that atomically reads a memory location,
565 /// combines it with another value, and then stores the result back.  Returns
566 /// the old value.
567 ///
568 class AtomicRMWInst : public Instruction {
569   void *operator new(size_t, unsigned) LLVM_DELETED_FUNCTION;
570 protected:
571   virtual AtomicRMWInst *clone_impl() const;
572 public:
573   /// This enumeration lists the possible modifications atomicrmw can make.  In
574   /// the descriptions, 'p' is the pointer to the instruction's memory location,
575   /// 'old' is the initial value of *p, and 'v' is the other value passed to the
576   /// instruction.  These instructions always return 'old'.
577   enum BinOp {
578     /// *p = v
579     Xchg,
580     /// *p = old + v
581     Add,
582     /// *p = old - v
583     Sub,
584     /// *p = old & v
585     And,
586     /// *p = ~old & v
587     Nand,
588     /// *p = old | v
589     Or,
590     /// *p = old ^ v
591     Xor,
592     /// *p = old >signed v ? old : v
593     Max,
594     /// *p = old <signed v ? old : v
595     Min,
596     /// *p = old >unsigned v ? old : v
597     UMax,
598     /// *p = old <unsigned v ? old : v
599     UMin,
600
601     FIRST_BINOP = Xchg,
602     LAST_BINOP = UMin,
603     BAD_BINOP
604   };
605
606   // allocate space for exactly two operands
607   void *operator new(size_t s) {
608     return User::operator new(s, 2);
609   }
610   AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val,
611                 AtomicOrdering Ordering, SynchronizationScope SynchScope,
612                 Instruction *InsertBefore = 0);
613   AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val,
614                 AtomicOrdering Ordering, SynchronizationScope SynchScope,
615                 BasicBlock *InsertAtEnd);
616
617   BinOp getOperation() const {
618     return static_cast<BinOp>(getSubclassDataFromInstruction() >> 5);
619   }
620
621   void setOperation(BinOp Operation) {
622     unsigned short SubclassData = getSubclassDataFromInstruction();
623     setInstructionSubclassData((SubclassData & 31) |
624                                (Operation << 5));
625   }
626
627   /// isVolatile - Return true if this is a RMW on a volatile memory location.
628   ///
629   bool isVolatile() const {
630     return getSubclassDataFromInstruction() & 1;
631   }
632
633   /// setVolatile - Specify whether this is a volatile RMW or not.
634   ///
635   void setVolatile(bool V) {
636      setInstructionSubclassData((getSubclassDataFromInstruction() & ~1) |
637                                 (unsigned)V);
638   }
639
640   /// Transparently provide more efficient getOperand methods.
641   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
642
643   /// Set the ordering constraint on this RMW.
644   void setOrdering(AtomicOrdering Ordering) {
645     assert(Ordering != NotAtomic &&
646            "atomicrmw instructions can only be atomic.");
647     setInstructionSubclassData((getSubclassDataFromInstruction() & ~(7 << 2)) |
648                                (Ordering << 2));
649   }
650
651   /// Specify whether this RMW orders other operations with respect to all
652   /// concurrently executing threads, or only with respect to signal handlers
653   /// executing in the same thread.
654   void setSynchScope(SynchronizationScope SynchScope) {
655     setInstructionSubclassData((getSubclassDataFromInstruction() & ~2) |
656                                (SynchScope << 1));
657   }
658
659   /// Returns the ordering constraint on this RMW.
660   AtomicOrdering getOrdering() const {
661     return AtomicOrdering((getSubclassDataFromInstruction() >> 2) & 7);
662   }
663
664   /// Returns whether this RMW is atomic between threads or only within a
665   /// single thread.
666   SynchronizationScope getSynchScope() const {
667     return SynchronizationScope((getSubclassDataFromInstruction() & 2) >> 1);
668   }
669
670   Value *getPointerOperand() { return getOperand(0); }
671   const Value *getPointerOperand() const { return getOperand(0); }
672   static unsigned getPointerOperandIndex() { return 0U; }
673
674   Value *getValOperand() { return getOperand(1); }
675   const Value *getValOperand() const { return getOperand(1); }
676
677   unsigned getPointerAddressSpace() const {
678     return cast<PointerType>(getPointerOperand()->getType())->getAddressSpace();
679   }
680
681   // Methods for support type inquiry through isa, cast, and dyn_cast:
682   static inline bool classof(const AtomicRMWInst *) { return true; }
683   static inline bool classof(const Instruction *I) {
684     return I->getOpcode() == Instruction::AtomicRMW;
685   }
686   static inline bool classof(const Value *V) {
687     return isa<Instruction>(V) && classof(cast<Instruction>(V));
688   }
689 private:
690   void Init(BinOp Operation, Value *Ptr, Value *Val,
691             AtomicOrdering Ordering, SynchronizationScope SynchScope);
692   // Shadow Instruction::setInstructionSubclassData with a private forwarding
693   // method so that subclasses cannot accidentally use it.
694   void setInstructionSubclassData(unsigned short D) {
695     Instruction::setInstructionSubclassData(D);
696   }
697 };
698
699 template <>
700 struct OperandTraits<AtomicRMWInst>
701     : public FixedNumOperandTraits<AtomicRMWInst,2> {
702 };
703
704 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(AtomicRMWInst, Value)
705
706 //===----------------------------------------------------------------------===//
707 //                             GetElementPtrInst Class
708 //===----------------------------------------------------------------------===//
709
710 // checkGEPType - Simple wrapper function to give a better assertion failure
711 // message on bad indexes for a gep instruction.
712 //
713 inline Type *checkGEPType(Type *Ty) {
714   assert(Ty && "Invalid GetElementPtrInst indices for type!");
715   return Ty;
716 }
717
718 /// GetElementPtrInst - an instruction for type-safe pointer arithmetic to
719 /// access elements of arrays and structs
720 ///
721 class GetElementPtrInst : public Instruction {
722   GetElementPtrInst(const GetElementPtrInst &GEPI);
723   void init(Value *Ptr, ArrayRef<Value *> IdxList, const Twine &NameStr);
724
725   /// Constructors - Create a getelementptr instruction with a base pointer an
726   /// list of indices. The first ctor can optionally insert before an existing
727   /// instruction, the second appends the new instruction to the specified
728   /// BasicBlock.
729   inline GetElementPtrInst(Value *Ptr, ArrayRef<Value *> IdxList,
730                            unsigned Values, const Twine &NameStr,
731                            Instruction *InsertBefore);
732   inline GetElementPtrInst(Value *Ptr, ArrayRef<Value *> IdxList,
733                            unsigned Values, const Twine &NameStr,
734                            BasicBlock *InsertAtEnd);
735 protected:
736   virtual GetElementPtrInst *clone_impl() const;
737 public:
738   static GetElementPtrInst *Create(Value *Ptr, ArrayRef<Value *> IdxList,
739                                    const Twine &NameStr = "",
740                                    Instruction *InsertBefore = 0) {
741     unsigned Values = 1 + unsigned(IdxList.size());
742     return new(Values)
743       GetElementPtrInst(Ptr, IdxList, Values, NameStr, InsertBefore);
744   }
745   static GetElementPtrInst *Create(Value *Ptr, ArrayRef<Value *> IdxList,
746                                    const Twine &NameStr,
747                                    BasicBlock *InsertAtEnd) {
748     unsigned Values = 1 + unsigned(IdxList.size());
749     return new(Values)
750       GetElementPtrInst(Ptr, IdxList, Values, NameStr, InsertAtEnd);
751   }
752
753   /// Create an "inbounds" getelementptr. See the documentation for the
754   /// "inbounds" flag in LangRef.html for details.
755   static GetElementPtrInst *CreateInBounds(Value *Ptr,
756                                            ArrayRef<Value *> IdxList,
757                                            const Twine &NameStr = "",
758                                            Instruction *InsertBefore = 0) {
759     GetElementPtrInst *GEP = Create(Ptr, IdxList, NameStr, InsertBefore);
760     GEP->setIsInBounds(true);
761     return GEP;
762   }
763   static GetElementPtrInst *CreateInBounds(Value *Ptr,
764                                            ArrayRef<Value *> IdxList,
765                                            const Twine &NameStr,
766                                            BasicBlock *InsertAtEnd) {
767     GetElementPtrInst *GEP = Create(Ptr, IdxList, NameStr, InsertAtEnd);
768     GEP->setIsInBounds(true);
769     return GEP;
770   }
771
772   /// Transparently provide more efficient getOperand methods.
773   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
774
775   // getType - Overload to return most specific pointer type...
776   PointerType *getType() const {
777     return reinterpret_cast<PointerType*>(Instruction::getType());
778   }
779
780   /// getIndexedType - Returns the type of the element that would be loaded with
781   /// a load instruction with the specified parameters.
782   ///
783   /// Null is returned if the indices are invalid for the specified
784   /// pointer type.
785   ///
786   static Type *getIndexedType(Type *Ptr, ArrayRef<Value *> IdxList);
787   static Type *getIndexedType(Type *Ptr, ArrayRef<Constant *> IdxList);
788   static Type *getIndexedType(Type *Ptr, ArrayRef<uint64_t> IdxList);
789
790   /// getAddressSpace - Returns the address space used by the GEP pointer.
791   ///
792   static unsigned getAddressSpace(Value *Ptr);
793
794   inline op_iterator       idx_begin()       { return op_begin()+1; }
795   inline const_op_iterator idx_begin() const { return op_begin()+1; }
796   inline op_iterator       idx_end()         { return op_end(); }
797   inline const_op_iterator idx_end()   const { return op_end(); }
798
799   Value *getPointerOperand() {
800     return getOperand(0);
801   }
802   const Value *getPointerOperand() const {
803     return getOperand(0);
804   }
805   static unsigned getPointerOperandIndex() {
806     return 0U;    // get index for modifying correct operand.
807   }
808
809   unsigned getPointerAddressSpace() const {
810     return cast<PointerType>(getPointerOperandType())->getAddressSpace();
811   }
812
813   /// getPointerOperandType - Method to return the pointer operand as a
814   /// PointerType.
815   Type *getPointerOperandType() const {
816     return getPointerOperand()->getType();
817   }
818
819   /// GetGEPReturnType - Returns the pointer type returned by the GEP
820   /// instruction, which may be a vector of pointers.
821   static Type *getGEPReturnType(Value *Ptr, ArrayRef<Value *> IdxList) {
822     Type *PtrTy = PointerType::get(checkGEPType(
823                                    getIndexedType(Ptr->getType(), IdxList)),
824                                    getAddressSpace(Ptr));
825     // Vector GEP
826     if (Ptr->getType()->isVectorTy()) {
827       unsigned NumElem = cast<VectorType>(Ptr->getType())->getNumElements();
828       return VectorType::get(PtrTy, NumElem);
829     }
830
831     // Scalar GEP
832     return PtrTy;
833   }
834
835   unsigned getNumIndices() const {  // Note: always non-negative
836     return getNumOperands() - 1;
837   }
838
839   bool hasIndices() const {
840     return getNumOperands() > 1;
841   }
842
843   /// hasAllZeroIndices - Return true if all of the indices of this GEP are
844   /// zeros.  If so, the result pointer and the first operand have the same
845   /// value, just potentially different types.
846   bool hasAllZeroIndices() const;
847
848   /// hasAllConstantIndices - Return true if all of the indices of this GEP are
849   /// constant integers.  If so, the result pointer and the first operand have
850   /// a constant offset between them.
851   bool hasAllConstantIndices() const;
852
853   /// setIsInBounds - Set or clear the inbounds flag on this GEP instruction.
854   /// See LangRef.html for the meaning of inbounds on a getelementptr.
855   void setIsInBounds(bool b = true);
856
857   /// isInBounds - Determine whether the GEP has the inbounds flag.
858   bool isInBounds() const;
859
860   // Methods for support type inquiry through isa, cast, and dyn_cast:
861   static inline bool classof(const GetElementPtrInst *) { return true; }
862   static inline bool classof(const Instruction *I) {
863     return (I->getOpcode() == Instruction::GetElementPtr);
864   }
865   static inline bool classof(const Value *V) {
866     return isa<Instruction>(V) && classof(cast<Instruction>(V));
867   }
868 };
869
870 template <>
871 struct OperandTraits<GetElementPtrInst> :
872   public VariadicOperandTraits<GetElementPtrInst, 1> {
873 };
874
875 GetElementPtrInst::GetElementPtrInst(Value *Ptr,
876                                      ArrayRef<Value *> IdxList,
877                                      unsigned Values,
878                                      const Twine &NameStr,
879                                      Instruction *InsertBefore)
880   : Instruction(getGEPReturnType(Ptr, IdxList),
881                 GetElementPtr,
882                 OperandTraits<GetElementPtrInst>::op_end(this) - Values,
883                 Values, InsertBefore) {
884   init(Ptr, IdxList, NameStr);
885 }
886 GetElementPtrInst::GetElementPtrInst(Value *Ptr,
887                                      ArrayRef<Value *> IdxList,
888                                      unsigned Values,
889                                      const Twine &NameStr,
890                                      BasicBlock *InsertAtEnd)
891   : Instruction(getGEPReturnType(Ptr, IdxList),
892                 GetElementPtr,
893                 OperandTraits<GetElementPtrInst>::op_end(this) - Values,
894                 Values, InsertAtEnd) {
895   init(Ptr, IdxList, NameStr);
896 }
897
898
899 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(GetElementPtrInst, Value)
900
901
902 //===----------------------------------------------------------------------===//
903 //                               ICmpInst Class
904 //===----------------------------------------------------------------------===//
905
906 /// This instruction compares its operands according to the predicate given
907 /// to the constructor. It only operates on integers or pointers. The operands
908 /// must be identical types.
909 /// @brief Represent an integer comparison operator.
910 class ICmpInst: public CmpInst {
911 protected:
912   /// @brief Clone an identical ICmpInst
913   virtual ICmpInst *clone_impl() const;
914 public:
915   /// @brief Constructor with insert-before-instruction semantics.
916   ICmpInst(
917     Instruction *InsertBefore,  ///< Where to insert
918     Predicate pred,  ///< The predicate to use for the comparison
919     Value *LHS,      ///< The left-hand-side of the expression
920     Value *RHS,      ///< The right-hand-side of the expression
921     const Twine &NameStr = ""  ///< Name of the instruction
922   ) : CmpInst(makeCmpResultType(LHS->getType()),
923               Instruction::ICmp, pred, LHS, RHS, NameStr,
924               InsertBefore) {
925     assert(pred >= CmpInst::FIRST_ICMP_PREDICATE &&
926            pred <= CmpInst::LAST_ICMP_PREDICATE &&
927            "Invalid ICmp predicate value");
928     assert(getOperand(0)->getType() == getOperand(1)->getType() &&
929           "Both operands to ICmp instruction are not of the same type!");
930     // Check that the operands are the right type
931     assert((getOperand(0)->getType()->isIntOrIntVectorTy() ||
932             getOperand(0)->getType()->getScalarType()->isPointerTy()) &&
933            "Invalid operand types for ICmp instruction");
934   }
935
936   /// @brief Constructor with insert-at-end semantics.
937   ICmpInst(
938     BasicBlock &InsertAtEnd, ///< Block to insert into.
939     Predicate pred,  ///< The predicate to use for the comparison
940     Value *LHS,      ///< The left-hand-side of the expression
941     Value *RHS,      ///< The right-hand-side of the expression
942     const Twine &NameStr = ""  ///< Name of the instruction
943   ) : CmpInst(makeCmpResultType(LHS->getType()),
944               Instruction::ICmp, pred, LHS, RHS, NameStr,
945               &InsertAtEnd) {
946     assert(pred >= CmpInst::FIRST_ICMP_PREDICATE &&
947           pred <= CmpInst::LAST_ICMP_PREDICATE &&
948           "Invalid ICmp predicate value");
949     assert(getOperand(0)->getType() == getOperand(1)->getType() &&
950           "Both operands to ICmp instruction are not of the same type!");
951     // Check that the operands are the right type
952     assert((getOperand(0)->getType()->isIntOrIntVectorTy() ||
953             getOperand(0)->getType()->isPointerTy()) &&
954            "Invalid operand types for ICmp instruction");
955   }
956
957   /// @brief Constructor with no-insertion semantics
958   ICmpInst(
959     Predicate pred, ///< The predicate to use for the comparison
960     Value *LHS,     ///< The left-hand-side of the expression
961     Value *RHS,     ///< The right-hand-side of the expression
962     const Twine &NameStr = "" ///< Name of the instruction
963   ) : CmpInst(makeCmpResultType(LHS->getType()),
964               Instruction::ICmp, pred, LHS, RHS, NameStr) {
965     assert(pred >= CmpInst::FIRST_ICMP_PREDICATE &&
966            pred <= CmpInst::LAST_ICMP_PREDICATE &&
967            "Invalid ICmp predicate value");
968     assert(getOperand(0)->getType() == getOperand(1)->getType() &&
969           "Both operands to ICmp instruction are not of the same type!");
970     // Check that the operands are the right type
971     assert((getOperand(0)->getType()->isIntOrIntVectorTy() ||
972             getOperand(0)->getType()->getScalarType()->isPointerTy()) &&
973            "Invalid operand types for ICmp instruction");
974   }
975
976   /// For example, EQ->EQ, SLE->SLE, UGT->SGT, etc.
977   /// @returns the predicate that would be the result if the operand were
978   /// regarded as signed.
979   /// @brief Return the signed version of the predicate
980   Predicate getSignedPredicate() const {
981     return getSignedPredicate(getPredicate());
982   }
983
984   /// This is a static version that you can use without an instruction.
985   /// @brief Return the signed version of the predicate.
986   static Predicate getSignedPredicate(Predicate pred);
987
988   /// For example, EQ->EQ, SLE->ULE, UGT->UGT, etc.
989   /// @returns the predicate that would be the result if the operand were
990   /// regarded as unsigned.
991   /// @brief Return the unsigned version of the predicate
992   Predicate getUnsignedPredicate() const {
993     return getUnsignedPredicate(getPredicate());
994   }
995
996   /// This is a static version that you can use without an instruction.
997   /// @brief Return the unsigned version of the predicate.
998   static Predicate getUnsignedPredicate(Predicate pred);
999
1000   /// isEquality - Return true if this predicate is either EQ or NE.  This also
1001   /// tests for commutativity.
1002   static bool isEquality(Predicate P) {
1003     return P == ICMP_EQ || P == ICMP_NE;
1004   }
1005
1006   /// isEquality - Return true if this predicate is either EQ or NE.  This also
1007   /// tests for commutativity.
1008   bool isEquality() const {
1009     return isEquality(getPredicate());
1010   }
1011
1012   /// @returns true if the predicate of this ICmpInst is commutative
1013   /// @brief Determine if this relation is commutative.
1014   bool isCommutative() const { return isEquality(); }
1015
1016   /// isRelational - Return true if the predicate is relational (not EQ or NE).
1017   ///
1018   bool isRelational() const {
1019     return !isEquality();
1020   }
1021
1022   /// isRelational - Return true if the predicate is relational (not EQ or NE).
1023   ///
1024   static bool isRelational(Predicate P) {
1025     return !isEquality(P);
1026   }
1027
1028   /// Initialize a set of values that all satisfy the predicate with C.
1029   /// @brief Make a ConstantRange for a relation with a constant value.
1030   static ConstantRange makeConstantRange(Predicate pred, const APInt &C);
1031
1032   /// Exchange the two operands to this instruction in such a way that it does
1033   /// not modify the semantics of the instruction. The predicate value may be
1034   /// changed to retain the same result if the predicate is order dependent
1035   /// (e.g. ult).
1036   /// @brief Swap operands and adjust predicate.
1037   void swapOperands() {
1038     setPredicate(getSwappedPredicate());
1039     Op<0>().swap(Op<1>());
1040   }
1041
1042   // Methods for support type inquiry through isa, cast, and dyn_cast:
1043   static inline bool classof(const ICmpInst *) { return true; }
1044   static inline bool classof(const Instruction *I) {
1045     return I->getOpcode() == Instruction::ICmp;
1046   }
1047   static inline bool classof(const Value *V) {
1048     return isa<Instruction>(V) && classof(cast<Instruction>(V));
1049   }
1050
1051 };
1052
1053 //===----------------------------------------------------------------------===//
1054 //                               FCmpInst Class
1055 //===----------------------------------------------------------------------===//
1056
1057 /// This instruction compares its operands according to the predicate given
1058 /// to the constructor. It only operates on floating point values or packed
1059 /// vectors of floating point values. The operands must be identical types.
1060 /// @brief Represents a floating point comparison operator.
1061 class FCmpInst: public CmpInst {
1062 protected:
1063   /// @brief Clone an identical FCmpInst
1064   virtual FCmpInst *clone_impl() const;
1065 public:
1066   /// @brief Constructor with insert-before-instruction semantics.
1067   FCmpInst(
1068     Instruction *InsertBefore, ///< Where to insert
1069     Predicate pred,  ///< The predicate to use for the comparison
1070     Value *LHS,      ///< The left-hand-side of the expression
1071     Value *RHS,      ///< The right-hand-side of the expression
1072     const Twine &NameStr = ""  ///< Name of the instruction
1073   ) : CmpInst(makeCmpResultType(LHS->getType()),
1074               Instruction::FCmp, pred, LHS, RHS, NameStr,
1075               InsertBefore) {
1076     assert(pred <= FCmpInst::LAST_FCMP_PREDICATE &&
1077            "Invalid FCmp predicate value");
1078     assert(getOperand(0)->getType() == getOperand(1)->getType() &&
1079            "Both operands to FCmp instruction are not of the same type!");
1080     // Check that the operands are the right type
1081     assert(getOperand(0)->getType()->isFPOrFPVectorTy() &&
1082            "Invalid operand types for FCmp instruction");
1083   }
1084
1085   /// @brief Constructor with insert-at-end semantics.
1086   FCmpInst(
1087     BasicBlock &InsertAtEnd, ///< Block to insert into.
1088     Predicate pred,  ///< The predicate to use for the comparison
1089     Value *LHS,      ///< The left-hand-side of the expression
1090     Value *RHS,      ///< The right-hand-side of the expression
1091     const Twine &NameStr = ""  ///< Name of the instruction
1092   ) : CmpInst(makeCmpResultType(LHS->getType()),
1093               Instruction::FCmp, pred, LHS, RHS, NameStr,
1094               &InsertAtEnd) {
1095     assert(pred <= FCmpInst::LAST_FCMP_PREDICATE &&
1096            "Invalid FCmp predicate value");
1097     assert(getOperand(0)->getType() == getOperand(1)->getType() &&
1098            "Both operands to FCmp instruction are not of the same type!");
1099     // Check that the operands are the right type
1100     assert(getOperand(0)->getType()->isFPOrFPVectorTy() &&
1101            "Invalid operand types for FCmp instruction");
1102   }
1103
1104   /// @brief Constructor with no-insertion semantics
1105   FCmpInst(
1106     Predicate pred, ///< The predicate to use for the comparison
1107     Value *LHS,     ///< The left-hand-side of the expression
1108     Value *RHS,     ///< The right-hand-side of the expression
1109     const Twine &NameStr = "" ///< Name of the instruction
1110   ) : CmpInst(makeCmpResultType(LHS->getType()),
1111               Instruction::FCmp, pred, LHS, RHS, NameStr) {
1112     assert(pred <= FCmpInst::LAST_FCMP_PREDICATE &&
1113            "Invalid FCmp predicate value");
1114     assert(getOperand(0)->getType() == getOperand(1)->getType() &&
1115            "Both operands to FCmp instruction are not of the same type!");
1116     // Check that the operands are the right type
1117     assert(getOperand(0)->getType()->isFPOrFPVectorTy() &&
1118            "Invalid operand types for FCmp instruction");
1119   }
1120
1121   /// @returns true if the predicate of this instruction is EQ or NE.
1122   /// @brief Determine if this is an equality predicate.
1123   bool isEquality() const {
1124     return getPredicate() == FCMP_OEQ || getPredicate() == FCMP_ONE ||
1125            getPredicate() == FCMP_UEQ || getPredicate() == FCMP_UNE;
1126   }
1127
1128   /// @returns true if the predicate of this instruction is commutative.
1129   /// @brief Determine if this is a commutative predicate.
1130   bool isCommutative() const {
1131     return isEquality() ||
1132            getPredicate() == FCMP_FALSE ||
1133            getPredicate() == FCMP_TRUE ||
1134            getPredicate() == FCMP_ORD ||
1135            getPredicate() == FCMP_UNO;
1136   }
1137
1138   /// @returns true if the predicate is relational (not EQ or NE).
1139   /// @brief Determine if this a relational predicate.
1140   bool isRelational() const { return !isEquality(); }
1141
1142   /// Exchange the two operands to this instruction in such a way that it does
1143   /// not modify the semantics of the instruction. The predicate value may be
1144   /// changed to retain the same result if the predicate is order dependent
1145   /// (e.g. ult).
1146   /// @brief Swap operands and adjust predicate.
1147   void swapOperands() {
1148     setPredicate(getSwappedPredicate());
1149     Op<0>().swap(Op<1>());
1150   }
1151
1152   /// @brief Methods for support type inquiry through isa, cast, and dyn_cast:
1153   static inline bool classof(const FCmpInst *) { return true; }
1154   static inline bool classof(const Instruction *I) {
1155     return I->getOpcode() == Instruction::FCmp;
1156   }
1157   static inline bool classof(const Value *V) {
1158     return isa<Instruction>(V) && classof(cast<Instruction>(V));
1159   }
1160 };
1161
1162 //===----------------------------------------------------------------------===//
1163 /// CallInst - This class represents a function call, abstracting a target
1164 /// machine's calling convention.  This class uses low bit of the SubClassData
1165 /// field to indicate whether or not this is a tail call.  The rest of the bits
1166 /// hold the calling convention of the call.
1167 ///
1168 class CallInst : public Instruction {
1169   AttrListPtr AttributeList; ///< parameter attributes for call
1170   CallInst(const CallInst &CI);
1171   void init(Value *Func, ArrayRef<Value *> Args, const Twine &NameStr);
1172   void init(Value *Func, const Twine &NameStr);
1173
1174   /// Construct a CallInst given a range of arguments.
1175   /// @brief Construct a CallInst from a range of arguments
1176   inline CallInst(Value *Func, ArrayRef<Value *> Args,
1177                   const Twine &NameStr, Instruction *InsertBefore);
1178
1179   /// Construct a CallInst given a range of arguments.
1180   /// @brief Construct a CallInst from a range of arguments
1181   inline CallInst(Value *Func, ArrayRef<Value *> Args,
1182                   const Twine &NameStr, BasicBlock *InsertAtEnd);
1183
1184   CallInst(Value *F, Value *Actual, const Twine &NameStr,
1185            Instruction *InsertBefore);
1186   CallInst(Value *F, Value *Actual, const Twine &NameStr,
1187            BasicBlock *InsertAtEnd);
1188   explicit CallInst(Value *F, const Twine &NameStr,
1189                     Instruction *InsertBefore);
1190   CallInst(Value *F, const Twine &NameStr, BasicBlock *InsertAtEnd);
1191 protected:
1192   virtual CallInst *clone_impl() const;
1193 public:
1194   static CallInst *Create(Value *Func,
1195                           ArrayRef<Value *> Args,
1196                           const Twine &NameStr = "",
1197                           Instruction *InsertBefore = 0) {
1198     return new(unsigned(Args.size() + 1))
1199       CallInst(Func, Args, NameStr, InsertBefore);
1200   }
1201   static CallInst *Create(Value *Func,
1202                           ArrayRef<Value *> Args,
1203                           const Twine &NameStr, BasicBlock *InsertAtEnd) {
1204     return new(unsigned(Args.size() + 1))
1205       CallInst(Func, Args, NameStr, InsertAtEnd);
1206   }
1207   static CallInst *Create(Value *F, const Twine &NameStr = "",
1208                           Instruction *InsertBefore = 0) {
1209     return new(1) CallInst(F, NameStr, InsertBefore);
1210   }
1211   static CallInst *Create(Value *F, const Twine &NameStr,
1212                           BasicBlock *InsertAtEnd) {
1213     return new(1) CallInst(F, NameStr, InsertAtEnd);
1214   }
1215   /// CreateMalloc - Generate the IR for a call to malloc:
1216   /// 1. Compute the malloc call's argument as the specified type's size,
1217   ///    possibly multiplied by the array size if the array size is not
1218   ///    constant 1.
1219   /// 2. Call malloc with that argument.
1220   /// 3. Bitcast the result of the malloc call to the specified type.
1221   static Instruction *CreateMalloc(Instruction *InsertBefore,
1222                                    Type *IntPtrTy, Type *AllocTy,
1223                                    Value *AllocSize, Value *ArraySize = 0,
1224                                    Function* MallocF = 0,
1225                                    const Twine &Name = "");
1226   static Instruction *CreateMalloc(BasicBlock *InsertAtEnd,
1227                                    Type *IntPtrTy, Type *AllocTy,
1228                                    Value *AllocSize, Value *ArraySize = 0,
1229                                    Function* MallocF = 0,
1230                                    const Twine &Name = "");
1231   /// CreateFree - Generate the IR for a call to the builtin free function.
1232   static Instruction* CreateFree(Value* Source, Instruction *InsertBefore);
1233   static Instruction* CreateFree(Value* Source, BasicBlock *InsertAtEnd);
1234
1235   ~CallInst();
1236
1237   bool isTailCall() const { return getSubclassDataFromInstruction() & 1; }
1238   void setTailCall(bool isTC = true) {
1239     setInstructionSubclassData((getSubclassDataFromInstruction() & ~1) |
1240                                unsigned(isTC));
1241   }
1242
1243   /// Provide fast operand accessors
1244   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
1245
1246   /// getNumArgOperands - Return the number of call arguments.
1247   ///
1248   unsigned getNumArgOperands() const { return getNumOperands() - 1; }
1249
1250   /// getArgOperand/setArgOperand - Return/set the i-th call argument.
1251   ///
1252   Value *getArgOperand(unsigned i) const { return getOperand(i); }
1253   void setArgOperand(unsigned i, Value *v) { setOperand(i, v); }
1254
1255   /// getCallingConv/setCallingConv - Get or set the calling convention of this
1256   /// function call.
1257   CallingConv::ID getCallingConv() const {
1258     return static_cast<CallingConv::ID>(getSubclassDataFromInstruction() >> 1);
1259   }
1260   void setCallingConv(CallingConv::ID CC) {
1261     setInstructionSubclassData((getSubclassDataFromInstruction() & 1) |
1262                                (static_cast<unsigned>(CC) << 1));
1263   }
1264
1265   /// getAttributes - Return the parameter attributes for this call.
1266   ///
1267   const AttrListPtr &getAttributes() const { return AttributeList; }
1268
1269   /// setAttributes - Set the parameter attributes for this call.
1270   ///
1271   void setAttributes(const AttrListPtr &Attrs) { AttributeList = Attrs; }
1272
1273   /// addAttribute - adds the attribute to the list of attributes.
1274   void addAttribute(unsigned i, Attributes attr);
1275
1276   /// removeAttribute - removes the attribute from the list of attributes.
1277   void removeAttribute(unsigned i, Attributes attr);
1278
1279   /// @brief Determine whether this call has the given attribute.
1280   bool hasFnAttr(Attributes::AttrVal A) const;
1281
1282   /// @brief Determine whether the call or the callee has the given attributes.
1283   bool paramHasAttr(unsigned i, Attributes::AttrVal A) const;
1284
1285   /// @brief Extract the alignment for a call or parameter (0=unknown).
1286   unsigned getParamAlignment(unsigned i) const {
1287     return AttributeList.getParamAlignment(i);
1288   }
1289
1290   /// @brief Return true if the call should not be inlined.
1291   bool isNoInline() const { return hasFnAttr(Attributes::NoInline); }
1292   void setIsNoInline() {
1293     Attributes::Builder B;
1294     B.addAttribute(Attributes::NoInline);
1295     addAttribute(~0, Attributes::get(B));
1296   }
1297
1298   /// @brief Return true if the call can return twice
1299   bool canReturnTwice() const {
1300     return hasFnAttr(Attributes::ReturnsTwice);
1301   }
1302   void setCanReturnTwice() {
1303     Attributes::Builder B;
1304     B.addAttribute(Attributes::ReturnsTwice);
1305     addAttribute(~0U, Attributes::get(B));
1306   }
1307
1308   /// @brief Determine if the call does not access memory.
1309   bool doesNotAccessMemory() const {
1310     return hasFnAttr(Attributes::ReadNone);
1311   }
1312   void setDoesNotAccessMemory() {
1313     Attributes::Builder B;
1314     B.addAttribute(Attributes::ReadNone);
1315     addAttribute(~0U, Attributes::get(B));
1316   }
1317
1318   /// @brief Determine if the call does not access or only reads memory.
1319   bool onlyReadsMemory() const {
1320     return doesNotAccessMemory() || hasFnAttr(Attributes::ReadOnly);
1321   }
1322   void setOnlyReadsMemory() {
1323     Attributes::Builder B;
1324     B.addAttribute(Attributes::ReadOnly);
1325     addAttribute(~0, Attributes::get(B));
1326   }
1327
1328   /// @brief Determine if the call cannot return.
1329   bool doesNotReturn() const { return hasFnAttr(Attributes::NoReturn); }
1330   void setDoesNotReturn() {
1331     Attributes::Builder B;
1332     B.addAttribute(Attributes::NoReturn);
1333     addAttribute(~0, Attributes::get(B));
1334   }
1335
1336   /// @brief Determine if the call cannot unwind.
1337   bool doesNotThrow() const { return hasFnAttr(Attributes::NoUnwind); }
1338   void setDoesNotThrow() {
1339     Attributes::Builder B;
1340     B.addAttribute(Attributes::NoUnwind);
1341     addAttribute(~0, Attributes::get(B));
1342   }
1343
1344   /// @brief Determine if the call returns a structure through first
1345   /// pointer argument.
1346   bool hasStructRetAttr() const {
1347     // Be friendly and also check the callee.
1348     return paramHasAttr(1, Attributes::StructRet);
1349   }
1350
1351   /// @brief Determine if any call argument is an aggregate passed by value.
1352   bool hasByValArgument() const {
1353     for (unsigned I = 0, E = AttributeList.getNumAttrs(); I != E; ++I)
1354       if (AttributeList.getAttributesAtIndex(I).hasAttribute(Attributes::ByVal))
1355         return true;
1356     return false;
1357   }
1358
1359   /// getCalledFunction - Return the function called, or null if this is an
1360   /// indirect function invocation.
1361   ///
1362   Function *getCalledFunction() const {
1363     return dyn_cast<Function>(Op<-1>());
1364   }
1365
1366   /// getCalledValue - Get a pointer to the function that is invoked by this
1367   /// instruction.
1368   const Value *getCalledValue() const { return Op<-1>(); }
1369         Value *getCalledValue()       { return Op<-1>(); }
1370
1371   /// setCalledFunction - Set the function called.
1372   void setCalledFunction(Value* Fn) {
1373     Op<-1>() = Fn;
1374   }
1375
1376   /// isInlineAsm - Check if this call is an inline asm statement.
1377   bool isInlineAsm() const {
1378     return isa<InlineAsm>(Op<-1>());
1379   }
1380
1381   // Methods for support type inquiry through isa, cast, and dyn_cast:
1382   static inline bool classof(const CallInst *) { return true; }
1383   static inline bool classof(const Instruction *I) {
1384     return I->getOpcode() == Instruction::Call;
1385   }
1386   static inline bool classof(const Value *V) {
1387     return isa<Instruction>(V) && classof(cast<Instruction>(V));
1388   }
1389 private:
1390   // Shadow Instruction::setInstructionSubclassData with a private forwarding
1391   // method so that subclasses cannot accidentally use it.
1392   void setInstructionSubclassData(unsigned short D) {
1393     Instruction::setInstructionSubclassData(D);
1394   }
1395 };
1396
1397 template <>
1398 struct OperandTraits<CallInst> : public VariadicOperandTraits<CallInst, 1> {
1399 };
1400
1401 CallInst::CallInst(Value *Func, ArrayRef<Value *> Args,
1402                    const Twine &NameStr, BasicBlock *InsertAtEnd)
1403   : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
1404                                    ->getElementType())->getReturnType(),
1405                 Instruction::Call,
1406                 OperandTraits<CallInst>::op_end(this) - (Args.size() + 1),
1407                 unsigned(Args.size() + 1), InsertAtEnd) {
1408   init(Func, Args, NameStr);
1409 }
1410
1411 CallInst::CallInst(Value *Func, ArrayRef<Value *> Args,
1412                    const Twine &NameStr, Instruction *InsertBefore)
1413   : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
1414                                    ->getElementType())->getReturnType(),
1415                 Instruction::Call,
1416                 OperandTraits<CallInst>::op_end(this) - (Args.size() + 1),
1417                 unsigned(Args.size() + 1), InsertBefore) {
1418   init(Func, Args, NameStr);
1419 }
1420
1421
1422 // Note: if you get compile errors about private methods then
1423 //       please update your code to use the high-level operand
1424 //       interfaces. See line 943 above.
1425 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(CallInst, Value)
1426
1427 //===----------------------------------------------------------------------===//
1428 //                               SelectInst Class
1429 //===----------------------------------------------------------------------===//
1430
1431 /// SelectInst - This class represents the LLVM 'select' instruction.
1432 ///
1433 class SelectInst : public Instruction {
1434   void init(Value *C, Value *S1, Value *S2) {
1435     assert(!areInvalidOperands(C, S1, S2) && "Invalid operands for select");
1436     Op<0>() = C;
1437     Op<1>() = S1;
1438     Op<2>() = S2;
1439   }
1440
1441   SelectInst(Value *C, Value *S1, Value *S2, const Twine &NameStr,
1442              Instruction *InsertBefore)
1443     : Instruction(S1->getType(), Instruction::Select,
1444                   &Op<0>(), 3, InsertBefore) {
1445     init(C, S1, S2);
1446     setName(NameStr);
1447   }
1448   SelectInst(Value *C, Value *S1, Value *S2, const Twine &NameStr,
1449              BasicBlock *InsertAtEnd)
1450     : Instruction(S1->getType(), Instruction::Select,
1451                   &Op<0>(), 3, InsertAtEnd) {
1452     init(C, S1, S2);
1453     setName(NameStr);
1454   }
1455 protected:
1456   virtual SelectInst *clone_impl() const;
1457 public:
1458   static SelectInst *Create(Value *C, Value *S1, Value *S2,
1459                             const Twine &NameStr = "",
1460                             Instruction *InsertBefore = 0) {
1461     return new(3) SelectInst(C, S1, S2, NameStr, InsertBefore);
1462   }
1463   static SelectInst *Create(Value *C, Value *S1, Value *S2,
1464                             const Twine &NameStr,
1465                             BasicBlock *InsertAtEnd) {
1466     return new(3) SelectInst(C, S1, S2, NameStr, InsertAtEnd);
1467   }
1468
1469   const Value *getCondition() const { return Op<0>(); }
1470   const Value *getTrueValue() const { return Op<1>(); }
1471   const Value *getFalseValue() const { return Op<2>(); }
1472   Value *getCondition() { return Op<0>(); }
1473   Value *getTrueValue() { return Op<1>(); }
1474   Value *getFalseValue() { return Op<2>(); }
1475
1476   /// areInvalidOperands - Return a string if the specified operands are invalid
1477   /// for a select operation, otherwise return null.
1478   static const char *areInvalidOperands(Value *Cond, Value *True, Value *False);
1479
1480   /// Transparently provide more efficient getOperand methods.
1481   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
1482
1483   OtherOps getOpcode() const {
1484     return static_cast<OtherOps>(Instruction::getOpcode());
1485   }
1486
1487   // Methods for support type inquiry through isa, cast, and dyn_cast:
1488   static inline bool classof(const SelectInst *) { return true; }
1489   static inline bool classof(const Instruction *I) {
1490     return I->getOpcode() == Instruction::Select;
1491   }
1492   static inline bool classof(const Value *V) {
1493     return isa<Instruction>(V) && classof(cast<Instruction>(V));
1494   }
1495 };
1496
1497 template <>
1498 struct OperandTraits<SelectInst> : public FixedNumOperandTraits<SelectInst, 3> {
1499 };
1500
1501 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(SelectInst, Value)
1502
1503 //===----------------------------------------------------------------------===//
1504 //                                VAArgInst Class
1505 //===----------------------------------------------------------------------===//
1506
1507 /// VAArgInst - This class represents the va_arg llvm instruction, which returns
1508 /// an argument of the specified type given a va_list and increments that list
1509 ///
1510 class VAArgInst : public UnaryInstruction {
1511 protected:
1512   virtual VAArgInst *clone_impl() const;
1513
1514 public:
1515   VAArgInst(Value *List, Type *Ty, const Twine &NameStr = "",
1516              Instruction *InsertBefore = 0)
1517     : UnaryInstruction(Ty, VAArg, List, InsertBefore) {
1518     setName(NameStr);
1519   }
1520   VAArgInst(Value *List, Type *Ty, const Twine &NameStr,
1521             BasicBlock *InsertAtEnd)
1522     : UnaryInstruction(Ty, VAArg, List, InsertAtEnd) {
1523     setName(NameStr);
1524   }
1525
1526   Value *getPointerOperand() { return getOperand(0); }
1527   const Value *getPointerOperand() const { return getOperand(0); }
1528   static unsigned getPointerOperandIndex() { return 0U; }
1529
1530   // Methods for support type inquiry through isa, cast, and dyn_cast:
1531   static inline bool classof(const VAArgInst *) { return true; }
1532   static inline bool classof(const Instruction *I) {
1533     return I->getOpcode() == VAArg;
1534   }
1535   static inline bool classof(const Value *V) {
1536     return isa<Instruction>(V) && classof(cast<Instruction>(V));
1537   }
1538 };
1539
1540 //===----------------------------------------------------------------------===//
1541 //                                ExtractElementInst Class
1542 //===----------------------------------------------------------------------===//
1543
1544 /// ExtractElementInst - This instruction extracts a single (scalar)
1545 /// element from a VectorType value
1546 ///
1547 class ExtractElementInst : public Instruction {
1548   ExtractElementInst(Value *Vec, Value *Idx, const Twine &NameStr = "",
1549                      Instruction *InsertBefore = 0);
1550   ExtractElementInst(Value *Vec, Value *Idx, const Twine &NameStr,
1551                      BasicBlock *InsertAtEnd);
1552 protected:
1553   virtual ExtractElementInst *clone_impl() const;
1554
1555 public:
1556   static ExtractElementInst *Create(Value *Vec, Value *Idx,
1557                                    const Twine &NameStr = "",
1558                                    Instruction *InsertBefore = 0) {
1559     return new(2) ExtractElementInst(Vec, Idx, NameStr, InsertBefore);
1560   }
1561   static ExtractElementInst *Create(Value *Vec, Value *Idx,
1562                                    const Twine &NameStr,
1563                                    BasicBlock *InsertAtEnd) {
1564     return new(2) ExtractElementInst(Vec, Idx, NameStr, InsertAtEnd);
1565   }
1566
1567   /// isValidOperands - Return true if an extractelement instruction can be
1568   /// formed with the specified operands.
1569   static bool isValidOperands(const Value *Vec, const Value *Idx);
1570
1571   Value *getVectorOperand() { return Op<0>(); }
1572   Value *getIndexOperand() { return Op<1>(); }
1573   const Value *getVectorOperand() const { return Op<0>(); }
1574   const Value *getIndexOperand() const { return Op<1>(); }
1575
1576   VectorType *getVectorOperandType() const {
1577     return reinterpret_cast<VectorType*>(getVectorOperand()->getType());
1578   }
1579
1580
1581   /// Transparently provide more efficient getOperand methods.
1582   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
1583
1584   // Methods for support type inquiry through isa, cast, and dyn_cast:
1585   static inline bool classof(const ExtractElementInst *) { return true; }
1586   static inline bool classof(const Instruction *I) {
1587     return I->getOpcode() == Instruction::ExtractElement;
1588   }
1589   static inline bool classof(const Value *V) {
1590     return isa<Instruction>(V) && classof(cast<Instruction>(V));
1591   }
1592 };
1593
1594 template <>
1595 struct OperandTraits<ExtractElementInst> :
1596   public FixedNumOperandTraits<ExtractElementInst, 2> {
1597 };
1598
1599 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ExtractElementInst, Value)
1600
1601 //===----------------------------------------------------------------------===//
1602 //                                InsertElementInst Class
1603 //===----------------------------------------------------------------------===//
1604
1605 /// InsertElementInst - This instruction inserts a single (scalar)
1606 /// element into a VectorType value
1607 ///
1608 class InsertElementInst : public Instruction {
1609   InsertElementInst(Value *Vec, Value *NewElt, Value *Idx,
1610                     const Twine &NameStr = "",
1611                     Instruction *InsertBefore = 0);
1612   InsertElementInst(Value *Vec, Value *NewElt, Value *Idx,
1613                     const Twine &NameStr, BasicBlock *InsertAtEnd);
1614 protected:
1615   virtual InsertElementInst *clone_impl() const;
1616
1617 public:
1618   static InsertElementInst *Create(Value *Vec, Value *NewElt, Value *Idx,
1619                                    const Twine &NameStr = "",
1620                                    Instruction *InsertBefore = 0) {
1621     return new(3) InsertElementInst(Vec, NewElt, Idx, NameStr, InsertBefore);
1622   }
1623   static InsertElementInst *Create(Value *Vec, Value *NewElt, Value *Idx,
1624                                    const Twine &NameStr,
1625                                    BasicBlock *InsertAtEnd) {
1626     return new(3) InsertElementInst(Vec, NewElt, Idx, NameStr, InsertAtEnd);
1627   }
1628
1629   /// isValidOperands - Return true if an insertelement instruction can be
1630   /// formed with the specified operands.
1631   static bool isValidOperands(const Value *Vec, const Value *NewElt,
1632                               const Value *Idx);
1633
1634   /// getType - Overload to return most specific vector type.
1635   ///
1636   VectorType *getType() const {
1637     return reinterpret_cast<VectorType*>(Instruction::getType());
1638   }
1639
1640   /// Transparently provide more efficient getOperand methods.
1641   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
1642
1643   // Methods for support type inquiry through isa, cast, and dyn_cast:
1644   static inline bool classof(const InsertElementInst *) { return true; }
1645   static inline bool classof(const Instruction *I) {
1646     return I->getOpcode() == Instruction::InsertElement;
1647   }
1648   static inline bool classof(const Value *V) {
1649     return isa<Instruction>(V) && classof(cast<Instruction>(V));
1650   }
1651 };
1652
1653 template <>
1654 struct OperandTraits<InsertElementInst> :
1655   public FixedNumOperandTraits<InsertElementInst, 3> {
1656 };
1657
1658 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertElementInst, Value)
1659
1660 //===----------------------------------------------------------------------===//
1661 //                           ShuffleVectorInst Class
1662 //===----------------------------------------------------------------------===//
1663
1664 /// ShuffleVectorInst - This instruction constructs a fixed permutation of two
1665 /// input vectors.
1666 ///
1667 class ShuffleVectorInst : public Instruction {
1668 protected:
1669   virtual ShuffleVectorInst *clone_impl() const;
1670
1671 public:
1672   // allocate space for exactly three operands
1673   void *operator new(size_t s) {
1674     return User::operator new(s, 3);
1675   }
1676   ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1677                     const Twine &NameStr = "",
1678                     Instruction *InsertBefor = 0);
1679   ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1680                     const Twine &NameStr, BasicBlock *InsertAtEnd);
1681
1682   /// isValidOperands - Return true if a shufflevector instruction can be
1683   /// formed with the specified operands.
1684   static bool isValidOperands(const Value *V1, const Value *V2,
1685                               const Value *Mask);
1686
1687   /// getType - Overload to return most specific vector type.
1688   ///
1689   VectorType *getType() const {
1690     return reinterpret_cast<VectorType*>(Instruction::getType());
1691   }
1692
1693   /// Transparently provide more efficient getOperand methods.
1694   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
1695
1696   Constant *getMask() const {
1697     return reinterpret_cast<Constant*>(getOperand(2));
1698   }
1699   
1700   /// getMaskValue - Return the index from the shuffle mask for the specified
1701   /// output result.  This is either -1 if the element is undef or a number less
1702   /// than 2*numelements.
1703   static int getMaskValue(Constant *Mask, unsigned i);
1704
1705   int getMaskValue(unsigned i) const {
1706     return getMaskValue(getMask(), i);
1707   }
1708   
1709   /// getShuffleMask - Return the full mask for this instruction, where each
1710   /// element is the element number and undef's are returned as -1.
1711   static void getShuffleMask(Constant *Mask, SmallVectorImpl<int> &Result);
1712
1713   void getShuffleMask(SmallVectorImpl<int> &Result) const {
1714     return getShuffleMask(getMask(), Result);
1715   }
1716
1717   SmallVector<int, 16> getShuffleMask() const {
1718     SmallVector<int, 16> Mask;
1719     getShuffleMask(Mask);
1720     return Mask;
1721   }
1722
1723
1724   // Methods for support type inquiry through isa, cast, and dyn_cast:
1725   static inline bool classof(const ShuffleVectorInst *) { return true; }
1726   static inline bool classof(const Instruction *I) {
1727     return I->getOpcode() == Instruction::ShuffleVector;
1728   }
1729   static inline bool classof(const Value *V) {
1730     return isa<Instruction>(V) && classof(cast<Instruction>(V));
1731   }
1732 };
1733
1734 template <>
1735 struct OperandTraits<ShuffleVectorInst> :
1736   public FixedNumOperandTraits<ShuffleVectorInst, 3> {
1737 };
1738
1739 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ShuffleVectorInst, Value)
1740
1741 //===----------------------------------------------------------------------===//
1742 //                                ExtractValueInst Class
1743 //===----------------------------------------------------------------------===//
1744
1745 /// ExtractValueInst - This instruction extracts a struct member or array
1746 /// element value from an aggregate value.
1747 ///
1748 class ExtractValueInst : public UnaryInstruction {
1749   SmallVector<unsigned, 4> Indices;
1750
1751   ExtractValueInst(const ExtractValueInst &EVI);
1752   void init(ArrayRef<unsigned> Idxs, const Twine &NameStr);
1753
1754   /// Constructors - Create a extractvalue instruction with a base aggregate
1755   /// value and a list of indices.  The first ctor can optionally insert before
1756   /// an existing instruction, the second appends the new instruction to the
1757   /// specified BasicBlock.
1758   inline ExtractValueInst(Value *Agg,
1759                           ArrayRef<unsigned> Idxs,
1760                           const Twine &NameStr,
1761                           Instruction *InsertBefore);
1762   inline ExtractValueInst(Value *Agg,
1763                           ArrayRef<unsigned> Idxs,
1764                           const Twine &NameStr, BasicBlock *InsertAtEnd);
1765
1766   // allocate space for exactly one operand
1767   void *operator new(size_t s) {
1768     return User::operator new(s, 1);
1769   }
1770 protected:
1771   virtual ExtractValueInst *clone_impl() const;
1772
1773 public:
1774   static ExtractValueInst *Create(Value *Agg,
1775                                   ArrayRef<unsigned> Idxs,
1776                                   const Twine &NameStr = "",
1777                                   Instruction *InsertBefore = 0) {
1778     return new
1779       ExtractValueInst(Agg, Idxs, NameStr, InsertBefore);
1780   }
1781   static ExtractValueInst *Create(Value *Agg,
1782                                   ArrayRef<unsigned> Idxs,
1783                                   const Twine &NameStr,
1784                                   BasicBlock *InsertAtEnd) {
1785     return new ExtractValueInst(Agg, Idxs, NameStr, InsertAtEnd);
1786   }
1787
1788   /// getIndexedType - Returns the type of the element that would be extracted
1789   /// with an extractvalue instruction with the specified parameters.
1790   ///
1791   /// Null is returned if the indices are invalid for the specified type.
1792   static Type *getIndexedType(Type *Agg, ArrayRef<unsigned> Idxs);
1793
1794   typedef const unsigned* idx_iterator;
1795   inline idx_iterator idx_begin() const { return Indices.begin(); }
1796   inline idx_iterator idx_end()   const { return Indices.end(); }
1797
1798   Value *getAggregateOperand() {
1799     return getOperand(0);
1800   }
1801   const Value *getAggregateOperand() const {
1802     return getOperand(0);
1803   }
1804   static unsigned getAggregateOperandIndex() {
1805     return 0U;                      // get index for modifying correct operand
1806   }
1807
1808   ArrayRef<unsigned> getIndices() const {
1809     return Indices;
1810   }
1811
1812   unsigned getNumIndices() const {
1813     return (unsigned)Indices.size();
1814   }
1815
1816   bool hasIndices() const {
1817     return true;
1818   }
1819
1820   // Methods for support type inquiry through isa, cast, and dyn_cast:
1821   static inline bool classof(const ExtractValueInst *) { return true; }
1822   static inline bool classof(const Instruction *I) {
1823     return I->getOpcode() == Instruction::ExtractValue;
1824   }
1825   static inline bool classof(const Value *V) {
1826     return isa<Instruction>(V) && classof(cast<Instruction>(V));
1827   }
1828 };
1829
1830 ExtractValueInst::ExtractValueInst(Value *Agg,
1831                                    ArrayRef<unsigned> Idxs,
1832                                    const Twine &NameStr,
1833                                    Instruction *InsertBefore)
1834   : UnaryInstruction(checkGEPType(getIndexedType(Agg->getType(), Idxs)),
1835                      ExtractValue, Agg, InsertBefore) {
1836   init(Idxs, NameStr);
1837 }
1838 ExtractValueInst::ExtractValueInst(Value *Agg,
1839                                    ArrayRef<unsigned> Idxs,
1840                                    const Twine &NameStr,
1841                                    BasicBlock *InsertAtEnd)
1842   : UnaryInstruction(checkGEPType(getIndexedType(Agg->getType(), Idxs)),
1843                      ExtractValue, Agg, InsertAtEnd) {
1844   init(Idxs, NameStr);
1845 }
1846
1847
1848 //===----------------------------------------------------------------------===//
1849 //                                InsertValueInst Class
1850 //===----------------------------------------------------------------------===//
1851
1852 /// InsertValueInst - This instruction inserts a struct field of array element
1853 /// value into an aggregate value.
1854 ///
1855 class InsertValueInst : public Instruction {
1856   SmallVector<unsigned, 4> Indices;
1857
1858   void *operator new(size_t, unsigned) LLVM_DELETED_FUNCTION;
1859   InsertValueInst(const InsertValueInst &IVI);
1860   void init(Value *Agg, Value *Val, ArrayRef<unsigned> Idxs,
1861             const Twine &NameStr);
1862
1863   /// Constructors - Create a insertvalue instruction with a base aggregate
1864   /// value, a value to insert, and a list of indices.  The first ctor can
1865   /// optionally insert before an existing instruction, the second appends
1866   /// the new instruction to the specified BasicBlock.
1867   inline InsertValueInst(Value *Agg, Value *Val,
1868                          ArrayRef<unsigned> Idxs,
1869                          const Twine &NameStr,
1870                          Instruction *InsertBefore);
1871   inline InsertValueInst(Value *Agg, Value *Val,
1872                          ArrayRef<unsigned> Idxs,
1873                          const Twine &NameStr, BasicBlock *InsertAtEnd);
1874
1875   /// Constructors - These two constructors are convenience methods because one
1876   /// and two index insertvalue instructions are so common.
1877   InsertValueInst(Value *Agg, Value *Val,
1878                   unsigned Idx, const Twine &NameStr = "",
1879                   Instruction *InsertBefore = 0);
1880   InsertValueInst(Value *Agg, Value *Val, unsigned Idx,
1881                   const Twine &NameStr, BasicBlock *InsertAtEnd);
1882 protected:
1883   virtual InsertValueInst *clone_impl() const;
1884 public:
1885   // allocate space for exactly two operands
1886   void *operator new(size_t s) {
1887     return User::operator new(s, 2);
1888   }
1889
1890   static InsertValueInst *Create(Value *Agg, Value *Val,
1891                                  ArrayRef<unsigned> Idxs,
1892                                  const Twine &NameStr = "",
1893                                  Instruction *InsertBefore = 0) {
1894     return new InsertValueInst(Agg, Val, Idxs, NameStr, InsertBefore);
1895   }
1896   static InsertValueInst *Create(Value *Agg, Value *Val,
1897                                  ArrayRef<unsigned> Idxs,
1898                                  const Twine &NameStr,
1899                                  BasicBlock *InsertAtEnd) {
1900     return new InsertValueInst(Agg, Val, Idxs, NameStr, InsertAtEnd);
1901   }
1902
1903   /// Transparently provide more efficient getOperand methods.
1904   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
1905
1906   typedef const unsigned* idx_iterator;
1907   inline idx_iterator idx_begin() const { return Indices.begin(); }
1908   inline idx_iterator idx_end()   const { return Indices.end(); }
1909
1910   Value *getAggregateOperand() {
1911     return getOperand(0);
1912   }
1913   const Value *getAggregateOperand() const {
1914     return getOperand(0);
1915   }
1916   static unsigned getAggregateOperandIndex() {
1917     return 0U;                      // get index for modifying correct operand
1918   }
1919
1920   Value *getInsertedValueOperand() {
1921     return getOperand(1);
1922   }
1923   const Value *getInsertedValueOperand() const {
1924     return getOperand(1);
1925   }
1926   static unsigned getInsertedValueOperandIndex() {
1927     return 1U;                      // get index for modifying correct operand
1928   }
1929
1930   ArrayRef<unsigned> getIndices() const {
1931     return Indices;
1932   }
1933
1934   unsigned getNumIndices() const {
1935     return (unsigned)Indices.size();
1936   }
1937
1938   bool hasIndices() const {
1939     return true;
1940   }
1941
1942   // Methods for support type inquiry through isa, cast, and dyn_cast:
1943   static inline bool classof(const InsertValueInst *) { return true; }
1944   static inline bool classof(const Instruction *I) {
1945     return I->getOpcode() == Instruction::InsertValue;
1946   }
1947   static inline bool classof(const Value *V) {
1948     return isa<Instruction>(V) && classof(cast<Instruction>(V));
1949   }
1950 };
1951
1952 template <>
1953 struct OperandTraits<InsertValueInst> :
1954   public FixedNumOperandTraits<InsertValueInst, 2> {
1955 };
1956
1957 InsertValueInst::InsertValueInst(Value *Agg,
1958                                  Value *Val,
1959                                  ArrayRef<unsigned> Idxs,
1960                                  const Twine &NameStr,
1961                                  Instruction *InsertBefore)
1962   : Instruction(Agg->getType(), InsertValue,
1963                 OperandTraits<InsertValueInst>::op_begin(this),
1964                 2, InsertBefore) {
1965   init(Agg, Val, Idxs, NameStr);
1966 }
1967 InsertValueInst::InsertValueInst(Value *Agg,
1968                                  Value *Val,
1969                                  ArrayRef<unsigned> Idxs,
1970                                  const Twine &NameStr,
1971                                  BasicBlock *InsertAtEnd)
1972   : Instruction(Agg->getType(), InsertValue,
1973                 OperandTraits<InsertValueInst>::op_begin(this),
1974                 2, InsertAtEnd) {
1975   init(Agg, Val, Idxs, NameStr);
1976 }
1977
1978 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertValueInst, Value)
1979
1980 //===----------------------------------------------------------------------===//
1981 //                               PHINode Class
1982 //===----------------------------------------------------------------------===//
1983
1984 // PHINode - The PHINode class is used to represent the magical mystical PHI
1985 // node, that can not exist in nature, but can be synthesized in a computer
1986 // scientist's overactive imagination.
1987 //
1988 class PHINode : public Instruction {
1989   void *operator new(size_t, unsigned) LLVM_DELETED_FUNCTION;
1990   /// ReservedSpace - The number of operands actually allocated.  NumOperands is
1991   /// the number actually in use.
1992   unsigned ReservedSpace;
1993   PHINode(const PHINode &PN);
1994   // allocate space for exactly zero operands
1995   void *operator new(size_t s) {
1996     return User::operator new(s, 0);
1997   }
1998   explicit PHINode(Type *Ty, unsigned NumReservedValues,
1999                    const Twine &NameStr = "", Instruction *InsertBefore = 0)
2000     : Instruction(Ty, Instruction::PHI, 0, 0, InsertBefore),
2001       ReservedSpace(NumReservedValues) {
2002     setName(NameStr);
2003     OperandList = allocHungoffUses(ReservedSpace);
2004   }
2005
2006   PHINode(Type *Ty, unsigned NumReservedValues, const Twine &NameStr,
2007           BasicBlock *InsertAtEnd)
2008     : Instruction(Ty, Instruction::PHI, 0, 0, InsertAtEnd),
2009       ReservedSpace(NumReservedValues) {
2010     setName(NameStr);
2011     OperandList = allocHungoffUses(ReservedSpace);
2012   }
2013 protected:
2014   // allocHungoffUses - this is more complicated than the generic
2015   // User::allocHungoffUses, because we have to allocate Uses for the incoming
2016   // values and pointers to the incoming blocks, all in one allocation.
2017   Use *allocHungoffUses(unsigned) const;
2018
2019   virtual PHINode *clone_impl() const;
2020 public:
2021   /// Constructors - NumReservedValues is a hint for the number of incoming
2022   /// edges that this phi node will have (use 0 if you really have no idea).
2023   static PHINode *Create(Type *Ty, unsigned NumReservedValues,
2024                          const Twine &NameStr = "",
2025                          Instruction *InsertBefore = 0) {
2026     return new PHINode(Ty, NumReservedValues, NameStr, InsertBefore);
2027   }
2028   static PHINode *Create(Type *Ty, unsigned NumReservedValues, 
2029                          const Twine &NameStr, BasicBlock *InsertAtEnd) {
2030     return new PHINode(Ty, NumReservedValues, NameStr, InsertAtEnd);
2031   }
2032   ~PHINode();
2033
2034   /// Provide fast operand accessors
2035   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
2036
2037   // Block iterator interface. This provides access to the list of incoming
2038   // basic blocks, which parallels the list of incoming values.
2039
2040   typedef BasicBlock **block_iterator;
2041   typedef BasicBlock * const *const_block_iterator;
2042
2043   block_iterator block_begin() {
2044     Use::UserRef *ref =
2045       reinterpret_cast<Use::UserRef*>(op_begin() + ReservedSpace);
2046     return reinterpret_cast<block_iterator>(ref + 1);
2047   }
2048
2049   const_block_iterator block_begin() const {
2050     const Use::UserRef *ref =
2051       reinterpret_cast<const Use::UserRef*>(op_begin() + ReservedSpace);
2052     return reinterpret_cast<const_block_iterator>(ref + 1);
2053   }
2054
2055   block_iterator block_end() {
2056     return block_begin() + getNumOperands();
2057   }
2058
2059   const_block_iterator block_end() const {
2060     return block_begin() + getNumOperands();
2061   }
2062
2063   /// getNumIncomingValues - Return the number of incoming edges
2064   ///
2065   unsigned getNumIncomingValues() const { return getNumOperands(); }
2066
2067   /// getIncomingValue - Return incoming value number x
2068   ///
2069   Value *getIncomingValue(unsigned i) const {
2070     return getOperand(i);
2071   }
2072   void setIncomingValue(unsigned i, Value *V) {
2073     setOperand(i, V);
2074   }
2075   static unsigned getOperandNumForIncomingValue(unsigned i) {
2076     return i;
2077   }
2078   static unsigned getIncomingValueNumForOperand(unsigned i) {
2079     return i;
2080   }
2081
2082   /// getIncomingBlock - Return incoming basic block number @p i.
2083   ///
2084   BasicBlock *getIncomingBlock(unsigned i) const {
2085     return block_begin()[i];
2086   }
2087
2088   /// getIncomingBlock - Return incoming basic block corresponding
2089   /// to an operand of the PHI.
2090   ///
2091   BasicBlock *getIncomingBlock(const Use &U) const {
2092     assert(this == U.getUser() && "Iterator doesn't point to PHI's Uses?");
2093     return getIncomingBlock(unsigned(&U - op_begin()));
2094   }
2095
2096   /// getIncomingBlock - Return incoming basic block corresponding
2097   /// to value use iterator.
2098   ///
2099   template <typename U>
2100   BasicBlock *getIncomingBlock(value_use_iterator<U> I) const {
2101     return getIncomingBlock(I.getUse());
2102   }
2103
2104   void setIncomingBlock(unsigned i, BasicBlock *BB) {
2105     block_begin()[i] = BB;
2106   }
2107
2108   /// addIncoming - Add an incoming value to the end of the PHI list
2109   ///
2110   void addIncoming(Value *V, BasicBlock *BB) {
2111     assert(V && "PHI node got a null value!");
2112     assert(BB && "PHI node got a null basic block!");
2113     assert(getType() == V->getType() &&
2114            "All operands to PHI node must be the same type as the PHI node!");
2115     if (NumOperands == ReservedSpace)
2116       growOperands();  // Get more space!
2117     // Initialize some new operands.
2118     ++NumOperands;
2119     setIncomingValue(NumOperands - 1, V);
2120     setIncomingBlock(NumOperands - 1, BB);
2121   }
2122
2123   /// removeIncomingValue - Remove an incoming value.  This is useful if a
2124   /// predecessor basic block is deleted.  The value removed is returned.
2125   ///
2126   /// If the last incoming value for a PHI node is removed (and DeletePHIIfEmpty
2127   /// is true), the PHI node is destroyed and any uses of it are replaced with
2128   /// dummy values.  The only time there should be zero incoming values to a PHI
2129   /// node is when the block is dead, so this strategy is sound.
2130   ///
2131   Value *removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty = true);
2132
2133   Value *removeIncomingValue(const BasicBlock *BB, bool DeletePHIIfEmpty=true) {
2134     int Idx = getBasicBlockIndex(BB);
2135     assert(Idx >= 0 && "Invalid basic block argument to remove!");
2136     return removeIncomingValue(Idx, DeletePHIIfEmpty);
2137   }
2138
2139   /// getBasicBlockIndex - Return the first index of the specified basic
2140   /// block in the value list for this PHI.  Returns -1 if no instance.
2141   ///
2142   int getBasicBlockIndex(const BasicBlock *BB) const {
2143     for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
2144       if (block_begin()[i] == BB)
2145         return i;
2146     return -1;
2147   }
2148
2149   Value *getIncomingValueForBlock(const BasicBlock *BB) const {
2150     int Idx = getBasicBlockIndex(BB);
2151     assert(Idx >= 0 && "Invalid basic block argument!");
2152     return getIncomingValue(Idx);
2153   }
2154
2155   /// hasConstantValue - If the specified PHI node always merges together the
2156   /// same value, return the value, otherwise return null.
2157   Value *hasConstantValue() const;
2158
2159   /// Methods for support type inquiry through isa, cast, and dyn_cast:
2160   static inline bool classof(const PHINode *) { return true; }
2161   static inline bool classof(const Instruction *I) {
2162     return I->getOpcode() == Instruction::PHI;
2163   }
2164   static inline bool classof(const Value *V) {
2165     return isa<Instruction>(V) && classof(cast<Instruction>(V));
2166   }
2167  private:
2168   void growOperands();
2169 };
2170
2171 template <>
2172 struct OperandTraits<PHINode> : public HungoffOperandTraits<2> {
2173 };
2174
2175 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(PHINode, Value)
2176
2177 //===----------------------------------------------------------------------===//
2178 //                           LandingPadInst Class
2179 //===----------------------------------------------------------------------===//
2180
2181 //===---------------------------------------------------------------------------
2182 /// LandingPadInst - The landingpad instruction holds all of the information
2183 /// necessary to generate correct exception handling. The landingpad instruction
2184 /// cannot be moved from the top of a landing pad block, which itself is
2185 /// accessible only from the 'unwind' edge of an invoke. This uses the
2186 /// SubclassData field in Value to store whether or not the landingpad is a
2187 /// cleanup.
2188 ///
2189 class LandingPadInst : public Instruction {
2190   /// ReservedSpace - The number of operands actually allocated.  NumOperands is
2191   /// the number actually in use.
2192   unsigned ReservedSpace;
2193   LandingPadInst(const LandingPadInst &LP);
2194 public:
2195   enum ClauseType { Catch, Filter };
2196 private:
2197   void *operator new(size_t, unsigned) LLVM_DELETED_FUNCTION;
2198   // Allocate space for exactly zero operands.
2199   void *operator new(size_t s) {
2200     return User::operator new(s, 0);
2201   }
2202   void growOperands(unsigned Size);
2203   void init(Value *PersFn, unsigned NumReservedValues, const Twine &NameStr);
2204
2205   explicit LandingPadInst(Type *RetTy, Value *PersonalityFn,
2206                           unsigned NumReservedValues, const Twine &NameStr,
2207                           Instruction *InsertBefore);
2208   explicit LandingPadInst(Type *RetTy, Value *PersonalityFn,
2209                           unsigned NumReservedValues, const Twine &NameStr,
2210                           BasicBlock *InsertAtEnd);
2211 protected:
2212   virtual LandingPadInst *clone_impl() const;
2213 public:
2214   /// Constructors - NumReservedClauses is a hint for the number of incoming
2215   /// clauses that this landingpad will have (use 0 if you really have no idea).
2216   static LandingPadInst *Create(Type *RetTy, Value *PersonalityFn,
2217                                 unsigned NumReservedClauses,
2218                                 const Twine &NameStr = "",
2219                                 Instruction *InsertBefore = 0);
2220   static LandingPadInst *Create(Type *RetTy, Value *PersonalityFn,
2221                                 unsigned NumReservedClauses,
2222                                 const Twine &NameStr, BasicBlock *InsertAtEnd);
2223   ~LandingPadInst();
2224
2225   /// Provide fast operand accessors
2226   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
2227
2228   /// getPersonalityFn - Get the personality function associated with this
2229   /// landing pad.
2230   Value *getPersonalityFn() const { return getOperand(0); }
2231
2232   /// isCleanup - Return 'true' if this landingpad instruction is a
2233   /// cleanup. I.e., it should be run when unwinding even if its landing pad
2234   /// doesn't catch the exception.
2235   bool isCleanup() const { return getSubclassDataFromInstruction() & 1; }
2236
2237   /// setCleanup - Indicate that this landingpad instruction is a cleanup.
2238   void setCleanup(bool V) {
2239     setInstructionSubclassData((getSubclassDataFromInstruction() & ~1) |
2240                                (V ? 1 : 0));
2241   }
2242
2243   /// addClause - Add a catch or filter clause to the landing pad.
2244   void addClause(Value *ClauseVal);
2245
2246   /// getClause - Get the value of the clause at index Idx. Use isCatch/isFilter
2247   /// to determine what type of clause this is.
2248   Value *getClause(unsigned Idx) const { return OperandList[Idx + 1]; }
2249
2250   /// isCatch - Return 'true' if the clause and index Idx is a catch clause.
2251   bool isCatch(unsigned Idx) const {
2252     return !isa<ArrayType>(OperandList[Idx + 1]->getType());
2253   }
2254
2255   /// isFilter - Return 'true' if the clause and index Idx is a filter clause.
2256   bool isFilter(unsigned Idx) const {
2257     return isa<ArrayType>(OperandList[Idx + 1]->getType());
2258   }
2259
2260   /// getNumClauses - Get the number of clauses for this landing pad.
2261   unsigned getNumClauses() const { return getNumOperands() - 1; }
2262
2263   /// reserveClauses - Grow the size of the operand list to accommodate the new
2264   /// number of clauses.
2265   void reserveClauses(unsigned Size) { growOperands(Size); }
2266
2267   // Methods for support type inquiry through isa, cast, and dyn_cast:
2268   static inline bool classof(const LandingPadInst *) { return true; }
2269   static inline bool classof(const Instruction *I) {
2270     return I->getOpcode() == Instruction::LandingPad;
2271   }
2272   static inline bool classof(const Value *V) {
2273     return isa<Instruction>(V) && classof(cast<Instruction>(V));
2274   }
2275 };
2276
2277 template <>
2278 struct OperandTraits<LandingPadInst> : public HungoffOperandTraits<2> {
2279 };
2280
2281 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(LandingPadInst, Value)
2282
2283 //===----------------------------------------------------------------------===//
2284 //                               ReturnInst Class
2285 //===----------------------------------------------------------------------===//
2286
2287 //===---------------------------------------------------------------------------
2288 /// ReturnInst - Return a value (possibly void), from a function.  Execution
2289 /// does not continue in this function any longer.
2290 ///
2291 class ReturnInst : public TerminatorInst {
2292   ReturnInst(const ReturnInst &RI);
2293
2294 private:
2295   // ReturnInst constructors:
2296   // ReturnInst()                  - 'ret void' instruction
2297   // ReturnInst(    null)          - 'ret void' instruction
2298   // ReturnInst(Value* X)          - 'ret X'    instruction
2299   // ReturnInst(    null, Inst *I) - 'ret void' instruction, insert before I
2300   // ReturnInst(Value* X, Inst *I) - 'ret X'    instruction, insert before I
2301   // ReturnInst(    null, BB *B)   - 'ret void' instruction, insert @ end of B
2302   // ReturnInst(Value* X, BB *B)   - 'ret X'    instruction, insert @ end of B
2303   //
2304   // NOTE: If the Value* passed is of type void then the constructor behaves as
2305   // if it was passed NULL.
2306   explicit ReturnInst(LLVMContext &C, Value *retVal = 0,
2307                       Instruction *InsertBefore = 0);
2308   ReturnInst(LLVMContext &C, Value *retVal, BasicBlock *InsertAtEnd);
2309   explicit ReturnInst(LLVMContext &C, BasicBlock *InsertAtEnd);
2310 protected:
2311   virtual ReturnInst *clone_impl() const;
2312 public:
2313   static ReturnInst* Create(LLVMContext &C, Value *retVal = 0,
2314                             Instruction *InsertBefore = 0) {
2315     return new(!!retVal) ReturnInst(C, retVal, InsertBefore);
2316   }
2317   static ReturnInst* Create(LLVMContext &C, Value *retVal,
2318                             BasicBlock *InsertAtEnd) {
2319     return new(!!retVal) ReturnInst(C, retVal, InsertAtEnd);
2320   }
2321   static ReturnInst* Create(LLVMContext &C, BasicBlock *InsertAtEnd) {
2322     return new(0) ReturnInst(C, InsertAtEnd);
2323   }
2324   virtual ~ReturnInst();
2325
2326   /// Provide fast operand accessors
2327   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
2328
2329   /// Convenience accessor. Returns null if there is no return value.
2330   Value *getReturnValue() const {
2331     return getNumOperands() != 0 ? getOperand(0) : 0;
2332   }
2333
2334   unsigned getNumSuccessors() const { return 0; }
2335
2336   // Methods for support type inquiry through isa, cast, and dyn_cast:
2337   static inline bool classof(const ReturnInst *) { return true; }
2338   static inline bool classof(const Instruction *I) {
2339     return (I->getOpcode() == Instruction::Ret);
2340   }
2341   static inline bool classof(const Value *V) {
2342     return isa<Instruction>(V) && classof(cast<Instruction>(V));
2343   }
2344  private:
2345   virtual BasicBlock *getSuccessorV(unsigned idx) const;
2346   virtual unsigned getNumSuccessorsV() const;
2347   virtual void setSuccessorV(unsigned idx, BasicBlock *B);
2348 };
2349
2350 template <>
2351 struct OperandTraits<ReturnInst> : public VariadicOperandTraits<ReturnInst> {
2352 };
2353
2354 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ReturnInst, Value)
2355
2356 //===----------------------------------------------------------------------===//
2357 //                               BranchInst Class
2358 //===----------------------------------------------------------------------===//
2359
2360 //===---------------------------------------------------------------------------
2361 /// BranchInst - Conditional or Unconditional Branch instruction.
2362 ///
2363 class BranchInst : public TerminatorInst {
2364   /// Ops list - Branches are strange.  The operands are ordered:
2365   ///  [Cond, FalseDest,] TrueDest.  This makes some accessors faster because
2366   /// they don't have to check for cond/uncond branchness. These are mostly
2367   /// accessed relative from op_end().
2368   BranchInst(const BranchInst &BI);
2369   void AssertOK();
2370   // BranchInst constructors (where {B, T, F} are blocks, and C is a condition):
2371   // BranchInst(BB *B)                           - 'br B'
2372   // BranchInst(BB* T, BB *F, Value *C)          - 'br C, T, F'
2373   // BranchInst(BB* B, Inst *I)                  - 'br B'        insert before I
2374   // BranchInst(BB* T, BB *F, Value *C, Inst *I) - 'br C, T, F', insert before I
2375   // BranchInst(BB* B, BB *I)                    - 'br B'        insert at end
2376   // BranchInst(BB* T, BB *F, Value *C, BB *I)   - 'br C, T, F', insert at end
2377   explicit BranchInst(BasicBlock *IfTrue, Instruction *InsertBefore = 0);
2378   BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
2379              Instruction *InsertBefore = 0);
2380   BranchInst(BasicBlock *IfTrue, BasicBlock *InsertAtEnd);
2381   BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
2382              BasicBlock *InsertAtEnd);
2383 protected:
2384   virtual BranchInst *clone_impl() const;
2385 public:
2386   static BranchInst *Create(BasicBlock *IfTrue, Instruction *InsertBefore = 0) {
2387     return new(1) BranchInst(IfTrue, InsertBefore);
2388   }
2389   static BranchInst *Create(BasicBlock *IfTrue, BasicBlock *IfFalse,
2390                             Value *Cond, Instruction *InsertBefore = 0) {
2391     return new(3) BranchInst(IfTrue, IfFalse, Cond, InsertBefore);
2392   }
2393   static BranchInst *Create(BasicBlock *IfTrue, BasicBlock *InsertAtEnd) {
2394     return new(1) BranchInst(IfTrue, InsertAtEnd);
2395   }
2396   static BranchInst *Create(BasicBlock *IfTrue, BasicBlock *IfFalse,
2397                             Value *Cond, BasicBlock *InsertAtEnd) {
2398     return new(3) BranchInst(IfTrue, IfFalse, Cond, InsertAtEnd);
2399   }
2400
2401   /// Transparently provide more efficient getOperand methods.
2402   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
2403
2404   bool isUnconditional() const { return getNumOperands() == 1; }
2405   bool isConditional()   const { return getNumOperands() == 3; }
2406
2407   Value *getCondition() const {
2408     assert(isConditional() && "Cannot get condition of an uncond branch!");
2409     return Op<-3>();
2410   }
2411
2412   void setCondition(Value *V) {
2413     assert(isConditional() && "Cannot set condition of unconditional branch!");
2414     Op<-3>() = V;
2415   }
2416
2417   unsigned getNumSuccessors() const { return 1+isConditional(); }
2418
2419   BasicBlock *getSuccessor(unsigned i) const {
2420     assert(i < getNumSuccessors() && "Successor # out of range for Branch!");
2421     return cast_or_null<BasicBlock>((&Op<-1>() - i)->get());
2422   }
2423
2424   void setSuccessor(unsigned idx, BasicBlock *NewSucc) {
2425     assert(idx < getNumSuccessors() && "Successor # out of range for Branch!");
2426     *(&Op<-1>() - idx) = (Value*)NewSucc;
2427   }
2428
2429   /// \brief Swap the successors of this branch instruction.
2430   ///
2431   /// Swaps the successors of the branch instruction. This also swaps any
2432   /// branch weight metadata associated with the instruction so that it
2433   /// continues to map correctly to each operand.
2434   void swapSuccessors();
2435
2436   // Methods for support type inquiry through isa, cast, and dyn_cast:
2437   static inline bool classof(const BranchInst *) { return true; }
2438   static inline bool classof(const Instruction *I) {
2439     return (I->getOpcode() == Instruction::Br);
2440   }
2441   static inline bool classof(const Value *V) {
2442     return isa<Instruction>(V) && classof(cast<Instruction>(V));
2443   }
2444 private:
2445   virtual BasicBlock *getSuccessorV(unsigned idx) const;
2446   virtual unsigned getNumSuccessorsV() const;
2447   virtual void setSuccessorV(unsigned idx, BasicBlock *B);
2448 };
2449
2450 template <>
2451 struct OperandTraits<BranchInst> : public VariadicOperandTraits<BranchInst, 1> {
2452 };
2453
2454 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(BranchInst, Value)
2455
2456 //===----------------------------------------------------------------------===//
2457 //                               SwitchInst Class
2458 //===----------------------------------------------------------------------===//
2459
2460 //===---------------------------------------------------------------------------
2461 /// SwitchInst - Multiway switch
2462 ///
2463 class SwitchInst : public TerminatorInst {
2464   void *operator new(size_t, unsigned) LLVM_DELETED_FUNCTION;
2465   unsigned ReservedSpace;
2466   // Operands format:
2467   // Operand[0]    = Value to switch on
2468   // Operand[1]    = Default basic block destination
2469   // Operand[2n  ] = Value to match
2470   // Operand[2n+1] = BasicBlock to go to on match
2471   
2472   // Store case values separately from operands list. We needn't User-Use
2473   // concept here, since it is just a case value, it will always constant,
2474   // and case value couldn't reused with another instructions/values.
2475   // Additionally:
2476   // It allows us to use custom type for case values that is not inherited
2477   // from Value. Since case value is a complex type that implements
2478   // the subset of integers, we needn't extract sub-constants within
2479   // slow getAggregateElement method.
2480   // For case values we will use std::list to by two reasons:
2481   // 1. It allows to add/remove cases without whole collection reallocation.
2482   // 2. In most of cases we needn't random access.
2483   // Currently case values are also stored in Operands List, but it will moved
2484   // out in future commits.
2485   typedef std::list<IntegersSubset> Subsets;
2486   typedef Subsets::iterator SubsetsIt;
2487   typedef Subsets::const_iterator SubsetsConstIt;
2488   
2489   Subsets TheSubsets;
2490   
2491   SwitchInst(const SwitchInst &SI);
2492   void init(Value *Value, BasicBlock *Default, unsigned NumReserved);
2493   void growOperands();
2494   // allocate space for exactly zero operands
2495   void *operator new(size_t s) {
2496     return User::operator new(s, 0);
2497   }
2498   /// SwitchInst ctor - Create a new switch instruction, specifying a value to
2499   /// switch on and a default destination.  The number of additional cases can
2500   /// be specified here to make memory allocation more efficient.  This
2501   /// constructor can also autoinsert before another instruction.
2502   SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
2503              Instruction *InsertBefore);
2504
2505   /// SwitchInst ctor - Create a new switch instruction, specifying a value to
2506   /// switch on and a default destination.  The number of additional cases can
2507   /// be specified here to make memory allocation more efficient.  This
2508   /// constructor also autoinserts at the end of the specified BasicBlock.
2509   SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
2510              BasicBlock *InsertAtEnd);
2511 protected:
2512   virtual SwitchInst *clone_impl() const;
2513 public:
2514   
2515   // FIXME: Currently there are a lot of unclean template parameters,
2516   // we need to make refactoring in future.
2517   // All these parameters are used to implement both iterator and const_iterator
2518   // without code duplication.
2519   // SwitchInstTy may be "const SwitchInst" or "SwitchInst"
2520   // ConstantIntTy may be "const ConstantInt" or "ConstantInt"
2521   // SubsetsItTy may be SubsetsConstIt or SubsetsIt
2522   // BasicBlockTy may be "const BasicBlock" or "BasicBlock"
2523   template <class SwitchInstTy, class ConstantIntTy,
2524             class SubsetsItTy, class BasicBlockTy> 
2525     class CaseIteratorT;
2526
2527   typedef CaseIteratorT<const SwitchInst, const ConstantInt,
2528                         SubsetsConstIt, const BasicBlock> ConstCaseIt;
2529   class CaseIt;
2530   
2531   // -2
2532   static const unsigned DefaultPseudoIndex = static_cast<unsigned>(~0L-1);
2533   
2534   static SwitchInst *Create(Value *Value, BasicBlock *Default,
2535                             unsigned NumCases, Instruction *InsertBefore = 0) {
2536     return new SwitchInst(Value, Default, NumCases, InsertBefore);
2537   }
2538   static SwitchInst *Create(Value *Value, BasicBlock *Default,
2539                             unsigned NumCases, BasicBlock *InsertAtEnd) {
2540     return new SwitchInst(Value, Default, NumCases, InsertAtEnd);
2541   }
2542   
2543   ~SwitchInst();
2544
2545   /// Provide fast operand accessors
2546   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
2547
2548   // Accessor Methods for Switch stmt
2549   Value *getCondition() const { return getOperand(0); }
2550   void setCondition(Value *V) { setOperand(0, V); }
2551
2552   BasicBlock *getDefaultDest() const {
2553     return cast<BasicBlock>(getOperand(1));
2554   }
2555
2556   void setDefaultDest(BasicBlock *DefaultCase) {
2557     setOperand(1, reinterpret_cast<Value*>(DefaultCase));
2558   }
2559
2560   /// getNumCases - return the number of 'cases' in this switch instruction,
2561   /// except the default case
2562   unsigned getNumCases() const {
2563     return getNumOperands()/2 - 1;
2564   }
2565
2566   /// Returns a read/write iterator that points to the first
2567   /// case in SwitchInst.
2568   CaseIt case_begin() {
2569     return CaseIt(this, 0, TheSubsets.begin());
2570   }
2571   /// Returns a read-only iterator that points to the first
2572   /// case in the SwitchInst.
2573   ConstCaseIt case_begin() const {
2574     return ConstCaseIt(this, 0, TheSubsets.begin());
2575   }
2576   
2577   /// Returns a read/write iterator that points one past the last
2578   /// in the SwitchInst.
2579   CaseIt case_end() {
2580     return CaseIt(this, getNumCases(), TheSubsets.end());
2581   }
2582   /// Returns a read-only iterator that points one past the last
2583   /// in the SwitchInst.
2584   ConstCaseIt case_end() const {
2585     return ConstCaseIt(this, getNumCases(), TheSubsets.end());
2586   }
2587   /// Returns an iterator that points to the default case.
2588   /// Note: this iterator allows to resolve successor only. Attempt
2589   /// to resolve case value causes an assertion.
2590   /// Also note, that increment and decrement also causes an assertion and
2591   /// makes iterator invalid. 
2592   CaseIt case_default() {
2593     return CaseIt(this, DefaultPseudoIndex, TheSubsets.end());
2594   }
2595   ConstCaseIt case_default() const {
2596     return ConstCaseIt(this, DefaultPseudoIndex, TheSubsets.end());
2597   }
2598   
2599   /// findCaseValue - Search all of the case values for the specified constant.
2600   /// If it is explicitly handled, return the case iterator of it, otherwise
2601   /// return default case iterator to indicate
2602   /// that it is handled by the default handler.
2603   CaseIt findCaseValue(const ConstantInt *C) {
2604     for (CaseIt i = case_begin(), e = case_end(); i != e; ++i)
2605       if (i.getCaseValueEx().isSatisfies(IntItem::fromConstantInt(C)))
2606         return i;
2607     return case_default();
2608   }
2609   ConstCaseIt findCaseValue(const ConstantInt *C) const {
2610     for (ConstCaseIt i = case_begin(), e = case_end(); i != e; ++i)
2611       if (i.getCaseValueEx().isSatisfies(IntItem::fromConstantInt(C)))
2612         return i;
2613     return case_default();
2614   }    
2615   
2616   /// findCaseDest - Finds the unique case value for a given successor. Returns
2617   /// null if the successor is not found, not unique, or is the default case.
2618   ConstantInt *findCaseDest(BasicBlock *BB) {
2619     if (BB == getDefaultDest()) return NULL;
2620
2621     ConstantInt *CI = NULL;
2622     for (CaseIt i = case_begin(), e = case_end(); i != e; ++i) {
2623       if (i.getCaseSuccessor() == BB) {
2624         if (CI) return NULL;   // Multiple cases lead to BB.
2625         else CI = i.getCaseValue();
2626       }
2627     }
2628     return CI;
2629   }
2630
2631   /// addCase - Add an entry to the switch instruction...
2632   /// @deprecated
2633   /// Note:
2634   /// This action invalidates case_end(). Old case_end() iterator will
2635   /// point to the added case.
2636   void addCase(ConstantInt *OnVal, BasicBlock *Dest);
2637   
2638   /// addCase - Add an entry to the switch instruction.
2639   /// Note:
2640   /// This action invalidates case_end(). Old case_end() iterator will
2641   /// point to the added case.
2642   void addCase(IntegersSubset& OnVal, BasicBlock *Dest);
2643
2644   /// removeCase - This method removes the specified case and its successor
2645   /// from the switch instruction. Note that this operation may reorder the
2646   /// remaining cases at index idx and above.
2647   /// Note:
2648   /// This action invalidates iterators for all cases following the one removed,
2649   /// including the case_end() iterator.
2650   void removeCase(CaseIt& i);
2651
2652   unsigned getNumSuccessors() const { return getNumOperands()/2; }
2653   BasicBlock *getSuccessor(unsigned idx) const {
2654     assert(idx < getNumSuccessors() &&"Successor idx out of range for switch!");
2655     return cast<BasicBlock>(getOperand(idx*2+1));
2656   }
2657   void setSuccessor(unsigned idx, BasicBlock *NewSucc) {
2658     assert(idx < getNumSuccessors() && "Successor # out of range for switch!");
2659     setOperand(idx*2+1, (Value*)NewSucc);
2660   }
2661   
2662   uint16_t hash() const {
2663     uint32_t NumberOfCases = (uint32_t)getNumCases();
2664     uint16_t Hash = (0xFFFF & NumberOfCases) ^ (NumberOfCases >> 16);
2665     for (ConstCaseIt i = case_begin(), e = case_end();
2666          i != e; ++i) {
2667       uint32_t NumItems = (uint32_t)i.getCaseValueEx().getNumItems(); 
2668       Hash = (Hash << 1) ^ (0xFFFF & NumItems) ^ (NumItems >> 16);
2669     }
2670     return Hash;
2671   }  
2672   
2673   // Case iterators definition.
2674
2675   template <class SwitchInstTy, class ConstantIntTy,
2676             class SubsetsItTy, class BasicBlockTy> 
2677   class CaseIteratorT {
2678   protected:
2679     
2680     SwitchInstTy *SI;
2681     unsigned long Index;
2682     SubsetsItTy SubsetIt;
2683     
2684     /// Initializes case iterator for given SwitchInst and for given
2685     /// case number.    
2686     friend class SwitchInst;
2687     CaseIteratorT(SwitchInstTy *SI, unsigned SuccessorIndex,
2688                   SubsetsItTy CaseValueIt) {
2689       this->SI = SI;
2690       Index = SuccessorIndex;
2691       this->SubsetIt = CaseValueIt;
2692     }
2693     
2694   public:
2695     typedef typename SubsetsItTy::reference IntegersSubsetRef;
2696     typedef CaseIteratorT<SwitchInstTy, ConstantIntTy,
2697                           SubsetsItTy, BasicBlockTy> Self;
2698     
2699     CaseIteratorT(SwitchInstTy *SI, unsigned CaseNum) {
2700           this->SI = SI;
2701           Index = CaseNum;
2702           SubsetIt = SI->TheSubsets.begin();
2703           std::advance(SubsetIt, CaseNum);
2704         }
2705         
2706     
2707     /// Initializes case iterator for given SwitchInst and for given
2708     /// TerminatorInst's successor index.
2709     static Self fromSuccessorIndex(SwitchInstTy *SI, unsigned SuccessorIndex) {
2710       assert(SuccessorIndex < SI->getNumSuccessors() &&
2711              "Successor index # out of range!");    
2712       return SuccessorIndex != 0 ? 
2713              Self(SI, SuccessorIndex - 1) :
2714              Self(SI, DefaultPseudoIndex);       
2715     }
2716     
2717     /// Resolves case value for current case.
2718     /// @deprecated
2719     ConstantIntTy *getCaseValue() {
2720       assert(Index < SI->getNumCases() && "Index out the number of cases.");
2721       IntegersSubsetRef CaseRanges = *SubsetIt;
2722       
2723       // FIXME: Currently we work with ConstantInt based cases.
2724       // So return CaseValue as ConstantInt.
2725       return CaseRanges.getSingleNumber(0).toConstantInt();
2726     }
2727
2728     /// Resolves case value for current case.
2729     IntegersSubsetRef getCaseValueEx() {
2730       assert(Index < SI->getNumCases() && "Index out the number of cases.");
2731       return *SubsetIt;
2732     }
2733     
2734     /// Resolves successor for current case.
2735     BasicBlockTy *getCaseSuccessor() {
2736       assert((Index < SI->getNumCases() ||
2737               Index == DefaultPseudoIndex) &&
2738              "Index out the number of cases.");
2739       return SI->getSuccessor(getSuccessorIndex());      
2740     }
2741     
2742     /// Returns number of current case.
2743     unsigned getCaseIndex() const { return Index; }
2744     
2745     /// Returns TerminatorInst's successor index for current case successor.
2746     unsigned getSuccessorIndex() const {
2747       assert((Index == DefaultPseudoIndex || Index < SI->getNumCases()) &&
2748              "Index out the number of cases.");
2749       return Index != DefaultPseudoIndex ? Index + 1 : 0;
2750     }
2751     
2752     Self operator++() {
2753       // Check index correctness after increment.
2754       // Note: Index == getNumCases() means end().
2755       assert(Index+1 <= SI->getNumCases() && "Index out the number of cases.");
2756       ++Index;
2757       if (Index == 0)
2758         SubsetIt = SI->TheSubsets.begin();
2759       else
2760         ++SubsetIt;
2761       return *this;
2762     }
2763     Self operator++(int) {
2764       Self tmp = *this;
2765       ++(*this);
2766       return tmp;
2767     }
2768     Self operator--() { 
2769       // Check index correctness after decrement.
2770       // Note: Index == getNumCases() means end().
2771       // Also allow "-1" iterator here. That will became valid after ++.
2772       unsigned NumCases = SI->getNumCases();
2773       assert((Index == 0 || Index-1 <= NumCases) &&
2774              "Index out the number of cases.");
2775       --Index;
2776       if (Index == NumCases) {
2777         SubsetIt = SI->TheSubsets.end();
2778         return *this;
2779       }
2780         
2781       if (Index != -1UL)
2782         --SubsetIt;
2783       
2784       return *this;
2785     }
2786     Self operator--(int) {
2787       Self tmp = *this;
2788       --(*this);
2789       return tmp;
2790     }
2791     bool operator==(const Self& RHS) const {
2792       assert(RHS.SI == SI && "Incompatible operators.");
2793       return RHS.Index == Index;
2794     }
2795     bool operator!=(const Self& RHS) const {
2796       assert(RHS.SI == SI && "Incompatible operators.");
2797       return RHS.Index != Index;
2798     }
2799   };
2800
2801   class CaseIt : public CaseIteratorT<SwitchInst, ConstantInt,
2802                                       SubsetsIt, BasicBlock> {
2803     typedef CaseIteratorT<SwitchInst, ConstantInt, SubsetsIt, BasicBlock>
2804       ParentTy;
2805     
2806   protected:
2807     friend class SwitchInst;
2808     CaseIt(SwitchInst *SI, unsigned CaseNum, SubsetsIt SubsetIt) :
2809       ParentTy(SI, CaseNum, SubsetIt) {}
2810     
2811     void updateCaseValueOperand(IntegersSubset& V) {
2812       SI->setOperand(2 + Index*2, reinterpret_cast<Value*>((Constant*)V));      
2813     }
2814   
2815   public:
2816
2817     CaseIt(SwitchInst *SI, unsigned CaseNum) : ParentTy(SI, CaseNum) {}    
2818     
2819     CaseIt(const ParentTy& Src) : ParentTy(Src) {}
2820
2821     /// Sets the new value for current case.    
2822     /// @deprecated.
2823     void setValue(ConstantInt *V) {
2824       assert(Index < SI->getNumCases() && "Index out the number of cases.");
2825       IntegersSubsetToBB Mapping;
2826       // FIXME: Currently we work with ConstantInt based cases.
2827       // So inititalize IntItem container directly from ConstantInt.
2828       Mapping.add(IntItem::fromConstantInt(V));
2829       *SubsetIt = Mapping.getCase();
2830       updateCaseValueOperand(*SubsetIt);
2831     }
2832     
2833     /// Sets the new value for current case.
2834     void setValueEx(IntegersSubset& V) {
2835       assert(Index < SI->getNumCases() && "Index out the number of cases.");
2836       *SubsetIt = V;
2837       updateCaseValueOperand(*SubsetIt);   
2838     }
2839     
2840     /// Sets the new successor for current case.
2841     void setSuccessor(BasicBlock *S) {
2842       SI->setSuccessor(getSuccessorIndex(), S);      
2843     }
2844   };
2845
2846   // Methods for support type inquiry through isa, cast, and dyn_cast:
2847
2848   static inline bool classof(const SwitchInst *) { return true; }
2849   static inline bool classof(const Instruction *I) {
2850     return I->getOpcode() == Instruction::Switch;
2851   }
2852   static inline bool classof(const Value *V) {
2853     return isa<Instruction>(V) && classof(cast<Instruction>(V));
2854   }
2855 private:
2856   virtual BasicBlock *getSuccessorV(unsigned idx) const;
2857   virtual unsigned getNumSuccessorsV() const;
2858   virtual void setSuccessorV(unsigned idx, BasicBlock *B);
2859 };
2860
2861 template <>
2862 struct OperandTraits<SwitchInst> : public HungoffOperandTraits<2> {
2863 };
2864
2865 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(SwitchInst, Value)
2866
2867
2868 //===----------------------------------------------------------------------===//
2869 //                             IndirectBrInst Class
2870 //===----------------------------------------------------------------------===//
2871
2872 //===---------------------------------------------------------------------------
2873 /// IndirectBrInst - Indirect Branch Instruction.
2874 ///
2875 class IndirectBrInst : public TerminatorInst {
2876   void *operator new(size_t, unsigned) LLVM_DELETED_FUNCTION;
2877   unsigned ReservedSpace;
2878   // Operand[0]    = Value to switch on
2879   // Operand[1]    = Default basic block destination
2880   // Operand[2n  ] = Value to match
2881   // Operand[2n+1] = BasicBlock to go to on match
2882   IndirectBrInst(const IndirectBrInst &IBI);
2883   void init(Value *Address, unsigned NumDests);
2884   void growOperands();
2885   // allocate space for exactly zero operands
2886   void *operator new(size_t s) {
2887     return User::operator new(s, 0);
2888   }
2889   /// IndirectBrInst ctor - Create a new indirectbr instruction, specifying an
2890   /// Address to jump to.  The number of expected destinations can be specified
2891   /// here to make memory allocation more efficient.  This constructor can also
2892   /// autoinsert before another instruction.
2893   IndirectBrInst(Value *Address, unsigned NumDests, Instruction *InsertBefore);
2894
2895   /// IndirectBrInst ctor - Create a new indirectbr instruction, specifying an
2896   /// Address to jump to.  The number of expected destinations can be specified
2897   /// here to make memory allocation more efficient.  This constructor also
2898   /// autoinserts at the end of the specified BasicBlock.
2899   IndirectBrInst(Value *Address, unsigned NumDests, BasicBlock *InsertAtEnd);
2900 protected:
2901   virtual IndirectBrInst *clone_impl() const;
2902 public:
2903   static IndirectBrInst *Create(Value *Address, unsigned NumDests,
2904                                 Instruction *InsertBefore = 0) {
2905     return new IndirectBrInst(Address, NumDests, InsertBefore);
2906   }
2907   static IndirectBrInst *Create(Value *Address, unsigned NumDests,
2908                                 BasicBlock *InsertAtEnd) {
2909     return new IndirectBrInst(Address, NumDests, InsertAtEnd);
2910   }
2911   ~IndirectBrInst();
2912
2913   /// Provide fast operand accessors.
2914   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
2915
2916   // Accessor Methods for IndirectBrInst instruction.
2917   Value *getAddress() { return getOperand(0); }
2918   const Value *getAddress() const { return getOperand(0); }
2919   void setAddress(Value *V) { setOperand(0, V); }
2920
2921
2922   /// getNumDestinations - return the number of possible destinations in this
2923   /// indirectbr instruction.
2924   unsigned getNumDestinations() const { return getNumOperands()-1; }
2925
2926   /// getDestination - Return the specified destination.
2927   BasicBlock *getDestination(unsigned i) { return getSuccessor(i); }
2928   const BasicBlock *getDestination(unsigned i) const { return getSuccessor(i); }
2929
2930   /// addDestination - Add a destination.
2931   ///
2932   void addDestination(BasicBlock *Dest);
2933
2934   /// removeDestination - This method removes the specified successor from the
2935   /// indirectbr instruction.
2936   void removeDestination(unsigned i);
2937
2938   unsigned getNumSuccessors() const { return getNumOperands()-1; }
2939   BasicBlock *getSuccessor(unsigned i) const {
2940     return cast<BasicBlock>(getOperand(i+1));
2941   }
2942   void setSuccessor(unsigned i, BasicBlock *NewSucc) {
2943     setOperand(i+1, (Value*)NewSucc);
2944   }
2945
2946   // Methods for support type inquiry through isa, cast, and dyn_cast:
2947   static inline bool classof(const IndirectBrInst *) { return true; }
2948   static inline bool classof(const Instruction *I) {
2949     return I->getOpcode() == Instruction::IndirectBr;
2950   }
2951   static inline bool classof(const Value *V) {
2952     return isa<Instruction>(V) && classof(cast<Instruction>(V));
2953   }
2954 private:
2955   virtual BasicBlock *getSuccessorV(unsigned idx) const;
2956   virtual unsigned getNumSuccessorsV() const;
2957   virtual void setSuccessorV(unsigned idx, BasicBlock *B);
2958 };
2959
2960 template <>
2961 struct OperandTraits<IndirectBrInst> : public HungoffOperandTraits<1> {
2962 };
2963
2964 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(IndirectBrInst, Value)
2965
2966
2967 //===----------------------------------------------------------------------===//
2968 //                               InvokeInst Class
2969 //===----------------------------------------------------------------------===//
2970
2971 /// InvokeInst - Invoke instruction.  The SubclassData field is used to hold the
2972 /// calling convention of the call.
2973 ///
2974 class InvokeInst : public TerminatorInst {
2975   AttrListPtr AttributeList;
2976   InvokeInst(const InvokeInst &BI);
2977   void init(Value *Func, BasicBlock *IfNormal, BasicBlock *IfException,
2978             ArrayRef<Value *> Args, const Twine &NameStr);
2979
2980   /// Construct an InvokeInst given a range of arguments.
2981   ///
2982   /// @brief Construct an InvokeInst from a range of arguments
2983   inline InvokeInst(Value *Func, BasicBlock *IfNormal, BasicBlock *IfException,
2984                     ArrayRef<Value *> Args, unsigned Values,
2985                     const Twine &NameStr, Instruction *InsertBefore);
2986
2987   /// Construct an InvokeInst given a range of arguments.
2988   ///
2989   /// @brief Construct an InvokeInst from a range of arguments
2990   inline InvokeInst(Value *Func, BasicBlock *IfNormal, BasicBlock *IfException,
2991                     ArrayRef<Value *> Args, unsigned Values,
2992                     const Twine &NameStr, BasicBlock *InsertAtEnd);
2993 protected:
2994   virtual InvokeInst *clone_impl() const;
2995 public:
2996   static InvokeInst *Create(Value *Func,
2997                             BasicBlock *IfNormal, BasicBlock *IfException,
2998                             ArrayRef<Value *> Args, const Twine &NameStr = "",
2999                             Instruction *InsertBefore = 0) {
3000     unsigned Values = unsigned(Args.size()) + 3;
3001     return new(Values) InvokeInst(Func, IfNormal, IfException, Args,
3002                                   Values, NameStr, InsertBefore);
3003   }
3004   static InvokeInst *Create(Value *Func,
3005                             BasicBlock *IfNormal, BasicBlock *IfException,
3006                             ArrayRef<Value *> Args, const Twine &NameStr,
3007                             BasicBlock *InsertAtEnd) {
3008     unsigned Values = unsigned(Args.size()) + 3;
3009     return new(Values) InvokeInst(Func, IfNormal, IfException, Args,
3010                                   Values, NameStr, InsertAtEnd);
3011   }
3012
3013   /// Provide fast operand accessors
3014   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
3015
3016   /// getNumArgOperands - Return the number of invoke arguments.
3017   ///
3018   unsigned getNumArgOperands() const { return getNumOperands() - 3; }
3019
3020   /// getArgOperand/setArgOperand - Return/set the i-th invoke argument.
3021   ///
3022   Value *getArgOperand(unsigned i) const { return getOperand(i); }
3023   void setArgOperand(unsigned i, Value *v) { setOperand(i, v); }
3024
3025   /// getCallingConv/setCallingConv - Get or set the calling convention of this
3026   /// function call.
3027   CallingConv::ID getCallingConv() const {
3028     return static_cast<CallingConv::ID>(getSubclassDataFromInstruction());
3029   }
3030   void setCallingConv(CallingConv::ID CC) {
3031     setInstructionSubclassData(static_cast<unsigned>(CC));
3032   }
3033
3034   /// getAttributes - Return the parameter attributes for this invoke.
3035   ///
3036   const AttrListPtr &getAttributes() const { return AttributeList; }
3037
3038   /// setAttributes - Set the parameter attributes for this invoke.
3039   ///
3040   void setAttributes(const AttrListPtr &Attrs) { AttributeList = Attrs; }
3041
3042   /// addAttribute - adds the attribute to the list of attributes.
3043   void addAttribute(unsigned i, Attributes attr);
3044
3045   /// removeAttribute - removes the attribute from the list of attributes.
3046   void removeAttribute(unsigned i, Attributes attr);
3047
3048   /// @brief Determine whether this call has the NoAlias attribute.
3049   bool hasFnAttr(Attributes::AttrVal A) const;
3050
3051   /// @brief Determine whether the call or the callee has the given attributes.
3052   bool paramHasAttr(unsigned i, Attributes::AttrVal A) const;
3053
3054   /// @brief Extract the alignment for a call or parameter (0=unknown).
3055   unsigned getParamAlignment(unsigned i) const {
3056     return AttributeList.getParamAlignment(i);
3057   }
3058
3059   /// @brief Return true if the call should not be inlined.
3060   bool isNoInline() const { return hasFnAttr(Attributes::NoInline); }
3061   void setIsNoInline() {
3062     Attributes::Builder B;
3063     B.addAttribute(Attributes::NoInline);
3064     addAttribute(~0, Attributes::get(B));
3065   }
3066
3067   /// @brief Determine if the call does not access memory.
3068   bool doesNotAccessMemory() const {
3069     return hasFnAttr(Attributes::ReadNone);
3070   }
3071   void setDoesNotAccessMemory() {
3072     Attributes::Builder B;
3073     B.addAttribute(Attributes::ReadNone);
3074     addAttribute(~0, Attributes::get(B));
3075   }
3076
3077   /// @brief Determine if the call does not access or only reads memory.
3078   bool onlyReadsMemory() const {
3079     return doesNotAccessMemory() || hasFnAttr(Attributes::ReadOnly);
3080   }
3081   void setOnlyReadsMemory() {
3082     Attributes::Builder B;
3083     B.addAttribute(Attributes::ReadOnly);
3084     addAttribute(~0, Attributes::get(B));
3085   }
3086
3087   /// @brief Determine if the call cannot return.
3088   bool doesNotReturn() const { return hasFnAttr(Attributes::NoReturn); }
3089   void setDoesNotReturn() {
3090     Attributes::Builder B;
3091     B.addAttribute(Attributes::NoReturn);
3092     addAttribute(~0, Attributes::get(B));
3093   }
3094
3095   /// @brief Determine if the call cannot unwind.
3096   bool doesNotThrow() const { return hasFnAttr(Attributes::NoUnwind); }
3097   void setDoesNotThrow() {
3098     Attributes::Builder B;
3099     B.addAttribute(Attributes::NoUnwind);
3100     addAttribute(~0, Attributes::get(B));
3101   }
3102
3103   /// @brief Determine if the call returns a structure through first
3104   /// pointer argument.
3105   bool hasStructRetAttr() const {
3106     // Be friendly and also check the callee.
3107     return paramHasAttr(1, Attributes::StructRet);
3108   }
3109
3110   /// @brief Determine if any call argument is an aggregate passed by value.
3111   bool hasByValArgument() const {
3112     for (unsigned I = 0, E = AttributeList.getNumAttrs(); I != E; ++I)
3113       if (AttributeList.getAttributesAtIndex(I).hasAttribute(Attributes::ByVal))
3114         return true;
3115     return false;
3116   }
3117
3118   /// getCalledFunction - Return the function called, or null if this is an
3119   /// indirect function invocation.
3120   ///
3121   Function *getCalledFunction() const {
3122     return dyn_cast<Function>(Op<-3>());
3123   }
3124
3125   /// getCalledValue - Get a pointer to the function that is invoked by this
3126   /// instruction
3127   const Value *getCalledValue() const { return Op<-3>(); }
3128         Value *getCalledValue()       { return Op<-3>(); }
3129
3130   /// setCalledFunction - Set the function called.
3131   void setCalledFunction(Value* Fn) {
3132     Op<-3>() = Fn;
3133   }
3134
3135   // get*Dest - Return the destination basic blocks...
3136   BasicBlock *getNormalDest() const {
3137     return cast<BasicBlock>(Op<-2>());
3138   }
3139   BasicBlock *getUnwindDest() const {
3140     return cast<BasicBlock>(Op<-1>());
3141   }
3142   void setNormalDest(BasicBlock *B) {
3143     Op<-2>() = reinterpret_cast<Value*>(B);
3144   }
3145   void setUnwindDest(BasicBlock *B) {
3146     Op<-1>() = reinterpret_cast<Value*>(B);
3147   }
3148
3149   /// getLandingPadInst - Get the landingpad instruction from the landing pad
3150   /// block (the unwind destination).
3151   LandingPadInst *getLandingPadInst() const;
3152
3153   BasicBlock *getSuccessor(unsigned i) const {
3154     assert(i < 2 && "Successor # out of range for invoke!");
3155     return i == 0 ? getNormalDest() : getUnwindDest();
3156   }
3157
3158   void setSuccessor(unsigned idx, BasicBlock *NewSucc) {
3159     assert(idx < 2 && "Successor # out of range for invoke!");
3160     *(&Op<-2>() + idx) = reinterpret_cast<Value*>(NewSucc);
3161   }
3162
3163   unsigned getNumSuccessors() const { return 2; }
3164
3165   // Methods for support type inquiry through isa, cast, and dyn_cast:
3166   static inline bool classof(const InvokeInst *) { return true; }
3167   static inline bool classof(const Instruction *I) {
3168     return (I->getOpcode() == Instruction::Invoke);
3169   }
3170   static inline bool classof(const Value *V) {
3171     return isa<Instruction>(V) && classof(cast<Instruction>(V));
3172   }
3173
3174 private:
3175   virtual BasicBlock *getSuccessorV(unsigned idx) const;
3176   virtual unsigned getNumSuccessorsV() const;
3177   virtual void setSuccessorV(unsigned idx, BasicBlock *B);
3178
3179   // Shadow Instruction::setInstructionSubclassData with a private forwarding
3180   // method so that subclasses cannot accidentally use it.
3181   void setInstructionSubclassData(unsigned short D) {
3182     Instruction::setInstructionSubclassData(D);
3183   }
3184 };
3185
3186 template <>
3187 struct OperandTraits<InvokeInst> : public VariadicOperandTraits<InvokeInst, 3> {
3188 };
3189
3190 InvokeInst::InvokeInst(Value *Func,
3191                        BasicBlock *IfNormal, BasicBlock *IfException,
3192                        ArrayRef<Value *> Args, unsigned Values,
3193                        const Twine &NameStr, Instruction *InsertBefore)
3194   : TerminatorInst(cast<FunctionType>(cast<PointerType>(Func->getType())
3195                                       ->getElementType())->getReturnType(),
3196                    Instruction::Invoke,
3197                    OperandTraits<InvokeInst>::op_end(this) - Values,
3198                    Values, InsertBefore) {
3199   init(Func, IfNormal, IfException, Args, NameStr);
3200 }
3201 InvokeInst::InvokeInst(Value *Func,
3202                        BasicBlock *IfNormal, BasicBlock *IfException,
3203                        ArrayRef<Value *> Args, unsigned Values,
3204                        const Twine &NameStr, BasicBlock *InsertAtEnd)
3205   : TerminatorInst(cast<FunctionType>(cast<PointerType>(Func->getType())
3206                                       ->getElementType())->getReturnType(),
3207                    Instruction::Invoke,
3208                    OperandTraits<InvokeInst>::op_end(this) - Values,
3209                    Values, InsertAtEnd) {
3210   init(Func, IfNormal, IfException, Args, NameStr);
3211 }
3212
3213 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InvokeInst, Value)
3214
3215 //===----------------------------------------------------------------------===//
3216 //                              ResumeInst Class
3217 //===----------------------------------------------------------------------===//
3218
3219 //===---------------------------------------------------------------------------
3220 /// ResumeInst - Resume the propagation of an exception.
3221 ///
3222 class ResumeInst : public TerminatorInst {
3223   ResumeInst(const ResumeInst &RI);
3224
3225   explicit ResumeInst(Value *Exn, Instruction *InsertBefore=0);
3226   ResumeInst(Value *Exn, BasicBlock *InsertAtEnd);
3227 protected:
3228   virtual ResumeInst *clone_impl() const;
3229 public:
3230   static ResumeInst *Create(Value *Exn, Instruction *InsertBefore = 0) {
3231     return new(1) ResumeInst(Exn, InsertBefore);
3232   }
3233   static ResumeInst *Create(Value *Exn, BasicBlock *InsertAtEnd) {
3234     return new(1) ResumeInst(Exn, InsertAtEnd);
3235   }
3236
3237   /// Provide fast operand accessors
3238   DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
3239
3240   /// Convenience accessor.
3241   Value *getValue() const { return Op<0>(); }
3242
3243   unsigned getNumSuccessors() const { return 0; }
3244
3245   // Methods for support type inquiry through isa, cast, and dyn_cast:
3246   static inline bool classof(const ResumeInst *) { return true; }
3247   static inline bool classof(const Instruction *I) {
3248     return I->getOpcode() == Instruction::Resume;
3249   }
3250   static inline bool classof(const Value *V) {
3251     return isa<Instruction>(V) && classof(cast<Instruction>(V));
3252   }
3253 private:
3254   virtual BasicBlock *getSuccessorV(unsigned idx) const;
3255   virtual unsigned getNumSuccessorsV() const;
3256   virtual void setSuccessorV(unsigned idx, BasicBlock *B);
3257 };
3258
3259 template <>
3260 struct OperandTraits<ResumeInst> :
3261     public FixedNumOperandTraits<ResumeInst, 1> {
3262 };
3263
3264 DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ResumeInst, Value)
3265
3266 //===----------------------------------------------------------------------===//
3267 //                           UnreachableInst Class
3268 //===----------------------------------------------------------------------===//
3269
3270 //===---------------------------------------------------------------------------
3271 /// UnreachableInst - This function has undefined behavior.  In particular, the
3272 /// presence of this instruction indicates some higher level knowledge that the
3273 /// end of the block cannot be reached.
3274 ///
3275 class UnreachableInst : public TerminatorInst {
3276   void *operator new(size_t, unsigned) LLVM_DELETED_FUNCTION;
3277 protected:
3278   virtual UnreachableInst *clone_impl() const;
3279
3280 public:
3281   // allocate space for exactly zero operands
3282   void *operator new(size_t s) {
3283     return User::operator new(s, 0);
3284   }
3285   explicit UnreachableInst(LLVMContext &C, Instruction *InsertBefore = 0);
3286   explicit UnreachableInst(LLVMContext &C, BasicBlock *InsertAtEnd);
3287
3288   unsigned getNumSuccessors() const { return 0; }
3289
3290   // Methods for support type inquiry through isa, cast, and dyn_cast:
3291   static inline bool classof(const UnreachableInst *) { return true; }
3292   static inline bool classof(const Instruction *I) {
3293     return I->getOpcode() == Instruction::Unreachable;
3294   }
3295   static inline bool classof(const Value *V) {
3296     return isa<Instruction>(V) && classof(cast<Instruction>(V));
3297   }
3298 private:
3299   virtual BasicBlock *getSuccessorV(unsigned idx) const;
3300   virtual unsigned getNumSuccessorsV() const;
3301   virtual void setSuccessorV(unsigned idx, BasicBlock *B);
3302 };
3303
3304 //===----------------------------------------------------------------------===//
3305 //                                 TruncInst Class
3306 //===----------------------------------------------------------------------===//
3307
3308 /// @brief This class represents a truncation of integer types.
3309 class TruncInst : public CastInst {
3310 protected:
3311   /// @brief Clone an identical TruncInst
3312   virtual TruncInst *clone_impl() const;
3313
3314 public:
3315   /// @brief Constructor with insert-before-instruction semantics
3316   TruncInst(
3317     Value *S,                     ///< The value to be truncated
3318     Type *Ty,               ///< The (smaller) type to truncate to
3319     const Twine &NameStr = "",    ///< A name for the new instruction
3320     Instruction *InsertBefore = 0 ///< Where to insert the new instruction
3321   );
3322
3323   /// @brief Constructor with insert-at-end-of-block semantics
3324   TruncInst(
3325     Value *S,                     ///< The value to be truncated
3326     Type *Ty,               ///< The (smaller) type to truncate to
3327     const Twine &NameStr,         ///< A name for the new instruction
3328     BasicBlock *InsertAtEnd       ///< The block to insert the instruction into
3329   );
3330
3331   /// @brief Methods for support type inquiry through isa, cast, and dyn_cast:
3332   static inline bool classof(const TruncInst *) { return true; }
3333   static inline bool classof(const Instruction *I) {
3334     return I->getOpcode() == Trunc;
3335   }
3336   static inline bool classof(const Value *V) {
3337     return isa<Instruction>(V) && classof(cast<Instruction>(V));
3338   }
3339 };
3340
3341 //===----------------------------------------------------------------------===//
3342 //                                 ZExtInst Class
3343 //===----------------------------------------------------------------------===//
3344
3345 /// @brief This class represents zero extension of integer types.
3346 class ZExtInst : public CastInst {
3347 protected:
3348   /// @brief Clone an identical ZExtInst
3349   virtual ZExtInst *clone_impl() const;
3350
3351 public:
3352   /// @brief Constructor with insert-before-instruction semantics
3353   ZExtInst(
3354     Value *S,                     ///< The value to be zero extended
3355     Type *Ty,               ///< The type to zero extend to
3356     const Twine &NameStr = "",    ///< A name for the new instruction
3357     Instruction *InsertBefore = 0 ///< Where to insert the new instruction
3358   );
3359
3360   /// @brief Constructor with insert-at-end semantics.
3361   ZExtInst(
3362     Value *S,                     ///< The value to be zero extended
3363     Type *Ty,               ///< The type to zero extend to
3364     const Twine &NameStr,         ///< A name for the new instruction
3365     BasicBlock *InsertAtEnd       ///< The block to insert the instruction into
3366   );
3367
3368   /// @brief Methods for support type inquiry through isa, cast, and dyn_cast:
3369   static inline bool classof(const ZExtInst *) { return true; }
3370   static inline bool classof(const Instruction *I) {
3371     return I->getOpcode() == ZExt;
3372   }
3373   static inline bool classof(const Value *V) {
3374     return isa<Instruction>(V) && classof(cast<Instruction>(V));
3375   }
3376 };
3377
3378 //===----------------------------------------------------------------------===//
3379 //                                 SExtInst Class
3380 //===----------------------------------------------------------------------===//
3381
3382 /// @brief This class represents a sign extension of integer types.
3383 class SExtInst : public CastInst {
3384 protected:
3385   /// @brief Clone an identical SExtInst
3386   virtual SExtInst *clone_impl() const;
3387
3388 public:
3389   /// @brief Constructor with insert-before-instruction semantics
3390   SExtInst(
3391     Value *S,                     ///< The value to be sign extended
3392     Type *Ty,               ///< The type to sign extend to
3393     const Twine &NameStr = "",    ///< A name for the new instruction
3394     Instruction *InsertBefore = 0 ///< Where to insert the new instruction
3395   );
3396
3397   /// @brief Constructor with insert-at-end-of-block semantics
3398   SExtInst(
3399     Value *S,                     ///< The value to be sign extended
3400     Type *Ty,               ///< The type to sign extend to
3401     const Twine &NameStr,         ///< A name for the new instruction
3402     BasicBlock *InsertAtEnd       ///< The block to insert the instruction into
3403   );
3404
3405   /// @brief Methods for support type inquiry through isa, cast, and dyn_cast:
3406   static inline bool classof(const SExtInst *) { return true; }
3407   static inline bool classof(const Instruction *I) {
3408     return I->getOpcode() == SExt;
3409   }
3410   static inline bool classof(const Value *V) {
3411     return isa<Instruction>(V) && classof(cast<Instruction>(V));
3412   }
3413 };
3414
3415 //===----------------------------------------------------------------------===//
3416 //                                 FPTruncInst Class
3417 //===----------------------------------------------------------------------===//
3418
3419 /// @brief This class represents a truncation of floating point types.
3420 class FPTruncInst : public CastInst {
3421 protected:
3422   /// @brief Clone an identical FPTruncInst
3423   virtual FPTruncInst *clone_impl() const;
3424
3425 public:
3426   /// @brief Constructor with insert-before-instruction semantics
3427   FPTruncInst(
3428     Value *S,                     ///< The value to be truncated
3429     Type *Ty,               ///< The type to truncate to
3430     const Twine &NameStr = "",    ///< A name for the new instruction
3431     Instruction *InsertBefore = 0 ///< Where to insert the new instruction
3432   );
3433
3434   /// @brief Constructor with insert-before-instruction semantics
3435   FPTruncInst(
3436     Value *S,                     ///< The value to be truncated
3437     Type *Ty,               ///< The type to truncate to
3438     const Twine &NameStr,         ///< A name for the new instruction
3439     BasicBlock *InsertAtEnd       ///< The block to insert the instruction into
3440   );
3441
3442   /// @brief Methods for support type inquiry through isa, cast, and dyn_cast:
3443   static inline bool classof(const FPTruncInst *) { return true; }
3444   static inline bool classof(const Instruction *I) {
3445     return I->getOpcode() == FPTrunc;
3446   }
3447   static inline bool classof(const Value *V) {
3448     return isa<Instruction>(V) && classof(cast<Instruction>(V));
3449   }
3450 };
3451
3452 //===----------------------------------------------------------------------===//
3453 //                                 FPExtInst Class
3454 //===----------------------------------------------------------------------===//
3455
3456 /// @brief This class represents an extension of floating point types.
3457 class FPExtInst : public CastInst {
3458 protected:
3459   /// @brief Clone an identical FPExtInst
3460   virtual FPExtInst *clone_impl() const;
3461
3462 public:
3463   /// @brief Constructor with insert-before-instruction semantics
3464   FPExtInst(
3465     Value *S,                     ///< The value to be extended
3466     Type *Ty,               ///< The type to extend to
3467     const Twine &NameStr = "",    ///< A name for the new instruction
3468     Instruction *InsertBefore = 0 ///< Where to insert the new instruction
3469   );
3470
3471   /// @brief Constructor with insert-at-end-of-block semantics
3472   FPExtInst(
3473     Value *S,                     ///< The value to be extended
3474     Type *Ty,               ///< The type to extend to
3475     const Twine &NameStr,         ///< A name for the new instruction
3476     BasicBlock *InsertAtEnd       ///< The block to insert the instruction into
3477   );
3478
3479   /// @brief Methods for support type inquiry through isa, cast, and dyn_cast:
3480   static inline bool classof(const FPExtInst *) { return true; }
3481   static inline bool classof(const Instruction *I) {
3482     return I->getOpcode() == FPExt;
3483   }
3484   static inline bool classof(const Value *V) {
3485     return isa<Instruction>(V) && classof(cast<Instruction>(V));
3486   }
3487 };
3488
3489 //===----------------------------------------------------------------------===//
3490 //                                 UIToFPInst Class
3491 //===----------------------------------------------------------------------===//
3492
3493 /// @brief This class represents a cast unsigned integer to floating point.
3494 class UIToFPInst : public CastInst {
3495 protected:
3496   /// @brief Clone an identical UIToFPInst
3497   virtual UIToFPInst *clone_impl() const;
3498
3499 public:
3500   /// @brief Constructor with insert-before-instruction semantics
3501   UIToFPInst(
3502     Value *S,                     ///< The value to be converted
3503     Type *Ty,               ///< The type to convert to
3504     const Twine &NameStr = "",    ///< A name for the new instruction
3505     Instruction *InsertBefore = 0 ///< Where to insert the new instruction
3506   );
3507
3508   /// @brief Constructor with insert-at-end-of-block semantics
3509   UIToFPInst(
3510     Value *S,                     ///< The value to be converted
3511     Type *Ty,               ///< The type to convert to
3512     const Twine &NameStr,         ///< A name for the new instruction
3513     BasicBlock *InsertAtEnd       ///< The block to insert the instruction into
3514   );
3515
3516   /// @brief Methods for support type inquiry through isa, cast, and dyn_cast:
3517   static inline bool classof(const UIToFPInst *) { return true; }
3518   static inline bool classof(const Instruction *I) {
3519     return I->getOpcode() == UIToFP;
3520   }
3521   static inline bool classof(const Value *V) {
3522     return isa<Instruction>(V) && classof(cast<Instruction>(V));
3523   }
3524 };
3525
3526 //===----------------------------------------------------------------------===//
3527 //                                 SIToFPInst Class
3528 //===----------------------------------------------------------------------===//
3529
3530 /// @brief This class represents a cast from signed integer to floating point.
3531 class SIToFPInst : public CastInst {
3532 protected:
3533   /// @brief Clone an identical SIToFPInst
3534   virtual SIToFPInst *clone_impl() const;
3535
3536 public:
3537   /// @brief Constructor with insert-before-instruction semantics
3538   SIToFPInst(
3539     Value *S,                     ///< The value to be converted
3540     Type *Ty,               ///< The type to convert to
3541     const Twine &NameStr = "",    ///< A name for the new instruction
3542     Instruction *InsertBefore = 0 ///< Where to insert the new instruction
3543   );
3544
3545   /// @brief Constructor with insert-at-end-of-block semantics
3546   SIToFPInst(
3547     Value *S,                     ///< The value to be converted
3548     Type *Ty,               ///< The type to convert to
3549     const Twine &NameStr,         ///< A name for the new instruction
3550     BasicBlock *InsertAtEnd       ///< The block to insert the instruction into
3551   );
3552
3553   /// @brief Methods for support type inquiry through isa, cast, and dyn_cast:
3554   static inline bool classof(const SIToFPInst *) { return true; }
3555   static inline bool classof(const Instruction *I) {
3556     return I->getOpcode() == SIToFP;
3557   }
3558   static inline bool classof(const Value *V) {
3559     return isa<Instruction>(V) && classof(cast<Instruction>(V));
3560   }
3561 };
3562
3563 //===----------------------------------------------------------------------===//
3564 //                                 FPToUIInst Class
3565 //===----------------------------------------------------------------------===//
3566
3567 /// @brief This class represents a cast from floating point to unsigned integer
3568 class FPToUIInst  : public CastInst {
3569 protected:
3570   /// @brief Clone an identical FPToUIInst
3571   virtual FPToUIInst *clone_impl() const;
3572
3573 public:
3574   /// @brief Constructor with insert-before-instruction semantics
3575   FPToUIInst(
3576     Value *S,                     ///< The value to be converted
3577     Type *Ty,               ///< The type to convert to
3578     const Twine &NameStr = "",    ///< A name for the new instruction
3579     Instruction *InsertBefore = 0 ///< Where to insert the new instruction
3580   );
3581
3582   /// @brief Constructor with insert-at-end-of-block semantics
3583   FPToUIInst(
3584     Value *S,                     ///< The value to be converted
3585     Type *Ty,               ///< The type to convert to
3586     const Twine &NameStr,         ///< A name for the new instruction
3587     BasicBlock *InsertAtEnd       ///< Where to insert the new instruction
3588   );
3589
3590   /// @brief Methods for support type inquiry through isa, cast, and dyn_cast:
3591   static inline bool classof(const FPToUIInst *) { return true; }
3592   static inline bool classof(const Instruction *I) {
3593     return I->getOpcode() == FPToUI;
3594   }
3595   static inline bool classof(const Value *V) {
3596     return isa<Instruction>(V) && classof(cast<Instruction>(V));
3597   }
3598 };
3599
3600 //===----------------------------------------------------------------------===//
3601 //                                 FPToSIInst Class
3602 //===----------------------------------------------------------------------===//
3603
3604 /// @brief This class represents a cast from floating point to signed integer.
3605 class FPToSIInst  : public CastInst {
3606 protected:
3607   /// @brief Clone an identical FPToSIInst
3608   virtual FPToSIInst *clone_impl() const;
3609
3610 public:
3611   /// @brief Constructor with insert-before-instruction semantics
3612   FPToSIInst(
3613     Value *S,                     ///< The value to be converted
3614     Type *Ty,               ///< The type to convert to
3615     const Twine &NameStr = "",    ///< A name for the new instruction
3616     Instruction *InsertBefore = 0 ///< Where to insert the new instruction
3617   );
3618
3619   /// @brief Constructor with insert-at-end-of-block semantics
3620   FPToSIInst(
3621     Value *S,                     ///< The value to be converted
3622     Type *Ty,               ///< The type to convert to
3623     const Twine &NameStr,         ///< A name for the new instruction
3624     BasicBlock *InsertAtEnd       ///< The block to insert the instruction into
3625   );
3626
3627   /// @brief Methods for support type inquiry through isa, cast, and dyn_cast:
3628   static inline bool classof(const FPToSIInst *) { return true; }
3629   static inline bool classof(const Instruction *I) {
3630     return I->getOpcode() == FPToSI;
3631   }
3632   static inline bool classof(const Value *V) {
3633     return isa<Instruction>(V) && classof(cast<Instruction>(V));
3634   }
3635 };
3636
3637 //===----------------------------------------------------------------------===//
3638 //                                 IntToPtrInst Class
3639 //===----------------------------------------------------------------------===//
3640
3641 /// @brief This class represents a cast from an integer to a pointer.
3642 class IntToPtrInst : public CastInst {
3643 public:
3644   /// @brief Constructor with insert-before-instruction semantics
3645   IntToPtrInst(
3646     Value *S,                     ///< The value to be converted
3647     Type *Ty,               ///< The type to convert to
3648     const Twine &NameStr = "",    ///< A name for the new instruction
3649     Instruction *InsertBefore = 0 ///< Where to insert the new instruction
3650   );
3651
3652   /// @brief Constructor with insert-at-end-of-block semantics
3653   IntToPtrInst(
3654     Value *S,                     ///< The value to be converted
3655     Type *Ty,               ///< The type to convert to
3656     const Twine &NameStr,         ///< A name for the new instruction
3657     BasicBlock *InsertAtEnd       ///< The block to insert the instruction into
3658   );
3659
3660   /// @brief Clone an identical IntToPtrInst
3661   virtual IntToPtrInst *clone_impl() const;
3662
3663   /// @brief return the address space of the pointer.
3664   unsigned getAddressSpace() const {
3665     if (getType()->isPointerTy()) 
3666       return cast<PointerType>(getType())->getAddressSpace();
3667     if (getType()->isVectorTy() &&
3668         cast<VectorType>(getType())->getElementType()->isPointerTy())
3669       return cast<PointerType>(
3670           cast<VectorType>(getType())->getElementType())
3671         ->getAddressSpace();
3672     llvm_unreachable("Must be a pointer or a vector of pointers.");
3673     return 0;
3674   }
3675
3676   // Methods for support type inquiry through isa, cast, and dyn_cast:
3677   static inline bool classof(const IntToPtrInst *) { return true; }
3678   static inline bool classof(const Instruction *I) {
3679     return I->getOpcode() == IntToPtr;
3680   }
3681   static inline bool classof(const Value *V) {
3682     return isa<Instruction>(V) && classof(cast<Instruction>(V));
3683   }
3684 };
3685
3686 //===----------------------------------------------------------------------===//
3687 //                                 PtrToIntInst Class
3688 //===----------------------------------------------------------------------===//
3689
3690 /// @brief This class represents a cast from a pointer to an integer
3691 class PtrToIntInst : public CastInst {
3692 protected:
3693   /// @brief Clone an identical PtrToIntInst
3694   virtual PtrToIntInst *clone_impl() const;
3695
3696 public:
3697   /// @brief Constructor with insert-before-instruction semantics
3698   PtrToIntInst(
3699     Value *S,                     ///< The value to be converted
3700     Type *Ty,               ///< The type to convert to
3701     const Twine &NameStr = "",    ///< A name for the new instruction
3702     Instruction *InsertBefore = 0 ///< Where to insert the new instruction
3703   );
3704
3705   /// @brief Constructor with insert-at-end-of-block semantics
3706   PtrToIntInst(
3707     Value *S,                     ///< The value to be converted
3708     Type *Ty,               ///< The type to convert to
3709     const Twine &NameStr,         ///< A name for the new instruction
3710     BasicBlock *InsertAtEnd       ///< The block to insert the instruction into
3711   );
3712
3713   /// @brief return the address space of the pointer.
3714   unsigned getPointerAddressSpace() const {
3715     Type *Ty = getOperand(0)->getType();
3716     if (Ty->isPointerTy())
3717       return cast<PointerType>(Ty)->getAddressSpace();
3718     if (Ty->isVectorTy()
3719         && cast<VectorType>(Ty)->getElementType()->isPointerTy())
3720       return cast<PointerType>(
3721           cast<VectorType>(Ty)->getElementType())
3722         ->getAddressSpace();
3723     llvm_unreachable("Must be a pointer or a vector of pointers.");
3724     return 0;
3725   }
3726
3727   // Methods for support type inquiry through isa, cast, and dyn_cast:
3728   static inline bool classof(const PtrToIntInst *) { return true; }
3729   static inline bool classof(const Instruction *I) {
3730     return I->getOpcode() == PtrToInt;
3731   }
3732   static inline bool classof(const Value *V) {
3733     return isa<Instruction>(V) && classof(cast<Instruction>(V));
3734   }
3735 };
3736
3737 //===----------------------------------------------------------------------===//
3738 //                             BitCastInst Class
3739 //===----------------------------------------------------------------------===//
3740
3741 /// @brief This class represents a no-op cast from one type to another.
3742 class BitCastInst : public CastInst {
3743 protected:
3744   /// @brief Clone an identical BitCastInst
3745   virtual BitCastInst *clone_impl() const;
3746
3747 public:
3748   /// @brief Constructor with insert-before-instruction semantics
3749   BitCastInst(
3750     Value *S,                     ///< The value to be casted
3751     Type *Ty,               ///< The type to casted to
3752     const Twine &NameStr = "",    ///< A name for the new instruction
3753     Instruction *InsertBefore = 0 ///< Where to insert the new instruction
3754   );
3755
3756   /// @brief Constructor with insert-at-end-of-block semantics
3757   BitCastInst(
3758     Value *S,                     ///< The value to be casted
3759     Type *Ty,               ///< The type to casted to
3760     const Twine &NameStr,         ///< A name for the new instruction
3761     BasicBlock *InsertAtEnd       ///< The block to insert the instruction into
3762   );
3763
3764   // Methods for support type inquiry through isa, cast, and dyn_cast:
3765   static inline bool classof(const BitCastInst *) { return true; }
3766   static inline bool classof(const Instruction *I) {
3767     return I->getOpcode() == BitCast;
3768   }
3769   static inline bool classof(const Value *V) {
3770     return isa<Instruction>(V) && classof(cast<Instruction>(V));
3771   }
3772 };
3773
3774 } // End llvm namespace
3775
3776 #endif