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