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