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 was developed by the LLVM research group and is distributed under
00006 // the University of Illinois Open Source 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/BasicBlock.h"
00016 #include "llvm/Constants.h"
00017 #include "llvm/DerivedTypes.h"
00018 #include "llvm/Function.h"
00019 #include "llvm/Instructions.h"
00020 #include "llvm/Support/CallSite.h"
00021 using namespace llvm;
00022 
00023 unsigned CallSite::getCallingConv() const {
00024   if (CallInst *CI = dyn_cast<CallInst>(I))
00025     return CI->getCallingConv();
00026   else
00027     return cast<InvokeInst>(I)->getCallingConv();
00028 }
00029 void CallSite::setCallingConv(unsigned CC) {
00030   if (CallInst *CI = dyn_cast<CallInst>(I))
00031     CI->setCallingConv(CC);
00032   else
00033     cast<InvokeInst>(I)->setCallingConv(CC);
00034 }
00035 
00036 
00037 
00038 
00039 //===----------------------------------------------------------------------===//
00040 //                            TerminatorInst Class
00041 //===----------------------------------------------------------------------===//
00042 
00043 TerminatorInst::TerminatorInst(Instruction::TermOps iType,
00044                                Use *Ops, unsigned NumOps, Instruction *IB)
00045   : Instruction(Type::VoidTy, iType, Ops, NumOps, "", IB) {
00046 }
00047 
00048 TerminatorInst::TerminatorInst(Instruction::TermOps iType,
00049                                Use *Ops, unsigned NumOps, BasicBlock *IAE)
00050   : Instruction(Type::VoidTy, iType, Ops, NumOps, "", IAE) {
00051 }
00052 
00053 // Out of line virtual method, so the vtable, etc has a home.
00054 TerminatorInst::~TerminatorInst() {
00055 }
00056 
00057 // Out of line virtual method, so the vtable, etc has a home.
00058 UnaryInstruction::~UnaryInstruction() {
00059 }
00060 
00061 
00062 //===----------------------------------------------------------------------===//
00063 //                               PHINode Class
00064 //===----------------------------------------------------------------------===//
00065 
00066 PHINode::PHINode(const PHINode &PN)
00067   : Instruction(PN.getType(), Instruction::PHI,
00068                 new Use[PN.getNumOperands()], PN.getNumOperands()),
00069     ReservedSpace(PN.getNumOperands()) {
00070   Use *OL = OperandList;
00071   for (unsigned i = 0, e = PN.getNumOperands(); i != e; i+=2) {
00072     OL[i].init(PN.getOperand(i), this);
00073     OL[i+1].init(PN.getOperand(i+1), this);
00074   }
00075 }
00076 
00077 PHINode::~PHINode() {
00078   delete [] OperandList;
00079 }
00080 
00081 // removeIncomingValue - Remove an incoming value.  This is useful if a
00082 // predecessor basic block is deleted.
00083 Value *PHINode::removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty) {
00084   unsigned NumOps = getNumOperands();
00085   Use *OL = OperandList;
00086   assert(Idx*2 < NumOps && "BB not in PHI node!");
00087   Value *Removed = OL[Idx*2];
00088 
00089   // Move everything after this operand down.
00090   //
00091   // FIXME: we could just swap with the end of the list, then erase.  However,
00092   // client might not expect this to happen.  The code as it is thrashes the
00093   // use/def lists, which is kinda lame.
00094   for (unsigned i = (Idx+1)*2; i != NumOps; i += 2) {
00095     OL[i-2] = OL[i];
00096     OL[i-2+1] = OL[i+1];
00097   }
00098 
00099   // Nuke the last value.
00100   OL[NumOps-2].set(0);
00101   OL[NumOps-2+1].set(0);
00102   NumOperands = NumOps-2;
00103 
00104   // If the PHI node is dead, because it has zero entries, nuke it now.
00105   if (NumOps == 2 && DeletePHIIfEmpty) {
00106     // If anyone is using this PHI, make them use a dummy value instead...
00107     replaceAllUsesWith(UndefValue::get(getType()));
00108     eraseFromParent();
00109   }
00110   return Removed;
00111 }
00112 
00113 /// resizeOperands - resize operands - This adjusts the length of the operands
00114 /// list according to the following behavior:
00115 ///   1. If NumOps == 0, grow the operand list in response to a push_back style
00116 ///      of operation.  This grows the number of ops by 1.5 times.
00117 ///   2. If NumOps > NumOperands, reserve space for NumOps operands.
00118 ///   3. If NumOps == NumOperands, trim the reserved space.
00119 ///
00120 void PHINode::resizeOperands(unsigned NumOps) {
00121   if (NumOps == 0) {
00122     NumOps = (getNumOperands())*3/2;
00123     if (NumOps < 4) NumOps = 4;      // 4 op PHI nodes are VERY common.
00124   } else if (NumOps*2 > NumOperands) {
00125     // No resize needed.
00126     if (ReservedSpace >= NumOps) return;
00127   } else if (NumOps == NumOperands) {
00128     if (ReservedSpace == NumOps) return;
00129   } else {
00130     return;
00131   }
00132 
00133   ReservedSpace = NumOps;
00134   Use *NewOps = new Use[NumOps];
00135   Use *OldOps = OperandList;
00136   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
00137       NewOps[i].init(OldOps[i], this);
00138       OldOps[i].set(0);
00139   }
00140   delete [] OldOps;
00141   OperandList = NewOps;
00142 }
00143 
00144 /// hasConstantValue - If the specified PHI node always merges together the same
00145 /// value, return the value, otherwise return null.
00146 ///
00147 Value *PHINode::hasConstantValue(bool AllowNonDominatingInstruction) const {
00148   // If the PHI node only has one incoming value, eliminate the PHI node...
00149   if (getNumIncomingValues() == 1)
00150     if (getIncomingValue(0) != this)   // not  X = phi X
00151       return getIncomingValue(0);
00152     else
00153       return UndefValue::get(getType());  // Self cycle is dead.
00154       
00155   // Otherwise if all of the incoming values are the same for the PHI, replace
00156   // the PHI node with the incoming value.
00157   //
00158   Value *InVal = 0;
00159   bool HasUndefInput = false;
00160   for (unsigned i = 0, e = getNumIncomingValues(); i != e; ++i)
00161     if (isa<UndefValue>(getIncomingValue(i)))
00162       HasUndefInput = true;
00163     else if (getIncomingValue(i) != this)  // Not the PHI node itself...
00164       if (InVal && getIncomingValue(i) != InVal)
00165         return 0;  // Not the same, bail out.
00166       else
00167         InVal = getIncomingValue(i);
00168   
00169   // The only case that could cause InVal to be null is if we have a PHI node
00170   // that only has entries for itself.  In this case, there is no entry into the
00171   // loop, so kill the PHI.
00172   //
00173   if (InVal == 0) InVal = UndefValue::get(getType());
00174   
00175   // If we have a PHI node like phi(X, undef, X), where X is defined by some
00176   // instruction, we cannot always return X as the result of the PHI node.  Only
00177   // do this if X is not an instruction (thus it must dominate the PHI block),
00178   // or if the client is prepared to deal with this possibility.
00179   if (HasUndefInput && !AllowNonDominatingInstruction)
00180     if (Instruction *IV = dyn_cast<Instruction>(InVal))
00181       // If it's in the entry block, it dominates everything.
00182       if (IV->getParent() != &IV->getParent()->getParent()->front() ||
00183           isa<InvokeInst>(IV))
00184         return 0;   // Cannot guarantee that InVal dominates this PHINode.
00185 
00186   // All of the incoming values are the same, return the value now.
00187   return InVal;
00188 }
00189 
00190 
00191 //===----------------------------------------------------------------------===//
00192 //                        CallInst Implementation
00193 //===----------------------------------------------------------------------===//
00194 
00195 CallInst::~CallInst() {
00196   delete [] OperandList;
00197 }
00198 
00199 void CallInst::init(Value *Func, const std::vector<Value*> &Params) {
00200   NumOperands = Params.size()+1;
00201   Use *OL = OperandList = new Use[Params.size()+1];
00202   OL[0].init(Func, this);
00203 
00204   const FunctionType *FTy =
00205     cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
00206 
00207   assert((Params.size() == FTy->getNumParams() ||
00208           (FTy->isVarArg() && Params.size() > FTy->getNumParams())) &&
00209          "Calling a function with bad signature!");
00210   for (unsigned i = 0, e = Params.size(); i != e; ++i) {
00211     assert((i >= FTy->getNumParams() || 
00212             FTy->getParamType(i) == Params[i]->getType()) &&
00213            "Calling a function with a bad signature!");
00214     OL[i+1].init(Params[i], this);
00215   }
00216 }
00217 
00218 void CallInst::init(Value *Func, Value *Actual1, Value *Actual2) {
00219   NumOperands = 3;
00220   Use *OL = OperandList = new Use[3];
00221   OL[0].init(Func, this);
00222   OL[1].init(Actual1, this);
00223   OL[2].init(Actual2, this);
00224 
00225   const FunctionType *FTy =
00226     cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
00227 
00228   assert((FTy->getNumParams() == 2 ||
00229           (FTy->isVarArg() && FTy->getNumParams() < 2)) &&
00230          "Calling a function with bad signature");
00231   assert((0 >= FTy->getNumParams() || 
00232           FTy->getParamType(0) == Actual1->getType()) &&
00233          "Calling a function with a bad signature!");
00234   assert((1 >= FTy->getNumParams() || 
00235           FTy->getParamType(1) == Actual2->getType()) &&
00236          "Calling a function with a bad signature!");
00237 }
00238 
00239 void CallInst::init(Value *Func, Value *Actual) {
00240   NumOperands = 2;
00241   Use *OL = OperandList = new Use[2];
00242   OL[0].init(Func, this);
00243   OL[1].init(Actual, this);
00244 
00245   const FunctionType *FTy =
00246     cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
00247 
00248   assert((FTy->getNumParams() == 1 ||
00249           (FTy->isVarArg() && FTy->getNumParams() == 0)) &&
00250          "Calling a function with bad signature");
00251   assert((0 == FTy->getNumParams() || 
00252           FTy->getParamType(0) == Actual->getType()) &&
00253          "Calling a function with a bad signature!");
00254 }
00255 
00256 void CallInst::init(Value *Func) {
00257   NumOperands = 1;
00258   Use *OL = OperandList = new Use[1];
00259   OL[0].init(Func, this);
00260 
00261   const FunctionType *MTy =
00262     cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
00263 
00264   assert(MTy->getNumParams() == 0 && "Calling a function with bad signature");
00265 }
00266 
00267 CallInst::CallInst(Value *Func, const std::vector<Value*> &Params,
00268                    const std::string &Name, Instruction *InsertBefore)
00269   : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
00270                                  ->getElementType())->getReturnType(),
00271                 Instruction::Call, 0, 0, Name, InsertBefore) {
00272   init(Func, Params);
00273 }
00274 
00275 CallInst::CallInst(Value *Func, const std::vector<Value*> &Params,
00276                    const std::string &Name, BasicBlock *InsertAtEnd)
00277   : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
00278                                  ->getElementType())->getReturnType(),
00279                 Instruction::Call, 0, 0, Name, InsertAtEnd) {
00280   init(Func, Params);
00281 }
00282 
00283 CallInst::CallInst(Value *Func, Value *Actual1, Value *Actual2,
00284                    const std::string &Name, Instruction  *InsertBefore)
00285   : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
00286                                    ->getElementType())->getReturnType(),
00287                 Instruction::Call, 0, 0, Name, InsertBefore) {
00288   init(Func, Actual1, Actual2);
00289 }
00290 
00291 CallInst::CallInst(Value *Func, Value *Actual1, Value *Actual2,
00292                    const std::string &Name, BasicBlock  *InsertAtEnd)
00293   : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
00294                                    ->getElementType())->getReturnType(),
00295                 Instruction::Call, 0, 0, Name, InsertAtEnd) {
00296   init(Func, Actual1, Actual2);
00297 }
00298 
00299 CallInst::CallInst(Value *Func, Value* Actual, const std::string &Name,
00300                    Instruction  *InsertBefore)
00301   : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
00302                                    ->getElementType())->getReturnType(),
00303                 Instruction::Call, 0, 0, Name, InsertBefore) {
00304   init(Func, Actual);
00305 }
00306 
00307 CallInst::CallInst(Value *Func, Value* Actual, const std::string &Name,
00308                    BasicBlock  *InsertAtEnd)
00309   : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
00310                                    ->getElementType())->getReturnType(),
00311                 Instruction::Call, 0, 0, Name, InsertAtEnd) {
00312   init(Func, Actual);
00313 }
00314 
00315 CallInst::CallInst(Value *Func, const std::string &Name,
00316                    Instruction *InsertBefore)
00317   : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
00318                                    ->getElementType())->getReturnType(),
00319                 Instruction::Call, 0, 0, Name, InsertBefore) {
00320   init(Func);
00321 }
00322 
00323 CallInst::CallInst(Value *Func, const std::string &Name,
00324                    BasicBlock *InsertAtEnd)
00325   : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
00326                                    ->getElementType())->getReturnType(),
00327                 Instruction::Call, 0, 0, Name, InsertAtEnd) {
00328   init(Func);
00329 }
00330 
00331 CallInst::CallInst(const CallInst &CI)
00332   : Instruction(CI.getType(), Instruction::Call, new Use[CI.getNumOperands()],
00333                 CI.getNumOperands()) {
00334   SubclassData = CI.SubclassData;
00335   Use *OL = OperandList;
00336   Use *InOL = CI.OperandList;
00337   for (unsigned i = 0, e = CI.getNumOperands(); i != e; ++i)
00338     OL[i].init(InOL[i], this);
00339 }
00340 
00341 
00342 //===----------------------------------------------------------------------===//
00343 //                        InvokeInst Implementation
00344 //===----------------------------------------------------------------------===//
00345 
00346 InvokeInst::~InvokeInst() {
00347   delete [] OperandList;
00348 }
00349 
00350 void InvokeInst::init(Value *Fn, BasicBlock *IfNormal, BasicBlock *IfException,
00351                       const std::vector<Value*> &Params) {
00352   NumOperands = 3+Params.size();
00353   Use *OL = OperandList = new Use[3+Params.size()];
00354   OL[0].init(Fn, this);
00355   OL[1].init(IfNormal, this);
00356   OL[2].init(IfException, this);
00357   const FunctionType *FTy =
00358     cast<FunctionType>(cast<PointerType>(Fn->getType())->getElementType());
00359 
00360   assert((Params.size() == FTy->getNumParams()) ||
00361          (FTy->isVarArg() && Params.size() > FTy->getNumParams()) &&
00362          "Calling a function with bad signature");
00363 
00364   for (unsigned i = 0, e = Params.size(); i != e; i++) {
00365     assert((i >= FTy->getNumParams() || 
00366             FTy->getParamType(i) == Params[i]->getType()) &&
00367            "Invoking a function with a bad signature!");
00368     
00369     OL[i+3].init(Params[i], this);
00370   }
00371 }
00372 
00373 InvokeInst::InvokeInst(Value *Fn, BasicBlock *IfNormal,
00374                        BasicBlock *IfException,
00375                        const std::vector<Value*> &Params,
00376                        const std::string &Name, Instruction *InsertBefore)
00377   : TerminatorInst(cast<FunctionType>(cast<PointerType>(Fn->getType())
00378                                     ->getElementType())->getReturnType(),
00379                    Instruction::Invoke, 0, 0, Name, InsertBefore) {
00380   init(Fn, IfNormal, IfException, Params);
00381 }
00382 
00383 InvokeInst::InvokeInst(Value *Fn, BasicBlock *IfNormal,
00384                        BasicBlock *IfException,
00385                        const std::vector<Value*> &Params,
00386                        const std::string &Name, BasicBlock *InsertAtEnd)
00387   : TerminatorInst(cast<FunctionType>(cast<PointerType>(Fn->getType())
00388                                     ->getElementType())->getReturnType(),
00389                    Instruction::Invoke, 0, 0, Name, InsertAtEnd) {
00390   init(Fn, IfNormal, IfException, Params);
00391 }
00392 
00393 InvokeInst::InvokeInst(const InvokeInst &II)
00394   : TerminatorInst(II.getType(), Instruction::Invoke,
00395                    new Use[II.getNumOperands()], II.getNumOperands()) {
00396   SubclassData = II.SubclassData;
00397   Use *OL = OperandList, *InOL = II.OperandList;
00398   for (unsigned i = 0, e = II.getNumOperands(); i != e; ++i)
00399     OL[i].init(InOL[i], this);
00400 }
00401 
00402 BasicBlock *InvokeInst::getSuccessorV(unsigned idx) const {
00403   return getSuccessor(idx);
00404 }
00405 unsigned InvokeInst::getNumSuccessorsV() const {
00406   return getNumSuccessors();
00407 }
00408 void InvokeInst::setSuccessorV(unsigned idx, BasicBlock *B) {
00409   return setSuccessor(idx, B);
00410 }
00411 
00412 
00413 //===----------------------------------------------------------------------===//
00414 //                        ReturnInst Implementation
00415 //===----------------------------------------------------------------------===//
00416 
00417 void ReturnInst::init(Value *retVal) {
00418   if (retVal && retVal->getType() != Type::VoidTy) {
00419     assert(!isa<BasicBlock>(retVal) &&
00420            "Cannot return basic block.  Probably using the incorrect ctor");
00421     NumOperands = 1;
00422     RetVal.init(retVal, this);
00423   }
00424 }
00425 
00426 unsigned ReturnInst::getNumSuccessorsV() const {
00427   return getNumSuccessors();
00428 }
00429 
00430 // Out-of-line ReturnInst method, put here so the C++ compiler can choose to
00431 // emit the vtable for the class in this translation unit.
00432 void ReturnInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
00433   assert(0 && "ReturnInst has no successors!");
00434 }
00435 
00436 BasicBlock *ReturnInst::getSuccessorV(unsigned idx) const {
00437   assert(0 && "ReturnInst has no successors!");
00438   abort();
00439   return 0;
00440 }
00441 
00442 
00443 //===----------------------------------------------------------------------===//
00444 //                        UnwindInst Implementation
00445 //===----------------------------------------------------------------------===//
00446 
00447 unsigned UnwindInst::getNumSuccessorsV() const {
00448   return getNumSuccessors();
00449 }
00450 
00451 void UnwindInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
00452   assert(0 && "UnwindInst has no successors!");
00453 }
00454 
00455 BasicBlock *UnwindInst::getSuccessorV(unsigned idx) const {
00456   assert(0 && "UnwindInst has no successors!");
00457   abort();
00458   return 0;
00459 }
00460 
00461 //===----------------------------------------------------------------------===//
00462 //                      UnreachableInst Implementation
00463 //===----------------------------------------------------------------------===//
00464 
00465 unsigned UnreachableInst::getNumSuccessorsV() const {
00466   return getNumSuccessors();
00467 }
00468 
00469 void UnreachableInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
00470   assert(0 && "UnwindInst has no successors!");
00471 }
00472 
00473 BasicBlock *UnreachableInst::getSuccessorV(unsigned idx) const {
00474   assert(0 && "UnwindInst has no successors!");
00475   abort();
00476   return 0;
00477 }
00478 
00479 //===----------------------------------------------------------------------===//
00480 //                        BranchInst Implementation
00481 //===----------------------------------------------------------------------===//
00482 
00483 void BranchInst::AssertOK() {
00484   if (isConditional())
00485     assert(getCondition()->getType() == Type::BoolTy &&
00486            "May only branch on boolean predicates!");
00487 }
00488 
00489 BranchInst::BranchInst(const BranchInst &BI) :
00490   TerminatorInst(Instruction::Br, Ops, BI.getNumOperands()) {
00491   OperandList[0].init(BI.getOperand(0), this);
00492   if (BI.getNumOperands() != 1) {
00493     assert(BI.getNumOperands() == 3 && "BR can have 1 or 3 operands!");
00494     OperandList[1].init(BI.getOperand(1), this);
00495     OperandList[2].init(BI.getOperand(2), this);
00496   }
00497 }
00498 
00499 BasicBlock *BranchInst::getSuccessorV(unsigned idx) const {
00500   return getSuccessor(idx);
00501 }
00502 unsigned BranchInst::getNumSuccessorsV() const {
00503   return getNumSuccessors();
00504 }
00505 void BranchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
00506   setSuccessor(idx, B);
00507 }
00508 
00509 
00510 //===----------------------------------------------------------------------===//
00511 //                        AllocationInst Implementation
00512 //===----------------------------------------------------------------------===//
00513 
00514 static Value *getAISize(Value *Amt) {
00515   if (!Amt)
00516     Amt = ConstantUInt::get(Type::UIntTy, 1);
00517   else {
00518     assert(!isa<BasicBlock>(Amt) &&
00519            "Passed basic block into allocation size parameter!  Ue other ctor");
00520     assert(Amt->getType() == Type::UIntTy &&
00521            "Malloc/Allocation array size != UIntTy!");
00522   }
00523   return Amt;
00524 }
00525 
00526 AllocationInst::AllocationInst(const Type *Ty, Value *ArraySize, unsigned iTy,
00527                                unsigned Align, const std::string &Name,
00528                                Instruction *InsertBefore)
00529   : UnaryInstruction(PointerType::get(Ty), iTy, getAISize(ArraySize),
00530                      Name, InsertBefore), Alignment(Align) {
00531   assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
00532   assert(Ty != Type::VoidTy && "Cannot allocate void!");
00533 }
00534 
00535 AllocationInst::AllocationInst(const Type *Ty, Value *ArraySize, unsigned iTy,
00536                                unsigned Align, const std::string &Name,
00537                                BasicBlock *InsertAtEnd)
00538   : UnaryInstruction(PointerType::get(Ty), iTy, getAISize(ArraySize),
00539                      Name, InsertAtEnd), Alignment(Align) {
00540   assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
00541   assert(Ty != Type::VoidTy && "Cannot allocate void!");
00542 }
00543 
00544 // Out of line virtual method, so the vtable, etc has a home.
00545 AllocationInst::~AllocationInst() {
00546 }
00547 
00548 bool AllocationInst::isArrayAllocation() const {
00549   if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(getOperand(0)))
00550     return CUI->getValue() != 1;
00551   return true;
00552 }
00553 
00554 const Type *AllocationInst::getAllocatedType() const {
00555   return getType()->getElementType();
00556 }
00557 
00558 AllocaInst::AllocaInst(const AllocaInst &AI)
00559   : AllocationInst(AI.getType()->getElementType(), (Value*)AI.getOperand(0),
00560                    Instruction::Alloca, AI.getAlignment()) {
00561 }
00562 
00563 MallocInst::MallocInst(const MallocInst &MI)
00564   : AllocationInst(MI.getType()->getElementType(), (Value*)MI.getOperand(0),
00565                    Instruction::Malloc, MI.getAlignment()) {
00566 }
00567 
00568 //===----------------------------------------------------------------------===//
00569 //                             FreeInst Implementation
00570 //===----------------------------------------------------------------------===//
00571 
00572 void FreeInst::AssertOK() {
00573   assert(isa<PointerType>(getOperand(0)->getType()) &&
00574          "Can not free something of nonpointer type!");
00575 }
00576 
00577 FreeInst::FreeInst(Value *Ptr, Instruction *InsertBefore)
00578   : UnaryInstruction(Type::VoidTy, Free, Ptr, "", InsertBefore) {
00579   AssertOK();
00580 }
00581 
00582 FreeInst::FreeInst(Value *Ptr, BasicBlock *InsertAtEnd)
00583   : UnaryInstruction(Type::VoidTy, Free, Ptr, "", InsertAtEnd) {
00584   AssertOK();
00585 }
00586 
00587 
00588 //===----------------------------------------------------------------------===//
00589 //                           LoadInst Implementation
00590 //===----------------------------------------------------------------------===//
00591 
00592 void LoadInst::AssertOK() {
00593   assert(isa<PointerType>(getOperand(0)->getType()) &&
00594          "Ptr must have pointer type.");
00595 }
00596 
00597 LoadInst::LoadInst(Value *Ptr, const std::string &Name, Instruction *InsertBef)
00598   : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
00599                      Load, Ptr, Name, InsertBef) {
00600   setVolatile(false);
00601   AssertOK();
00602 }
00603 
00604 LoadInst::LoadInst(Value *Ptr, const std::string &Name, BasicBlock *InsertAE)
00605   : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
00606                      Load, Ptr, Name, InsertAE) {
00607   setVolatile(false);
00608   AssertOK();
00609 }
00610 
00611 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile,
00612                    Instruction *InsertBef)
00613   : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
00614                      Load, Ptr, Name, InsertBef) {
00615   setVolatile(isVolatile);
00616   AssertOK();
00617 }
00618 
00619 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile,
00620                    BasicBlock *InsertAE)
00621   : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
00622                      Load, Ptr, Name, InsertAE) {
00623   setVolatile(isVolatile);
00624   AssertOK();
00625 }
00626 
00627 
00628 //===----------------------------------------------------------------------===//
00629 //                           StoreInst Implementation
00630 //===----------------------------------------------------------------------===//
00631 
00632 void StoreInst::AssertOK() {
00633   assert(isa<PointerType>(getOperand(1)->getType()) &&
00634          "Ptr must have pointer type!");
00635   assert(getOperand(0)->getType() ==
00636                  cast<PointerType>(getOperand(1)->getType())->getElementType()
00637          && "Ptr must be a pointer to Val type!");
00638 }
00639 
00640 
00641 StoreInst::StoreInst(Value *val, Value *addr, Instruction *InsertBefore)
00642   : Instruction(Type::VoidTy, Store, Ops, 2, "", InsertBefore) {
00643   Ops[0].init(val, this);
00644   Ops[1].init(addr, this);
00645   setVolatile(false);
00646   AssertOK();
00647 }
00648 
00649 StoreInst::StoreInst(Value *val, Value *addr, BasicBlock *InsertAtEnd)
00650   : Instruction(Type::VoidTy, Store, Ops, 2, "", InsertAtEnd) {
00651   Ops[0].init(val, this);
00652   Ops[1].init(addr, this);
00653   setVolatile(false);
00654   AssertOK();
00655 }
00656 
00657 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
00658                      Instruction *InsertBefore)
00659   : Instruction(Type::VoidTy, Store, Ops, 2, "", InsertBefore) {
00660   Ops[0].init(val, this);
00661   Ops[1].init(addr, this);
00662   setVolatile(isVolatile);
00663   AssertOK();
00664 }
00665 
00666 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
00667                      BasicBlock *InsertAtEnd)
00668   : Instruction(Type::VoidTy, Store, Ops, 2, "", InsertAtEnd) {
00669   Ops[0].init(val, this);
00670   Ops[1].init(addr, this);
00671   setVolatile(isVolatile);
00672   AssertOK();
00673 }
00674 
00675 //===----------------------------------------------------------------------===//
00676 //                       GetElementPtrInst Implementation
00677 //===----------------------------------------------------------------------===//
00678 
00679 // checkType - Simple wrapper function to give a better assertion failure
00680 // message on bad indexes for a gep instruction.
00681 //
00682 static inline const Type *checkType(const Type *Ty) {
00683   assert(Ty && "Invalid GetElementPtrInst indices for type!");
00684   return Ty;
00685 }
00686 
00687 void GetElementPtrInst::init(Value *Ptr, const std::vector<Value*> &Idx) {
00688   NumOperands = 1+Idx.size();
00689   Use *OL = OperandList = new Use[NumOperands];
00690   OL[0].init(Ptr, this);
00691 
00692   for (unsigned i = 0, e = Idx.size(); i != e; ++i)
00693     OL[i+1].init(Idx[i], this);
00694 }
00695 
00696 void GetElementPtrInst::init(Value *Ptr, Value *Idx0, Value *Idx1) {
00697   NumOperands = 3;
00698   Use *OL = OperandList = new Use[3];
00699   OL[0].init(Ptr, this);
00700   OL[1].init(Idx0, this);
00701   OL[2].init(Idx1, this);
00702 }
00703 
00704 void GetElementPtrInst::init(Value *Ptr, Value *Idx) {
00705   NumOperands = 2;
00706   Use *OL = OperandList = new Use[2];
00707   OL[0].init(Ptr, this);
00708   OL[1].init(Idx, this);
00709 }
00710 
00711 GetElementPtrInst::GetElementPtrInst(Value *Ptr, const std::vector<Value*> &Idx,
00712                                      const std::string &Name, Instruction *InBe)
00713   : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),
00714                                                           Idx, true))),
00715                 GetElementPtr, 0, 0, Name, InBe) {
00716   init(Ptr, Idx);
00717 }
00718 
00719 GetElementPtrInst::GetElementPtrInst(Value *Ptr, const std::vector<Value*> &Idx,
00720                                      const std::string &Name, BasicBlock *IAE)
00721   : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),
00722                                                           Idx, true))),
00723                 GetElementPtr, 0, 0, Name, IAE) {
00724   init(Ptr, Idx);
00725 }
00726 
00727 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx,
00728                                      const std::string &Name, Instruction *InBe)
00729   : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),Idx))),
00730                 GetElementPtr, 0, 0, Name, InBe) {
00731   init(Ptr, Idx);
00732 }
00733 
00734 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx,
00735                                      const std::string &Name, BasicBlock *IAE)
00736   : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),Idx))),
00737                 GetElementPtr, 0, 0, Name, IAE) {
00738   init(Ptr, Idx);
00739 }
00740 
00741 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx0, Value *Idx1,
00742                                      const std::string &Name, Instruction *InBe)
00743   : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),
00744                                                           Idx0, Idx1, true))),
00745                 GetElementPtr, 0, 0, Name, InBe) {
00746   init(Ptr, Idx0, Idx1);
00747 }
00748 
00749 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx0, Value *Idx1,
00750                                      const std::string &Name, BasicBlock *IAE)
00751   : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),
00752                                                           Idx0, Idx1, true))),
00753                 GetElementPtr, 0, 0, Name, IAE) {
00754   init(Ptr, Idx0, Idx1);
00755 }
00756 
00757 GetElementPtrInst::~GetElementPtrInst() {
00758   delete[] OperandList;
00759 }
00760 
00761 // getIndexedType - Returns the type of the element that would be loaded with
00762 // a load instruction with the specified parameters.
00763 //
00764 // A null type is returned if the indices are invalid for the specified
00765 // pointer type.
00766 //
00767 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr,
00768                                               const std::vector<Value*> &Idx,
00769                                               bool AllowCompositeLeaf) {
00770   if (!isa<PointerType>(Ptr)) return 0;   // Type isn't a pointer type!
00771 
00772   // Handle the special case of the empty set index set...
00773   if (Idx.empty())
00774     if (AllowCompositeLeaf ||
00775         cast<PointerType>(Ptr)->getElementType()->isFirstClassType())
00776       return cast<PointerType>(Ptr)->getElementType();
00777     else
00778       return 0;
00779 
00780   unsigned CurIdx = 0;
00781   while (const CompositeType *CT = dyn_cast<CompositeType>(Ptr)) {
00782     if (Idx.size() == CurIdx) {
00783       if (AllowCompositeLeaf || CT->isFirstClassType()) return Ptr;
00784       return 0;   // Can't load a whole structure or array!?!?
00785     }
00786 
00787     Value *Index = Idx[CurIdx++];
00788     if (isa<PointerType>(CT) && CurIdx != 1)
00789       return 0;  // Can only index into pointer types at the first index!
00790     if (!CT->indexValid(Index)) return 0;
00791     Ptr = CT->getTypeAtIndex(Index);
00792 
00793     // If the new type forwards to another type, then it is in the middle
00794     // of being refined to another type (and hence, may have dropped all
00795     // references to what it was using before).  So, use the new forwarded
00796     // type.
00797     if (const Type * Ty = Ptr->getForwardedType()) {
00798       Ptr = Ty;
00799     }
00800   }
00801   return CurIdx == Idx.size() ? Ptr : 0;
00802 }
00803 
00804 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr,
00805                                               Value *Idx0, Value *Idx1,
00806                                               bool AllowCompositeLeaf) {
00807   const PointerType *PTy = dyn_cast<PointerType>(Ptr);
00808   if (!PTy) return 0;   // Type isn't a pointer type!
00809 
00810   // Check the pointer index.
00811   if (!PTy->indexValid(Idx0)) return 0;
00812 
00813   const CompositeType *CT = dyn_cast<CompositeType>(PTy->getElementType());
00814   if (!CT || !CT->indexValid(Idx1)) return 0;
00815 
00816   const Type *ElTy = CT->getTypeAtIndex(Idx1);
00817   if (AllowCompositeLeaf || ElTy->isFirstClassType())
00818     return ElTy;
00819   return 0;
00820 }
00821 
00822 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr, Value *Idx) {
00823   const PointerType *PTy = dyn_cast<PointerType>(Ptr);
00824   if (!PTy) return 0;   // Type isn't a pointer type!
00825 
00826   // Check the pointer index.
00827   if (!PTy->indexValid(Idx)) return 0;
00828 
00829   return PTy->getElementType();
00830 }
00831 
00832 //===----------------------------------------------------------------------===//
00833 //                           ExtractElementInst Implementation
00834 //===----------------------------------------------------------------------===//
00835 
00836 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
00837                                        const std::string &Name,
00838                                        Instruction *InsertBef)
00839   : Instruction(cast<PackedType>(Val->getType())->getElementType(),
00840                 ExtractElement, Ops, 2, Name, InsertBef) {
00841   assert(isValidOperands(Val, Index) &&
00842          "Invalid extractelement instruction operands!");
00843   Ops[0].init(Val, this);
00844   Ops[1].init(Index, this);
00845 }
00846 
00847 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
00848                                        const std::string &Name,
00849                                        BasicBlock *InsertAE)
00850   : Instruction(cast<PackedType>(Val->getType())->getElementType(),
00851                 ExtractElement, Ops, 2, Name, InsertAE) {
00852   assert(isValidOperands(Val, Index) &&
00853          "Invalid extractelement instruction operands!");
00854 
00855   Ops[0].init(Val, this);
00856   Ops[1].init(Index, this);
00857 }
00858 
00859 bool ExtractElementInst::isValidOperands(const Value *Val, const Value *Index) {
00860   if (!isa<PackedType>(Val->getType()) || Index->getType() != Type::UIntTy)
00861     return false;
00862   return true;
00863 }
00864 
00865 
00866 //===----------------------------------------------------------------------===//
00867 //                           InsertElementInst Implementation
00868 //===----------------------------------------------------------------------===//
00869 
00870 InsertElementInst::InsertElementInst(const InsertElementInst &IE)
00871     : Instruction(IE.getType(), InsertElement, Ops, 3) {
00872   Ops[0].init(IE.Ops[0], this);
00873   Ops[1].init(IE.Ops[1], this);
00874   Ops[2].init(IE.Ops[2], this);
00875 }
00876 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
00877                                      const std::string &Name,
00878                                      Instruction *InsertBef)
00879   : Instruction(Vec->getType(), InsertElement, Ops, 3, Name, InsertBef) {
00880   assert(isValidOperands(Vec, Elt, Index) &&
00881          "Invalid insertelement instruction operands!");
00882   Ops[0].init(Vec, this);
00883   Ops[1].init(Elt, this);
00884   Ops[2].init(Index, this);
00885 }
00886 
00887 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
00888                                      const std::string &Name,
00889                                      BasicBlock *InsertAE)
00890   : Instruction(Vec->getType(), InsertElement, Ops, 3, Name, InsertAE) {
00891   assert(isValidOperands(Vec, Elt, Index) &&
00892          "Invalid insertelement instruction operands!");
00893 
00894   Ops[0].init(Vec, this);
00895   Ops[1].init(Elt, this);
00896   Ops[2].init(Index, this);
00897 }
00898 
00899 bool InsertElementInst::isValidOperands(const Value *Vec, const Value *Elt, 
00900                                         const Value *Index) {
00901   if (!isa<PackedType>(Vec->getType()))
00902     return false;   // First operand of insertelement must be packed type.
00903   
00904   if (Elt->getType() != cast<PackedType>(Vec->getType())->getElementType())
00905     return false;// Second operand of insertelement must be packed element type.
00906     
00907   if (Index->getType() != Type::UIntTy)
00908     return false;  // Third operand of insertelement must be uint.
00909   return true;
00910 }
00911 
00912 
00913 //===----------------------------------------------------------------------===//
00914 //                      ShuffleVectorInst Implementation
00915 //===----------------------------------------------------------------------===//
00916 
00917 ShuffleVectorInst::ShuffleVectorInst(const ShuffleVectorInst &SV) 
00918     : Instruction(SV.getType(), ShuffleVector, Ops, 3) {
00919   Ops[0].init(SV.Ops[0], this);
00920   Ops[1].init(SV.Ops[1], this);
00921   Ops[2].init(SV.Ops[2], this);
00922 }
00923 
00924 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
00925                                      const std::string &Name,
00926                                      Instruction *InsertBefore)
00927   : Instruction(V1->getType(), ShuffleVector, Ops, 3, Name, InsertBefore) {
00928   assert(isValidOperands(V1, V2, Mask) &&
00929          "Invalid shuffle vector instruction operands!");
00930   Ops[0].init(V1, this);
00931   Ops[1].init(V2, this);
00932   Ops[2].init(Mask, this);
00933 }
00934 
00935 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
00936                                      const std::string &Name, 
00937                                      BasicBlock *InsertAtEnd)
00938   : Instruction(V1->getType(), ShuffleVector, Ops, 3, Name, InsertAtEnd) {
00939   assert(isValidOperands(V1, V2, Mask) &&
00940          "Invalid shuffle vector instruction operands!");
00941 
00942   Ops[0].init(V1, this);
00943   Ops[1].init(V2, this);
00944   Ops[2].init(Mask, this);
00945 }
00946 
00947 bool ShuffleVectorInst::isValidOperands(const Value *V1, const Value *V2, 
00948                                         const Value *Mask) {
00949   if (!isa<PackedType>(V1->getType())) return false;
00950   if (V1->getType() != V2->getType()) return false;
00951   if (!isa<PackedType>(Mask->getType()) ||
00952          cast<PackedType>(Mask->getType())->getElementType() != Type::UIntTy ||
00953          cast<PackedType>(Mask->getType())->getNumElements() !=
00954          cast<PackedType>(V1->getType())->getNumElements())
00955     return false;
00956   return true;
00957 }
00958 
00959 
00960 //===----------------------------------------------------------------------===//
00961 //                             BinaryOperator Class
00962 //===----------------------------------------------------------------------===//
00963 
00964 void BinaryOperator::init(BinaryOps iType)
00965 {
00966   Value *LHS = getOperand(0), *RHS = getOperand(1);
00967   assert(LHS->getType() == RHS->getType() &&
00968          "Binary operator operand types must match!");
00969 #ifndef NDEBUG
00970   switch (iType) {
00971   case Add: case Sub:
00972   case Mul: case Div:
00973   case Rem:
00974     assert(getType() == LHS->getType() &&
00975            "Arithmetic operation should return same type as operands!");
00976     assert((getType()->isInteger() || getType()->isFloatingPoint() ||
00977             isa<PackedType>(getType())) &&
00978           "Tried to create an arithmetic operation on a non-arithmetic type!");
00979     break;
00980   case And: case Or:
00981   case Xor:
00982     assert(getType() == LHS->getType() &&
00983            "Logical operation should return same type as operands!");
00984     assert((getType()->isIntegral() ||
00985             (isa<PackedType>(getType()) && 
00986              cast<PackedType>(getType())->getElementType()->isIntegral())) &&
00987            "Tried to create a logical operation on a non-integral type!");
00988     break;
00989   case SetLT: case SetGT: case SetLE:
00990   case SetGE: case SetEQ: case SetNE:
00991     assert(getType() == Type::BoolTy && "Setcc must return bool!");
00992   default:
00993     break;
00994   }
00995 #endif
00996 }
00997 
00998 BinaryOperator *BinaryOperator::create(BinaryOps Op, Value *S1, Value *S2,
00999                                        const std::string &Name,
01000                                        Instruction *InsertBefore) {
01001   assert(S1->getType() == S2->getType() &&
01002          "Cannot create binary operator with two operands of differing type!");
01003   switch (Op) {
01004   // Binary comparison operators...
01005   case SetLT: case SetGT: case SetLE:
01006   case SetGE: case SetEQ: case SetNE:
01007     return new SetCondInst(Op, S1, S2, Name, InsertBefore);
01008 
01009   default:
01010     return new BinaryOperator(Op, S1, S2, S1->getType(), Name, InsertBefore);
01011   }
01012 }
01013 
01014 BinaryOperator *BinaryOperator::create(BinaryOps Op, Value *S1, Value *S2,
01015                                        const std::string &Name,
01016                                        BasicBlock *InsertAtEnd) {
01017   BinaryOperator *Res = create(Op, S1, S2, Name);
01018   InsertAtEnd->getInstList().push_back(Res);
01019   return Res;
01020 }
01021 
01022 BinaryOperator *BinaryOperator::createNeg(Value *Op, const std::string &Name,
01023                                           Instruction *InsertBefore) {
01024   if (!Op->getType()->isFloatingPoint())
01025     return new BinaryOperator(Instruction::Sub,
01026                               Constant::getNullValue(Op->getType()), Op,
01027                               Op->getType(), Name, InsertBefore);
01028   else
01029     return new BinaryOperator(Instruction::Sub,
01030                               ConstantFP::get(Op->getType(), -0.0), Op,
01031                               Op->getType(), Name, InsertBefore);
01032 }
01033 
01034 BinaryOperator *BinaryOperator::createNeg(Value *Op, const std::string &Name,
01035                                           BasicBlock *InsertAtEnd) {
01036   if (!Op->getType()->isFloatingPoint())
01037     return new BinaryOperator(Instruction::Sub,
01038                               Constant::getNullValue(Op->getType()), Op,
01039                               Op->getType(), Name, InsertAtEnd);
01040   else
01041     return new BinaryOperator(Instruction::Sub,
01042                               ConstantFP::get(Op->getType(), -0.0), Op,
01043                               Op->getType(), Name, InsertAtEnd);
01044 }
01045 
01046 BinaryOperator *BinaryOperator::createNot(Value *Op, const std::string &Name,
01047                                           Instruction *InsertBefore) {
01048   Constant *C;
01049   if (const PackedType *PTy = dyn_cast<PackedType>(Op->getType())) {
01050     C = ConstantIntegral::getAllOnesValue(PTy->getElementType());
01051     C = ConstantPacked::get(std::vector<Constant*>(PTy->getNumElements(), C));
01052   } else {
01053     C = ConstantIntegral::getAllOnesValue(Op->getType());
01054   }
01055   
01056   return new BinaryOperator(Instruction::Xor, Op, C,
01057                             Op->getType(), Name, InsertBefore);
01058 }
01059 
01060 BinaryOperator *BinaryOperator::createNot(Value *Op, const std::string &Name,
01061                                           BasicBlock *InsertAtEnd) {
01062   Constant *AllOnes;
01063   if (const PackedType *PTy = dyn_cast<PackedType>(Op->getType())) {
01064     // Create a vector of all ones values.
01065     Constant *Elt = ConstantIntegral::getAllOnesValue(PTy->getElementType());
01066     AllOnes = 
01067       ConstantPacked::get(std::vector<Constant*>(PTy->getNumElements(), Elt));
01068   } else {
01069     AllOnes = ConstantIntegral::getAllOnesValue(Op->getType());
01070   }
01071   
01072   return new BinaryOperator(Instruction::Xor, Op, AllOnes,
01073                             Op->getType(), Name, InsertAtEnd);
01074 }
01075 
01076 
01077 // isConstantAllOnes - Helper function for several functions below
01078 static inline bool isConstantAllOnes(const Value *V) {
01079   return isa<ConstantIntegral>(V) &&cast<ConstantIntegral>(V)->isAllOnesValue();
01080 }
01081 
01082 bool BinaryOperator::isNeg(const Value *V) {
01083   if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
01084     if (Bop->getOpcode() == Instruction::Sub)
01085       if (!V->getType()->isFloatingPoint())
01086         return Bop->getOperand(0) == Constant::getNullValue(Bop->getType());
01087       else
01088         return Bop->getOperand(0) == ConstantFP::get(Bop->getType(), -0.0);
01089   return false;
01090 }
01091 
01092 bool BinaryOperator::isNot(const Value *V) {
01093   if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
01094     return (Bop->getOpcode() == Instruction::Xor &&
01095             (isConstantAllOnes(Bop->getOperand(1)) ||
01096              isConstantAllOnes(Bop->getOperand(0))));
01097   return false;
01098 }
01099 
01100 Value *BinaryOperator::getNegArgument(Value *BinOp) {
01101   assert(isNeg(BinOp) && "getNegArgument from non-'neg' instruction!");
01102   return cast<BinaryOperator>(BinOp)->getOperand(1);
01103 }
01104 
01105 const Value *BinaryOperator::getNegArgument(const Value *BinOp) {
01106   return getNegArgument(const_cast<Value*>(BinOp));
01107 }
01108 
01109 Value *BinaryOperator::getNotArgument(Value *BinOp) {
01110   assert(isNot(BinOp) && "getNotArgument on non-'not' instruction!");
01111   BinaryOperator *BO = cast<BinaryOperator>(BinOp);
01112   Value *Op0 = BO->getOperand(0);
01113   Value *Op1 = BO->getOperand(1);
01114   if (isConstantAllOnes(Op0)) return Op1;
01115 
01116   assert(isConstantAllOnes(Op1));
01117   return Op0;
01118 }
01119 
01120 const Value *BinaryOperator::getNotArgument(const Value *BinOp) {
01121   return getNotArgument(const_cast<Value*>(BinOp));
01122 }
01123 
01124 
01125 // swapOperands - Exchange the two operands to this instruction.  This
01126 // instruction is safe to use on any binary instruction and does not
01127 // modify the semantics of the instruction.  If the instruction is
01128 // order dependent (SetLT f.e.) the opcode is changed.
01129 //
01130 bool BinaryOperator::swapOperands() {
01131   if (isCommutative())
01132     ;  // If the instruction is commutative, it is safe to swap the operands
01133   else if (SetCondInst *SCI = dyn_cast<SetCondInst>(this))
01134     /// FIXME: SetCC instructions shouldn't all have different opcodes.
01135     setOpcode(SCI->getSwappedCondition());
01136   else
01137     return true;   // Can't commute operands
01138 
01139   std::swap(Ops[0], Ops[1]);
01140   return false;
01141 }
01142 
01143 
01144 //===----------------------------------------------------------------------===//
01145 //                             SetCondInst Class
01146 //===----------------------------------------------------------------------===//
01147 
01148 SetCondInst::SetCondInst(BinaryOps Opcode, Value *S1, Value *S2,
01149                          const std::string &Name, Instruction *InsertBefore)
01150   : BinaryOperator(Opcode, S1, S2, Type::BoolTy, Name, InsertBefore) {
01151 
01152   // Make sure it's a valid type... getInverseCondition will assert out if not.
01153   assert(getInverseCondition(Opcode));
01154 }
01155 
01156 SetCondInst::SetCondInst(BinaryOps Opcode, Value *S1, Value *S2,
01157                          const std::string &Name, BasicBlock *InsertAtEnd)
01158   : BinaryOperator(Opcode, S1, S2, Type::BoolTy, Name, InsertAtEnd) {
01159 
01160   // Make sure it's a valid type... getInverseCondition will assert out if not.
01161   assert(getInverseCondition(Opcode));
01162 }
01163 
01164 // getInverseCondition - Return the inverse of the current condition opcode.
01165 // For example seteq -> setne, setgt -> setle, setlt -> setge, etc...
01166 //
01167 Instruction::BinaryOps SetCondInst::getInverseCondition(BinaryOps Opcode) {
01168   switch (Opcode) {
01169   default:
01170     assert(0 && "Unknown setcc opcode!");
01171   case SetEQ: return SetNE;
01172   case SetNE: return SetEQ;
01173   case SetGT: return SetLE;
01174   case SetLT: return SetGE;
01175   case SetGE: return SetLT;
01176   case SetLE: return SetGT;
01177   }
01178 }
01179 
01180 // getSwappedCondition - Return the condition opcode that would be the result
01181 // of exchanging the two operands of the setcc instruction without changing
01182 // the result produced.  Thus, seteq->seteq, setle->setge, setlt->setgt, etc.
01183 //
01184 Instruction::BinaryOps SetCondInst::getSwappedCondition(BinaryOps Opcode) {
01185   switch (Opcode) {
01186   default: assert(0 && "Unknown setcc instruction!");
01187   case SetEQ: case SetNE: return Opcode;
01188   case SetGT: return SetLT;
01189   case SetLT: return SetGT;
01190   case SetGE: return SetLE;
01191   case SetLE: return SetGE;
01192   }
01193 }
01194 
01195 //===----------------------------------------------------------------------===//
01196 //                        SwitchInst Implementation
01197 //===----------------------------------------------------------------------===//
01198 
01199 void SwitchInst::init(Value *Value, BasicBlock *Default, unsigned NumCases) {
01200   assert(Value && Default);
01201   ReservedSpace = 2+NumCases*2;
01202   NumOperands = 2;
01203   OperandList = new Use[ReservedSpace];
01204 
01205   OperandList[0].init(Value, this);
01206   OperandList[1].init(Default, this);
01207 }
01208 
01209 SwitchInst::SwitchInst(const SwitchInst &SI)
01210   : TerminatorInst(Instruction::Switch, new Use[SI.getNumOperands()],
01211                    SI.getNumOperands()) {
01212   Use *OL = OperandList, *InOL = SI.OperandList;
01213   for (unsigned i = 0, E = SI.getNumOperands(); i != E; i+=2) {
01214     OL[i].init(InOL[i], this);
01215     OL[i+1].init(InOL[i+1], this);
01216   }
01217 }
01218 
01219 SwitchInst::~SwitchInst() {
01220   delete [] OperandList;
01221 }
01222 
01223 
01224 /// addCase - Add an entry to the switch instruction...
01225 ///
01226 void SwitchInst::addCase(ConstantInt *OnVal, BasicBlock *Dest) {
01227   unsigned OpNo = NumOperands;
01228   if (OpNo+2 > ReservedSpace)
01229     resizeOperands(0);  // Get more space!
01230   // Initialize some new operands.
01231   assert(OpNo+1 < ReservedSpace && "Growing didn't work!");
01232   NumOperands = OpNo+2;
01233   OperandList[OpNo].init(OnVal, this);
01234   OperandList[OpNo+1].init(Dest, this);
01235 }
01236 
01237 /// removeCase - This method removes the specified successor from the switch
01238 /// instruction.  Note that this cannot be used to remove the default
01239 /// destination (successor #0).
01240 ///
01241 void SwitchInst::removeCase(unsigned idx) {
01242   assert(idx != 0 && "Cannot remove the default case!");
01243   assert(idx*2 < getNumOperands() && "Successor index out of range!!!");
01244 
01245   unsigned NumOps = getNumOperands();
01246   Use *OL = OperandList;
01247 
01248   // Move everything after this operand down.
01249   //
01250   // FIXME: we could just swap with the end of the list, then erase.  However,
01251   // client might not expect this to happen.  The code as it is thrashes the
01252   // use/def lists, which is kinda lame.
01253   for (unsigned i = (idx+1)*2; i != NumOps; i += 2) {
01254     OL[i-2] = OL[i];
01255     OL[i-2+1] = OL[i+1];
01256   }
01257 
01258   // Nuke the last value.
01259   OL[NumOps-2].set(0);
01260   OL[NumOps-2+1].set(0);
01261   NumOperands = NumOps-2;
01262 }
01263 
01264 /// resizeOperands - resize operands - This adjusts the length of the operands
01265 /// list according to the following behavior:
01266 ///   1. If NumOps == 0, grow the operand list in response to a push_back style
01267 ///      of operation.  This grows the number of ops by 1.5 times.
01268 ///   2. If NumOps > NumOperands, reserve space for NumOps operands.
01269 ///   3. If NumOps == NumOperands, trim the reserved space.
01270 ///
01271 void SwitchInst::resizeOperands(unsigned NumOps) {
01272   if (NumOps == 0) {
01273     NumOps = getNumOperands()/2*6;
01274   } else if (NumOps*2 > NumOperands) {
01275     // No resize needed.
01276     if (ReservedSpace >= NumOps) return;
01277   } else if (NumOps == NumOperands) {
01278     if (ReservedSpace == NumOps) return;
01279   } else {
01280     return;
01281   }
01282 
01283   ReservedSpace = NumOps;
01284   Use *NewOps = new Use[NumOps];
01285   Use *OldOps = OperandList;
01286   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
01287       NewOps[i].init(OldOps[i], this);
01288       OldOps[i].set(0);
01289   }
01290   delete [] OldOps;
01291   OperandList = NewOps;
01292 }
01293 
01294 
01295 BasicBlock *SwitchInst::getSuccessorV(unsigned idx) const {
01296   return getSuccessor(idx);
01297 }
01298 unsigned SwitchInst::getNumSuccessorsV() const {
01299   return getNumSuccessors();
01300 }
01301 void SwitchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
01302   setSuccessor(idx, B);
01303 }
01304 
01305 
01306 // Define these methods here so vtables don't get emitted into every translation
01307 // unit that uses these classes.
01308 
01309 GetElementPtrInst *GetElementPtrInst::clone() const {
01310   return new GetElementPtrInst(*this);
01311 }
01312 
01313 BinaryOperator *BinaryOperator::clone() const {
01314   return create(getOpcode(), Ops[0], Ops[1]);
01315 }
01316 
01317 MallocInst *MallocInst::clone() const { return new MallocInst(*this); }
01318 AllocaInst *AllocaInst::clone() const { return new AllocaInst(*this); }
01319 FreeInst   *FreeInst::clone()   const { return new FreeInst(getOperand(0)); }
01320 LoadInst   *LoadInst::clone()   const { return new LoadInst(*this); }
01321 StoreInst  *StoreInst::clone()  const { return new StoreInst(*this); }
01322 CastInst   *CastInst::clone()   const { return new CastInst(*this); }
01323 CallInst   *CallInst::clone()   const { return new CallInst(*this); }
01324 ShiftInst  *ShiftInst::clone()  const { return new ShiftInst(*this); }
01325 SelectInst *SelectInst::clone() const { return new SelectInst(*this); }
01326 VAArgInst  *VAArgInst::clone()  const { return new VAArgInst(*this); }
01327 ExtractElementInst *ExtractElementInst::clone() const {
01328   return new ExtractElementInst(*this);
01329 }
01330 InsertElementInst *InsertElementInst::clone() const {
01331   return new InsertElementInst(*this);
01332 }
01333 ShuffleVectorInst *ShuffleVectorInst::clone() const {
01334   return new ShuffleVectorInst(*this);
01335 }
01336 PHINode    *PHINode::clone()    const { return new PHINode(*this); }
01337 ReturnInst *ReturnInst::clone() const { return new ReturnInst(*this); }
01338 BranchInst *BranchInst::clone() const { return new BranchInst(*this); }
01339 SwitchInst *SwitchInst::clone() const { return new SwitchInst(*this); }
01340 InvokeInst *InvokeInst::clone() const { return new InvokeInst(*this); }
01341 UnwindInst *UnwindInst::clone() const { return new UnwindInst(); }
01342 UnreachableInst *UnreachableInst::clone() const { return new UnreachableInst();}