LLVM API Documentation

Instructions.cpp
Go to the documentation of this file.
00001 //===-- Instructions.cpp - Implement the LLVM instructions ----------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements all of the non-inline methods for the LLVM instruction
00011 // classes.
00012 //
00013 //===----------------------------------------------------------------------===//
00014 
00015 #include "llvm/IR/Instructions.h"
00016 #include "LLVMContextImpl.h"
00017 #include "llvm/IR/CallSite.h"
00018 #include "llvm/IR/ConstantRange.h"
00019 #include "llvm/IR/Constants.h"
00020 #include "llvm/IR/DataLayout.h"
00021 #include "llvm/IR/DerivedTypes.h"
00022 #include "llvm/IR/Function.h"
00023 #include "llvm/IR/Module.h"
00024 #include "llvm/IR/Operator.h"
00025 #include "llvm/Support/ErrorHandling.h"
00026 #include "llvm/Support/MathExtras.h"
00027 using namespace llvm;
00028 
00029 //===----------------------------------------------------------------------===//
00030 //                            CallSite Class
00031 //===----------------------------------------------------------------------===//
00032 
00033 User::op_iterator CallSite::getCallee() const {
00034   Instruction *II(getInstruction());
00035   return isCall()
00036     ? cast<CallInst>(II)->op_end() - 1 // Skip Callee
00037     : cast<InvokeInst>(II)->op_end() - 3; // Skip BB, BB, Callee
00038 }
00039 
00040 //===----------------------------------------------------------------------===//
00041 //                            TerminatorInst Class
00042 //===----------------------------------------------------------------------===//
00043 
00044 // Out of line virtual method, so the vtable, etc has a home.
00045 TerminatorInst::~TerminatorInst() {
00046 }
00047 
00048 //===----------------------------------------------------------------------===//
00049 //                           UnaryInstruction Class
00050 //===----------------------------------------------------------------------===//
00051 
00052 // Out of line virtual method, so the vtable, etc has a home.
00053 UnaryInstruction::~UnaryInstruction() {
00054 }
00055 
00056 //===----------------------------------------------------------------------===//
00057 //                              SelectInst Class
00058 //===----------------------------------------------------------------------===//
00059 
00060 /// areInvalidOperands - Return a string if the specified operands are invalid
00061 /// for a select operation, otherwise return null.
00062 const char *SelectInst::areInvalidOperands(Value *Op0, Value *Op1, Value *Op2) {
00063   if (Op1->getType() != Op2->getType())
00064     return "both values to select must have same type";
00065   
00066   if (VectorType *VT = dyn_cast<VectorType>(Op0->getType())) {
00067     // Vector select.
00068     if (VT->getElementType() != Type::getInt1Ty(Op0->getContext()))
00069       return "vector select condition element type must be i1";
00070     VectorType *ET = dyn_cast<VectorType>(Op1->getType());
00071     if (!ET)
00072       return "selected values for vector select must be vectors";
00073     if (ET->getNumElements() != VT->getNumElements())
00074       return "vector select requires selected vectors to have "
00075                    "the same vector length as select condition";
00076   } else if (Op0->getType() != Type::getInt1Ty(Op0->getContext())) {
00077     return "select condition must be i1 or <n x i1>";
00078   }
00079   return nullptr;
00080 }
00081 
00082 
00083 //===----------------------------------------------------------------------===//
00084 //                               PHINode Class
00085 //===----------------------------------------------------------------------===//
00086 
00087 PHINode::PHINode(const PHINode &PN)
00088   : Instruction(PN.getType(), Instruction::PHI,
00089                 allocHungoffUses(PN.getNumOperands()), PN.getNumOperands()),
00090     ReservedSpace(PN.getNumOperands()) {
00091   std::copy(PN.op_begin(), PN.op_end(), op_begin());
00092   std::copy(PN.block_begin(), PN.block_end(), block_begin());
00093   SubclassOptionalData = PN.SubclassOptionalData;
00094 }
00095 
00096 PHINode::~PHINode() {
00097   dropHungoffUses();
00098 }
00099 
00100 Use *PHINode::allocHungoffUses(unsigned N) const {
00101   // Allocate the array of Uses of the incoming values, followed by a pointer
00102   // (with bottom bit set) to the User, followed by the array of pointers to
00103   // the incoming basic blocks.
00104   size_t size = N * sizeof(Use) + sizeof(Use::UserRef)
00105     + N * sizeof(BasicBlock*);
00106   Use *Begin = static_cast<Use*>(::operator new(size));
00107   Use *End = Begin + N;
00108   (void) new(End) Use::UserRef(const_cast<PHINode*>(this), 1);
00109   return Use::initTags(Begin, End);
00110 }
00111 
00112 // removeIncomingValue - Remove an incoming value.  This is useful if a
00113 // predecessor basic block is deleted.
00114 Value *PHINode::removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty) {
00115   Value *Removed = getIncomingValue(Idx);
00116 
00117   // Move everything after this operand down.
00118   //
00119   // FIXME: we could just swap with the end of the list, then erase.  However,
00120   // clients might not expect this to happen.  The code as it is thrashes the
00121   // use/def lists, which is kinda lame.
00122   std::copy(op_begin() + Idx + 1, op_end(), op_begin() + Idx);
00123   std::copy(block_begin() + Idx + 1, block_end(), block_begin() + Idx);
00124 
00125   // Nuke the last value.
00126   Op<-1>().set(nullptr);
00127   --NumOperands;
00128 
00129   // If the PHI node is dead, because it has zero entries, nuke it now.
00130   if (getNumOperands() == 0 && DeletePHIIfEmpty) {
00131     // If anyone is using this PHI, make them use a dummy value instead...
00132     replaceAllUsesWith(UndefValue::get(getType()));
00133     eraseFromParent();
00134   }
00135   return Removed;
00136 }
00137 
00138 /// growOperands - grow operands - This grows the operand list in response
00139 /// to a push_back style of operation.  This grows the number of ops by 1.5
00140 /// times.
00141 ///
00142 void PHINode::growOperands() {
00143   unsigned e = getNumOperands();
00144   unsigned NumOps = e + e / 2;
00145   if (NumOps < 2) NumOps = 2;      // 2 op PHI nodes are VERY common.
00146 
00147   Use *OldOps = op_begin();
00148   BasicBlock **OldBlocks = block_begin();
00149 
00150   ReservedSpace = NumOps;
00151   OperandList = allocHungoffUses(ReservedSpace);
00152 
00153   std::copy(OldOps, OldOps + e, op_begin());
00154   std::copy(OldBlocks, OldBlocks + e, block_begin());
00155 
00156   Use::zap(OldOps, OldOps + e, true);
00157 }
00158 
00159 /// hasConstantValue - If the specified PHI node always merges together the same
00160 /// value, return the value, otherwise return null.
00161 Value *PHINode::hasConstantValue() const {
00162   // Exploit the fact that phi nodes always have at least one entry.
00163   Value *ConstantValue = getIncomingValue(0);
00164   for (unsigned i = 1, e = getNumIncomingValues(); i != e; ++i)
00165     if (getIncomingValue(i) != ConstantValue && getIncomingValue(i) != this) {
00166       if (ConstantValue != this)
00167         return nullptr; // Incoming values not all the same.
00168        // The case where the first value is this PHI.
00169       ConstantValue = getIncomingValue(i);
00170     }
00171   if (ConstantValue == this)
00172     return UndefValue::get(getType());
00173   return ConstantValue;
00174 }
00175 
00176 //===----------------------------------------------------------------------===//
00177 //                       LandingPadInst Implementation
00178 //===----------------------------------------------------------------------===//
00179 
00180 LandingPadInst::LandingPadInst(Type *RetTy, Value *PersonalityFn,
00181                                unsigned NumReservedValues, const Twine &NameStr,
00182                                Instruction *InsertBefore)
00183   : Instruction(RetTy, Instruction::LandingPad, nullptr, 0, InsertBefore) {
00184   init(PersonalityFn, 1 + NumReservedValues, NameStr);
00185 }
00186 
00187 LandingPadInst::LandingPadInst(Type *RetTy, Value *PersonalityFn,
00188                                unsigned NumReservedValues, const Twine &NameStr,
00189                                BasicBlock *InsertAtEnd)
00190   : Instruction(RetTy, Instruction::LandingPad, nullptr, 0, InsertAtEnd) {
00191   init(PersonalityFn, 1 + NumReservedValues, NameStr);
00192 }
00193 
00194 LandingPadInst::LandingPadInst(const LandingPadInst &LP)
00195   : Instruction(LP.getType(), Instruction::LandingPad,
00196                 allocHungoffUses(LP.getNumOperands()), LP.getNumOperands()),
00197     ReservedSpace(LP.getNumOperands()) {
00198   Use *OL = OperandList, *InOL = LP.OperandList;
00199   for (unsigned I = 0, E = ReservedSpace; I != E; ++I)
00200     OL[I] = InOL[I];
00201 
00202   setCleanup(LP.isCleanup());
00203 }
00204 
00205 LandingPadInst::~LandingPadInst() {
00206   dropHungoffUses();
00207 }
00208 
00209 LandingPadInst *LandingPadInst::Create(Type *RetTy, Value *PersonalityFn,
00210                                        unsigned NumReservedClauses,
00211                                        const Twine &NameStr,
00212                                        Instruction *InsertBefore) {
00213   return new LandingPadInst(RetTy, PersonalityFn, NumReservedClauses, NameStr,
00214                             InsertBefore);
00215 }
00216 
00217 LandingPadInst *LandingPadInst::Create(Type *RetTy, Value *PersonalityFn,
00218                                        unsigned NumReservedClauses,
00219                                        const Twine &NameStr,
00220                                        BasicBlock *InsertAtEnd) {
00221   return new LandingPadInst(RetTy, PersonalityFn, NumReservedClauses, NameStr,
00222                             InsertAtEnd);
00223 }
00224 
00225 void LandingPadInst::init(Value *PersFn, unsigned NumReservedValues,
00226                           const Twine &NameStr) {
00227   ReservedSpace = NumReservedValues;
00228   NumOperands = 1;
00229   OperandList = allocHungoffUses(ReservedSpace);
00230   OperandList[0] = PersFn;
00231   setName(NameStr);
00232   setCleanup(false);
00233 }
00234 
00235 /// growOperands - grow operands - This grows the operand list in response to a
00236 /// push_back style of operation. This grows the number of ops by 2 times.
00237 void LandingPadInst::growOperands(unsigned Size) {
00238   unsigned e = getNumOperands();
00239   if (ReservedSpace >= e + Size) return;
00240   ReservedSpace = (e + Size / 2) * 2;
00241 
00242   Use *NewOps = allocHungoffUses(ReservedSpace);
00243   Use *OldOps = OperandList;
00244   for (unsigned i = 0; i != e; ++i)
00245       NewOps[i] = OldOps[i];
00246 
00247   OperandList = NewOps;
00248   Use::zap(OldOps, OldOps + e, true);
00249 }
00250 
00251 void LandingPadInst::addClause(Value *Val) {
00252   unsigned OpNo = getNumOperands();
00253   growOperands(1);
00254   assert(OpNo < ReservedSpace && "Growing didn't work!");
00255   ++NumOperands;
00256   OperandList[OpNo] = Val;
00257 }
00258 
00259 //===----------------------------------------------------------------------===//
00260 //                        CallInst Implementation
00261 //===----------------------------------------------------------------------===//
00262 
00263 CallInst::~CallInst() {
00264 }
00265 
00266 void CallInst::init(Value *Func, ArrayRef<Value *> Args, const Twine &NameStr) {
00267   assert(NumOperands == Args.size() + 1 && "NumOperands not set up?");
00268   Op<-1>() = Func;
00269 
00270 #ifndef NDEBUG
00271   FunctionType *FTy =
00272     cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
00273 
00274   assert((Args.size() == FTy->getNumParams() ||
00275           (FTy->isVarArg() && Args.size() > FTy->getNumParams())) &&
00276          "Calling a function with bad signature!");
00277 
00278   for (unsigned i = 0; i != Args.size(); ++i)
00279     assert((i >= FTy->getNumParams() || 
00280             FTy->getParamType(i) == Args[i]->getType()) &&
00281            "Calling a function with a bad signature!");
00282 #endif
00283 
00284   std::copy(Args.begin(), Args.end(), op_begin());
00285   setName(NameStr);
00286 }
00287 
00288 void CallInst::init(Value *Func, const Twine &NameStr) {
00289   assert(NumOperands == 1 && "NumOperands not set up?");
00290   Op<-1>() = Func;
00291 
00292 #ifndef NDEBUG
00293   FunctionType *FTy =
00294     cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
00295 
00296   assert(FTy->getNumParams() == 0 && "Calling a function with bad signature");
00297 #endif
00298 
00299   setName(NameStr);
00300 }
00301 
00302 CallInst::CallInst(Value *Func, const Twine &Name,
00303                    Instruction *InsertBefore)
00304   : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
00305                                    ->getElementType())->getReturnType(),
00306                 Instruction::Call,
00307                 OperandTraits<CallInst>::op_end(this) - 1,
00308                 1, InsertBefore) {
00309   init(Func, Name);
00310 }
00311 
00312 CallInst::CallInst(Value *Func, const Twine &Name,
00313                    BasicBlock *InsertAtEnd)
00314   : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
00315                                    ->getElementType())->getReturnType(),
00316                 Instruction::Call,
00317                 OperandTraits<CallInst>::op_end(this) - 1,
00318                 1, InsertAtEnd) {
00319   init(Func, Name);
00320 }
00321 
00322 CallInst::CallInst(const CallInst &CI)
00323   : Instruction(CI.getType(), Instruction::Call,
00324                 OperandTraits<CallInst>::op_end(this) - CI.getNumOperands(),
00325                 CI.getNumOperands()) {
00326   setAttributes(CI.getAttributes());
00327   setTailCall(CI.isTailCall());
00328   setCallingConv(CI.getCallingConv());
00329     
00330   std::copy(CI.op_begin(), CI.op_end(), op_begin());
00331   SubclassOptionalData = CI.SubclassOptionalData;
00332 }
00333 
00334 void CallInst::addAttribute(unsigned i, Attribute::AttrKind attr) {
00335   AttributeSet PAL = getAttributes();
00336   PAL = PAL.addAttribute(getContext(), i, attr);
00337   setAttributes(PAL);
00338 }
00339 
00340 void CallInst::removeAttribute(unsigned i, Attribute attr) {
00341   AttributeSet PAL = getAttributes();
00342   AttrBuilder B(attr);
00343   LLVMContext &Context = getContext();
00344   PAL = PAL.removeAttributes(Context, i,
00345                              AttributeSet::get(Context, i, B));
00346   setAttributes(PAL);
00347 }
00348 
00349 bool CallInst::hasFnAttrImpl(Attribute::AttrKind A) const {
00350   if (AttributeList.hasAttribute(AttributeSet::FunctionIndex, A))
00351     return true;
00352   if (const Function *F = getCalledFunction())
00353     return F->getAttributes().hasAttribute(AttributeSet::FunctionIndex, A);
00354   return false;
00355 }
00356 
00357 bool CallInst::paramHasAttr(unsigned i, Attribute::AttrKind A) const {
00358   if (AttributeList.hasAttribute(i, A))
00359     return true;
00360   if (const Function *F = getCalledFunction())
00361     return F->getAttributes().hasAttribute(i, A);
00362   return false;
00363 }
00364 
00365 /// IsConstantOne - Return true only if val is constant int 1
00366 static bool IsConstantOne(Value *val) {
00367   assert(val && "IsConstantOne does not work with NULL val");
00368   return isa<ConstantInt>(val) && cast<ConstantInt>(val)->isOne();
00369 }
00370 
00371 static Instruction *createMalloc(Instruction *InsertBefore,
00372                                  BasicBlock *InsertAtEnd, Type *IntPtrTy,
00373                                  Type *AllocTy, Value *AllocSize, 
00374                                  Value *ArraySize, Function *MallocF,
00375                                  const Twine &Name) {
00376   assert(((!InsertBefore && InsertAtEnd) || (InsertBefore && !InsertAtEnd)) &&
00377          "createMalloc needs either InsertBefore or InsertAtEnd");
00378 
00379   // malloc(type) becomes: 
00380   //       bitcast (i8* malloc(typeSize)) to type*
00381   // malloc(type, arraySize) becomes:
00382   //       bitcast (i8 *malloc(typeSize*arraySize)) to type*
00383   if (!ArraySize)
00384     ArraySize = ConstantInt::get(IntPtrTy, 1);
00385   else if (ArraySize->getType() != IntPtrTy) {
00386     if (InsertBefore)
00387       ArraySize = CastInst::CreateIntegerCast(ArraySize, IntPtrTy, false,
00388                                               "", InsertBefore);
00389     else
00390       ArraySize = CastInst::CreateIntegerCast(ArraySize, IntPtrTy, false,
00391                                               "", InsertAtEnd);
00392   }
00393 
00394   if (!IsConstantOne(ArraySize)) {
00395     if (IsConstantOne(AllocSize)) {
00396       AllocSize = ArraySize;         // Operand * 1 = Operand
00397     } else if (Constant *CO = dyn_cast<Constant>(ArraySize)) {
00398       Constant *Scale = ConstantExpr::getIntegerCast(CO, IntPtrTy,
00399                                                      false /*ZExt*/);
00400       // Malloc arg is constant product of type size and array size
00401       AllocSize = ConstantExpr::getMul(Scale, cast<Constant>(AllocSize));
00402     } else {
00403       // Multiply type size by the array size...
00404       if (InsertBefore)
00405         AllocSize = BinaryOperator::CreateMul(ArraySize, AllocSize,
00406                                               "mallocsize", InsertBefore);
00407       else
00408         AllocSize = BinaryOperator::CreateMul(ArraySize, AllocSize,
00409                                               "mallocsize", InsertAtEnd);
00410     }
00411   }
00412 
00413   assert(AllocSize->getType() == IntPtrTy && "malloc arg is wrong size");
00414   // Create the call to Malloc.
00415   BasicBlock* BB = InsertBefore ? InsertBefore->getParent() : InsertAtEnd;
00416   Module* M = BB->getParent()->getParent();
00417   Type *BPTy = Type::getInt8PtrTy(BB->getContext());
00418   Value *MallocFunc = MallocF;
00419   if (!MallocFunc)
00420     // prototype malloc as "void *malloc(size_t)"
00421     MallocFunc = M->getOrInsertFunction("malloc", BPTy, IntPtrTy, NULL);
00422   PointerType *AllocPtrType = PointerType::getUnqual(AllocTy);
00423   CallInst *MCall = nullptr;
00424   Instruction *Result = nullptr;
00425   if (InsertBefore) {
00426     MCall = CallInst::Create(MallocFunc, AllocSize, "malloccall", InsertBefore);
00427     Result = MCall;
00428     if (Result->getType() != AllocPtrType)
00429       // Create a cast instruction to convert to the right type...
00430       Result = new BitCastInst(MCall, AllocPtrType, Name, InsertBefore);
00431   } else {
00432     MCall = CallInst::Create(MallocFunc, AllocSize, "malloccall");
00433     Result = MCall;
00434     if (Result->getType() != AllocPtrType) {
00435       InsertAtEnd->getInstList().push_back(MCall);
00436       // Create a cast instruction to convert to the right type...
00437       Result = new BitCastInst(MCall, AllocPtrType, Name);
00438     }
00439   }
00440   MCall->setTailCall();
00441   if (Function *F = dyn_cast<Function>(MallocFunc)) {
00442     MCall->setCallingConv(F->getCallingConv());
00443     if (!F->doesNotAlias(0)) F->setDoesNotAlias(0);
00444   }
00445   assert(!MCall->getType()->isVoidTy() && "Malloc has void return type");
00446 
00447   return Result;
00448 }
00449 
00450 /// CreateMalloc - Generate the IR for a call to malloc:
00451 /// 1. Compute the malloc call's argument as the specified type's size,
00452 ///    possibly multiplied by the array size if the array size is not
00453 ///    constant 1.
00454 /// 2. Call malloc with that argument.
00455 /// 3. Bitcast the result of the malloc call to the specified type.
00456 Instruction *CallInst::CreateMalloc(Instruction *InsertBefore,
00457                                     Type *IntPtrTy, Type *AllocTy,
00458                                     Value *AllocSize, Value *ArraySize,
00459                                     Function * MallocF,
00460                                     const Twine &Name) {
00461   return createMalloc(InsertBefore, nullptr, IntPtrTy, AllocTy, AllocSize,
00462                       ArraySize, MallocF, Name);
00463 }
00464 
00465 /// CreateMalloc - Generate the IR for a call to malloc:
00466 /// 1. Compute the malloc call's argument as the specified type's size,
00467 ///    possibly multiplied by the array size if the array size is not
00468 ///    constant 1.
00469 /// 2. Call malloc with that argument.
00470 /// 3. Bitcast the result of the malloc call to the specified type.
00471 /// Note: This function does not add the bitcast to the basic block, that is the
00472 /// responsibility of the caller.
00473 Instruction *CallInst::CreateMalloc(BasicBlock *InsertAtEnd,
00474                                     Type *IntPtrTy, Type *AllocTy,
00475                                     Value *AllocSize, Value *ArraySize, 
00476                                     Function *MallocF, const Twine &Name) {
00477   return createMalloc(nullptr, InsertAtEnd, IntPtrTy, AllocTy, AllocSize,
00478                       ArraySize, MallocF, Name);
00479 }
00480 
00481 static Instruction* createFree(Value* Source, Instruction *InsertBefore,
00482                                BasicBlock *InsertAtEnd) {
00483   assert(((!InsertBefore && InsertAtEnd) || (InsertBefore && !InsertAtEnd)) &&
00484          "createFree needs either InsertBefore or InsertAtEnd");
00485   assert(Source->getType()->isPointerTy() &&
00486          "Can not free something of nonpointer type!");
00487 
00488   BasicBlock* BB = InsertBefore ? InsertBefore->getParent() : InsertAtEnd;
00489   Module* M = BB->getParent()->getParent();
00490 
00491   Type *VoidTy = Type::getVoidTy(M->getContext());
00492   Type *IntPtrTy = Type::getInt8PtrTy(M->getContext());
00493   // prototype free as "void free(void*)"
00494   Value *FreeFunc = M->getOrInsertFunction("free", VoidTy, IntPtrTy, NULL);
00495   CallInst* Result = nullptr;
00496   Value *PtrCast = Source;
00497   if (InsertBefore) {
00498     if (Source->getType() != IntPtrTy)
00499       PtrCast = new BitCastInst(Source, IntPtrTy, "", InsertBefore);
00500     Result = CallInst::Create(FreeFunc, PtrCast, "", InsertBefore);
00501   } else {
00502     if (Source->getType() != IntPtrTy)
00503       PtrCast = new BitCastInst(Source, IntPtrTy, "", InsertAtEnd);
00504     Result = CallInst::Create(FreeFunc, PtrCast, "");
00505   }
00506   Result->setTailCall();
00507   if (Function *F = dyn_cast<Function>(FreeFunc))
00508     Result->setCallingConv(F->getCallingConv());
00509 
00510   return Result;
00511 }
00512 
00513 /// CreateFree - Generate the IR for a call to the builtin free function.
00514 Instruction * CallInst::CreateFree(Value* Source, Instruction *InsertBefore) {
00515   return createFree(Source, InsertBefore, nullptr);
00516 }
00517 
00518 /// CreateFree - Generate the IR for a call to the builtin free function.
00519 /// Note: This function does not add the call to the basic block, that is the
00520 /// responsibility of the caller.
00521 Instruction* CallInst::CreateFree(Value* Source, BasicBlock *InsertAtEnd) {
00522   Instruction* FreeCall = createFree(Source, nullptr, InsertAtEnd);
00523   assert(FreeCall && "CreateFree did not create a CallInst");
00524   return FreeCall;
00525 }
00526 
00527 //===----------------------------------------------------------------------===//
00528 //                        InvokeInst Implementation
00529 //===----------------------------------------------------------------------===//
00530 
00531 void InvokeInst::init(Value *Fn, BasicBlock *IfNormal, BasicBlock *IfException,
00532                       ArrayRef<Value *> Args, const Twine &NameStr) {
00533   assert(NumOperands == 3 + Args.size() && "NumOperands not set up?");
00534   Op<-3>() = Fn;
00535   Op<-2>() = IfNormal;
00536   Op<-1>() = IfException;
00537 
00538 #ifndef NDEBUG
00539   FunctionType *FTy =
00540     cast<FunctionType>(cast<PointerType>(Fn->getType())->getElementType());
00541 
00542   assert(((Args.size() == FTy->getNumParams()) ||
00543           (FTy->isVarArg() && Args.size() > FTy->getNumParams())) &&
00544          "Invoking a function with bad signature");
00545 
00546   for (unsigned i = 0, e = Args.size(); i != e; i++)
00547     assert((i >= FTy->getNumParams() || 
00548             FTy->getParamType(i) == Args[i]->getType()) &&
00549            "Invoking a function with a bad signature!");
00550 #endif
00551 
00552   std::copy(Args.begin(), Args.end(), op_begin());
00553   setName(NameStr);
00554 }
00555 
00556 InvokeInst::InvokeInst(const InvokeInst &II)
00557   : TerminatorInst(II.getType(), Instruction::Invoke,
00558                    OperandTraits<InvokeInst>::op_end(this)
00559                    - II.getNumOperands(),
00560                    II.getNumOperands()) {
00561   setAttributes(II.getAttributes());
00562   setCallingConv(II.getCallingConv());
00563   std::copy(II.op_begin(), II.op_end(), op_begin());
00564   SubclassOptionalData = II.SubclassOptionalData;
00565 }
00566 
00567 BasicBlock *InvokeInst::getSuccessorV(unsigned idx) const {
00568   return getSuccessor(idx);
00569 }
00570 unsigned InvokeInst::getNumSuccessorsV() const {
00571   return getNumSuccessors();
00572 }
00573 void InvokeInst::setSuccessorV(unsigned idx, BasicBlock *B) {
00574   return setSuccessor(idx, B);
00575 }
00576 
00577 bool InvokeInst::hasFnAttrImpl(Attribute::AttrKind A) const {
00578   if (AttributeList.hasAttribute(AttributeSet::FunctionIndex, A))
00579     return true;
00580   if (const Function *F = getCalledFunction())
00581     return F->getAttributes().hasAttribute(AttributeSet::FunctionIndex, A);
00582   return false;
00583 }
00584 
00585 bool InvokeInst::paramHasAttr(unsigned i, Attribute::AttrKind A) const {
00586   if (AttributeList.hasAttribute(i, A))
00587     return true;
00588   if (const Function *F = getCalledFunction())
00589     return F->getAttributes().hasAttribute(i, A);
00590   return false;
00591 }
00592 
00593 void InvokeInst::addAttribute(unsigned i, Attribute::AttrKind attr) {
00594   AttributeSet PAL = getAttributes();
00595   PAL = PAL.addAttribute(getContext(), i, attr);
00596   setAttributes(PAL);
00597 }
00598 
00599 void InvokeInst::removeAttribute(unsigned i, Attribute attr) {
00600   AttributeSet PAL = getAttributes();
00601   AttrBuilder B(attr);
00602   PAL = PAL.removeAttributes(getContext(), i,
00603                              AttributeSet::get(getContext(), i, B));
00604   setAttributes(PAL);
00605 }
00606 
00607 LandingPadInst *InvokeInst::getLandingPadInst() const {
00608   return cast<LandingPadInst>(getUnwindDest()->getFirstNonPHI());
00609 }
00610 
00611 //===----------------------------------------------------------------------===//
00612 //                        ReturnInst Implementation
00613 //===----------------------------------------------------------------------===//
00614 
00615 ReturnInst::ReturnInst(const ReturnInst &RI)
00616   : TerminatorInst(Type::getVoidTy(RI.getContext()), Instruction::Ret,
00617                    OperandTraits<ReturnInst>::op_end(this) -
00618                      RI.getNumOperands(),
00619                    RI.getNumOperands()) {
00620   if (RI.getNumOperands())
00621     Op<0>() = RI.Op<0>();
00622   SubclassOptionalData = RI.SubclassOptionalData;
00623 }
00624 
00625 ReturnInst::ReturnInst(LLVMContext &C, Value *retVal, Instruction *InsertBefore)
00626   : TerminatorInst(Type::getVoidTy(C), Instruction::Ret,
00627                    OperandTraits<ReturnInst>::op_end(this) - !!retVal, !!retVal,
00628                    InsertBefore) {
00629   if (retVal)
00630     Op<0>() = retVal;
00631 }
00632 ReturnInst::ReturnInst(LLVMContext &C, Value *retVal, BasicBlock *InsertAtEnd)
00633   : TerminatorInst(Type::getVoidTy(C), Instruction::Ret,
00634                    OperandTraits<ReturnInst>::op_end(this) - !!retVal, !!retVal,
00635                    InsertAtEnd) {
00636   if (retVal)
00637     Op<0>() = retVal;
00638 }
00639 ReturnInst::ReturnInst(LLVMContext &Context, BasicBlock *InsertAtEnd)
00640   : TerminatorInst(Type::getVoidTy(Context), Instruction::Ret,
00641                    OperandTraits<ReturnInst>::op_end(this), 0, InsertAtEnd) {
00642 }
00643 
00644 unsigned ReturnInst::getNumSuccessorsV() const {
00645   return getNumSuccessors();
00646 }
00647 
00648 /// Out-of-line ReturnInst method, put here so the C++ compiler can choose to
00649 /// emit the vtable for the class in this translation unit.
00650 void ReturnInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
00651   llvm_unreachable("ReturnInst has no successors!");
00652 }
00653 
00654 BasicBlock *ReturnInst::getSuccessorV(unsigned idx) const {
00655   llvm_unreachable("ReturnInst has no successors!");
00656 }
00657 
00658 ReturnInst::~ReturnInst() {
00659 }
00660 
00661 //===----------------------------------------------------------------------===//
00662 //                        ResumeInst Implementation
00663 //===----------------------------------------------------------------------===//
00664 
00665 ResumeInst::ResumeInst(const ResumeInst &RI)
00666   : TerminatorInst(Type::getVoidTy(RI.getContext()), Instruction::Resume,
00667                    OperandTraits<ResumeInst>::op_begin(this), 1) {
00668   Op<0>() = RI.Op<0>();
00669 }
00670 
00671 ResumeInst::ResumeInst(Value *Exn, Instruction *InsertBefore)
00672   : TerminatorInst(Type::getVoidTy(Exn->getContext()), Instruction::Resume,
00673                    OperandTraits<ResumeInst>::op_begin(this), 1, InsertBefore) {
00674   Op<0>() = Exn;
00675 }
00676 
00677 ResumeInst::ResumeInst(Value *Exn, BasicBlock *InsertAtEnd)
00678   : TerminatorInst(Type::getVoidTy(Exn->getContext()), Instruction::Resume,
00679                    OperandTraits<ResumeInst>::op_begin(this), 1, InsertAtEnd) {
00680   Op<0>() = Exn;
00681 }
00682 
00683 unsigned ResumeInst::getNumSuccessorsV() const {
00684   return getNumSuccessors();
00685 }
00686 
00687 void ResumeInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
00688   llvm_unreachable("ResumeInst has no successors!");
00689 }
00690 
00691 BasicBlock *ResumeInst::getSuccessorV(unsigned idx) const {
00692   llvm_unreachable("ResumeInst has no successors!");
00693 }
00694 
00695 //===----------------------------------------------------------------------===//
00696 //                      UnreachableInst Implementation
00697 //===----------------------------------------------------------------------===//
00698 
00699 UnreachableInst::UnreachableInst(LLVMContext &Context, 
00700                                  Instruction *InsertBefore)
00701   : TerminatorInst(Type::getVoidTy(Context), Instruction::Unreachable,
00702                    nullptr, 0, InsertBefore) {
00703 }
00704 UnreachableInst::UnreachableInst(LLVMContext &Context, BasicBlock *InsertAtEnd)
00705   : TerminatorInst(Type::getVoidTy(Context), Instruction::Unreachable,
00706                    nullptr, 0, InsertAtEnd) {
00707 }
00708 
00709 unsigned UnreachableInst::getNumSuccessorsV() const {
00710   return getNumSuccessors();
00711 }
00712 
00713 void UnreachableInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
00714   llvm_unreachable("UnreachableInst has no successors!");
00715 }
00716 
00717 BasicBlock *UnreachableInst::getSuccessorV(unsigned idx) const {
00718   llvm_unreachable("UnreachableInst has no successors!");
00719 }
00720 
00721 //===----------------------------------------------------------------------===//
00722 //                        BranchInst Implementation
00723 //===----------------------------------------------------------------------===//
00724 
00725 void BranchInst::AssertOK() {
00726   if (isConditional())
00727     assert(getCondition()->getType()->isIntegerTy(1) &&
00728            "May only branch on boolean predicates!");
00729 }
00730 
00731 BranchInst::BranchInst(BasicBlock *IfTrue, Instruction *InsertBefore)
00732   : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
00733                    OperandTraits<BranchInst>::op_end(this) - 1,
00734                    1, InsertBefore) {
00735   assert(IfTrue && "Branch destination may not be null!");
00736   Op<-1>() = IfTrue;
00737 }
00738 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
00739                        Instruction *InsertBefore)
00740   : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
00741                    OperandTraits<BranchInst>::op_end(this) - 3,
00742                    3, InsertBefore) {
00743   Op<-1>() = IfTrue;
00744   Op<-2>() = IfFalse;
00745   Op<-3>() = Cond;
00746 #ifndef NDEBUG
00747   AssertOK();
00748 #endif
00749 }
00750 
00751 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *InsertAtEnd)
00752   : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
00753                    OperandTraits<BranchInst>::op_end(this) - 1,
00754                    1, InsertAtEnd) {
00755   assert(IfTrue && "Branch destination may not be null!");
00756   Op<-1>() = IfTrue;
00757 }
00758 
00759 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
00760            BasicBlock *InsertAtEnd)
00761   : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
00762                    OperandTraits<BranchInst>::op_end(this) - 3,
00763                    3, InsertAtEnd) {
00764   Op<-1>() = IfTrue;
00765   Op<-2>() = IfFalse;
00766   Op<-3>() = Cond;
00767 #ifndef NDEBUG
00768   AssertOK();
00769 #endif
00770 }
00771 
00772 
00773 BranchInst::BranchInst(const BranchInst &BI) :
00774   TerminatorInst(Type::getVoidTy(BI.getContext()), Instruction::Br,
00775                  OperandTraits<BranchInst>::op_end(this) - BI.getNumOperands(),
00776                  BI.getNumOperands()) {
00777   Op<-1>() = BI.Op<-1>();
00778   if (BI.getNumOperands() != 1) {
00779     assert(BI.getNumOperands() == 3 && "BR can have 1 or 3 operands!");
00780     Op<-3>() = BI.Op<-3>();
00781     Op<-2>() = BI.Op<-2>();
00782   }
00783   SubclassOptionalData = BI.SubclassOptionalData;
00784 }
00785 
00786 void BranchInst::swapSuccessors() {
00787   assert(isConditional() &&
00788          "Cannot swap successors of an unconditional branch");
00789   Op<-1>().swap(Op<-2>());
00790 
00791   // Update profile metadata if present and it matches our structural
00792   // expectations.
00793   MDNode *ProfileData = getMetadata(LLVMContext::MD_prof);
00794   if (!ProfileData || ProfileData->getNumOperands() != 3)
00795     return;
00796 
00797   // The first operand is the name. Fetch them backwards and build a new one.
00798   Value *Ops[] = {
00799     ProfileData->getOperand(0),
00800     ProfileData->getOperand(2),
00801     ProfileData->getOperand(1)
00802   };
00803   setMetadata(LLVMContext::MD_prof,
00804               MDNode::get(ProfileData->getContext(), Ops));
00805 }
00806 
00807 BasicBlock *BranchInst::getSuccessorV(unsigned idx) const {
00808   return getSuccessor(idx);
00809 }
00810 unsigned BranchInst::getNumSuccessorsV() const {
00811   return getNumSuccessors();
00812 }
00813 void BranchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
00814   setSuccessor(idx, B);
00815 }
00816 
00817 
00818 //===----------------------------------------------------------------------===//
00819 //                        AllocaInst Implementation
00820 //===----------------------------------------------------------------------===//
00821 
00822 static Value *getAISize(LLVMContext &Context, Value *Amt) {
00823   if (!Amt)
00824     Amt = ConstantInt::get(Type::getInt32Ty(Context), 1);
00825   else {
00826     assert(!isa<BasicBlock>(Amt) &&
00827            "Passed basic block into allocation size parameter! Use other ctor");
00828     assert(Amt->getType()->isIntegerTy() &&
00829            "Allocation array size is not an integer!");
00830   }
00831   return Amt;
00832 }
00833 
00834 AllocaInst::AllocaInst(Type *Ty, Value *ArraySize,
00835                        const Twine &Name, Instruction *InsertBefore)
00836   : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
00837                      getAISize(Ty->getContext(), ArraySize), InsertBefore) {
00838   setAlignment(0);
00839   assert(!Ty->isVoidTy() && "Cannot allocate void!");
00840   setName(Name);
00841 }
00842 
00843 AllocaInst::AllocaInst(Type *Ty, Value *ArraySize,
00844                        const Twine &Name, BasicBlock *InsertAtEnd)
00845   : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
00846                      getAISize(Ty->getContext(), ArraySize), InsertAtEnd) {
00847   setAlignment(0);
00848   assert(!Ty->isVoidTy() && "Cannot allocate void!");
00849   setName(Name);
00850 }
00851 
00852 AllocaInst::AllocaInst(Type *Ty, const Twine &Name,
00853                        Instruction *InsertBefore)
00854   : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
00855                      getAISize(Ty->getContext(), nullptr), InsertBefore) {
00856   setAlignment(0);
00857   assert(!Ty->isVoidTy() && "Cannot allocate void!");
00858   setName(Name);
00859 }
00860 
00861 AllocaInst::AllocaInst(Type *Ty, const Twine &Name,
00862                        BasicBlock *InsertAtEnd)
00863   : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
00864                      getAISize(Ty->getContext(), nullptr), InsertAtEnd) {
00865   setAlignment(0);
00866   assert(!Ty->isVoidTy() && "Cannot allocate void!");
00867   setName(Name);
00868 }
00869 
00870 AllocaInst::AllocaInst(Type *Ty, Value *ArraySize, unsigned Align,
00871                        const Twine &Name, Instruction *InsertBefore)
00872   : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
00873                      getAISize(Ty->getContext(), ArraySize), InsertBefore) {
00874   setAlignment(Align);
00875   assert(!Ty->isVoidTy() && "Cannot allocate void!");
00876   setName(Name);
00877 }
00878 
00879 AllocaInst::AllocaInst(Type *Ty, Value *ArraySize, unsigned Align,
00880                        const Twine &Name, BasicBlock *InsertAtEnd)
00881   : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
00882                      getAISize(Ty->getContext(), ArraySize), InsertAtEnd) {
00883   setAlignment(Align);
00884   assert(!Ty->isVoidTy() && "Cannot allocate void!");
00885   setName(Name);
00886 }
00887 
00888 // Out of line virtual method, so the vtable, etc has a home.
00889 AllocaInst::~AllocaInst() {
00890 }
00891 
00892 void AllocaInst::setAlignment(unsigned Align) {
00893   assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
00894   assert(Align <= MaximumAlignment &&
00895          "Alignment is greater than MaximumAlignment!");
00896   setInstructionSubclassData((getSubclassDataFromInstruction() & ~31) |
00897                              (Log2_32(Align) + 1));
00898   assert(getAlignment() == Align && "Alignment representation error!");
00899 }
00900 
00901 bool AllocaInst::isArrayAllocation() const {
00902   if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(0)))
00903     return !CI->isOne();
00904   return true;
00905 }
00906 
00907 Type *AllocaInst::getAllocatedType() const {
00908   return getType()->getElementType();
00909 }
00910 
00911 /// isStaticAlloca - Return true if this alloca is in the entry block of the
00912 /// function and is a constant size.  If so, the code generator will fold it
00913 /// into the prolog/epilog code, so it is basically free.
00914 bool AllocaInst::isStaticAlloca() const {
00915   // Must be constant size.
00916   if (!isa<ConstantInt>(getArraySize())) return false;
00917   
00918   // Must be in the entry block.
00919   const BasicBlock *Parent = getParent();
00920   return Parent == &Parent->getParent()->front() && !isUsedWithInAlloca();
00921 }
00922 
00923 //===----------------------------------------------------------------------===//
00924 //                           LoadInst Implementation
00925 //===----------------------------------------------------------------------===//
00926 
00927 void LoadInst::AssertOK() {
00928   assert(getOperand(0)->getType()->isPointerTy() &&
00929          "Ptr must have pointer type.");
00930   assert(!(isAtomic() && getAlignment() == 0) &&
00931          "Alignment required for atomic load");
00932 }
00933 
00934 LoadInst::LoadInst(Value *Ptr, const Twine &Name, Instruction *InsertBef)
00935   : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
00936                      Load, Ptr, InsertBef) {
00937   setVolatile(false);
00938   setAlignment(0);
00939   setAtomic(NotAtomic);
00940   AssertOK();
00941   setName(Name);
00942 }
00943 
00944 LoadInst::LoadInst(Value *Ptr, const Twine &Name, BasicBlock *InsertAE)
00945   : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
00946                      Load, Ptr, InsertAE) {
00947   setVolatile(false);
00948   setAlignment(0);
00949   setAtomic(NotAtomic);
00950   AssertOK();
00951   setName(Name);
00952 }
00953 
00954 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
00955                    Instruction *InsertBef)
00956   : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
00957                      Load, Ptr, InsertBef) {
00958   setVolatile(isVolatile);
00959   setAlignment(0);
00960   setAtomic(NotAtomic);
00961   AssertOK();
00962   setName(Name);
00963 }
00964 
00965 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
00966                    BasicBlock *InsertAE)
00967   : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
00968                      Load, Ptr, InsertAE) {
00969   setVolatile(isVolatile);
00970   setAlignment(0);
00971   setAtomic(NotAtomic);
00972   AssertOK();
00973   setName(Name);
00974 }
00975 
00976 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile, 
00977                    unsigned Align, Instruction *InsertBef)
00978   : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
00979                      Load, Ptr, InsertBef) {
00980   setVolatile(isVolatile);
00981   setAlignment(Align);
00982   setAtomic(NotAtomic);
00983   AssertOK();
00984   setName(Name);
00985 }
00986 
00987 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile, 
00988                    unsigned Align, BasicBlock *InsertAE)
00989   : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
00990                      Load, Ptr, InsertAE) {
00991   setVolatile(isVolatile);
00992   setAlignment(Align);
00993   setAtomic(NotAtomic);
00994   AssertOK();
00995   setName(Name);
00996 }
00997 
00998 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile, 
00999                    unsigned Align, AtomicOrdering Order,
01000                    SynchronizationScope SynchScope,
01001                    Instruction *InsertBef)
01002   : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
01003                      Load, Ptr, InsertBef) {
01004   setVolatile(isVolatile);
01005   setAlignment(Align);
01006   setAtomic(Order, SynchScope);
01007   AssertOK();
01008   setName(Name);
01009 }
01010 
01011 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile, 
01012                    unsigned Align, AtomicOrdering Order,
01013                    SynchronizationScope SynchScope,
01014                    BasicBlock *InsertAE)
01015   : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
01016                      Load, Ptr, InsertAE) {
01017   setVolatile(isVolatile);
01018   setAlignment(Align);
01019   setAtomic(Order, SynchScope);
01020   AssertOK();
01021   setName(Name);
01022 }
01023 
01024 LoadInst::LoadInst(Value *Ptr, const char *Name, Instruction *InsertBef)
01025   : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
01026                      Load, Ptr, InsertBef) {
01027   setVolatile(false);
01028   setAlignment(0);
01029   setAtomic(NotAtomic);
01030   AssertOK();
01031   if (Name && Name[0]) setName(Name);
01032 }
01033 
01034 LoadInst::LoadInst(Value *Ptr, const char *Name, BasicBlock *InsertAE)
01035   : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
01036                      Load, Ptr, InsertAE) {
01037   setVolatile(false);
01038   setAlignment(0);
01039   setAtomic(NotAtomic);
01040   AssertOK();
01041   if (Name && Name[0]) setName(Name);
01042 }
01043 
01044 LoadInst::LoadInst(Value *Ptr, const char *Name, bool isVolatile,
01045                    Instruction *InsertBef)
01046 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
01047                    Load, Ptr, InsertBef) {
01048   setVolatile(isVolatile);
01049   setAlignment(0);
01050   setAtomic(NotAtomic);
01051   AssertOK();
01052   if (Name && Name[0]) setName(Name);
01053 }
01054 
01055 LoadInst::LoadInst(Value *Ptr, const char *Name, bool isVolatile,
01056                    BasicBlock *InsertAE)
01057   : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
01058                      Load, Ptr, InsertAE) {
01059   setVolatile(isVolatile);
01060   setAlignment(0);
01061   setAtomic(NotAtomic);
01062   AssertOK();
01063   if (Name && Name[0]) setName(Name);
01064 }
01065 
01066 void LoadInst::setAlignment(unsigned Align) {
01067   assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
01068   assert(Align <= MaximumAlignment &&
01069          "Alignment is greater than MaximumAlignment!");
01070   setInstructionSubclassData((getSubclassDataFromInstruction() & ~(31 << 1)) |
01071                              ((Log2_32(Align)+1)<<1));
01072   assert(getAlignment() == Align && "Alignment representation error!");
01073 }
01074 
01075 //===----------------------------------------------------------------------===//
01076 //                           StoreInst Implementation
01077 //===----------------------------------------------------------------------===//
01078 
01079 void StoreInst::AssertOK() {
01080   assert(getOperand(0) && getOperand(1) && "Both operands must be non-null!");
01081   assert(getOperand(1)->getType()->isPointerTy() &&
01082          "Ptr must have pointer type!");
01083   assert(getOperand(0)->getType() ==
01084                  cast<PointerType>(getOperand(1)->getType())->getElementType()
01085          && "Ptr must be a pointer to Val type!");
01086   assert(!(isAtomic() && getAlignment() == 0) &&
01087          "Alignment required for atomic store");
01088 }
01089 
01090 
01091 StoreInst::StoreInst(Value *val, Value *addr, Instruction *InsertBefore)
01092   : Instruction(Type::getVoidTy(val->getContext()), Store,
01093                 OperandTraits<StoreInst>::op_begin(this),
01094                 OperandTraits<StoreInst>::operands(this),
01095                 InsertBefore) {
01096   Op<0>() = val;
01097   Op<1>() = addr;
01098   setVolatile(false);
01099   setAlignment(0);
01100   setAtomic(NotAtomic);
01101   AssertOK();
01102 }
01103 
01104 StoreInst::StoreInst(Value *val, Value *addr, BasicBlock *InsertAtEnd)
01105   : Instruction(Type::getVoidTy(val->getContext()), Store,
01106                 OperandTraits<StoreInst>::op_begin(this),
01107                 OperandTraits<StoreInst>::operands(this),
01108                 InsertAtEnd) {
01109   Op<0>() = val;
01110   Op<1>() = addr;
01111   setVolatile(false);
01112   setAlignment(0);
01113   setAtomic(NotAtomic);
01114   AssertOK();
01115 }
01116 
01117 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
01118                      Instruction *InsertBefore)
01119   : Instruction(Type::getVoidTy(val->getContext()), Store,
01120                 OperandTraits<StoreInst>::op_begin(this),
01121                 OperandTraits<StoreInst>::operands(this),
01122                 InsertBefore) {
01123   Op<0>() = val;
01124   Op<1>() = addr;
01125   setVolatile(isVolatile);
01126   setAlignment(0);
01127   setAtomic(NotAtomic);
01128   AssertOK();
01129 }
01130 
01131 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
01132                      unsigned Align, Instruction *InsertBefore)
01133   : Instruction(Type::getVoidTy(val->getContext()), Store,
01134                 OperandTraits<StoreInst>::op_begin(this),
01135                 OperandTraits<StoreInst>::operands(this),
01136                 InsertBefore) {
01137   Op<0>() = val;
01138   Op<1>() = addr;
01139   setVolatile(isVolatile);
01140   setAlignment(Align);
01141   setAtomic(NotAtomic);
01142   AssertOK();
01143 }
01144 
01145 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
01146                      unsigned Align, AtomicOrdering Order,
01147                      SynchronizationScope SynchScope,
01148                      Instruction *InsertBefore)
01149   : Instruction(Type::getVoidTy(val->getContext()), Store,
01150                 OperandTraits<StoreInst>::op_begin(this),
01151                 OperandTraits<StoreInst>::operands(this),
01152                 InsertBefore) {
01153   Op<0>() = val;
01154   Op<1>() = addr;
01155   setVolatile(isVolatile);
01156   setAlignment(Align);
01157   setAtomic(Order, SynchScope);
01158   AssertOK();
01159 }
01160 
01161 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
01162                      BasicBlock *InsertAtEnd)
01163   : Instruction(Type::getVoidTy(val->getContext()), Store,
01164                 OperandTraits<StoreInst>::op_begin(this),
01165                 OperandTraits<StoreInst>::operands(this),
01166                 InsertAtEnd) {
01167   Op<0>() = val;
01168   Op<1>() = addr;
01169   setVolatile(isVolatile);
01170   setAlignment(0);
01171   setAtomic(NotAtomic);
01172   AssertOK();
01173 }
01174 
01175 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
01176                      unsigned Align, BasicBlock *InsertAtEnd)
01177   : Instruction(Type::getVoidTy(val->getContext()), Store,
01178                 OperandTraits<StoreInst>::op_begin(this),
01179                 OperandTraits<StoreInst>::operands(this),
01180                 InsertAtEnd) {
01181   Op<0>() = val;
01182   Op<1>() = addr;
01183   setVolatile(isVolatile);
01184   setAlignment(Align);
01185   setAtomic(NotAtomic);
01186   AssertOK();
01187 }
01188 
01189 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
01190                      unsigned Align, AtomicOrdering Order,
01191                      SynchronizationScope SynchScope,
01192                      BasicBlock *InsertAtEnd)
01193   : Instruction(Type::getVoidTy(val->getContext()), Store,
01194                 OperandTraits<StoreInst>::op_begin(this),
01195                 OperandTraits<StoreInst>::operands(this),
01196                 InsertAtEnd) {
01197   Op<0>() = val;
01198   Op<1>() = addr;
01199   setVolatile(isVolatile);
01200   setAlignment(Align);
01201   setAtomic(Order, SynchScope);
01202   AssertOK();
01203 }
01204 
01205 void StoreInst::setAlignment(unsigned Align) {
01206   assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
01207   assert(Align <= MaximumAlignment &&
01208          "Alignment is greater than MaximumAlignment!");
01209   setInstructionSubclassData((getSubclassDataFromInstruction() & ~(31 << 1)) |
01210                              ((Log2_32(Align)+1) << 1));
01211   assert(getAlignment() == Align && "Alignment representation error!");
01212 }
01213 
01214 //===----------------------------------------------------------------------===//
01215 //                       AtomicCmpXchgInst Implementation
01216 //===----------------------------------------------------------------------===//
01217 
01218 void AtomicCmpXchgInst::Init(Value *Ptr, Value *Cmp, Value *NewVal,
01219                              AtomicOrdering SuccessOrdering,
01220                              AtomicOrdering FailureOrdering,
01221                              SynchronizationScope SynchScope) {
01222   Op<0>() = Ptr;
01223   Op<1>() = Cmp;
01224   Op<2>() = NewVal;
01225   setSuccessOrdering(SuccessOrdering);
01226   setFailureOrdering(FailureOrdering);
01227   setSynchScope(SynchScope);
01228 
01229   assert(getOperand(0) && getOperand(1) && getOperand(2) &&
01230          "All operands must be non-null!");
01231   assert(getOperand(0)->getType()->isPointerTy() &&
01232          "Ptr must have pointer type!");
01233   assert(getOperand(1)->getType() ==
01234                  cast<PointerType>(getOperand(0)->getType())->getElementType()
01235          && "Ptr must be a pointer to Cmp type!");
01236   assert(getOperand(2)->getType() ==
01237                  cast<PointerType>(getOperand(0)->getType())->getElementType()
01238          && "Ptr must be a pointer to NewVal type!");
01239   assert(SuccessOrdering != NotAtomic &&
01240          "AtomicCmpXchg instructions must be atomic!");
01241   assert(FailureOrdering != NotAtomic &&
01242          "AtomicCmpXchg instructions must be atomic!");
01243   assert(SuccessOrdering >= FailureOrdering &&
01244          "AtomicCmpXchg success ordering must be at least as strong as fail");
01245   assert(FailureOrdering != Release && FailureOrdering != AcquireRelease &&
01246          "AtomicCmpXchg failure ordering cannot include release semantics");
01247 }
01248 
01249 AtomicCmpXchgInst::AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal,
01250                                      AtomicOrdering SuccessOrdering,
01251                                      AtomicOrdering FailureOrdering,
01252                                      SynchronizationScope SynchScope,
01253                                      Instruction *InsertBefore)
01254   : Instruction(Cmp->getType(), AtomicCmpXchg,
01255                 OperandTraits<AtomicCmpXchgInst>::op_begin(this),
01256                 OperandTraits<AtomicCmpXchgInst>::operands(this),
01257                 InsertBefore) {
01258   Init(Ptr, Cmp, NewVal, SuccessOrdering, FailureOrdering, SynchScope);
01259 }
01260 
01261 AtomicCmpXchgInst::AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal,
01262                                      AtomicOrdering SuccessOrdering,
01263                                      AtomicOrdering FailureOrdering,
01264                                      SynchronizationScope SynchScope,
01265                                      BasicBlock *InsertAtEnd)
01266   : Instruction(Cmp->getType(), AtomicCmpXchg,
01267                 OperandTraits<AtomicCmpXchgInst>::op_begin(this),
01268                 OperandTraits<AtomicCmpXchgInst>::operands(this),
01269                 InsertAtEnd) {
01270   Init(Ptr, Cmp, NewVal, SuccessOrdering, FailureOrdering, SynchScope);
01271 }
01272  
01273 //===----------------------------------------------------------------------===//
01274 //                       AtomicRMWInst Implementation
01275 //===----------------------------------------------------------------------===//
01276 
01277 void AtomicRMWInst::Init(BinOp Operation, Value *Ptr, Value *Val,
01278                          AtomicOrdering Ordering,
01279                          SynchronizationScope SynchScope) {
01280   Op<0>() = Ptr;
01281   Op<1>() = Val;
01282   setOperation(Operation);
01283   setOrdering(Ordering);
01284   setSynchScope(SynchScope);
01285 
01286   assert(getOperand(0) && getOperand(1) &&
01287          "All operands must be non-null!");
01288   assert(getOperand(0)->getType()->isPointerTy() &&
01289          "Ptr must have pointer type!");
01290   assert(getOperand(1)->getType() ==
01291          cast<PointerType>(getOperand(0)->getType())->getElementType()
01292          && "Ptr must be a pointer to Val type!");
01293   assert(Ordering != NotAtomic &&
01294          "AtomicRMW instructions must be atomic!");
01295 }
01296 
01297 AtomicRMWInst::AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val,
01298                              AtomicOrdering Ordering,
01299                              SynchronizationScope SynchScope,
01300                              Instruction *InsertBefore)
01301   : Instruction(Val->getType(), AtomicRMW,
01302                 OperandTraits<AtomicRMWInst>::op_begin(this),
01303                 OperandTraits<AtomicRMWInst>::operands(this),
01304                 InsertBefore) {
01305   Init(Operation, Ptr, Val, Ordering, SynchScope);
01306 }
01307 
01308 AtomicRMWInst::AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val,
01309                              AtomicOrdering Ordering,
01310                              SynchronizationScope SynchScope,
01311                              BasicBlock *InsertAtEnd)
01312   : Instruction(Val->getType(), AtomicRMW,
01313                 OperandTraits<AtomicRMWInst>::op_begin(this),
01314                 OperandTraits<AtomicRMWInst>::operands(this),
01315                 InsertAtEnd) {
01316   Init(Operation, Ptr, Val, Ordering, SynchScope);
01317 }
01318 
01319 //===----------------------------------------------------------------------===//
01320 //                       FenceInst Implementation
01321 //===----------------------------------------------------------------------===//
01322 
01323 FenceInst::FenceInst(LLVMContext &C, AtomicOrdering Ordering, 
01324                      SynchronizationScope SynchScope,
01325                      Instruction *InsertBefore)
01326   : Instruction(Type::getVoidTy(C), Fence, nullptr, 0, InsertBefore) {
01327   setOrdering(Ordering);
01328   setSynchScope(SynchScope);
01329 }
01330 
01331 FenceInst::FenceInst(LLVMContext &C, AtomicOrdering Ordering, 
01332                      SynchronizationScope SynchScope,
01333                      BasicBlock *InsertAtEnd)
01334   : Instruction(Type::getVoidTy(C), Fence, nullptr, 0, InsertAtEnd) {
01335   setOrdering(Ordering);
01336   setSynchScope(SynchScope);
01337 }
01338 
01339 //===----------------------------------------------------------------------===//
01340 //                       GetElementPtrInst Implementation
01341 //===----------------------------------------------------------------------===//
01342 
01343 void GetElementPtrInst::init(Value *Ptr, ArrayRef<Value *> IdxList,
01344                              const Twine &Name) {
01345   assert(NumOperands == 1 + IdxList.size() && "NumOperands not initialized?");
01346   OperandList[0] = Ptr;
01347   std::copy(IdxList.begin(), IdxList.end(), op_begin() + 1);
01348   setName(Name);
01349 }
01350 
01351 GetElementPtrInst::GetElementPtrInst(const GetElementPtrInst &GEPI)
01352   : Instruction(GEPI.getType(), GetElementPtr,
01353                 OperandTraits<GetElementPtrInst>::op_end(this)
01354                 - GEPI.getNumOperands(),
01355                 GEPI.getNumOperands()) {
01356   std::copy(GEPI.op_begin(), GEPI.op_end(), op_begin());
01357   SubclassOptionalData = GEPI.SubclassOptionalData;
01358 }
01359 
01360 /// getIndexedType - Returns the type of the element that would be accessed with
01361 /// a gep instruction with the specified parameters.
01362 ///
01363 /// The Idxs pointer should point to a continuous piece of memory containing the
01364 /// indices, either as Value* or uint64_t.
01365 ///
01366 /// A null type is returned if the indices are invalid for the specified
01367 /// pointer type.
01368 ///
01369 template <typename IndexTy>
01370 static Type *getIndexedTypeInternal(Type *Ptr, ArrayRef<IndexTy> IdxList) {
01371   PointerType *PTy = dyn_cast<PointerType>(Ptr->getScalarType());
01372   if (!PTy) return nullptr;   // Type isn't a pointer type!
01373   Type *Agg = PTy->getElementType();
01374 
01375   // Handle the special case of the empty set index set, which is always valid.
01376   if (IdxList.empty())
01377     return Agg;
01378 
01379   // If there is at least one index, the top level type must be sized, otherwise
01380   // it cannot be 'stepped over'.
01381   if (!Agg->isSized())
01382     return nullptr;
01383 
01384   unsigned CurIdx = 1;
01385   for (; CurIdx != IdxList.size(); ++CurIdx) {
01386     CompositeType *CT = dyn_cast<CompositeType>(Agg);
01387     if (!CT || CT->isPointerTy()) return nullptr;
01388     IndexTy Index = IdxList[CurIdx];
01389     if (!CT->indexValid(Index)) return nullptr;
01390     Agg = CT->getTypeAtIndex(Index);
01391   }
01392   return CurIdx == IdxList.size() ? Agg : nullptr;
01393 }
01394 
01395 Type *GetElementPtrInst::getIndexedType(Type *Ptr, ArrayRef<Value *> IdxList) {
01396   return getIndexedTypeInternal(Ptr, IdxList);
01397 }
01398 
01399 Type *GetElementPtrInst::getIndexedType(Type *Ptr,
01400                                         ArrayRef<Constant *> IdxList) {
01401   return getIndexedTypeInternal(Ptr, IdxList);
01402 }
01403 
01404 Type *GetElementPtrInst::getIndexedType(Type *Ptr, ArrayRef<uint64_t> IdxList) {
01405   return getIndexedTypeInternal(Ptr, IdxList);
01406 }
01407 
01408 /// hasAllZeroIndices - Return true if all of the indices of this GEP are
01409 /// zeros.  If so, the result pointer and the first operand have the same
01410 /// value, just potentially different types.
01411 bool GetElementPtrInst::hasAllZeroIndices() const {
01412   for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
01413     if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(i))) {
01414       if (!CI->isZero()) return false;
01415     } else {
01416       return false;
01417     }
01418   }
01419   return true;
01420 }
01421 
01422 /// hasAllConstantIndices - Return true if all of the indices of this GEP are
01423 /// constant integers.  If so, the result pointer and the first operand have
01424 /// a constant offset between them.
01425 bool GetElementPtrInst::hasAllConstantIndices() const {
01426   for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
01427     if (!isa<ConstantInt>(getOperand(i)))
01428       return false;
01429   }
01430   return true;
01431 }
01432 
01433 void GetElementPtrInst::setIsInBounds(bool B) {
01434   cast<GEPOperator>(this)->setIsInBounds(B);
01435 }
01436 
01437 bool GetElementPtrInst::isInBounds() const {
01438   return cast<GEPOperator>(this)->isInBounds();
01439 }
01440 
01441 bool GetElementPtrInst::accumulateConstantOffset(const DataLayout &DL,
01442                                                  APInt &Offset) const {
01443   // Delegate to the generic GEPOperator implementation.
01444   return cast<GEPOperator>(this)->accumulateConstantOffset(DL, Offset);
01445 }
01446 
01447 //===----------------------------------------------------------------------===//
01448 //                           ExtractElementInst Implementation
01449 //===----------------------------------------------------------------------===//
01450 
01451 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
01452                                        const Twine &Name,
01453                                        Instruction *InsertBef)
01454   : Instruction(cast<VectorType>(Val->getType())->getElementType(),
01455                 ExtractElement,
01456                 OperandTraits<ExtractElementInst>::op_begin(this),
01457                 2, InsertBef) {
01458   assert(isValidOperands(Val, Index) &&
01459          "Invalid extractelement instruction operands!");
01460   Op<0>() = Val;
01461   Op<1>() = Index;
01462   setName(Name);
01463 }
01464 
01465 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
01466                                        const Twine &Name,
01467                                        BasicBlock *InsertAE)
01468   : Instruction(cast<VectorType>(Val->getType())->getElementType(),
01469                 ExtractElement,
01470                 OperandTraits<ExtractElementInst>::op_begin(this),
01471                 2, InsertAE) {
01472   assert(isValidOperands(Val, Index) &&
01473          "Invalid extractelement instruction operands!");
01474 
01475   Op<0>() = Val;
01476   Op<1>() = Index;
01477   setName(Name);
01478 }
01479 
01480 
01481 bool ExtractElementInst::isValidOperands(const Value *Val, const Value *Index) {
01482   if (!Val->getType()->isVectorTy() || !Index->getType()->isIntegerTy(32))
01483     return false;
01484   return true;
01485 }
01486 
01487 
01488 //===----------------------------------------------------------------------===//
01489 //                           InsertElementInst Implementation
01490 //===----------------------------------------------------------------------===//
01491 
01492 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
01493                                      const Twine &Name,
01494                                      Instruction *InsertBef)
01495   : Instruction(Vec->getType(), InsertElement,
01496                 OperandTraits<InsertElementInst>::op_begin(this),
01497                 3, InsertBef) {
01498   assert(isValidOperands(Vec, Elt, Index) &&
01499          "Invalid insertelement instruction operands!");
01500   Op<0>() = Vec;
01501   Op<1>() = Elt;
01502   Op<2>() = Index;
01503   setName(Name);
01504 }
01505 
01506 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
01507                                      const Twine &Name,
01508                                      BasicBlock *InsertAE)
01509   : Instruction(Vec->getType(), InsertElement,
01510                 OperandTraits<InsertElementInst>::op_begin(this),
01511                 3, InsertAE) {
01512   assert(isValidOperands(Vec, Elt, Index) &&
01513          "Invalid insertelement instruction operands!");
01514 
01515   Op<0>() = Vec;
01516   Op<1>() = Elt;
01517   Op<2>() = Index;
01518   setName(Name);
01519 }
01520 
01521 bool InsertElementInst::isValidOperands(const Value *Vec, const Value *Elt, 
01522                                         const Value *Index) {
01523   if (!Vec->getType()->isVectorTy())
01524     return false;   // First operand of insertelement must be vector type.
01525   
01526   if (Elt->getType() != cast<VectorType>(Vec->getType())->getElementType())
01527     return false;// Second operand of insertelement must be vector element type.
01528     
01529   if (!Index->getType()->isIntegerTy(32))
01530     return false;  // Third operand of insertelement must be i32.
01531   return true;
01532 }
01533 
01534 
01535 //===----------------------------------------------------------------------===//
01536 //                      ShuffleVectorInst Implementation
01537 //===----------------------------------------------------------------------===//
01538 
01539 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
01540                                      const Twine &Name,
01541                                      Instruction *InsertBefore)
01542 : Instruction(VectorType::get(cast<VectorType>(V1->getType())->getElementType(),
01543                 cast<VectorType>(Mask->getType())->getNumElements()),
01544               ShuffleVector,
01545               OperandTraits<ShuffleVectorInst>::op_begin(this),
01546               OperandTraits<ShuffleVectorInst>::operands(this),
01547               InsertBefore) {
01548   assert(isValidOperands(V1, V2, Mask) &&
01549          "Invalid shuffle vector instruction operands!");
01550   Op<0>() = V1;
01551   Op<1>() = V2;
01552   Op<2>() = Mask;
01553   setName(Name);
01554 }
01555 
01556 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
01557                                      const Twine &Name,
01558                                      BasicBlock *InsertAtEnd)
01559 : Instruction(VectorType::get(cast<VectorType>(V1->getType())->getElementType(),
01560                 cast<VectorType>(Mask->getType())->getNumElements()),
01561               ShuffleVector,
01562               OperandTraits<ShuffleVectorInst>::op_begin(this),
01563               OperandTraits<ShuffleVectorInst>::operands(this),
01564               InsertAtEnd) {
01565   assert(isValidOperands(V1, V2, Mask) &&
01566          "Invalid shuffle vector instruction operands!");
01567 
01568   Op<0>() = V1;
01569   Op<1>() = V2;
01570   Op<2>() = Mask;
01571   setName(Name);
01572 }
01573 
01574 bool ShuffleVectorInst::isValidOperands(const Value *V1, const Value *V2,
01575                                         const Value *Mask) {
01576   // V1 and V2 must be vectors of the same type.
01577   if (!V1->getType()->isVectorTy() || V1->getType() != V2->getType())
01578     return false;
01579   
01580   // Mask must be vector of i32.
01581   VectorType *MaskTy = dyn_cast<VectorType>(Mask->getType());
01582   if (!MaskTy || !MaskTy->getElementType()->isIntegerTy(32))
01583     return false;
01584 
01585   // Check to see if Mask is valid.
01586   if (isa<UndefValue>(Mask) || isa<ConstantAggregateZero>(Mask))
01587     return true;
01588 
01589   if (const ConstantVector *MV = dyn_cast<ConstantVector>(Mask)) {
01590     unsigned V1Size = cast<VectorType>(V1->getType())->getNumElements();
01591     for (Value *Op : MV->operands()) {
01592       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
01593         if (CI->uge(V1Size*2))
01594           return false;
01595       } else if (!isa<UndefValue>(Op)) {
01596         return false;
01597       }
01598     }
01599     return true;
01600   }
01601   
01602   if (const ConstantDataSequential *CDS =
01603         dyn_cast<ConstantDataSequential>(Mask)) {
01604     unsigned V1Size = cast<VectorType>(V1->getType())->getNumElements();
01605     for (unsigned i = 0, e = MaskTy->getNumElements(); i != e; ++i)
01606       if (CDS->getElementAsInteger(i) >= V1Size*2)
01607         return false;
01608     return true;
01609   }
01610   
01611   // The bitcode reader can create a place holder for a forward reference
01612   // used as the shuffle mask. When this occurs, the shuffle mask will
01613   // fall into this case and fail. To avoid this error, do this bit of
01614   // ugliness to allow such a mask pass.
01615   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(Mask))
01616     if (CE->getOpcode() == Instruction::UserOp1)
01617       return true;
01618 
01619   return false;
01620 }
01621 
01622 /// getMaskValue - Return the index from the shuffle mask for the specified
01623 /// output result.  This is either -1 if the element is undef or a number less
01624 /// than 2*numelements.
01625 int ShuffleVectorInst::getMaskValue(Constant *Mask, unsigned i) {
01626   assert(i < Mask->getType()->getVectorNumElements() && "Index out of range");
01627   if (ConstantDataSequential *CDS =dyn_cast<ConstantDataSequential>(Mask))
01628     return CDS->getElementAsInteger(i);
01629   Constant *C = Mask->getAggregateElement(i);
01630   if (isa<UndefValue>(C))
01631     return -1;
01632   return cast<ConstantInt>(C)->getZExtValue();
01633 }
01634 
01635 /// getShuffleMask - Return the full mask for this instruction, where each
01636 /// element is the element number and undef's are returned as -1.
01637 void ShuffleVectorInst::getShuffleMask(Constant *Mask,
01638                                        SmallVectorImpl<int> &Result) {
01639   unsigned NumElts = Mask->getType()->getVectorNumElements();
01640   
01641   if (ConstantDataSequential *CDS=dyn_cast<ConstantDataSequential>(Mask)) {
01642     for (unsigned i = 0; i != NumElts; ++i)
01643       Result.push_back(CDS->getElementAsInteger(i));
01644     return;
01645   }    
01646   for (unsigned i = 0; i != NumElts; ++i) {
01647     Constant *C = Mask->getAggregateElement(i);
01648     Result.push_back(isa<UndefValue>(C) ? -1 :
01649                      cast<ConstantInt>(C)->getZExtValue());
01650   }
01651 }
01652 
01653 
01654 //===----------------------------------------------------------------------===//
01655 //                             InsertValueInst Class
01656 //===----------------------------------------------------------------------===//
01657 
01658 void InsertValueInst::init(Value *Agg, Value *Val, ArrayRef<unsigned> Idxs, 
01659                            const Twine &Name) {
01660   assert(NumOperands == 2 && "NumOperands not initialized?");
01661 
01662   // There's no fundamental reason why we require at least one index
01663   // (other than weirdness with &*IdxBegin being invalid; see
01664   // getelementptr's init routine for example). But there's no
01665   // present need to support it.
01666   assert(Idxs.size() > 0 && "InsertValueInst must have at least one index");
01667 
01668   assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs) ==
01669          Val->getType() && "Inserted value must match indexed type!");
01670   Op<0>() = Agg;
01671   Op<1>() = Val;
01672 
01673   Indices.append(Idxs.begin(), Idxs.end());
01674   setName(Name);
01675 }
01676 
01677 InsertValueInst::InsertValueInst(const InsertValueInst &IVI)
01678   : Instruction(IVI.getType(), InsertValue,
01679                 OperandTraits<InsertValueInst>::op_begin(this), 2),
01680     Indices(IVI.Indices) {
01681   Op<0>() = IVI.getOperand(0);
01682   Op<1>() = IVI.getOperand(1);
01683   SubclassOptionalData = IVI.SubclassOptionalData;
01684 }
01685 
01686 //===----------------------------------------------------------------------===//
01687 //                             ExtractValueInst Class
01688 //===----------------------------------------------------------------------===//
01689 
01690 void ExtractValueInst::init(ArrayRef<unsigned> Idxs, const Twine &Name) {
01691   assert(NumOperands == 1 && "NumOperands not initialized?");
01692 
01693   // There's no fundamental reason why we require at least one index.
01694   // But there's no present need to support it.
01695   assert(Idxs.size() > 0 && "ExtractValueInst must have at least one index");
01696 
01697   Indices.append(Idxs.begin(), Idxs.end());
01698   setName(Name);
01699 }
01700 
01701 ExtractValueInst::ExtractValueInst(const ExtractValueInst &EVI)
01702   : UnaryInstruction(EVI.getType(), ExtractValue, EVI.getOperand(0)),
01703     Indices(EVI.Indices) {
01704   SubclassOptionalData = EVI.SubclassOptionalData;
01705 }
01706 
01707 // getIndexedType - Returns the type of the element that would be extracted
01708 // with an extractvalue instruction with the specified parameters.
01709 //
01710 // A null type is returned if the indices are invalid for the specified
01711 // pointer type.
01712 //
01713 Type *ExtractValueInst::getIndexedType(Type *Agg,
01714                                        ArrayRef<unsigned> Idxs) {
01715   for (unsigned Index : Idxs) {
01716     // We can't use CompositeType::indexValid(Index) here.
01717     // indexValid() always returns true for arrays because getelementptr allows
01718     // out-of-bounds indices. Since we don't allow those for extractvalue and
01719     // insertvalue we need to check array indexing manually.
01720     // Since the only other types we can index into are struct types it's just
01721     // as easy to check those manually as well.
01722     if (ArrayType *AT = dyn_cast<ArrayType>(Agg)) {
01723       if (Index >= AT->getNumElements())
01724         return nullptr;
01725     } else if (StructType *ST = dyn_cast<StructType>(Agg)) {
01726       if (Index >= ST->getNumElements())
01727         return nullptr;
01728     } else {
01729       // Not a valid type to index into.
01730       return nullptr;
01731     }
01732 
01733     Agg = cast<CompositeType>(Agg)->getTypeAtIndex(Index);
01734   }
01735   return const_cast<Type*>(Agg);
01736 }
01737 
01738 //===----------------------------------------------------------------------===//
01739 //                             BinaryOperator Class
01740 //===----------------------------------------------------------------------===//
01741 
01742 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
01743                                Type *Ty, const Twine &Name,
01744                                Instruction *InsertBefore)
01745   : Instruction(Ty, iType,
01746                 OperandTraits<BinaryOperator>::op_begin(this),
01747                 OperandTraits<BinaryOperator>::operands(this),
01748                 InsertBefore) {
01749   Op<0>() = S1;
01750   Op<1>() = S2;
01751   init(iType);
01752   setName(Name);
01753 }
01754 
01755 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2, 
01756                                Type *Ty, const Twine &Name,
01757                                BasicBlock *InsertAtEnd)
01758   : Instruction(Ty, iType,
01759                 OperandTraits<BinaryOperator>::op_begin(this),
01760                 OperandTraits<BinaryOperator>::operands(this),
01761                 InsertAtEnd) {
01762   Op<0>() = S1;
01763   Op<1>() = S2;
01764   init(iType);
01765   setName(Name);
01766 }
01767 
01768 
01769 void BinaryOperator::init(BinaryOps iType) {
01770   Value *LHS = getOperand(0), *RHS = getOperand(1);
01771   (void)LHS; (void)RHS; // Silence warnings.
01772   assert(LHS->getType() == RHS->getType() &&
01773          "Binary operator operand types must match!");
01774 #ifndef NDEBUG
01775   switch (iType) {
01776   case Add: case Sub:
01777   case Mul:
01778     assert(getType() == LHS->getType() &&
01779            "Arithmetic operation should return same type as operands!");
01780     assert(getType()->isIntOrIntVectorTy() &&
01781            "Tried to create an integer operation on a non-integer type!");
01782     break;
01783   case FAdd: case FSub:
01784   case FMul:
01785     assert(getType() == LHS->getType() &&
01786            "Arithmetic operation should return same type as operands!");
01787     assert(getType()->isFPOrFPVectorTy() &&
01788            "Tried to create a floating-point operation on a "
01789            "non-floating-point type!");
01790     break;
01791   case UDiv: 
01792   case SDiv: 
01793     assert(getType() == LHS->getType() &&
01794            "Arithmetic operation should return same type as operands!");
01795     assert((getType()->isIntegerTy() || (getType()->isVectorTy() && 
01796             cast<VectorType>(getType())->getElementType()->isIntegerTy())) &&
01797            "Incorrect operand type (not integer) for S/UDIV");
01798     break;
01799   case FDiv:
01800     assert(getType() == LHS->getType() &&
01801            "Arithmetic operation should return same type as operands!");
01802     assert(getType()->isFPOrFPVectorTy() &&
01803            "Incorrect operand type (not floating point) for FDIV");
01804     break;
01805   case URem: 
01806   case SRem: 
01807     assert(getType() == LHS->getType() &&
01808            "Arithmetic operation should return same type as operands!");
01809     assert((getType()->isIntegerTy() || (getType()->isVectorTy() && 
01810             cast<VectorType>(getType())->getElementType()->isIntegerTy())) &&
01811            "Incorrect operand type (not integer) for S/UREM");
01812     break;
01813   case FRem:
01814     assert(getType() == LHS->getType() &&
01815            "Arithmetic operation should return same type as operands!");
01816     assert(getType()->isFPOrFPVectorTy() &&
01817            "Incorrect operand type (not floating point) for FREM");
01818     break;
01819   case Shl:
01820   case LShr:
01821   case AShr:
01822     assert(getType() == LHS->getType() &&
01823            "Shift operation should return same type as operands!");
01824     assert((getType()->isIntegerTy() ||
01825             (getType()->isVectorTy() && 
01826              cast<VectorType>(getType())->getElementType()->isIntegerTy())) &&
01827            "Tried to create a shift operation on a non-integral type!");
01828     break;
01829   case And: case Or:
01830   case Xor:
01831     assert(getType() == LHS->getType() &&
01832            "Logical operation should return same type as operands!");
01833     assert((getType()->isIntegerTy() ||
01834             (getType()->isVectorTy() && 
01835              cast<VectorType>(getType())->getElementType()->isIntegerTy())) &&
01836            "Tried to create a logical operation on a non-integral type!");
01837     break;
01838   default:
01839     break;
01840   }
01841 #endif
01842 }
01843 
01844 BinaryOperator *BinaryOperator::Create(BinaryOps Op, Value *S1, Value *S2,
01845                                        const Twine &Name,
01846                                        Instruction *InsertBefore) {
01847   assert(S1->getType() == S2->getType() &&
01848          "Cannot create binary operator with two operands of differing type!");
01849   return new BinaryOperator(Op, S1, S2, S1->getType(), Name, InsertBefore);
01850 }
01851 
01852 BinaryOperator *BinaryOperator::Create(BinaryOps Op, Value *S1, Value *S2,
01853                                        const Twine &Name,
01854                                        BasicBlock *InsertAtEnd) {
01855   BinaryOperator *Res = Create(Op, S1, S2, Name);
01856   InsertAtEnd->getInstList().push_back(Res);
01857   return Res;
01858 }
01859 
01860 BinaryOperator *BinaryOperator::CreateNeg(Value *Op, const Twine &Name,
01861                                           Instruction *InsertBefore) {
01862   Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
01863   return new BinaryOperator(Instruction::Sub,
01864                             zero, Op,
01865                             Op->getType(), Name, InsertBefore);
01866 }
01867 
01868 BinaryOperator *BinaryOperator::CreateNeg(Value *Op, const Twine &Name,
01869                                           BasicBlock *InsertAtEnd) {
01870   Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
01871   return new BinaryOperator(Instruction::Sub,
01872                             zero, Op,
01873                             Op->getType(), Name, InsertAtEnd);
01874 }
01875 
01876 BinaryOperator *BinaryOperator::CreateNSWNeg(Value *Op, const Twine &Name,
01877                                              Instruction *InsertBefore) {
01878   Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
01879   return BinaryOperator::CreateNSWSub(zero, Op, Name, InsertBefore);
01880 }
01881 
01882 BinaryOperator *BinaryOperator::CreateNSWNeg(Value *Op, const Twine &Name,
01883                                              BasicBlock *InsertAtEnd) {
01884   Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
01885   return BinaryOperator::CreateNSWSub(zero, Op, Name, InsertAtEnd);
01886 }
01887 
01888 BinaryOperator *BinaryOperator::CreateNUWNeg(Value *Op, const Twine &Name,
01889                                              Instruction *InsertBefore) {
01890   Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
01891   return BinaryOperator::CreateNUWSub(zero, Op, Name, InsertBefore);
01892 }
01893 
01894 BinaryOperator *BinaryOperator::CreateNUWNeg(Value *Op, const Twine &Name,
01895                                              BasicBlock *InsertAtEnd) {
01896   Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
01897   return BinaryOperator::CreateNUWSub(zero, Op, Name, InsertAtEnd);
01898 }
01899 
01900 BinaryOperator *BinaryOperator::CreateFNeg(Value *Op, const Twine &Name,
01901                                            Instruction *InsertBefore) {
01902   Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
01903   return new BinaryOperator(Instruction::FSub, zero, Op,
01904                             Op->getType(), Name, InsertBefore);
01905 }
01906 
01907 BinaryOperator *BinaryOperator::CreateFNeg(Value *Op, const Twine &Name,
01908                                            BasicBlock *InsertAtEnd) {
01909   Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
01910   return new BinaryOperator(Instruction::FSub, zero, Op,
01911                             Op->getType(), Name, InsertAtEnd);
01912 }
01913 
01914 BinaryOperator *BinaryOperator::CreateNot(Value *Op, const Twine &Name,
01915                                           Instruction *InsertBefore) {
01916   Constant *C = Constant::getAllOnesValue(Op->getType());
01917   return new BinaryOperator(Instruction::Xor, Op, C,
01918                             Op->getType(), Name, InsertBefore);
01919 }
01920 
01921 BinaryOperator *BinaryOperator::CreateNot(Value *Op, const Twine &Name,
01922                                           BasicBlock *InsertAtEnd) {
01923   Constant *AllOnes = Constant::getAllOnesValue(Op->getType());
01924   return new BinaryOperator(Instruction::Xor, Op, AllOnes,
01925                             Op->getType(), Name, InsertAtEnd);
01926 }
01927 
01928 
01929 // isConstantAllOnes - Helper function for several functions below
01930 static inline bool isConstantAllOnes(const Value *V) {
01931   if (const Constant *C = dyn_cast<Constant>(V))
01932     return C->isAllOnesValue();
01933   return false;
01934 }
01935 
01936 bool BinaryOperator::isNeg(const Value *V) {
01937   if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
01938     if (Bop->getOpcode() == Instruction::Sub)
01939       if (Constant* C = dyn_cast<Constant>(Bop->getOperand(0)))
01940         return C->isNegativeZeroValue();
01941   return false;
01942 }
01943 
01944 bool BinaryOperator::isFNeg(const Value *V, bool IgnoreZeroSign) {
01945   if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
01946     if (Bop->getOpcode() == Instruction::FSub)
01947       if (Constant* C = dyn_cast<Constant>(Bop->getOperand(0))) {
01948         if (!IgnoreZeroSign)
01949           IgnoreZeroSign = cast<Instruction>(V)->hasNoSignedZeros();
01950         return !IgnoreZeroSign ? C->isNegativeZeroValue() : C->isZeroValue();
01951       }
01952   return false;
01953 }
01954 
01955 bool BinaryOperator::isNot(const Value *V) {
01956   if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
01957     return (Bop->getOpcode() == Instruction::Xor &&
01958             (isConstantAllOnes(Bop->getOperand(1)) ||
01959              isConstantAllOnes(Bop->getOperand(0))));
01960   return false;
01961 }
01962 
01963 Value *BinaryOperator::getNegArgument(Value *BinOp) {
01964   return cast<BinaryOperator>(BinOp)->getOperand(1);
01965 }
01966 
01967 const Value *BinaryOperator::getNegArgument(const Value *BinOp) {
01968   return getNegArgument(const_cast<Value*>(BinOp));
01969 }
01970 
01971 Value *BinaryOperator::getFNegArgument(Value *BinOp) {
01972   return cast<BinaryOperator>(BinOp)->getOperand(1);
01973 }
01974 
01975 const Value *BinaryOperator::getFNegArgument(const Value *BinOp) {
01976   return getFNegArgument(const_cast<Value*>(BinOp));
01977 }
01978 
01979 Value *BinaryOperator::getNotArgument(Value *BinOp) {
01980   assert(isNot(BinOp) && "getNotArgument on non-'not' instruction!");
01981   BinaryOperator *BO = cast<BinaryOperator>(BinOp);
01982   Value *Op0 = BO->getOperand(0);
01983   Value *Op1 = BO->getOperand(1);
01984   if (isConstantAllOnes(Op0)) return Op1;
01985 
01986   assert(isConstantAllOnes(Op1));
01987   return Op0;
01988 }
01989 
01990 const Value *BinaryOperator::getNotArgument(const Value *BinOp) {
01991   return getNotArgument(const_cast<Value*>(BinOp));
01992 }
01993 
01994 
01995 // swapOperands - Exchange the two operands to this instruction.  This
01996 // instruction is safe to use on any binary instruction and does not
01997 // modify the semantics of the instruction.  If the instruction is
01998 // order dependent (SetLT f.e.) the opcode is changed.
01999 //
02000 bool BinaryOperator::swapOperands() {
02001   if (!isCommutative())
02002     return true; // Can't commute operands
02003   Op<0>().swap(Op<1>());
02004   return false;
02005 }
02006 
02007 void BinaryOperator::setHasNoUnsignedWrap(bool b) {
02008   cast<OverflowingBinaryOperator>(this)->setHasNoUnsignedWrap(b);
02009 }
02010 
02011 void BinaryOperator::setHasNoSignedWrap(bool b) {
02012   cast<OverflowingBinaryOperator>(this)->setHasNoSignedWrap(b);
02013 }
02014 
02015 void BinaryOperator::setIsExact(bool b) {
02016   cast<PossiblyExactOperator>(this)->setIsExact(b);
02017 }
02018 
02019 bool BinaryOperator::hasNoUnsignedWrap() const {
02020   return cast<OverflowingBinaryOperator>(this)->hasNoUnsignedWrap();
02021 }
02022 
02023 bool BinaryOperator::hasNoSignedWrap() const {
02024   return cast<OverflowingBinaryOperator>(this)->hasNoSignedWrap();
02025 }
02026 
02027 bool BinaryOperator::isExact() const {
02028   return cast<PossiblyExactOperator>(this)->isExact();
02029 }
02030 
02031 //===----------------------------------------------------------------------===//
02032 //                             FPMathOperator Class
02033 //===----------------------------------------------------------------------===//
02034 
02035 /// getFPAccuracy - Get the maximum error permitted by this operation in ULPs.
02036 /// An accuracy of 0.0 means that the operation should be performed with the
02037 /// default precision.
02038 float FPMathOperator::getFPAccuracy() const {
02039   const MDNode *MD =
02040     cast<Instruction>(this)->getMetadata(LLVMContext::MD_fpmath);
02041   if (!MD)
02042     return 0.0;
02043   ConstantFP *Accuracy = cast<ConstantFP>(MD->getOperand(0));
02044   return Accuracy->getValueAPF().convertToFloat();
02045 }
02046 
02047 
02048 //===----------------------------------------------------------------------===//
02049 //                                CastInst Class
02050 //===----------------------------------------------------------------------===//
02051 
02052 void CastInst::anchor() {}
02053 
02054 // Just determine if this cast only deals with integral->integral conversion.
02055 bool CastInst::isIntegerCast() const {
02056   switch (getOpcode()) {
02057     default: return false;
02058     case Instruction::ZExt:
02059     case Instruction::SExt:
02060     case Instruction::Trunc:
02061       return true;
02062     case Instruction::BitCast:
02063       return getOperand(0)->getType()->isIntegerTy() &&
02064         getType()->isIntegerTy();
02065   }
02066 }
02067 
02068 bool CastInst::isLosslessCast() const {
02069   // Only BitCast can be lossless, exit fast if we're not BitCast
02070   if (getOpcode() != Instruction::BitCast)
02071     return false;
02072 
02073   // Identity cast is always lossless
02074   Type* SrcTy = getOperand(0)->getType();
02075   Type* DstTy = getType();
02076   if (SrcTy == DstTy)
02077     return true;
02078   
02079   // Pointer to pointer is always lossless.
02080   if (SrcTy->isPointerTy())
02081     return DstTy->isPointerTy();
02082   return false;  // Other types have no identity values
02083 }
02084 
02085 /// This function determines if the CastInst does not require any bits to be
02086 /// changed in order to effect the cast. Essentially, it identifies cases where
02087 /// no code gen is necessary for the cast, hence the name no-op cast.  For 
02088 /// example, the following are all no-op casts:
02089 /// # bitcast i32* %x to i8*
02090 /// # bitcast <2 x i32> %x to <4 x i16> 
02091 /// # ptrtoint i32* %x to i32     ; on 32-bit plaforms only
02092 /// @brief Determine if the described cast is a no-op.
02093 bool CastInst::isNoopCast(Instruction::CastOps Opcode,
02094                           Type *SrcTy,
02095                           Type *DestTy,
02096                           Type *IntPtrTy) {
02097   switch (Opcode) {
02098     default: llvm_unreachable("Invalid CastOp");
02099     case Instruction::Trunc:
02100     case Instruction::ZExt:
02101     case Instruction::SExt: 
02102     case Instruction::FPTrunc:
02103     case Instruction::FPExt:
02104     case Instruction::UIToFP:
02105     case Instruction::SIToFP:
02106     case Instruction::FPToUI:
02107     case Instruction::FPToSI:
02108     case Instruction::AddrSpaceCast:
02109       // TODO: Target informations may give a more accurate answer here.
02110       return false;
02111     case Instruction::BitCast:
02112       return true;  // BitCast never modifies bits.
02113     case Instruction::PtrToInt:
02114       return IntPtrTy->getScalarSizeInBits() ==
02115              DestTy->getScalarSizeInBits();
02116     case Instruction::IntToPtr:
02117       return IntPtrTy->getScalarSizeInBits() ==
02118              SrcTy->getScalarSizeInBits();
02119   }
02120 }
02121 
02122 /// @brief Determine if a cast is a no-op.
02123 bool CastInst::isNoopCast(Type *IntPtrTy) const {
02124   return isNoopCast(getOpcode(), getOperand(0)->getType(), getType(), IntPtrTy);
02125 }
02126 
02127 bool CastInst::isNoopCast(const DataLayout *DL) const {
02128   if (!DL) {
02129     // Assume maximum pointer size.
02130     return isNoopCast(Type::getInt64Ty(getContext()));
02131   }
02132 
02133   Type *PtrOpTy = nullptr;
02134   if (getOpcode() == Instruction::PtrToInt)
02135     PtrOpTy = getOperand(0)->getType();
02136   else if (getOpcode() == Instruction::IntToPtr)
02137     PtrOpTy = getType();
02138 
02139   Type *IntPtrTy = PtrOpTy
02140                  ? DL->getIntPtrType(PtrOpTy)
02141                  : DL->getIntPtrType(getContext(), 0);
02142 
02143   return isNoopCast(getOpcode(), getOperand(0)->getType(), getType(), IntPtrTy);
02144 }
02145 
02146 /// This function determines if a pair of casts can be eliminated and what
02147 /// opcode should be used in the elimination. This assumes that there are two
02148 /// instructions like this:
02149 /// *  %F = firstOpcode SrcTy %x to MidTy
02150 /// *  %S = secondOpcode MidTy %F to DstTy
02151 /// The function returns a resultOpcode so these two casts can be replaced with:
02152 /// *  %Replacement = resultOpcode %SrcTy %x to DstTy
02153 /// If no such cast is permited, the function returns 0.
02154 unsigned CastInst::isEliminableCastPair(
02155   Instruction::CastOps firstOp, Instruction::CastOps secondOp,
02156   Type *SrcTy, Type *MidTy, Type *DstTy, Type *SrcIntPtrTy, Type *MidIntPtrTy,
02157   Type *DstIntPtrTy) {
02158   // Define the 144 possibilities for these two cast instructions. The values
02159   // in this matrix determine what to do in a given situation and select the
02160   // case in the switch below.  The rows correspond to firstOp, the columns 
02161   // correspond to secondOp.  In looking at the table below, keep in  mind
02162   // the following cast properties:
02163   //
02164   //          Size Compare       Source               Destination
02165   // Operator  Src ? Size   Type       Sign         Type       Sign
02166   // -------- ------------ -------------------   ---------------------
02167   // TRUNC         >       Integer      Any        Integral     Any
02168   // ZEXT          <       Integral   Unsigned     Integer      Any
02169   // SEXT          <       Integral    Signed      Integer      Any
02170   // FPTOUI       n/a      FloatPt      n/a        Integral   Unsigned
02171   // FPTOSI       n/a      FloatPt      n/a        Integral    Signed
02172   // UITOFP       n/a      Integral   Unsigned     FloatPt      n/a
02173   // SITOFP       n/a      Integral    Signed      FloatPt      n/a
02174   // FPTRUNC       >       FloatPt      n/a        FloatPt      n/a
02175   // FPEXT         <       FloatPt      n/a        FloatPt      n/a
02176   // PTRTOINT     n/a      Pointer      n/a        Integral   Unsigned
02177   // INTTOPTR     n/a      Integral   Unsigned     Pointer      n/a
02178   // BITCAST       =       FirstClass   n/a       FirstClass    n/a
02179   // ADDRSPCST    n/a      Pointer      n/a        Pointer      n/a
02180   //
02181   // NOTE: some transforms are safe, but we consider them to be non-profitable.
02182   // For example, we could merge "fptoui double to i32" + "zext i32 to i64",
02183   // into "fptoui double to i64", but this loses information about the range
02184   // of the produced value (we no longer know the top-part is all zeros).
02185   // Further this conversion is often much more expensive for typical hardware,
02186   // and causes issues when building libgcc.  We disallow fptosi+sext for the
02187   // same reason.
02188   const unsigned numCastOps =
02189     Instruction::CastOpsEnd - Instruction::CastOpsBegin;
02190   static const uint8_t CastResults[numCastOps][numCastOps] = {
02191     // T        F  F  U  S  F  F  P  I  B  A  -+
02192     // R  Z  S  P  P  I  I  T  P  2  N  T  S   |
02193     // U  E  E  2  2  2  2  R  E  I  T  C  C   +- secondOp
02194     // N  X  X  U  S  F  F  N  X  N  2  V  V   |
02195     // C  T  T  I  I  P  P  C  T  T  P  T  T  -+
02196     {  1, 0, 0,99,99, 0, 0,99,99,99, 0, 3, 0}, // Trunc         -+
02197     {  8, 1, 9,99,99, 2, 0,99,99,99, 2, 3, 0}, // ZExt           |
02198     {  8, 0, 1,99,99, 0, 2,99,99,99, 0, 3, 0}, // SExt           |
02199     {  0, 0, 0,99,99, 0, 0,99,99,99, 0, 3, 0}, // FPToUI         |
02200     {  0, 0, 0,99,99, 0, 0,99,99,99, 0, 3, 0}, // FPToSI         |
02201     { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4, 0}, // UIToFP         +- firstOp
02202     { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4, 0}, // SIToFP         |
02203     { 99,99,99, 0, 0,99,99, 1, 0,99,99, 4, 0}, // FPTrunc        |
02204     { 99,99,99, 2, 2,99,99,10, 2,99,99, 4, 0}, // FPExt          |
02205     {  1, 0, 0,99,99, 0, 0,99,99,99, 7, 3, 0}, // PtrToInt       |
02206     { 99,99,99,99,99,99,99,99,99,11,99,15, 0}, // IntToPtr       |
02207     {  5, 5, 5, 6, 6, 5, 5, 6, 6,16, 5, 1,14}, // BitCast        |
02208     {  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,13,12}, // AddrSpaceCast -+
02209   };
02210 
02211   // If either of the casts are a bitcast from scalar to vector, disallow the
02212   // merging. However, bitcast of A->B->A are allowed.
02213   bool isFirstBitcast  = (firstOp == Instruction::BitCast);
02214   bool isSecondBitcast = (secondOp == Instruction::BitCast);
02215   bool chainedBitcast  = (SrcTy == DstTy && isFirstBitcast && isSecondBitcast);
02216 
02217   // Check if any of the bitcasts convert scalars<->vectors.
02218   if ((isFirstBitcast  && isa<VectorType>(SrcTy) != isa<VectorType>(MidTy)) ||
02219       (isSecondBitcast && isa<VectorType>(MidTy) != isa<VectorType>(DstTy)))
02220     // Unless we are bitcasing to the original type, disallow optimizations.
02221     if (!chainedBitcast) return 0;
02222 
02223   int ElimCase = CastResults[firstOp-Instruction::CastOpsBegin]
02224                             [secondOp-Instruction::CastOpsBegin];
02225   switch (ElimCase) {
02226     case 0: 
02227       // Categorically disallowed.
02228       return 0;
02229     case 1: 
02230       // Allowed, use first cast's opcode.
02231       return firstOp;
02232     case 2: 
02233       // Allowed, use second cast's opcode.
02234       return secondOp;
02235     case 3: 
02236       // No-op cast in second op implies firstOp as long as the DestTy
02237       // is integer and we are not converting between a vector and a
02238       // non-vector type.
02239       if (!SrcTy->isVectorTy() && DstTy->isIntegerTy())
02240         return firstOp;
02241       return 0;
02242     case 4:
02243       // No-op cast in second op implies firstOp as long as the DestTy
02244       // is floating point.
02245       if (DstTy->isFloatingPointTy())
02246         return firstOp;
02247       return 0;
02248     case 5: 
02249       // No-op cast in first op implies secondOp as long as the SrcTy
02250       // is an integer.
02251       if (SrcTy->isIntegerTy())
02252         return secondOp;
02253       return 0;
02254     case 6:
02255       // No-op cast in first op implies secondOp as long as the SrcTy
02256       // is a floating point.
02257       if (SrcTy->isFloatingPointTy())
02258         return secondOp;
02259       return 0;
02260     case 7: {
02261       // Cannot simplify if address spaces are different!
02262       if (SrcTy->getPointerAddressSpace() != DstTy->getPointerAddressSpace())
02263         return 0;
02264 
02265       unsigned MidSize = MidTy->getScalarSizeInBits();
02266       // We can still fold this without knowing the actual sizes as long we
02267       // know that the intermediate pointer is the largest possible
02268       // pointer size.
02269       // FIXME: Is this always true?
02270       if (MidSize == 64)
02271         return Instruction::BitCast;
02272 
02273       // ptrtoint, inttoptr -> bitcast (ptr -> ptr) if int size is >= ptr size.
02274       if (!SrcIntPtrTy || DstIntPtrTy != SrcIntPtrTy)
02275         return 0;
02276       unsigned PtrSize = SrcIntPtrTy->getScalarSizeInBits();
02277       if (MidSize >= PtrSize)
02278         return Instruction::BitCast;
02279       return 0;
02280     }
02281     case 8: {
02282       // ext, trunc -> bitcast,    if the SrcTy and DstTy are same size
02283       // ext, trunc -> ext,        if sizeof(SrcTy) < sizeof(DstTy)
02284       // ext, trunc -> trunc,      if sizeof(SrcTy) > sizeof(DstTy)
02285       unsigned SrcSize = SrcTy->getScalarSizeInBits();
02286       unsigned DstSize = DstTy->getScalarSizeInBits();
02287       if (SrcSize == DstSize)
02288         return Instruction::BitCast;
02289       else if (SrcSize < DstSize)
02290         return firstOp;
02291       return secondOp;
02292     }
02293     case 9:
02294       // zext, sext -> zext, because sext can't sign extend after zext
02295       return Instruction::ZExt;
02296     case 10:
02297       // fpext followed by ftrunc is allowed if the bit size returned to is
02298       // the same as the original, in which case its just a bitcast
02299       if (SrcTy == DstTy)
02300         return Instruction::BitCast;
02301       return 0; // If the types are not the same we can't eliminate it.
02302     case 11: {
02303       // inttoptr, ptrtoint -> bitcast if SrcSize<=PtrSize and SrcSize==DstSize
02304       if (!MidIntPtrTy)
02305         return 0;
02306       unsigned PtrSize = MidIntPtrTy->getScalarSizeInBits();
02307       unsigned SrcSize = SrcTy->getScalarSizeInBits();
02308       unsigned DstSize = DstTy->getScalarSizeInBits();
02309       if (SrcSize <= PtrSize && SrcSize == DstSize)
02310         return Instruction::BitCast;
02311       return 0;
02312     }
02313     case 12: {
02314       // addrspacecast, addrspacecast -> bitcast,       if SrcAS == DstAS
02315       // addrspacecast, addrspacecast -> addrspacecast, if SrcAS != DstAS
02316       if (SrcTy->getPointerAddressSpace() != DstTy->getPointerAddressSpace())
02317         return Instruction::AddrSpaceCast;
02318       return Instruction::BitCast;
02319     }
02320     case 13:
02321       // FIXME: this state can be merged with (1), but the following assert
02322       // is useful to check the correcteness of the sequence due to semantic
02323       // change of bitcast.
02324       assert(
02325         SrcTy->isPtrOrPtrVectorTy() &&
02326         MidTy->isPtrOrPtrVectorTy() &&
02327         DstTy->isPtrOrPtrVectorTy() &&
02328         SrcTy->getPointerAddressSpace() != MidTy->getPointerAddressSpace() &&
02329         MidTy->getPointerAddressSpace() == DstTy->getPointerAddressSpace() &&
02330         "Illegal addrspacecast, bitcast sequence!");
02331       // Allowed, use first cast's opcode
02332       return firstOp;
02333     case 14:
02334       // FIXME: this state can be merged with (2), but the following assert
02335       // is useful to check the correcteness of the sequence due to semantic
02336       // change of bitcast.
02337       assert(
02338         SrcTy->isPtrOrPtrVectorTy() &&
02339         MidTy->isPtrOrPtrVectorTy() &&
02340         DstTy->isPtrOrPtrVectorTy() &&
02341         SrcTy->getPointerAddressSpace() == MidTy->getPointerAddressSpace() &&
02342         MidTy->getPointerAddressSpace() != DstTy->getPointerAddressSpace() &&
02343         "Illegal bitcast, addrspacecast sequence!");
02344       // Allowed, use second cast's opcode
02345       return secondOp;
02346     case 15:
02347       // FIXME: this state can be merged with (1), but the following assert
02348       // is useful to check the correcteness of the sequence due to semantic
02349       // change of bitcast.
02350       assert(
02351         SrcTy->isIntOrIntVectorTy() &&
02352         MidTy->isPtrOrPtrVectorTy() &&
02353         DstTy->isPtrOrPtrVectorTy() &&
02354         MidTy->getPointerAddressSpace() == DstTy->getPointerAddressSpace() &&
02355         "Illegal inttoptr, bitcast sequence!");
02356       // Allowed, use first cast's opcode
02357       return firstOp;
02358     case 16:
02359       // FIXME: this state can be merged with (2), but the following assert
02360       // is useful to check the correcteness of the sequence due to semantic
02361       // change of bitcast.
02362       assert(
02363         SrcTy->isPtrOrPtrVectorTy() &&
02364         MidTy->isPtrOrPtrVectorTy() &&
02365         DstTy->isIntOrIntVectorTy() &&
02366         SrcTy->getPointerAddressSpace() == MidTy->getPointerAddressSpace() &&
02367         "Illegal bitcast, ptrtoint sequence!");
02368       // Allowed, use second cast's opcode
02369       return secondOp;
02370     case 99: 
02371       // Cast combination can't happen (error in input). This is for all cases
02372       // where the MidTy is not the same for the two cast instructions.
02373       llvm_unreachable("Invalid Cast Combination");
02374     default:
02375       llvm_unreachable("Error in CastResults table!!!");
02376   }
02377 }
02378 
02379 CastInst *CastInst::Create(Instruction::CastOps op, Value *S, Type *Ty, 
02380   const Twine &Name, Instruction *InsertBefore) {
02381   assert(castIsValid(op, S, Ty) && "Invalid cast!");
02382   // Construct and return the appropriate CastInst subclass
02383   switch (op) {
02384   case Trunc:         return new TruncInst         (S, Ty, Name, InsertBefore);
02385   case ZExt:          return new ZExtInst          (S, Ty, Name, InsertBefore);
02386   case SExt:          return new SExtInst          (S, Ty, Name, InsertBefore);
02387   case FPTrunc:       return new FPTruncInst       (S, Ty, Name, InsertBefore);
02388   case FPExt:         return new FPExtInst         (S, Ty, Name, InsertBefore);
02389   case UIToFP:        return new UIToFPInst        (S, Ty, Name, InsertBefore);
02390   case SIToFP:        return new SIToFPInst        (S, Ty, Name, InsertBefore);
02391   case FPToUI:        return new FPToUIInst        (S, Ty, Name, InsertBefore);
02392   case FPToSI:        return new FPToSIInst        (S, Ty, Name, InsertBefore);
02393   case PtrToInt:      return new PtrToIntInst      (S, Ty, Name, InsertBefore);
02394   case IntToPtr:      return new IntToPtrInst      (S, Ty, Name, InsertBefore);
02395   case BitCast:       return new BitCastInst       (S, Ty, Name, InsertBefore);
02396   case AddrSpaceCast: return new AddrSpaceCastInst (S, Ty, Name, InsertBefore);
02397   default: llvm_unreachable("Invalid opcode provided");
02398   }
02399 }
02400 
02401 CastInst *CastInst::Create(Instruction::CastOps op, Value *S, Type *Ty,
02402   const Twine &Name, BasicBlock *InsertAtEnd) {
02403   assert(castIsValid(op, S, Ty) && "Invalid cast!");
02404   // Construct and return the appropriate CastInst subclass
02405   switch (op) {
02406   case Trunc:         return new TruncInst         (S, Ty, Name, InsertAtEnd);
02407   case ZExt:          return new ZExtInst          (S, Ty, Name, InsertAtEnd);
02408   case SExt:          return new SExtInst          (S, Ty, Name, InsertAtEnd);
02409   case FPTrunc:       return new FPTruncInst       (S, Ty, Name, InsertAtEnd);
02410   case FPExt:         return new FPExtInst         (S, Ty, Name, InsertAtEnd);
02411   case UIToFP:        return new UIToFPInst        (S, Ty, Name, InsertAtEnd);
02412   case SIToFP:        return new SIToFPInst        (S, Ty, Name, InsertAtEnd);
02413   case FPToUI:        return new FPToUIInst        (S, Ty, Name, InsertAtEnd);
02414   case FPToSI:        return new FPToSIInst        (S, Ty, Name, InsertAtEnd);
02415   case PtrToInt:      return new PtrToIntInst      (S, Ty, Name, InsertAtEnd);
02416   case IntToPtr:      return new IntToPtrInst      (S, Ty, Name, InsertAtEnd);
02417   case BitCast:       return new BitCastInst       (S, Ty, Name, InsertAtEnd);
02418   case AddrSpaceCast: return new AddrSpaceCastInst (S, Ty, Name, InsertAtEnd);
02419   default: llvm_unreachable("Invalid opcode provided");
02420   }
02421 }
02422 
02423 CastInst *CastInst::CreateZExtOrBitCast(Value *S, Type *Ty, 
02424                                         const Twine &Name,
02425                                         Instruction *InsertBefore) {
02426   if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
02427     return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
02428   return Create(Instruction::ZExt, S, Ty, Name, InsertBefore);
02429 }
02430 
02431 CastInst *CastInst::CreateZExtOrBitCast(Value *S, Type *Ty, 
02432                                         const Twine &Name,
02433                                         BasicBlock *InsertAtEnd) {
02434   if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
02435     return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
02436   return Create(Instruction::ZExt, S, Ty, Name, InsertAtEnd);
02437 }
02438 
02439 CastInst *CastInst::CreateSExtOrBitCast(Value *S, Type *Ty, 
02440                                         const Twine &Name,
02441                                         Instruction *InsertBefore) {
02442   if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
02443     return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
02444   return Create(Instruction::SExt, S, Ty, Name, InsertBefore);
02445 }
02446 
02447 CastInst *CastInst::CreateSExtOrBitCast(Value *S, Type *Ty, 
02448                                         const Twine &Name,
02449                                         BasicBlock *InsertAtEnd) {
02450   if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
02451     return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
02452   return Create(Instruction::SExt, S, Ty, Name, InsertAtEnd);
02453 }
02454 
02455 CastInst *CastInst::CreateTruncOrBitCast(Value *S, Type *Ty,
02456                                          const Twine &Name,
02457                                          Instruction *InsertBefore) {
02458   if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
02459     return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
02460   return Create(Instruction::Trunc, S, Ty, Name, InsertBefore);
02461 }
02462 
02463 CastInst *CastInst::CreateTruncOrBitCast(Value *S, Type *Ty,
02464                                          const Twine &Name, 
02465                                          BasicBlock *InsertAtEnd) {
02466   if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
02467     return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
02468   return Create(Instruction::Trunc, S, Ty, Name, InsertAtEnd);
02469 }
02470 
02471 CastInst *CastInst::CreatePointerCast(Value *S, Type *Ty,
02472                                       const Twine &Name,
02473                                       BasicBlock *InsertAtEnd) {
02474   assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
02475   assert((Ty->isIntOrIntVectorTy() || Ty->isPtrOrPtrVectorTy()) &&
02476          "Invalid cast");
02477   assert(Ty->isVectorTy() == S->getType()->isVectorTy() && "Invalid cast");
02478   assert((!Ty->isVectorTy() ||
02479           Ty->getVectorNumElements() == S->getType()->getVectorNumElements()) &&
02480          "Invalid cast");
02481 
02482   if (Ty->isIntOrIntVectorTy())
02483     return Create(Instruction::PtrToInt, S, Ty, Name, InsertAtEnd);
02484 
02485   Type *STy = S->getType();
02486   if (STy->getPointerAddressSpace() != Ty->getPointerAddressSpace())
02487     return Create(Instruction::AddrSpaceCast, S, Ty, Name, InsertAtEnd);
02488 
02489   return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
02490 }
02491 
02492 /// @brief Create a BitCast or a PtrToInt cast instruction
02493 CastInst *CastInst::CreatePointerCast(Value *S, Type *Ty,
02494                                       const Twine &Name,
02495                                       Instruction *InsertBefore) {
02496   assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
02497   assert((Ty->isIntOrIntVectorTy() || Ty->isPtrOrPtrVectorTy()) &&
02498          "Invalid cast");
02499   assert(Ty->isVectorTy() == S->getType()->isVectorTy() && "Invalid cast");
02500   assert((!Ty->isVectorTy() ||
02501           Ty->getVectorNumElements() == S->getType()->getVectorNumElements()) &&
02502          "Invalid cast");
02503 
02504   if (Ty->isIntOrIntVectorTy())
02505     return Create(Instruction::PtrToInt, S, Ty, Name, InsertBefore);
02506 
02507   Type *STy = S->getType();
02508   if (STy->getPointerAddressSpace() != Ty->getPointerAddressSpace())
02509     return Create(Instruction::AddrSpaceCast, S, Ty, Name, InsertBefore);
02510 
02511   return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
02512 }
02513 
02514 CastInst *CastInst::CreateIntegerCast(Value *C, Type *Ty, 
02515                                       bool isSigned, const Twine &Name,
02516                                       Instruction *InsertBefore) {
02517   assert(C->getType()->isIntOrIntVectorTy() && Ty->isIntOrIntVectorTy() &&
02518          "Invalid integer cast");
02519   unsigned SrcBits = C->getType()->getScalarSizeInBits();
02520   unsigned DstBits = Ty->getScalarSizeInBits();
02521   Instruction::CastOps opcode =
02522     (SrcBits == DstBits ? Instruction::BitCast :
02523      (SrcBits > DstBits ? Instruction::Trunc :
02524       (isSigned ? Instruction::SExt : Instruction::ZExt)));
02525   return Create(opcode, C, Ty, Name, InsertBefore);
02526 }
02527 
02528 CastInst *CastInst::CreateIntegerCast(Value *C, Type *Ty, 
02529                                       bool isSigned, const Twine &Name,
02530                                       BasicBlock *InsertAtEnd) {
02531   assert(C->getType()->isIntOrIntVectorTy() && Ty->isIntOrIntVectorTy() &&
02532          "Invalid cast");
02533   unsigned SrcBits = C->getType()->getScalarSizeInBits();
02534   unsigned DstBits = Ty->getScalarSizeInBits();
02535   Instruction::CastOps opcode =
02536     (SrcBits == DstBits ? Instruction::BitCast :
02537      (SrcBits > DstBits ? Instruction::Trunc :
02538       (isSigned ? Instruction::SExt : Instruction::ZExt)));
02539   return Create(opcode, C, Ty, Name, InsertAtEnd);
02540 }
02541 
02542 CastInst *CastInst::CreateFPCast(Value *C, Type *Ty, 
02543                                  const Twine &Name, 
02544                                  Instruction *InsertBefore) {
02545   assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
02546          "Invalid cast");
02547   unsigned SrcBits = C->getType()->getScalarSizeInBits();
02548   unsigned DstBits = Ty->getScalarSizeInBits();
02549   Instruction::CastOps opcode =
02550     (SrcBits == DstBits ? Instruction::BitCast :
02551      (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
02552   return Create(opcode, C, Ty, Name, InsertBefore);
02553 }
02554 
02555 CastInst *CastInst::CreateFPCast(Value *C, Type *Ty, 
02556                                  const Twine &Name, 
02557                                  BasicBlock *InsertAtEnd) {
02558   assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
02559          "Invalid cast");
02560   unsigned SrcBits = C->getType()->getScalarSizeInBits();
02561   unsigned DstBits = Ty->getScalarSizeInBits();
02562   Instruction::CastOps opcode =
02563     (SrcBits == DstBits ? Instruction::BitCast :
02564      (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
02565   return Create(opcode, C, Ty, Name, InsertAtEnd);
02566 }
02567 
02568 // Check whether it is valid to call getCastOpcode for these types.
02569 // This routine must be kept in sync with getCastOpcode.
02570 bool CastInst::isCastable(Type *SrcTy, Type *DestTy) {
02571   if (!SrcTy->isFirstClassType() || !DestTy->isFirstClassType())
02572     return false;
02573 
02574   if (SrcTy == DestTy)
02575     return true;
02576 
02577   if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy))
02578     if (VectorType *DestVecTy = dyn_cast<VectorType>(DestTy))
02579       if (SrcVecTy->getNumElements() == DestVecTy->getNumElements()) {
02580         // An element by element cast.  Valid if casting the elements is valid.
02581         SrcTy = SrcVecTy->getElementType();
02582         DestTy = DestVecTy->getElementType();
02583       }
02584 
02585   // Get the bit sizes, we'll need these
02586   unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();   // 0 for ptr
02587   unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr
02588 
02589   // Run through the possibilities ...
02590   if (DestTy->isIntegerTy()) {               // Casting to integral
02591     if (SrcTy->isIntegerTy()) {                // Casting from integral
02592         return true;
02593     } else if (SrcTy->isFloatingPointTy()) {   // Casting from floating pt
02594       return true;
02595     } else if (SrcTy->isVectorTy()) {          // Casting from vector
02596       return DestBits == SrcBits;
02597     } else {                                   // Casting from something else
02598       return SrcTy->isPointerTy();
02599     }
02600   } else if (DestTy->isFloatingPointTy()) {  // Casting to floating pt
02601     if (SrcTy->isIntegerTy()) {                // Casting from integral
02602       return true;
02603     } else if (SrcTy->isFloatingPointTy()) {   // Casting from floating pt
02604       return true;
02605     } else if (SrcTy->isVectorTy()) {          // Casting from vector
02606       return DestBits == SrcBits;
02607     } else {                                   // Casting from something else
02608       return false;
02609     }
02610   } else if (DestTy->isVectorTy()) {         // Casting to vector
02611     return DestBits == SrcBits;
02612   } else if (DestTy->isPointerTy()) {        // Casting to pointer
02613     if (SrcTy->isPointerTy()) {                // Casting from pointer
02614       return true;
02615     } else if (SrcTy->isIntegerTy()) {         // Casting from integral
02616       return true;
02617     } else {                                   // Casting from something else
02618       return false;
02619     }
02620   } else if (DestTy->isX86_MMXTy()) {
02621     if (SrcTy->isVectorTy()) {
02622       return DestBits == SrcBits;       // 64-bit vector to MMX
02623     } else {
02624       return false;
02625     }
02626   } else {                                   // Casting to something else
02627     return false;
02628   }
02629 }
02630 
02631 bool CastInst::isBitCastable(Type *SrcTy, Type *DestTy) {
02632   if (!SrcTy->isFirstClassType() || !DestTy->isFirstClassType())
02633     return false;
02634 
02635   if (SrcTy == DestTy)
02636     return true;
02637 
02638   if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy)) {
02639     if (VectorType *DestVecTy = dyn_cast<VectorType>(DestTy)) {
02640       if (SrcVecTy->getNumElements() == DestVecTy->getNumElements()) {
02641         // An element by element cast. Valid if casting the elements is valid.
02642         SrcTy = SrcVecTy->getElementType();
02643         DestTy = DestVecTy->getElementType();
02644       }
02645     }
02646   }
02647 
02648   if (PointerType *DestPtrTy = dyn_cast<PointerType>(DestTy)) {
02649     if (PointerType *SrcPtrTy = dyn_cast<PointerType>(SrcTy)) {
02650       return SrcPtrTy->getAddressSpace() == DestPtrTy->getAddressSpace();
02651     }
02652   }
02653 
02654   unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();   // 0 for ptr
02655   unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr
02656 
02657   // Could still have vectors of pointers if the number of elements doesn't
02658   // match
02659   if (SrcBits == 0 || DestBits == 0)
02660     return false;
02661 
02662   if (SrcBits != DestBits)
02663     return false;
02664 
02665   if (DestTy->isX86_MMXTy() || SrcTy->isX86_MMXTy())
02666     return false;
02667 
02668   return true;
02669 }
02670 
02671 // Provide a way to get a "cast" where the cast opcode is inferred from the
02672 // types and size of the operand. This, basically, is a parallel of the
02673 // logic in the castIsValid function below.  This axiom should hold:
02674 //   castIsValid( getCastOpcode(Val, Ty), Val, Ty)
02675 // should not assert in castIsValid. In other words, this produces a "correct"
02676 // casting opcode for the arguments passed to it.
02677 // This routine must be kept in sync with isCastable.
02678 Instruction::CastOps
02679 CastInst::getCastOpcode(
02680   const Value *Src, bool SrcIsSigned, Type *DestTy, bool DestIsSigned) {
02681   Type *SrcTy = Src->getType();
02682 
02683   assert(SrcTy->isFirstClassType() && DestTy->isFirstClassType() &&
02684          "Only first class types are castable!");
02685 
02686   if (SrcTy == DestTy)
02687     return BitCast;
02688 
02689   // FIXME: Check address space sizes here
02690   if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy))
02691     if (VectorType *DestVecTy = dyn_cast<VectorType>(DestTy))
02692       if (SrcVecTy->getNumElements() == DestVecTy->getNumElements()) {
02693         // An element by element cast.  Find the appropriate opcode based on the
02694         // element types.
02695         SrcTy = SrcVecTy->getElementType();
02696         DestTy = DestVecTy->getElementType();
02697       }
02698 
02699   // Get the bit sizes, we'll need these
02700   unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();   // 0 for ptr
02701   unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr
02702 
02703   // Run through the possibilities ...
02704   if (DestTy->isIntegerTy()) {                      // Casting to integral
02705     if (SrcTy->isIntegerTy()) {                     // Casting from integral
02706       if (DestBits < SrcBits)
02707         return Trunc;                               // int -> smaller int
02708       else if (DestBits > SrcBits) {                // its an extension
02709         if (SrcIsSigned)
02710           return SExt;                              // signed -> SEXT
02711         else
02712           return ZExt;                              // unsigned -> ZEXT
02713       } else {
02714         return BitCast;                             // Same size, No-op cast
02715       }
02716     } else if (SrcTy->isFloatingPointTy()) {        // Casting from floating pt
02717       if (DestIsSigned) 
02718         return FPToSI;                              // FP -> sint
02719       else
02720         return FPToUI;                              // FP -> uint 
02721     } else if (SrcTy->isVectorTy()) {
02722       assert(DestBits == SrcBits &&
02723              "Casting vector to integer of different width");
02724       return BitCast;                             // Same size, no-op cast
02725     } else {
02726       assert(SrcTy->isPointerTy() &&
02727              "Casting from a value that is not first-class type");
02728       return PtrToInt;                              // ptr -> int
02729     }
02730   } else if (DestTy->isFloatingPointTy()) {         // Casting to floating pt
02731     if (SrcTy->isIntegerTy()) {                     // Casting from integral
02732       if (SrcIsSigned)
02733         return SIToFP;                              // sint -> FP
02734       else
02735         return UIToFP;                              // uint -> FP
02736     } else if (SrcTy->isFloatingPointTy()) {        // Casting from floating pt
02737       if (DestBits < SrcBits) {
02738         return FPTrunc;                             // FP -> smaller FP
02739       } else if (DestBits > SrcBits) {
02740         return FPExt;                               // FP -> larger FP
02741       } else  {
02742         return BitCast;                             // same size, no-op cast
02743       }
02744     } else if (SrcTy->isVectorTy()) {
02745       assert(DestBits == SrcBits &&
02746              "Casting vector to floating point of different width");
02747       return BitCast;                             // same size, no-op cast
02748     }
02749     llvm_unreachable("Casting pointer or non-first class to float");
02750   } else if (DestTy->isVectorTy()) {
02751     assert(DestBits == SrcBits &&
02752            "Illegal cast to vector (wrong type or size)");
02753     return BitCast;
02754   } else if (DestTy->isPointerTy()) {
02755     if (SrcTy->isPointerTy()) {
02756       if (DestTy->getPointerAddressSpace() != SrcTy->getPointerAddressSpace())
02757         return AddrSpaceCast;
02758       return BitCast;                               // ptr -> ptr
02759     } else if (SrcTy->isIntegerTy()) {
02760       return IntToPtr;                              // int -> ptr
02761     }
02762     llvm_unreachable("Casting pointer to other than pointer or int");
02763   } else if (DestTy->isX86_MMXTy()) {
02764     if (SrcTy->isVectorTy()) {
02765       assert(DestBits == SrcBits && "Casting vector of wrong width to X86_MMX");
02766       return BitCast;                               // 64-bit vector to MMX
02767     }
02768     llvm_unreachable("Illegal cast to X86_MMX");
02769   }
02770   llvm_unreachable("Casting to type that is not first-class");
02771 }
02772 
02773 //===----------------------------------------------------------------------===//
02774 //                    CastInst SubClass Constructors
02775 //===----------------------------------------------------------------------===//
02776 
02777 /// Check that the construction parameters for a CastInst are correct. This
02778 /// could be broken out into the separate constructors but it is useful to have
02779 /// it in one place and to eliminate the redundant code for getting the sizes
02780 /// of the types involved.
02781 bool 
02782 CastInst::castIsValid(Instruction::CastOps op, Value *S, Type *DstTy) {
02783 
02784   // Check for type sanity on the arguments
02785   Type *SrcTy = S->getType();
02786 
02787   // If this is a cast to the same type then it's trivially true.
02788   if (SrcTy == DstTy)
02789     return true;
02790 
02791   if (!SrcTy->isFirstClassType() || !DstTy->isFirstClassType() ||
02792       SrcTy->isAggregateType() || DstTy->isAggregateType())
02793     return false;
02794 
02795   // Get the size of the types in bits, we'll need this later
02796   unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
02797   unsigned DstBitSize = DstTy->getScalarSizeInBits();
02798 
02799   // If these are vector types, get the lengths of the vectors (using zero for
02800   // scalar types means that checking that vector lengths match also checks that
02801   // scalars are not being converted to vectors or vectors to scalars).
02802   unsigned SrcLength = SrcTy->isVectorTy() ?
02803     cast<VectorType>(SrcTy)->getNumElements() : 0;
02804   unsigned DstLength = DstTy->isVectorTy() ?
02805     cast<VectorType>(DstTy)->getNumElements() : 0;
02806 
02807   // Switch on the opcode provided
02808   switch (op) {
02809   default: return false; // This is an input error
02810   case Instruction::Trunc:
02811     return SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy() &&
02812       SrcLength == DstLength && SrcBitSize > DstBitSize;
02813   case Instruction::ZExt:
02814     return SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy() &&
02815       SrcLength == DstLength && SrcBitSize < DstBitSize;
02816   case Instruction::SExt: 
02817     return SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy() &&
02818       SrcLength == DstLength && SrcBitSize < DstBitSize;
02819   case Instruction::FPTrunc:
02820     return SrcTy->isFPOrFPVectorTy() && DstTy->isFPOrFPVectorTy() &&
02821       SrcLength == DstLength && SrcBitSize > DstBitSize;
02822   case Instruction::FPExt:
02823     return SrcTy->isFPOrFPVectorTy() && DstTy->isFPOrFPVectorTy() &&
02824       SrcLength == DstLength && SrcBitSize < DstBitSize;
02825   case Instruction::UIToFP:
02826   case Instruction::SIToFP:
02827     return SrcTy->isIntOrIntVectorTy() && DstTy->isFPOrFPVectorTy() &&
02828       SrcLength == DstLength;
02829   case Instruction::FPToUI:
02830   case Instruction::FPToSI:
02831     return SrcTy->isFPOrFPVectorTy() && DstTy->isIntOrIntVectorTy() &&
02832       SrcLength == DstLength;
02833   case Instruction::PtrToInt:
02834     if (isa<VectorType>(SrcTy) != isa<VectorType>(DstTy))
02835       return false;
02836     if (VectorType *VT = dyn_cast<VectorType>(SrcTy))
02837       if (VT->getNumElements() != cast<VectorType>(DstTy)->getNumElements())
02838         return false;
02839     return SrcTy->getScalarType()->isPointerTy() &&
02840            DstTy->getScalarType()->isIntegerTy();
02841   case Instruction::IntToPtr:
02842     if (isa<VectorType>(SrcTy) != isa<VectorType>(DstTy))
02843       return false;
02844     if (VectorType *VT = dyn_cast<VectorType>(SrcTy))
02845       if (VT->getNumElements() != cast<VectorType>(DstTy)->getNumElements())
02846         return false;
02847     return SrcTy->getScalarType()->isIntegerTy() &&
02848            DstTy->getScalarType()->isPointerTy();
02849   case Instruction::BitCast: {
02850     PointerType *SrcPtrTy = dyn_cast<PointerType>(SrcTy->getScalarType());
02851     PointerType *DstPtrTy = dyn_cast<PointerType>(DstTy->getScalarType());
02852 
02853     // BitCast implies a no-op cast of type only. No bits change.
02854     // However, you can't cast pointers to anything but pointers.
02855     if (!SrcPtrTy != !DstPtrTy)
02856       return false;
02857 
02858     // For non-pointer cases, the cast is okay if the source and destination bit
02859     // widths are identical.
02860     if (!SrcPtrTy)
02861       return SrcTy->getPrimitiveSizeInBits() == DstTy->getPrimitiveSizeInBits();
02862 
02863     // If both are pointers then the address spaces must match.
02864     if (SrcPtrTy->getAddressSpace() != DstPtrTy->getAddressSpace())
02865       return false;
02866 
02867     // A vector of pointers must have the same number of elements.
02868     if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy)) {
02869       if (VectorType *DstVecTy = dyn_cast<VectorType>(DstTy))
02870         return (SrcVecTy->getNumElements() == DstVecTy->getNumElements());
02871 
02872       return false;
02873     }
02874 
02875     return true;
02876   }
02877   case Instruction::AddrSpaceCast: {
02878     PointerType *SrcPtrTy = dyn_cast<PointerType>(SrcTy->getScalarType());
02879     if (!SrcPtrTy)
02880       return false;
02881 
02882     PointerType *DstPtrTy = dyn_cast<PointerType>(DstTy->getScalarType());
02883     if (!DstPtrTy)
02884       return false;
02885 
02886     if (SrcPtrTy->getAddressSpace() == DstPtrTy->getAddressSpace())
02887       return false;
02888 
02889     if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy)) {
02890       if (VectorType *DstVecTy = dyn_cast<VectorType>(DstTy))
02891         return (SrcVecTy->getNumElements() == DstVecTy->getNumElements());
02892 
02893       return false;
02894     }
02895 
02896     return true;
02897   }
02898   }
02899 }
02900 
02901 TruncInst::TruncInst(
02902   Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
02903 ) : CastInst(Ty, Trunc, S, Name, InsertBefore) {
02904   assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
02905 }
02906 
02907 TruncInst::TruncInst(
02908   Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
02909 ) : CastInst(Ty, Trunc, S, Name, InsertAtEnd) { 
02910   assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
02911 }
02912 
02913 ZExtInst::ZExtInst(
02914   Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
02915 )  : CastInst(Ty, ZExt, S, Name, InsertBefore) { 
02916   assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
02917 }
02918 
02919 ZExtInst::ZExtInst(
02920   Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
02921 )  : CastInst(Ty, ZExt, S, Name, InsertAtEnd) { 
02922   assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
02923 }
02924 SExtInst::SExtInst(
02925   Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
02926 ) : CastInst(Ty, SExt, S, Name, InsertBefore) { 
02927   assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
02928 }
02929 
02930 SExtInst::SExtInst(
02931   Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
02932 )  : CastInst(Ty, SExt, S, Name, InsertAtEnd) { 
02933   assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
02934 }
02935 
02936 FPTruncInst::FPTruncInst(
02937   Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
02938 ) : CastInst(Ty, FPTrunc, S, Name, InsertBefore) { 
02939   assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
02940 }
02941 
02942 FPTruncInst::FPTruncInst(
02943   Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
02944 ) : CastInst(Ty, FPTrunc, S, Name, InsertAtEnd) { 
02945   assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
02946 }
02947 
02948 FPExtInst::FPExtInst(
02949   Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
02950 ) : CastInst(Ty, FPExt, S, Name, InsertBefore) { 
02951   assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
02952 }
02953 
02954 FPExtInst::FPExtInst(
02955   Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
02956 ) : CastInst(Ty, FPExt, S, Name, InsertAtEnd) { 
02957   assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
02958 }
02959 
02960 UIToFPInst::UIToFPInst(
02961   Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
02962 ) : CastInst(Ty, UIToFP, S, Name, InsertBefore) { 
02963   assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
02964 }
02965 
02966 UIToFPInst::UIToFPInst(
02967   Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
02968 ) : CastInst(Ty, UIToFP, S, Name, InsertAtEnd) { 
02969   assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
02970 }
02971 
02972 SIToFPInst::SIToFPInst(
02973   Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
02974 ) : CastInst(Ty, SIToFP, S, Name, InsertBefore) { 
02975   assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
02976 }
02977 
02978 SIToFPInst::SIToFPInst(
02979   Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
02980 ) : CastInst(Ty, SIToFP, S, Name, InsertAtEnd) { 
02981   assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
02982 }
02983 
02984 FPToUIInst::FPToUIInst(
02985   Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
02986 ) : CastInst(Ty, FPToUI, S, Name, InsertBefore) { 
02987   assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
02988 }
02989 
02990 FPToUIInst::FPToUIInst(
02991   Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
02992 ) : CastInst(Ty, FPToUI, S, Name, InsertAtEnd) { 
02993   assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
02994 }
02995 
02996 FPToSIInst::FPToSIInst(
02997   Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
02998 ) : CastInst(Ty, FPToSI, S, Name, InsertBefore) { 
02999   assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
03000 }
03001 
03002 FPToSIInst::FPToSIInst(
03003   Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
03004 ) : CastInst(Ty, FPToSI, S, Name, InsertAtEnd) { 
03005   assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
03006 }
03007 
03008 PtrToIntInst::PtrToIntInst(
03009   Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
03010 ) : CastInst(Ty, PtrToInt, S, Name, InsertBefore) { 
03011   assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
03012 }
03013 
03014 PtrToIntInst::PtrToIntInst(
03015   Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
03016 ) : CastInst(Ty, PtrToInt, S, Name, InsertAtEnd) { 
03017   assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
03018 }
03019 
03020 IntToPtrInst::IntToPtrInst(
03021   Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
03022 ) : CastInst(Ty, IntToPtr, S, Name, InsertBefore) { 
03023   assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
03024 }
03025 
03026 IntToPtrInst::IntToPtrInst(
03027   Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
03028 ) : CastInst(Ty, IntToPtr, S, Name, InsertAtEnd) { 
03029   assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
03030 }
03031 
03032 BitCastInst::BitCastInst(
03033   Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
03034 ) : CastInst(Ty, BitCast, S, Name, InsertBefore) { 
03035   assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
03036 }
03037 
03038 BitCastInst::BitCastInst(
03039   Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
03040 ) : CastInst(Ty, BitCast, S, Name, InsertAtEnd) { 
03041   assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
03042 }
03043 
03044 AddrSpaceCastInst::AddrSpaceCastInst(
03045   Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
03046 ) : CastInst(Ty, AddrSpaceCast, S, Name, InsertBefore) {
03047   assert(castIsValid(getOpcode(), S, Ty) && "Illegal AddrSpaceCast");
03048 }
03049 
03050 AddrSpaceCastInst::AddrSpaceCastInst(
03051   Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
03052 ) : CastInst(Ty, AddrSpaceCast, S, Name, InsertAtEnd) {
03053   assert(castIsValid(getOpcode(), S, Ty) && "Illegal AddrSpaceCast");
03054 }
03055 
03056 //===----------------------------------------------------------------------===//
03057 //                               CmpInst Classes
03058 //===----------------------------------------------------------------------===//
03059 
03060 void CmpInst::anchor() {}
03061 
03062 CmpInst::CmpInst(Type *ty, OtherOps op, unsigned short predicate,
03063                  Value *LHS, Value *RHS, const Twine &Name,
03064                  Instruction *InsertBefore)
03065   : Instruction(ty, op,
03066                 OperandTraits<CmpInst>::op_begin(this),
03067                 OperandTraits<CmpInst>::operands(this),
03068                 InsertBefore) {
03069     Op<0>() = LHS;
03070     Op<1>() = RHS;
03071   setPredicate((Predicate)predicate);
03072   setName(Name);
03073 }
03074 
03075 CmpInst::CmpInst(Type *ty, OtherOps op, unsigned short predicate,
03076                  Value *LHS, Value *RHS, const Twine &Name,
03077                  BasicBlock *InsertAtEnd)
03078   : Instruction(ty, op,
03079                 OperandTraits<CmpInst>::op_begin(this),
03080                 OperandTraits<CmpInst>::operands(this),
03081                 InsertAtEnd) {
03082   Op<0>() = LHS;
03083   Op<1>() = RHS;
03084   setPredicate((Predicate)predicate);
03085   setName(Name);
03086 }
03087 
03088 CmpInst *
03089 CmpInst::Create(OtherOps Op, unsigned short predicate,
03090                 Value *S1, Value *S2, 
03091                 const Twine &Name, Instruction *InsertBefore) {
03092   if (Op == Instruction::ICmp) {
03093     if (InsertBefore)
03094       return new ICmpInst(InsertBefore, CmpInst::Predicate(predicate),
03095                           S1, S2, Name);
03096     else
03097       return new ICmpInst(CmpInst::Predicate(predicate),
03098                           S1, S2, Name);
03099   }
03100   
03101   if (InsertBefore)
03102     return new FCmpInst(InsertBefore, CmpInst::Predicate(predicate),
03103                         S1, S2, Name);
03104   else
03105     return new FCmpInst(CmpInst::Predicate(predicate),
03106                         S1, S2, Name);
03107 }
03108 
03109 CmpInst *
03110 CmpInst::Create(OtherOps Op, unsigned short predicate, Value *S1, Value *S2, 
03111                 const Twine &Name, BasicBlock *InsertAtEnd) {
03112   if (Op == Instruction::ICmp) {
03113     return new ICmpInst(*InsertAtEnd, CmpInst::Predicate(predicate),
03114                         S1, S2, Name);
03115   }
03116   return new FCmpInst(*InsertAtEnd, CmpInst::Predicate(predicate),
03117                       S1, S2, Name);
03118 }
03119 
03120 void CmpInst::swapOperands() {
03121   if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
03122     IC->swapOperands();
03123   else
03124     cast<FCmpInst>(this)->swapOperands();
03125 }
03126 
03127 bool CmpInst::isCommutative() const {
03128   if (const ICmpInst *IC = dyn_cast<ICmpInst>(this))
03129     return IC->isCommutative();
03130   return cast<FCmpInst>(this)->isCommutative();
03131 }
03132 
03133 bool CmpInst::isEquality() const {
03134   if (const ICmpInst *IC = dyn_cast<ICmpInst>(this))
03135     return IC->isEquality();
03136   return cast<FCmpInst>(this)->isEquality();
03137 }
03138 
03139 
03140 CmpInst::Predicate CmpInst::getInversePredicate(Predicate pred) {
03141   switch (pred) {
03142     default: llvm_unreachable("Unknown cmp predicate!");
03143     case ICMP_EQ: return ICMP_NE;
03144     case ICMP_NE: return ICMP_EQ;
03145     case ICMP_UGT: return ICMP_ULE;
03146     case ICMP_ULT: return ICMP_UGE;
03147     case ICMP_UGE: return ICMP_ULT;
03148     case ICMP_ULE: return ICMP_UGT;
03149     case ICMP_SGT: return ICMP_SLE;
03150     case ICMP_SLT: return ICMP_SGE;
03151     case ICMP_SGE: return ICMP_SLT;
03152     case ICMP_SLE: return ICMP_SGT;
03153 
03154     case FCMP_OEQ: return FCMP_UNE;
03155     case FCMP_ONE: return FCMP_UEQ;
03156     case FCMP_OGT: return FCMP_ULE;
03157     case FCMP_OLT: return FCMP_UGE;
03158     case FCMP_OGE: return FCMP_ULT;
03159     case FCMP_OLE: return FCMP_UGT;
03160     case FCMP_UEQ: return FCMP_ONE;
03161     case FCMP_UNE: return FCMP_OEQ;
03162     case FCMP_UGT: return FCMP_OLE;
03163     case FCMP_ULT: return FCMP_OGE;
03164     case FCMP_UGE: return FCMP_OLT;
03165     case FCMP_ULE: return FCMP_OGT;
03166     case FCMP_ORD: return FCMP_UNO;
03167     case FCMP_UNO: return FCMP_ORD;
03168     case FCMP_TRUE: return FCMP_FALSE;
03169     case FCMP_FALSE: return FCMP_TRUE;
03170   }
03171 }
03172 
03173 ICmpInst::Predicate ICmpInst::getSignedPredicate(Predicate pred) {
03174   switch (pred) {
03175     default: llvm_unreachable("Unknown icmp predicate!");
03176     case ICMP_EQ: case ICMP_NE: 
03177     case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE: 
03178        return pred;
03179     case ICMP_UGT: return ICMP_SGT;
03180     case ICMP_ULT: return ICMP_SLT;
03181     case ICMP_UGE: return ICMP_SGE;
03182     case ICMP_ULE: return ICMP_SLE;
03183   }
03184 }
03185 
03186 ICmpInst::Predicate ICmpInst::getUnsignedPredicate(Predicate pred) {
03187   switch (pred) {
03188     default: llvm_unreachable("Unknown icmp predicate!");
03189     case ICMP_EQ: case ICMP_NE: 
03190     case ICMP_UGT: case ICMP_ULT: case ICMP_UGE: case ICMP_ULE: 
03191        return pred;
03192     case ICMP_SGT: return ICMP_UGT;
03193     case ICMP_SLT: return ICMP_ULT;
03194     case ICMP_SGE: return ICMP_UGE;
03195     case ICMP_SLE: return ICMP_ULE;
03196   }
03197 }
03198 
03199 /// Initialize a set of values that all satisfy the condition with C.
03200 ///
03201 ConstantRange 
03202 ICmpInst::makeConstantRange(Predicate pred, const APInt &C) {
03203   APInt Lower(C);
03204   APInt Upper(C);
03205   uint32_t BitWidth = C.getBitWidth();
03206   switch (pred) {
03207   default: llvm_unreachable("Invalid ICmp opcode to ConstantRange ctor!");
03208   case ICmpInst::ICMP_EQ: ++Upper; break;
03209   case ICmpInst::ICMP_NE: ++Lower; break;
03210   case ICmpInst::ICMP_ULT:
03211     Lower = APInt::getMinValue(BitWidth);
03212     // Check for an empty-set condition.
03213     if (Lower == Upper)
03214       return ConstantRange(BitWidth, /*isFullSet=*/false);
03215     break;
03216   case ICmpInst::ICMP_SLT:
03217     Lower = APInt::getSignedMinValue(BitWidth);
03218     // Check for an empty-set condition.
03219     if (Lower == Upper)
03220       return ConstantRange(BitWidth, /*isFullSet=*/false);
03221     break;
03222   case ICmpInst::ICMP_UGT: 
03223     ++Lower; Upper = APInt::getMinValue(BitWidth);        // Min = Next(Max)
03224     // Check for an empty-set condition.
03225     if (Lower == Upper)
03226       return ConstantRange(BitWidth, /*isFullSet=*/false);
03227     break;
03228   case ICmpInst::ICMP_SGT:
03229     ++Lower; Upper = APInt::getSignedMinValue(BitWidth);  // Min = Next(Max)
03230     // Check for an empty-set condition.
03231     if (Lower == Upper)
03232       return ConstantRange(BitWidth, /*isFullSet=*/false);
03233     break;
03234   case ICmpInst::ICMP_ULE: 
03235     Lower = APInt::getMinValue(BitWidth); ++Upper; 
03236     // Check for a full-set condition.
03237     if (Lower == Upper)
03238       return ConstantRange(BitWidth, /*isFullSet=*/true);
03239     break;
03240   case ICmpInst::ICMP_SLE: 
03241     Lower = APInt::getSignedMinValue(BitWidth); ++Upper; 
03242     // Check for a full-set condition.
03243     if (Lower == Upper)
03244       return ConstantRange(BitWidth, /*isFullSet=*/true);
03245     break;
03246   case ICmpInst::ICMP_UGE:
03247     Upper = APInt::getMinValue(BitWidth);        // Min = Next(Max)
03248     // Check for a full-set condition.
03249     if (Lower == Upper)
03250       return ConstantRange(BitWidth, /*isFullSet=*/true);
03251     break;
03252   case ICmpInst::ICMP_SGE:
03253     Upper = APInt::getSignedMinValue(BitWidth);  // Min = Next(Max)
03254     // Check for a full-set condition.
03255     if (Lower == Upper)
03256       return ConstantRange(BitWidth, /*isFullSet=*/true);
03257     break;
03258   }
03259   return ConstantRange(Lower, Upper);
03260 }
03261 
03262 CmpInst::Predicate CmpInst::getSwappedPredicate(Predicate pred) {
03263   switch (pred) {
03264     default: llvm_unreachable("Unknown cmp predicate!");
03265     case ICMP_EQ: case ICMP_NE:
03266       return pred;
03267     case ICMP_SGT: return ICMP_SLT;
03268     case ICMP_SLT: return ICMP_SGT;
03269     case ICMP_SGE: return ICMP_SLE;
03270     case ICMP_SLE: return ICMP_SGE;
03271     case ICMP_UGT: return ICMP_ULT;
03272     case ICMP_ULT: return ICMP_UGT;
03273     case ICMP_UGE: return ICMP_ULE;
03274     case ICMP_ULE: return ICMP_UGE;
03275   
03276     case FCMP_FALSE: case FCMP_TRUE:
03277     case FCMP_OEQ: case FCMP_ONE:
03278     case FCMP_UEQ: case FCMP_UNE:
03279     case FCMP_ORD: case FCMP_UNO:
03280       return pred;
03281     case FCMP_OGT: return FCMP_OLT;
03282     case FCMP_OLT: return FCMP_OGT;
03283     case FCMP_OGE: return FCMP_OLE;
03284     case FCMP_OLE: return FCMP_OGE;
03285     case FCMP_UGT: return FCMP_ULT;
03286     case FCMP_ULT: return FCMP_UGT;
03287     case FCMP_UGE: return FCMP_ULE;
03288     case FCMP_ULE: return FCMP_UGE;
03289   }
03290 }
03291 
03292 bool CmpInst::isUnsigned(unsigned short predicate) {
03293   switch (predicate) {
03294     default: return false;
03295     case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_ULE: case ICmpInst::ICMP_UGT: 
03296     case ICmpInst::ICMP_UGE: return true;
03297   }
03298 }
03299 
03300 bool CmpInst::isSigned(unsigned short predicate) {
03301   switch (predicate) {
03302     default: return false;
03303     case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_SLE: case ICmpInst::ICMP_SGT: 
03304     case ICmpInst::ICMP_SGE: return true;
03305   }
03306 }
03307 
03308 bool CmpInst::isOrdered(unsigned short predicate) {
03309   switch (predicate) {
03310     default: return false;
03311     case FCmpInst::FCMP_OEQ: case FCmpInst::FCMP_ONE: case FCmpInst::FCMP_OGT: 
03312     case FCmpInst::FCMP_OLT: case FCmpInst::FCMP_OGE: case FCmpInst::FCMP_OLE: 
03313     case FCmpInst::FCMP_ORD: return true;
03314   }
03315 }
03316       
03317 bool CmpInst::isUnordered(unsigned short predicate) {
03318   switch (predicate) {
03319     default: return false;
03320     case FCmpInst::FCMP_UEQ: case FCmpInst::FCMP_UNE: case FCmpInst::FCMP_UGT: 
03321     case FCmpInst::FCMP_ULT: case FCmpInst::FCMP_UGE: case FCmpInst::FCMP_ULE: 
03322     case FCmpInst::FCMP_UNO: return true;
03323   }
03324 }
03325 
03326 bool CmpInst::isTrueWhenEqual(unsigned short predicate) {
03327   switch(predicate) {
03328     default: return false;
03329     case ICMP_EQ:   case ICMP_UGE: case ICMP_ULE: case ICMP_SGE: case ICMP_SLE:
03330     case FCMP_TRUE: case FCMP_UEQ: case FCMP_UGE: case FCMP_ULE: return true;
03331   }
03332 }
03333 
03334 bool CmpInst::isFalseWhenEqual(unsigned short predicate) {
03335   switch(predicate) {
03336   case ICMP_NE:    case ICMP_UGT: case ICMP_ULT: case ICMP_SGT: case ICMP_SLT:
03337   case FCMP_FALSE: case FCMP_ONE: case FCMP_OGT: case FCMP_OLT: return true;
03338   default: return false;
03339   }
03340 }
03341 
03342 
03343 //===----------------------------------------------------------------------===//
03344 //                        SwitchInst Implementation
03345 //===----------------------------------------------------------------------===//
03346 
03347 void SwitchInst::init(Value *Value, BasicBlock *Default, unsigned NumReserved) {
03348   assert(Value && Default && NumReserved);
03349   ReservedSpace = NumReserved;
03350   NumOperands = 2;
03351   OperandList = allocHungoffUses(ReservedSpace);
03352 
03353   OperandList[0] = Value;
03354   OperandList[1] = Default;
03355 }
03356 
03357 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
03358 /// switch on and a default destination.  The number of additional cases can
03359 /// be specified here to make memory allocation more efficient.  This
03360 /// constructor can also autoinsert before another instruction.
03361 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
03362                        Instruction *InsertBefore)
03363   : TerminatorInst(Type::getVoidTy(Value->getContext()), Instruction::Switch,
03364                    nullptr, 0, InsertBefore) {
03365   init(Value, Default, 2+NumCases*2);
03366 }
03367 
03368 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
03369 /// switch on and a default destination.  The number of additional cases can
03370 /// be specified here to make memory allocation more efficient.  This
03371 /// constructor also autoinserts at the end of the specified BasicBlock.
03372 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
03373                        BasicBlock *InsertAtEnd)
03374   : TerminatorInst(Type::getVoidTy(Value->getContext()), Instruction::Switch,
03375                    nullptr, 0, InsertAtEnd) {
03376   init(Value, Default, 2+NumCases*2);
03377 }
03378 
03379 SwitchInst::SwitchInst(const SwitchInst &SI)
03380   : TerminatorInst(SI.getType(), Instruction::Switch, nullptr, 0) {
03381   init(SI.getCondition(), SI.getDefaultDest(), SI.getNumOperands());
03382   NumOperands = SI.getNumOperands();
03383   Use *OL = OperandList, *InOL = SI.OperandList;
03384   for (unsigned i = 2, E = SI.getNumOperands(); i != E; i += 2) {
03385     OL[i] = InOL[i];
03386     OL[i+1] = InOL[i+1];
03387   }
03388   SubclassOptionalData = SI.SubclassOptionalData;
03389 }
03390 
03391 SwitchInst::~SwitchInst() {
03392   dropHungoffUses();
03393 }
03394 
03395 
03396 /// addCase - Add an entry to the switch instruction...
03397 ///
03398 void SwitchInst::addCase(ConstantInt *OnVal, BasicBlock *Dest) {
03399   unsigned NewCaseIdx = getNumCases(); 
03400   unsigned OpNo = NumOperands;
03401   if (OpNo+2 > ReservedSpace)
03402     growOperands();  // Get more space!
03403   // Initialize some new operands.
03404   assert(OpNo+1 < ReservedSpace && "Growing didn't work!");
03405   NumOperands = OpNo+2;
03406   CaseIt Case(this, NewCaseIdx);
03407   Case.setValue(OnVal);
03408   Case.setSuccessor(Dest);
03409 }
03410 
03411 /// removeCase - This method removes the specified case and its successor
03412 /// from the switch instruction.
03413 void SwitchInst::removeCase(CaseIt i) {
03414   unsigned idx = i.getCaseIndex();
03415   
03416   assert(2 + idx*2 < getNumOperands() && "Case index out of range!!!");
03417 
03418   unsigned NumOps = getNumOperands();
03419   Use *OL = OperandList;
03420 
03421   // Overwrite this case with the end of the list.
03422   if (2 + (idx + 1) * 2 != NumOps) {
03423     OL[2 + idx * 2] = OL[NumOps - 2];
03424     OL[2 + idx * 2 + 1] = OL[NumOps - 1];
03425   }
03426 
03427   // Nuke the last value.
03428   OL[NumOps-2].set(nullptr);
03429   OL[NumOps-2+1].set(nullptr);
03430   NumOperands = NumOps-2;
03431 }
03432 
03433 /// growOperands - grow operands - This grows the operand list in response
03434 /// to a push_back style of operation.  This grows the number of ops by 3 times.
03435 ///
03436 void SwitchInst::growOperands() {
03437   unsigned e = getNumOperands();
03438   unsigned NumOps = e*3;
03439 
03440   ReservedSpace = NumOps;
03441   Use *NewOps = allocHungoffUses(NumOps);
03442   Use *OldOps = OperandList;
03443   for (unsigned i = 0; i != e; ++i) {
03444       NewOps[i] = OldOps[i];
03445   }
03446   OperandList = NewOps;
03447   Use::zap(OldOps, OldOps + e, true);
03448 }
03449 
03450 
03451 BasicBlock *SwitchInst::getSuccessorV(unsigned idx) const {
03452   return getSuccessor(idx);
03453 }
03454 unsigned SwitchInst::getNumSuccessorsV() const {
03455   return getNumSuccessors();
03456 }
03457 void SwitchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
03458   setSuccessor(idx, B);
03459 }
03460 
03461 //===----------------------------------------------------------------------===//
03462 //                        IndirectBrInst Implementation
03463 //===----------------------------------------------------------------------===//
03464 
03465 void IndirectBrInst::init(Value *Address, unsigned NumDests) {
03466   assert(Address && Address->getType()->isPointerTy() &&
03467          "Address of indirectbr must be a pointer");
03468   ReservedSpace = 1+NumDests;
03469   NumOperands = 1;
03470   OperandList = allocHungoffUses(ReservedSpace);
03471   
03472   OperandList[0] = Address;
03473 }
03474 
03475 
03476 /// growOperands - grow operands - This grows the operand list in response
03477 /// to a push_back style of operation.  This grows the number of ops by 2 times.
03478 ///
03479 void IndirectBrInst::growOperands() {
03480   unsigned e = getNumOperands();
03481   unsigned NumOps = e*2;
03482   
03483   ReservedSpace = NumOps;
03484   Use *NewOps = allocHungoffUses(NumOps);
03485   Use *OldOps = OperandList;
03486   for (unsigned i = 0; i != e; ++i)
03487     NewOps[i] = OldOps[i];
03488   OperandList = NewOps;
03489   Use::zap(OldOps, OldOps + e, true);
03490 }
03491 
03492 IndirectBrInst::IndirectBrInst(Value *Address, unsigned NumCases,
03493                                Instruction *InsertBefore)
03494 : TerminatorInst(Type::getVoidTy(Address->getContext()),Instruction::IndirectBr,
03495                  nullptr, 0, InsertBefore) {
03496   init(Address, NumCases);
03497 }
03498 
03499 IndirectBrInst::IndirectBrInst(Value *Address, unsigned NumCases,
03500                                BasicBlock *InsertAtEnd)
03501 : TerminatorInst(Type::getVoidTy(Address->getContext()),Instruction::IndirectBr,
03502                  nullptr, 0, InsertAtEnd) {
03503   init(Address, NumCases);
03504 }
03505 
03506 IndirectBrInst::IndirectBrInst(const IndirectBrInst &IBI)
03507   : TerminatorInst(Type::getVoidTy(IBI.getContext()), Instruction::IndirectBr,
03508                    allocHungoffUses(IBI.getNumOperands()),
03509                    IBI.getNumOperands()) {
03510   Use *OL = OperandList, *InOL = IBI.OperandList;
03511   for (unsigned i = 0, E = IBI.getNumOperands(); i != E; ++i)
03512     OL[i] = InOL[i];
03513   SubclassOptionalData = IBI.SubclassOptionalData;
03514 }
03515 
03516 IndirectBrInst::~IndirectBrInst() {
03517   dropHungoffUses();
03518 }
03519 
03520 /// addDestination - Add a destination.
03521 ///
03522 void IndirectBrInst::addDestination(BasicBlock *DestBB) {
03523   unsigned OpNo = NumOperands;
03524   if (OpNo+1 > ReservedSpace)
03525     growOperands();  // Get more space!
03526   // Initialize some new operands.
03527   assert(OpNo < ReservedSpace && "Growing didn't work!");
03528   NumOperands = OpNo+1;
03529   OperandList[OpNo] = DestBB;
03530 }
03531 
03532 /// removeDestination - This method removes the specified successor from the
03533 /// indirectbr instruction.
03534 void IndirectBrInst::removeDestination(unsigned idx) {
03535   assert(idx < getNumOperands()-1 && "Successor index out of range!");
03536   
03537   unsigned NumOps = getNumOperands();
03538   Use *OL = OperandList;
03539 
03540   // Replace this value with the last one.
03541   OL[idx+1] = OL[NumOps-1];
03542   
03543   // Nuke the last value.
03544   OL[NumOps-1].set(nullptr);
03545   NumOperands = NumOps-1;
03546 }
03547 
03548 BasicBlock *IndirectBrInst::getSuccessorV(unsigned idx) const {
03549   return getSuccessor(idx);
03550 }
03551 unsigned IndirectBrInst::getNumSuccessorsV() const {
03552   return getNumSuccessors();
03553 }
03554 void IndirectBrInst::setSuccessorV(unsigned idx, BasicBlock *B) {
03555   setSuccessor(idx, B);
03556 }
03557 
03558 //===----------------------------------------------------------------------===//
03559 //                           clone_impl() implementations
03560 //===----------------------------------------------------------------------===//
03561 
03562 // Define these methods here so vtables don't get emitted into every translation
03563 // unit that uses these classes.
03564 
03565 GetElementPtrInst *GetElementPtrInst::clone_impl() const {
03566   return new (getNumOperands()) GetElementPtrInst(*this);
03567 }
03568 
03569 BinaryOperator *BinaryOperator::clone_impl() const {
03570   return Create(getOpcode(), Op<0>(), Op<1>());
03571 }
03572 
03573 FCmpInst* FCmpInst::clone_impl() const {
03574   return new FCmpInst(getPredicate(), Op<0>(), Op<1>());
03575 }
03576 
03577 ICmpInst* ICmpInst::clone_impl() const {
03578   return new ICmpInst(getPredicate(), Op<0>(), Op<1>());
03579 }
03580 
03581 ExtractValueInst *ExtractValueInst::clone_impl() const {
03582   return new ExtractValueInst(*this);
03583 }
03584 
03585 InsertValueInst *InsertValueInst::clone_impl() const {
03586   return new InsertValueInst(*this);
03587 }
03588 
03589 AllocaInst *AllocaInst::clone_impl() const {
03590   return new AllocaInst(getAllocatedType(),
03591                         (Value*)getOperand(0),
03592                         getAlignment());
03593 }
03594 
03595 LoadInst *LoadInst::clone_impl() const {
03596   return new LoadInst(getOperand(0), Twine(), isVolatile(),
03597                       getAlignment(), getOrdering(), getSynchScope());
03598 }
03599 
03600 StoreInst *StoreInst::clone_impl() const {
03601   return new StoreInst(getOperand(0), getOperand(1), isVolatile(),
03602                        getAlignment(), getOrdering(), getSynchScope());
03603   
03604 }
03605 
03606 AtomicCmpXchgInst *AtomicCmpXchgInst::clone_impl() const {
03607   AtomicCmpXchgInst *Result =
03608     new AtomicCmpXchgInst(getOperand(0), getOperand(1), getOperand(2),
03609                           getSuccessOrdering(), getFailureOrdering(),
03610                           getSynchScope());
03611   Result->setVolatile(isVolatile());
03612   return Result;
03613 }
03614 
03615 AtomicRMWInst *AtomicRMWInst::clone_impl() const {
03616   AtomicRMWInst *Result =
03617     new AtomicRMWInst(getOperation(),getOperand(0), getOperand(1),
03618                       getOrdering(), getSynchScope());
03619   Result->setVolatile(isVolatile());
03620   return Result;
03621 }
03622 
03623 FenceInst *FenceInst::clone_impl() const {
03624   return new FenceInst(getContext(), getOrdering(), getSynchScope());
03625 }
03626 
03627 TruncInst *TruncInst::clone_impl() const {
03628   return new TruncInst(getOperand(0), getType());
03629 }
03630 
03631 ZExtInst *ZExtInst::clone_impl() const {
03632   return new ZExtInst(getOperand(0), getType());
03633 }
03634 
03635 SExtInst *SExtInst::clone_impl() const {
03636   return new SExtInst(getOperand(0), getType());
03637 }
03638 
03639 FPTruncInst *FPTruncInst::clone_impl() const {
03640   return new FPTruncInst(getOperand(0), getType());
03641 }
03642 
03643 FPExtInst *FPExtInst::clone_impl() const {
03644   return new FPExtInst(getOperand(0), getType());
03645 }
03646 
03647 UIToFPInst *UIToFPInst::clone_impl() const {
03648   return new UIToFPInst(getOperand(0), getType());
03649 }
03650 
03651 SIToFPInst *SIToFPInst::clone_impl() const {
03652   return new SIToFPInst(getOperand(0), getType());
03653 }
03654 
03655 FPToUIInst *FPToUIInst::clone_impl() const {
03656   return new FPToUIInst(getOperand(0), getType());
03657 }
03658 
03659 FPToSIInst *FPToSIInst::clone_impl() const {
03660   return new FPToSIInst(getOperand(0), getType());
03661 }
03662 
03663 PtrToIntInst *PtrToIntInst::clone_impl() const {
03664   return new PtrToIntInst(getOperand(0), getType());
03665 }
03666 
03667 IntToPtrInst *IntToPtrInst::clone_impl() const {
03668   return new IntToPtrInst(getOperand(0), getType());
03669 }
03670 
03671 BitCastInst *BitCastInst::clone_impl() const {
03672   return new BitCastInst(getOperand(0), getType());
03673 }
03674 
03675 AddrSpaceCastInst *AddrSpaceCastInst::clone_impl() const {
03676   return new AddrSpaceCastInst(getOperand(0), getType());
03677 }
03678 
03679 CallInst *CallInst::clone_impl() const {
03680   return  new(getNumOperands()) CallInst(*this);
03681 }
03682 
03683 SelectInst *SelectInst::clone_impl() const {
03684   return SelectInst::Create(getOperand(0), getOperand(1), getOperand(2));
03685 }
03686 
03687 VAArgInst *VAArgInst::clone_impl() const {
03688   return new VAArgInst(getOperand(0), getType());
03689 }
03690 
03691 ExtractElementInst *ExtractElementInst::clone_impl() const {
03692   return ExtractElementInst::Create(getOperand(0), getOperand(1));
03693 }
03694 
03695 InsertElementInst *InsertElementInst::clone_impl() const {
03696   return InsertElementInst::Create(getOperand(0), getOperand(1), getOperand(2));
03697 }
03698 
03699 ShuffleVectorInst *ShuffleVectorInst::clone_impl() const {
03700   return new ShuffleVectorInst(getOperand(0), getOperand(1), getOperand(2));
03701 }
03702 
03703 PHINode *PHINode::clone_impl() const {
03704   return new PHINode(*this);
03705 }
03706 
03707 LandingPadInst *LandingPadInst::clone_impl() const {
03708   return new LandingPadInst(*this);
03709 }
03710 
03711 ReturnInst *ReturnInst::clone_impl() const {
03712   return new(getNumOperands()) ReturnInst(*this);
03713 }
03714 
03715 BranchInst *BranchInst::clone_impl() const {
03716   return new(getNumOperands()) BranchInst(*this);
03717 }
03718 
03719 SwitchInst *SwitchInst::clone_impl() const {
03720   return new SwitchInst(*this);
03721 }
03722 
03723 IndirectBrInst *IndirectBrInst::clone_impl() const {
03724   return new IndirectBrInst(*this);
03725 }
03726 
03727 
03728 InvokeInst *InvokeInst::clone_impl() const {
03729   return new(getNumOperands()) InvokeInst(*this);
03730 }
03731 
03732 ResumeInst *ResumeInst::clone_impl() const {
03733   return new(1) ResumeInst(*this);
03734 }
03735 
03736 UnreachableInst *UnreachableInst::clone_impl() const {
03737   LLVMContext &Context = getContext();
03738   return new UnreachableInst(Context);
03739 }