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