1 //===-- Instructions.cpp - Implement the LLVM instructions ----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements all of the non-inline methods for the LLVM instruction
13 //===----------------------------------------------------------------------===//
15 #include "llvm/BasicBlock.h"
16 #include "llvm/Constants.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/Function.h"
19 #include "llvm/Instructions.h"
20 #include "llvm/Support/CallSite.h"
23 unsigned CallSite::getCallingConv() const {
24 if (CallInst *CI = dyn_cast<CallInst>(I))
25 return CI->getCallingConv();
27 return cast<InvokeInst>(I)->getCallingConv();
29 void CallSite::setCallingConv(unsigned CC) {
30 if (CallInst *CI = dyn_cast<CallInst>(I))
31 CI->setCallingConv(CC);
33 cast<InvokeInst>(I)->setCallingConv(CC);
37 //===----------------------------------------------------------------------===//
38 // TerminatorInst Class
39 //===----------------------------------------------------------------------===//
41 TerminatorInst::TerminatorInst(Instruction::TermOps iType,
42 Use *Ops, unsigned NumOps, Instruction *IB)
43 : Instruction(Type::VoidTy, iType, Ops, NumOps, "", IB) {
46 TerminatorInst::TerminatorInst(Instruction::TermOps iType,
47 Use *Ops, unsigned NumOps, BasicBlock *IAE)
48 : Instruction(Type::VoidTy, iType, Ops, NumOps, "", IAE) {
53 //===----------------------------------------------------------------------===//
55 //===----------------------------------------------------------------------===//
57 PHINode::PHINode(const PHINode &PN)
58 : Instruction(PN.getType(), Instruction::PHI,
59 new Use[PN.getNumOperands()], PN.getNumOperands()),
60 ReservedSpace(PN.getNumOperands()) {
61 Use *OL = OperandList;
62 for (unsigned i = 0, e = PN.getNumOperands(); i != e; i+=2) {
63 OL[i].init(PN.getOperand(i), this);
64 OL[i+1].init(PN.getOperand(i+1), this);
69 delete [] OperandList;
72 // removeIncomingValue - Remove an incoming value. This is useful if a
73 // predecessor basic block is deleted.
74 Value *PHINode::removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty) {
75 unsigned NumOps = getNumOperands();
76 Use *OL = OperandList;
77 assert(Idx*2 < NumOps && "BB not in PHI node!");
78 Value *Removed = OL[Idx*2];
80 // Move everything after this operand down.
82 // FIXME: we could just swap with the end of the list, then erase. However,
83 // client might not expect this to happen. The code as it is thrashes the
84 // use/def lists, which is kinda lame.
85 for (unsigned i = (Idx+1)*2; i != NumOps; i += 2) {
90 // Nuke the last value.
92 OL[NumOps-2+1].set(0);
93 NumOperands = NumOps-2;
95 // If the PHI node is dead, because it has zero entries, nuke it now.
96 if (NumOps == 2 && DeletePHIIfEmpty) {
97 // If anyone is using this PHI, make them use a dummy value instead...
98 replaceAllUsesWith(UndefValue::get(getType()));
104 /// resizeOperands - resize operands - This adjusts the length of the operands
105 /// list according to the following behavior:
106 /// 1. If NumOps == 0, grow the operand list in response to a push_back style
107 /// of operation. This grows the number of ops by 1.5 times.
108 /// 2. If NumOps > NumOperands, reserve space for NumOps operands.
109 /// 3. If NumOps == NumOperands, trim the reserved space.
111 void PHINode::resizeOperands(unsigned NumOps) {
113 NumOps = (getNumOperands())*3/2;
114 if (NumOps < 4) NumOps = 4; // 4 op PHI nodes are VERY common.
115 } else if (NumOps*2 > NumOperands) {
117 if (ReservedSpace >= NumOps) return;
118 } else if (NumOps == NumOperands) {
119 if (ReservedSpace == NumOps) return;
124 ReservedSpace = NumOps;
125 Use *NewOps = new Use[NumOps];
126 Use *OldOps = OperandList;
127 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
128 NewOps[i].init(OldOps[i], this);
132 OperandList = NewOps;
135 /// hasConstantValue - If the specified PHI node always merges together the same
136 /// value, return the value, otherwise return null.
138 Value *PHINode::hasConstantValue(bool AllowNonDominatingInstruction) {
139 // If the PHI node only has one incoming value, eliminate the PHI node...
140 if (getNumIncomingValues() == 1)
141 return getIncomingValue(0);
143 // Otherwise if all of the incoming values are the same for the PHI, replace
144 // the PHI node with the incoming value.
147 for (unsigned i = 0, e = getNumIncomingValues(); i != e; ++i)
148 if (getIncomingValue(i) != this && // Not the PHI node itself...
149 !isa<UndefValue>(getIncomingValue(i)))
150 if (InVal && getIncomingValue(i) != InVal)
151 return 0; // Not the same, bail out.
153 InVal = getIncomingValue(i);
155 // The only case that could cause InVal to be null is if we have a PHI node
156 // that only has entries for itself. In this case, there is no entry into the
157 // loop, so kill the PHI.
159 if (InVal == 0) InVal = UndefValue::get(getType());
161 // All of the incoming values are the same, return the value now.
166 //===----------------------------------------------------------------------===//
167 // CallInst Implementation
168 //===----------------------------------------------------------------------===//
170 CallInst::~CallInst() {
171 delete [] OperandList;
174 void CallInst::init(Value *Func, const std::vector<Value*> &Params) {
175 NumOperands = Params.size()+1;
176 Use *OL = OperandList = new Use[Params.size()+1];
177 OL[0].init(Func, this);
179 const FunctionType *FTy =
180 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
182 assert((Params.size() == FTy->getNumParams() ||
183 (FTy->isVarArg() && Params.size() > FTy->getNumParams())) &&
184 "Calling a function with bad signature");
185 for (unsigned i = 0, e = Params.size(); i != e; ++i)
186 OL[i+1].init(Params[i], this);
189 void CallInst::init(Value *Func, Value *Actual1, Value *Actual2) {
191 Use *OL = OperandList = new Use[3];
192 OL[0].init(Func, this);
193 OL[1].init(Actual1, this);
194 OL[2].init(Actual2, this);
196 const FunctionType *FTy =
197 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
199 assert((FTy->getNumParams() == 2 ||
200 (FTy->isVarArg() && FTy->getNumParams() == 0)) &&
201 "Calling a function with bad signature");
204 void CallInst::init(Value *Func, Value *Actual) {
206 Use *OL = OperandList = new Use[2];
207 OL[0].init(Func, this);
208 OL[1].init(Actual, this);
210 const FunctionType *FTy =
211 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
213 assert((FTy->getNumParams() == 1 ||
214 (FTy->isVarArg() && FTy->getNumParams() == 0)) &&
215 "Calling a function with bad signature");
218 void CallInst::init(Value *Func) {
220 Use *OL = OperandList = new Use[1];
221 OL[0].init(Func, this);
223 const FunctionType *MTy =
224 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
226 assert(MTy->getNumParams() == 0 && "Calling a function with bad signature");
229 CallInst::CallInst(Value *Func, const std::vector<Value*> &Params,
230 const std::string &Name, Instruction *InsertBefore)
231 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
232 ->getElementType())->getReturnType(),
233 Instruction::Call, 0, 0, Name, InsertBefore) {
237 CallInst::CallInst(Value *Func, const std::vector<Value*> &Params,
238 const std::string &Name, BasicBlock *InsertAtEnd)
239 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
240 ->getElementType())->getReturnType(),
241 Instruction::Call, 0, 0, Name, InsertAtEnd) {
245 CallInst::CallInst(Value *Func, Value *Actual1, Value *Actual2,
246 const std::string &Name, Instruction *InsertBefore)
247 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
248 ->getElementType())->getReturnType(),
249 Instruction::Call, 0, 0, Name, InsertBefore) {
250 init(Func, Actual1, Actual2);
253 CallInst::CallInst(Value *Func, Value *Actual1, Value *Actual2,
254 const std::string &Name, BasicBlock *InsertAtEnd)
255 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
256 ->getElementType())->getReturnType(),
257 Instruction::Call, 0, 0, Name, InsertAtEnd) {
258 init(Func, Actual1, Actual2);
261 CallInst::CallInst(Value *Func, Value* Actual, const std::string &Name,
262 Instruction *InsertBefore)
263 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
264 ->getElementType())->getReturnType(),
265 Instruction::Call, 0, 0, Name, InsertBefore) {
269 CallInst::CallInst(Value *Func, Value* Actual, const std::string &Name,
270 BasicBlock *InsertAtEnd)
271 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
272 ->getElementType())->getReturnType(),
273 Instruction::Call, 0, 0, Name, InsertAtEnd) {
277 CallInst::CallInst(Value *Func, const std::string &Name,
278 Instruction *InsertBefore)
279 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
280 ->getElementType())->getReturnType(),
281 Instruction::Call, 0, 0, Name, InsertBefore) {
285 CallInst::CallInst(Value *Func, const std::string &Name,
286 BasicBlock *InsertAtEnd)
287 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
288 ->getElementType())->getReturnType(),
289 Instruction::Call, 0, 0, Name, InsertAtEnd) {
293 CallInst::CallInst(const CallInst &CI)
294 : Instruction(CI.getType(), Instruction::Call, new Use[CI.getNumOperands()],
295 CI.getNumOperands()) {
296 SubclassData = CI.SubclassData;
297 Use *OL = OperandList;
298 Use *InOL = CI.OperandList;
299 for (unsigned i = 0, e = CI.getNumOperands(); i != e; ++i)
300 OL[i].init(InOL[i], this);
304 //===----------------------------------------------------------------------===//
305 // InvokeInst Implementation
306 //===----------------------------------------------------------------------===//
308 InvokeInst::~InvokeInst() {
309 delete [] OperandList;
312 void InvokeInst::init(Value *Fn, BasicBlock *IfNormal, BasicBlock *IfException,
313 const std::vector<Value*> &Params) {
314 NumOperands = 3+Params.size();
315 Use *OL = OperandList = new Use[3+Params.size()];
316 OL[0].init(Fn, this);
317 OL[1].init(IfNormal, this);
318 OL[2].init(IfException, this);
319 const FunctionType *FTy =
320 cast<FunctionType>(cast<PointerType>(Fn->getType())->getElementType());
322 assert((Params.size() == FTy->getNumParams()) ||
323 (FTy->isVarArg() && Params.size() > FTy->getNumParams()) &&
324 "Calling a function with bad signature");
326 for (unsigned i = 0, e = Params.size(); i != e; i++)
327 OL[i+3].init(Params[i], this);
330 InvokeInst::InvokeInst(Value *Fn, BasicBlock *IfNormal,
331 BasicBlock *IfException,
332 const std::vector<Value*> &Params,
333 const std::string &Name, Instruction *InsertBefore)
334 : TerminatorInst(cast<FunctionType>(cast<PointerType>(Fn->getType())
335 ->getElementType())->getReturnType(),
336 Instruction::Invoke, 0, 0, Name, InsertBefore) {
337 init(Fn, IfNormal, IfException, Params);
340 InvokeInst::InvokeInst(Value *Fn, BasicBlock *IfNormal,
341 BasicBlock *IfException,
342 const std::vector<Value*> &Params,
343 const std::string &Name, BasicBlock *InsertAtEnd)
344 : TerminatorInst(cast<FunctionType>(cast<PointerType>(Fn->getType())
345 ->getElementType())->getReturnType(),
346 Instruction::Invoke, 0, 0, Name, InsertAtEnd) {
347 init(Fn, IfNormal, IfException, Params);
350 InvokeInst::InvokeInst(const InvokeInst &II)
351 : TerminatorInst(II.getType(), Instruction::Invoke,
352 new Use[II.getNumOperands()], II.getNumOperands()) {
353 SubclassData = II.SubclassData;
354 Use *OL = OperandList, *InOL = II.OperandList;
355 for (unsigned i = 0, e = II.getNumOperands(); i != e; ++i)
356 OL[i].init(InOL[i], this);
359 BasicBlock *InvokeInst::getSuccessorV(unsigned idx) const {
360 return getSuccessor(idx);
362 unsigned InvokeInst::getNumSuccessorsV() const {
363 return getNumSuccessors();
365 void InvokeInst::setSuccessorV(unsigned idx, BasicBlock *B) {
366 return setSuccessor(idx, B);
370 //===----------------------------------------------------------------------===//
371 // ReturnInst Implementation
372 //===----------------------------------------------------------------------===//
374 void ReturnInst::init(Value *retVal) {
375 if (retVal && retVal->getType() != Type::VoidTy) {
376 assert(!isa<BasicBlock>(retVal) &&
377 "Cannot return basic block. Probably using the incorrect ctor");
379 RetVal.init(retVal, this);
383 unsigned ReturnInst::getNumSuccessorsV() const {
384 return getNumSuccessors();
387 // Out-of-line ReturnInst method, put here so the C++ compiler can choose to
388 // emit the vtable for the class in this translation unit.
389 void ReturnInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
390 assert(0 && "ReturnInst has no successors!");
393 BasicBlock *ReturnInst::getSuccessorV(unsigned idx) const {
394 assert(0 && "ReturnInst has no successors!");
400 //===----------------------------------------------------------------------===//
401 // UnwindInst Implementation
402 //===----------------------------------------------------------------------===//
404 unsigned UnwindInst::getNumSuccessorsV() const {
405 return getNumSuccessors();
408 void UnwindInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
409 assert(0 && "UnwindInst has no successors!");
412 BasicBlock *UnwindInst::getSuccessorV(unsigned idx) const {
413 assert(0 && "UnwindInst has no successors!");
418 //===----------------------------------------------------------------------===//
419 // UnreachableInst Implementation
420 //===----------------------------------------------------------------------===//
422 unsigned UnreachableInst::getNumSuccessorsV() const {
423 return getNumSuccessors();
426 void UnreachableInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
427 assert(0 && "UnwindInst has no successors!");
430 BasicBlock *UnreachableInst::getSuccessorV(unsigned idx) const {
431 assert(0 && "UnwindInst has no successors!");
436 //===----------------------------------------------------------------------===//
437 // BranchInst Implementation
438 //===----------------------------------------------------------------------===//
440 void BranchInst::AssertOK() {
442 assert(getCondition()->getType() == Type::BoolTy &&
443 "May only branch on boolean predicates!");
446 BranchInst::BranchInst(const BranchInst &BI) :
447 TerminatorInst(Instruction::Br, Ops, BI.getNumOperands()) {
448 OperandList[0].init(BI.getOperand(0), this);
449 if (BI.getNumOperands() != 1) {
450 assert(BI.getNumOperands() == 3 && "BR can have 1 or 3 operands!");
451 OperandList[1].init(BI.getOperand(1), this);
452 OperandList[2].init(BI.getOperand(2), this);
456 BasicBlock *BranchInst::getSuccessorV(unsigned idx) const {
457 return getSuccessor(idx);
459 unsigned BranchInst::getNumSuccessorsV() const {
460 return getNumSuccessors();
462 void BranchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
463 setSuccessor(idx, B);
467 //===----------------------------------------------------------------------===//
468 // AllocationInst Implementation
469 //===----------------------------------------------------------------------===//
471 static Value *getAISize(Value *Amt) {
473 Amt = ConstantUInt::get(Type::UIntTy, 1);
475 assert(Amt->getType() == Type::UIntTy &&
476 "Malloc/Allocation array size != UIntTy!");
480 AllocationInst::AllocationInst(const Type *Ty, Value *ArraySize, unsigned iTy,
481 const std::string &Name,
482 Instruction *InsertBefore)
483 : UnaryInstruction(PointerType::get(Ty), iTy, getAISize(ArraySize),
484 Name, InsertBefore) {
485 assert(Ty != Type::VoidTy && "Cannot allocate void!");
488 AllocationInst::AllocationInst(const Type *Ty, Value *ArraySize, unsigned iTy,
489 const std::string &Name,
490 BasicBlock *InsertAtEnd)
491 : UnaryInstruction(PointerType::get(Ty), iTy, getAISize(ArraySize),
493 assert(Ty != Type::VoidTy && "Cannot allocate void!");
496 bool AllocationInst::isArrayAllocation() const {
497 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(getOperand(0)))
498 return CUI->getValue() != 1;
502 const Type *AllocationInst::getAllocatedType() const {
503 return getType()->getElementType();
506 AllocaInst::AllocaInst(const AllocaInst &AI)
507 : AllocationInst(AI.getType()->getElementType(), (Value*)AI.getOperand(0),
508 Instruction::Alloca) {
511 MallocInst::MallocInst(const MallocInst &MI)
512 : AllocationInst(MI.getType()->getElementType(), (Value*)MI.getOperand(0),
513 Instruction::Malloc) {
516 //===----------------------------------------------------------------------===//
517 // FreeInst Implementation
518 //===----------------------------------------------------------------------===//
520 void FreeInst::AssertOK() {
521 assert(isa<PointerType>(getOperand(0)->getType()) &&
522 "Can not free something of nonpointer type!");
525 FreeInst::FreeInst(Value *Ptr, Instruction *InsertBefore)
526 : UnaryInstruction(Type::VoidTy, Free, Ptr, "", InsertBefore) {
530 FreeInst::FreeInst(Value *Ptr, BasicBlock *InsertAtEnd)
531 : UnaryInstruction(Type::VoidTy, Free, Ptr, "", InsertAtEnd) {
536 //===----------------------------------------------------------------------===//
537 // LoadInst Implementation
538 //===----------------------------------------------------------------------===//
540 void LoadInst::AssertOK() {
541 assert(isa<PointerType>(getOperand(0)->getType()) &&
542 "Ptr must have pointer type.");
545 LoadInst::LoadInst(Value *Ptr, const std::string &Name, Instruction *InsertBef)
546 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
547 Load, Ptr, Name, InsertBef) {
552 LoadInst::LoadInst(Value *Ptr, const std::string &Name, BasicBlock *InsertAE)
553 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
554 Load, Ptr, Name, InsertAE) {
559 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile,
560 Instruction *InsertBef)
561 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
562 Load, Ptr, Name, InsertBef) {
563 setVolatile(isVolatile);
567 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile,
568 BasicBlock *InsertAE)
569 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
570 Load, Ptr, Name, InsertAE) {
571 setVolatile(isVolatile);
576 //===----------------------------------------------------------------------===//
577 // StoreInst Implementation
578 //===----------------------------------------------------------------------===//
580 void StoreInst::AssertOK() {
581 assert(isa<PointerType>(getOperand(1)->getType()) &&
582 "Ptr must have pointer type!");
583 assert(getOperand(0)->getType() ==
584 cast<PointerType>(getOperand(1)->getType())->getElementType()
585 && "Ptr must be a pointer to Val type!");
589 StoreInst::StoreInst(Value *val, Value *addr, Instruction *InsertBefore)
590 : Instruction(Type::VoidTy, Store, Ops, 2, "", InsertBefore) {
591 Ops[0].init(val, this);
592 Ops[1].init(addr, this);
597 StoreInst::StoreInst(Value *val, Value *addr, BasicBlock *InsertAtEnd)
598 : Instruction(Type::VoidTy, Store, Ops, 2, "", InsertAtEnd) {
599 Ops[0].init(val, this);
600 Ops[1].init(addr, this);
605 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
606 Instruction *InsertBefore)
607 : Instruction(Type::VoidTy, Store, Ops, 2, "", InsertBefore) {
608 Ops[0].init(val, this);
609 Ops[1].init(addr, this);
610 setVolatile(isVolatile);
614 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
615 BasicBlock *InsertAtEnd)
616 : Instruction(Type::VoidTy, Store, Ops, 2, "", InsertAtEnd) {
617 Ops[0].init(val, this);
618 Ops[1].init(addr, this);
619 setVolatile(isVolatile);
623 //===----------------------------------------------------------------------===//
624 // GetElementPtrInst Implementation
625 //===----------------------------------------------------------------------===//
627 // checkType - Simple wrapper function to give a better assertion failure
628 // message on bad indexes for a gep instruction.
630 static inline const Type *checkType(const Type *Ty) {
631 assert(Ty && "Invalid indices for type!");
635 void GetElementPtrInst::init(Value *Ptr, const std::vector<Value*> &Idx) {
636 NumOperands = 1+Idx.size();
637 Use *OL = OperandList = new Use[NumOperands];
638 OL[0].init(Ptr, this);
640 for (unsigned i = 0, e = Idx.size(); i != e; ++i)
641 OL[i+1].init(Idx[i], this);
644 void GetElementPtrInst::init(Value *Ptr, Value *Idx0, Value *Idx1) {
646 Use *OL = OperandList = new Use[3];
647 OL[0].init(Ptr, this);
648 OL[1].init(Idx0, this);
649 OL[2].init(Idx1, this);
652 void GetElementPtrInst::init(Value *Ptr, Value *Idx) {
654 Use *OL = OperandList = new Use[2];
655 OL[0].init(Ptr, this);
656 OL[1].init(Idx, this);
659 GetElementPtrInst::GetElementPtrInst(Value *Ptr, const std::vector<Value*> &Idx,
660 const std::string &Name, Instruction *InBe)
661 : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),
663 GetElementPtr, 0, 0, Name, InBe) {
667 GetElementPtrInst::GetElementPtrInst(Value *Ptr, const std::vector<Value*> &Idx,
668 const std::string &Name, BasicBlock *IAE)
669 : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),
671 GetElementPtr, 0, 0, Name, IAE) {
675 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx,
676 const std::string &Name, Instruction *InBe)
677 : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),Idx))),
678 GetElementPtr, 0, 0, Name, InBe) {
682 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx,
683 const std::string &Name, BasicBlock *IAE)
684 : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),Idx))),
685 GetElementPtr, 0, 0, Name, IAE) {
689 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx0, Value *Idx1,
690 const std::string &Name, Instruction *InBe)
691 : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),
693 GetElementPtr, 0, 0, Name, InBe) {
694 init(Ptr, Idx0, Idx1);
697 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx0, Value *Idx1,
698 const std::string &Name, BasicBlock *IAE)
699 : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),
701 GetElementPtr, 0, 0, Name, IAE) {
702 init(Ptr, Idx0, Idx1);
705 GetElementPtrInst::~GetElementPtrInst() {
706 delete[] OperandList;
709 // getIndexedType - Returns the type of the element that would be loaded with
710 // a load instruction with the specified parameters.
712 // A null type is returned if the indices are invalid for the specified
715 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr,
716 const std::vector<Value*> &Idx,
717 bool AllowCompositeLeaf) {
718 if (!isa<PointerType>(Ptr)) return 0; // Type isn't a pointer type!
720 // Handle the special case of the empty set index set...
722 if (AllowCompositeLeaf ||
723 cast<PointerType>(Ptr)->getElementType()->isFirstClassType())
724 return cast<PointerType>(Ptr)->getElementType();
729 while (const CompositeType *CT = dyn_cast<CompositeType>(Ptr)) {
730 if (Idx.size() == CurIdx) {
731 if (AllowCompositeLeaf || CT->isFirstClassType()) return Ptr;
732 return 0; // Can't load a whole structure or array!?!?
735 Value *Index = Idx[CurIdx++];
736 if (isa<PointerType>(CT) && CurIdx != 1)
737 return 0; // Can only index into pointer types at the first index!
738 if (!CT->indexValid(Index)) return 0;
739 Ptr = CT->getTypeAtIndex(Index);
741 // If the new type forwards to another type, then it is in the middle
742 // of being refined to another type (and hence, may have dropped all
743 // references to what it was using before). So, use the new forwarded
745 if (const Type * Ty = Ptr->getForwardedType()) {
749 return CurIdx == Idx.size() ? Ptr : 0;
752 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr,
753 Value *Idx0, Value *Idx1,
754 bool AllowCompositeLeaf) {
755 const PointerType *PTy = dyn_cast<PointerType>(Ptr);
756 if (!PTy) return 0; // Type isn't a pointer type!
758 // Check the pointer index.
759 if (!PTy->indexValid(Idx0)) return 0;
761 const CompositeType *CT = dyn_cast<CompositeType>(PTy->getElementType());
762 if (!CT || !CT->indexValid(Idx1)) return 0;
764 const Type *ElTy = CT->getTypeAtIndex(Idx1);
765 if (AllowCompositeLeaf || ElTy->isFirstClassType())
770 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr, Value *Idx) {
771 const PointerType *PTy = dyn_cast<PointerType>(Ptr);
772 if (!PTy) return 0; // Type isn't a pointer type!
774 // Check the pointer index.
775 if (!PTy->indexValid(Idx)) return 0;
777 return PTy->getElementType();
780 //===----------------------------------------------------------------------===//
781 // BinaryOperator Class
782 //===----------------------------------------------------------------------===//
784 void BinaryOperator::init(BinaryOps iType)
786 Value *LHS = getOperand(0), *RHS = getOperand(1);
787 assert(LHS->getType() == RHS->getType() &&
788 "Binary operator operand types must match!");
794 assert(getType() == LHS->getType() &&
795 "Arithmetic operation should return same type as operands!");
796 assert((getType()->isInteger() ||
797 getType()->isFloatingPoint() ||
798 isa<PackedType>(getType()) ) &&
799 "Tried to create an arithmetic operation on a non-arithmetic type!");
803 assert(getType() == LHS->getType() &&
804 "Logical operation should return same type as operands!");
805 assert(getType()->isIntegral() &&
806 "Tried to create a logical operation on a non-integral type!");
808 case SetLT: case SetGT: case SetLE:
809 case SetGE: case SetEQ: case SetNE:
810 assert(getType() == Type::BoolTy && "Setcc must return bool!");
817 BinaryOperator *BinaryOperator::create(BinaryOps Op, Value *S1, Value *S2,
818 const std::string &Name,
819 Instruction *InsertBefore) {
820 assert(S1->getType() == S2->getType() &&
821 "Cannot create binary operator with two operands of differing type!");
823 // Binary comparison operators...
824 case SetLT: case SetGT: case SetLE:
825 case SetGE: case SetEQ: case SetNE:
826 return new SetCondInst(Op, S1, S2, Name, InsertBefore);
829 return new BinaryOperator(Op, S1, S2, S1->getType(), Name, InsertBefore);
833 BinaryOperator *BinaryOperator::create(BinaryOps Op, Value *S1, Value *S2,
834 const std::string &Name,
835 BasicBlock *InsertAtEnd) {
836 BinaryOperator *Res = create(Op, S1, S2, Name);
837 InsertAtEnd->getInstList().push_back(Res);
841 BinaryOperator *BinaryOperator::createNeg(Value *Op, const std::string &Name,
842 Instruction *InsertBefore) {
843 if (!Op->getType()->isFloatingPoint())
844 return new BinaryOperator(Instruction::Sub,
845 Constant::getNullValue(Op->getType()), Op,
846 Op->getType(), Name, InsertBefore);
848 return new BinaryOperator(Instruction::Sub,
849 ConstantFP::get(Op->getType(), -0.0), Op,
850 Op->getType(), Name, InsertBefore);
853 BinaryOperator *BinaryOperator::createNeg(Value *Op, const std::string &Name,
854 BasicBlock *InsertAtEnd) {
855 if (!Op->getType()->isFloatingPoint())
856 return new BinaryOperator(Instruction::Sub,
857 Constant::getNullValue(Op->getType()), Op,
858 Op->getType(), Name, InsertAtEnd);
860 return new BinaryOperator(Instruction::Sub,
861 ConstantFP::get(Op->getType(), -0.0), Op,
862 Op->getType(), Name, InsertAtEnd);
865 BinaryOperator *BinaryOperator::createNot(Value *Op, const std::string &Name,
866 Instruction *InsertBefore) {
867 return new BinaryOperator(Instruction::Xor, Op,
868 ConstantIntegral::getAllOnesValue(Op->getType()),
869 Op->getType(), Name, InsertBefore);
872 BinaryOperator *BinaryOperator::createNot(Value *Op, const std::string &Name,
873 BasicBlock *InsertAtEnd) {
874 return new BinaryOperator(Instruction::Xor, Op,
875 ConstantIntegral::getAllOnesValue(Op->getType()),
876 Op->getType(), Name, InsertAtEnd);
880 // isConstantAllOnes - Helper function for several functions below
881 static inline bool isConstantAllOnes(const Value *V) {
882 return isa<ConstantIntegral>(V) &&cast<ConstantIntegral>(V)->isAllOnesValue();
885 bool BinaryOperator::isNeg(const Value *V) {
886 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
887 if (Bop->getOpcode() == Instruction::Sub)
888 if (!V->getType()->isFloatingPoint())
889 return Bop->getOperand(0) == Constant::getNullValue(Bop->getType());
891 return Bop->getOperand(0) == ConstantFP::get(Bop->getType(), -0.0);
895 bool BinaryOperator::isNot(const Value *V) {
896 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
897 return (Bop->getOpcode() == Instruction::Xor &&
898 (isConstantAllOnes(Bop->getOperand(1)) ||
899 isConstantAllOnes(Bop->getOperand(0))));
903 Value *BinaryOperator::getNegArgument(Value *BinOp) {
904 assert(isNeg(BinOp) && "getNegArgument from non-'neg' instruction!");
905 return cast<BinaryOperator>(BinOp)->getOperand(1);
908 const Value *BinaryOperator::getNegArgument(const Value *BinOp) {
909 return getNegArgument(const_cast<Value*>(BinOp));
912 Value *BinaryOperator::getNotArgument(Value *BinOp) {
913 assert(isNot(BinOp) && "getNotArgument on non-'not' instruction!");
914 BinaryOperator *BO = cast<BinaryOperator>(BinOp);
915 Value *Op0 = BO->getOperand(0);
916 Value *Op1 = BO->getOperand(1);
917 if (isConstantAllOnes(Op0)) return Op1;
919 assert(isConstantAllOnes(Op1));
923 const Value *BinaryOperator::getNotArgument(const Value *BinOp) {
924 return getNotArgument(const_cast<Value*>(BinOp));
928 // swapOperands - Exchange the two operands to this instruction. This
929 // instruction is safe to use on any binary instruction and does not
930 // modify the semantics of the instruction. If the instruction is
931 // order dependent (SetLT f.e.) the opcode is changed.
933 bool BinaryOperator::swapOperands() {
935 ; // If the instruction is commutative, it is safe to swap the operands
936 else if (SetCondInst *SCI = dyn_cast<SetCondInst>(this))
937 /// FIXME: SetCC instructions shouldn't all have different opcodes.
938 setOpcode(SCI->getSwappedCondition());
940 return true; // Can't commute operands
942 std::swap(Ops[0], Ops[1]);
947 //===----------------------------------------------------------------------===//
949 //===----------------------------------------------------------------------===//
951 SetCondInst::SetCondInst(BinaryOps Opcode, Value *S1, Value *S2,
952 const std::string &Name, Instruction *InsertBefore)
953 : BinaryOperator(Opcode, S1, S2, Type::BoolTy, Name, InsertBefore) {
955 // Make sure it's a valid type... getInverseCondition will assert out if not.
956 assert(getInverseCondition(Opcode));
959 SetCondInst::SetCondInst(BinaryOps Opcode, Value *S1, Value *S2,
960 const std::string &Name, BasicBlock *InsertAtEnd)
961 : BinaryOperator(Opcode, S1, S2, Type::BoolTy, Name, InsertAtEnd) {
963 // Make sure it's a valid type... getInverseCondition will assert out if not.
964 assert(getInverseCondition(Opcode));
967 // getInverseCondition - Return the inverse of the current condition opcode.
968 // For example seteq -> setne, setgt -> setle, setlt -> setge, etc...
970 Instruction::BinaryOps SetCondInst::getInverseCondition(BinaryOps Opcode) {
973 assert(0 && "Unknown setcc opcode!");
974 case SetEQ: return SetNE;
975 case SetNE: return SetEQ;
976 case SetGT: return SetLE;
977 case SetLT: return SetGE;
978 case SetGE: return SetLT;
979 case SetLE: return SetGT;
983 // getSwappedCondition - Return the condition opcode that would be the result
984 // of exchanging the two operands of the setcc instruction without changing
985 // the result produced. Thus, seteq->seteq, setle->setge, setlt->setgt, etc.
987 Instruction::BinaryOps SetCondInst::getSwappedCondition(BinaryOps Opcode) {
989 default: assert(0 && "Unknown setcc instruction!");
990 case SetEQ: case SetNE: return Opcode;
991 case SetGT: return SetLT;
992 case SetLT: return SetGT;
993 case SetGE: return SetLE;
994 case SetLE: return SetGE;
998 //===----------------------------------------------------------------------===//
999 // SwitchInst Implementation
1000 //===----------------------------------------------------------------------===//
1002 void SwitchInst::init(Value *Value, BasicBlock *Default, unsigned NumCases) {
1003 assert(Value && Default);
1004 ReservedSpace = 2+NumCases*2;
1006 OperandList = new Use[ReservedSpace];
1008 OperandList[0].init(Value, this);
1009 OperandList[1].init(Default, this);
1012 SwitchInst::SwitchInst(const SwitchInst &SI)
1013 : TerminatorInst(Instruction::Switch, new Use[SI.getNumOperands()],
1014 SI.getNumOperands()) {
1015 Use *OL = OperandList, *InOL = SI.OperandList;
1016 for (unsigned i = 0, E = SI.getNumOperands(); i != E; i+=2) {
1017 OL[i].init(InOL[i], this);
1018 OL[i+1].init(InOL[i+1], this);
1022 SwitchInst::~SwitchInst() {
1023 delete [] OperandList;
1027 /// addCase - Add an entry to the switch instruction...
1029 void SwitchInst::addCase(ConstantInt *OnVal, BasicBlock *Dest) {
1030 unsigned OpNo = NumOperands;
1031 if (OpNo+2 > ReservedSpace)
1032 resizeOperands(0); // Get more space!
1033 // Initialize some new operands.
1034 assert(OpNo+1 < ReservedSpace && "Growing didn't work!");
1035 NumOperands = OpNo+2;
1036 OperandList[OpNo].init(OnVal, this);
1037 OperandList[OpNo+1].init(Dest, this);
1040 /// removeCase - This method removes the specified successor from the switch
1041 /// instruction. Note that this cannot be used to remove the default
1042 /// destination (successor #0).
1044 void SwitchInst::removeCase(unsigned idx) {
1045 assert(idx != 0 && "Cannot remove the default case!");
1046 assert(idx*2 < getNumOperands() && "Successor index out of range!!!");
1048 unsigned NumOps = getNumOperands();
1049 Use *OL = OperandList;
1051 // Move everything after this operand down.
1053 // FIXME: we could just swap with the end of the list, then erase. However,
1054 // client might not expect this to happen. The code as it is thrashes the
1055 // use/def lists, which is kinda lame.
1056 for (unsigned i = (idx+1)*2; i != NumOps; i += 2) {
1058 OL[i-2+1] = OL[i+1];
1061 // Nuke the last value.
1062 OL[NumOps-2].set(0);
1063 OL[NumOps-2+1].set(0);
1064 NumOperands = NumOps-2;
1067 /// resizeOperands - resize operands - This adjusts the length of the operands
1068 /// list according to the following behavior:
1069 /// 1. If NumOps == 0, grow the operand list in response to a push_back style
1070 /// of operation. This grows the number of ops by 1.5 times.
1071 /// 2. If NumOps > NumOperands, reserve space for NumOps operands.
1072 /// 3. If NumOps == NumOperands, trim the reserved space.
1074 void SwitchInst::resizeOperands(unsigned NumOps) {
1076 NumOps = getNumOperands()/2*6;
1077 } else if (NumOps*2 > NumOperands) {
1078 // No resize needed.
1079 if (ReservedSpace >= NumOps) return;
1080 } else if (NumOps == NumOperands) {
1081 if (ReservedSpace == NumOps) return;
1086 ReservedSpace = NumOps;
1087 Use *NewOps = new Use[NumOps];
1088 Use *OldOps = OperandList;
1089 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1090 NewOps[i].init(OldOps[i], this);
1094 OperandList = NewOps;
1098 BasicBlock *SwitchInst::getSuccessorV(unsigned idx) const {
1099 return getSuccessor(idx);
1101 unsigned SwitchInst::getNumSuccessorsV() const {
1102 return getNumSuccessors();
1104 void SwitchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
1105 setSuccessor(idx, B);
1109 // Define these methods here so vtables don't get emitted into every translation
1110 // unit that uses these classes.
1112 GetElementPtrInst *GetElementPtrInst::clone() const {
1113 return new GetElementPtrInst(*this);
1116 BinaryOperator *BinaryOperator::clone() const {
1117 return create(getOpcode(), Ops[0], Ops[1]);
1120 MallocInst *MallocInst::clone() const { return new MallocInst(*this); }
1121 AllocaInst *AllocaInst::clone() const { return new AllocaInst(*this); }
1122 FreeInst *FreeInst::clone() const { return new FreeInst(getOperand(0)); }
1123 LoadInst *LoadInst::clone() const { return new LoadInst(*this); }
1124 StoreInst *StoreInst::clone() const { return new StoreInst(*this); }
1125 CastInst *CastInst::clone() const { return new CastInst(*this); }
1126 CallInst *CallInst::clone() const { return new CallInst(*this); }
1127 ShiftInst *ShiftInst::clone() const { return new ShiftInst(*this); }
1128 SelectInst *SelectInst::clone() const { return new SelectInst(*this); }
1129 VAArgInst *VAArgInst::clone() const { return new VAArgInst(*this); }
1130 PHINode *PHINode::clone() const { return new PHINode(*this); }
1131 ReturnInst *ReturnInst::clone() const { return new ReturnInst(*this); }
1132 BranchInst *BranchInst::clone() const { return new BranchInst(*this); }
1133 SwitchInst *SwitchInst::clone() const { return new SwitchInst(*this); }
1134 InvokeInst *InvokeInst::clone() const { return new InvokeInst(*this); }
1135 UnwindInst *UnwindInst::clone() const { return new UnwindInst(); }
1136 UnreachableInst *UnreachableInst::clone() const { return new UnreachableInst();}