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