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