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