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