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