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