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) const {
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 bool HasUndefInput = false;
148 for (unsigned i = 0, e = getNumIncomingValues(); i != e; ++i)
149 if (isa<UndefValue>(getIncomingValue(i)))
150 HasUndefInput = true;
151 else if (getIncomingValue(i) != this) // Not the PHI node itself...
152 if (InVal && getIncomingValue(i) != InVal)
153 return 0; // Not the same, bail out.
155 InVal = getIncomingValue(i);
157 // The only case that could cause InVal to be null is if we have a PHI node
158 // that only has entries for itself. In this case, there is no entry into the
159 // loop, so kill the PHI.
161 if (InVal == 0) InVal = UndefValue::get(getType());
163 // If we have a PHI node like phi(X, undef, X), where X is defined by some
164 // instruction, we cannot always return X as the result of the PHI node. Only
165 // do this if X is not an instruction (thus it must dominate the PHI block),
166 // or if the client is prepared to deal with this possibility.
167 if (HasUndefInput && !AllowNonDominatingInstruction)
168 if (Instruction *IV = dyn_cast<Instruction>(InVal))
169 // If it's in the entry block, it dominates everything.
170 if (IV->getParent() != &IV->getParent()->getParent()->front() ||
172 return 0; // Cannot guarantee that InVal dominates this PHINode.
174 // All of the incoming values are the same, return the value now.
179 //===----------------------------------------------------------------------===//
180 // CallInst Implementation
181 //===----------------------------------------------------------------------===//
183 CallInst::~CallInst() {
184 delete [] OperandList;
187 void CallInst::init(Value *Func, const std::vector<Value*> &Params) {
188 NumOperands = Params.size()+1;
189 Use *OL = OperandList = new Use[Params.size()+1];
190 OL[0].init(Func, this);
192 const FunctionType *FTy =
193 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
195 assert((Params.size() == FTy->getNumParams() ||
196 (FTy->isVarArg() && Params.size() > FTy->getNumParams())) &&
197 "Calling a function with bad signature");
198 for (unsigned i = 0, e = Params.size(); i != e; ++i)
199 OL[i+1].init(Params[i], this);
202 void CallInst::init(Value *Func, Value *Actual1, Value *Actual2) {
204 Use *OL = OperandList = new Use[3];
205 OL[0].init(Func, this);
206 OL[1].init(Actual1, this);
207 OL[2].init(Actual2, this);
209 const FunctionType *FTy =
210 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
212 assert((FTy->getNumParams() == 2 ||
213 (FTy->isVarArg() && FTy->getNumParams() == 0)) &&
214 "Calling a function with bad signature");
217 void CallInst::init(Value *Func, Value *Actual) {
219 Use *OL = OperandList = new Use[2];
220 OL[0].init(Func, this);
221 OL[1].init(Actual, this);
223 const FunctionType *FTy =
224 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
226 assert((FTy->getNumParams() == 1 ||
227 (FTy->isVarArg() && FTy->getNumParams() == 0)) &&
228 "Calling a function with bad signature");
231 void CallInst::init(Value *Func) {
233 Use *OL = OperandList = new Use[1];
234 OL[0].init(Func, this);
236 const FunctionType *MTy =
237 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
239 assert(MTy->getNumParams() == 0 && "Calling a function with bad signature");
242 CallInst::CallInst(Value *Func, const std::vector<Value*> &Params,
243 const std::string &Name, Instruction *InsertBefore)
244 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
245 ->getElementType())->getReturnType(),
246 Instruction::Call, 0, 0, Name, InsertBefore) {
250 CallInst::CallInst(Value *Func, const std::vector<Value*> &Params,
251 const std::string &Name, BasicBlock *InsertAtEnd)
252 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
253 ->getElementType())->getReturnType(),
254 Instruction::Call, 0, 0, Name, InsertAtEnd) {
258 CallInst::CallInst(Value *Func, Value *Actual1, Value *Actual2,
259 const std::string &Name, Instruction *InsertBefore)
260 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
261 ->getElementType())->getReturnType(),
262 Instruction::Call, 0, 0, Name, InsertBefore) {
263 init(Func, Actual1, Actual2);
266 CallInst::CallInst(Value *Func, Value *Actual1, Value *Actual2,
267 const std::string &Name, BasicBlock *InsertAtEnd)
268 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
269 ->getElementType())->getReturnType(),
270 Instruction::Call, 0, 0, Name, InsertAtEnd) {
271 init(Func, Actual1, Actual2);
274 CallInst::CallInst(Value *Func, Value* Actual, const std::string &Name,
275 Instruction *InsertBefore)
276 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
277 ->getElementType())->getReturnType(),
278 Instruction::Call, 0, 0, Name, InsertBefore) {
282 CallInst::CallInst(Value *Func, Value* Actual, const std::string &Name,
283 BasicBlock *InsertAtEnd)
284 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
285 ->getElementType())->getReturnType(),
286 Instruction::Call, 0, 0, Name, InsertAtEnd) {
290 CallInst::CallInst(Value *Func, const std::string &Name,
291 Instruction *InsertBefore)
292 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
293 ->getElementType())->getReturnType(),
294 Instruction::Call, 0, 0, Name, InsertBefore) {
298 CallInst::CallInst(Value *Func, const std::string &Name,
299 BasicBlock *InsertAtEnd)
300 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
301 ->getElementType())->getReturnType(),
302 Instruction::Call, 0, 0, Name, InsertAtEnd) {
306 CallInst::CallInst(const CallInst &CI)
307 : Instruction(CI.getType(), Instruction::Call, new Use[CI.getNumOperands()],
308 CI.getNumOperands()) {
309 SubclassData = CI.SubclassData;
310 Use *OL = OperandList;
311 Use *InOL = CI.OperandList;
312 for (unsigned i = 0, e = CI.getNumOperands(); i != e; ++i)
313 OL[i].init(InOL[i], this);
317 //===----------------------------------------------------------------------===//
318 // InvokeInst Implementation
319 //===----------------------------------------------------------------------===//
321 InvokeInst::~InvokeInst() {
322 delete [] OperandList;
325 void InvokeInst::init(Value *Fn, BasicBlock *IfNormal, BasicBlock *IfException,
326 const std::vector<Value*> &Params) {
327 NumOperands = 3+Params.size();
328 Use *OL = OperandList = new Use[3+Params.size()];
329 OL[0].init(Fn, this);
330 OL[1].init(IfNormal, this);
331 OL[2].init(IfException, this);
332 const FunctionType *FTy =
333 cast<FunctionType>(cast<PointerType>(Fn->getType())->getElementType());
335 assert((Params.size() == FTy->getNumParams()) ||
336 (FTy->isVarArg() && Params.size() > FTy->getNumParams()) &&
337 "Calling a function with bad signature");
339 for (unsigned i = 0, e = Params.size(); i != e; i++)
340 OL[i+3].init(Params[i], this);
343 InvokeInst::InvokeInst(Value *Fn, BasicBlock *IfNormal,
344 BasicBlock *IfException,
345 const std::vector<Value*> &Params,
346 const std::string &Name, Instruction *InsertBefore)
347 : TerminatorInst(cast<FunctionType>(cast<PointerType>(Fn->getType())
348 ->getElementType())->getReturnType(),
349 Instruction::Invoke, 0, 0, Name, InsertBefore) {
350 init(Fn, IfNormal, IfException, Params);
353 InvokeInst::InvokeInst(Value *Fn, BasicBlock *IfNormal,
354 BasicBlock *IfException,
355 const std::vector<Value*> &Params,
356 const std::string &Name, BasicBlock *InsertAtEnd)
357 : TerminatorInst(cast<FunctionType>(cast<PointerType>(Fn->getType())
358 ->getElementType())->getReturnType(),
359 Instruction::Invoke, 0, 0, Name, InsertAtEnd) {
360 init(Fn, IfNormal, IfException, Params);
363 InvokeInst::InvokeInst(const InvokeInst &II)
364 : TerminatorInst(II.getType(), Instruction::Invoke,
365 new Use[II.getNumOperands()], II.getNumOperands()) {
366 SubclassData = II.SubclassData;
367 Use *OL = OperandList, *InOL = II.OperandList;
368 for (unsigned i = 0, e = II.getNumOperands(); i != e; ++i)
369 OL[i].init(InOL[i], this);
372 BasicBlock *InvokeInst::getSuccessorV(unsigned idx) const {
373 return getSuccessor(idx);
375 unsigned InvokeInst::getNumSuccessorsV() const {
376 return getNumSuccessors();
378 void InvokeInst::setSuccessorV(unsigned idx, BasicBlock *B) {
379 return setSuccessor(idx, B);
383 //===----------------------------------------------------------------------===//
384 // ReturnInst Implementation
385 //===----------------------------------------------------------------------===//
387 void ReturnInst::init(Value *retVal) {
388 if (retVal && retVal->getType() != Type::VoidTy) {
389 assert(!isa<BasicBlock>(retVal) &&
390 "Cannot return basic block. Probably using the incorrect ctor");
392 RetVal.init(retVal, this);
396 unsigned ReturnInst::getNumSuccessorsV() const {
397 return getNumSuccessors();
400 // Out-of-line ReturnInst method, put here so the C++ compiler can choose to
401 // emit the vtable for the class in this translation unit.
402 void ReturnInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
403 assert(0 && "ReturnInst has no successors!");
406 BasicBlock *ReturnInst::getSuccessorV(unsigned idx) const {
407 assert(0 && "ReturnInst has no successors!");
413 //===----------------------------------------------------------------------===//
414 // UnwindInst Implementation
415 //===----------------------------------------------------------------------===//
417 unsigned UnwindInst::getNumSuccessorsV() const {
418 return getNumSuccessors();
421 void UnwindInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
422 assert(0 && "UnwindInst has no successors!");
425 BasicBlock *UnwindInst::getSuccessorV(unsigned idx) const {
426 assert(0 && "UnwindInst has no successors!");
431 //===----------------------------------------------------------------------===//
432 // UnreachableInst Implementation
433 //===----------------------------------------------------------------------===//
435 unsigned UnreachableInst::getNumSuccessorsV() const {
436 return getNumSuccessors();
439 void UnreachableInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
440 assert(0 && "UnwindInst has no successors!");
443 BasicBlock *UnreachableInst::getSuccessorV(unsigned idx) const {
444 assert(0 && "UnwindInst has no successors!");
449 //===----------------------------------------------------------------------===//
450 // BranchInst Implementation
451 //===----------------------------------------------------------------------===//
453 void BranchInst::AssertOK() {
455 assert(getCondition()->getType() == Type::BoolTy &&
456 "May only branch on boolean predicates!");
459 BranchInst::BranchInst(const BranchInst &BI) :
460 TerminatorInst(Instruction::Br, Ops, BI.getNumOperands()) {
461 OperandList[0].init(BI.getOperand(0), this);
462 if (BI.getNumOperands() != 1) {
463 assert(BI.getNumOperands() == 3 && "BR can have 1 or 3 operands!");
464 OperandList[1].init(BI.getOperand(1), this);
465 OperandList[2].init(BI.getOperand(2), this);
469 BasicBlock *BranchInst::getSuccessorV(unsigned idx) const {
470 return getSuccessor(idx);
472 unsigned BranchInst::getNumSuccessorsV() const {
473 return getNumSuccessors();
475 void BranchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
476 setSuccessor(idx, B);
480 //===----------------------------------------------------------------------===//
481 // AllocationInst Implementation
482 //===----------------------------------------------------------------------===//
484 static Value *getAISize(Value *Amt) {
486 Amt = ConstantUInt::get(Type::UIntTy, 1);
488 assert(Amt->getType() == Type::UIntTy &&
489 "Malloc/Allocation array size != UIntTy!");
493 AllocationInst::AllocationInst(const Type *Ty, Value *ArraySize, unsigned iTy,
494 const std::string &Name,
495 Instruction *InsertBefore)
496 : UnaryInstruction(PointerType::get(Ty), iTy, getAISize(ArraySize),
497 Name, InsertBefore) {
498 assert(Ty != Type::VoidTy && "Cannot allocate void!");
501 AllocationInst::AllocationInst(const Type *Ty, Value *ArraySize, unsigned iTy,
502 const std::string &Name,
503 BasicBlock *InsertAtEnd)
504 : UnaryInstruction(PointerType::get(Ty), iTy, getAISize(ArraySize),
506 assert(Ty != Type::VoidTy && "Cannot allocate void!");
509 bool AllocationInst::isArrayAllocation() const {
510 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(getOperand(0)))
511 return CUI->getValue() != 1;
515 const Type *AllocationInst::getAllocatedType() const {
516 return getType()->getElementType();
519 AllocaInst::AllocaInst(const AllocaInst &AI)
520 : AllocationInst(AI.getType()->getElementType(), (Value*)AI.getOperand(0),
521 Instruction::Alloca) {
524 MallocInst::MallocInst(const MallocInst &MI)
525 : AllocationInst(MI.getType()->getElementType(), (Value*)MI.getOperand(0),
526 Instruction::Malloc) {
529 //===----------------------------------------------------------------------===//
530 // FreeInst Implementation
531 //===----------------------------------------------------------------------===//
533 void FreeInst::AssertOK() {
534 assert(isa<PointerType>(getOperand(0)->getType()) &&
535 "Can not free something of nonpointer type!");
538 FreeInst::FreeInst(Value *Ptr, Instruction *InsertBefore)
539 : UnaryInstruction(Type::VoidTy, Free, Ptr, "", InsertBefore) {
543 FreeInst::FreeInst(Value *Ptr, BasicBlock *InsertAtEnd)
544 : UnaryInstruction(Type::VoidTy, Free, Ptr, "", InsertAtEnd) {
549 //===----------------------------------------------------------------------===//
550 // LoadInst Implementation
551 //===----------------------------------------------------------------------===//
553 void LoadInst::AssertOK() {
554 assert(isa<PointerType>(getOperand(0)->getType()) &&
555 "Ptr must have pointer type.");
558 LoadInst::LoadInst(Value *Ptr, const std::string &Name, Instruction *InsertBef)
559 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
560 Load, Ptr, Name, InsertBef) {
565 LoadInst::LoadInst(Value *Ptr, const std::string &Name, BasicBlock *InsertAE)
566 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
567 Load, Ptr, Name, InsertAE) {
572 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile,
573 Instruction *InsertBef)
574 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
575 Load, Ptr, Name, InsertBef) {
576 setVolatile(isVolatile);
580 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile,
581 BasicBlock *InsertAE)
582 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
583 Load, Ptr, Name, InsertAE) {
584 setVolatile(isVolatile);
589 //===----------------------------------------------------------------------===//
590 // StoreInst Implementation
591 //===----------------------------------------------------------------------===//
593 void StoreInst::AssertOK() {
594 assert(isa<PointerType>(getOperand(1)->getType()) &&
595 "Ptr must have pointer type!");
596 assert(getOperand(0)->getType() ==
597 cast<PointerType>(getOperand(1)->getType())->getElementType()
598 && "Ptr must be a pointer to Val type!");
602 StoreInst::StoreInst(Value *val, Value *addr, Instruction *InsertBefore)
603 : Instruction(Type::VoidTy, Store, Ops, 2, "", InsertBefore) {
604 Ops[0].init(val, this);
605 Ops[1].init(addr, this);
610 StoreInst::StoreInst(Value *val, Value *addr, BasicBlock *InsertAtEnd)
611 : Instruction(Type::VoidTy, Store, Ops, 2, "", InsertAtEnd) {
612 Ops[0].init(val, this);
613 Ops[1].init(addr, this);
618 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
619 Instruction *InsertBefore)
620 : Instruction(Type::VoidTy, Store, Ops, 2, "", InsertBefore) {
621 Ops[0].init(val, this);
622 Ops[1].init(addr, this);
623 setVolatile(isVolatile);
627 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
628 BasicBlock *InsertAtEnd)
629 : Instruction(Type::VoidTy, Store, Ops, 2, "", InsertAtEnd) {
630 Ops[0].init(val, this);
631 Ops[1].init(addr, this);
632 setVolatile(isVolatile);
636 //===----------------------------------------------------------------------===//
637 // GetElementPtrInst Implementation
638 //===----------------------------------------------------------------------===//
640 // checkType - Simple wrapper function to give a better assertion failure
641 // message on bad indexes for a gep instruction.
643 static inline const Type *checkType(const Type *Ty) {
644 assert(Ty && "Invalid indices for type!");
648 void GetElementPtrInst::init(Value *Ptr, const std::vector<Value*> &Idx) {
649 NumOperands = 1+Idx.size();
650 Use *OL = OperandList = new Use[NumOperands];
651 OL[0].init(Ptr, this);
653 for (unsigned i = 0, e = Idx.size(); i != e; ++i)
654 OL[i+1].init(Idx[i], this);
657 void GetElementPtrInst::init(Value *Ptr, Value *Idx0, Value *Idx1) {
659 Use *OL = OperandList = new Use[3];
660 OL[0].init(Ptr, this);
661 OL[1].init(Idx0, this);
662 OL[2].init(Idx1, this);
665 void GetElementPtrInst::init(Value *Ptr, Value *Idx) {
667 Use *OL = OperandList = new Use[2];
668 OL[0].init(Ptr, this);
669 OL[1].init(Idx, this);
672 GetElementPtrInst::GetElementPtrInst(Value *Ptr, const std::vector<Value*> &Idx,
673 const std::string &Name, Instruction *InBe)
674 : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),
676 GetElementPtr, 0, 0, Name, InBe) {
680 GetElementPtrInst::GetElementPtrInst(Value *Ptr, const std::vector<Value*> &Idx,
681 const std::string &Name, BasicBlock *IAE)
682 : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),
684 GetElementPtr, 0, 0, Name, IAE) {
688 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx,
689 const std::string &Name, Instruction *InBe)
690 : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),Idx))),
691 GetElementPtr, 0, 0, Name, InBe) {
695 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx,
696 const std::string &Name, BasicBlock *IAE)
697 : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),Idx))),
698 GetElementPtr, 0, 0, Name, IAE) {
702 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx0, Value *Idx1,
703 const std::string &Name, Instruction *InBe)
704 : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),
706 GetElementPtr, 0, 0, Name, InBe) {
707 init(Ptr, Idx0, Idx1);
710 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx0, Value *Idx1,
711 const std::string &Name, BasicBlock *IAE)
712 : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),
714 GetElementPtr, 0, 0, Name, IAE) {
715 init(Ptr, Idx0, Idx1);
718 GetElementPtrInst::~GetElementPtrInst() {
719 delete[] OperandList;
722 // getIndexedType - Returns the type of the element that would be loaded with
723 // a load instruction with the specified parameters.
725 // A null type is returned if the indices are invalid for the specified
728 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr,
729 const std::vector<Value*> &Idx,
730 bool AllowCompositeLeaf) {
731 if (!isa<PointerType>(Ptr)) return 0; // Type isn't a pointer type!
733 // Handle the special case of the empty set index set...
735 if (AllowCompositeLeaf ||
736 cast<PointerType>(Ptr)->getElementType()->isFirstClassType())
737 return cast<PointerType>(Ptr)->getElementType();
742 while (const CompositeType *CT = dyn_cast<CompositeType>(Ptr)) {
743 if (Idx.size() == CurIdx) {
744 if (AllowCompositeLeaf || CT->isFirstClassType()) return Ptr;
745 return 0; // Can't load a whole structure or array!?!?
748 Value *Index = Idx[CurIdx++];
749 if (isa<PointerType>(CT) && CurIdx != 1)
750 return 0; // Can only index into pointer types at the first index!
751 if (!CT->indexValid(Index)) return 0;
752 Ptr = CT->getTypeAtIndex(Index);
754 // If the new type forwards to another type, then it is in the middle
755 // of being refined to another type (and hence, may have dropped all
756 // references to what it was using before). So, use the new forwarded
758 if (const Type * Ty = Ptr->getForwardedType()) {
762 return CurIdx == Idx.size() ? Ptr : 0;
765 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr,
766 Value *Idx0, Value *Idx1,
767 bool AllowCompositeLeaf) {
768 const PointerType *PTy = dyn_cast<PointerType>(Ptr);
769 if (!PTy) return 0; // Type isn't a pointer type!
771 // Check the pointer index.
772 if (!PTy->indexValid(Idx0)) return 0;
774 const CompositeType *CT = dyn_cast<CompositeType>(PTy->getElementType());
775 if (!CT || !CT->indexValid(Idx1)) return 0;
777 const Type *ElTy = CT->getTypeAtIndex(Idx1);
778 if (AllowCompositeLeaf || ElTy->isFirstClassType())
783 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr, Value *Idx) {
784 const PointerType *PTy = dyn_cast<PointerType>(Ptr);
785 if (!PTy) return 0; // Type isn't a pointer type!
787 // Check the pointer index.
788 if (!PTy->indexValid(Idx)) return 0;
790 return PTy->getElementType();
793 //===----------------------------------------------------------------------===//
794 // BinaryOperator Class
795 //===----------------------------------------------------------------------===//
797 void BinaryOperator::init(BinaryOps iType)
799 Value *LHS = getOperand(0), *RHS = getOperand(1);
800 assert(LHS->getType() == RHS->getType() &&
801 "Binary operator operand types must match!");
807 assert(getType() == LHS->getType() &&
808 "Arithmetic operation should return same type as operands!");
809 assert((getType()->isInteger() ||
810 getType()->isFloatingPoint() ||
811 isa<PackedType>(getType()) ) &&
812 "Tried to create an arithmetic operation on a non-arithmetic type!");
816 assert(getType() == LHS->getType() &&
817 "Logical operation should return same type as operands!");
818 assert(getType()->isIntegral() &&
819 "Tried to create a logical operation on a non-integral type!");
821 case SetLT: case SetGT: case SetLE:
822 case SetGE: case SetEQ: case SetNE:
823 assert(getType() == Type::BoolTy && "Setcc must return bool!");
830 BinaryOperator *BinaryOperator::create(BinaryOps Op, Value *S1, Value *S2,
831 const std::string &Name,
832 Instruction *InsertBefore) {
833 assert(S1->getType() == S2->getType() &&
834 "Cannot create binary operator with two operands of differing type!");
836 // Binary comparison operators...
837 case SetLT: case SetGT: case SetLE:
838 case SetGE: case SetEQ: case SetNE:
839 return new SetCondInst(Op, S1, S2, Name, InsertBefore);
842 return new BinaryOperator(Op, S1, S2, S1->getType(), Name, InsertBefore);
846 BinaryOperator *BinaryOperator::create(BinaryOps Op, Value *S1, Value *S2,
847 const std::string &Name,
848 BasicBlock *InsertAtEnd) {
849 BinaryOperator *Res = create(Op, S1, S2, Name);
850 InsertAtEnd->getInstList().push_back(Res);
854 BinaryOperator *BinaryOperator::createNeg(Value *Op, const std::string &Name,
855 Instruction *InsertBefore) {
856 if (!Op->getType()->isFloatingPoint())
857 return new BinaryOperator(Instruction::Sub,
858 Constant::getNullValue(Op->getType()), Op,
859 Op->getType(), Name, InsertBefore);
861 return new BinaryOperator(Instruction::Sub,
862 ConstantFP::get(Op->getType(), -0.0), Op,
863 Op->getType(), Name, InsertBefore);
866 BinaryOperator *BinaryOperator::createNeg(Value *Op, const std::string &Name,
867 BasicBlock *InsertAtEnd) {
868 if (!Op->getType()->isFloatingPoint())
869 return new BinaryOperator(Instruction::Sub,
870 Constant::getNullValue(Op->getType()), Op,
871 Op->getType(), Name, InsertAtEnd);
873 return new BinaryOperator(Instruction::Sub,
874 ConstantFP::get(Op->getType(), -0.0), Op,
875 Op->getType(), Name, InsertAtEnd);
878 BinaryOperator *BinaryOperator::createNot(Value *Op, const std::string &Name,
879 Instruction *InsertBefore) {
880 return new BinaryOperator(Instruction::Xor, Op,
881 ConstantIntegral::getAllOnesValue(Op->getType()),
882 Op->getType(), Name, InsertBefore);
885 BinaryOperator *BinaryOperator::createNot(Value *Op, const std::string &Name,
886 BasicBlock *InsertAtEnd) {
887 return new BinaryOperator(Instruction::Xor, Op,
888 ConstantIntegral::getAllOnesValue(Op->getType()),
889 Op->getType(), Name, InsertAtEnd);
893 // isConstantAllOnes - Helper function for several functions below
894 static inline bool isConstantAllOnes(const Value *V) {
895 return isa<ConstantIntegral>(V) &&cast<ConstantIntegral>(V)->isAllOnesValue();
898 bool BinaryOperator::isNeg(const Value *V) {
899 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
900 if (Bop->getOpcode() == Instruction::Sub)
901 if (!V->getType()->isFloatingPoint())
902 return Bop->getOperand(0) == Constant::getNullValue(Bop->getType());
904 return Bop->getOperand(0) == ConstantFP::get(Bop->getType(), -0.0);
908 bool BinaryOperator::isNot(const Value *V) {
909 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
910 return (Bop->getOpcode() == Instruction::Xor &&
911 (isConstantAllOnes(Bop->getOperand(1)) ||
912 isConstantAllOnes(Bop->getOperand(0))));
916 Value *BinaryOperator::getNegArgument(Value *BinOp) {
917 assert(isNeg(BinOp) && "getNegArgument from non-'neg' instruction!");
918 return cast<BinaryOperator>(BinOp)->getOperand(1);
921 const Value *BinaryOperator::getNegArgument(const Value *BinOp) {
922 return getNegArgument(const_cast<Value*>(BinOp));
925 Value *BinaryOperator::getNotArgument(Value *BinOp) {
926 assert(isNot(BinOp) && "getNotArgument on non-'not' instruction!");
927 BinaryOperator *BO = cast<BinaryOperator>(BinOp);
928 Value *Op0 = BO->getOperand(0);
929 Value *Op1 = BO->getOperand(1);
930 if (isConstantAllOnes(Op0)) return Op1;
932 assert(isConstantAllOnes(Op1));
936 const Value *BinaryOperator::getNotArgument(const Value *BinOp) {
937 return getNotArgument(const_cast<Value*>(BinOp));
941 // swapOperands - Exchange the two operands to this instruction. This
942 // instruction is safe to use on any binary instruction and does not
943 // modify the semantics of the instruction. If the instruction is
944 // order dependent (SetLT f.e.) the opcode is changed.
946 bool BinaryOperator::swapOperands() {
948 ; // If the instruction is commutative, it is safe to swap the operands
949 else if (SetCondInst *SCI = dyn_cast<SetCondInst>(this))
950 /// FIXME: SetCC instructions shouldn't all have different opcodes.
951 setOpcode(SCI->getSwappedCondition());
953 return true; // Can't commute operands
955 std::swap(Ops[0], Ops[1]);
960 //===----------------------------------------------------------------------===//
962 //===----------------------------------------------------------------------===//
964 SetCondInst::SetCondInst(BinaryOps Opcode, Value *S1, Value *S2,
965 const std::string &Name, Instruction *InsertBefore)
966 : BinaryOperator(Opcode, S1, S2, Type::BoolTy, Name, InsertBefore) {
968 // Make sure it's a valid type... getInverseCondition will assert out if not.
969 assert(getInverseCondition(Opcode));
972 SetCondInst::SetCondInst(BinaryOps Opcode, Value *S1, Value *S2,
973 const std::string &Name, BasicBlock *InsertAtEnd)
974 : BinaryOperator(Opcode, S1, S2, Type::BoolTy, Name, InsertAtEnd) {
976 // Make sure it's a valid type... getInverseCondition will assert out if not.
977 assert(getInverseCondition(Opcode));
980 // getInverseCondition - Return the inverse of the current condition opcode.
981 // For example seteq -> setne, setgt -> setle, setlt -> setge, etc...
983 Instruction::BinaryOps SetCondInst::getInverseCondition(BinaryOps Opcode) {
986 assert(0 && "Unknown setcc opcode!");
987 case SetEQ: return SetNE;
988 case SetNE: return SetEQ;
989 case SetGT: return SetLE;
990 case SetLT: return SetGE;
991 case SetGE: return SetLT;
992 case SetLE: return SetGT;
996 // getSwappedCondition - Return the condition opcode that would be the result
997 // of exchanging the two operands of the setcc instruction without changing
998 // the result produced. Thus, seteq->seteq, setle->setge, setlt->setgt, etc.
1000 Instruction::BinaryOps SetCondInst::getSwappedCondition(BinaryOps Opcode) {
1002 default: assert(0 && "Unknown setcc instruction!");
1003 case SetEQ: case SetNE: return Opcode;
1004 case SetGT: return SetLT;
1005 case SetLT: return SetGT;
1006 case SetGE: return SetLE;
1007 case SetLE: return SetGE;
1011 //===----------------------------------------------------------------------===//
1012 // SwitchInst Implementation
1013 //===----------------------------------------------------------------------===//
1015 void SwitchInst::init(Value *Value, BasicBlock *Default, unsigned NumCases) {
1016 assert(Value && Default);
1017 ReservedSpace = 2+NumCases*2;
1019 OperandList = new Use[ReservedSpace];
1021 OperandList[0].init(Value, this);
1022 OperandList[1].init(Default, this);
1025 SwitchInst::SwitchInst(const SwitchInst &SI)
1026 : TerminatorInst(Instruction::Switch, new Use[SI.getNumOperands()],
1027 SI.getNumOperands()) {
1028 Use *OL = OperandList, *InOL = SI.OperandList;
1029 for (unsigned i = 0, E = SI.getNumOperands(); i != E; i+=2) {
1030 OL[i].init(InOL[i], this);
1031 OL[i+1].init(InOL[i+1], this);
1035 SwitchInst::~SwitchInst() {
1036 delete [] OperandList;
1040 /// addCase - Add an entry to the switch instruction...
1042 void SwitchInst::addCase(ConstantInt *OnVal, BasicBlock *Dest) {
1043 unsigned OpNo = NumOperands;
1044 if (OpNo+2 > ReservedSpace)
1045 resizeOperands(0); // Get more space!
1046 // Initialize some new operands.
1047 assert(OpNo+1 < ReservedSpace && "Growing didn't work!");
1048 NumOperands = OpNo+2;
1049 OperandList[OpNo].init(OnVal, this);
1050 OperandList[OpNo+1].init(Dest, this);
1053 /// removeCase - This method removes the specified successor from the switch
1054 /// instruction. Note that this cannot be used to remove the default
1055 /// destination (successor #0).
1057 void SwitchInst::removeCase(unsigned idx) {
1058 assert(idx != 0 && "Cannot remove the default case!");
1059 assert(idx*2 < getNumOperands() && "Successor index out of range!!!");
1061 unsigned NumOps = getNumOperands();
1062 Use *OL = OperandList;
1064 // Move everything after this operand down.
1066 // FIXME: we could just swap with the end of the list, then erase. However,
1067 // client might not expect this to happen. The code as it is thrashes the
1068 // use/def lists, which is kinda lame.
1069 for (unsigned i = (idx+1)*2; i != NumOps; i += 2) {
1071 OL[i-2+1] = OL[i+1];
1074 // Nuke the last value.
1075 OL[NumOps-2].set(0);
1076 OL[NumOps-2+1].set(0);
1077 NumOperands = NumOps-2;
1080 /// resizeOperands - resize operands - This adjusts the length of the operands
1081 /// list according to the following behavior:
1082 /// 1. If NumOps == 0, grow the operand list in response to a push_back style
1083 /// of operation. This grows the number of ops by 1.5 times.
1084 /// 2. If NumOps > NumOperands, reserve space for NumOps operands.
1085 /// 3. If NumOps == NumOperands, trim the reserved space.
1087 void SwitchInst::resizeOperands(unsigned NumOps) {
1089 NumOps = getNumOperands()/2*6;
1090 } else if (NumOps*2 > NumOperands) {
1091 // No resize needed.
1092 if (ReservedSpace >= NumOps) return;
1093 } else if (NumOps == NumOperands) {
1094 if (ReservedSpace == NumOps) return;
1099 ReservedSpace = NumOps;
1100 Use *NewOps = new Use[NumOps];
1101 Use *OldOps = OperandList;
1102 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1103 NewOps[i].init(OldOps[i], this);
1107 OperandList = NewOps;
1111 BasicBlock *SwitchInst::getSuccessorV(unsigned idx) const {
1112 return getSuccessor(idx);
1114 unsigned SwitchInst::getNumSuccessorsV() const {
1115 return getNumSuccessors();
1117 void SwitchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
1118 setSuccessor(idx, B);
1122 // Define these methods here so vtables don't get emitted into every translation
1123 // unit that uses these classes.
1125 GetElementPtrInst *GetElementPtrInst::clone() const {
1126 return new GetElementPtrInst(*this);
1129 BinaryOperator *BinaryOperator::clone() const {
1130 return create(getOpcode(), Ops[0], Ops[1]);
1133 MallocInst *MallocInst::clone() const { return new MallocInst(*this); }
1134 AllocaInst *AllocaInst::clone() const { return new AllocaInst(*this); }
1135 FreeInst *FreeInst::clone() const { return new FreeInst(getOperand(0)); }
1136 LoadInst *LoadInst::clone() const { return new LoadInst(*this); }
1137 StoreInst *StoreInst::clone() const { return new StoreInst(*this); }
1138 CastInst *CastInst::clone() const { return new CastInst(*this); }
1139 CallInst *CallInst::clone() const { return new CallInst(*this); }
1140 ShiftInst *ShiftInst::clone() const { return new ShiftInst(*this); }
1141 SelectInst *SelectInst::clone() const { return new SelectInst(*this); }
1142 VAArgInst *VAArgInst::clone() const { return new VAArgInst(*this); }
1143 PHINode *PHINode::clone() const { return new PHINode(*this); }
1144 ReturnInst *ReturnInst::clone() const { return new ReturnInst(*this); }
1145 BranchInst *BranchInst::clone() const { return new BranchInst(*this); }
1146 SwitchInst *SwitchInst::clone() const { return new SwitchInst(*this); }
1147 InvokeInst *InvokeInst::clone() const { return new InvokeInst(*this); }
1148 UnwindInst *UnwindInst::clone() const { return new UnwindInst(); }
1149 UnreachableInst *UnreachableInst::clone() const { return new UnreachableInst();}