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