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