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