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