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