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