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