Change:
[oota-llvm.git] / lib / VMCore / Instructions.cpp
1 //===-- Instructions.cpp - Implement the LLVM instructions ----------------===//
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 implements all of the non-inline methods for the LLVM instruction
11 // classes.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "LLVMContextImpl.h"
16 #include "llvm/Constants.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/Function.h"
19 #include "llvm/Instructions.h"
20 #include "llvm/Module.h"
21 #include "llvm/Operator.h"
22 #include "llvm/Support/ErrorHandling.h"
23 #include "llvm/Support/CallSite.h"
24 #include "llvm/Support/ConstantRange.h"
25 #include "llvm/Support/MathExtras.h"
26 using namespace llvm;
27
28 //===----------------------------------------------------------------------===//
29 //                            CallSite Class
30 //===----------------------------------------------------------------------===//
31
32 User::op_iterator CallSite::getCallee() const {
33   Instruction *II(getInstruction());
34   return isCall()
35     ? cast<CallInst>(II)->op_end() - 1 // Skip Callee
36     : cast<InvokeInst>(II)->op_end() - 3; // Skip BB, BB, Callee
37 }
38
39 //===----------------------------------------------------------------------===//
40 //                            TerminatorInst Class
41 //===----------------------------------------------------------------------===//
42
43 // Out of line virtual method, so the vtable, etc has a home.
44 TerminatorInst::~TerminatorInst() {
45 }
46
47 //===----------------------------------------------------------------------===//
48 //                           UnaryInstruction Class
49 //===----------------------------------------------------------------------===//
50
51 // Out of line virtual method, so the vtable, etc has a home.
52 UnaryInstruction::~UnaryInstruction() {
53 }
54
55 //===----------------------------------------------------------------------===//
56 //                              SelectInst Class
57 //===----------------------------------------------------------------------===//
58
59 /// areInvalidOperands - Return a string if the specified operands are invalid
60 /// for a select operation, otherwise return null.
61 const char *SelectInst::areInvalidOperands(Value *Op0, Value *Op1, Value *Op2) {
62   if (Op1->getType() != Op2->getType())
63     return "both values to select must have same type";
64   
65   if (VectorType *VT = dyn_cast<VectorType>(Op0->getType())) {
66     // Vector select.
67     if (VT->getElementType() != Type::getInt1Ty(Op0->getContext()))
68       return "vector select condition element type must be i1";
69     VectorType *ET = dyn_cast<VectorType>(Op1->getType());
70     if (ET == 0)
71       return "selected values for vector select must be vectors";
72     if (ET->getNumElements() != VT->getNumElements())
73       return "vector select requires selected vectors to have "
74                    "the same vector length as select condition";
75   } else if (Op0->getType() != Type::getInt1Ty(Op0->getContext())) {
76     return "select condition must be i1 or <n x i1>";
77   }
78   return 0;
79 }
80
81
82 //===----------------------------------------------------------------------===//
83 //                               PHINode Class
84 //===----------------------------------------------------------------------===//
85
86 PHINode::PHINode(const PHINode &PN)
87   : Instruction(PN.getType(), Instruction::PHI,
88                 allocHungoffUses(PN.getNumOperands()), PN.getNumOperands()),
89     ReservedSpace(PN.getNumOperands()) {
90   std::copy(PN.op_begin(), PN.op_end(), op_begin());
91   std::copy(PN.block_begin(), PN.block_end(), block_begin());
92   SubclassOptionalData = PN.SubclassOptionalData;
93 }
94
95 PHINode::~PHINode() {
96   dropHungoffUses();
97 }
98
99 Use *PHINode::allocHungoffUses(unsigned N) const {
100   // Allocate the array of Uses of the incoming values, followed by a pointer
101   // (with bottom bit set) to the User, followed by the array of pointers to
102   // the incoming basic blocks.
103   size_t size = N * sizeof(Use) + sizeof(Use::UserRef)
104     + N * sizeof(BasicBlock*);
105   Use *Begin = static_cast<Use*>(::operator new(size));
106   Use *End = Begin + N;
107   (void) new(End) Use::UserRef(const_cast<PHINode*>(this), 1);
108   return Use::initTags(Begin, End);
109 }
110
111 // removeIncomingValue - Remove an incoming value.  This is useful if a
112 // predecessor basic block is deleted.
113 Value *PHINode::removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty) {
114   Value *Removed = getIncomingValue(Idx);
115
116   // Move everything after this operand down.
117   //
118   // FIXME: we could just swap with the end of the list, then erase.  However,
119   // clients might not expect this to happen.  The code as it is thrashes the
120   // use/def lists, which is kinda lame.
121   std::copy(op_begin() + Idx + 1, op_end(), op_begin() + Idx);
122   std::copy(block_begin() + Idx + 1, block_end(), block_begin() + Idx);
123
124   // Nuke the last value.
125   Op<-1>().set(0);
126   --NumOperands;
127
128   // If the PHI node is dead, because it has zero entries, nuke it now.
129   if (getNumOperands() == 0 && DeletePHIIfEmpty) {
130     // If anyone is using this PHI, make them use a dummy value instead...
131     replaceAllUsesWith(UndefValue::get(getType()));
132     eraseFromParent();
133   }
134   return Removed;
135 }
136
137 /// growOperands - grow operands - This grows the operand list in response
138 /// to a push_back style of operation.  This grows the number of ops by 1.5
139 /// times.
140 ///
141 void PHINode::growOperands() {
142   unsigned e = getNumOperands();
143   unsigned NumOps = e + e / 2;
144   if (NumOps < 2) NumOps = 2;      // 2 op PHI nodes are VERY common.
145
146   Use *OldOps = op_begin();
147   BasicBlock **OldBlocks = block_begin();
148
149   ReservedSpace = NumOps;
150   OperandList = allocHungoffUses(ReservedSpace);
151
152   std::copy(OldOps, OldOps + e, op_begin());
153   std::copy(OldBlocks, OldBlocks + e, block_begin());
154
155   Use::zap(OldOps, OldOps + e, true);
156 }
157
158 /// hasConstantValue - If the specified PHI node always merges together the same
159 /// value, return the value, otherwise return null.
160 Value *PHINode::hasConstantValue() const {
161   // Exploit the fact that phi nodes always have at least one entry.
162   Value *ConstantValue = getIncomingValue(0);
163   for (unsigned i = 1, e = getNumIncomingValues(); i != e; ++i)
164     if (getIncomingValue(i) != ConstantValue)
165       return 0; // Incoming values not all the same.
166   return ConstantValue;
167 }
168
169 //===----------------------------------------------------------------------===//
170 //                       LandingPadInst Implementation
171 //===----------------------------------------------------------------------===//
172
173 LandingPadInst::LandingPadInst(Type *RetTy, Value *PersonalityFn,
174                                unsigned NumReservedValues, const Twine &NameStr,
175                                Instruction *InsertBefore)
176   : Instruction(RetTy, Instruction::LandingPad, 0, 0, InsertBefore) {
177   init(PersonalityFn, 1 + NumReservedValues, NameStr);
178 }
179
180 LandingPadInst::LandingPadInst(Type *RetTy, Value *PersonalityFn,
181                                unsigned NumReservedValues, const Twine &NameStr,
182                                BasicBlock *InsertAtEnd)
183   : Instruction(RetTy, Instruction::LandingPad, 0, 0, InsertAtEnd) {
184   init(PersonalityFn, 1 + NumReservedValues, NameStr);
185 }
186
187 LandingPadInst::LandingPadInst(const LandingPadInst &LP)
188   : Instruction(LP.getType(), Instruction::LandingPad,
189                 allocHungoffUses(LP.getNumOperands()), LP.getNumOperands()),
190     ReservedSpace(LP.getNumOperands()) {
191   Use *OL = OperandList, *InOL = LP.OperandList;
192   for (unsigned I = 0, E = ReservedSpace; I != E; ++I)
193     OL[I] = InOL[I];
194
195   setCleanup(LP.isCleanup());
196 }
197
198 LandingPadInst::~LandingPadInst() {
199   dropHungoffUses();
200 }
201
202 LandingPadInst *LandingPadInst::Create(Type *RetTy, Value *PersonalityFn,
203                                        unsigned NumReservedClauses,
204                                        const Twine &NameStr,
205                                        Instruction *InsertBefore) {
206   return new LandingPadInst(RetTy, PersonalityFn, NumReservedClauses, NameStr,
207                             InsertBefore);
208 }
209
210 LandingPadInst *LandingPadInst::Create(Type *RetTy, Value *PersonalityFn,
211                                        unsigned NumReservedClauses,
212                                        const Twine &NameStr,
213                                        BasicBlock *InsertAtEnd) {
214   return new LandingPadInst(RetTy, PersonalityFn, NumReservedClauses, NameStr,
215                             InsertAtEnd);
216 }
217
218 void LandingPadInst::init(Value *PersFn, unsigned NumReservedValues,
219                           const Twine &NameStr) {
220   ReservedSpace = NumReservedValues;
221   NumOperands = 1;
222   OperandList = allocHungoffUses(ReservedSpace);
223   OperandList[0] = PersFn;
224   setName(NameStr);
225   setCleanup(false);
226 }
227
228 /// growOperands - grow operands - This grows the operand list in response to a
229 /// push_back style of operation. This grows the number of ops by 2 times.
230 void LandingPadInst::growOperands(unsigned Size) {
231   unsigned e = getNumOperands();
232   if (ReservedSpace >= e + Size) return;
233   ReservedSpace = (e + Size / 2) * 2;
234
235   Use *NewOps = allocHungoffUses(ReservedSpace);
236   Use *OldOps = OperandList;
237   for (unsigned i = 0; i != e; ++i)
238       NewOps[i] = OldOps[i];
239
240   OperandList = NewOps;
241   Use::zap(OldOps, OldOps + e, true);
242 }
243
244 void LandingPadInst::addClause(Value *Val) {
245   unsigned OpNo = getNumOperands();
246   growOperands(1);
247   assert(OpNo < ReservedSpace && "Growing didn't work!");
248   ++NumOperands;
249   OperandList[OpNo] = Val;
250 }
251
252 //===----------------------------------------------------------------------===//
253 //                        CallInst Implementation
254 //===----------------------------------------------------------------------===//
255
256 CallInst::~CallInst() {
257 }
258
259 void CallInst::init(Value *Func, ArrayRef<Value *> Args, const Twine &NameStr) {
260   assert(NumOperands == Args.size() + 1 && "NumOperands not set up?");
261   Op<-1>() = Func;
262
263 #ifndef NDEBUG
264   FunctionType *FTy =
265     cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
266
267   assert((Args.size() == FTy->getNumParams() ||
268           (FTy->isVarArg() && Args.size() > FTy->getNumParams())) &&
269          "Calling a function with bad signature!");
270
271   for (unsigned i = 0; i != Args.size(); ++i)
272     assert((i >= FTy->getNumParams() || 
273             FTy->getParamType(i) == Args[i]->getType()) &&
274            "Calling a function with a bad signature!");
275 #endif
276
277   std::copy(Args.begin(), Args.end(), op_begin());
278   setName(NameStr);
279 }
280
281 void CallInst::init(Value *Func, const Twine &NameStr) {
282   assert(NumOperands == 1 && "NumOperands not set up?");
283   Op<-1>() = Func;
284
285 #ifndef NDEBUG
286   FunctionType *FTy =
287     cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
288
289   assert(FTy->getNumParams() == 0 && "Calling a function with bad signature");
290 #endif
291
292   setName(NameStr);
293 }
294
295 CallInst::CallInst(Value *Func, const Twine &Name,
296                    Instruction *InsertBefore)
297   : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
298                                    ->getElementType())->getReturnType(),
299                 Instruction::Call,
300                 OperandTraits<CallInst>::op_end(this) - 1,
301                 1, InsertBefore) {
302   init(Func, Name);
303 }
304
305 CallInst::CallInst(Value *Func, const Twine &Name,
306                    BasicBlock *InsertAtEnd)
307   : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
308                                    ->getElementType())->getReturnType(),
309                 Instruction::Call,
310                 OperandTraits<CallInst>::op_end(this) - 1,
311                 1, InsertAtEnd) {
312   init(Func, Name);
313 }
314
315 CallInst::CallInst(const CallInst &CI)
316   : Instruction(CI.getType(), Instruction::Call,
317                 OperandTraits<CallInst>::op_end(this) - CI.getNumOperands(),
318                 CI.getNumOperands()) {
319   setAttributes(CI.getAttributes());
320   setTailCall(CI.isTailCall());
321   setCallingConv(CI.getCallingConv());
322     
323   std::copy(CI.op_begin(), CI.op_end(), op_begin());
324   SubclassOptionalData = CI.SubclassOptionalData;
325 }
326
327 void CallInst::addAttribute(unsigned i, Attributes attr) {
328   AttrListPtr PAL = getAttributes();
329   PAL = PAL.addAttr(i, attr);
330   setAttributes(PAL);
331 }
332
333 void CallInst::removeAttribute(unsigned i, Attributes attr) {
334   AttrListPtr PAL = getAttributes();
335   PAL = PAL.removeAttr(i, attr);
336   setAttributes(PAL);
337 }
338
339 bool CallInst::paramHasAttr(unsigned i, Attributes attr) const {
340   if (AttributeList.paramHasAttr(i, attr))
341     return true;
342   if (const Function *F = getCalledFunction())
343     return F->paramHasAttr(i, attr);
344   return false;
345 }
346
347 /// IsConstantOne - Return true only if val is constant int 1
348 static bool IsConstantOne(Value *val) {
349   assert(val && "IsConstantOne does not work with NULL val");
350   return isa<ConstantInt>(val) && cast<ConstantInt>(val)->isOne();
351 }
352
353 static Instruction *createMalloc(Instruction *InsertBefore,
354                                  BasicBlock *InsertAtEnd, Type *IntPtrTy,
355                                  Type *AllocTy, Value *AllocSize, 
356                                  Value *ArraySize, Function *MallocF,
357                                  const Twine &Name) {
358   assert(((!InsertBefore && InsertAtEnd) || (InsertBefore && !InsertAtEnd)) &&
359          "createMalloc needs either InsertBefore or InsertAtEnd");
360
361   // malloc(type) becomes: 
362   //       bitcast (i8* malloc(typeSize)) to type*
363   // malloc(type, arraySize) becomes:
364   //       bitcast (i8 *malloc(typeSize*arraySize)) to type*
365   if (!ArraySize)
366     ArraySize = ConstantInt::get(IntPtrTy, 1);
367   else if (ArraySize->getType() != IntPtrTy) {
368     if (InsertBefore)
369       ArraySize = CastInst::CreateIntegerCast(ArraySize, IntPtrTy, false,
370                                               "", InsertBefore);
371     else
372       ArraySize = CastInst::CreateIntegerCast(ArraySize, IntPtrTy, false,
373                                               "", InsertAtEnd);
374   }
375
376   if (!IsConstantOne(ArraySize)) {
377     if (IsConstantOne(AllocSize)) {
378       AllocSize = ArraySize;         // Operand * 1 = Operand
379     } else if (Constant *CO = dyn_cast<Constant>(ArraySize)) {
380       Constant *Scale = ConstantExpr::getIntegerCast(CO, IntPtrTy,
381                                                      false /*ZExt*/);
382       // Malloc arg is constant product of type size and array size
383       AllocSize = ConstantExpr::getMul(Scale, cast<Constant>(AllocSize));
384     } else {
385       // Multiply type size by the array size...
386       if (InsertBefore)
387         AllocSize = BinaryOperator::CreateMul(ArraySize, AllocSize,
388                                               "mallocsize", InsertBefore);
389       else
390         AllocSize = BinaryOperator::CreateMul(ArraySize, AllocSize,
391                                               "mallocsize", InsertAtEnd);
392     }
393   }
394
395   assert(AllocSize->getType() == IntPtrTy && "malloc arg is wrong size");
396   // Create the call to Malloc.
397   BasicBlock* BB = InsertBefore ? InsertBefore->getParent() : InsertAtEnd;
398   Module* M = BB->getParent()->getParent();
399   Type *BPTy = Type::getInt8PtrTy(BB->getContext());
400   Value *MallocFunc = MallocF;
401   if (!MallocFunc)
402     // prototype malloc as "void *malloc(size_t)"
403     MallocFunc = M->getOrInsertFunction("malloc", BPTy, IntPtrTy, NULL);
404   PointerType *AllocPtrType = PointerType::getUnqual(AllocTy);
405   CallInst *MCall = NULL;
406   Instruction *Result = NULL;
407   if (InsertBefore) {
408     MCall = CallInst::Create(MallocFunc, AllocSize, "malloccall", InsertBefore);
409     Result = MCall;
410     if (Result->getType() != AllocPtrType)
411       // Create a cast instruction to convert to the right type...
412       Result = new BitCastInst(MCall, AllocPtrType, Name, InsertBefore);
413   } else {
414     MCall = CallInst::Create(MallocFunc, AllocSize, "malloccall");
415     Result = MCall;
416     if (Result->getType() != AllocPtrType) {
417       InsertAtEnd->getInstList().push_back(MCall);
418       // Create a cast instruction to convert to the right type...
419       Result = new BitCastInst(MCall, AllocPtrType, Name);
420     }
421   }
422   MCall->setTailCall();
423   if (Function *F = dyn_cast<Function>(MallocFunc)) {
424     MCall->setCallingConv(F->getCallingConv());
425     if (!F->doesNotAlias(0)) F->setDoesNotAlias(0);
426   }
427   assert(!MCall->getType()->isVoidTy() && "Malloc has void return type");
428
429   return Result;
430 }
431
432 /// CreateMalloc - Generate the IR for a call to malloc:
433 /// 1. Compute the malloc call's argument as the specified type's size,
434 ///    possibly multiplied by the array size if the array size is not
435 ///    constant 1.
436 /// 2. Call malloc with that argument.
437 /// 3. Bitcast the result of the malloc call to the specified type.
438 Instruction *CallInst::CreateMalloc(Instruction *InsertBefore,
439                                     Type *IntPtrTy, Type *AllocTy,
440                                     Value *AllocSize, Value *ArraySize,
441                                     Function * MallocF,
442                                     const Twine &Name) {
443   return createMalloc(InsertBefore, NULL, IntPtrTy, AllocTy, AllocSize,
444                       ArraySize, MallocF, Name);
445 }
446
447 /// CreateMalloc - Generate the IR for a call to malloc:
448 /// 1. Compute the malloc call's argument as the specified type's size,
449 ///    possibly multiplied by the array size if the array size is not
450 ///    constant 1.
451 /// 2. Call malloc with that argument.
452 /// 3. Bitcast the result of the malloc call to the specified type.
453 /// Note: This function does not add the bitcast to the basic block, that is the
454 /// responsibility of the caller.
455 Instruction *CallInst::CreateMalloc(BasicBlock *InsertAtEnd,
456                                     Type *IntPtrTy, Type *AllocTy,
457                                     Value *AllocSize, Value *ArraySize, 
458                                     Function *MallocF, const Twine &Name) {
459   return createMalloc(NULL, InsertAtEnd, IntPtrTy, AllocTy, AllocSize,
460                       ArraySize, MallocF, Name);
461 }
462
463 static Instruction* createFree(Value* Source, Instruction *InsertBefore,
464                                BasicBlock *InsertAtEnd) {
465   assert(((!InsertBefore && InsertAtEnd) || (InsertBefore && !InsertAtEnd)) &&
466          "createFree needs either InsertBefore or InsertAtEnd");
467   assert(Source->getType()->isPointerTy() &&
468          "Can not free something of nonpointer type!");
469
470   BasicBlock* BB = InsertBefore ? InsertBefore->getParent() : InsertAtEnd;
471   Module* M = BB->getParent()->getParent();
472
473   Type *VoidTy = Type::getVoidTy(M->getContext());
474   Type *IntPtrTy = Type::getInt8PtrTy(M->getContext());
475   // prototype free as "void free(void*)"
476   Value *FreeFunc = M->getOrInsertFunction("free", VoidTy, IntPtrTy, NULL);
477   CallInst* Result = NULL;
478   Value *PtrCast = Source;
479   if (InsertBefore) {
480     if (Source->getType() != IntPtrTy)
481       PtrCast = new BitCastInst(Source, IntPtrTy, "", InsertBefore);
482     Result = CallInst::Create(FreeFunc, PtrCast, "", InsertBefore);
483   } else {
484     if (Source->getType() != IntPtrTy)
485       PtrCast = new BitCastInst(Source, IntPtrTy, "", InsertAtEnd);
486     Result = CallInst::Create(FreeFunc, PtrCast, "");
487   }
488   Result->setTailCall();
489   if (Function *F = dyn_cast<Function>(FreeFunc))
490     Result->setCallingConv(F->getCallingConv());
491
492   return Result;
493 }
494
495 /// CreateFree - Generate the IR for a call to the builtin free function.
496 Instruction * CallInst::CreateFree(Value* Source, Instruction *InsertBefore) {
497   return createFree(Source, InsertBefore, NULL);
498 }
499
500 /// CreateFree - Generate the IR for a call to the builtin free function.
501 /// Note: This function does not add the call to the basic block, that is the
502 /// responsibility of the caller.
503 Instruction* CallInst::CreateFree(Value* Source, BasicBlock *InsertAtEnd) {
504   Instruction* FreeCall = createFree(Source, NULL, InsertAtEnd);
505   assert(FreeCall && "CreateFree did not create a CallInst");
506   return FreeCall;
507 }
508
509 //===----------------------------------------------------------------------===//
510 //                        InvokeInst Implementation
511 //===----------------------------------------------------------------------===//
512
513 void InvokeInst::init(Value *Fn, BasicBlock *IfNormal, BasicBlock *IfException,
514                       ArrayRef<Value *> Args, const Twine &NameStr) {
515   assert(NumOperands == 3 + Args.size() && "NumOperands not set up?");
516   Op<-3>() = Fn;
517   Op<-2>() = IfNormal;
518   Op<-1>() = IfException;
519
520 #ifndef NDEBUG
521   FunctionType *FTy =
522     cast<FunctionType>(cast<PointerType>(Fn->getType())->getElementType());
523
524   assert(((Args.size() == FTy->getNumParams()) ||
525           (FTy->isVarArg() && Args.size() > FTy->getNumParams())) &&
526          "Invoking a function with bad signature");
527
528   for (unsigned i = 0, e = Args.size(); i != e; i++)
529     assert((i >= FTy->getNumParams() || 
530             FTy->getParamType(i) == Args[i]->getType()) &&
531            "Invoking a function with a bad signature!");
532 #endif
533
534   std::copy(Args.begin(), Args.end(), op_begin());
535   setName(NameStr);
536 }
537
538 InvokeInst::InvokeInst(const InvokeInst &II)
539   : TerminatorInst(II.getType(), Instruction::Invoke,
540                    OperandTraits<InvokeInst>::op_end(this)
541                    - II.getNumOperands(),
542                    II.getNumOperands()) {
543   setAttributes(II.getAttributes());
544   setCallingConv(II.getCallingConv());
545   std::copy(II.op_begin(), II.op_end(), op_begin());
546   SubclassOptionalData = II.SubclassOptionalData;
547 }
548
549 BasicBlock *InvokeInst::getSuccessorV(unsigned idx) const {
550   return getSuccessor(idx);
551 }
552 unsigned InvokeInst::getNumSuccessorsV() const {
553   return getNumSuccessors();
554 }
555 void InvokeInst::setSuccessorV(unsigned idx, BasicBlock *B) {
556   return setSuccessor(idx, B);
557 }
558
559 bool InvokeInst::paramHasAttr(unsigned i, Attributes attr) const {
560   if (AttributeList.paramHasAttr(i, attr))
561     return true;
562   if (const Function *F = getCalledFunction())
563     return F->paramHasAttr(i, attr);
564   return false;
565 }
566
567 void InvokeInst::addAttribute(unsigned i, Attributes attr) {
568   AttrListPtr PAL = getAttributes();
569   PAL = PAL.addAttr(i, attr);
570   setAttributes(PAL);
571 }
572
573 void InvokeInst::removeAttribute(unsigned i, Attributes attr) {
574   AttrListPtr PAL = getAttributes();
575   PAL = PAL.removeAttr(i, attr);
576   setAttributes(PAL);
577 }
578
579 LandingPadInst *InvokeInst::getLandingPadInst() const {
580   return cast<LandingPadInst>(getUnwindDest()->getFirstNonPHI());
581 }
582
583 //===----------------------------------------------------------------------===//
584 //                        ReturnInst Implementation
585 //===----------------------------------------------------------------------===//
586
587 ReturnInst::ReturnInst(const ReturnInst &RI)
588   : TerminatorInst(Type::getVoidTy(RI.getContext()), Instruction::Ret,
589                    OperandTraits<ReturnInst>::op_end(this) -
590                      RI.getNumOperands(),
591                    RI.getNumOperands()) {
592   if (RI.getNumOperands())
593     Op<0>() = RI.Op<0>();
594   SubclassOptionalData = RI.SubclassOptionalData;
595 }
596
597 ReturnInst::ReturnInst(LLVMContext &C, Value *retVal, Instruction *InsertBefore)
598   : TerminatorInst(Type::getVoidTy(C), Instruction::Ret,
599                    OperandTraits<ReturnInst>::op_end(this) - !!retVal, !!retVal,
600                    InsertBefore) {
601   if (retVal)
602     Op<0>() = retVal;
603 }
604 ReturnInst::ReturnInst(LLVMContext &C, Value *retVal, BasicBlock *InsertAtEnd)
605   : TerminatorInst(Type::getVoidTy(C), Instruction::Ret,
606                    OperandTraits<ReturnInst>::op_end(this) - !!retVal, !!retVal,
607                    InsertAtEnd) {
608   if (retVal)
609     Op<0>() = retVal;
610 }
611 ReturnInst::ReturnInst(LLVMContext &Context, BasicBlock *InsertAtEnd)
612   : TerminatorInst(Type::getVoidTy(Context), Instruction::Ret,
613                    OperandTraits<ReturnInst>::op_end(this), 0, InsertAtEnd) {
614 }
615
616 unsigned ReturnInst::getNumSuccessorsV() const {
617   return getNumSuccessors();
618 }
619
620 /// Out-of-line ReturnInst method, put here so the C++ compiler can choose to
621 /// emit the vtable for the class in this translation unit.
622 void ReturnInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
623   llvm_unreachable("ReturnInst has no successors!");
624 }
625
626 BasicBlock *ReturnInst::getSuccessorV(unsigned idx) const {
627   llvm_unreachable("ReturnInst has no successors!");
628   return 0;
629 }
630
631 ReturnInst::~ReturnInst() {
632 }
633
634 //===----------------------------------------------------------------------===//
635 //                        UnwindInst Implementation
636 //===----------------------------------------------------------------------===//
637
638 UnwindInst::UnwindInst(LLVMContext &Context, Instruction *InsertBefore)
639   : TerminatorInst(Type::getVoidTy(Context), Instruction::Unwind,
640                    0, 0, InsertBefore) {
641 }
642 UnwindInst::UnwindInst(LLVMContext &Context, BasicBlock *InsertAtEnd)
643   : TerminatorInst(Type::getVoidTy(Context), Instruction::Unwind,
644                    0, 0, InsertAtEnd) {
645 }
646
647
648 unsigned UnwindInst::getNumSuccessorsV() const {
649   return getNumSuccessors();
650 }
651
652 void UnwindInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
653   llvm_unreachable("UnwindInst has no successors!");
654 }
655
656 BasicBlock *UnwindInst::getSuccessorV(unsigned idx) const {
657   llvm_unreachable("UnwindInst has no successors!");
658   return 0;
659 }
660
661 //===----------------------------------------------------------------------===//
662 //                        ResumeInst Implementation
663 //===----------------------------------------------------------------------===//
664
665 ResumeInst::ResumeInst(const ResumeInst &RI)
666   : TerminatorInst(Type::getVoidTy(RI.getContext()), Instruction::Resume,
667                    OperandTraits<ResumeInst>::op_begin(this), 1) {
668   Op<0>() = RI.Op<0>();
669 }
670
671 ResumeInst::ResumeInst(Value *Exn, Instruction *InsertBefore)
672   : TerminatorInst(Type::getVoidTy(Exn->getContext()), Instruction::Resume,
673                    OperandTraits<ResumeInst>::op_begin(this), 1, InsertBefore) {
674   Op<0>() = Exn;
675 }
676
677 ResumeInst::ResumeInst(Value *Exn, BasicBlock *InsertAtEnd)
678   : TerminatorInst(Type::getVoidTy(Exn->getContext()), Instruction::Resume,
679                    OperandTraits<ResumeInst>::op_begin(this), 1, InsertAtEnd) {
680   Op<0>() = Exn;
681 }
682
683 unsigned ResumeInst::getNumSuccessorsV() const {
684   return getNumSuccessors();
685 }
686
687 void ResumeInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
688   llvm_unreachable("ResumeInst has no successors!");
689 }
690
691 BasicBlock *ResumeInst::getSuccessorV(unsigned idx) const {
692   llvm_unreachable("ResumeInst has no successors!");
693   return 0;
694 }
695
696 //===----------------------------------------------------------------------===//
697 //                      UnreachableInst Implementation
698 //===----------------------------------------------------------------------===//
699
700 UnreachableInst::UnreachableInst(LLVMContext &Context, 
701                                  Instruction *InsertBefore)
702   : TerminatorInst(Type::getVoidTy(Context), Instruction::Unreachable,
703                    0, 0, InsertBefore) {
704 }
705 UnreachableInst::UnreachableInst(LLVMContext &Context, BasicBlock *InsertAtEnd)
706   : TerminatorInst(Type::getVoidTy(Context), Instruction::Unreachable,
707                    0, 0, InsertAtEnd) {
708 }
709
710 unsigned UnreachableInst::getNumSuccessorsV() const {
711   return getNumSuccessors();
712 }
713
714 void UnreachableInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
715   llvm_unreachable("UnwindInst has no successors!");
716 }
717
718 BasicBlock *UnreachableInst::getSuccessorV(unsigned idx) const {
719   llvm_unreachable("UnwindInst has no successors!");
720   return 0;
721 }
722
723 //===----------------------------------------------------------------------===//
724 //                        BranchInst Implementation
725 //===----------------------------------------------------------------------===//
726
727 void BranchInst::AssertOK() {
728   if (isConditional())
729     assert(getCondition()->getType()->isIntegerTy(1) &&
730            "May only branch on boolean predicates!");
731 }
732
733 BranchInst::BranchInst(BasicBlock *IfTrue, Instruction *InsertBefore)
734   : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
735                    OperandTraits<BranchInst>::op_end(this) - 1,
736                    1, InsertBefore) {
737   assert(IfTrue != 0 && "Branch destination may not be null!");
738   Op<-1>() = IfTrue;
739 }
740 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
741                        Instruction *InsertBefore)
742   : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
743                    OperandTraits<BranchInst>::op_end(this) - 3,
744                    3, InsertBefore) {
745   Op<-1>() = IfTrue;
746   Op<-2>() = IfFalse;
747   Op<-3>() = Cond;
748 #ifndef NDEBUG
749   AssertOK();
750 #endif
751 }
752
753 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *InsertAtEnd)
754   : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
755                    OperandTraits<BranchInst>::op_end(this) - 1,
756                    1, InsertAtEnd) {
757   assert(IfTrue != 0 && "Branch destination may not be null!");
758   Op<-1>() = IfTrue;
759 }
760
761 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
762            BasicBlock *InsertAtEnd)
763   : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
764                    OperandTraits<BranchInst>::op_end(this) - 3,
765                    3, InsertAtEnd) {
766   Op<-1>() = IfTrue;
767   Op<-2>() = IfFalse;
768   Op<-3>() = Cond;
769 #ifndef NDEBUG
770   AssertOK();
771 #endif
772 }
773
774
775 BranchInst::BranchInst(const BranchInst &BI) :
776   TerminatorInst(Type::getVoidTy(BI.getContext()), Instruction::Br,
777                  OperandTraits<BranchInst>::op_end(this) - BI.getNumOperands(),
778                  BI.getNumOperands()) {
779   Op<-1>() = BI.Op<-1>();
780   if (BI.getNumOperands() != 1) {
781     assert(BI.getNumOperands() == 3 && "BR can have 1 or 3 operands!");
782     Op<-3>() = BI.Op<-3>();
783     Op<-2>() = BI.Op<-2>();
784   }
785   SubclassOptionalData = BI.SubclassOptionalData;
786 }
787
788 BasicBlock *BranchInst::getSuccessorV(unsigned idx) const {
789   return getSuccessor(idx);
790 }
791 unsigned BranchInst::getNumSuccessorsV() const {
792   return getNumSuccessors();
793 }
794 void BranchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
795   setSuccessor(idx, B);
796 }
797
798
799 //===----------------------------------------------------------------------===//
800 //                        AllocaInst Implementation
801 //===----------------------------------------------------------------------===//
802
803 static Value *getAISize(LLVMContext &Context, Value *Amt) {
804   if (!Amt)
805     Amt = ConstantInt::get(Type::getInt32Ty(Context), 1);
806   else {
807     assert(!isa<BasicBlock>(Amt) &&
808            "Passed basic block into allocation size parameter! Use other ctor");
809     assert(Amt->getType()->isIntegerTy() &&
810            "Allocation array size is not an integer!");
811   }
812   return Amt;
813 }
814
815 AllocaInst::AllocaInst(Type *Ty, Value *ArraySize,
816                        const Twine &Name, Instruction *InsertBefore)
817   : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
818                      getAISize(Ty->getContext(), ArraySize), InsertBefore) {
819   setAlignment(0);
820   assert(!Ty->isVoidTy() && "Cannot allocate void!");
821   setName(Name);
822 }
823
824 AllocaInst::AllocaInst(Type *Ty, Value *ArraySize,
825                        const Twine &Name, BasicBlock *InsertAtEnd)
826   : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
827                      getAISize(Ty->getContext(), ArraySize), InsertAtEnd) {
828   setAlignment(0);
829   assert(!Ty->isVoidTy() && "Cannot allocate void!");
830   setName(Name);
831 }
832
833 AllocaInst::AllocaInst(Type *Ty, const Twine &Name,
834                        Instruction *InsertBefore)
835   : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
836                      getAISize(Ty->getContext(), 0), InsertBefore) {
837   setAlignment(0);
838   assert(!Ty->isVoidTy() && "Cannot allocate void!");
839   setName(Name);
840 }
841
842 AllocaInst::AllocaInst(Type *Ty, const Twine &Name,
843                        BasicBlock *InsertAtEnd)
844   : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
845                      getAISize(Ty->getContext(), 0), InsertAtEnd) {
846   setAlignment(0);
847   assert(!Ty->isVoidTy() && "Cannot allocate void!");
848   setName(Name);
849 }
850
851 AllocaInst::AllocaInst(Type *Ty, Value *ArraySize, unsigned Align,
852                        const Twine &Name, Instruction *InsertBefore)
853   : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
854                      getAISize(Ty->getContext(), ArraySize), InsertBefore) {
855   setAlignment(Align);
856   assert(!Ty->isVoidTy() && "Cannot allocate void!");
857   setName(Name);
858 }
859
860 AllocaInst::AllocaInst(Type *Ty, Value *ArraySize, unsigned Align,
861                        const Twine &Name, BasicBlock *InsertAtEnd)
862   : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
863                      getAISize(Ty->getContext(), ArraySize), InsertAtEnd) {
864   setAlignment(Align);
865   assert(!Ty->isVoidTy() && "Cannot allocate void!");
866   setName(Name);
867 }
868
869 // Out of line virtual method, so the vtable, etc has a home.
870 AllocaInst::~AllocaInst() {
871 }
872
873 void AllocaInst::setAlignment(unsigned Align) {
874   assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
875   assert(Align <= MaximumAlignment &&
876          "Alignment is greater than MaximumAlignment!");
877   setInstructionSubclassData(Log2_32(Align) + 1);
878   assert(getAlignment() == Align && "Alignment representation error!");
879 }
880
881 bool AllocaInst::isArrayAllocation() const {
882   if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(0)))
883     return !CI->isOne();
884   return true;
885 }
886
887 Type *AllocaInst::getAllocatedType() const {
888   return getType()->getElementType();
889 }
890
891 /// isStaticAlloca - Return true if this alloca is in the entry block of the
892 /// function and is a constant size.  If so, the code generator will fold it
893 /// into the prolog/epilog code, so it is basically free.
894 bool AllocaInst::isStaticAlloca() const {
895   // Must be constant size.
896   if (!isa<ConstantInt>(getArraySize())) return false;
897   
898   // Must be in the entry block.
899   const BasicBlock *Parent = getParent();
900   return Parent == &Parent->getParent()->front();
901 }
902
903 //===----------------------------------------------------------------------===//
904 //                           LoadInst Implementation
905 //===----------------------------------------------------------------------===//
906
907 void LoadInst::AssertOK() {
908   assert(getOperand(0)->getType()->isPointerTy() &&
909          "Ptr must have pointer type.");
910   assert(!(isAtomic() && getAlignment() == 0) &&
911          "Alignment required for atomic load");
912 }
913
914 LoadInst::LoadInst(Value *Ptr, const Twine &Name, Instruction *InsertBef)
915   : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
916                      Load, Ptr, InsertBef) {
917   setVolatile(false);
918   setAlignment(0);
919   setAtomic(NotAtomic);
920   AssertOK();
921   setName(Name);
922 }
923
924 LoadInst::LoadInst(Value *Ptr, const Twine &Name, BasicBlock *InsertAE)
925   : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
926                      Load, Ptr, InsertAE) {
927   setVolatile(false);
928   setAlignment(0);
929   setAtomic(NotAtomic);
930   AssertOK();
931   setName(Name);
932 }
933
934 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
935                    Instruction *InsertBef)
936   : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
937                      Load, Ptr, InsertBef) {
938   setVolatile(isVolatile);
939   setAlignment(0);
940   setAtomic(NotAtomic);
941   AssertOK();
942   setName(Name);
943 }
944
945 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
946                    BasicBlock *InsertAE)
947   : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
948                      Load, Ptr, InsertAE) {
949   setVolatile(isVolatile);
950   setAlignment(0);
951   setAtomic(NotAtomic);
952   AssertOK();
953   setName(Name);
954 }
955
956 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile, 
957                    unsigned Align, Instruction *InsertBef)
958   : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
959                      Load, Ptr, InsertBef) {
960   setVolatile(isVolatile);
961   setAlignment(Align);
962   setAtomic(NotAtomic);
963   AssertOK();
964   setName(Name);
965 }
966
967 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile, 
968                    unsigned Align, BasicBlock *InsertAE)
969   : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
970                      Load, Ptr, InsertAE) {
971   setVolatile(isVolatile);
972   setAlignment(Align);
973   setAtomic(NotAtomic);
974   AssertOK();
975   setName(Name);
976 }
977
978 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile, 
979                    unsigned Align, AtomicOrdering Order,
980                    SynchronizationScope SynchScope,
981                    Instruction *InsertBef)
982   : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
983                      Load, Ptr, InsertBef) {
984   setVolatile(isVolatile);
985   setAlignment(Align);
986   setAtomic(Order, SynchScope);
987   AssertOK();
988   setName(Name);
989 }
990
991 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile, 
992                    unsigned Align, AtomicOrdering Order,
993                    SynchronizationScope SynchScope,
994                    BasicBlock *InsertAE)
995   : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
996                      Load, Ptr, InsertAE) {
997   setVolatile(isVolatile);
998   setAlignment(Align);
999   setAtomic(Order, SynchScope);
1000   AssertOK();
1001   setName(Name);
1002 }
1003
1004 LoadInst::LoadInst(Value *Ptr, const char *Name, Instruction *InsertBef)
1005   : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1006                      Load, Ptr, InsertBef) {
1007   setVolatile(false);
1008   setAlignment(0);
1009   setAtomic(NotAtomic);
1010   AssertOK();
1011   if (Name && Name[0]) setName(Name);
1012 }
1013
1014 LoadInst::LoadInst(Value *Ptr, const char *Name, BasicBlock *InsertAE)
1015   : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1016                      Load, Ptr, InsertAE) {
1017   setVolatile(false);
1018   setAlignment(0);
1019   setAtomic(NotAtomic);
1020   AssertOK();
1021   if (Name && Name[0]) setName(Name);
1022 }
1023
1024 LoadInst::LoadInst(Value *Ptr, const char *Name, bool isVolatile,
1025                    Instruction *InsertBef)
1026 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1027                    Load, Ptr, InsertBef) {
1028   setVolatile(isVolatile);
1029   setAlignment(0);
1030   setAtomic(NotAtomic);
1031   AssertOK();
1032   if (Name && Name[0]) setName(Name);
1033 }
1034
1035 LoadInst::LoadInst(Value *Ptr, const char *Name, bool isVolatile,
1036                    BasicBlock *InsertAE)
1037   : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1038                      Load, Ptr, InsertAE) {
1039   setVolatile(isVolatile);
1040   setAlignment(0);
1041   setAtomic(NotAtomic);
1042   AssertOK();
1043   if (Name && Name[0]) setName(Name);
1044 }
1045
1046 void LoadInst::setAlignment(unsigned Align) {
1047   assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
1048   assert(Align <= MaximumAlignment &&
1049          "Alignment is greater than MaximumAlignment!");
1050   setInstructionSubclassData((getSubclassDataFromInstruction() & ~(31 << 1)) |
1051                              ((Log2_32(Align)+1)<<1));
1052   assert(getAlignment() == Align && "Alignment representation error!");
1053 }
1054
1055 //===----------------------------------------------------------------------===//
1056 //                           StoreInst Implementation
1057 //===----------------------------------------------------------------------===//
1058
1059 void StoreInst::AssertOK() {
1060   assert(getOperand(0) && getOperand(1) && "Both operands must be non-null!");
1061   assert(getOperand(1)->getType()->isPointerTy() &&
1062          "Ptr must have pointer type!");
1063   assert(getOperand(0)->getType() ==
1064                  cast<PointerType>(getOperand(1)->getType())->getElementType()
1065          && "Ptr must be a pointer to Val type!");
1066   assert(!(isAtomic() && getAlignment() == 0) &&
1067          "Alignment required for atomic load");
1068 }
1069
1070
1071 StoreInst::StoreInst(Value *val, Value *addr, Instruction *InsertBefore)
1072   : Instruction(Type::getVoidTy(val->getContext()), Store,
1073                 OperandTraits<StoreInst>::op_begin(this),
1074                 OperandTraits<StoreInst>::operands(this),
1075                 InsertBefore) {
1076   Op<0>() = val;
1077   Op<1>() = addr;
1078   setVolatile(false);
1079   setAlignment(0);
1080   setAtomic(NotAtomic);
1081   AssertOK();
1082 }
1083
1084 StoreInst::StoreInst(Value *val, Value *addr, BasicBlock *InsertAtEnd)
1085   : Instruction(Type::getVoidTy(val->getContext()), Store,
1086                 OperandTraits<StoreInst>::op_begin(this),
1087                 OperandTraits<StoreInst>::operands(this),
1088                 InsertAtEnd) {
1089   Op<0>() = val;
1090   Op<1>() = addr;
1091   setVolatile(false);
1092   setAlignment(0);
1093   setAtomic(NotAtomic);
1094   AssertOK();
1095 }
1096
1097 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1098                      Instruction *InsertBefore)
1099   : Instruction(Type::getVoidTy(val->getContext()), Store,
1100                 OperandTraits<StoreInst>::op_begin(this),
1101                 OperandTraits<StoreInst>::operands(this),
1102                 InsertBefore) {
1103   Op<0>() = val;
1104   Op<1>() = addr;
1105   setVolatile(isVolatile);
1106   setAlignment(0);
1107   setAtomic(NotAtomic);
1108   AssertOK();
1109 }
1110
1111 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1112                      unsigned Align, Instruction *InsertBefore)
1113   : Instruction(Type::getVoidTy(val->getContext()), Store,
1114                 OperandTraits<StoreInst>::op_begin(this),
1115                 OperandTraits<StoreInst>::operands(this),
1116                 InsertBefore) {
1117   Op<0>() = val;
1118   Op<1>() = addr;
1119   setVolatile(isVolatile);
1120   setAlignment(Align);
1121   setAtomic(NotAtomic);
1122   AssertOK();
1123 }
1124
1125 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1126                      unsigned Align, AtomicOrdering Order,
1127                      SynchronizationScope SynchScope,
1128                      Instruction *InsertBefore)
1129   : Instruction(Type::getVoidTy(val->getContext()), Store,
1130                 OperandTraits<StoreInst>::op_begin(this),
1131                 OperandTraits<StoreInst>::operands(this),
1132                 InsertBefore) {
1133   Op<0>() = val;
1134   Op<1>() = addr;
1135   setVolatile(isVolatile);
1136   setAlignment(Align);
1137   setAtomic(Order, SynchScope);
1138   AssertOK();
1139 }
1140
1141 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1142                      BasicBlock *InsertAtEnd)
1143   : Instruction(Type::getVoidTy(val->getContext()), Store,
1144                 OperandTraits<StoreInst>::op_begin(this),
1145                 OperandTraits<StoreInst>::operands(this),
1146                 InsertAtEnd) {
1147   Op<0>() = val;
1148   Op<1>() = addr;
1149   setVolatile(isVolatile);
1150   setAlignment(0);
1151   setAtomic(NotAtomic);
1152   AssertOK();
1153 }
1154
1155 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1156                      unsigned Align, BasicBlock *InsertAtEnd)
1157   : Instruction(Type::getVoidTy(val->getContext()), Store,
1158                 OperandTraits<StoreInst>::op_begin(this),
1159                 OperandTraits<StoreInst>::operands(this),
1160                 InsertAtEnd) {
1161   Op<0>() = val;
1162   Op<1>() = addr;
1163   setVolatile(isVolatile);
1164   setAlignment(Align);
1165   setAtomic(NotAtomic);
1166   AssertOK();
1167 }
1168
1169 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1170                      unsigned Align, AtomicOrdering Order,
1171                      SynchronizationScope SynchScope,
1172                      BasicBlock *InsertAtEnd)
1173   : Instruction(Type::getVoidTy(val->getContext()), Store,
1174                 OperandTraits<StoreInst>::op_begin(this),
1175                 OperandTraits<StoreInst>::operands(this),
1176                 InsertAtEnd) {
1177   Op<0>() = val;
1178   Op<1>() = addr;
1179   setVolatile(isVolatile);
1180   setAlignment(Align);
1181   setAtomic(Order, SynchScope);
1182   AssertOK();
1183 }
1184
1185 void StoreInst::setAlignment(unsigned Align) {
1186   assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
1187   assert(Align <= MaximumAlignment &&
1188          "Alignment is greater than MaximumAlignment!");
1189   setInstructionSubclassData((getSubclassDataFromInstruction() & ~(31 << 1)) |
1190                              ((Log2_32(Align)+1) << 1));
1191   assert(getAlignment() == Align && "Alignment representation error!");
1192 }
1193
1194 //===----------------------------------------------------------------------===//
1195 //                       AtomicCmpXchgInst Implementation
1196 //===----------------------------------------------------------------------===//
1197
1198 void AtomicCmpXchgInst::Init(Value *Ptr, Value *Cmp, Value *NewVal,
1199                              AtomicOrdering Ordering,
1200                              SynchronizationScope SynchScope) {
1201   Op<0>() = Ptr;
1202   Op<1>() = Cmp;
1203   Op<2>() = NewVal;
1204   setOrdering(Ordering);
1205   setSynchScope(SynchScope);
1206
1207   assert(getOperand(0) && getOperand(1) && getOperand(2) &&
1208          "All operands must be non-null!");
1209   assert(getOperand(0)->getType()->isPointerTy() &&
1210          "Ptr must have pointer type!");
1211   assert(getOperand(1)->getType() ==
1212                  cast<PointerType>(getOperand(0)->getType())->getElementType()
1213          && "Ptr must be a pointer to Cmp type!");
1214   assert(getOperand(2)->getType() ==
1215                  cast<PointerType>(getOperand(0)->getType())->getElementType()
1216          && "Ptr must be a pointer to NewVal type!");
1217   assert(Ordering != NotAtomic &&
1218          "AtomicCmpXchg instructions must be atomic!");
1219 }
1220
1221 AtomicCmpXchgInst::AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal,
1222                                      AtomicOrdering Ordering,
1223                                      SynchronizationScope SynchScope,
1224                                      Instruction *InsertBefore)
1225   : Instruction(Cmp->getType(), AtomicCmpXchg,
1226                 OperandTraits<AtomicCmpXchgInst>::op_begin(this),
1227                 OperandTraits<AtomicCmpXchgInst>::operands(this),
1228                 InsertBefore) {
1229   Init(Ptr, Cmp, NewVal, Ordering, SynchScope);
1230 }
1231
1232 AtomicCmpXchgInst::AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal,
1233                                      AtomicOrdering Ordering,
1234                                      SynchronizationScope SynchScope,
1235                                      BasicBlock *InsertAtEnd)
1236   : Instruction(Cmp->getType(), AtomicCmpXchg,
1237                 OperandTraits<AtomicCmpXchgInst>::op_begin(this),
1238                 OperandTraits<AtomicCmpXchgInst>::operands(this),
1239                 InsertAtEnd) {
1240   Init(Ptr, Cmp, NewVal, Ordering, SynchScope);
1241 }
1242  
1243 //===----------------------------------------------------------------------===//
1244 //                       AtomicRMWInst Implementation
1245 //===----------------------------------------------------------------------===//
1246
1247 void AtomicRMWInst::Init(BinOp Operation, Value *Ptr, Value *Val,
1248                          AtomicOrdering Ordering,
1249                          SynchronizationScope SynchScope) {
1250   Op<0>() = Ptr;
1251   Op<1>() = Val;
1252   setOperation(Operation);
1253   setOrdering(Ordering);
1254   setSynchScope(SynchScope);
1255
1256   assert(getOperand(0) && getOperand(1) &&
1257          "All operands must be non-null!");
1258   assert(getOperand(0)->getType()->isPointerTy() &&
1259          "Ptr must have pointer type!");
1260   assert(getOperand(1)->getType() ==
1261          cast<PointerType>(getOperand(0)->getType())->getElementType()
1262          && "Ptr must be a pointer to Val type!");
1263   assert(Ordering != NotAtomic &&
1264          "AtomicRMW instructions must be atomic!");
1265 }
1266
1267 AtomicRMWInst::AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val,
1268                              AtomicOrdering Ordering,
1269                              SynchronizationScope SynchScope,
1270                              Instruction *InsertBefore)
1271   : Instruction(Val->getType(), AtomicRMW,
1272                 OperandTraits<AtomicRMWInst>::op_begin(this),
1273                 OperandTraits<AtomicRMWInst>::operands(this),
1274                 InsertBefore) {
1275   Init(Operation, Ptr, Val, Ordering, SynchScope);
1276 }
1277
1278 AtomicRMWInst::AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val,
1279                              AtomicOrdering Ordering,
1280                              SynchronizationScope SynchScope,
1281                              BasicBlock *InsertAtEnd)
1282   : Instruction(Val->getType(), AtomicRMW,
1283                 OperandTraits<AtomicRMWInst>::op_begin(this),
1284                 OperandTraits<AtomicRMWInst>::operands(this),
1285                 InsertAtEnd) {
1286   Init(Operation, Ptr, Val, Ordering, SynchScope);
1287 }
1288
1289 //===----------------------------------------------------------------------===//
1290 //                       FenceInst Implementation
1291 //===----------------------------------------------------------------------===//
1292
1293 FenceInst::FenceInst(LLVMContext &C, AtomicOrdering Ordering, 
1294                      SynchronizationScope SynchScope,
1295                      Instruction *InsertBefore)
1296   : Instruction(Type::getVoidTy(C), Fence, 0, 0, InsertBefore) {
1297   setOrdering(Ordering);
1298   setSynchScope(SynchScope);
1299 }
1300
1301 FenceInst::FenceInst(LLVMContext &C, AtomicOrdering Ordering, 
1302                      SynchronizationScope SynchScope,
1303                      BasicBlock *InsertAtEnd)
1304   : Instruction(Type::getVoidTy(C), Fence, 0, 0, InsertAtEnd) {
1305   setOrdering(Ordering);
1306   setSynchScope(SynchScope);
1307 }
1308
1309 //===----------------------------------------------------------------------===//
1310 //                       GetElementPtrInst Implementation
1311 //===----------------------------------------------------------------------===//
1312
1313 void GetElementPtrInst::init(Value *Ptr, ArrayRef<Value *> IdxList,
1314                              const Twine &Name) {
1315   assert(NumOperands == 1 + IdxList.size() && "NumOperands not initialized?");
1316   OperandList[0] = Ptr;
1317   std::copy(IdxList.begin(), IdxList.end(), op_begin() + 1);
1318   setName(Name);
1319 }
1320
1321 GetElementPtrInst::GetElementPtrInst(const GetElementPtrInst &GEPI)
1322   : Instruction(GEPI.getType(), GetElementPtr,
1323                 OperandTraits<GetElementPtrInst>::op_end(this)
1324                 - GEPI.getNumOperands(),
1325                 GEPI.getNumOperands()) {
1326   std::copy(GEPI.op_begin(), GEPI.op_end(), op_begin());
1327   SubclassOptionalData = GEPI.SubclassOptionalData;
1328 }
1329
1330 /// getIndexedType - Returns the type of the element that would be accessed with
1331 /// a gep instruction with the specified parameters.
1332 ///
1333 /// The Idxs pointer should point to a continuous piece of memory containing the
1334 /// indices, either as Value* or uint64_t.
1335 ///
1336 /// A null type is returned if the indices are invalid for the specified
1337 /// pointer type.
1338 ///
1339 template <typename IndexTy>
1340 static Type *getIndexedTypeInternal(Type *Ptr, ArrayRef<IndexTy> IdxList) {
1341   PointerType *PTy = dyn_cast<PointerType>(Ptr);
1342   if (!PTy) return 0;   // Type isn't a pointer type!
1343   Type *Agg = PTy->getElementType();
1344
1345   // Handle the special case of the empty set index set, which is always valid.
1346   if (IdxList.empty())
1347     return Agg;
1348   
1349   // If there is at least one index, the top level type must be sized, otherwise
1350   // it cannot be 'stepped over'.
1351   if (!Agg->isSized())
1352     return 0;
1353
1354   unsigned CurIdx = 1;
1355   for (; CurIdx != IdxList.size(); ++CurIdx) {
1356     CompositeType *CT = dyn_cast<CompositeType>(Agg);
1357     if (!CT || CT->isPointerTy()) return 0;
1358     IndexTy Index = IdxList[CurIdx];
1359     if (!CT->indexValid(Index)) return 0;
1360     Agg = CT->getTypeAtIndex(Index);
1361   }
1362   return CurIdx == IdxList.size() ? Agg : 0;
1363 }
1364
1365 Type *GetElementPtrInst::getIndexedType(Type *Ptr, ArrayRef<Value *> IdxList) {
1366   return getIndexedTypeInternal(Ptr, IdxList);
1367 }
1368
1369 Type *GetElementPtrInst::getIndexedType(Type *Ptr,
1370                                         ArrayRef<Constant *> IdxList) {
1371   return getIndexedTypeInternal(Ptr, IdxList);
1372 }
1373
1374 Type *GetElementPtrInst::getIndexedType(Type *Ptr, ArrayRef<uint64_t> IdxList) {
1375   return getIndexedTypeInternal(Ptr, IdxList);
1376 }
1377
1378 /// hasAllZeroIndices - Return true if all of the indices of this GEP are
1379 /// zeros.  If so, the result pointer and the first operand have the same
1380 /// value, just potentially different types.
1381 bool GetElementPtrInst::hasAllZeroIndices() const {
1382   for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1383     if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(i))) {
1384       if (!CI->isZero()) return false;
1385     } else {
1386       return false;
1387     }
1388   }
1389   return true;
1390 }
1391
1392 /// hasAllConstantIndices - Return true if all of the indices of this GEP are
1393 /// constant integers.  If so, the result pointer and the first operand have
1394 /// a constant offset between them.
1395 bool GetElementPtrInst::hasAllConstantIndices() const {
1396   for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1397     if (!isa<ConstantInt>(getOperand(i)))
1398       return false;
1399   }
1400   return true;
1401 }
1402
1403 void GetElementPtrInst::setIsInBounds(bool B) {
1404   cast<GEPOperator>(this)->setIsInBounds(B);
1405 }
1406
1407 bool GetElementPtrInst::isInBounds() const {
1408   return cast<GEPOperator>(this)->isInBounds();
1409 }
1410
1411 //===----------------------------------------------------------------------===//
1412 //                           ExtractElementInst Implementation
1413 //===----------------------------------------------------------------------===//
1414
1415 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
1416                                        const Twine &Name,
1417                                        Instruction *InsertBef)
1418   : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1419                 ExtractElement,
1420                 OperandTraits<ExtractElementInst>::op_begin(this),
1421                 2, InsertBef) {
1422   assert(isValidOperands(Val, Index) &&
1423          "Invalid extractelement instruction operands!");
1424   Op<0>() = Val;
1425   Op<1>() = Index;
1426   setName(Name);
1427 }
1428
1429 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
1430                                        const Twine &Name,
1431                                        BasicBlock *InsertAE)
1432   : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1433                 ExtractElement,
1434                 OperandTraits<ExtractElementInst>::op_begin(this),
1435                 2, InsertAE) {
1436   assert(isValidOperands(Val, Index) &&
1437          "Invalid extractelement instruction operands!");
1438
1439   Op<0>() = Val;
1440   Op<1>() = Index;
1441   setName(Name);
1442 }
1443
1444
1445 bool ExtractElementInst::isValidOperands(const Value *Val, const Value *Index) {
1446   if (!Val->getType()->isVectorTy() || !Index->getType()->isIntegerTy(32))
1447     return false;
1448   return true;
1449 }
1450
1451
1452 //===----------------------------------------------------------------------===//
1453 //                           InsertElementInst Implementation
1454 //===----------------------------------------------------------------------===//
1455
1456 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
1457                                      const Twine &Name,
1458                                      Instruction *InsertBef)
1459   : Instruction(Vec->getType(), InsertElement,
1460                 OperandTraits<InsertElementInst>::op_begin(this),
1461                 3, InsertBef) {
1462   assert(isValidOperands(Vec, Elt, Index) &&
1463          "Invalid insertelement instruction operands!");
1464   Op<0>() = Vec;
1465   Op<1>() = Elt;
1466   Op<2>() = Index;
1467   setName(Name);
1468 }
1469
1470 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
1471                                      const Twine &Name,
1472                                      BasicBlock *InsertAE)
1473   : Instruction(Vec->getType(), InsertElement,
1474                 OperandTraits<InsertElementInst>::op_begin(this),
1475                 3, InsertAE) {
1476   assert(isValidOperands(Vec, Elt, Index) &&
1477          "Invalid insertelement instruction operands!");
1478
1479   Op<0>() = Vec;
1480   Op<1>() = Elt;
1481   Op<2>() = Index;
1482   setName(Name);
1483 }
1484
1485 bool InsertElementInst::isValidOperands(const Value *Vec, const Value *Elt, 
1486                                         const Value *Index) {
1487   if (!Vec->getType()->isVectorTy())
1488     return false;   // First operand of insertelement must be vector type.
1489   
1490   if (Elt->getType() != cast<VectorType>(Vec->getType())->getElementType())
1491     return false;// Second operand of insertelement must be vector element type.
1492     
1493   if (!Index->getType()->isIntegerTy(32))
1494     return false;  // Third operand of insertelement must be i32.
1495   return true;
1496 }
1497
1498
1499 //===----------------------------------------------------------------------===//
1500 //                      ShuffleVectorInst Implementation
1501 //===----------------------------------------------------------------------===//
1502
1503 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1504                                      const Twine &Name,
1505                                      Instruction *InsertBefore)
1506 : Instruction(VectorType::get(cast<VectorType>(V1->getType())->getElementType(),
1507                 cast<VectorType>(Mask->getType())->getNumElements()),
1508               ShuffleVector,
1509               OperandTraits<ShuffleVectorInst>::op_begin(this),
1510               OperandTraits<ShuffleVectorInst>::operands(this),
1511               InsertBefore) {
1512   assert(isValidOperands(V1, V2, Mask) &&
1513          "Invalid shuffle vector instruction operands!");
1514   Op<0>() = V1;
1515   Op<1>() = V2;
1516   Op<2>() = Mask;
1517   setName(Name);
1518 }
1519
1520 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1521                                      const Twine &Name,
1522                                      BasicBlock *InsertAtEnd)
1523 : Instruction(VectorType::get(cast<VectorType>(V1->getType())->getElementType(),
1524                 cast<VectorType>(Mask->getType())->getNumElements()),
1525               ShuffleVector,
1526               OperandTraits<ShuffleVectorInst>::op_begin(this),
1527               OperandTraits<ShuffleVectorInst>::operands(this),
1528               InsertAtEnd) {
1529   assert(isValidOperands(V1, V2, Mask) &&
1530          "Invalid shuffle vector instruction operands!");
1531
1532   Op<0>() = V1;
1533   Op<1>() = V2;
1534   Op<2>() = Mask;
1535   setName(Name);
1536 }
1537
1538 bool ShuffleVectorInst::isValidOperands(const Value *V1, const Value *V2,
1539                                         const Value *Mask) {
1540   if (!V1->getType()->isVectorTy() || V1->getType() != V2->getType())
1541     return false;
1542   
1543   VectorType *MaskTy = dyn_cast<VectorType>(Mask->getType());
1544   if (MaskTy == 0 || !MaskTy->getElementType()->isIntegerTy(32))
1545     return false;
1546
1547   // Check to see if Mask is valid.
1548   if (const ConstantVector *MV = dyn_cast<ConstantVector>(Mask)) {
1549     VectorType *VTy = cast<VectorType>(V1->getType());
1550     for (unsigned i = 0, e = MV->getNumOperands(); i != e; ++i) {
1551       if (ConstantInt* CI = dyn_cast<ConstantInt>(MV->getOperand(i))) {
1552         if (CI->uge(VTy->getNumElements()*2))
1553           return false;
1554       } else if (!isa<UndefValue>(MV->getOperand(i))) {
1555         return false;
1556       }
1557     }
1558   }
1559   else if (!isa<UndefValue>(Mask) && !isa<ConstantAggregateZero>(Mask))
1560     return false;
1561   
1562   return true;
1563 }
1564
1565 /// getMaskValue - Return the index from the shuffle mask for the specified
1566 /// output result.  This is either -1 if the element is undef or a number less
1567 /// than 2*numelements.
1568 int ShuffleVectorInst::getMaskValue(unsigned i) const {
1569   const Constant *Mask = cast<Constant>(getOperand(2));
1570   if (isa<UndefValue>(Mask)) return -1;
1571   if (isa<ConstantAggregateZero>(Mask)) return 0;
1572   const ConstantVector *MaskCV = cast<ConstantVector>(Mask);
1573   assert(i < MaskCV->getNumOperands() && "Index out of range");
1574
1575   if (isa<UndefValue>(MaskCV->getOperand(i)))
1576     return -1;
1577   return cast<ConstantInt>(MaskCV->getOperand(i))->getZExtValue();
1578 }
1579
1580 //===----------------------------------------------------------------------===//
1581 //                             InsertValueInst Class
1582 //===----------------------------------------------------------------------===//
1583
1584 void InsertValueInst::init(Value *Agg, Value *Val, ArrayRef<unsigned> Idxs, 
1585                            const Twine &Name) {
1586   assert(NumOperands == 2 && "NumOperands not initialized?");
1587
1588   // There's no fundamental reason why we require at least one index
1589   // (other than weirdness with &*IdxBegin being invalid; see
1590   // getelementptr's init routine for example). But there's no
1591   // present need to support it.
1592   assert(Idxs.size() > 0 && "InsertValueInst must have at least one index");
1593
1594   assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs) ==
1595          Val->getType() && "Inserted value must match indexed type!");
1596   Op<0>() = Agg;
1597   Op<1>() = Val;
1598
1599   Indices.append(Idxs.begin(), Idxs.end());
1600   setName(Name);
1601 }
1602
1603 InsertValueInst::InsertValueInst(const InsertValueInst &IVI)
1604   : Instruction(IVI.getType(), InsertValue,
1605                 OperandTraits<InsertValueInst>::op_begin(this), 2),
1606     Indices(IVI.Indices) {
1607   Op<0>() = IVI.getOperand(0);
1608   Op<1>() = IVI.getOperand(1);
1609   SubclassOptionalData = IVI.SubclassOptionalData;
1610 }
1611
1612 //===----------------------------------------------------------------------===//
1613 //                             ExtractValueInst Class
1614 //===----------------------------------------------------------------------===//
1615
1616 void ExtractValueInst::init(ArrayRef<unsigned> Idxs, const Twine &Name) {
1617   assert(NumOperands == 1 && "NumOperands not initialized?");
1618
1619   // There's no fundamental reason why we require at least one index.
1620   // But there's no present need to support it.
1621   assert(Idxs.size() > 0 && "ExtractValueInst must have at least one index");
1622
1623   Indices.append(Idxs.begin(), Idxs.end());
1624   setName(Name);
1625 }
1626
1627 ExtractValueInst::ExtractValueInst(const ExtractValueInst &EVI)
1628   : UnaryInstruction(EVI.getType(), ExtractValue, EVI.getOperand(0)),
1629     Indices(EVI.Indices) {
1630   SubclassOptionalData = EVI.SubclassOptionalData;
1631 }
1632
1633 // getIndexedType - Returns the type of the element that would be extracted
1634 // with an extractvalue instruction with the specified parameters.
1635 //
1636 // A null type is returned if the indices are invalid for the specified
1637 // pointer type.
1638 //
1639 Type *ExtractValueInst::getIndexedType(Type *Agg,
1640                                        ArrayRef<unsigned> Idxs) {
1641   for (unsigned CurIdx = 0; CurIdx != Idxs.size(); ++CurIdx) {
1642     unsigned Index = Idxs[CurIdx];
1643     // We can't use CompositeType::indexValid(Index) here.
1644     // indexValid() always returns true for arrays because getelementptr allows
1645     // out-of-bounds indices. Since we don't allow those for extractvalue and
1646     // insertvalue we need to check array indexing manually.
1647     // Since the only other types we can index into are struct types it's just
1648     // as easy to check those manually as well.
1649     if (ArrayType *AT = dyn_cast<ArrayType>(Agg)) {
1650       if (Index >= AT->getNumElements())
1651         return 0;
1652     } else if (StructType *ST = dyn_cast<StructType>(Agg)) {
1653       if (Index >= ST->getNumElements())
1654         return 0;
1655     } else {
1656       // Not a valid type to index into.
1657       return 0;
1658     }
1659
1660     Agg = cast<CompositeType>(Agg)->getTypeAtIndex(Index);
1661   }
1662   return const_cast<Type*>(Agg);
1663 }
1664
1665 //===----------------------------------------------------------------------===//
1666 //                             BinaryOperator Class
1667 //===----------------------------------------------------------------------===//
1668
1669 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
1670                                Type *Ty, const Twine &Name,
1671                                Instruction *InsertBefore)
1672   : Instruction(Ty, iType,
1673                 OperandTraits<BinaryOperator>::op_begin(this),
1674                 OperandTraits<BinaryOperator>::operands(this),
1675                 InsertBefore) {
1676   Op<0>() = S1;
1677   Op<1>() = S2;
1678   init(iType);
1679   setName(Name);
1680 }
1681
1682 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2, 
1683                                Type *Ty, const Twine &Name,
1684                                BasicBlock *InsertAtEnd)
1685   : Instruction(Ty, iType,
1686                 OperandTraits<BinaryOperator>::op_begin(this),
1687                 OperandTraits<BinaryOperator>::operands(this),
1688                 InsertAtEnd) {
1689   Op<0>() = S1;
1690   Op<1>() = S2;
1691   init(iType);
1692   setName(Name);
1693 }
1694
1695
1696 void BinaryOperator::init(BinaryOps iType) {
1697   Value *LHS = getOperand(0), *RHS = getOperand(1);
1698   (void)LHS; (void)RHS; // Silence warnings.
1699   assert(LHS->getType() == RHS->getType() &&
1700          "Binary operator operand types must match!");
1701 #ifndef NDEBUG
1702   switch (iType) {
1703   case Add: case Sub:
1704   case Mul:
1705     assert(getType() == LHS->getType() &&
1706            "Arithmetic operation should return same type as operands!");
1707     assert(getType()->isIntOrIntVectorTy() &&
1708            "Tried to create an integer operation on a non-integer type!");
1709     break;
1710   case FAdd: case FSub:
1711   case FMul:
1712     assert(getType() == LHS->getType() &&
1713            "Arithmetic operation should return same type as operands!");
1714     assert(getType()->isFPOrFPVectorTy() &&
1715            "Tried to create a floating-point operation on a "
1716            "non-floating-point type!");
1717     break;
1718   case UDiv: 
1719   case SDiv: 
1720     assert(getType() == LHS->getType() &&
1721            "Arithmetic operation should return same type as operands!");
1722     assert((getType()->isIntegerTy() || (getType()->isVectorTy() && 
1723             cast<VectorType>(getType())->getElementType()->isIntegerTy())) &&
1724            "Incorrect operand type (not integer) for S/UDIV");
1725     break;
1726   case FDiv:
1727     assert(getType() == LHS->getType() &&
1728            "Arithmetic operation should return same type as operands!");
1729     assert(getType()->isFPOrFPVectorTy() &&
1730            "Incorrect operand type (not floating point) for FDIV");
1731     break;
1732   case URem: 
1733   case SRem: 
1734     assert(getType() == LHS->getType() &&
1735            "Arithmetic operation should return same type as operands!");
1736     assert((getType()->isIntegerTy() || (getType()->isVectorTy() && 
1737             cast<VectorType>(getType())->getElementType()->isIntegerTy())) &&
1738            "Incorrect operand type (not integer) for S/UREM");
1739     break;
1740   case FRem:
1741     assert(getType() == LHS->getType() &&
1742            "Arithmetic operation should return same type as operands!");
1743     assert(getType()->isFPOrFPVectorTy() &&
1744            "Incorrect operand type (not floating point) for FREM");
1745     break;
1746   case Shl:
1747   case LShr:
1748   case AShr:
1749     assert(getType() == LHS->getType() &&
1750            "Shift operation should return same type as operands!");
1751     assert((getType()->isIntegerTy() ||
1752             (getType()->isVectorTy() && 
1753              cast<VectorType>(getType())->getElementType()->isIntegerTy())) &&
1754            "Tried to create a shift operation on a non-integral type!");
1755     break;
1756   case And: case Or:
1757   case Xor:
1758     assert(getType() == LHS->getType() &&
1759            "Logical operation should return same type as operands!");
1760     assert((getType()->isIntegerTy() ||
1761             (getType()->isVectorTy() && 
1762              cast<VectorType>(getType())->getElementType()->isIntegerTy())) &&
1763            "Tried to create a logical operation on a non-integral type!");
1764     break;
1765   default:
1766     break;
1767   }
1768 #endif
1769 }
1770
1771 BinaryOperator *BinaryOperator::Create(BinaryOps Op, Value *S1, Value *S2,
1772                                        const Twine &Name,
1773                                        Instruction *InsertBefore) {
1774   assert(S1->getType() == S2->getType() &&
1775          "Cannot create binary operator with two operands of differing type!");
1776   return new BinaryOperator(Op, S1, S2, S1->getType(), Name, InsertBefore);
1777 }
1778
1779 BinaryOperator *BinaryOperator::Create(BinaryOps Op, Value *S1, Value *S2,
1780                                        const Twine &Name,
1781                                        BasicBlock *InsertAtEnd) {
1782   BinaryOperator *Res = Create(Op, S1, S2, Name);
1783   InsertAtEnd->getInstList().push_back(Res);
1784   return Res;
1785 }
1786
1787 BinaryOperator *BinaryOperator::CreateNeg(Value *Op, const Twine &Name,
1788                                           Instruction *InsertBefore) {
1789   Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1790   return new BinaryOperator(Instruction::Sub,
1791                             zero, Op,
1792                             Op->getType(), Name, InsertBefore);
1793 }
1794
1795 BinaryOperator *BinaryOperator::CreateNeg(Value *Op, const Twine &Name,
1796                                           BasicBlock *InsertAtEnd) {
1797   Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1798   return new BinaryOperator(Instruction::Sub,
1799                             zero, Op,
1800                             Op->getType(), Name, InsertAtEnd);
1801 }
1802
1803 BinaryOperator *BinaryOperator::CreateNSWNeg(Value *Op, const Twine &Name,
1804                                              Instruction *InsertBefore) {
1805   Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1806   return BinaryOperator::CreateNSWSub(zero, Op, Name, InsertBefore);
1807 }
1808
1809 BinaryOperator *BinaryOperator::CreateNSWNeg(Value *Op, const Twine &Name,
1810                                              BasicBlock *InsertAtEnd) {
1811   Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1812   return BinaryOperator::CreateNSWSub(zero, Op, Name, InsertAtEnd);
1813 }
1814
1815 BinaryOperator *BinaryOperator::CreateNUWNeg(Value *Op, const Twine &Name,
1816                                              Instruction *InsertBefore) {
1817   Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1818   return BinaryOperator::CreateNUWSub(zero, Op, Name, InsertBefore);
1819 }
1820
1821 BinaryOperator *BinaryOperator::CreateNUWNeg(Value *Op, const Twine &Name,
1822                                              BasicBlock *InsertAtEnd) {
1823   Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1824   return BinaryOperator::CreateNUWSub(zero, Op, Name, InsertAtEnd);
1825 }
1826
1827 BinaryOperator *BinaryOperator::CreateFNeg(Value *Op, const Twine &Name,
1828                                            Instruction *InsertBefore) {
1829   Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1830   return new BinaryOperator(Instruction::FSub,
1831                             zero, Op,
1832                             Op->getType(), Name, InsertBefore);
1833 }
1834
1835 BinaryOperator *BinaryOperator::CreateFNeg(Value *Op, const Twine &Name,
1836                                            BasicBlock *InsertAtEnd) {
1837   Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1838   return new BinaryOperator(Instruction::FSub,
1839                             zero, Op,
1840                             Op->getType(), Name, InsertAtEnd);
1841 }
1842
1843 BinaryOperator *BinaryOperator::CreateNot(Value *Op, const Twine &Name,
1844                                           Instruction *InsertBefore) {
1845   Constant *C;
1846   if (VectorType *PTy = dyn_cast<VectorType>(Op->getType())) {
1847     C = Constant::getAllOnesValue(PTy->getElementType());
1848     C = ConstantVector::get(
1849                               std::vector<Constant*>(PTy->getNumElements(), C));
1850   } else {
1851     C = Constant::getAllOnesValue(Op->getType());
1852   }
1853   
1854   return new BinaryOperator(Instruction::Xor, Op, C,
1855                             Op->getType(), Name, InsertBefore);
1856 }
1857
1858 BinaryOperator *BinaryOperator::CreateNot(Value *Op, const Twine &Name,
1859                                           BasicBlock *InsertAtEnd) {
1860   Constant *AllOnes;
1861   if (VectorType *PTy = dyn_cast<VectorType>(Op->getType())) {
1862     // Create a vector of all ones values.
1863     Constant *Elt = Constant::getAllOnesValue(PTy->getElementType());
1864     AllOnes = ConstantVector::get(
1865                             std::vector<Constant*>(PTy->getNumElements(), Elt));
1866   } else {
1867     AllOnes = Constant::getAllOnesValue(Op->getType());
1868   }
1869   
1870   return new BinaryOperator(Instruction::Xor, Op, AllOnes,
1871                             Op->getType(), Name, InsertAtEnd);
1872 }
1873
1874
1875 // isConstantAllOnes - Helper function for several functions below
1876 static inline bool isConstantAllOnes(const Value *V) {
1877   if (const ConstantInt *CI = dyn_cast<ConstantInt>(V))
1878     return CI->isAllOnesValue();
1879   if (const ConstantVector *CV = dyn_cast<ConstantVector>(V))
1880     return CV->isAllOnesValue();
1881   return false;
1882 }
1883
1884 bool BinaryOperator::isNeg(const Value *V) {
1885   if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1886     if (Bop->getOpcode() == Instruction::Sub)
1887       if (Constant* C = dyn_cast<Constant>(Bop->getOperand(0)))
1888         return C->isNegativeZeroValue();
1889   return false;
1890 }
1891
1892 bool BinaryOperator::isFNeg(const Value *V) {
1893   if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1894     if (Bop->getOpcode() == Instruction::FSub)
1895       if (Constant* C = dyn_cast<Constant>(Bop->getOperand(0)))
1896         return C->isNegativeZeroValue();
1897   return false;
1898 }
1899
1900 bool BinaryOperator::isNot(const Value *V) {
1901   if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1902     return (Bop->getOpcode() == Instruction::Xor &&
1903             (isConstantAllOnes(Bop->getOperand(1)) ||
1904              isConstantAllOnes(Bop->getOperand(0))));
1905   return false;
1906 }
1907
1908 Value *BinaryOperator::getNegArgument(Value *BinOp) {
1909   return cast<BinaryOperator>(BinOp)->getOperand(1);
1910 }
1911
1912 const Value *BinaryOperator::getNegArgument(const Value *BinOp) {
1913   return getNegArgument(const_cast<Value*>(BinOp));
1914 }
1915
1916 Value *BinaryOperator::getFNegArgument(Value *BinOp) {
1917   return cast<BinaryOperator>(BinOp)->getOperand(1);
1918 }
1919
1920 const Value *BinaryOperator::getFNegArgument(const Value *BinOp) {
1921   return getFNegArgument(const_cast<Value*>(BinOp));
1922 }
1923
1924 Value *BinaryOperator::getNotArgument(Value *BinOp) {
1925   assert(isNot(BinOp) && "getNotArgument on non-'not' instruction!");
1926   BinaryOperator *BO = cast<BinaryOperator>(BinOp);
1927   Value *Op0 = BO->getOperand(0);
1928   Value *Op1 = BO->getOperand(1);
1929   if (isConstantAllOnes(Op0)) return Op1;
1930
1931   assert(isConstantAllOnes(Op1));
1932   return Op0;
1933 }
1934
1935 const Value *BinaryOperator::getNotArgument(const Value *BinOp) {
1936   return getNotArgument(const_cast<Value*>(BinOp));
1937 }
1938
1939
1940 // swapOperands - Exchange the two operands to this instruction.  This
1941 // instruction is safe to use on any binary instruction and does not
1942 // modify the semantics of the instruction.  If the instruction is
1943 // order dependent (SetLT f.e.) the opcode is changed.
1944 //
1945 bool BinaryOperator::swapOperands() {
1946   if (!isCommutative())
1947     return true; // Can't commute operands
1948   Op<0>().swap(Op<1>());
1949   return false;
1950 }
1951
1952 void BinaryOperator::setHasNoUnsignedWrap(bool b) {
1953   cast<OverflowingBinaryOperator>(this)->setHasNoUnsignedWrap(b);
1954 }
1955
1956 void BinaryOperator::setHasNoSignedWrap(bool b) {
1957   cast<OverflowingBinaryOperator>(this)->setHasNoSignedWrap(b);
1958 }
1959
1960 void BinaryOperator::setIsExact(bool b) {
1961   cast<PossiblyExactOperator>(this)->setIsExact(b);
1962 }
1963
1964 bool BinaryOperator::hasNoUnsignedWrap() const {
1965   return cast<OverflowingBinaryOperator>(this)->hasNoUnsignedWrap();
1966 }
1967
1968 bool BinaryOperator::hasNoSignedWrap() const {
1969   return cast<OverflowingBinaryOperator>(this)->hasNoSignedWrap();
1970 }
1971
1972 bool BinaryOperator::isExact() const {
1973   return cast<PossiblyExactOperator>(this)->isExact();
1974 }
1975
1976 //===----------------------------------------------------------------------===//
1977 //                                CastInst Class
1978 //===----------------------------------------------------------------------===//
1979
1980 // Just determine if this cast only deals with integral->integral conversion.
1981 bool CastInst::isIntegerCast() const {
1982   switch (getOpcode()) {
1983     default: return false;
1984     case Instruction::ZExt:
1985     case Instruction::SExt:
1986     case Instruction::Trunc:
1987       return true;
1988     case Instruction::BitCast:
1989       return getOperand(0)->getType()->isIntegerTy() &&
1990         getType()->isIntegerTy();
1991   }
1992 }
1993
1994 bool CastInst::isLosslessCast() const {
1995   // Only BitCast can be lossless, exit fast if we're not BitCast
1996   if (getOpcode() != Instruction::BitCast)
1997     return false;
1998
1999   // Identity cast is always lossless
2000   Type* SrcTy = getOperand(0)->getType();
2001   Type* DstTy = getType();
2002   if (SrcTy == DstTy)
2003     return true;
2004   
2005   // Pointer to pointer is always lossless.
2006   if (SrcTy->isPointerTy())
2007     return DstTy->isPointerTy();
2008   return false;  // Other types have no identity values
2009 }
2010
2011 /// This function determines if the CastInst does not require any bits to be
2012 /// changed in order to effect the cast. Essentially, it identifies cases where
2013 /// no code gen is necessary for the cast, hence the name no-op cast.  For 
2014 /// example, the following are all no-op casts:
2015 /// # bitcast i32* %x to i8*
2016 /// # bitcast <2 x i32> %x to <4 x i16> 
2017 /// # ptrtoint i32* %x to i32     ; on 32-bit plaforms only
2018 /// @brief Determine if the described cast is a no-op.
2019 bool CastInst::isNoopCast(Instruction::CastOps Opcode,
2020                           Type *SrcTy,
2021                           Type *DestTy,
2022                           Type *IntPtrTy) {
2023   switch (Opcode) {
2024     default:
2025       assert(0 && "Invalid CastOp");
2026     case Instruction::Trunc:
2027     case Instruction::ZExt:
2028     case Instruction::SExt: 
2029     case Instruction::FPTrunc:
2030     case Instruction::FPExt:
2031     case Instruction::UIToFP:
2032     case Instruction::SIToFP:
2033     case Instruction::FPToUI:
2034     case Instruction::FPToSI:
2035       return false; // These always modify bits
2036     case Instruction::BitCast:
2037       return true;  // BitCast never modifies bits.
2038     case Instruction::PtrToInt:
2039       return IntPtrTy->getScalarSizeInBits() ==
2040              DestTy->getScalarSizeInBits();
2041     case Instruction::IntToPtr:
2042       return IntPtrTy->getScalarSizeInBits() ==
2043              SrcTy->getScalarSizeInBits();
2044   }
2045 }
2046
2047 /// @brief Determine if a cast is a no-op.
2048 bool CastInst::isNoopCast(Type *IntPtrTy) const {
2049   return isNoopCast(getOpcode(), getOperand(0)->getType(), getType(), IntPtrTy);
2050 }
2051
2052 /// This function determines if a pair of casts can be eliminated and what 
2053 /// opcode should be used in the elimination. This assumes that there are two 
2054 /// instructions like this:
2055 /// *  %F = firstOpcode SrcTy %x to MidTy
2056 /// *  %S = secondOpcode MidTy %F to DstTy
2057 /// The function returns a resultOpcode so these two casts can be replaced with:
2058 /// *  %Replacement = resultOpcode %SrcTy %x to DstTy
2059 /// If no such cast is permited, the function returns 0.
2060 unsigned CastInst::isEliminableCastPair(
2061   Instruction::CastOps firstOp, Instruction::CastOps secondOp,
2062   Type *SrcTy, Type *MidTy, Type *DstTy, Type *IntPtrTy) {
2063   // Define the 144 possibilities for these two cast instructions. The values
2064   // in this matrix determine what to do in a given situation and select the
2065   // case in the switch below.  The rows correspond to firstOp, the columns 
2066   // correspond to secondOp.  In looking at the table below, keep in  mind
2067   // the following cast properties:
2068   //
2069   //          Size Compare       Source               Destination
2070   // Operator  Src ? Size   Type       Sign         Type       Sign
2071   // -------- ------------ -------------------   ---------------------
2072   // TRUNC         >       Integer      Any        Integral     Any
2073   // ZEXT          <       Integral   Unsigned     Integer      Any
2074   // SEXT          <       Integral    Signed      Integer      Any
2075   // FPTOUI       n/a      FloatPt      n/a        Integral   Unsigned
2076   // FPTOSI       n/a      FloatPt      n/a        Integral    Signed 
2077   // UITOFP       n/a      Integral   Unsigned     FloatPt      n/a   
2078   // SITOFP       n/a      Integral    Signed      FloatPt      n/a   
2079   // FPTRUNC       >       FloatPt      n/a        FloatPt      n/a   
2080   // FPEXT         <       FloatPt      n/a        FloatPt      n/a   
2081   // PTRTOINT     n/a      Pointer      n/a        Integral   Unsigned
2082   // INTTOPTR     n/a      Integral   Unsigned     Pointer      n/a
2083   // BITCAST       =       FirstClass   n/a       FirstClass    n/a   
2084   //
2085   // NOTE: some transforms are safe, but we consider them to be non-profitable.
2086   // For example, we could merge "fptoui double to i32" + "zext i32 to i64",
2087   // into "fptoui double to i64", but this loses information about the range
2088   // of the produced value (we no longer know the top-part is all zeros). 
2089   // Further this conversion is often much more expensive for typical hardware,
2090   // and causes issues when building libgcc.  We disallow fptosi+sext for the 
2091   // same reason.
2092   const unsigned numCastOps = 
2093     Instruction::CastOpsEnd - Instruction::CastOpsBegin;
2094   static const uint8_t CastResults[numCastOps][numCastOps] = {
2095     // T        F  F  U  S  F  F  P  I  B   -+
2096     // R  Z  S  P  P  I  I  T  P  2  N  T    |
2097     // U  E  E  2  2  2  2  R  E  I  T  C    +- secondOp
2098     // N  X  X  U  S  F  F  N  X  N  2  V    |
2099     // C  T  T  I  I  P  P  C  T  T  P  T   -+
2100     {  1, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // Trunc      -+
2101     {  8, 1, 9,99,99, 2, 0,99,99,99, 2, 3 }, // ZExt        |
2102     {  8, 0, 1,99,99, 0, 2,99,99,99, 0, 3 }, // SExt        |
2103     {  0, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // FPToUI      |
2104     {  0, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // FPToSI      |
2105     { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4 }, // UIToFP      +- firstOp
2106     { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4 }, // SIToFP      |
2107     { 99,99,99, 0, 0,99,99, 1, 0,99,99, 4 }, // FPTrunc     |
2108     { 99,99,99, 2, 2,99,99,10, 2,99,99, 4 }, // FPExt       |
2109     {  1, 0, 0,99,99, 0, 0,99,99,99, 7, 3 }, // PtrToInt    |
2110     { 99,99,99,99,99,99,99,99,99,13,99,12 }, // IntToPtr    |
2111     {  5, 5, 5, 6, 6, 5, 5, 6, 6,11, 5, 1 }, // BitCast    -+
2112   };
2113   
2114   // If either of the casts are a bitcast from scalar to vector, disallow the
2115   // merging. However, bitcast of A->B->A are allowed.
2116   bool isFirstBitcast  = (firstOp == Instruction::BitCast);
2117   bool isSecondBitcast = (secondOp == Instruction::BitCast);
2118   bool chainedBitcast  = (SrcTy == DstTy && isFirstBitcast && isSecondBitcast);
2119
2120   // Check if any of the bitcasts convert scalars<->vectors.
2121   if ((isFirstBitcast  && isa<VectorType>(SrcTy) != isa<VectorType>(MidTy)) ||
2122       (isSecondBitcast && isa<VectorType>(MidTy) != isa<VectorType>(DstTy)))
2123     // Unless we are bitcasing to the original type, disallow optimizations.
2124     if (!chainedBitcast) return 0;
2125
2126   int ElimCase = CastResults[firstOp-Instruction::CastOpsBegin]
2127                             [secondOp-Instruction::CastOpsBegin];
2128   switch (ElimCase) {
2129     case 0: 
2130       // categorically disallowed
2131       return 0;
2132     case 1: 
2133       // allowed, use first cast's opcode
2134       return firstOp;
2135     case 2: 
2136       // allowed, use second cast's opcode
2137       return secondOp;
2138     case 3: 
2139       // no-op cast in second op implies firstOp as long as the DestTy 
2140       // is integer and we are not converting between a vector and a
2141       // non vector type.
2142       if (!SrcTy->isVectorTy() && DstTy->isIntegerTy())
2143         return firstOp;
2144       return 0;
2145     case 4:
2146       // no-op cast in second op implies firstOp as long as the DestTy
2147       // is floating point.
2148       if (DstTy->isFloatingPointTy())
2149         return firstOp;
2150       return 0;
2151     case 5: 
2152       // no-op cast in first op implies secondOp as long as the SrcTy
2153       // is an integer.
2154       if (SrcTy->isIntegerTy())
2155         return secondOp;
2156       return 0;
2157     case 6:
2158       // no-op cast in first op implies secondOp as long as the SrcTy
2159       // is a floating point.
2160       if (SrcTy->isFloatingPointTy())
2161         return secondOp;
2162       return 0;
2163     case 7: { 
2164       // ptrtoint, inttoptr -> bitcast (ptr -> ptr) if int size is >= ptr size
2165       if (!IntPtrTy)
2166         return 0;
2167       unsigned PtrSize = IntPtrTy->getScalarSizeInBits();
2168       unsigned MidSize = MidTy->getScalarSizeInBits();
2169       if (MidSize >= PtrSize)
2170         return Instruction::BitCast;
2171       return 0;
2172     }
2173     case 8: {
2174       // ext, trunc -> bitcast,    if the SrcTy and DstTy are same size
2175       // ext, trunc -> ext,        if sizeof(SrcTy) < sizeof(DstTy)
2176       // ext, trunc -> trunc,      if sizeof(SrcTy) > sizeof(DstTy)
2177       unsigned SrcSize = SrcTy->getScalarSizeInBits();
2178       unsigned DstSize = DstTy->getScalarSizeInBits();
2179       if (SrcSize == DstSize)
2180         return Instruction::BitCast;
2181       else if (SrcSize < DstSize)
2182         return firstOp;
2183       return secondOp;
2184     }
2185     case 9: // zext, sext -> zext, because sext can't sign extend after zext
2186       return Instruction::ZExt;
2187     case 10:
2188       // fpext followed by ftrunc is allowed if the bit size returned to is
2189       // the same as the original, in which case its just a bitcast
2190       if (SrcTy == DstTy)
2191         return Instruction::BitCast;
2192       return 0; // If the types are not the same we can't eliminate it.
2193     case 11:
2194       // bitcast followed by ptrtoint is allowed as long as the bitcast
2195       // is a pointer to pointer cast.
2196       if (SrcTy->isPointerTy() && MidTy->isPointerTy())
2197         return secondOp;
2198       return 0;
2199     case 12:
2200       // inttoptr, bitcast -> intptr  if bitcast is a ptr to ptr cast
2201       if (MidTy->isPointerTy() && DstTy->isPointerTy())
2202         return firstOp;
2203       return 0;
2204     case 13: {
2205       // inttoptr, ptrtoint -> bitcast if SrcSize<=PtrSize and SrcSize==DstSize
2206       if (!IntPtrTy)
2207         return 0;
2208       unsigned PtrSize = IntPtrTy->getScalarSizeInBits();
2209       unsigned SrcSize = SrcTy->getScalarSizeInBits();
2210       unsigned DstSize = DstTy->getScalarSizeInBits();
2211       if (SrcSize <= PtrSize && SrcSize == DstSize)
2212         return Instruction::BitCast;
2213       return 0;
2214     }
2215     case 99: 
2216       // cast combination can't happen (error in input). This is for all cases
2217       // where the MidTy is not the same for the two cast instructions.
2218       assert(0 && "Invalid Cast Combination");
2219       return 0;
2220     default:
2221       assert(0 && "Error in CastResults table!!!");
2222       return 0;
2223   }
2224   return 0;
2225 }
2226
2227 CastInst *CastInst::Create(Instruction::CastOps op, Value *S, Type *Ty, 
2228   const Twine &Name, Instruction *InsertBefore) {
2229   assert(castIsValid(op, S, Ty) && "Invalid cast!");
2230   // Construct and return the appropriate CastInst subclass
2231   switch (op) {
2232     case Trunc:    return new TruncInst    (S, Ty, Name, InsertBefore);
2233     case ZExt:     return new ZExtInst     (S, Ty, Name, InsertBefore);
2234     case SExt:     return new SExtInst     (S, Ty, Name, InsertBefore);
2235     case FPTrunc:  return new FPTruncInst  (S, Ty, Name, InsertBefore);
2236     case FPExt:    return new FPExtInst    (S, Ty, Name, InsertBefore);
2237     case UIToFP:   return new UIToFPInst   (S, Ty, Name, InsertBefore);
2238     case SIToFP:   return new SIToFPInst   (S, Ty, Name, InsertBefore);
2239     case FPToUI:   return new FPToUIInst   (S, Ty, Name, InsertBefore);
2240     case FPToSI:   return new FPToSIInst   (S, Ty, Name, InsertBefore);
2241     case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertBefore);
2242     case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertBefore);
2243     case BitCast:  return new BitCastInst  (S, Ty, Name, InsertBefore);
2244     default:
2245       assert(0 && "Invalid opcode provided");
2246   }
2247   return 0;
2248 }
2249
2250 CastInst *CastInst::Create(Instruction::CastOps op, Value *S, Type *Ty,
2251   const Twine &Name, BasicBlock *InsertAtEnd) {
2252   assert(castIsValid(op, S, Ty) && "Invalid cast!");
2253   // Construct and return the appropriate CastInst subclass
2254   switch (op) {
2255     case Trunc:    return new TruncInst    (S, Ty, Name, InsertAtEnd);
2256     case ZExt:     return new ZExtInst     (S, Ty, Name, InsertAtEnd);
2257     case SExt:     return new SExtInst     (S, Ty, Name, InsertAtEnd);
2258     case FPTrunc:  return new FPTruncInst  (S, Ty, Name, InsertAtEnd);
2259     case FPExt:    return new FPExtInst    (S, Ty, Name, InsertAtEnd);
2260     case UIToFP:   return new UIToFPInst   (S, Ty, Name, InsertAtEnd);
2261     case SIToFP:   return new SIToFPInst   (S, Ty, Name, InsertAtEnd);
2262     case FPToUI:   return new FPToUIInst   (S, Ty, Name, InsertAtEnd);
2263     case FPToSI:   return new FPToSIInst   (S, Ty, Name, InsertAtEnd);
2264     case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertAtEnd);
2265     case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertAtEnd);
2266     case BitCast:  return new BitCastInst  (S, Ty, Name, InsertAtEnd);
2267     default:
2268       assert(0 && "Invalid opcode provided");
2269   }
2270   return 0;
2271 }
2272
2273 CastInst *CastInst::CreateZExtOrBitCast(Value *S, Type *Ty, 
2274                                         const Twine &Name,
2275                                         Instruction *InsertBefore) {
2276   if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2277     return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2278   return Create(Instruction::ZExt, S, Ty, Name, InsertBefore);
2279 }
2280
2281 CastInst *CastInst::CreateZExtOrBitCast(Value *S, Type *Ty, 
2282                                         const Twine &Name,
2283                                         BasicBlock *InsertAtEnd) {
2284   if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2285     return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2286   return Create(Instruction::ZExt, S, Ty, Name, InsertAtEnd);
2287 }
2288
2289 CastInst *CastInst::CreateSExtOrBitCast(Value *S, Type *Ty, 
2290                                         const Twine &Name,
2291                                         Instruction *InsertBefore) {
2292   if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2293     return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2294   return Create(Instruction::SExt, S, Ty, Name, InsertBefore);
2295 }
2296
2297 CastInst *CastInst::CreateSExtOrBitCast(Value *S, Type *Ty, 
2298                                         const Twine &Name,
2299                                         BasicBlock *InsertAtEnd) {
2300   if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2301     return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2302   return Create(Instruction::SExt, S, Ty, Name, InsertAtEnd);
2303 }
2304
2305 CastInst *CastInst::CreateTruncOrBitCast(Value *S, Type *Ty,
2306                                          const Twine &Name,
2307                                          Instruction *InsertBefore) {
2308   if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2309     return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2310   return Create(Instruction::Trunc, S, Ty, Name, InsertBefore);
2311 }
2312
2313 CastInst *CastInst::CreateTruncOrBitCast(Value *S, Type *Ty,
2314                                          const Twine &Name, 
2315                                          BasicBlock *InsertAtEnd) {
2316   if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2317     return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2318   return Create(Instruction::Trunc, S, Ty, Name, InsertAtEnd);
2319 }
2320
2321 CastInst *CastInst::CreatePointerCast(Value *S, Type *Ty,
2322                                       const Twine &Name,
2323                                       BasicBlock *InsertAtEnd) {
2324   assert(S->getType()->isPointerTy() && "Invalid cast");
2325   assert((Ty->isIntegerTy() || Ty->isPointerTy()) &&
2326          "Invalid cast");
2327
2328   if (Ty->isIntegerTy())
2329     return Create(Instruction::PtrToInt, S, Ty, Name, InsertAtEnd);
2330   return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2331 }
2332
2333 /// @brief Create a BitCast or a PtrToInt cast instruction
2334 CastInst *CastInst::CreatePointerCast(Value *S, Type *Ty, 
2335                                       const Twine &Name, 
2336                                       Instruction *InsertBefore) {
2337   assert(S->getType()->isPointerTy() && "Invalid cast");
2338   assert((Ty->isIntegerTy() || Ty->isPointerTy()) &&
2339          "Invalid cast");
2340
2341   if (Ty->isIntegerTy())
2342     return Create(Instruction::PtrToInt, S, Ty, Name, InsertBefore);
2343   return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2344 }
2345
2346 CastInst *CastInst::CreateIntegerCast(Value *C, Type *Ty, 
2347                                       bool isSigned, const Twine &Name,
2348                                       Instruction *InsertBefore) {
2349   assert(C->getType()->isIntOrIntVectorTy() && Ty->isIntOrIntVectorTy() &&
2350          "Invalid integer cast");
2351   unsigned SrcBits = C->getType()->getScalarSizeInBits();
2352   unsigned DstBits = Ty->getScalarSizeInBits();
2353   Instruction::CastOps opcode =
2354     (SrcBits == DstBits ? Instruction::BitCast :
2355      (SrcBits > DstBits ? Instruction::Trunc :
2356       (isSigned ? Instruction::SExt : Instruction::ZExt)));
2357   return Create(opcode, C, Ty, Name, InsertBefore);
2358 }
2359
2360 CastInst *CastInst::CreateIntegerCast(Value *C, Type *Ty, 
2361                                       bool isSigned, const Twine &Name,
2362                                       BasicBlock *InsertAtEnd) {
2363   assert(C->getType()->isIntOrIntVectorTy() && Ty->isIntOrIntVectorTy() &&
2364          "Invalid cast");
2365   unsigned SrcBits = C->getType()->getScalarSizeInBits();
2366   unsigned DstBits = Ty->getScalarSizeInBits();
2367   Instruction::CastOps opcode =
2368     (SrcBits == DstBits ? Instruction::BitCast :
2369      (SrcBits > DstBits ? Instruction::Trunc :
2370       (isSigned ? Instruction::SExt : Instruction::ZExt)));
2371   return Create(opcode, C, Ty, Name, InsertAtEnd);
2372 }
2373
2374 CastInst *CastInst::CreateFPCast(Value *C, Type *Ty, 
2375                                  const Twine &Name, 
2376                                  Instruction *InsertBefore) {
2377   assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
2378          "Invalid cast");
2379   unsigned SrcBits = C->getType()->getScalarSizeInBits();
2380   unsigned DstBits = Ty->getScalarSizeInBits();
2381   Instruction::CastOps opcode =
2382     (SrcBits == DstBits ? Instruction::BitCast :
2383      (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
2384   return Create(opcode, C, Ty, Name, InsertBefore);
2385 }
2386
2387 CastInst *CastInst::CreateFPCast(Value *C, Type *Ty, 
2388                                  const Twine &Name, 
2389                                  BasicBlock *InsertAtEnd) {
2390   assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
2391          "Invalid cast");
2392   unsigned SrcBits = C->getType()->getScalarSizeInBits();
2393   unsigned DstBits = Ty->getScalarSizeInBits();
2394   Instruction::CastOps opcode =
2395     (SrcBits == DstBits ? Instruction::BitCast :
2396      (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
2397   return Create(opcode, C, Ty, Name, InsertAtEnd);
2398 }
2399
2400 // Check whether it is valid to call getCastOpcode for these types.
2401 // This routine must be kept in sync with getCastOpcode.
2402 bool CastInst::isCastable(Type *SrcTy, Type *DestTy) {
2403   if (!SrcTy->isFirstClassType() || !DestTy->isFirstClassType())
2404     return false;
2405
2406   if (SrcTy == DestTy)
2407     return true;
2408
2409   if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy))
2410     if (VectorType *DestVecTy = dyn_cast<VectorType>(DestTy))
2411       if (SrcVecTy->getNumElements() == DestVecTy->getNumElements()) {
2412         // An element by element cast.  Valid if casting the elements is valid.
2413         SrcTy = SrcVecTy->getElementType();
2414         DestTy = DestVecTy->getElementType();
2415       }
2416
2417   // Get the bit sizes, we'll need these
2418   unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();   // 0 for ptr
2419   unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr
2420
2421   // Run through the possibilities ...
2422   if (DestTy->isIntegerTy()) {               // Casting to integral
2423     if (SrcTy->isIntegerTy()) {                // Casting from integral
2424         return true;
2425     } else if (SrcTy->isFloatingPointTy()) {   // Casting from floating pt
2426       return true;
2427     } else if (SrcTy->isVectorTy()) {          // Casting from vector
2428       return DestBits == SrcBits;
2429     } else {                                   // Casting from something else
2430       return SrcTy->isPointerTy();
2431     }
2432   } else if (DestTy->isFloatingPointTy()) {  // Casting to floating pt
2433     if (SrcTy->isIntegerTy()) {                // Casting from integral
2434       return true;
2435     } else if (SrcTy->isFloatingPointTy()) {   // Casting from floating pt
2436       return true;
2437     } else if (SrcTy->isVectorTy()) {          // Casting from vector
2438       return DestBits == SrcBits;
2439     } else {                                   // Casting from something else
2440       return false;
2441     }
2442   } else if (DestTy->isVectorTy()) {         // Casting to vector
2443     return DestBits == SrcBits;
2444   } else if (DestTy->isPointerTy()) {        // Casting to pointer
2445     if (SrcTy->isPointerTy()) {                // Casting from pointer
2446       return true;
2447     } else if (SrcTy->isIntegerTy()) {         // Casting from integral
2448       return true;
2449     } else {                                   // Casting from something else
2450       return false;
2451     }
2452   } else if (DestTy->isX86_MMXTy()) {
2453     if (SrcTy->isVectorTy()) {
2454       return DestBits == SrcBits;       // 64-bit vector to MMX
2455     } else {
2456       return false;
2457     }
2458   } else {                                   // Casting to something else
2459     return false;
2460   }
2461 }
2462
2463 // Provide a way to get a "cast" where the cast opcode is inferred from the 
2464 // types and size of the operand. This, basically, is a parallel of the 
2465 // logic in the castIsValid function below.  This axiom should hold:
2466 //   castIsValid( getCastOpcode(Val, Ty), Val, Ty)
2467 // should not assert in castIsValid. In other words, this produces a "correct"
2468 // casting opcode for the arguments passed to it.
2469 // This routine must be kept in sync with isCastable.
2470 Instruction::CastOps
2471 CastInst::getCastOpcode(
2472   const Value *Src, bool SrcIsSigned, Type *DestTy, bool DestIsSigned) {
2473   Type *SrcTy = Src->getType();
2474
2475   assert(SrcTy->isFirstClassType() && DestTy->isFirstClassType() &&
2476          "Only first class types are castable!");
2477
2478   if (SrcTy == DestTy)
2479     return BitCast;
2480
2481   if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy))
2482     if (VectorType *DestVecTy = dyn_cast<VectorType>(DestTy))
2483       if (SrcVecTy->getNumElements() == DestVecTy->getNumElements()) {
2484         // An element by element cast.  Find the appropriate opcode based on the
2485         // element types.
2486         SrcTy = SrcVecTy->getElementType();
2487         DestTy = DestVecTy->getElementType();
2488       }
2489
2490   // Get the bit sizes, we'll need these
2491   unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();   // 0 for ptr
2492   unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr
2493
2494   // Run through the possibilities ...
2495   if (DestTy->isIntegerTy()) {                      // Casting to integral
2496     if (SrcTy->isIntegerTy()) {                     // Casting from integral
2497       if (DestBits < SrcBits)
2498         return Trunc;                               // int -> smaller int
2499       else if (DestBits > SrcBits) {                // its an extension
2500         if (SrcIsSigned)
2501           return SExt;                              // signed -> SEXT
2502         else
2503           return ZExt;                              // unsigned -> ZEXT
2504       } else {
2505         return BitCast;                             // Same size, No-op cast
2506       }
2507     } else if (SrcTy->isFloatingPointTy()) {        // Casting from floating pt
2508       if (DestIsSigned) 
2509         return FPToSI;                              // FP -> sint
2510       else
2511         return FPToUI;                              // FP -> uint 
2512     } else if (SrcTy->isVectorTy()) {
2513       assert(DestBits == SrcBits &&
2514              "Casting vector to integer of different width");
2515       return BitCast;                             // Same size, no-op cast
2516     } else {
2517       assert(SrcTy->isPointerTy() &&
2518              "Casting from a value that is not first-class type");
2519       return PtrToInt;                              // ptr -> int
2520     }
2521   } else if (DestTy->isFloatingPointTy()) {         // Casting to floating pt
2522     if (SrcTy->isIntegerTy()) {                     // Casting from integral
2523       if (SrcIsSigned)
2524         return SIToFP;                              // sint -> FP
2525       else
2526         return UIToFP;                              // uint -> FP
2527     } else if (SrcTy->isFloatingPointTy()) {        // Casting from floating pt
2528       if (DestBits < SrcBits) {
2529         return FPTrunc;                             // FP -> smaller FP
2530       } else if (DestBits > SrcBits) {
2531         return FPExt;                               // FP -> larger FP
2532       } else  {
2533         return BitCast;                             // same size, no-op cast
2534       }
2535     } else if (SrcTy->isVectorTy()) {
2536       assert(DestBits == SrcBits &&
2537              "Casting vector to floating point of different width");
2538       return BitCast;                             // same size, no-op cast
2539     } else {
2540       llvm_unreachable("Casting pointer or non-first class to float");
2541     }
2542   } else if (DestTy->isVectorTy()) {
2543     assert(DestBits == SrcBits &&
2544            "Illegal cast to vector (wrong type or size)");
2545     return BitCast;
2546   } else if (DestTy->isPointerTy()) {
2547     if (SrcTy->isPointerTy()) {
2548       return BitCast;                               // ptr -> ptr
2549     } else if (SrcTy->isIntegerTy()) {
2550       return IntToPtr;                              // int -> ptr
2551     } else {
2552       assert(0 && "Casting pointer to other than pointer or int");
2553     }
2554   } else if (DestTy->isX86_MMXTy()) {
2555     if (SrcTy->isVectorTy()) {
2556       assert(DestBits == SrcBits && "Casting vector of wrong width to X86_MMX");
2557       return BitCast;                               // 64-bit vector to MMX
2558     } else {
2559       assert(0 && "Illegal cast to X86_MMX");
2560     }
2561   } else {
2562     assert(0 && "Casting to type that is not first-class");
2563   }
2564
2565   // If we fall through to here we probably hit an assertion cast above
2566   // and assertions are not turned on. Anything we return is an error, so
2567   // BitCast is as good a choice as any.
2568   return BitCast;
2569 }
2570
2571 //===----------------------------------------------------------------------===//
2572 //                    CastInst SubClass Constructors
2573 //===----------------------------------------------------------------------===//
2574
2575 /// Check that the construction parameters for a CastInst are correct. This
2576 /// could be broken out into the separate constructors but it is useful to have
2577 /// it in one place and to eliminate the redundant code for getting the sizes
2578 /// of the types involved.
2579 bool 
2580 CastInst::castIsValid(Instruction::CastOps op, Value *S, Type *DstTy) {
2581
2582   // Check for type sanity on the arguments
2583   Type *SrcTy = S->getType();
2584   if (!SrcTy->isFirstClassType() || !DstTy->isFirstClassType() ||
2585       SrcTy->isAggregateType() || DstTy->isAggregateType())
2586     return false;
2587
2588   // Get the size of the types in bits, we'll need this later
2589   unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
2590   unsigned DstBitSize = DstTy->getScalarSizeInBits();
2591
2592   // If these are vector types, get the lengths of the vectors (using zero for
2593   // scalar types means that checking that vector lengths match also checks that
2594   // scalars are not being converted to vectors or vectors to scalars).
2595   unsigned SrcLength = SrcTy->isVectorTy() ?
2596     cast<VectorType>(SrcTy)->getNumElements() : 0;
2597   unsigned DstLength = DstTy->isVectorTy() ?
2598     cast<VectorType>(DstTy)->getNumElements() : 0;
2599
2600   // Switch on the opcode provided
2601   switch (op) {
2602   default: return false; // This is an input error
2603   case Instruction::Trunc:
2604     return SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy() &&
2605       SrcLength == DstLength && SrcBitSize > DstBitSize;
2606   case Instruction::ZExt:
2607     return SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy() &&
2608       SrcLength == DstLength && SrcBitSize < DstBitSize;
2609   case Instruction::SExt: 
2610     return SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy() &&
2611       SrcLength == DstLength && SrcBitSize < DstBitSize;
2612   case Instruction::FPTrunc:
2613     return SrcTy->isFPOrFPVectorTy() && DstTy->isFPOrFPVectorTy() &&
2614       SrcLength == DstLength && SrcBitSize > DstBitSize;
2615   case Instruction::FPExt:
2616     return SrcTy->isFPOrFPVectorTy() && DstTy->isFPOrFPVectorTy() &&
2617       SrcLength == DstLength && SrcBitSize < DstBitSize;
2618   case Instruction::UIToFP:
2619   case Instruction::SIToFP:
2620     return SrcTy->isIntOrIntVectorTy() && DstTy->isFPOrFPVectorTy() &&
2621       SrcLength == DstLength;
2622   case Instruction::FPToUI:
2623   case Instruction::FPToSI:
2624     return SrcTy->isFPOrFPVectorTy() && DstTy->isIntOrIntVectorTy() &&
2625       SrcLength == DstLength;
2626   case Instruction::PtrToInt:
2627     return SrcTy->isPointerTy() && DstTy->isIntegerTy();
2628   case Instruction::IntToPtr:
2629     return SrcTy->isIntegerTy() && DstTy->isPointerTy();
2630   case Instruction::BitCast:
2631     // BitCast implies a no-op cast of type only. No bits change.
2632     // However, you can't cast pointers to anything but pointers.
2633     if (SrcTy->isPointerTy() != DstTy->isPointerTy())
2634       return false;
2635
2636     // Now we know we're not dealing with a pointer/non-pointer mismatch. In all
2637     // these cases, the cast is okay if the source and destination bit widths
2638     // are identical.
2639     return SrcTy->getPrimitiveSizeInBits() == DstTy->getPrimitiveSizeInBits();
2640   }
2641 }
2642
2643 TruncInst::TruncInst(
2644   Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2645 ) : CastInst(Ty, Trunc, S, Name, InsertBefore) {
2646   assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
2647 }
2648
2649 TruncInst::TruncInst(
2650   Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2651 ) : CastInst(Ty, Trunc, S, Name, InsertAtEnd) { 
2652   assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
2653 }
2654
2655 ZExtInst::ZExtInst(
2656   Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2657 )  : CastInst(Ty, ZExt, S, Name, InsertBefore) { 
2658   assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
2659 }
2660
2661 ZExtInst::ZExtInst(
2662   Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2663 )  : CastInst(Ty, ZExt, S, Name, InsertAtEnd) { 
2664   assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
2665 }
2666 SExtInst::SExtInst(
2667   Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2668 ) : CastInst(Ty, SExt, S, Name, InsertBefore) { 
2669   assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
2670 }
2671
2672 SExtInst::SExtInst(
2673   Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2674 )  : CastInst(Ty, SExt, S, Name, InsertAtEnd) { 
2675   assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
2676 }
2677
2678 FPTruncInst::FPTruncInst(
2679   Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2680 ) : CastInst(Ty, FPTrunc, S, Name, InsertBefore) { 
2681   assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
2682 }
2683
2684 FPTruncInst::FPTruncInst(
2685   Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2686 ) : CastInst(Ty, FPTrunc, S, Name, InsertAtEnd) { 
2687   assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
2688 }
2689
2690 FPExtInst::FPExtInst(
2691   Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2692 ) : CastInst(Ty, FPExt, S, Name, InsertBefore) { 
2693   assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
2694 }
2695
2696 FPExtInst::FPExtInst(
2697   Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2698 ) : CastInst(Ty, FPExt, S, Name, InsertAtEnd) { 
2699   assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
2700 }
2701
2702 UIToFPInst::UIToFPInst(
2703   Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2704 ) : CastInst(Ty, UIToFP, S, Name, InsertBefore) { 
2705   assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
2706 }
2707
2708 UIToFPInst::UIToFPInst(
2709   Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2710 ) : CastInst(Ty, UIToFP, S, Name, InsertAtEnd) { 
2711   assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
2712 }
2713
2714 SIToFPInst::SIToFPInst(
2715   Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2716 ) : CastInst(Ty, SIToFP, S, Name, InsertBefore) { 
2717   assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
2718 }
2719
2720 SIToFPInst::SIToFPInst(
2721   Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2722 ) : CastInst(Ty, SIToFP, S, Name, InsertAtEnd) { 
2723   assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
2724 }
2725
2726 FPToUIInst::FPToUIInst(
2727   Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2728 ) : CastInst(Ty, FPToUI, S, Name, InsertBefore) { 
2729   assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
2730 }
2731
2732 FPToUIInst::FPToUIInst(
2733   Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2734 ) : CastInst(Ty, FPToUI, S, Name, InsertAtEnd) { 
2735   assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
2736 }
2737
2738 FPToSIInst::FPToSIInst(
2739   Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2740 ) : CastInst(Ty, FPToSI, S, Name, InsertBefore) { 
2741   assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
2742 }
2743
2744 FPToSIInst::FPToSIInst(
2745   Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2746 ) : CastInst(Ty, FPToSI, S, Name, InsertAtEnd) { 
2747   assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
2748 }
2749
2750 PtrToIntInst::PtrToIntInst(
2751   Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2752 ) : CastInst(Ty, PtrToInt, S, Name, InsertBefore) { 
2753   assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
2754 }
2755
2756 PtrToIntInst::PtrToIntInst(
2757   Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2758 ) : CastInst(Ty, PtrToInt, S, Name, InsertAtEnd) { 
2759   assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
2760 }
2761
2762 IntToPtrInst::IntToPtrInst(
2763   Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2764 ) : CastInst(Ty, IntToPtr, S, Name, InsertBefore) { 
2765   assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
2766 }
2767
2768 IntToPtrInst::IntToPtrInst(
2769   Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2770 ) : CastInst(Ty, IntToPtr, S, Name, InsertAtEnd) { 
2771   assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
2772 }
2773
2774 BitCastInst::BitCastInst(
2775   Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2776 ) : CastInst(Ty, BitCast, S, Name, InsertBefore) { 
2777   assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
2778 }
2779
2780 BitCastInst::BitCastInst(
2781   Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2782 ) : CastInst(Ty, BitCast, S, Name, InsertAtEnd) { 
2783   assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
2784 }
2785
2786 //===----------------------------------------------------------------------===//
2787 //                               CmpInst Classes
2788 //===----------------------------------------------------------------------===//
2789
2790 void CmpInst::Anchor() const {}
2791
2792 CmpInst::CmpInst(Type *ty, OtherOps op, unsigned short predicate,
2793                  Value *LHS, Value *RHS, const Twine &Name,
2794                  Instruction *InsertBefore)
2795   : Instruction(ty, op,
2796                 OperandTraits<CmpInst>::op_begin(this),
2797                 OperandTraits<CmpInst>::operands(this),
2798                 InsertBefore) {
2799     Op<0>() = LHS;
2800     Op<1>() = RHS;
2801   setPredicate((Predicate)predicate);
2802   setName(Name);
2803 }
2804
2805 CmpInst::CmpInst(Type *ty, OtherOps op, unsigned short predicate,
2806                  Value *LHS, Value *RHS, const Twine &Name,
2807                  BasicBlock *InsertAtEnd)
2808   : Instruction(ty, op,
2809                 OperandTraits<CmpInst>::op_begin(this),
2810                 OperandTraits<CmpInst>::operands(this),
2811                 InsertAtEnd) {
2812   Op<0>() = LHS;
2813   Op<1>() = RHS;
2814   setPredicate((Predicate)predicate);
2815   setName(Name);
2816 }
2817
2818 CmpInst *
2819 CmpInst::Create(OtherOps Op, unsigned short predicate,
2820                 Value *S1, Value *S2, 
2821                 const Twine &Name, Instruction *InsertBefore) {
2822   if (Op == Instruction::ICmp) {
2823     if (InsertBefore)
2824       return new ICmpInst(InsertBefore, CmpInst::Predicate(predicate),
2825                           S1, S2, Name);
2826     else
2827       return new ICmpInst(CmpInst::Predicate(predicate),
2828                           S1, S2, Name);
2829   }
2830   
2831   if (InsertBefore)
2832     return new FCmpInst(InsertBefore, CmpInst::Predicate(predicate),
2833                         S1, S2, Name);
2834   else
2835     return new FCmpInst(CmpInst::Predicate(predicate),
2836                         S1, S2, Name);
2837 }
2838
2839 CmpInst *
2840 CmpInst::Create(OtherOps Op, unsigned short predicate, Value *S1, Value *S2, 
2841                 const Twine &Name, BasicBlock *InsertAtEnd) {
2842   if (Op == Instruction::ICmp) {
2843     return new ICmpInst(*InsertAtEnd, CmpInst::Predicate(predicate),
2844                         S1, S2, Name);
2845   }
2846   return new FCmpInst(*InsertAtEnd, CmpInst::Predicate(predicate),
2847                       S1, S2, Name);
2848 }
2849
2850 void CmpInst::swapOperands() {
2851   if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2852     IC->swapOperands();
2853   else
2854     cast<FCmpInst>(this)->swapOperands();
2855 }
2856
2857 bool CmpInst::isCommutative() const {
2858   if (const ICmpInst *IC = dyn_cast<ICmpInst>(this))
2859     return IC->isCommutative();
2860   return cast<FCmpInst>(this)->isCommutative();
2861 }
2862
2863 bool CmpInst::isEquality() const {
2864   if (const ICmpInst *IC = dyn_cast<ICmpInst>(this))
2865     return IC->isEquality();
2866   return cast<FCmpInst>(this)->isEquality();
2867 }
2868
2869
2870 CmpInst::Predicate CmpInst::getInversePredicate(Predicate pred) {
2871   switch (pred) {
2872     default: assert(0 && "Unknown cmp predicate!");
2873     case ICMP_EQ: return ICMP_NE;
2874     case ICMP_NE: return ICMP_EQ;
2875     case ICMP_UGT: return ICMP_ULE;
2876     case ICMP_ULT: return ICMP_UGE;
2877     case ICMP_UGE: return ICMP_ULT;
2878     case ICMP_ULE: return ICMP_UGT;
2879     case ICMP_SGT: return ICMP_SLE;
2880     case ICMP_SLT: return ICMP_SGE;
2881     case ICMP_SGE: return ICMP_SLT;
2882     case ICMP_SLE: return ICMP_SGT;
2883
2884     case FCMP_OEQ: return FCMP_UNE;
2885     case FCMP_ONE: return FCMP_UEQ;
2886     case FCMP_OGT: return FCMP_ULE;
2887     case FCMP_OLT: return FCMP_UGE;
2888     case FCMP_OGE: return FCMP_ULT;
2889     case FCMP_OLE: return FCMP_UGT;
2890     case FCMP_UEQ: return FCMP_ONE;
2891     case FCMP_UNE: return FCMP_OEQ;
2892     case FCMP_UGT: return FCMP_OLE;
2893     case FCMP_ULT: return FCMP_OGE;
2894     case FCMP_UGE: return FCMP_OLT;
2895     case FCMP_ULE: return FCMP_OGT;
2896     case FCMP_ORD: return FCMP_UNO;
2897     case FCMP_UNO: return FCMP_ORD;
2898     case FCMP_TRUE: return FCMP_FALSE;
2899     case FCMP_FALSE: return FCMP_TRUE;
2900   }
2901 }
2902
2903 ICmpInst::Predicate ICmpInst::getSignedPredicate(Predicate pred) {
2904   switch (pred) {
2905     default: assert(0 && "Unknown icmp predicate!");
2906     case ICMP_EQ: case ICMP_NE: 
2907     case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE: 
2908        return pred;
2909     case ICMP_UGT: return ICMP_SGT;
2910     case ICMP_ULT: return ICMP_SLT;
2911     case ICMP_UGE: return ICMP_SGE;
2912     case ICMP_ULE: return ICMP_SLE;
2913   }
2914 }
2915
2916 ICmpInst::Predicate ICmpInst::getUnsignedPredicate(Predicate pred) {
2917   switch (pred) {
2918     default: assert(0 && "Unknown icmp predicate!");
2919     case ICMP_EQ: case ICMP_NE: 
2920     case ICMP_UGT: case ICMP_ULT: case ICMP_UGE: case ICMP_ULE: 
2921        return pred;
2922     case ICMP_SGT: return ICMP_UGT;
2923     case ICMP_SLT: return ICMP_ULT;
2924     case ICMP_SGE: return ICMP_UGE;
2925     case ICMP_SLE: return ICMP_ULE;
2926   }
2927 }
2928
2929 /// Initialize a set of values that all satisfy the condition with C.
2930 ///
2931 ConstantRange 
2932 ICmpInst::makeConstantRange(Predicate pred, const APInt &C) {
2933   APInt Lower(C);
2934   APInt Upper(C);
2935   uint32_t BitWidth = C.getBitWidth();
2936   switch (pred) {
2937   default: llvm_unreachable("Invalid ICmp opcode to ConstantRange ctor!");
2938   case ICmpInst::ICMP_EQ: Upper++; break;
2939   case ICmpInst::ICMP_NE: Lower++; break;
2940   case ICmpInst::ICMP_ULT:
2941     Lower = APInt::getMinValue(BitWidth);
2942     // Check for an empty-set condition.
2943     if (Lower == Upper)
2944       return ConstantRange(BitWidth, /*isFullSet=*/false);
2945     break;
2946   case ICmpInst::ICMP_SLT:
2947     Lower = APInt::getSignedMinValue(BitWidth);
2948     // Check for an empty-set condition.
2949     if (Lower == Upper)
2950       return ConstantRange(BitWidth, /*isFullSet=*/false);
2951     break;
2952   case ICmpInst::ICMP_UGT: 
2953     Lower++; Upper = APInt::getMinValue(BitWidth);        // Min = Next(Max)
2954     // Check for an empty-set condition.
2955     if (Lower == Upper)
2956       return ConstantRange(BitWidth, /*isFullSet=*/false);
2957     break;
2958   case ICmpInst::ICMP_SGT:
2959     Lower++; Upper = APInt::getSignedMinValue(BitWidth);  // Min = Next(Max)
2960     // Check for an empty-set condition.
2961     if (Lower == Upper)
2962       return ConstantRange(BitWidth, /*isFullSet=*/false);
2963     break;
2964   case ICmpInst::ICMP_ULE: 
2965     Lower = APInt::getMinValue(BitWidth); Upper++; 
2966     // Check for a full-set condition.
2967     if (Lower == Upper)
2968       return ConstantRange(BitWidth, /*isFullSet=*/true);
2969     break;
2970   case ICmpInst::ICMP_SLE: 
2971     Lower = APInt::getSignedMinValue(BitWidth); Upper++; 
2972     // Check for a full-set condition.
2973     if (Lower == Upper)
2974       return ConstantRange(BitWidth, /*isFullSet=*/true);
2975     break;
2976   case ICmpInst::ICMP_UGE:
2977     Upper = APInt::getMinValue(BitWidth);        // Min = Next(Max)
2978     // Check for a full-set condition.
2979     if (Lower == Upper)
2980       return ConstantRange(BitWidth, /*isFullSet=*/true);
2981     break;
2982   case ICmpInst::ICMP_SGE:
2983     Upper = APInt::getSignedMinValue(BitWidth);  // Min = Next(Max)
2984     // Check for a full-set condition.
2985     if (Lower == Upper)
2986       return ConstantRange(BitWidth, /*isFullSet=*/true);
2987     break;
2988   }
2989   return ConstantRange(Lower, Upper);
2990 }
2991
2992 CmpInst::Predicate CmpInst::getSwappedPredicate(Predicate pred) {
2993   switch (pred) {
2994     default: assert(0 && "Unknown cmp predicate!");
2995     case ICMP_EQ: case ICMP_NE:
2996       return pred;
2997     case ICMP_SGT: return ICMP_SLT;
2998     case ICMP_SLT: return ICMP_SGT;
2999     case ICMP_SGE: return ICMP_SLE;
3000     case ICMP_SLE: return ICMP_SGE;
3001     case ICMP_UGT: return ICMP_ULT;
3002     case ICMP_ULT: return ICMP_UGT;
3003     case ICMP_UGE: return ICMP_ULE;
3004     case ICMP_ULE: return ICMP_UGE;
3005   
3006     case FCMP_FALSE: case FCMP_TRUE:
3007     case FCMP_OEQ: case FCMP_ONE:
3008     case FCMP_UEQ: case FCMP_UNE:
3009     case FCMP_ORD: case FCMP_UNO:
3010       return pred;
3011     case FCMP_OGT: return FCMP_OLT;
3012     case FCMP_OLT: return FCMP_OGT;
3013     case FCMP_OGE: return FCMP_OLE;
3014     case FCMP_OLE: return FCMP_OGE;
3015     case FCMP_UGT: return FCMP_ULT;
3016     case FCMP_ULT: return FCMP_UGT;
3017     case FCMP_UGE: return FCMP_ULE;
3018     case FCMP_ULE: return FCMP_UGE;
3019   }
3020 }
3021
3022 bool CmpInst::isUnsigned(unsigned short predicate) {
3023   switch (predicate) {
3024     default: return false;
3025     case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_ULE: case ICmpInst::ICMP_UGT: 
3026     case ICmpInst::ICMP_UGE: return true;
3027   }
3028 }
3029
3030 bool CmpInst::isSigned(unsigned short predicate) {
3031   switch (predicate) {
3032     default: return false;
3033     case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_SLE: case ICmpInst::ICMP_SGT: 
3034     case ICmpInst::ICMP_SGE: return true;
3035   }
3036 }
3037
3038 bool CmpInst::isOrdered(unsigned short predicate) {
3039   switch (predicate) {
3040     default: return false;
3041     case FCmpInst::FCMP_OEQ: case FCmpInst::FCMP_ONE: case FCmpInst::FCMP_OGT: 
3042     case FCmpInst::FCMP_OLT: case FCmpInst::FCMP_OGE: case FCmpInst::FCMP_OLE: 
3043     case FCmpInst::FCMP_ORD: return true;
3044   }
3045 }
3046       
3047 bool CmpInst::isUnordered(unsigned short predicate) {
3048   switch (predicate) {
3049     default: return false;
3050     case FCmpInst::FCMP_UEQ: case FCmpInst::FCMP_UNE: case FCmpInst::FCMP_UGT: 
3051     case FCmpInst::FCMP_ULT: case FCmpInst::FCMP_UGE: case FCmpInst::FCMP_ULE: 
3052     case FCmpInst::FCMP_UNO: return true;
3053   }
3054 }
3055
3056 bool CmpInst::isTrueWhenEqual(unsigned short predicate) {
3057   switch(predicate) {
3058     default: return false;
3059     case ICMP_EQ:   case ICMP_UGE: case ICMP_ULE: case ICMP_SGE: case ICMP_SLE:
3060     case FCMP_TRUE: case FCMP_UEQ: case FCMP_UGE: case FCMP_ULE: return true;
3061   }
3062 }
3063
3064 bool CmpInst::isFalseWhenEqual(unsigned short predicate) {
3065   switch(predicate) {
3066   case ICMP_NE:    case ICMP_UGT: case ICMP_ULT: case ICMP_SGT: case ICMP_SLT:
3067   case FCMP_FALSE: case FCMP_ONE: case FCMP_OGT: case FCMP_OLT: return true;
3068   default: return false;
3069   }
3070 }
3071
3072
3073 //===----------------------------------------------------------------------===//
3074 //                        SwitchInst Implementation
3075 //===----------------------------------------------------------------------===//
3076
3077 void SwitchInst::init(Value *Value, BasicBlock *Default, unsigned NumReserved) {
3078   assert(Value && Default && NumReserved);
3079   ReservedSpace = NumReserved;
3080   NumOperands = 2;
3081   OperandList = allocHungoffUses(ReservedSpace);
3082
3083   OperandList[0] = Value;
3084   OperandList[1] = Default;
3085 }
3086
3087 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
3088 /// switch on and a default destination.  The number of additional cases can
3089 /// be specified here to make memory allocation more efficient.  This
3090 /// constructor can also autoinsert before another instruction.
3091 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
3092                        Instruction *InsertBefore)
3093   : TerminatorInst(Type::getVoidTy(Value->getContext()), Instruction::Switch,
3094                    0, 0, InsertBefore) {
3095   init(Value, Default, 2+NumCases*2);
3096 }
3097
3098 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
3099 /// switch on and a default destination.  The number of additional cases can
3100 /// be specified here to make memory allocation more efficient.  This
3101 /// constructor also autoinserts at the end of the specified BasicBlock.
3102 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
3103                        BasicBlock *InsertAtEnd)
3104   : TerminatorInst(Type::getVoidTy(Value->getContext()), Instruction::Switch,
3105                    0, 0, InsertAtEnd) {
3106   init(Value, Default, 2+NumCases*2);
3107 }
3108
3109 SwitchInst::SwitchInst(const SwitchInst &SI)
3110   : TerminatorInst(SI.getType(), Instruction::Switch, 0, 0) {
3111   init(SI.getCondition(), SI.getDefaultDest(), SI.getNumOperands());
3112   NumOperands = SI.getNumOperands();
3113   Use *OL = OperandList, *InOL = SI.OperandList;
3114   for (unsigned i = 2, E = SI.getNumOperands(); i != E; i += 2) {
3115     OL[i] = InOL[i];
3116     OL[i+1] = InOL[i+1];
3117   }
3118   SubclassOptionalData = SI.SubclassOptionalData;
3119 }
3120
3121 SwitchInst::~SwitchInst() {
3122   dropHungoffUses();
3123 }
3124
3125
3126 /// addCase - Add an entry to the switch instruction...
3127 ///
3128 void SwitchInst::addCase(ConstantInt *OnVal, BasicBlock *Dest) {
3129   unsigned OpNo = NumOperands;
3130   if (OpNo+2 > ReservedSpace)
3131     growOperands();  // Get more space!
3132   // Initialize some new operands.
3133   assert(OpNo+1 < ReservedSpace && "Growing didn't work!");
3134   NumOperands = OpNo+2;
3135   OperandList[OpNo] = OnVal;
3136   OperandList[OpNo+1] = Dest;
3137 }
3138
3139 /// removeCase - This method removes the specified successor from the switch
3140 /// instruction.  Note that this cannot be used to remove the default
3141 /// destination (successor #0).
3142 ///
3143 void SwitchInst::removeCase(unsigned idx) {
3144   assert(idx != 0 && "Cannot remove the default case!");
3145   assert(idx*2 < getNumOperands() && "Successor index out of range!!!");
3146
3147   unsigned NumOps = getNumOperands();
3148   Use *OL = OperandList;
3149
3150   // Overwrite this case with the end of the list.
3151   if ((idx + 1) * 2 != NumOps) {
3152     OL[idx * 2] = OL[NumOps - 2];
3153     OL[idx * 2 + 1] = OL[NumOps - 1];
3154   }
3155
3156   // Nuke the last value.
3157   OL[NumOps-2].set(0);
3158   OL[NumOps-2+1].set(0);
3159   NumOperands = NumOps-2;
3160 }
3161
3162 /// growOperands - grow operands - This grows the operand list in response
3163 /// to a push_back style of operation.  This grows the number of ops by 3 times.
3164 ///
3165 void SwitchInst::growOperands() {
3166   unsigned e = getNumOperands();
3167   unsigned NumOps = e*3;
3168
3169   ReservedSpace = NumOps;
3170   Use *NewOps = allocHungoffUses(NumOps);
3171   Use *OldOps = OperandList;
3172   for (unsigned i = 0; i != e; ++i) {
3173       NewOps[i] = OldOps[i];
3174   }
3175   OperandList = NewOps;
3176   Use::zap(OldOps, OldOps + e, true);
3177 }
3178
3179
3180 BasicBlock *SwitchInst::getSuccessorV(unsigned idx) const {
3181   return getSuccessor(idx);
3182 }
3183 unsigned SwitchInst::getNumSuccessorsV() const {
3184   return getNumSuccessors();
3185 }
3186 void SwitchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
3187   setSuccessor(idx, B);
3188 }
3189
3190 //===----------------------------------------------------------------------===//
3191 //                        IndirectBrInst Implementation
3192 //===----------------------------------------------------------------------===//
3193
3194 void IndirectBrInst::init(Value *Address, unsigned NumDests) {
3195   assert(Address && Address->getType()->isPointerTy() &&
3196          "Address of indirectbr must be a pointer");
3197   ReservedSpace = 1+NumDests;
3198   NumOperands = 1;
3199   OperandList = allocHungoffUses(ReservedSpace);
3200   
3201   OperandList[0] = Address;
3202 }
3203
3204
3205 /// growOperands - grow operands - This grows the operand list in response
3206 /// to a push_back style of operation.  This grows the number of ops by 2 times.
3207 ///
3208 void IndirectBrInst::growOperands() {
3209   unsigned e = getNumOperands();
3210   unsigned NumOps = e*2;
3211   
3212   ReservedSpace = NumOps;
3213   Use *NewOps = allocHungoffUses(NumOps);
3214   Use *OldOps = OperandList;
3215   for (unsigned i = 0; i != e; ++i)
3216     NewOps[i] = OldOps[i];
3217   OperandList = NewOps;
3218   Use::zap(OldOps, OldOps + e, true);
3219 }
3220
3221 IndirectBrInst::IndirectBrInst(Value *Address, unsigned NumCases,
3222                                Instruction *InsertBefore)
3223 : TerminatorInst(Type::getVoidTy(Address->getContext()),Instruction::IndirectBr,
3224                  0, 0, InsertBefore) {
3225   init(Address, NumCases);
3226 }
3227
3228 IndirectBrInst::IndirectBrInst(Value *Address, unsigned NumCases,
3229                                BasicBlock *InsertAtEnd)
3230 : TerminatorInst(Type::getVoidTy(Address->getContext()),Instruction::IndirectBr,
3231                  0, 0, InsertAtEnd) {
3232   init(Address, NumCases);
3233 }
3234
3235 IndirectBrInst::IndirectBrInst(const IndirectBrInst &IBI)
3236   : TerminatorInst(Type::getVoidTy(IBI.getContext()), Instruction::IndirectBr,
3237                    allocHungoffUses(IBI.getNumOperands()),
3238                    IBI.getNumOperands()) {
3239   Use *OL = OperandList, *InOL = IBI.OperandList;
3240   for (unsigned i = 0, E = IBI.getNumOperands(); i != E; ++i)
3241     OL[i] = InOL[i];
3242   SubclassOptionalData = IBI.SubclassOptionalData;
3243 }
3244
3245 IndirectBrInst::~IndirectBrInst() {
3246   dropHungoffUses();
3247 }
3248
3249 /// addDestination - Add a destination.
3250 ///
3251 void IndirectBrInst::addDestination(BasicBlock *DestBB) {
3252   unsigned OpNo = NumOperands;
3253   if (OpNo+1 > ReservedSpace)
3254     growOperands();  // Get more space!
3255   // Initialize some new operands.
3256   assert(OpNo < ReservedSpace && "Growing didn't work!");
3257   NumOperands = OpNo+1;
3258   OperandList[OpNo] = DestBB;
3259 }
3260
3261 /// removeDestination - This method removes the specified successor from the
3262 /// indirectbr instruction.
3263 void IndirectBrInst::removeDestination(unsigned idx) {
3264   assert(idx < getNumOperands()-1 && "Successor index out of range!");
3265   
3266   unsigned NumOps = getNumOperands();
3267   Use *OL = OperandList;
3268
3269   // Replace this value with the last one.
3270   OL[idx+1] = OL[NumOps-1];
3271   
3272   // Nuke the last value.
3273   OL[NumOps-1].set(0);
3274   NumOperands = NumOps-1;
3275 }
3276
3277 BasicBlock *IndirectBrInst::getSuccessorV(unsigned idx) const {
3278   return getSuccessor(idx);
3279 }
3280 unsigned IndirectBrInst::getNumSuccessorsV() const {
3281   return getNumSuccessors();
3282 }
3283 void IndirectBrInst::setSuccessorV(unsigned idx, BasicBlock *B) {
3284   setSuccessor(idx, B);
3285 }
3286
3287 //===----------------------------------------------------------------------===//
3288 //                           clone_impl() implementations
3289 //===----------------------------------------------------------------------===//
3290
3291 // Define these methods here so vtables don't get emitted into every translation
3292 // unit that uses these classes.
3293
3294 GetElementPtrInst *GetElementPtrInst::clone_impl() const {
3295   return new (getNumOperands()) GetElementPtrInst(*this);
3296 }
3297
3298 BinaryOperator *BinaryOperator::clone_impl() const {
3299   return Create(getOpcode(), Op<0>(), Op<1>());
3300 }
3301
3302 FCmpInst* FCmpInst::clone_impl() const {
3303   return new FCmpInst(getPredicate(), Op<0>(), Op<1>());
3304 }
3305
3306 ICmpInst* ICmpInst::clone_impl() const {
3307   return new ICmpInst(getPredicate(), Op<0>(), Op<1>());
3308 }
3309
3310 ExtractValueInst *ExtractValueInst::clone_impl() const {
3311   return new ExtractValueInst(*this);
3312 }
3313
3314 InsertValueInst *InsertValueInst::clone_impl() const {
3315   return new InsertValueInst(*this);
3316 }
3317
3318 AllocaInst *AllocaInst::clone_impl() const {
3319   return new AllocaInst(getAllocatedType(),
3320                         (Value*)getOperand(0),
3321                         getAlignment());
3322 }
3323
3324 LoadInst *LoadInst::clone_impl() const {
3325   return new LoadInst(getOperand(0), Twine(), isVolatile(),
3326                       getAlignment(), getOrdering(), getSynchScope());
3327 }
3328
3329 StoreInst *StoreInst::clone_impl() const {
3330   return new StoreInst(getOperand(0), getOperand(1), isVolatile(),
3331                        getAlignment(), getOrdering(), getSynchScope());
3332   
3333 }
3334
3335 AtomicCmpXchgInst *AtomicCmpXchgInst::clone_impl() const {
3336   AtomicCmpXchgInst *Result =
3337     new AtomicCmpXchgInst(getOperand(0), getOperand(1), getOperand(2),
3338                           getOrdering(), getSynchScope());
3339   Result->setVolatile(isVolatile());
3340   return Result;
3341 }
3342
3343 AtomicRMWInst *AtomicRMWInst::clone_impl() const {
3344   AtomicRMWInst *Result =
3345     new AtomicRMWInst(getOperation(),getOperand(0), getOperand(1),
3346                       getOrdering(), getSynchScope());
3347   Result->setVolatile(isVolatile());
3348   return Result;
3349 }
3350
3351 FenceInst *FenceInst::clone_impl() const {
3352   return new FenceInst(getContext(), getOrdering(), getSynchScope());
3353 }
3354
3355 TruncInst *TruncInst::clone_impl() const {
3356   return new TruncInst(getOperand(0), getType());
3357 }
3358
3359 ZExtInst *ZExtInst::clone_impl() const {
3360   return new ZExtInst(getOperand(0), getType());
3361 }
3362
3363 SExtInst *SExtInst::clone_impl() const {
3364   return new SExtInst(getOperand(0), getType());
3365 }
3366
3367 FPTruncInst *FPTruncInst::clone_impl() const {
3368   return new FPTruncInst(getOperand(0), getType());
3369 }
3370
3371 FPExtInst *FPExtInst::clone_impl() const {
3372   return new FPExtInst(getOperand(0), getType());
3373 }
3374
3375 UIToFPInst *UIToFPInst::clone_impl() const {
3376   return new UIToFPInst(getOperand(0), getType());
3377 }
3378
3379 SIToFPInst *SIToFPInst::clone_impl() const {
3380   return new SIToFPInst(getOperand(0), getType());
3381 }
3382
3383 FPToUIInst *FPToUIInst::clone_impl() const {
3384   return new FPToUIInst(getOperand(0), getType());
3385 }
3386
3387 FPToSIInst *FPToSIInst::clone_impl() const {
3388   return new FPToSIInst(getOperand(0), getType());
3389 }
3390
3391 PtrToIntInst *PtrToIntInst::clone_impl() const {
3392   return new PtrToIntInst(getOperand(0), getType());
3393 }
3394
3395 IntToPtrInst *IntToPtrInst::clone_impl() const {
3396   return new IntToPtrInst(getOperand(0), getType());
3397 }
3398
3399 BitCastInst *BitCastInst::clone_impl() const {
3400   return new BitCastInst(getOperand(0), getType());
3401 }
3402
3403 CallInst *CallInst::clone_impl() const {
3404   return  new(getNumOperands()) CallInst(*this);
3405 }
3406
3407 SelectInst *SelectInst::clone_impl() const {
3408   return SelectInst::Create(getOperand(0), getOperand(1), getOperand(2));
3409 }
3410
3411 VAArgInst *VAArgInst::clone_impl() const {
3412   return new VAArgInst(getOperand(0), getType());
3413 }
3414
3415 ExtractElementInst *ExtractElementInst::clone_impl() const {
3416   return ExtractElementInst::Create(getOperand(0), getOperand(1));
3417 }
3418
3419 InsertElementInst *InsertElementInst::clone_impl() const {
3420   return InsertElementInst::Create(getOperand(0),
3421                                    getOperand(1),
3422                                    getOperand(2));
3423 }
3424
3425 ShuffleVectorInst *ShuffleVectorInst::clone_impl() const {
3426   return new ShuffleVectorInst(getOperand(0),
3427                            getOperand(1),
3428                            getOperand(2));
3429 }
3430
3431 PHINode *PHINode::clone_impl() const {
3432   return new PHINode(*this);
3433 }
3434
3435 LandingPadInst *LandingPadInst::clone_impl() const {
3436   return new LandingPadInst(*this);
3437 }
3438
3439 ReturnInst *ReturnInst::clone_impl() const {
3440   return new(getNumOperands()) ReturnInst(*this);
3441 }
3442
3443 BranchInst *BranchInst::clone_impl() const {
3444   return new(getNumOperands()) BranchInst(*this);
3445 }
3446
3447 SwitchInst *SwitchInst::clone_impl() const {
3448   return new SwitchInst(*this);
3449 }
3450
3451 IndirectBrInst *IndirectBrInst::clone_impl() const {
3452   return new IndirectBrInst(*this);
3453 }
3454
3455
3456 InvokeInst *InvokeInst::clone_impl() const {
3457   return new(getNumOperands()) InvokeInst(*this);
3458 }
3459
3460 ResumeInst *ResumeInst::clone_impl() const {
3461   return new(1) ResumeInst(*this);
3462 }
3463
3464 UnwindInst *UnwindInst::clone_impl() const {
3465   LLVMContext &Context = getContext();
3466   return new UnwindInst(Context);
3467 }
3468
3469 UnreachableInst *UnreachableInst::clone_impl() const {
3470   LLVMContext &Context = getContext();
3471   return new UnreachableInst(Context);
3472 }