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