LLVM API Documentation

Instructions.cpp

Go to the documentation of this file.
00001 //===-- Instructions.cpp - Implement the LLVM instructions ----------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements all of the non-inline methods for the LLVM instruction
00011 // classes.
00012 //
00013 //===----------------------------------------------------------------------===//
00014 
00015 #include "llvm/Constants.h"
00016 #include "llvm/DerivedTypes.h"
00017 #include "llvm/Function.h"
00018 #include "llvm/Instructions.h"
00019 #include "llvm/Support/CallSite.h"
00020 #include "llvm/Support/ConstantRange.h"
00021 #include "llvm/Support/MathExtras.h"
00022 using namespace llvm;
00023 
00024 //===----------------------------------------------------------------------===//
00025 //                            CallSite Class
00026 //===----------------------------------------------------------------------===//
00027 
00028 #define CALLSITE_DELEGATE_GETTER(METHOD) \
00029   Instruction *II(getInstruction());     \
00030   return isCall()                        \
00031     ? cast<CallInst>(II)->METHOD         \
00032     : cast<InvokeInst>(II)->METHOD
00033 
00034 #define CALLSITE_DELEGATE_SETTER(METHOD) \
00035   Instruction *II(getInstruction());     \
00036   if (isCall())                          \
00037     cast<CallInst>(II)->METHOD;          \
00038   else                                   \
00039     cast<InvokeInst>(II)->METHOD
00040 
00041 CallSite::CallSite(Instruction *C) {
00042   assert((isa<CallInst>(C) || isa<InvokeInst>(C)) && "Not a call!");
00043   I.setPointer(C);
00044   I.setInt(isa<CallInst>(C));
00045 }
00046 unsigned CallSite::getCallingConv() const {
00047   CALLSITE_DELEGATE_GETTER(getCallingConv());
00048 }
00049 void CallSite::setCallingConv(unsigned CC) {
00050   CALLSITE_DELEGATE_SETTER(setCallingConv(CC));
00051 }
00052 const AttrListPtr &CallSite::getAttributes() const {
00053   CALLSITE_DELEGATE_GETTER(getAttributes());
00054 }
00055 void CallSite::setAttributes(const AttrListPtr &PAL) {
00056   CALLSITE_DELEGATE_SETTER(setAttributes(PAL));
00057 }
00058 bool CallSite::paramHasAttr(uint16_t i, Attributes attr) const {
00059   CALLSITE_DELEGATE_GETTER(paramHasAttr(i, attr));
00060 }
00061 uint16_t CallSite::getParamAlignment(uint16_t i) const {
00062   CALLSITE_DELEGATE_GETTER(getParamAlignment(i));
00063 }
00064 bool CallSite::doesNotAccessMemory() const {
00065   CALLSITE_DELEGATE_GETTER(doesNotAccessMemory());
00066 }
00067 void CallSite::setDoesNotAccessMemory(bool doesNotAccessMemory) {
00068   CALLSITE_DELEGATE_SETTER(setDoesNotAccessMemory(doesNotAccessMemory));
00069 }
00070 bool CallSite::onlyReadsMemory() const {
00071   CALLSITE_DELEGATE_GETTER(onlyReadsMemory());
00072 }
00073 void CallSite::setOnlyReadsMemory(bool onlyReadsMemory) {
00074   CALLSITE_DELEGATE_SETTER(setOnlyReadsMemory(onlyReadsMemory));
00075 }
00076 bool CallSite::doesNotReturn() const {
00077  CALLSITE_DELEGATE_GETTER(doesNotReturn());
00078 }
00079 void CallSite::setDoesNotReturn(bool doesNotReturn) {
00080   CALLSITE_DELEGATE_SETTER(setDoesNotReturn(doesNotReturn));
00081 }
00082 bool CallSite::doesNotThrow() const {
00083   CALLSITE_DELEGATE_GETTER(doesNotThrow());
00084 }
00085 void CallSite::setDoesNotThrow(bool doesNotThrow) {
00086   CALLSITE_DELEGATE_SETTER(setDoesNotThrow(doesNotThrow));
00087 }
00088 
00089 bool CallSite::hasArgument(const Value *Arg) const {
00090   for (arg_iterator AI = this->arg_begin(), E = this->arg_end(); AI != E; ++AI)
00091     if (AI->get() == Arg)
00092       return true;
00093   return false;
00094 }
00095 
00096 #undef CALLSITE_DELEGATE_GETTER
00097 #undef CALLSITE_DELEGATE_SETTER
00098 
00099 //===----------------------------------------------------------------------===//
00100 //                            TerminatorInst Class
00101 //===----------------------------------------------------------------------===//
00102 
00103 // Out of line virtual method, so the vtable, etc has a home.
00104 TerminatorInst::~TerminatorInst() {
00105 }
00106 
00107 //===----------------------------------------------------------------------===//
00108 //                           UnaryInstruction Class
00109 //===----------------------------------------------------------------------===//
00110 
00111 // Out of line virtual method, so the vtable, etc has a home.
00112 UnaryInstruction::~UnaryInstruction() {
00113 }
00114 
00115 //===----------------------------------------------------------------------===//
00116 //                              SelectInst Class
00117 //===----------------------------------------------------------------------===//
00118 
00119 /// areInvalidOperands - Return a string if the specified operands are invalid
00120 /// for a select operation, otherwise return null.
00121 const char *SelectInst::areInvalidOperands(Value *Op0, Value *Op1, Value *Op2) {
00122   if (Op1->getType() != Op2->getType())
00123     return "both values to select must have same type";
00124   
00125   if (const VectorType *VT = dyn_cast<VectorType>(Op0->getType())) {
00126     // Vector select.
00127     if (VT->getElementType() != Type::Int1Ty)
00128       return "vector select condition element type must be i1";
00129     const VectorType *ET = dyn_cast<VectorType>(Op1->getType());
00130     if (ET == 0)
00131       return "selected values for vector select must be vectors";
00132     if (ET->getNumElements() != VT->getNumElements())
00133       return "vector select requires selected vectors to have "
00134                    "the same vector length as select condition";
00135   } else if (Op0->getType() != Type::Int1Ty) {
00136     return "select condition must be i1 or <n x i1>";
00137   }
00138   return 0;
00139 }
00140 
00141 
00142 //===----------------------------------------------------------------------===//
00143 //                               PHINode Class
00144 //===----------------------------------------------------------------------===//
00145 
00146 PHINode::PHINode(const PHINode &PN)
00147   : Instruction(PN.getType(), Instruction::PHI,
00148                 allocHungoffUses(PN.getNumOperands()), PN.getNumOperands()),
00149     ReservedSpace(PN.getNumOperands()) {
00150   Use *OL = OperandList;
00151   for (unsigned i = 0, e = PN.getNumOperands(); i != e; i+=2) {
00152     OL[i] = PN.getOperand(i);
00153     OL[i+1] = PN.getOperand(i+1);
00154   }
00155 }
00156 
00157 PHINode::~PHINode() {
00158   if (OperandList)
00159     dropHungoffUses(OperandList);
00160 }
00161 
00162 // removeIncomingValue - Remove an incoming value.  This is useful if a
00163 // predecessor basic block is deleted.
00164 Value *PHINode::removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty) {
00165   unsigned NumOps = getNumOperands();
00166   Use *OL = OperandList;
00167   assert(Idx*2 < NumOps && "BB not in PHI node!");
00168   Value *Removed = OL[Idx*2];
00169 
00170   // Move everything after this operand down.
00171   //
00172   // FIXME: we could just swap with the end of the list, then erase.  However,
00173   // client might not expect this to happen.  The code as it is thrashes the
00174   // use/def lists, which is kinda lame.
00175   for (unsigned i = (Idx+1)*2; i != NumOps; i += 2) {
00176     OL[i-2] = OL[i];
00177     OL[i-2+1] = OL[i+1];
00178   }
00179 
00180   // Nuke the last value.
00181   OL[NumOps-2].set(0);
00182   OL[NumOps-2+1].set(0);
00183   NumOperands = NumOps-2;
00184 
00185   // If the PHI node is dead, because it has zero entries, nuke it now.
00186   if (NumOps == 2 && DeletePHIIfEmpty) {
00187     // If anyone is using this PHI, make them use a dummy value instead...
00188     replaceAllUsesWith(UndefValue::get(getType()));
00189     eraseFromParent();
00190   }
00191   return Removed;
00192 }
00193 
00194 /// resizeOperands - resize operands - This adjusts the length of the operands
00195 /// list according to the following behavior:
00196 ///   1. If NumOps == 0, grow the operand list in response to a push_back style
00197 ///      of operation.  This grows the number of ops by 1.5 times.
00198 ///   2. If NumOps > NumOperands, reserve space for NumOps operands.
00199 ///   3. If NumOps == NumOperands, trim the reserved space.
00200 ///
00201 void PHINode::resizeOperands(unsigned NumOps) {
00202   unsigned e = getNumOperands();
00203   if (NumOps == 0) {
00204     NumOps = e*3/2;
00205     if (NumOps < 4) NumOps = 4;      // 4 op PHI nodes are VERY common.
00206   } else if (NumOps*2 > NumOperands) {
00207     // No resize needed.
00208     if (ReservedSpace >= NumOps) return;
00209   } else if (NumOps == NumOperands) {
00210     if (ReservedSpace == NumOps) return;
00211   } else {
00212     return;
00213   }
00214 
00215   ReservedSpace = NumOps;
00216   Use *OldOps = OperandList;
00217   Use *NewOps = allocHungoffUses(NumOps);
00218   std::copy(OldOps, OldOps + e, NewOps);
00219   OperandList = NewOps;
00220   if (OldOps) Use::zap(OldOps, OldOps + e, true);
00221 }
00222 
00223 /// hasConstantValue - If the specified PHI node always merges together the same
00224 /// value, return the value, otherwise return null.
00225 ///
00226 Value *PHINode::hasConstantValue(bool AllowNonDominatingInstruction) const {
00227   // If the PHI node only has one incoming value, eliminate the PHI node...
00228   if (getNumIncomingValues() == 1) {
00229     if (getIncomingValue(0) != this)   // not  X = phi X
00230       return getIncomingValue(0);
00231     else
00232       return UndefValue::get(getType());  // Self cycle is dead.
00233   }
00234       
00235   // Otherwise if all of the incoming values are the same for the PHI, replace
00236   // the PHI node with the incoming value.
00237   //
00238   Value *InVal = 0;
00239   bool HasUndefInput = false;
00240   for (unsigned i = 0, e = getNumIncomingValues(); i != e; ++i)
00241     if (isa<UndefValue>(getIncomingValue(i))) {
00242       HasUndefInput = true;
00243     } else if (getIncomingValue(i) != this) { // Not the PHI node itself...
00244       if (InVal && getIncomingValue(i) != InVal)
00245         return 0;  // Not the same, bail out.
00246       else
00247         InVal = getIncomingValue(i);
00248     }
00249   
00250   // The only case that could cause InVal to be null is if we have a PHI node
00251   // that only has entries for itself.  In this case, there is no entry into the
00252   // loop, so kill the PHI.
00253   //
00254   if (InVal == 0) InVal = UndefValue::get(getType());
00255   
00256   // If we have a PHI node like phi(X, undef, X), where X is defined by some
00257   // instruction, we cannot always return X as the result of the PHI node.  Only
00258   // do this if X is not an instruction (thus it must dominate the PHI block),
00259   // or if the client is prepared to deal with this possibility.
00260   if (HasUndefInput && !AllowNonDominatingInstruction)
00261     if (Instruction *IV = dyn_cast<Instruction>(InVal))
00262       // If it's in the entry block, it dominates everything.
00263       if (IV->getParent() != &IV->getParent()->getParent()->getEntryBlock() ||
00264           isa<InvokeInst>(IV))
00265         return 0;   // Cannot guarantee that InVal dominates this PHINode.
00266 
00267   // All of the incoming values are the same, return the value now.
00268   return InVal;
00269 }
00270 
00271 
00272 //===----------------------------------------------------------------------===//
00273 //                        CallInst Implementation
00274 //===----------------------------------------------------------------------===//
00275 
00276 CallInst::~CallInst() {
00277 }
00278 
00279 void CallInst::init(Value *Func, Value* const *Params, unsigned NumParams) {
00280   assert(NumOperands == NumParams+1 && "NumOperands not set up?");
00281   Use *OL = OperandList;
00282   OL[0] = Func;
00283 
00284   const FunctionType *FTy =
00285     cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
00286   FTy = FTy;  // silence warning.
00287 
00288   assert((NumParams == FTy->getNumParams() ||
00289           (FTy->isVarArg() && NumParams > FTy->getNumParams())) &&
00290          "Calling a function with bad signature!");
00291   for (unsigned i = 0; i != NumParams; ++i) {
00292     assert((i >= FTy->getNumParams() || 
00293             FTy->getParamType(i) == Params[i]->getType()) &&
00294            "Calling a function with a bad signature!");
00295     OL[i+1] = Params[i];
00296   }
00297 }
00298 
00299 void CallInst::init(Value *Func, Value *Actual1, Value *Actual2) {
00300   assert(NumOperands == 3 && "NumOperands not set up?");
00301   Use *OL = OperandList;
00302   OL[0] = Func;
00303   OL[1] = Actual1;
00304   OL[2] = Actual2;
00305 
00306   const FunctionType *FTy =
00307     cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
00308   FTy = FTy;  // silence warning.
00309 
00310   assert((FTy->getNumParams() == 2 ||
00311           (FTy->isVarArg() && FTy->getNumParams() < 2)) &&
00312          "Calling a function with bad signature");
00313   assert((0 >= FTy->getNumParams() || 
00314           FTy->getParamType(0) == Actual1->getType()) &&
00315          "Calling a function with a bad signature!");
00316   assert((1 >= FTy->getNumParams() || 
00317           FTy->getParamType(1) == Actual2->getType()) &&
00318          "Calling a function with a bad signature!");
00319 }
00320 
00321 void CallInst::init(Value *Func, Value *Actual) {
00322   assert(NumOperands == 2 && "NumOperands not set up?");
00323   Use *OL = OperandList;
00324   OL[0] = Func;
00325   OL[1] = Actual;
00326 
00327   const FunctionType *FTy =
00328     cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
00329   FTy = FTy;  // silence warning.
00330 
00331   assert((FTy->getNumParams() == 1 ||
00332           (FTy->isVarArg() && FTy->getNumParams() == 0)) &&
00333          "Calling a function with bad signature");
00334   assert((0 == FTy->getNumParams() || 
00335           FTy->getParamType(0) == Actual->getType()) &&
00336          "Calling a function with a bad signature!");
00337 }
00338 
00339 void CallInst::init(Value *Func) {
00340   assert(NumOperands == 1 && "NumOperands not set up?");
00341   Use *OL = OperandList;
00342   OL[0] = Func;
00343 
00344   const FunctionType *FTy =
00345     cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
00346   FTy = FTy;  // silence warning.
00347 
00348   assert(FTy->getNumParams() == 0 && "Calling a function with bad signature");
00349 }
00350 
00351 CallInst::CallInst(Value *Func, Value* Actual, const std::string &Name,
00352                    Instruction *InsertBefore)
00353   : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
00354                                    ->getElementType())->getReturnType(),
00355                 Instruction::Call,
00356                 OperandTraits<CallInst>::op_end(this) - 2,
00357                 2, InsertBefore) {
00358   init(Func, Actual);
00359   setName(Name);
00360 }
00361 
00362 CallInst::CallInst(Value *Func, Value* Actual, const std::string &Name,
00363                    BasicBlock  *InsertAtEnd)
00364   : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
00365                                    ->getElementType())->getReturnType(),
00366                 Instruction::Call,
00367                 OperandTraits<CallInst>::op_end(this) - 2,
00368                 2, InsertAtEnd) {
00369   init(Func, Actual);
00370   setName(Name);
00371 }
00372 CallInst::CallInst(Value *Func, const std::string &Name,
00373                    Instruction *InsertBefore)
00374   : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
00375                                    ->getElementType())->getReturnType(),
00376                 Instruction::Call,
00377                 OperandTraits<CallInst>::op_end(this) - 1,
00378                 1, InsertBefore) {
00379   init(Func);
00380   setName(Name);
00381 }
00382 
00383 CallInst::CallInst(Value *Func, const std::string &Name,
00384                    BasicBlock *InsertAtEnd)
00385   : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
00386                                    ->getElementType())->getReturnType(),
00387                 Instruction::Call,
00388                 OperandTraits<CallInst>::op_end(this) - 1,
00389                 1, InsertAtEnd) {
00390   init(Func);
00391   setName(Name);
00392 }
00393 
00394 CallInst::CallInst(const CallInst &CI)
00395   : Instruction(CI.getType(), Instruction::Call,
00396                 OperandTraits<CallInst>::op_end(this) - CI.getNumOperands(),
00397                 CI.getNumOperands()) {
00398   setAttributes(CI.getAttributes());
00399   SubclassData = CI.SubclassData;
00400   Use *OL = OperandList;
00401   Use *InOL = CI.OperandList;
00402   for (unsigned i = 0, e = CI.getNumOperands(); i != e; ++i)
00403     OL[i] = InOL[i];
00404 }
00405 
00406 void CallInst::addAttribute(unsigned i, Attributes attr) {
00407   AttrListPtr PAL = getAttributes();
00408   PAL = PAL.addAttr(i, attr);
00409   setAttributes(PAL);
00410 }
00411 
00412 void CallInst::removeAttribute(unsigned i, Attributes attr) {
00413   AttrListPtr PAL = getAttributes();
00414   PAL = PAL.removeAttr(i, attr);
00415   setAttributes(PAL);
00416 }
00417 
00418 bool CallInst::paramHasAttr(unsigned i, Attributes attr) const {
00419   if (AttributeList.paramHasAttr(i, attr))
00420     return true;
00421   if (const Function *F = getCalledFunction())
00422     return F->paramHasAttr(i, attr);
00423   return false;
00424 }
00425 
00426 
00427 //===----------------------------------------------------------------------===//
00428 //                        InvokeInst Implementation
00429 //===----------------------------------------------------------------------===//
00430 
00431 void InvokeInst::init(Value *Fn, BasicBlock *IfNormal, BasicBlock *IfException,
00432                       Value* const *Args, unsigned NumArgs) {
00433   assert(NumOperands == 3+NumArgs && "NumOperands not set up?");
00434   Use *OL = OperandList;
00435   OL[0] = Fn;
00436   OL[1] = IfNormal;
00437   OL[2] = IfException;
00438   const FunctionType *FTy =
00439     cast<FunctionType>(cast<PointerType>(Fn->getType())->getElementType());
00440   FTy = FTy;  // silence warning.
00441 
00442   assert(((NumArgs == FTy->getNumParams()) ||
00443           (FTy->isVarArg() && NumArgs > FTy->getNumParams())) &&
00444          "Calling a function with bad signature");
00445 
00446   for (unsigned i = 0, e = NumArgs; i != e; i++) {
00447     assert((i >= FTy->getNumParams() || 
00448             FTy->getParamType(i) == Args[i]->getType()) &&
00449            "Invoking a function with a bad signature!");
00450     
00451     OL[i+3] = Args[i];
00452   }
00453 }
00454 
00455 InvokeInst::InvokeInst(const InvokeInst &II)
00456   : TerminatorInst(II.getType(), Instruction::Invoke,
00457                    OperandTraits<InvokeInst>::op_end(this)
00458                    - II.getNumOperands(),
00459                    II.getNumOperands()) {
00460   setAttributes(II.getAttributes());
00461   SubclassData = II.SubclassData;
00462   Use *OL = OperandList, *InOL = II.OperandList;
00463   for (unsigned i = 0, e = II.getNumOperands(); i != e; ++i)
00464     OL[i] = InOL[i];
00465 }
00466 
00467 BasicBlock *InvokeInst::getSuccessorV(unsigned idx) const {
00468   return getSuccessor(idx);
00469 }
00470 unsigned InvokeInst::getNumSuccessorsV() const {
00471   return getNumSuccessors();
00472 }
00473 void InvokeInst::setSuccessorV(unsigned idx, BasicBlock *B) {
00474   return setSuccessor(idx, B);
00475 }
00476 
00477 bool InvokeInst::paramHasAttr(unsigned i, Attributes attr) const {
00478   if (AttributeList.paramHasAttr(i, attr))
00479     return true;
00480   if (const Function *F = getCalledFunction())
00481     return F->paramHasAttr(i, attr);
00482   return false;
00483 }
00484 
00485 void InvokeInst::addAttribute(unsigned i, Attributes attr) {
00486   AttrListPtr PAL = getAttributes();
00487   PAL = PAL.addAttr(i, attr);
00488   setAttributes(PAL);
00489 }
00490 
00491 void InvokeInst::removeAttribute(unsigned i, Attributes attr) {
00492   AttrListPtr PAL = getAttributes();
00493   PAL = PAL.removeAttr(i, attr);
00494   setAttributes(PAL);
00495 }
00496 
00497 
00498 //===----------------------------------------------------------------------===//
00499 //                        ReturnInst Implementation
00500 //===----------------------------------------------------------------------===//
00501 
00502 ReturnInst::ReturnInst(const ReturnInst &RI)
00503   : TerminatorInst(Type::VoidTy, Instruction::Ret,
00504                    OperandTraits<ReturnInst>::op_end(this) -
00505                      RI.getNumOperands(),
00506                    RI.getNumOperands()) {
00507   if (RI.getNumOperands())
00508     Op<0>() = RI.Op<0>();
00509 }
00510 
00511 ReturnInst::ReturnInst(Value *retVal, Instruction *InsertBefore)
00512   : TerminatorInst(Type::VoidTy, Instruction::Ret,
00513                    OperandTraits<ReturnInst>::op_end(this) - !!retVal, !!retVal,
00514                    InsertBefore) {
00515   if (retVal)
00516     Op<0>() = retVal;
00517 }
00518 ReturnInst::ReturnInst(Value *retVal, BasicBlock *InsertAtEnd)
00519   : TerminatorInst(Type::VoidTy, Instruction::Ret,
00520                    OperandTraits<ReturnInst>::op_end(this) - !!retVal, !!retVal,
00521                    InsertAtEnd) {
00522   if (retVal)
00523     Op<0>() = retVal;
00524 }
00525 ReturnInst::ReturnInst(BasicBlock *InsertAtEnd)
00526   : TerminatorInst(Type::VoidTy, Instruction::Ret,
00527                    OperandTraits<ReturnInst>::op_end(this), 0, InsertAtEnd) {
00528 }
00529 
00530 unsigned ReturnInst::getNumSuccessorsV() const {
00531   return getNumSuccessors();
00532 }
00533 
00534 /// Out-of-line ReturnInst method, put here so the C++ compiler can choose to
00535 /// emit the vtable for the class in this translation unit.
00536 void ReturnInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
00537   assert(0 && "ReturnInst has no successors!");
00538 }
00539 
00540 BasicBlock *ReturnInst::getSuccessorV(unsigned idx) const {
00541   assert(0 && "ReturnInst has no successors!");
00542   abort();
00543   return 0;
00544 }
00545 
00546 ReturnInst::~ReturnInst() {
00547 }
00548 
00549 //===----------------------------------------------------------------------===//
00550 //                        UnwindInst Implementation
00551 //===----------------------------------------------------------------------===//
00552 
00553 UnwindInst::UnwindInst(Instruction *InsertBefore)
00554   : TerminatorInst(Type::VoidTy, Instruction::Unwind, 0, 0, InsertBefore) {
00555 }
00556 UnwindInst::UnwindInst(BasicBlock *InsertAtEnd)
00557   : TerminatorInst(Type::VoidTy, Instruction::Unwind, 0, 0, InsertAtEnd) {
00558 }
00559 
00560 
00561 unsigned UnwindInst::getNumSuccessorsV() const {
00562   return getNumSuccessors();
00563 }
00564 
00565 void UnwindInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
00566   assert(0 && "UnwindInst has no successors!");
00567 }
00568 
00569 BasicBlock *UnwindInst::getSuccessorV(unsigned idx) const {
00570   assert(0 && "UnwindInst has no successors!");
00571   abort();
00572   return 0;
00573 }
00574 
00575 //===----------------------------------------------------------------------===//
00576 //                      UnreachableInst Implementation
00577 //===----------------------------------------------------------------------===//
00578 
00579 UnreachableInst::UnreachableInst(Instruction *InsertBefore)
00580   : TerminatorInst(Type::VoidTy, Instruction::Unreachable, 0, 0, InsertBefore) {
00581 }
00582 UnreachableInst::UnreachableInst(BasicBlock *InsertAtEnd)
00583   : TerminatorInst(Type::VoidTy, Instruction::Unreachable, 0, 0, InsertAtEnd) {
00584 }
00585 
00586 unsigned UnreachableInst::getNumSuccessorsV() const {
00587   return getNumSuccessors();
00588 }
00589 
00590 void UnreachableInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
00591   assert(0 && "UnwindInst has no successors!");
00592 }
00593 
00594 BasicBlock *UnreachableInst::getSuccessorV(unsigned idx) const {
00595   assert(0 && "UnwindInst has no successors!");
00596   abort();
00597   return 0;
00598 }
00599 
00600 //===----------------------------------------------------------------------===//
00601 //                        BranchInst Implementation
00602 //===----------------------------------------------------------------------===//
00603 
00604 void BranchInst::AssertOK() {
00605   if (isConditional())
00606     assert(getCondition()->getType() == Type::Int1Ty &&
00607            "May only branch on boolean predicates!");
00608 }
00609 
00610 BranchInst::BranchInst(BasicBlock *IfTrue, Instruction *InsertBefore)
00611   : TerminatorInst(Type::VoidTy, Instruction::Br,
00612                    OperandTraits<BranchInst>::op_end(this) - 1,
00613                    1, InsertBefore) {
00614   assert(IfTrue != 0 && "Branch destination may not be null!");
00615   Op<0>() = IfTrue;
00616 }
00617 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
00618                        Instruction *InsertBefore)
00619   : TerminatorInst(Type::VoidTy, Instruction::Br,
00620                    OperandTraits<BranchInst>::op_end(this) - 3,
00621                    3, InsertBefore) {
00622   Op<0>() = IfTrue;
00623   Op<1>() = IfFalse;
00624   Op<2>() = Cond;
00625 #ifndef NDEBUG
00626   AssertOK();
00627 #endif
00628 }
00629 
00630 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *InsertAtEnd)
00631   : TerminatorInst(Type::VoidTy, Instruction::Br,
00632                    OperandTraits<BranchInst>::op_end(this) - 1,
00633                    1, InsertAtEnd) {
00634   assert(IfTrue != 0 && "Branch destination may not be null!");
00635   Op<0>() = IfTrue;
00636 }
00637 
00638 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
00639            BasicBlock *InsertAtEnd)
00640   : TerminatorInst(Type::VoidTy, Instruction::Br,
00641                    OperandTraits<BranchInst>::op_end(this) - 3,
00642                    3, InsertAtEnd) {
00643   Op<0>() = IfTrue;
00644   Op<1>() = IfFalse;
00645   Op<2>() = Cond;
00646 #ifndef NDEBUG
00647   AssertOK();
00648 #endif
00649 }
00650 
00651 
00652 BranchInst::BranchInst(const BranchInst &BI) :
00653   TerminatorInst(Type::VoidTy, Instruction::Br,
00654                  OperandTraits<BranchInst>::op_end(this) - BI.getNumOperands(),
00655                  BI.getNumOperands()) {
00656   OperandList[0] = BI.getOperand(0);
00657   if (BI.getNumOperands() != 1) {
00658     assert(BI.getNumOperands() == 3 && "BR can have 1 or 3 operands!");
00659     OperandList[1] = BI.getOperand(1);
00660     OperandList[2] = BI.getOperand(2);
00661   }
00662 }
00663 
00664 BasicBlock *BranchInst::getSuccessorV(unsigned idx) const {
00665   return getSuccessor(idx);
00666 }
00667 unsigned BranchInst::getNumSuccessorsV() const {
00668   return getNumSuccessors();
00669 }
00670 void BranchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
00671   setSuccessor(idx, B);
00672 }
00673 
00674 
00675 //===----------------------------------------------------------------------===//
00676 //                        AllocationInst Implementation
00677 //===----------------------------------------------------------------------===//
00678 
00679 static Value *getAISize(Value *Amt) {
00680   if (!Amt)
00681     Amt = ConstantInt::get(Type::Int32Ty, 1);
00682   else {
00683     assert(!isa<BasicBlock>(Amt) &&
00684            "Passed basic block into allocation size parameter! Use other ctor");
00685     assert(Amt->getType() == Type::Int32Ty &&
00686            "Malloc/Allocation array size is not a 32-bit integer!");
00687   }
00688   return Amt;
00689 }
00690 
00691 AllocationInst::AllocationInst(const Type *Ty, Value *ArraySize, unsigned iTy,
00692                                unsigned Align, const std::string &Name,
00693                                Instruction *InsertBefore)
00694   : UnaryInstruction(PointerType::getUnqual(Ty), iTy, getAISize(ArraySize),
00695                      InsertBefore) {
00696   setAlignment(Align);
00697   assert(Ty != Type::VoidTy && "Cannot allocate void!");
00698   setName(Name);
00699 }
00700 
00701 AllocationInst::AllocationInst(const Type *Ty, Value *ArraySize, unsigned iTy,
00702                                unsigned Align, const std::string &Name,
00703                                BasicBlock *InsertAtEnd)
00704   : UnaryInstruction(PointerType::getUnqual(Ty), iTy, getAISize(ArraySize),
00705                      InsertAtEnd) {
00706   setAlignment(Align);
00707   assert(Ty != Type::VoidTy && "Cannot allocate void!");
00708   setName(Name);
00709 }
00710 
00711 // Out of line virtual method, so the vtable, etc has a home.
00712 AllocationInst::~AllocationInst() {
00713 }
00714 
00715 void AllocationInst::setAlignment(unsigned Align) {
00716   assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
00717   SubclassData = Log2_32(Align) + 1;
00718   assert(getAlignment() == Align && "Alignment representation error!");
00719 }
00720 
00721 bool AllocationInst::isArrayAllocation() const {
00722   if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(0)))
00723     return CI->getZExtValue() != 1;
00724   return true;
00725 }
00726 
00727 const Type *AllocationInst::getAllocatedType() const {
00728   return getType()->getElementType();
00729 }
00730 
00731 AllocaInst::AllocaInst(const AllocaInst &AI)
00732   : AllocationInst(AI.getType()->getElementType(), (Value*)AI.getOperand(0),
00733                    Instruction::Alloca, AI.getAlignment()) {
00734 }
00735 
00736 /// isStaticAlloca - Return true if this alloca is in the entry block of the
00737 /// function and is a constant size.  If so, the code generator will fold it
00738 /// into the prolog/epilog code, so it is basically free.
00739 bool AllocaInst::isStaticAlloca() const {
00740   // Must be constant size.
00741   if (!isa<ConstantInt>(getArraySize())) return false;
00742   
00743   // Must be in the entry block.
00744   const BasicBlock *Parent = getParent();
00745   return Parent == &Parent->getParent()->front();
00746 }
00747 
00748 MallocInst::MallocInst(const MallocInst &MI)
00749   : AllocationInst(MI.getType()->getElementType(), (Value*)MI.getOperand(0),
00750                    Instruction::Malloc, MI.getAlignment()) {
00751 }
00752 
00753 //===----------------------------------------------------------------------===//
00754 //                             FreeInst Implementation
00755 //===----------------------------------------------------------------------===//
00756 
00757 void FreeInst::AssertOK() {
00758   assert(isa<PointerType>(getOperand(0)->getType()) &&
00759          "Can not free something of nonpointer type!");
00760 }
00761 
00762 FreeInst::FreeInst(Value *Ptr, Instruction *InsertBefore)
00763   : UnaryInstruction(Type::VoidTy, Free, Ptr, InsertBefore) {
00764   AssertOK();
00765 }
00766 
00767 FreeInst::FreeInst(Value *Ptr, BasicBlock *InsertAtEnd)
00768   : UnaryInstruction(Type::VoidTy, Free, Ptr, InsertAtEnd) {
00769   AssertOK();
00770 }
00771 
00772 
00773 //===----------------------------------------------------------------------===//
00774 //                           LoadInst Implementation
00775 //===----------------------------------------------------------------------===//
00776 
00777 void LoadInst::AssertOK() {
00778   assert(isa<PointerType>(getOperand(0)->getType()) &&
00779          "Ptr must have pointer type.");
00780 }
00781 
00782 LoadInst::LoadInst(Value *Ptr, const std::string &Name, Instruction *InsertBef)
00783   : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
00784                      Load, Ptr, InsertBef) {
00785   setVolatile(false);
00786   setAlignment(0);
00787   AssertOK();
00788   setName(Name);
00789 }
00790 
00791 LoadInst::LoadInst(Value *Ptr, const std::string &Name, BasicBlock *InsertAE)
00792   : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
00793                      Load, Ptr, InsertAE) {
00794   setVolatile(false);
00795   setAlignment(0);
00796   AssertOK();
00797   setName(Name);
00798 }
00799 
00800 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile,
00801                    Instruction *InsertBef)
00802   : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
00803                      Load, Ptr, InsertBef) {
00804   setVolatile(isVolatile);
00805   setAlignment(0);
00806   AssertOK();
00807   setName(Name);
00808 }
00809 
00810 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile, 
00811                    unsigned Align, Instruction *InsertBef)
00812   : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
00813                      Load, Ptr, InsertBef) {
00814   setVolatile(isVolatile);
00815   setAlignment(Align);
00816   AssertOK();
00817   setName(Name);
00818 }
00819 
00820 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile, 
00821                    unsigned Align, BasicBlock *InsertAE)
00822   : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
00823                      Load, Ptr, InsertAE) {
00824   setVolatile(isVolatile);
00825   setAlignment(Align);
00826   AssertOK();
00827   setName(Name);
00828 }
00829 
00830 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile,
00831                    BasicBlock *InsertAE)
00832   : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
00833                      Load, Ptr, InsertAE) {
00834   setVolatile(isVolatile);
00835   setAlignment(0);
00836   AssertOK();
00837   setName(Name);
00838 }
00839 
00840 
00841 
00842 LoadInst::LoadInst(Value *Ptr, const char *Name, Instruction *InsertBef)
00843   : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
00844                      Load, Ptr, InsertBef) {
00845   setVolatile(false);
00846   setAlignment(0);
00847   AssertOK();
00848   if (Name && Name[0]) setName(Name);
00849 }
00850 
00851 LoadInst::LoadInst(Value *Ptr, const char *Name, BasicBlock *InsertAE)
00852   : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
00853                      Load, Ptr, InsertAE) {
00854   setVolatile(false);
00855   setAlignment(0);
00856   AssertOK();
00857   if (Name && Name[0]) setName(Name);
00858 }
00859 
00860 LoadInst::LoadInst(Value *Ptr, const char *Name, bool isVolatile,
00861                    Instruction *InsertBef)
00862 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
00863                    Load, Ptr, InsertBef) {
00864   setVolatile(isVolatile);
00865   setAlignment(0);
00866   AssertOK();
00867   if (Name && Name[0]) setName(Name);
00868 }
00869 
00870 LoadInst::LoadInst(Value *Ptr, const char *Name, bool isVolatile,
00871                    BasicBlock *InsertAE)
00872   : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
00873                      Load, Ptr, InsertAE) {
00874   setVolatile(isVolatile);
00875   setAlignment(0);
00876   AssertOK();
00877   if (Name && Name[0]) setName(Name);
00878 }
00879 
00880 void LoadInst::setAlignment(unsigned Align) {
00881   assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
00882   SubclassData = (SubclassData & 1) | ((Log2_32(Align)+1)<<1);
00883 }
00884 
00885 //===----------------------------------------------------------------------===//
00886 //                           StoreInst Implementation
00887 //===----------------------------------------------------------------------===//
00888 
00889 void StoreInst::AssertOK() {
00890   assert(getOperand(0) && getOperand(1) && "Both operands must be non-null!");
00891   assert(isa<PointerType>(getOperand(1)->getType()) &&
00892          "Ptr must have pointer type!");
00893   assert(getOperand(0)->getType() ==
00894                  cast<PointerType>(getOperand(1)->getType())->getElementType()
00895          && "Ptr must be a pointer to Val type!");
00896 }
00897 
00898 
00899 StoreInst::StoreInst(Value *val, Value *addr, Instruction *InsertBefore)
00900   : Instruction(Type::VoidTy, Store,
00901                 OperandTraits<StoreInst>::op_begin(this),
00902                 OperandTraits<StoreInst>::operands(this),
00903                 InsertBefore) {
00904   Op<0>() = val;
00905   Op<1>() = addr;
00906   setVolatile(false);
00907   setAlignment(0);
00908   AssertOK();
00909 }
00910 
00911 StoreInst::StoreInst(Value *val, Value *addr, BasicBlock *InsertAtEnd)
00912   : Instruction(Type::VoidTy, Store,
00913                 OperandTraits<StoreInst>::op_begin(this),
00914                 OperandTraits<StoreInst>::operands(this),
00915                 InsertAtEnd) {
00916   Op<0>() = val;
00917   Op<1>() = addr;
00918   setVolatile(false);
00919   setAlignment(0);
00920   AssertOK();
00921 }
00922 
00923 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
00924                      Instruction *InsertBefore)
00925   : Instruction(Type::VoidTy, Store,
00926                 OperandTraits<StoreInst>::op_begin(this),
00927                 OperandTraits<StoreInst>::operands(this),
00928                 InsertBefore) {
00929   Op<0>() = val;
00930   Op<1>() = addr;
00931   setVolatile(isVolatile);
00932   setAlignment(0);
00933   AssertOK();
00934 }
00935 
00936 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
00937                      unsigned Align, Instruction *InsertBefore)
00938   : Instruction(Type::VoidTy, Store,
00939                 OperandTraits<StoreInst>::op_begin(this),
00940                 OperandTraits<StoreInst>::operands(this),
00941                 InsertBefore) {
00942   Op<0>() = val;
00943   Op<1>() = addr;
00944   setVolatile(isVolatile);
00945   setAlignment(Align);
00946   AssertOK();
00947 }
00948 
00949 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
00950                      unsigned Align, BasicBlock *InsertAtEnd)
00951   : Instruction(Type::VoidTy, Store,
00952                 OperandTraits<StoreInst>::op_begin(this),
00953                 OperandTraits<StoreInst>::operands(this),
00954                 InsertAtEnd) {
00955   Op<0>() = val;
00956   Op<1>() = addr;
00957   setVolatile(isVolatile);
00958   setAlignment(Align);
00959   AssertOK();
00960 }
00961 
00962 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
00963                      BasicBlock *InsertAtEnd)
00964   : Instruction(Type::VoidTy, Store,
00965                 OperandTraits<StoreInst>::op_begin(this),
00966                 OperandTraits<StoreInst>::operands(this),
00967                 InsertAtEnd) {
00968   Op<0>() = val;
00969   Op<1>() = addr;
00970   setVolatile(isVolatile);
00971   setAlignment(0);
00972   AssertOK();
00973 }
00974 
00975 void StoreInst::setAlignment(unsigned Align) {
00976   assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
00977   SubclassData = (SubclassData & 1) | ((Log2_32(Align)+1)<<1);
00978 }
00979 
00980 //===----------------------------------------------------------------------===//
00981 //                       GetElementPtrInst Implementation
00982 //===----------------------------------------------------------------------===//
00983 
00984 static unsigned retrieveAddrSpace(const Value *Val) {
00985   return cast<PointerType>(Val->getType())->getAddressSpace();
00986 }
00987 
00988 void GetElementPtrInst::init(Value *Ptr, Value* const *Idx, unsigned NumIdx,
00989                              const std::string &Name) {
00990   assert(NumOperands == 1+NumIdx && "NumOperands not initialized?");
00991   Use *OL = OperandList;
00992   OL[0] = Ptr;
00993 
00994   for (unsigned i = 0; i != NumIdx; ++i)
00995     OL[i+1] = Idx[i];
00996 
00997   setName(Name);
00998 }
00999 
01000 void GetElementPtrInst::init(Value *Ptr, Value *Idx, const std::string &Name) {
01001   assert(NumOperands == 2 && "NumOperands not initialized?");
01002   Use *OL = OperandList;
01003   OL[0] = Ptr;
01004   OL[1] = Idx;
01005 
01006   setName(Name);
01007 }
01008 
01009 GetElementPtrInst::GetElementPtrInst(const GetElementPtrInst &GEPI)
01010   : Instruction(GEPI.getType(), GetElementPtr,
01011                 OperandTraits<GetElementPtrInst>::op_end(this)
01012                 - GEPI.getNumOperands(),
01013                 GEPI.getNumOperands()) {
01014   Use *OL = OperandList;
01015   Use *GEPIOL = GEPI.OperandList;
01016   for (unsigned i = 0, E = NumOperands; i != E; ++i)
01017     OL[i] = GEPIOL[i];
01018 }
01019 
01020 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx,
01021                                      const std::string &Name, Instruction *InBe)
01022   : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),Idx)),
01023                                  retrieveAddrSpace(Ptr)),
01024                 GetElementPtr,
01025                 OperandTraits<GetElementPtrInst>::op_end(this) - 2,
01026                 2, InBe) {
01027   init(Ptr, Idx, Name);
01028 }
01029 
01030 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx,
01031                                      const std::string &Name, BasicBlock *IAE)
01032   : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),Idx)),
01033                                  retrieveAddrSpace(Ptr)),
01034                 GetElementPtr,
01035                 OperandTraits<GetElementPtrInst>::op_end(this) - 2,
01036                 2, IAE) {
01037   init(Ptr, Idx, Name);
01038 }
01039 
01040 // getIndexedType - Returns the type of the element that would be loaded with
01041 // a load instruction with the specified parameters.
01042 //
01043 // The Idxs pointer should point to a continuous piece of memory containing the
01044 // indices, either as Value* or uint64_t.
01045 //
01046 // A null type is returned if the indices are invalid for the specified
01047 // pointer type.
01048 //
01049 template <typename IndexTy>
01050 static const Type* getIndexedTypeInternal(const Type *Ptr,
01051                                   IndexTy const *Idxs,
01052                                   unsigned NumIdx) {
01053   const PointerType *PTy = dyn_cast<PointerType>(Ptr);
01054   if (!PTy) return 0;   // Type isn't a pointer type!
01055   const Type *Agg = PTy->getElementType();
01056 
01057   // Handle the special case of the empty set index set...
01058   if (NumIdx == 0)
01059     return Agg;
01060 
01061   unsigned CurIdx = 1;
01062   for (; CurIdx != NumIdx; ++CurIdx) {
01063     const CompositeType *CT = dyn_cast<CompositeType>(Agg);
01064     if (!CT || isa<PointerType>(CT)) return 0;
01065     IndexTy Index = Idxs[CurIdx];
01066     if (!CT->indexValid(Index)) return 0;
01067     Agg = CT->getTypeAtIndex(Index);
01068 
01069     // If the new type forwards to another type, then it is in the middle
01070     // of being refined to another type (and hence, may have dropped all
01071     // references to what it was using before).  So, use the new forwarded
01072     // type.
01073     if (const Type *Ty = Agg->getForwardedType())
01074       Agg = Ty;
01075   }
01076   return CurIdx == NumIdx ? Agg : 0;
01077 }
01078 
01079 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr,
01080                                               Value* const *Idxs,
01081                                               unsigned NumIdx) {
01082   return getIndexedTypeInternal(Ptr, Idxs, NumIdx);
01083 }
01084 
01085 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr,
01086                                               uint64_t const *Idxs,
01087                                               unsigned NumIdx) {
01088   return getIndexedTypeInternal(Ptr, Idxs, NumIdx);
01089 }
01090 
01091 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr, Value *Idx) {
01092   const PointerType *PTy = dyn_cast<PointerType>(Ptr);
01093   if (!PTy) return 0;   // Type isn't a pointer type!
01094 
01095   // Check the pointer index.
01096   if (!PTy->indexValid(Idx)) return 0;
01097 
01098   return PTy->getElementType();
01099 }
01100 
01101 
01102 /// hasAllZeroIndices - Return true if all of the indices of this GEP are
01103 /// zeros.  If so, the result pointer and the first operand have the same
01104 /// value, just potentially different types.
01105 bool GetElementPtrInst::hasAllZeroIndices() const {
01106   for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
01107     if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(i))) {
01108       if (!CI->isZero()) return false;
01109     } else {
01110       return false;
01111     }
01112   }
01113   return true;
01114 }
01115 
01116 /// hasAllConstantIndices - Return true if all of the indices of this GEP are
01117 /// constant integers.  If so, the result pointer and the first operand have
01118 /// a constant offset between them.
01119 bool GetElementPtrInst::hasAllConstantIndices() const {
01120   for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
01121     if (!isa<ConstantInt>(getOperand(i)))
01122       return false;
01123   }
01124   return true;
01125 }
01126 
01127 
01128 //===----------------------------------------------------------------------===//
01129 //                           ExtractElementInst Implementation
01130 //===----------------------------------------------------------------------===//
01131 
01132 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
01133                                        const std::string &Name,
01134                                        Instruction *InsertBef)
01135   : Instruction(cast<VectorType>(Val->getType())->getElementType(),
01136                 ExtractElement,
01137                 OperandTraits<ExtractElementInst>::op_begin(this),
01138                 2, InsertBef) {
01139   assert(isValidOperands(Val, Index) &&
01140          "Invalid extractelement instruction operands!");
01141   Op<0>() = Val;
01142   Op<1>() = Index;
01143   setName(Name);
01144 }
01145 
01146 ExtractElementInst::ExtractElementInst(Value *Val, unsigned IndexV,
01147                                        const std::string &Name,
01148                                        Instruction *InsertBef)
01149   : Instruction(cast<VectorType>(Val->getType())->getElementType(),
01150                 ExtractElement,
01151                 OperandTraits<ExtractElementInst>::op_begin(this),
01152                 2, InsertBef) {
01153   Constant *Index = ConstantInt::get(Type::Int32Ty, IndexV);
01154   assert(isValidOperands(Val, Index) &&
01155          "Invalid extractelement instruction operands!");
01156   Op<0>() = Val;
01157   Op<1>() = Index;
01158   setName(Name);
01159 }
01160 
01161 
01162 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
01163                                        const std::string &Name,
01164                                        BasicBlock *InsertAE)
01165   : Instruction(cast<VectorType>(Val->getType())->getElementType(),
01166                 ExtractElement,
01167                 OperandTraits<ExtractElementInst>::op_begin(this),
01168                 2, InsertAE) {
01169   assert(isValidOperands(Val, Index) &&
01170          "Invalid extractelement instruction operands!");
01171 
01172   Op<0>() = Val;
01173   Op<1>() = Index;
01174   setName(Name);
01175 }
01176 
01177 ExtractElementInst::ExtractElementInst(Value *Val, unsigned IndexV,
01178                                        const std::string &Name,
01179                                        BasicBlock *InsertAE)
01180   : Instruction(cast<VectorType>(Val->getType())->getElementType(),
01181                 ExtractElement,
01182                 OperandTraits<ExtractElementInst>::op_begin(this),
01183                 2, InsertAE) {
01184   Constant *Index = ConstantInt::get(Type::Int32Ty, IndexV);
01185   assert(isValidOperands(Val, Index) &&
01186          "Invalid extractelement instruction operands!");
01187   
01188   Op<0>() = Val;
01189   Op<1>() = Index;
01190   setName(Name);
01191 }
01192 
01193 
01194 bool ExtractElementInst::isValidOperands(const Value *Val, const Value *Index) {
01195   if (!isa<VectorType>(Val->getType()) || Index->getType() != Type::Int32Ty)
01196     return false;
01197   return true;
01198 }
01199 
01200 
01201 //===----------------------------------------------------------------------===//
01202 //                           InsertElementInst Implementation
01203 //===----------------------------------------------------------------------===//
01204 
01205 InsertElementInst::InsertElementInst(const InsertElementInst &IE)
01206     : Instruction(IE.getType(), InsertElement,
01207                   OperandTraits<InsertElementInst>::op_begin(this), 3) {
01208   Op<0>() = IE.Op<0>();
01209   Op<1>() = IE.Op<1>();
01210   Op<2>() = IE.Op<2>();
01211 }
01212 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
01213                                      const std::string &Name,
01214                                      Instruction *InsertBef)
01215   : Instruction(Vec->getType(), InsertElement,
01216                 OperandTraits<InsertElementInst>::op_begin(this),
01217                 3, InsertBef) {
01218   assert(isValidOperands(Vec, Elt, Index) &&
01219          "Invalid insertelement instruction operands!");
01220   Op<0>() = Vec;
01221   Op<1>() = Elt;
01222   Op<2>() = Index;
01223   setName(Name);
01224 }
01225 
01226 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, unsigned IndexV,
01227                                      const std::string &Name,
01228                                      Instruction *InsertBef)
01229   : Instruction(Vec->getType(), InsertElement,
01230                 OperandTraits<InsertElementInst>::op_begin(this),
01231                 3, InsertBef) {
01232   Constant *Index = ConstantInt::get(Type::Int32Ty, IndexV);
01233   assert(isValidOperands(Vec, Elt, Index) &&
01234          "Invalid insertelement instruction operands!");
01235   Op<0>() = Vec;
01236   Op<1>() = Elt;
01237   Op<2>() = Index;
01238   setName(Name);
01239 }
01240 
01241 
01242 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
01243                                      const std::string &Name,
01244                                      BasicBlock *InsertAE)
01245   : Instruction(Vec->getType(), InsertElement,
01246                 OperandTraits<InsertElementInst>::op_begin(this),
01247                 3, InsertAE) {
01248   assert(isValidOperands(Vec, Elt, Index) &&
01249          "Invalid insertelement instruction operands!");
01250 
01251   Op<0>() = Vec;
01252   Op<1>() = Elt;
01253   Op<2>() = Index;
01254   setName(Name);
01255 }
01256 
01257 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, unsigned IndexV,
01258                                      const std::string &Name,
01259                                      BasicBlock *InsertAE)
01260 : Instruction(Vec->getType(), InsertElement,
01261               OperandTraits<InsertElementInst>::op_begin(this),
01262               3, InsertAE) {
01263   Constant *Index = ConstantInt::get(Type::Int32Ty, IndexV);
01264   assert(isValidOperands(Vec, Elt, Index) &&
01265          "Invalid insertelement instruction operands!");
01266   
01267   Op<0>() = Vec;
01268   Op<1>() = Elt;
01269   Op<2>() = Index;
01270   setName(Name);
01271 }
01272 
01273 bool InsertElementInst::isValidOperands(const Value *Vec, const Value *Elt, 
01274                                         const Value *Index) {
01275   if (!isa<VectorType>(Vec->getType()))
01276     return false;   // First operand of insertelement must be vector type.
01277   
01278   if (Elt->getType() != cast<VectorType>(Vec->getType())->getElementType())
01279     return false;// Second operand of insertelement must be vector element type.
01280     
01281   if (Index->getType() != Type::Int32Ty)
01282     return false;  // Third operand of insertelement must be uint.
01283   return true;
01284 }
01285 
01286 
01287 //===----------------------------------------------------------------------===//
01288 //                      ShuffleVectorInst Implementation
01289 //===----------------------------------------------------------------------===//
01290 
01291 ShuffleVectorInst::ShuffleVectorInst(const ShuffleVectorInst &SV) 
01292   : Instruction(SV.getType(), ShuffleVector,
01293                 OperandTraits<ShuffleVectorInst>::op_begin(this),
01294                 OperandTraits<ShuffleVectorInst>::operands(this)) {
01295   Op<0>() = SV.Op<0>();
01296   Op<1>() = SV.Op<1>();
01297   Op<2>() = SV.Op<2>();
01298 }
01299 
01300 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
01301                                      const std::string &Name,
01302                                      Instruction *InsertBefore)
01303 : Instruction(VectorType::get(cast<VectorType>(V1->getType())->getElementType(),
01304                 cast<VectorType>(Mask->getType())->getNumElements()),
01305               ShuffleVector,
01306               OperandTraits<ShuffleVectorInst>::op_begin(this),
01307               OperandTraits<ShuffleVectorInst>::operands(this),
01308               InsertBefore) {
01309   assert(isValidOperands(V1, V2, Mask) &&
01310          "Invalid shuffle vector instruction operands!");
01311   Op<0>() = V1;
01312   Op<1>() = V2;
01313   Op<2>() = Mask;
01314   setName(Name);
01315 }
01316 
01317 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
01318                                      const std::string &Name,
01319                                      BasicBlock *InsertAtEnd)
01320   : Instruction(V1->getType(), ShuffleVector,
01321                 OperandTraits<ShuffleVectorInst>::op_begin(this),
01322                 OperandTraits<ShuffleVectorInst>::operands(this),
01323                 InsertAtEnd) {
01324   assert(isValidOperands(V1, V2, Mask) &&
01325          "Invalid shuffle vector instruction operands!");
01326 
01327   Op<0>() = V1;
01328   Op<1>() = V2;
01329   Op<2>() = Mask;
01330   setName(Name);
01331 }
01332 
01333 bool ShuffleVectorInst::isValidOperands(const Value *V1, const Value *V2,
01334                                         const Value *Mask) {
01335   if (!isa<VectorType>(V1->getType()) || V1->getType() != V2->getType())
01336     return false;
01337   
01338   const VectorType *MaskTy = dyn_cast<VectorType>(Mask->getType());
01339   if (!isa<Constant>(Mask) || MaskTy == 0 ||
01340       MaskTy->getElementType() != Type::Int32Ty)
01341     return false;
01342   return true;
01343 }
01344 
01345 /// getMaskValue - Return the index from the shuffle mask for the specified
01346 /// output result.  This is either -1 if the element is undef or a number less
01347 /// than 2*numelements.
01348 int ShuffleVectorInst::getMaskValue(unsigned i) const {
01349   const Constant *Mask = cast<Constant>(getOperand(2));
01350   if (isa<UndefValue>(Mask)) return -1;
01351   if (isa<ConstantAggregateZero>(Mask)) return 0;
01352   const ConstantVector *MaskCV = cast<ConstantVector>(Mask);
01353   assert(i < MaskCV->getNumOperands() && "Index out of range");
01354 
01355   if (isa<UndefValue>(MaskCV->getOperand(i)))
01356     return -1;
01357   return cast<ConstantInt>(MaskCV->getOperand(i))->getZExtValue();
01358 }
01359 
01360 //===----------------------------------------------------------------------===//
01361 //                             InsertValueInst Class
01362 //===----------------------------------------------------------------------===//
01363 
01364 void InsertValueInst::init(Value *Agg, Value *Val, const unsigned *Idx, 
01365                            unsigned NumIdx, const std::string &Name) {
01366   assert(NumOperands == 2 && "NumOperands not initialized?");
01367   Op<0>() = Agg;
01368   Op<1>() = Val;
01369 
01370   Indices.insert(Indices.end(), Idx, Idx + NumIdx);
01371   setName(Name);
01372 }
01373 
01374 void InsertValueInst::init(Value *Agg, Value *Val, unsigned Idx, 
01375                            const std::string &Name) {
01376   assert(NumOperands == 2 && "NumOperands not initialized?");
01377   Op<0>() = Agg;
01378   Op<1>() = Val;
01379 
01380   Indices.push_back(Idx);
01381   setName(Name);
01382 }
01383 
01384 InsertValueInst::InsertValueInst(const InsertValueInst &IVI)
01385   : Instruction(IVI.getType(), InsertValue,
01386                 OperandTraits<InsertValueInst>::op_begin(this), 2),
01387     Indices(IVI.Indices) {
01388   Op<0>() = IVI.getOperand(0);
01389   Op<1>() = IVI.getOperand(1);
01390 }
01391 
01392 InsertValueInst::InsertValueInst(Value *Agg,
01393                                  Value *Val,
01394                                  unsigned Idx, 
01395                                  const std::string &Name,
01396                                  Instruction *InsertBefore)
01397   : Instruction(Agg->getType(), InsertValue,
01398                 OperandTraits<InsertValueInst>::op_begin(this),
01399                 2, InsertBefore) {
01400   init(Agg, Val, Idx, Name);
01401 }
01402 
01403 InsertValueInst::InsertValueInst(Value *Agg,
01404                                  Value *Val,
01405                                  unsigned Idx, 
01406                                  const std::string &Name,
01407                                  BasicBlock *InsertAtEnd)
01408   : Instruction(Agg->getType(), InsertValue,
01409                 OperandTraits<InsertValueInst>::op_begin(this),
01410                 2, InsertAtEnd) {
01411   init(Agg, Val, Idx, Name);
01412 }
01413 
01414 //===----------------------------------------------------------------------===//
01415 //                             ExtractValueInst Class
01416 //===----------------------------------------------------------------------===//
01417 
01418 void ExtractValueInst::init(const unsigned *Idx, unsigned NumIdx,
01419                             const std::string &Name) {
01420   assert(NumOperands == 1 && "NumOperands not initialized?");
01421 
01422   Indices.insert(Indices.end(), Idx, Idx + NumIdx);
01423   setName(Name);
01424 }
01425 
01426 void ExtractValueInst::init(unsigned Idx, const std::string &Name) {
01427   assert(NumOperands == 1 && "NumOperands not initialized?");
01428 
01429   Indices.push_back(Idx);
01430   setName(Name);
01431 }
01432 
01433 ExtractValueInst::ExtractValueInst(const ExtractValueInst &EVI)
01434   : UnaryInstruction(EVI.getType(), ExtractValue, EVI.getOperand(0)),
01435     Indices(EVI.Indices) {
01436 }
01437 
01438 // getIndexedType - Returns the type of the element that would be extracted
01439 // with an extractvalue instruction with the specified parameters.
01440 //
01441 // A null type is returned if the indices are invalid for the specified
01442 // pointer type.
01443 //
01444 const Type* ExtractValueInst::getIndexedType(const Type *Agg,
01445                                              const unsigned *Idxs,
01446                                              unsigned NumIdx) {
01447   unsigned CurIdx = 0;
01448   for (; CurIdx != NumIdx; ++CurIdx) {
01449     const CompositeType *CT = dyn_cast<CompositeType>(Agg);
01450     if (!CT || isa<PointerType>(CT) || isa<VectorType>(CT)) return 0;
01451     unsigned Index = Idxs[CurIdx];
01452     if (!CT->indexValid(Index)) return 0;
01453     Agg = CT->getTypeAtIndex(Index);
01454 
01455     // If the new type forwards to another type, then it is in the middle
01456     // of being refined to another type (and hence, may have dropped all
01457     // references to what it was using before).  So, use the new forwarded
01458     // type.
01459     if (const Type *Ty = Agg->getForwardedType())
01460       Agg = Ty;
01461   }
01462   return CurIdx == NumIdx ? Agg : 0;
01463 }
01464 
01465 const Type* ExtractValueInst::getIndexedType(const Type *Agg,
01466                                              unsigned Idx) {
01467   return getIndexedType(Agg, &Idx, 1);
01468 }
01469 
01470 //===----------------------------------------------------------------------===//
01471 //                             BinaryOperator Class
01472 //===----------------------------------------------------------------------===//
01473 
01474 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
01475                                const Type *Ty, const std::string &Name,
01476                                Instruction *InsertBefore)
01477   : Instruction(Ty, iType,
01478                 OperandTraits<BinaryOperator>::op_begin(this),
01479                 OperandTraits<BinaryOperator>::operands(this),
01480                 InsertBefore) {
01481   Op<0>() = S1;
01482   Op<1>() = S2;
01483   init(iType);
01484   setName(Name);
01485 }
01486 
01487 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2, 
01488                                const Type *Ty, const std::string &Name,
01489                                BasicBlock *InsertAtEnd)
01490   : Instruction(Ty, iType,
01491                 OperandTraits<BinaryOperator>::op_begin(this),
01492                 OperandTraits<BinaryOperator>::operands(this),
01493                 InsertAtEnd) {
01494   Op<0>() = S1;
01495   Op<1>() = S2;
01496   init(iType);
01497   setName(Name);
01498 }
01499 
01500 
01501 void BinaryOperator::init(BinaryOps iType) {
01502   Value *LHS = getOperand(0), *RHS = getOperand(1);
01503   LHS = LHS; RHS = RHS; // Silence warnings.
01504   assert(LHS->getType() == RHS->getType() &&
01505          "Binary operator operand types must match!");
01506 #ifndef NDEBUG
01507   switch (iType) {
01508   case Add: case Sub:
01509   case Mul: 
01510     assert(getType() == LHS->getType() &&
01511            "Arithmetic operation should return same type as operands!");
01512     assert((getType()->isInteger() || getType()->isFloatingPoint() ||
01513             isa<VectorType>(getType())) &&
01514           "Tried to create an arithmetic operation on a non-arithmetic type!");
01515     break;
01516   case UDiv: 
01517   case SDiv: 
01518     assert(getType() == LHS->getType() &&
01519            "Arithmetic operation should return same type as operands!");
01520     assert((getType()->isInteger() || (isa<VectorType>(getType()) && 
01521             cast<VectorType>(getType())->getElementType()->isInteger())) &&
01522            "Incorrect operand type (not integer) for S/UDIV");
01523     break;
01524   case FDiv:
01525     assert(getType() == LHS->getType() &&
01526            "Arithmetic operation should return same type as operands!");
01527     assert((getType()->isFloatingPoint() || (isa<VectorType>(getType()) &&
01528             cast<VectorType>(getType())->getElementType()->isFloatingPoint())) 
01529             && "Incorrect operand type (not floating point) for FDIV");
01530     break;
01531   case URem: 
01532   case SRem: 
01533     assert(getType() == LHS->getType() &&
01534            "Arithmetic operation should return same type as operands!");
01535     assert((getType()->isInteger() || (isa<VectorType>(getType()) && 
01536             cast<VectorType>(getType())->getElementType()->isInteger())) &&
01537            "Incorrect operand type (not integer) for S/UREM");
01538     break;
01539   case FRem:
01540     assert(getType() == LHS->getType() &&
01541            "Arithmetic operation should return same type as operands!");
01542     assert((getType()->isFloatingPoint() || (isa<VectorType>(getType()) &&
01543             cast<VectorType>(getType())->getElementType()->isFloatingPoint())) 
01544             && "Incorrect operand type (not floating point) for FREM");
01545     break;
01546   case Shl:
01547   case LShr:
01548   case AShr:
01549     assert(getType() == LHS->getType() &&
01550            "Shift operation should return same type as operands!");
01551     assert((getType()->isInteger() ||
01552             (isa<VectorType>(getType()) && 
01553              cast<VectorType>(getType())->getElementType()->isInteger())) &&
01554            "Tried to create a shift operation on a non-integral type!");
01555     break;
01556   case And: case Or:
01557   case Xor:
01558     assert(getType() == LHS->getType() &&
01559            "Logical operation should return same type as operands!");
01560     assert((getType()->isInteger() ||
01561             (isa<VectorType>(getType()) && 
01562              cast<VectorType>(getType())->getElementType()->isInteger())) &&
01563            "Tried to create a logical operation on a non-integral type!");
01564     break;
01565   default:
01566     break;
01567   }
01568 #endif
01569 }
01570 
01571 BinaryOperator *BinaryOperator::Create(BinaryOps Op, Value *S1, Value *S2,
01572                                        const std::string &Name,
01573                                        Instruction *InsertBefore) {
01574   assert(S1->getType() == S2->getType() &&
01575          "Cannot create binary operator with two operands of differing type!");
01576   return new BinaryOperator(Op, S1, S2, S1->getType(), Name, InsertBefore);
01577 }
01578 
01579 BinaryOperator *BinaryOperator::Create(BinaryOps Op, Value *S1, Value *S2,
01580                                        const std::string &Name,
01581                                        BasicBlock *InsertAtEnd) {
01582   BinaryOperator *Res = Create(Op, S1, S2, Name);
01583   InsertAtEnd->getInstList().push_back(Res);
01584   return Res;
01585 }
01586 
01587 BinaryOperator *BinaryOperator::CreateNeg(Value *Op, const std::string &Name,
01588                                           Instruction *InsertBefore) {
01589   Value *zero = ConstantExpr::getZeroValueForNegationExpr(Op->getType());
01590   return new BinaryOperator(Instruction::Sub,
01591                             zero, Op,
01592                             Op->getType(), Name, InsertBefore);
01593 }
01594 
01595 BinaryOperator *BinaryOperator::CreateNeg(Value *Op, const std::string &Name,
01596                                           BasicBlock *InsertAtEnd) {
01597   Value *zero = ConstantExpr::getZeroValueForNegationExpr(Op->getType());
01598   return new BinaryOperator(Instruction::Sub,
01599                             zero, Op,
01600                             Op->getType(), Name, InsertAtEnd);
01601 }
01602 
01603 BinaryOperator *BinaryOperator::CreateNot(Value *Op, const std::string &Name,
01604                                           Instruction *InsertBefore) {
01605   Constant *C;
01606   if (const VectorType *PTy = dyn_cast<VectorType>(Op->getType())) {
01607     C = ConstantInt::getAllOnesValue(PTy->getElementType());
01608     C = ConstantVector::get(std::vector<Constant*>(PTy->getNumElements(), C));
01609   } else {
01610     C = ConstantInt::getAllOnesValue(Op->getType());
01611   }
01612   
01613   return new BinaryOperator(Instruction::Xor, Op, C,
01614                             Op->getType(), Name, InsertBefore);
01615 }
01616 
01617 BinaryOperator *BinaryOperator::CreateNot(Value *Op, const std::string &Name,
01618                                           BasicBlock *InsertAtEnd) {
01619   Constant *AllOnes;
01620   if (const VectorType *PTy = dyn_cast<VectorType>(Op->getType())) {
01621     // Create a vector of all ones values.
01622     Constant *Elt = ConstantInt::getAllOnesValue(PTy->getElementType());
01623     AllOnes = 
01624       ConstantVector::get(std::vector<Constant*>(PTy->getNumElements(), Elt));
01625   } else {
01626     AllOnes = ConstantInt::getAllOnesValue(Op->getType());
01627   }
01628   
01629   return new BinaryOperator(Instruction::Xor, Op, AllOnes,
01630                             Op->getType(), Name, InsertAtEnd);
01631 }
01632 
01633 
01634 // isConstantAllOnes - Helper function for several functions below
01635 static inline bool isConstantAllOnes(const Value *V) {
01636   if (const ConstantInt *CI = dyn_cast<ConstantInt>(V))
01637     return CI->isAllOnesValue();
01638   if (const ConstantVector *CV = dyn_cast<ConstantVector>(V))
01639     return CV->isAllOnesValue();
01640   return false;
01641 }
01642 
01643 bool BinaryOperator::isNeg(const Value *V) {
01644   if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
01645     if (Bop->getOpcode() == Instruction::Sub)
01646       return Bop->getOperand(0) ==
01647              ConstantExpr::getZeroValueForNegationExpr(Bop->getType());
01648   return false;
01649 }
01650 
01651 bool BinaryOperator::isNot(const Value *V) {
01652   if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
01653     return (Bop->getOpcode() == Instruction::Xor &&
01654             (isConstantAllOnes(Bop->getOperand(1)) ||
01655              isConstantAllOnes(Bop->getOperand(0))));
01656   return false;
01657 }
01658 
01659 Value *BinaryOperator::getNegArgument(Value *BinOp) {
01660   assert(isNeg(BinOp) && "getNegArgument from non-'neg' instruction!");
01661   return cast<BinaryOperator>(BinOp)->getOperand(1);
01662 }
01663 
01664 const Value *BinaryOperator::getNegArgument(const Value *BinOp) {
01665   return getNegArgument(const_cast<Value*>(BinOp));
01666 }
01667 
01668 Value *BinaryOperator::getNotArgument(Value *BinOp) {
01669   assert(isNot(BinOp) && "getNotArgument on non-'not' instruction!");
01670   BinaryOperator *BO = cast<BinaryOperator>(BinOp);
01671   Value *Op0 = BO->getOperand(0);
01672   Value *Op1 = BO->getOperand(1);
01673   if (isConstantAllOnes(Op0)) return Op1;
01674 
01675   assert(isConstantAllOnes(Op1));
01676   return Op0;
01677 }
01678 
01679 const Value *BinaryOperator::getNotArgument(const Value *BinOp) {
01680   return getNotArgument(const_cast<Value*>(BinOp));
01681 }
01682 
01683 
01684 // swapOperands - Exchange the two operands to this instruction.  This
01685 // instruction is safe to use on any binary instruction and does not
01686 // modify the semantics of the instruction.  If the instruction is
01687 // order dependent (SetLT f.e.) the opcode is changed.
01688 //
01689 bool BinaryOperator::swapOperands() {
01690   if (!isCommutative())
01691     return true; // Can't commute operands
01692   Op<0>().swap(Op<1>());
01693   return false;
01694 }
01695 
01696 //===----------------------------------------------------------------------===//
01697 //                                CastInst Class
01698 //===----------------------------------------------------------------------===//
01699 
01700 // Just determine if this cast only deals with integral->integral conversion.
01701 bool CastInst::isIntegerCast() const {
01702   switch (getOpcode()) {
01703     default: return false;
01704     case Instruction::ZExt:
01705     case Instruction::SExt:
01706     case Instruction::Trunc:
01707       return true;
01708     case Instruction::BitCast:
01709       return getOperand(0)->getType()->isInteger() && getType()->isInteger();
01710   }
01711 }
01712 
01713 bool CastInst::isLosslessCast() const {
01714   // Only BitCast can be lossless, exit fast if we're not BitCast
01715   if (getOpcode() != Instruction::BitCast)
01716     return false;
01717 
01718   // Identity cast is always lossless
01719   const Type* SrcTy = getOperand(0)->getType();
01720   const Type* DstTy = getType();
01721   if (SrcTy == DstTy)
01722     return true;
01723   
01724   // Pointer to pointer is always lossless.
01725   if (isa<PointerType>(SrcTy))
01726     return isa<PointerType>(DstTy);
01727   return false;  // Other types have no identity values
01728 }
01729 
01730 /// This function determines if the CastInst does not require any bits to be
01731 /// changed in order to effect the cast. Essentially, it identifies cases where
01732 /// no code gen is necessary for the cast, hence the name no-op cast.  For 
01733 /// example, the following are all no-op casts:
01734 /// # bitcast i32* %x to i8*
01735 /// # bitcast <2 x i32> %x to <4 x i16> 
01736 /// # ptrtoint i32* %x to i32     ; on 32-bit plaforms only
01737 /// @brief Determine if a cast is a no-op.
01738 bool CastInst::isNoopCast(const Type *IntPtrTy) const {
01739   switch (getOpcode()) {
01740     default:
01741       assert(!"Invalid CastOp");
01742     case Instruction::Trunc:
01743     case Instruction::ZExt:
01744     case Instruction::SExt: 
01745     case Instruction::FPTrunc:
01746     case Instruction::FPExt:
01747     case Instruction::UIToFP:
01748     case Instruction::SIToFP:
01749     case Instruction::FPToUI:
01750     case Instruction::FPToSI:
01751       return false; // These always modify bits
01752     case Instruction::BitCast:
01753       return true;  // BitCast never modifies bits.
01754     case Instruction::PtrToInt:
01755       return IntPtrTy->getPrimitiveSizeInBits() ==
01756             getType()->getPrimitiveSizeInBits();
01757     case Instruction::IntToPtr:
01758       return IntPtrTy->getPrimitiveSizeInBits() ==
01759              getOperand(0)->getType()->getPrimitiveSizeInBits();
01760   }
01761 }
01762 
01763 /// This function determines if a pair of casts can be eliminated and what 
01764 /// opcode should be used in the elimination. This assumes that there are two 
01765 /// instructions like this:
01766 /// *  %F = firstOpcode SrcTy %x to MidTy
01767 /// *  %S = secondOpcode MidTy %F to DstTy
01768 /// The function returns a resultOpcode so these two casts can be replaced with:
01769 /// *  %Replacement = resultOpcode %SrcTy %x to DstTy
01770 /// If no such cast is permited, the function returns 0.
01771 unsigned CastInst::isEliminableCastPair(
01772   Instruction::CastOps firstOp, Instruction::CastOps secondOp,
01773   const Type *SrcTy, const Type *MidTy, const Type *DstTy, const Type *IntPtrTy)
01774 {
01775   // Define the 144 possibilities for these two cast instructions. The values
01776   // in this matrix determine what to do in a given situation and select the
01777   // case in the switch below.  The rows correspond to firstOp, the columns 
01778   // correspond to secondOp.  In looking at the table below, keep in  mind
01779   // the following cast properties:
01780   //
01781   //          Size Compare       Source               Destination
01782   // Operator  Src ? Size   Type       Sign         Type       Sign
01783   // -------- ------------ -------------------   ---------------------
01784   // TRUNC         >       Integer      Any        Integral     Any
01785   // ZEXT          <       Integral   Unsigned     Integer      Any
01786   // SEXT          <       Integral    Signed      Integer      Any
01787   // FPTOUI       n/a      FloatPt      n/a        Integral   Unsigned
01788   // FPTOSI       n/a      FloatPt      n/a        Integral    Signed 
01789   // UITOFP       n/a      Integral   Unsigned     FloatPt      n/a   
01790   // SITOFP       n/a      Integral    Signed      FloatPt      n/a   
01791   // FPTRUNC       >       FloatPt      n/a        FloatPt      n/a   
01792   // FPEXT         <       FloatPt      n/a        FloatPt      n/a   
01793   // PTRTOINT     n/a      Pointer      n/a        Integral   Unsigned
01794   // INTTOPTR     n/a      Integral   Unsigned     Pointer      n/a
01795   // BITCONVERT    =       FirstClass   n/a       FirstClass    n/a   
01796   //
01797   // NOTE: some transforms are safe, but we consider them to be non-profitable.
01798   // For example, we could merge "fptoui double to uint" + "zext uint to ulong",
01799   // into "fptoui double to ulong", but this loses information about the range
01800   // of the produced value (we no longer know the top-part is all zeros). 
01801   // Further this conversion is often much more expensive for typical hardware,
01802   // and causes issues when building libgcc.  We disallow fptosi+sext for the 
01803   // same reason.
01804   const unsigned numCastOps = 
01805     Instruction::CastOpsEnd - Instruction::CastOpsBegin;
01806   static const uint8_t CastResults[numCastOps][numCastOps] = {
01807     // T        F  F  U  S  F  F  P  I  B   -+
01808     // R  Z  S  P  P  I  I  T  P  2  N  T    |
01809     // U  E  E  2  2  2  2  R  E  I  T  C    +- secondOp
01810     // N  X  X  U  S  F  F  N  X  N  2  V    |
01811     // C  T  T  I  I  P  P  C  T  T  P  T   -+
01812     {  1, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // Trunc      -+
01813     {  8, 1, 9,99,99, 2, 0,99,99,99, 2, 3 }, // ZExt        |
01814     {  8, 0, 1,99,99, 0, 2,99,99,99, 0, 3 }, // SExt        |
01815     {  0, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // FPToUI      |
01816     {  0, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // FPToSI      |
01817     { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4 }, // UIToFP      +- firstOp
01818     { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4 }, // SIToFP      |
01819     { 99,99,99, 0, 0,99,99, 1, 0,99,99, 4 }, // FPTrunc     |
01820     { 99,99,99, 2, 2,99,99,10, 2,99,99, 4 }, // FPExt       |
01821     {  1, 0, 0,99,99, 0, 0,99,99,99, 7, 3 }, // PtrToInt    |
01822     { 99,99,99,99,99,99,99,99,99,13,99,12 }, // IntToPtr    |
01823     {  5, 5, 5, 6, 6, 5, 5, 6, 6,11, 5, 1 }, // BitCast    -+
01824   };
01825 
01826   int ElimCase = CastResults[firstOp-Instruction::CastOpsBegin]
01827                             [secondOp-Instruction::CastOpsBegin];
01828   switch (ElimCase) {
01829     case 0: 
01830       // categorically disallowed
01831       return 0;
01832     case 1: 
01833       // allowed, use first cast's opcode
01834       return firstOp;
01835     case 2: 
01836       // allowed, use second cast's opcode
01837       return secondOp;
01838     case 3: 
01839       // no-op cast in second op implies firstOp as long as the DestTy 
01840       // is integer
01841       if (DstTy->isInteger())
01842         return firstOp;
01843       return 0;
01844     case 4:
01845       // no-op cast in second op implies firstOp as long as the DestTy
01846       // is floating point
01847       if (DstTy->isFloatingPoint())
01848         return firstOp;
01849       return 0;
01850     case 5: 
01851       // no-op cast in first op implies secondOp as long as the SrcTy
01852       // is an integer
01853       if (SrcTy->isInteger())
01854         return secondOp;
01855       return 0;
01856     case 6:
01857       // no-op cast in first op implies secondOp as long as the SrcTy
01858       // is a floating point
01859       if (SrcTy->isFloatingPoint())
01860         return secondOp;
01861       return 0;
01862     case 7: { 
01863       // ptrtoint, inttoptr -> bitcast (ptr -> ptr) if int size is >= ptr size
01864       unsigned PtrSize = IntPtrTy->getPrimitiveSizeInBits();
01865       unsigned MidSize = MidTy->getPrimitiveSizeInBits();
01866       if (MidSize >= PtrSize)
01867         return Instruction::BitCast;
01868       return 0;
01869     }
01870     case 8: {
01871       // ext, trunc -> bitcast,    if the SrcTy and DstTy are same size
01872       // ext, trunc -> ext,        if sizeof(SrcTy) < sizeof(DstTy)
01873       // ext, trunc -> trunc,      if sizeof(SrcTy) > sizeof(DstTy)
01874       unsigned SrcSize = SrcTy->getPrimitiveSizeInBits();
01875       unsigned DstSize = DstTy->getPrimitiveSizeInBits();
01876       if (SrcSize == DstSize)
01877         return Instruction::BitCast;
01878       else if (SrcSize < DstSize)
01879         return firstOp;
01880       return secondOp;
01881     }
01882     case 9: // zext, sext -> zext, because sext can't sign extend after zext
01883       return Instruction::ZExt;
01884     case 10:
01885       // fpext followed by ftrunc is allowed if the bit size returned to is
01886       // the same as the original, in which case its just a bitcast
01887       if (SrcTy == DstTy)
01888         return Instruction::BitCast;
01889       return 0; // If the types are not the same we can't eliminate it.
01890     case 11:
01891       // bitcast followed by ptrtoint is allowed as long as the bitcast
01892       // is a pointer to pointer cast.
01893       if (isa<PointerType>(SrcTy) && isa<PointerType>(MidTy))
01894         return secondOp;
01895       return 0;
01896     case 12:
01897       // inttoptr, bitcast -> intptr  if bitcast is a ptr to ptr cast
01898       if (isa<PointerType>(MidTy) && isa<PointerType>(DstTy))
01899         return firstOp;
01900       return 0;
01901     case 13: {
01902       // inttoptr, ptrtoint -> bitcast if SrcSize<=PtrSize and SrcSize==DstSize
01903       unsigned PtrSize = IntPtrTy->getPrimitiveSizeInBits();
01904       unsigned SrcSize = SrcTy->getPrimitiveSizeInBits();
01905       unsigned DstSize = DstTy->getPrimitiveSizeInBits();
01906       if (SrcSize <= PtrSize && SrcSize == DstSize)
01907         return Instruction::BitCast;
01908       return 0;
01909     }
01910     case 99: 
01911       // cast combination can't happen (error in input). This is for all cases
01912       // where the MidTy is not the same for the two cast instructions.
01913       assert(!"Invalid Cast Combination");
01914       return 0;
01915     default:
01916       assert(!"Error in CastResults table!!!");
01917       return 0;
01918   }
01919   return 0;
01920 }
01921 
01922 CastInst *CastInst::Create(Instruction::CastOps op, Value *S, const Type *Ty, 
01923   const std::string &Name, Instruction *InsertBefore) {
01924   // Construct and return the appropriate CastInst subclass
01925   switch (op) {
01926     case Trunc:    return new TruncInst    (S, Ty, Name, InsertBefore);
01927     case ZExt:     return new ZExtInst     (S, Ty, Name, InsertBefore);
01928     case SExt:     return new SExtInst     (S, Ty, Name, InsertBefore);
01929     case FPTrunc:  return new FPTruncInst  (S, Ty, Name, InsertBefore);
01930     case FPExt:    return new FPExtInst    (S, Ty, Name, InsertBefore);
01931     case UIToFP:   return new UIToFPInst   (S, Ty, Name, InsertBefore);
01932     case SIToFP:   return new SIToFPInst   (S, Ty, Name, InsertBefore);
01933     case FPToUI:   return new FPToUIInst   (S, Ty, Name, InsertBefore);
01934     case FPToSI:   return new FPToSIInst   (S, Ty, Name, InsertBefore);
01935     case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertBefore);
01936     case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertBefore);
01937     case BitCast:  return new BitCastInst  (S, Ty, Name, InsertBefore);
01938     default:
01939       assert(!"Invalid opcode provided");
01940   }
01941   return 0;
01942 }
01943 
01944 CastInst *CastInst::Create(Instruction::CastOps op, Value *S, const Type *Ty,
01945   const std::string &Name, BasicBlock *InsertAtEnd) {
01946   // Construct and return the appropriate CastInst subclass
01947   switch (op) {
01948     case Trunc:    return new TruncInst    (S, Ty, Name, InsertAtEnd);
01949     case ZExt:     return new ZExtInst     (S, Ty, Name, InsertAtEnd);
01950     case SExt:     return new SExtInst     (S, Ty, Name, InsertAtEnd);
01951     case FPTrunc:  return new FPTruncInst  (S, Ty, Name, InsertAtEnd);
01952     case FPExt:    return new FPExtInst    (S, Ty, Name, InsertAtEnd);
01953     case UIToFP:   return new UIToFPInst   (S, Ty, Name, InsertAtEnd);
01954     case SIToFP:   return new SIToFPInst   (S, Ty, Name, InsertAtEnd);
01955     case FPToUI:   return new FPToUIInst   (S, Ty, Name, InsertAtEnd);
01956     case FPToSI:   return new FPToSIInst   (S, Ty, Name, InsertAtEnd);
01957     case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertAtEnd);
01958     case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertAtEnd);
01959     case BitCast:  return new BitCastInst  (S, Ty, Name, InsertAtEnd);
01960     default:
01961       assert(!"Invalid opcode provided");
01962   }
01963   return 0;
01964 }
01965 
01966 CastInst *CastInst::CreateZExtOrBitCast(Value *S, const Type *Ty, 
01967                                         const std::string &Name,
01968                                         Instruction *InsertBefore) {
01969   if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
01970     return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
01971   return Create(Instruction::ZExt, S, Ty, Name, InsertBefore);
01972 }
01973 
01974 CastInst *CastInst::CreateZExtOrBitCast(Value *S, const Type *Ty, 
01975                                         const std::string &Name,
01976                                         BasicBlock *InsertAtEnd) {
01977   if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
01978     return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
01979   return Create(Instruction::ZExt, S, Ty, Name, InsertAtEnd);
01980 }
01981 
01982 CastInst *CastInst::CreateSExtOrBitCast(Value *S, const Type *Ty, 
01983                                         const std::string &Name,
01984                                         Instruction *InsertBefore) {
01985   if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
01986     return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
01987   return Create(Instruction::SExt, S, Ty, Name, InsertBefore);
01988 }
01989 
01990 CastInst *CastInst::CreateSExtOrBitCast(Value *S, const Type *Ty, 
01991                                         const std::string &Name,
01992                                         BasicBlock *InsertAtEnd) {
01993   if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
01994     return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
01995   return Create(Instruction::SExt, S, Ty, Name, InsertAtEnd);
01996 }
01997 
01998 CastInst *CastInst::CreateTruncOrBitCast(Value *S, const Type *Ty,
01999                                          const std::string &Name,
02000                                          Instruction *InsertBefore) {
02001   if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
02002     return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
02003   return Create(Instruction::Trunc, S, Ty, Name, InsertBefore);
02004 }
02005 
02006 CastInst *CastInst::CreateTruncOrBitCast(Value *S, const Type *Ty,
02007                                          const std::string &Name, 
02008                                          BasicBlock *InsertAtEnd) {
02009   if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
02010     return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
02011   return Create(Instruction::Trunc, S, Ty, Name, InsertAtEnd);
02012 }
02013 
02014 CastInst *CastInst::CreatePointerCast(Value *S, const Type *Ty,
02015                                       const std::string &Name,
02016                                       BasicBlock *InsertAtEnd) {
02017   assert(isa<PointerType>(S->getType()) && "Invalid cast");
02018   assert((Ty->isInteger() || isa<PointerType>(Ty)) &&
02019          "Invalid cast");
02020 
02021   if (Ty->isInteger())
02022     return Create(Instruction::PtrToInt, S, Ty, Name, InsertAtEnd);
02023   return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
02024 }
02025 
02026 /// @brief Create a BitCast or a PtrToInt cast instruction
02027 CastInst *CastInst::CreatePointerCast(Value *S, const Type *Ty, 
02028                                       const std::string &Name, 
02029                                       Instruction *InsertBefore) {
02030   assert(isa<PointerType>(S->getType()) && "Invalid cast");
02031   assert((Ty->isInteger() || isa<PointerType>(Ty)) &&
02032          "Invalid cast");
02033 
02034   if (Ty->isInteger())
02035     return Create(Instruction::PtrToInt, S, Ty, Name, InsertBefore);
02036   return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
02037 }
02038 
02039 CastInst *CastInst::CreateIntegerCast(Value *C, const Type *Ty, 
02040                                       bool isSigned, const std::string &Name,
02041                                       Instruction *InsertBefore) {
02042   assert(C->getType()->isInteger() && Ty->isInteger() && "Invalid cast");
02043   unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
02044   unsigned DstBits = Ty->getPrimitiveSizeInBits();
02045   Instruction::CastOps opcode =
02046     (SrcBits == DstBits ? Instruction::BitCast :
02047      (SrcBits > DstBits ? Instruction::Trunc :
02048       (isSigned ? Instruction::SExt : Instruction::ZExt)));
02049   return Create(opcode, C, Ty, Name, InsertBefore);
02050 }
02051 
02052 CastInst *CastInst::CreateIntegerCast(Value *C, const Type *Ty, 
02053                                       bool isSigned, const std::string &Name,
02054                                       BasicBlock *InsertAtEnd) {
02055   assert(C->getType()->isInteger() && Ty->isInteger() && "Invalid cast");
02056   unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
02057   unsigned DstBits = Ty->getPrimitiveSizeInBits();
02058   Instruction::CastOps opcode =
02059     (SrcBits == DstBits ? Instruction::BitCast :
02060      (SrcBits > DstBits ? Instruction::Trunc :
02061       (isSigned ? Instruction::SExt : Instruction::ZExt)));
02062   return Create(opcode, C, Ty, Name, InsertAtEnd);
02063 }
02064 
02065 CastInst *CastInst::CreateFPCast(Value *C, const Type *Ty, 
02066                                  const std::string &Name, 
02067                                  Instruction *InsertBefore) {
02068   assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() && 
02069          "Invalid cast");
02070   unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
02071   unsigned DstBits = Ty->getPrimitiveSizeInBits();
02072   Instruction::CastOps opcode =
02073     (SrcBits == DstBits ? Instruction::BitCast :
02074      (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
02075   return Create(opcode, C, Ty, Name, InsertBefore);
02076 }
02077 
02078 CastInst *CastInst::CreateFPCast(Value *C, const Type *Ty, 
02079                                  const std::string &Name, 
02080                                  BasicBlock *InsertAtEnd) {
02081   assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() && 
02082          "Invalid cast");
02083   unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
02084   unsigned DstBits = Ty->getPrimitiveSizeInBits();
02085   Instruction::CastOps opcode =
02086     (SrcBits == DstBits ? Instruction::BitCast :
02087      (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
02088   return Create(opcode, C, Ty, Name, InsertAtEnd);
02089 }
02090 
02091 // Check whether it is valid to call getCastOpcode for these types.
02092 // This routine must be kept in sync with getCastOpcode.
02093 bool CastInst::isCastable(const Type *SrcTy, const Type *DestTy) {
02094   if (!SrcTy->isFirstClassType() || !DestTy->isFirstClassType())
02095     return false;
02096 
02097   if (SrcTy == DestTy)
02098     return true;
02099 
02100   // Get the bit sizes, we'll need these
02101   unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();   // 0 for ptr/vector
02102   unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr/vector
02103 
02104   // Run through the possibilities ...
02105   if (DestTy->isInteger()) {                   // Casting to integral
02106     if (SrcTy->isInteger()) {                  // Casting from integral
02107         return true;
02108     } else if (SrcTy->isFloatingPoint()) {     // Casting from floating pt
02109       return true;
02110     } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
02111                                                // Casting from vector
02112       return DestBits == PTy->getBitWidth();
02113     } else {                                   // Casting from something else
02114       return isa<PointerType>(SrcTy);
02115     }
02116   } else if (DestTy->isFloatingPoint()) {      // Casting to floating pt
02117     if (SrcTy->isInteger()) {                  // Casting from integral
02118       return true;
02119     } else if (SrcTy->isFloatingPoint()) {     // Casting from floating pt
02120       return true;
02121     } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
02122                                                // Casting from vector
02123       return DestBits == PTy->getBitWidth();
02124     } else {                                   // Casting from something else
02125       return false;
02126     }
02127   } else if (const VectorType *DestPTy = dyn_cast<VectorType>(DestTy)) {
02128                                                 // Casting to vector
02129     if (const VectorType *SrcPTy = dyn_cast<VectorType>(SrcTy)) {
02130                                                 // Casting from vector
02131       return DestPTy->getBitWidth() == SrcPTy->getBitWidth();
02132     } else {                                    // Casting from something else
02133       return DestPTy->getBitWidth() == SrcBits;
02134     }
02135   } else if (isa<PointerType>(DestTy)) {        // Casting to pointer
02136     if (isa<PointerType>(SrcTy)) {              // Casting from pointer
02137       return true;
02138     } else if (SrcTy->isInteger()) {            // Casting from integral
02139       return true;
02140     } else {                                    // Casting from something else
02141       return false;
02142     }
02143   } else {                                      // Casting to something else
02144     return false;
02145   }
02146 }
02147 
02148 // Provide a way to get a "cast" where the cast opcode is inferred from the 
02149 // types and size of the operand. This, basically, is a parallel of the 
02150 // logic in the castIsValid function below.  This axiom should hold:
02151 //   castIsValid( getCastOpcode(Val, Ty), Val, Ty)
02152 // should not assert in castIsValid. In other words, this produces a "correct"
02153 // casting opcode for the arguments passed to it.
02154 // This routine must be kept in sync with isCastable.
02155 Instruction::CastOps
02156 CastInst::getCastOpcode(
02157   const Value *Src, bool SrcIsSigned, const Type *DestTy, bool DestIsSigned) {
02158   // Get the bit sizes, we'll need these
02159   const Type *SrcTy = Src->getType();
02160   unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();   // 0 for ptr/vector
02161   unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr/vector
02162 
02163   assert(SrcTy->isFirstClassType() && DestTy->isFirstClassType() &&
02164          "Only first class types are castable!");
02165 
02166   // Run through the possibilities ...
02167   if (DestTy->isInteger()) {                       // Casting to integral
02168     if (SrcTy->isInteger()) {                      // Casting from integral
02169       if (DestBits < SrcBits)
02170         return Trunc;                               // int -> smaller int
02171       else if (DestBits > SrcBits) {                // its an extension
02172         if (SrcIsSigned)
02173           return SExt;                              // signed -> SEXT
02174         else
02175           return ZExt;                              // unsigned -> ZEXT
02176       } else {
02177         return BitCast;                             // Same size, No-op cast
02178       }
02179     } else if (SrcTy->isFloatingPoint()) {          // Casting from floating pt
02180       if (DestIsSigned) 
02181         return FPToSI;                              // FP -> sint
02182       else
02183         return FPToUI;                              // FP -> uint 
02184     } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
02185       assert(DestBits == PTy->getBitWidth() &&
02186                "Casting vector to integer of different width");
02187       PTy = NULL;
02188       return BitCast;                             // Same size, no-op cast
02189     } else {
02190       assert(isa<PointerType>(SrcTy) &&
02191              "Casting from a value that is not first-class type");
02192       return PtrToInt;                              // ptr -> int
02193     }
02194   } else if (DestTy->isFloatingPoint()) {           // Casting to floating pt
02195     if (SrcTy->isInteger()) {                      // Casting from integral
02196       if (SrcIsSigned)
02197         return SIToFP;                              // sint -> FP
02198       else
02199         return UIToFP;                              // uint -> FP
02200     } else if (SrcTy->isFloatingPoint()) {          // Casting from floating pt
02201       if (DestBits < SrcBits) {
02202         return FPTrunc;                             // FP -> smaller FP
02203       } else if (DestBits > SrcBits) {
02204         return FPExt;                               // FP -> larger FP
02205       } else  {
02206         return BitCast;                             // same size, no-op cast
02207       }
02208     } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
02209       assert(DestBits == PTy->getBitWidth() &&
02210              "Casting vector to floating point of different width");
02211       PTy = NULL;
02212       return BitCast;                             // same size, no-op cast
02213     } else {
02214       assert(0 && "Casting pointer or non-first class to float");
02215     }
02216   } else if (const VectorType *DestPTy = dyn_cast<VectorType>(DestTy)) {
02217     if (const VectorType *SrcPTy = dyn_cast<VectorType>(SrcTy)) {
02218       assert(DestPTy->getBitWidth() == SrcPTy->getBitWidth() &&
02219              "Casting vector to vector of different widths");
02220       SrcPTy = NULL;
02221       return BitCast;                             // vector -> vector
02222     } else if (DestPTy->getBitWidth() == SrcBits) {
02223       return BitCast;                               // float/int -> vector
02224     } else {
02225       assert(!"Illegal cast to vector (wrong type or size)");
02226     }
02227   } else if (isa<PointerType>(DestTy)) {
02228     if (isa<PointerType>(SrcTy)) {
02229       return BitCast;                               // ptr -> ptr
02230     } else if (SrcTy->isInteger()) {
02231       return IntToPtr;                              // int -> ptr
02232     } else {
02233       assert(!"Casting pointer to other than pointer or int");
02234     }
02235   } else {
02236     assert(!"Casting to type that is not first-class");
02237   }
02238 
02239   // If we fall through to here we probably hit an assertion cast above
02240   // and assertions are not turned on. Anything we return is an error, so
02241   // BitCast is as good a choice as any.
02242   return BitCast;
02243 }
02244 
02245 //===----------------------------------------------------------------------===//
02246 //                    CastInst SubClass Constructors
02247 //===----------------------------------------------------------------------===//
02248 
02249 /// Check that the construction parameters for a CastInst are correct. This
02250 /// could be broken out into the separate constructors but it is useful to have
02251 /// it in one place and to eliminate the redundant code for getting the sizes
02252 /// of the types involved.
02253 bool 
02254 CastInst::castIsValid(Instruction::CastOps op, Value *S, const Type *DstTy) {
02255 
02256   // Check for type sanity on the arguments
02257   const Type *SrcTy = S->getType();
02258   if (!SrcTy->isFirstClassType() || !DstTy->isFirstClassType())
02259     return false;
02260 
02261   // Get the size of the types in bits, we'll need this later
02262   unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
02263   unsigned DstBitSize = DstTy->getPrimitiveSizeInBits();
02264 
02265   // Switch on the opcode provided
02266   switch (op) {
02267   default: return false; // This is an input error
02268   case Instruction::Trunc:
02269     return SrcTy->isIntOrIntVector() &&
02270            DstTy->isIntOrIntVector()&& SrcBitSize > DstBitSize;
02271   case Instruction::ZExt:
02272     return SrcTy->isIntOrIntVector() &&
02273            DstTy->isIntOrIntVector()&& SrcBitSize < DstBitSize;
02274   case Instruction::SExt: 
02275     return SrcTy->isIntOrIntVector() &&
02276            DstTy->isIntOrIntVector()&& SrcBitSize < DstBitSize;
02277   case Instruction::FPTrunc:
02278     return SrcTy->isFPOrFPVector() &&
02279            DstTy->isFPOrFPVector() && 
02280            SrcBitSize > DstBitSize;
02281   case Instruction::FPExt:
02282     return SrcTy->isFPOrFPVector() &&
02283            DstTy->isFPOrFPVector() && 
02284            SrcBitSize < DstBitSize;
02285   case Instruction::UIToFP:
02286   case Instruction::SIToFP:
02287     if (const VectorType *SVTy = dyn_cast<VectorType>(SrcTy)) {
02288       if (const VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
02289         return SVTy->getElementType()->isIntOrIntVector() &&
02290                DVTy->getElementType()->isFPOrFPVector() &&
02291                SVTy->getNumElements() == DVTy->getNumElements();
02292       }
02293     }
02294     return SrcTy->isIntOrIntVector() && DstTy->isFPOrFPVector();
02295   case Instruction::FPToUI:
02296   case Instruction::FPToSI:
02297     if (const VectorType *SVTy = dyn_cast<VectorType>(SrcTy)) {
02298       if (const VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
02299         return SVTy->getElementType()->isFPOrFPVector() &&
02300                DVTy->getElementType()->isIntOrIntVector() &&
02301                SVTy->getNumElements() == DVTy->getNumElements();
02302       }
02303     }
02304     return SrcTy->isFPOrFPVector() && DstTy->isIntOrIntVector();
02305   case Instruction::PtrToInt:
02306     return isa<PointerType>(SrcTy) && DstTy->isInteger();
02307   case Instruction::IntToPtr:
02308     return SrcTy->isInteger() && isa<PointerType>(DstTy);
02309   case Instruction::BitCast:
02310     // BitCast implies a no-op cast of type only. No bits change.
02311     // However, you can't cast pointers to anything but pointers.
02312     if (isa<PointerType>(SrcTy) != isa<PointerType>(DstTy))
02313       return false;
02314 
02315     // Now we know we're not dealing with a pointer/non-pointer mismatch. In all
02316     // these cases, the cast is okay if the source and destination bit widths
02317     // are identical.
02318     return SrcBitSize == DstBitSize;
02319   }
02320 }
02321 
02322 TruncInst::TruncInst(
02323   Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
02324 ) : CastInst(Ty, Trunc, S, Name, InsertBefore) {
02325   assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
02326 }
02327 
02328 TruncInst::TruncInst(
02329   Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
02330 ) : CastInst(Ty, Trunc, S, Name, InsertAtEnd) { 
02331   assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
02332 }
02333 
02334 ZExtInst::ZExtInst(
02335   Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
02336 )  : CastInst(Ty, ZExt, S, Name, InsertBefore) { 
02337   assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
02338 }
02339 
02340 ZExtInst::ZExtInst(
02341   Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
02342 )  : CastInst(Ty, ZExt, S, Name, InsertAtEnd) { 
02343   assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
02344 }
02345 SExtInst::SExtInst(
02346   Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
02347 ) : CastInst(Ty, SExt, S, Name, InsertBefore) { 
02348   assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
02349 }
02350 
02351 SExtInst::SExtInst(
02352   Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
02353 )  : CastInst(Ty, SExt, S, Name, InsertAtEnd) { 
02354   assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
02355 }
02356 
02357 FPTruncInst::FPTruncInst(
02358   Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
02359 ) : CastInst(Ty, FPTrunc, S, Name, InsertBefore) { 
02360   assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
02361 }
02362 
02363 FPTruncInst::FPTruncInst(
02364   Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
02365 ) : CastInst(Ty, FPTrunc, S, Name, InsertAtEnd) { 
02366   assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
02367 }
02368 
02369 FPExtInst::FPExtInst(
02370   Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
02371 ) : CastInst(Ty, FPExt, S, Name, InsertBefore) { 
02372   assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
02373 }
02374 
02375 FPExtInst::FPExtInst(
02376   Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
02377 ) : CastInst(Ty, FPExt, S, Name, InsertAtEnd) { 
02378   assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
02379 }
02380 
02381 UIToFPInst::UIToFPInst(
02382   Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
02383 ) : CastInst(Ty, UIToFP, S, Name, InsertBefore) { 
02384   assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
02385 }
02386 
02387 UIToFPInst::UIToFPInst(
02388   Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
02389 ) : CastInst(Ty, UIToFP, S, Name, InsertAtEnd) { 
02390   assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
02391 }
02392 
02393 SIToFPInst::SIToFPInst(
02394   Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
02395 ) : CastInst(Ty, SIToFP, S, Name, InsertBefore) { 
02396   assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
02397 }
02398 
02399 SIToFPInst::SIToFPInst(
02400   Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
02401 ) : CastInst(Ty, SIToFP, S, Name, InsertAtEnd) { 
02402   assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
02403 }
02404 
02405 FPToUIInst::FPToUIInst(
02406   Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
02407 ) : CastInst(Ty, FPToUI, S, Name, InsertBefore) { 
02408   assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
02409 }
02410 
02411 FPToUIInst::FPToUIInst(
02412   Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
02413 ) : CastInst(Ty, FPToUI, S, Name, InsertAtEnd) { 
02414   assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
02415 }
02416 
02417 FPToSIInst::FPToSIInst(
02418   Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
02419 ) : CastInst(Ty, FPToSI, S, Name, InsertBefore) { 
02420   assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
02421 }
02422 
02423 FPToSIInst::FPToSIInst(
02424   Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
02425 ) : CastInst(Ty, FPToSI, S, Name, InsertAtEnd) { 
02426   assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
02427 }
02428 
02429 PtrToIntInst::PtrToIntInst(
02430   Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
02431 ) : CastInst(Ty, PtrToInt, S, Name, InsertBefore) { 
02432   assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
02433 }
02434 
02435 PtrToIntInst::PtrToIntInst(
02436   Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
02437 ) : CastInst(Ty, PtrToInt, S, Name, InsertAtEnd) { 
02438   assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
02439 }
02440 
02441 IntToPtrInst::IntToPtrInst(
02442   Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
02443 ) : CastInst(Ty, IntToPtr, S, Name, InsertBefore) { 
02444   assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
02445 }
02446 
02447 IntToPtrInst::IntToPtrInst(
02448   Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
02449 ) : CastInst(Ty, IntToPtr, S, Name, InsertAtEnd) { 
02450   assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
02451 }
02452 
02453 BitCastInst::BitCastInst(
02454   Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
02455 ) : CastInst(Ty, BitCast, S, Name, InsertBefore) { 
02456   assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
02457 }
02458 
02459 BitCastInst::BitCastInst(
02460   Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
02461 ) : CastInst(Ty, BitCast, S, Name, InsertAtEnd) { 
02462   assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
02463 }
02464 
02465 //===----------------------------------------------------------------------===//
02466 //                               CmpInst Classes
02467 //===----------------------------------------------------------------------===//
02468 
02469 CmpInst::CmpInst(const Type *ty, OtherOps op, unsigned short predicate,
02470                  Value *LHS, Value *RHS, const std::string &Name,
02471                  Instruction *InsertBefore)
02472   : Instruction(ty, op,
02473                 OperandTraits<CmpInst>::op_begin(this),
02474                 OperandTraits<CmpInst>::operands(this),
02475                 InsertBefore) {
02476     Op<0>() = LHS;
02477     Op<1>() = RHS;
02478   SubclassData = predicate;
02479   setName(Name);
02480 }
02481 
02482 CmpInst::CmpInst(const Type *ty, OtherOps op, unsigned short predicate,
02483                  Value *LHS, Value *RHS, const std::string &Name,
02484                  BasicBlock *InsertAtEnd)
02485   : Instruction(ty, op,
02486                 OperandTraits<CmpInst>::op_begin(this),
02487                 OperandTraits<CmpInst>::operands(this),
02488                 InsertAtEnd) {
02489   Op<0>() = LHS;
02490   Op<1>() = RHS;
02491   SubclassData = predicate;
02492   setName(Name);
02493 }
02494 
02495 CmpInst *
02496 CmpInst::Create(OtherOps Op, unsigned short predicate, Value *S1, Value *S2, 
02497                 const std::string &Name, Instruction *InsertBefore) {
02498   if (Op == Instruction::ICmp) {
02499     return new ICmpInst(CmpInst::Predicate(predicate), S1, S2, Name, 
02500                         InsertBefore);
02501   }
02502   if (Op == Instruction::FCmp) {
02503     return new FCmpInst(CmpInst::Predicate(predicate), S1, S2, Name, 
02504                         InsertBefore);
02505   }
02506   if (Op == Instruction::VICmp) {
02507     return new VICmpInst(CmpInst::Predicate(predicate), S1, S2, Name, 
02508                          InsertBefore);
02509   }
02510   return new VFCmpInst(CmpInst::Predicate(predicate), S1, S2, Name, 
02511                        InsertBefore);
02512 }
02513 
02514 CmpInst *
02515 CmpInst::Create(OtherOps Op, unsigned short predicate, Value *S1, Value *S2, 
02516                 const std::string &Name, BasicBlock *InsertAtEnd) {
02517   if (Op == Instruction::ICmp) {
02518     return new ICmpInst(CmpInst::Predicate(predicate), S1, S2, Name, 
02519                         InsertAtEnd);
02520   }
02521   if (Op == Instruction::FCmp) {
02522     return new FCmpInst(CmpInst::Predicate(predicate), S1, S2, Name, 
02523                         InsertAtEnd);
02524   }
02525   if (Op == Instruction::VICmp) {
02526     return new VICmpInst(CmpInst::Predicate(predicate), S1, S2, Name, 
02527                          InsertAtEnd);
02528   }
02529   return new VFCmpInst(CmpInst::Predicate(predicate), S1, S2, Name, 
02530                        InsertAtEnd);
02531 }
02532 
02533 void CmpInst::swapOperands() {
02534   if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
02535     IC->swapOperands();
02536   else
02537     cast<FCmpInst>(this)->swapOperands();
02538 }
02539 
02540 bool CmpInst::isCommutative() {
02541   if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
02542     return IC->isCommutative();
02543   return cast<FCmpInst>(this)->isCommutative();
02544 }
02545 
02546 bool CmpInst::isEquality() {
02547   if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
02548     return IC->isEquality();
02549   return cast<FCmpInst>(this)->isEquality();
02550 }
02551 
02552 
02553 CmpInst::Predicate CmpInst::getInversePredicate(Predicate pred) {
02554   switch (pred) {
02555     default: assert(!"Unknown cmp predicate!");
02556     case ICMP_EQ: return ICMP_NE;
02557     case ICMP_NE: return ICMP_EQ;
02558     case ICMP_UGT: return ICMP_ULE;
02559     case ICMP_ULT: return ICMP_UGE;
02560     case ICMP_UGE: return ICMP_ULT;
02561     case ICMP_ULE: return ICMP_UGT;
02562     case ICMP_SGT: return ICMP_SLE;
02563     case ICMP_SLT: return ICMP_SGE;
02564     case ICMP_SGE: return ICMP_SLT;
02565     case ICMP_SLE: return ICMP_SGT;
02566 
02567     case FCMP_OEQ: return FCMP_UNE;
02568     case FCMP_ONE: return FCMP_UEQ;
02569     case FCMP_OGT: return FCMP_ULE;
02570     case FCMP_OLT: return FCMP_UGE;
02571     case FCMP_OGE: return FCMP_ULT;
02572     case FCMP_OLE: return FCMP_UGT;
02573     case FCMP_UEQ: return FCMP_ONE;
02574     case FCMP_UNE: return FCMP_OEQ;
02575     case FCMP_UGT: return FCMP_OLE;
02576     case FCMP_ULT: return FCMP_OGE;
02577     case FCMP_UGE: return FCMP_OLT;
02578     case FCMP_ULE: return FCMP_OGT;
02579     case FCMP_ORD: return FCMP_UNO;
02580     case FCMP_UNO: return FCMP_ORD;
02581     case FCMP_TRUE: return FCMP_FALSE;
02582     case FCMP_FALSE: return FCMP_TRUE;
02583   }
02584 }
02585 
02586 ICmpInst::Predicate ICmpInst::getSignedPredicate(Predicate pred) {
02587   switch (pred) {
02588     default: assert(! "Unknown icmp predicate!");
02589     case ICMP_EQ: case ICMP_NE: 
02590     case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE: 
02591        return pred;
02592     case ICMP_UGT: return ICMP_SGT;
02593     case ICMP_ULT: return ICMP_SLT;
02594     case ICMP_UGE: return ICMP_SGE;
02595     case ICMP_ULE: return ICMP_SLE;
02596   }
02597 }
02598 
02599 ICmpInst::Predicate ICmpInst::getUnsignedPredicate(Predicate pred) {
02600   switch (pred) {
02601     default: assert(! "Unknown icmp predicate!");
02602     case ICMP_EQ: case ICMP_NE: 
02603     case ICMP_UGT: case ICMP_ULT: case ICMP_UGE: case ICMP_ULE: 
02604        return pred;
02605     case ICMP_SGT: return ICMP_UGT;
02606     case ICMP_SLT: return ICMP_ULT;
02607     case ICMP_SGE: return ICMP_UGE;
02608     case ICMP_SLE: return ICMP_ULE;
02609   }
02610 }
02611 
02612 bool ICmpInst::isSignedPredicate(Predicate pred) {
02613   switch (pred) {
02614     default: assert(! "Unknown icmp predicate!");
02615     case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE: 
02616       return true;
02617     case ICMP_EQ:  case ICMP_NE: case ICMP_UGT: case ICMP_ULT: 
02618     case ICMP_UGE: case ICMP_ULE:
02619       return false;
02620   }
02621 }
02622 
02623 /// Initialize a set of values that all satisfy the condition with C.
02624 ///
02625 ConstantRange 
02626 ICmpInst::makeConstantRange(Predicate pred, const APInt &C) {
02627   APInt Lower(C);
02628   APInt Upper(C);
02629   uint32_t BitWidth = C.getBitWidth();
02630   switch (pred) {
02631   default: assert(0 && "Invalid ICmp opcode to ConstantRange ctor!");
02632   case ICmpInst::ICMP_EQ: Upper++; break;
02633   case ICmpInst::ICMP_NE: Lower++; break;
02634   case ICmpInst::ICMP_ULT: Lower = APInt::getMinValue(BitWidth); break;
02635   case ICmpInst::ICMP_SLT: Lower = APInt::getSignedMinValue(BitWidth); break;
02636   case ICmpInst::ICMP_UGT: 
02637     Lower++; Upper = APInt::getMinValue(BitWidth);        // Min = Next(Max)
02638     break;
02639   case ICmpInst::ICMP_SGT:
02640     Lower++; Upper = APInt::getSignedMinValue(BitWidth);  // Min = Next(Max)
02641     break;
02642   case ICmpInst::ICMP_ULE: 
02643     Lower = APInt::getMinValue(BitWidth); Upper++; 
02644     break;
02645   case ICmpInst::ICMP_SLE: 
02646     Lower = APInt::getSignedMinValue(BitWidth); Upper++; 
02647     break;
02648   case ICmpInst::ICMP_UGE:
02649     Upper = APInt::getMinValue(BitWidth);        // Min = Next(Max)
02650     break;
02651   case ICmpInst::ICMP_SGE:
02652     Upper = APInt::getSignedMinValue(BitWidth);  // Min = Next(Max)
02653     break;
02654   }
02655   return ConstantRange(Lower, Upper);
02656 }
02657 
02658 CmpInst::Predicate CmpInst::getSwappedPredicate(Predicate pred) {
02659   switch (pred) {
02660     default: assert(!"Unknown cmp predicate!");
02661     case ICMP_EQ: case ICMP_NE:
02662       return pred;
02663     case ICMP_SGT: return ICMP_SLT;
02664     case ICMP_SLT: return ICMP_SGT;
02665     case ICMP_SGE: return ICMP_SLE;
02666     case ICMP_SLE: return ICMP_SGE;
02667     case ICMP_UGT: return ICMP_ULT;
02668     case ICMP_ULT: return ICMP_UGT;
02669     case ICMP_UGE: return ICMP_ULE;
02670     case ICMP_ULE: return ICMP_UGE;
02671   
02672     case FCMP_FALSE: case FCMP_TRUE:
02673     case FCMP_OEQ: case FCMP_ONE:
02674     case FCMP_UEQ: case FCMP_UNE:
02675     case FCMP_ORD: case FCMP_UNO:
02676       return pred;
02677     case FCMP_OGT: return FCMP_OLT;
02678     case FCMP_OLT: return FCMP_OGT;
02679     case FCMP_OGE: return FCMP_OLE;
02680     case FCMP_OLE: return FCMP_OGE;
02681     case FCMP_UGT: return FCMP_ULT;
02682     case FCMP_ULT: return FCMP_UGT;
02683     case FCMP_UGE: return FCMP_ULE;
02684     case FCMP_ULE: return FCMP_UGE;
02685   }
02686 }
02687 
02688 bool CmpInst::isUnsigned(unsigned short predicate) {
02689   switch (predicate) {
02690     default: return false;
02691     case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_ULE: case ICmpInst::ICMP_UGT: 
02692     case ICmpInst::ICMP_UGE: return true;
02693   }
02694 }
02695 
02696 bool CmpInst::isSigned(unsigned short predicate){
02697   switch (predicate) {
02698     default: return false;
02699     case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_SLE: case ICmpInst::ICMP_SGT: 
02700     case ICmpInst::ICMP_SGE: return true;
02701   }
02702 }
02703 
02704 bool CmpInst::isOrdered(unsigned short predicate) {
02705   switch (predicate) {
02706     default: return false;
02707     case FCmpInst::FCMP_OEQ: case FCmpInst::FCMP_ONE: case FCmpInst::FCMP_OGT: 
02708     case FCmpInst::FCMP_OLT: case FCmpInst::FCMP_OGE: case FCmpInst::FCMP_OLE: 
02709     case FCmpInst::FCMP_ORD: return true;
02710   }
02711 }
02712       
02713 bool CmpInst::isUnordered(unsigned short predicate) {
02714   switch (predicate) {
02715     default: return false;
02716     case FCmpInst::FCMP_UEQ: case FCmpInst::FCMP_UNE: case FCmpInst::FCMP_UGT: 
02717     case FCmpInst::FCMP_ULT: case FCmpInst::FCMP_UGE: case FCmpInst::FCMP_ULE: 
02718     case FCmpInst::FCMP_UNO: return true;
02719   }
02720 }
02721 
02722 //===----------------------------------------------------------------------===//
02723 //                        SwitchInst Implementation
02724 //===----------------------------------------------------------------------===//
02725 
02726 void SwitchInst::init(Value *Value, BasicBlock *Default, unsigned NumCases) {
02727   assert(Value && Default);
02728   ReservedSpace = 2+NumCases*2;
02729   NumOperands = 2;
02730   OperandList = allocHungoffUses(ReservedSpace);
02731 
02732   OperandList[0] = Value;
02733   OperandList[1] = Default;
02734 }
02735 
02736 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
02737 /// switch on and a default destination.  The number of additional cases can
02738 /// be specified here to make memory allocation more efficient.  This
02739 /// constructor can also autoinsert before another instruction.
02740 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
02741                        Instruction *InsertBefore)
02742   : TerminatorInst(Type::VoidTy, Instruction::Switch, 0, 0, InsertBefore) {
02743   init(Value, Default, NumCases);
02744 }
02745 
02746 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
02747 /// switch on and a default destination.  The number of additional cases can
02748 /// be specified here to make memory allocation more efficient.  This
02749 /// constructor also autoinserts at the end of the specified BasicBlock.
02750 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
02751                        BasicBlock *InsertAtEnd)
02752   : TerminatorInst(Type::VoidTy, Instruction::Switch, 0, 0, InsertAtEnd) {
02753   init(Value, Default, NumCases);
02754 }
02755 
02756 SwitchInst::SwitchInst(const SwitchInst &SI)
02757   : TerminatorInst(Type::VoidTy, Instruction::Switch,
02758                    allocHungoffUses(SI.getNumOperands()), SI.getNumOperands()) {
02759   Use *OL = OperandList, *InOL = SI.OperandList;
02760   for (unsigned i = 0, E = SI.getNumOperands(); i != E; i+=2) {
02761     OL[i] = InOL[i];
02762     OL[i+1] = InOL[i+1];
02763   }
02764 }
02765 
02766 SwitchInst::~SwitchInst() {
02767   dropHungoffUses(OperandList);
02768 }
02769 
02770 
02771 /// addCase - Add an entry to the switch instruction...
02772 ///
02773 void SwitchInst::addCase(ConstantInt *OnVal, BasicBlock *Dest) {
02774   unsigned OpNo = NumOperands;
02775   if (OpNo+2 > ReservedSpace)
02776     resizeOperands(0);  // Get more space!
02777   // Initialize some new operands.
02778   assert(OpNo+1 < ReservedSpace && "Growing didn't work!");
02779   NumOperands = OpNo+2;
02780   OperandList[OpNo] = OnVal;
02781   OperandList[OpNo+1] = Dest;
02782 }
02783 
02784 /// removeCase - This method removes the specified successor from the switch
02785 /// instruction.  Note that this cannot be used to remove the default
02786 /// destination (successor #0).
02787 ///
02788 void SwitchInst::removeCase(unsigned idx) {
02789   assert(idx != 0 && "Cannot remove the default case!");
02790   assert(idx*2 < getNumOperands() && "Successor index out of range!!!");
02791 
02792   unsigned NumOps = getNumOperands();
02793   Use *OL = OperandList;
02794 
02795   // Move everything after this operand down.
02796   //
02797   // FIXME: we could just swap with the end of the list, then erase.  However,
02798   // client might not expect this to happen.  The code as it is thrashes the
02799   // use/def lists, which is kinda lame.
02800   for (unsigned i = (idx+1)*2; i != NumOps; i += 2) {
02801     OL[i-2] = OL[i];
02802     OL[i-2+1] = OL[i+1];
02803   }
02804 
02805   // Nuke the last value.
02806   OL[NumOps-2].set(0);
02807   OL[NumOps-2+1].set(0);
02808   NumOperands = NumOps-2;
02809 }
02810 
02811 /// resizeOperands - resize operands - This adjusts the length of the operands
02812 /// list according to the following behavior:
02813 ///   1. If NumOps == 0, grow the operand list in response to a push_back style
02814 ///      of operation.  This grows the number of ops by 3 times.
02815 ///   2. If NumOps > NumOperands, reserve space for NumOps operands.
02816 ///   3. If NumOps == NumOperands, trim the reserved space.
02817 ///
02818 void SwitchInst::resizeOperands(unsigned NumOps) {
02819   unsigned e = getNumOperands();
02820   if (NumOps == 0) {
02821     NumOps = e*3;
02822   } else if (NumOps*2 > NumOperands) {
02823     // No resize needed.
02824     if (ReservedSpace >= NumOps) return;
02825   } else if (NumOps == NumOperands) {
02826     if (ReservedSpace == NumOps) return;
02827   } else {
02828     return;
02829   }
02830 
02831   ReservedSpace = NumOps;
02832   Use *NewOps = allocHungoffUses(NumOps);
02833   Use *OldOps = OperandList;
02834   for (unsigned i = 0; i != e; ++i) {
02835       NewOps[i] = OldOps[i];
02836   }
02837   OperandList = NewOps;
02838   if (OldOps) Use::zap(OldOps, OldOps + e, true);
02839 }
02840 
02841 
02842 BasicBlock *SwitchInst::getSuccessorV(unsigned idx) const {
02843   return getSuccessor(idx);
02844 }
02845 unsigned SwitchInst::getNumSuccessorsV() const {
02846   return getNumSuccessors();
02847 }
02848 void SwitchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
02849   setSuccessor(idx, B);
02850 }
02851 
02852 // Define these methods here so vtables don't get emitted into every translation
02853 // unit that uses these classes.
02854 
02855 GetElementPtrInst *GetElementPtrInst::clone() const {
02856   return new(getNumOperands()) GetElementPtrInst(*this);
02857 }
02858 
02859 BinaryOperator *BinaryOperator::clone() const {
02860   return Create(getOpcode(), Op<0>(), Op<1>());
02861 }
02862 
02863 FCmpInst* FCmpInst::clone() const {
02864   return new FCmpInst(getPredicate(), Op<0>(), Op<1>());
02865 }
02866 ICmpInst* ICmpInst::clone() const {
02867   return new ICmpInst(getPredicate(), Op<0>(), Op<1>());
02868 }
02869 
02870 VFCmpInst* VFCmpInst::clone() const {
02871   return new VFCmpInst(getPredicate(), Op<0>(), Op<1>());
02872 }
02873 VICmpInst* VICmpInst::clone() const {
02874   return new VICmpInst(getPredicate(), Op<0>(), Op<1>());
02875 }
02876 
02877 ExtractValueInst *ExtractValueInst::clone() const {
02878   return new ExtractValueInst(*this);
02879 }
02880 InsertValueInst *InsertValueInst::clone() const {
02881   return new InsertValueInst(*this);
02882 }
02883 
02884 
02885 MallocInst *MallocInst::clone()   const { return new MallocInst(*this); }
02886 AllocaInst *AllocaInst::clone()   const { return new AllocaInst(*this); }
02887 FreeInst   *FreeInst::clone()     const { return new FreeInst(getOperand(0)); }
02888 LoadInst   *LoadInst::clone()     const { return new LoadInst(*this); }
02889 StoreInst  *StoreInst::clone()    const { return new StoreInst(*this); }
02890 CastInst   *TruncInst::clone()    const { return new TruncInst(*this); }
02891 CastInst   *ZExtInst::clone()     const { return new ZExtInst(*this); }
02892 CastInst   *SExtInst::clone()     const { return new SExtInst(*this); }
02893 CastInst   *FPTruncInst::clone()  const { return new FPTruncInst(*this); }
02894 CastInst   *FPExtInst::clone()    const { return new FPExtInst(*this); }
02895 CastInst   *UIToFPInst::clone()   const { return new UIToFPInst(*this); }
02896 CastInst   *SIToFPInst::clone()   const { return new SIToFPInst(*this); }
02897 CastInst   *FPToUIInst::clone()   const { return new FPToUIInst(*this); }
02898 CastInst   *FPToSIInst::clone()   const { return new FPToSIInst(*this); }
02899 CastInst   *PtrToIntInst::clone() const { return new PtrToIntInst(*this); }
02900 CastInst   *IntToPtrInst::clone() const { return new IntToPtrInst(*this); }
02901 CastInst   *BitCastInst::clone()  const { return new BitCastInst(*this); }
02902 CallInst   *CallInst::clone()     const {
02903   return new(getNumOperands()) CallInst(*this);
02904 }
02905 SelectInst *SelectInst::clone()   const {
02906   return new(getNumOperands()) SelectInst(*this);
02907 }
02908 VAArgInst  *VAArgInst::clone()    const { return new VAArgInst(*this); }
02909 
02910 ExtractElementInst *ExtractElementInst::clone() const {
02911   return new ExtractElementInst(*this);
02912 }
02913 InsertElementInst *InsertElementInst::clone() const {
02914   return InsertElementInst::Create(*this);
02915 }
02916 ShuffleVectorInst *ShuffleVectorInst::clone() const {
02917   return new ShuffleVectorInst(*this);
02918 }
02919 PHINode    *PHINode::clone()    const { return new PHINode(*this); }
02920 ReturnInst *ReturnInst::clone() const {
02921   return new(getNumOperands()) ReturnInst(*this);
02922 }
02923 BranchInst *BranchInst::clone() const {
02924   return new(getNumOperands()) BranchInst(*this);
02925 }
02926 SwitchInst *SwitchInst::clone() const { return new SwitchInst(*this); }
02927 InvokeInst *InvokeInst::clone() const {
02928   return new(getNumOperands()) InvokeInst(*this);
02929 }
02930 UnwindInst *UnwindInst::clone() const { return new UnwindInst(); }
02931 UnreachableInst *UnreachableInst::clone() const { return new UnreachableInst();}