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