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