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