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