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 if (getIncomingValue(0) != this) // not X = phi X
142 return getIncomingValue(0);
144 return UndefValue::get(getType()); // Self cycle is dead.
146 // Otherwise if all of the incoming values are the same for the PHI, replace
147 // the PHI node with the incoming value.
150 bool HasUndefInput = false;
151 for (unsigned i = 0, e = getNumIncomingValues(); i != e; ++i)
152 if (isa<UndefValue>(getIncomingValue(i)))
153 HasUndefInput = true;
154 else if (getIncomingValue(i) != this) // Not the PHI node itself...
155 if (InVal && getIncomingValue(i) != InVal)
156 return 0; // Not the same, bail out.
158 InVal = getIncomingValue(i);
160 // The only case that could cause InVal to be null is if we have a PHI node
161 // that only has entries for itself. In this case, there is no entry into the
162 // loop, so kill the PHI.
164 if (InVal == 0) InVal = UndefValue::get(getType());
166 // If we have a PHI node like phi(X, undef, X), where X is defined by some
167 // instruction, we cannot always return X as the result of the PHI node. Only
168 // do this if X is not an instruction (thus it must dominate the PHI block),
169 // or if the client is prepared to deal with this possibility.
170 if (HasUndefInput && !AllowNonDominatingInstruction)
171 if (Instruction *IV = dyn_cast<Instruction>(InVal))
172 // If it's in the entry block, it dominates everything.
173 if (IV->getParent() != &IV->getParent()->getParent()->front() ||
175 return 0; // Cannot guarantee that InVal dominates this PHINode.
177 // All of the incoming values are the same, return the value now.
182 //===----------------------------------------------------------------------===//
183 // CallInst Implementation
184 //===----------------------------------------------------------------------===//
186 CallInst::~CallInst() {
187 delete [] OperandList;
190 void CallInst::init(Value *Func, const std::vector<Value*> &Params) {
191 NumOperands = Params.size()+1;
192 Use *OL = OperandList = new Use[Params.size()+1];
193 OL[0].init(Func, this);
195 const FunctionType *FTy =
196 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
198 assert((Params.size() == FTy->getNumParams() ||
199 (FTy->isVarArg() && Params.size() > FTy->getNumParams())) &&
200 "Calling a function with bad signature");
201 for (unsigned i = 0, e = Params.size(); i != e; ++i)
202 OL[i+1].init(Params[i], this);
205 void CallInst::init(Value *Func, Value *Actual1, Value *Actual2) {
207 Use *OL = OperandList = new Use[3];
208 OL[0].init(Func, this);
209 OL[1].init(Actual1, this);
210 OL[2].init(Actual2, this);
212 const FunctionType *FTy =
213 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
215 assert((FTy->getNumParams() == 2 ||
216 (FTy->isVarArg() && FTy->getNumParams() == 0)) &&
217 "Calling a function with bad signature");
220 void CallInst::init(Value *Func, Value *Actual) {
222 Use *OL = OperandList = new Use[2];
223 OL[0].init(Func, this);
224 OL[1].init(Actual, this);
226 const FunctionType *FTy =
227 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
229 assert((FTy->getNumParams() == 1 ||
230 (FTy->isVarArg() && FTy->getNumParams() == 0)) &&
231 "Calling a function with bad signature");
234 void CallInst::init(Value *Func) {
236 Use *OL = OperandList = new Use[1];
237 OL[0].init(Func, this);
239 const FunctionType *MTy =
240 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
242 assert(MTy->getNumParams() == 0 && "Calling a function with bad signature");
245 CallInst::CallInst(Value *Func, const std::vector<Value*> &Params,
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) {
253 CallInst::CallInst(Value *Func, const std::vector<Value*> &Params,
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) {
261 CallInst::CallInst(Value *Func, Value *Actual1, Value *Actual2,
262 const std::string &Name, Instruction *InsertBefore)
263 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
264 ->getElementType())->getReturnType(),
265 Instruction::Call, 0, 0, Name, InsertBefore) {
266 init(Func, Actual1, Actual2);
269 CallInst::CallInst(Value *Func, Value *Actual1, Value *Actual2,
270 const std::string &Name, BasicBlock *InsertAtEnd)
271 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
272 ->getElementType())->getReturnType(),
273 Instruction::Call, 0, 0, Name, InsertAtEnd) {
274 init(Func, Actual1, Actual2);
277 CallInst::CallInst(Value *Func, Value* Actual, 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, Value* Actual, 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(Value *Func, const std::string &Name,
294 Instruction *InsertBefore)
295 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
296 ->getElementType())->getReturnType(),
297 Instruction::Call, 0, 0, Name, InsertBefore) {
301 CallInst::CallInst(Value *Func, const std::string &Name,
302 BasicBlock *InsertAtEnd)
303 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
304 ->getElementType())->getReturnType(),
305 Instruction::Call, 0, 0, Name, InsertAtEnd) {
309 CallInst::CallInst(const CallInst &CI)
310 : Instruction(CI.getType(), Instruction::Call, new Use[CI.getNumOperands()],
311 CI.getNumOperands()) {
312 SubclassData = CI.SubclassData;
313 Use *OL = OperandList;
314 Use *InOL = CI.OperandList;
315 for (unsigned i = 0, e = CI.getNumOperands(); i != e; ++i)
316 OL[i].init(InOL[i], this);
320 //===----------------------------------------------------------------------===//
321 // InvokeInst Implementation
322 //===----------------------------------------------------------------------===//
324 InvokeInst::~InvokeInst() {
325 delete [] OperandList;
328 void InvokeInst::init(Value *Fn, BasicBlock *IfNormal, BasicBlock *IfException,
329 const std::vector<Value*> &Params) {
330 NumOperands = 3+Params.size();
331 Use *OL = OperandList = new Use[3+Params.size()];
332 OL[0].init(Fn, this);
333 OL[1].init(IfNormal, this);
334 OL[2].init(IfException, this);
335 const FunctionType *FTy =
336 cast<FunctionType>(cast<PointerType>(Fn->getType())->getElementType());
338 assert((Params.size() == FTy->getNumParams()) ||
339 (FTy->isVarArg() && Params.size() > FTy->getNumParams()) &&
340 "Calling a function with bad signature");
342 for (unsigned i = 0, e = Params.size(); i != e; i++)
343 OL[i+3].init(Params[i], this);
346 InvokeInst::InvokeInst(Value *Fn, BasicBlock *IfNormal,
347 BasicBlock *IfException,
348 const std::vector<Value*> &Params,
349 const std::string &Name, Instruction *InsertBefore)
350 : TerminatorInst(cast<FunctionType>(cast<PointerType>(Fn->getType())
351 ->getElementType())->getReturnType(),
352 Instruction::Invoke, 0, 0, Name, InsertBefore) {
353 init(Fn, IfNormal, IfException, Params);
356 InvokeInst::InvokeInst(Value *Fn, BasicBlock *IfNormal,
357 BasicBlock *IfException,
358 const std::vector<Value*> &Params,
359 const std::string &Name, BasicBlock *InsertAtEnd)
360 : TerminatorInst(cast<FunctionType>(cast<PointerType>(Fn->getType())
361 ->getElementType())->getReturnType(),
362 Instruction::Invoke, 0, 0, Name, InsertAtEnd) {
363 init(Fn, IfNormal, IfException, Params);
366 InvokeInst::InvokeInst(const InvokeInst &II)
367 : TerminatorInst(II.getType(), Instruction::Invoke,
368 new Use[II.getNumOperands()], II.getNumOperands()) {
369 SubclassData = II.SubclassData;
370 Use *OL = OperandList, *InOL = II.OperandList;
371 for (unsigned i = 0, e = II.getNumOperands(); i != e; ++i)
372 OL[i].init(InOL[i], this);
375 BasicBlock *InvokeInst::getSuccessorV(unsigned idx) const {
376 return getSuccessor(idx);
378 unsigned InvokeInst::getNumSuccessorsV() const {
379 return getNumSuccessors();
381 void InvokeInst::setSuccessorV(unsigned idx, BasicBlock *B) {
382 return setSuccessor(idx, B);
386 //===----------------------------------------------------------------------===//
387 // ReturnInst Implementation
388 //===----------------------------------------------------------------------===//
390 void ReturnInst::init(Value *retVal) {
391 if (retVal && retVal->getType() != Type::VoidTy) {
392 assert(!isa<BasicBlock>(retVal) &&
393 "Cannot return basic block. Probably using the incorrect ctor");
395 RetVal.init(retVal, this);
399 unsigned ReturnInst::getNumSuccessorsV() const {
400 return getNumSuccessors();
403 // Out-of-line ReturnInst method, put here so the C++ compiler can choose to
404 // emit the vtable for the class in this translation unit.
405 void ReturnInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
406 assert(0 && "ReturnInst has no successors!");
409 BasicBlock *ReturnInst::getSuccessorV(unsigned idx) const {
410 assert(0 && "ReturnInst has no successors!");
416 //===----------------------------------------------------------------------===//
417 // UnwindInst Implementation
418 //===----------------------------------------------------------------------===//
420 unsigned UnwindInst::getNumSuccessorsV() const {
421 return getNumSuccessors();
424 void UnwindInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
425 assert(0 && "UnwindInst has no successors!");
428 BasicBlock *UnwindInst::getSuccessorV(unsigned idx) const {
429 assert(0 && "UnwindInst has no successors!");
434 //===----------------------------------------------------------------------===//
435 // UnreachableInst Implementation
436 //===----------------------------------------------------------------------===//
438 unsigned UnreachableInst::getNumSuccessorsV() const {
439 return getNumSuccessors();
442 void UnreachableInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
443 assert(0 && "UnwindInst has no successors!");
446 BasicBlock *UnreachableInst::getSuccessorV(unsigned idx) const {
447 assert(0 && "UnwindInst has no successors!");
452 //===----------------------------------------------------------------------===//
453 // BranchInst Implementation
454 //===----------------------------------------------------------------------===//
456 void BranchInst::AssertOK() {
458 assert(getCondition()->getType() == Type::BoolTy &&
459 "May only branch on boolean predicates!");
462 BranchInst::BranchInst(const BranchInst &BI) :
463 TerminatorInst(Instruction::Br, Ops, BI.getNumOperands()) {
464 OperandList[0].init(BI.getOperand(0), this);
465 if (BI.getNumOperands() != 1) {
466 assert(BI.getNumOperands() == 3 && "BR can have 1 or 3 operands!");
467 OperandList[1].init(BI.getOperand(1), this);
468 OperandList[2].init(BI.getOperand(2), this);
472 BasicBlock *BranchInst::getSuccessorV(unsigned idx) const {
473 return getSuccessor(idx);
475 unsigned BranchInst::getNumSuccessorsV() const {
476 return getNumSuccessors();
478 void BranchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
479 setSuccessor(idx, B);
483 //===----------------------------------------------------------------------===//
484 // AllocationInst Implementation
485 //===----------------------------------------------------------------------===//
487 static Value *getAISize(Value *Amt) {
489 Amt = ConstantUInt::get(Type::UIntTy, 1);
491 assert(Amt->getType() == Type::UIntTy &&
492 "Malloc/Allocation array size != UIntTy!");
496 AllocationInst::AllocationInst(const Type *Ty, Value *ArraySize, unsigned iTy,
497 unsigned Align, const std::string &Name,
498 Instruction *InsertBefore)
499 : UnaryInstruction(PointerType::get(Ty), iTy, getAISize(ArraySize),
500 Name, InsertBefore), Alignment(Align) {
501 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
502 assert(Ty != Type::VoidTy && "Cannot allocate void!");
505 AllocationInst::AllocationInst(const Type *Ty, Value *ArraySize, unsigned iTy,
506 unsigned Align, const std::string &Name,
507 BasicBlock *InsertAtEnd)
508 : UnaryInstruction(PointerType::get(Ty), iTy, getAISize(ArraySize),
509 Name, InsertAtEnd), Alignment(Align) {
510 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
511 assert(Ty != Type::VoidTy && "Cannot allocate void!");
514 bool AllocationInst::isArrayAllocation() const {
515 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(getOperand(0)))
516 return CUI->getValue() != 1;
520 const Type *AllocationInst::getAllocatedType() const {
521 return getType()->getElementType();
524 AllocaInst::AllocaInst(const AllocaInst &AI)
525 : AllocationInst(AI.getType()->getElementType(), (Value*)AI.getOperand(0),
526 Instruction::Alloca, AI.getAlignment()) {
529 MallocInst::MallocInst(const MallocInst &MI)
530 : AllocationInst(MI.getType()->getElementType(), (Value*)MI.getOperand(0),
531 Instruction::Malloc, MI.getAlignment()) {
534 //===----------------------------------------------------------------------===//
535 // FreeInst Implementation
536 //===----------------------------------------------------------------------===//
538 void FreeInst::AssertOK() {
539 assert(isa<PointerType>(getOperand(0)->getType()) &&
540 "Can not free something of nonpointer type!");
543 FreeInst::FreeInst(Value *Ptr, Instruction *InsertBefore)
544 : UnaryInstruction(Type::VoidTy, Free, Ptr, "", InsertBefore) {
548 FreeInst::FreeInst(Value *Ptr, BasicBlock *InsertAtEnd)
549 : UnaryInstruction(Type::VoidTy, Free, Ptr, "", InsertAtEnd) {
554 //===----------------------------------------------------------------------===//
555 // LoadInst Implementation
556 //===----------------------------------------------------------------------===//
558 void LoadInst::AssertOK() {
559 assert(isa<PointerType>(getOperand(0)->getType()) &&
560 "Ptr must have pointer type.");
563 LoadInst::LoadInst(Value *Ptr, const std::string &Name, Instruction *InsertBef)
564 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
565 Load, Ptr, Name, InsertBef) {
570 LoadInst::LoadInst(Value *Ptr, const std::string &Name, BasicBlock *InsertAE)
571 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
572 Load, Ptr, Name, InsertAE) {
577 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile,
578 Instruction *InsertBef)
579 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
580 Load, Ptr, Name, InsertBef) {
581 setVolatile(isVolatile);
585 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile,
586 BasicBlock *InsertAE)
587 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
588 Load, Ptr, Name, InsertAE) {
589 setVolatile(isVolatile);
594 //===----------------------------------------------------------------------===//
595 // StoreInst Implementation
596 //===----------------------------------------------------------------------===//
598 void StoreInst::AssertOK() {
599 assert(isa<PointerType>(getOperand(1)->getType()) &&
600 "Ptr must have pointer type!");
601 assert(getOperand(0)->getType() ==
602 cast<PointerType>(getOperand(1)->getType())->getElementType()
603 && "Ptr must be a pointer to Val type!");
607 StoreInst::StoreInst(Value *val, Value *addr, Instruction *InsertBefore)
608 : Instruction(Type::VoidTy, Store, Ops, 2, "", InsertBefore) {
609 Ops[0].init(val, this);
610 Ops[1].init(addr, this);
615 StoreInst::StoreInst(Value *val, Value *addr, BasicBlock *InsertAtEnd)
616 : Instruction(Type::VoidTy, Store, Ops, 2, "", InsertAtEnd) {
617 Ops[0].init(val, this);
618 Ops[1].init(addr, this);
623 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
624 Instruction *InsertBefore)
625 : Instruction(Type::VoidTy, Store, Ops, 2, "", InsertBefore) {
626 Ops[0].init(val, this);
627 Ops[1].init(addr, this);
628 setVolatile(isVolatile);
632 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
633 BasicBlock *InsertAtEnd)
634 : Instruction(Type::VoidTy, Store, Ops, 2, "", InsertAtEnd) {
635 Ops[0].init(val, this);
636 Ops[1].init(addr, this);
637 setVolatile(isVolatile);
641 //===----------------------------------------------------------------------===//
642 // GetElementPtrInst Implementation
643 //===----------------------------------------------------------------------===//
645 // checkType - Simple wrapper function to give a better assertion failure
646 // message on bad indexes for a gep instruction.
648 static inline const Type *checkType(const Type *Ty) {
649 assert(Ty && "Invalid indices for type!");
653 void GetElementPtrInst::init(Value *Ptr, const std::vector<Value*> &Idx) {
654 NumOperands = 1+Idx.size();
655 Use *OL = OperandList = new Use[NumOperands];
656 OL[0].init(Ptr, this);
658 for (unsigned i = 0, e = Idx.size(); i != e; ++i)
659 OL[i+1].init(Idx[i], this);
662 void GetElementPtrInst::init(Value *Ptr, Value *Idx0, Value *Idx1) {
664 Use *OL = OperandList = new Use[3];
665 OL[0].init(Ptr, this);
666 OL[1].init(Idx0, this);
667 OL[2].init(Idx1, this);
670 void GetElementPtrInst::init(Value *Ptr, Value *Idx) {
672 Use *OL = OperandList = new Use[2];
673 OL[0].init(Ptr, this);
674 OL[1].init(Idx, this);
677 GetElementPtrInst::GetElementPtrInst(Value *Ptr, const std::vector<Value*> &Idx,
678 const std::string &Name, Instruction *InBe)
679 : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),
681 GetElementPtr, 0, 0, Name, InBe) {
685 GetElementPtrInst::GetElementPtrInst(Value *Ptr, const std::vector<Value*> &Idx,
686 const std::string &Name, BasicBlock *IAE)
687 : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),
689 GetElementPtr, 0, 0, Name, IAE) {
693 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx,
694 const std::string &Name, Instruction *InBe)
695 : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),Idx))),
696 GetElementPtr, 0, 0, Name, InBe) {
700 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx,
701 const std::string &Name, BasicBlock *IAE)
702 : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),Idx))),
703 GetElementPtr, 0, 0, Name, IAE) {
707 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx0, Value *Idx1,
708 const std::string &Name, Instruction *InBe)
709 : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),
711 GetElementPtr, 0, 0, Name, InBe) {
712 init(Ptr, Idx0, Idx1);
715 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx0, Value *Idx1,
716 const std::string &Name, BasicBlock *IAE)
717 : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),
719 GetElementPtr, 0, 0, Name, IAE) {
720 init(Ptr, Idx0, Idx1);
723 GetElementPtrInst::~GetElementPtrInst() {
724 delete[] OperandList;
727 // getIndexedType - Returns the type of the element that would be loaded with
728 // a load instruction with the specified parameters.
730 // A null type is returned if the indices are invalid for the specified
733 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr,
734 const std::vector<Value*> &Idx,
735 bool AllowCompositeLeaf) {
736 if (!isa<PointerType>(Ptr)) return 0; // Type isn't a pointer type!
738 // Handle the special case of the empty set index set...
740 if (AllowCompositeLeaf ||
741 cast<PointerType>(Ptr)->getElementType()->isFirstClassType())
742 return cast<PointerType>(Ptr)->getElementType();
747 while (const CompositeType *CT = dyn_cast<CompositeType>(Ptr)) {
748 if (Idx.size() == CurIdx) {
749 if (AllowCompositeLeaf || CT->isFirstClassType()) return Ptr;
750 return 0; // Can't load a whole structure or array!?!?
753 Value *Index = Idx[CurIdx++];
754 if (isa<PointerType>(CT) && CurIdx != 1)
755 return 0; // Can only index into pointer types at the first index!
756 if (!CT->indexValid(Index)) return 0;
757 Ptr = CT->getTypeAtIndex(Index);
759 // If the new type forwards to another type, then it is in the middle
760 // of being refined to another type (and hence, may have dropped all
761 // references to what it was using before). So, use the new forwarded
763 if (const Type * Ty = Ptr->getForwardedType()) {
767 return CurIdx == Idx.size() ? Ptr : 0;
770 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr,
771 Value *Idx0, Value *Idx1,
772 bool AllowCompositeLeaf) {
773 const PointerType *PTy = dyn_cast<PointerType>(Ptr);
774 if (!PTy) return 0; // Type isn't a pointer type!
776 // Check the pointer index.
777 if (!PTy->indexValid(Idx0)) return 0;
779 const CompositeType *CT = dyn_cast<CompositeType>(PTy->getElementType());
780 if (!CT || !CT->indexValid(Idx1)) return 0;
782 const Type *ElTy = CT->getTypeAtIndex(Idx1);
783 if (AllowCompositeLeaf || ElTy->isFirstClassType())
788 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr, Value *Idx) {
789 const PointerType *PTy = dyn_cast<PointerType>(Ptr);
790 if (!PTy) return 0; // Type isn't a pointer type!
792 // Check the pointer index.
793 if (!PTy->indexValid(Idx)) return 0;
795 return PTy->getElementType();
798 //===----------------------------------------------------------------------===//
799 // ExtractElementInst Implementation
800 //===----------------------------------------------------------------------===//
802 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
803 const std::string &Name, Instruction *InsertBef)
804 : Instruction(cast<PackedType>(Val->getType())->getElementType(),
805 ExtractElement, Ops, 2, Name, InsertBef) {
806 Ops[0].init(Val, this);
807 Ops[1].init(Index, this);
810 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
811 const std::string &Name, BasicBlock *InsertAE)
812 : Instruction(cast<PackedType>(Val->getType())->getElementType(),
813 ExtractElement, Ops, 2, Name, InsertAE) {
814 Ops[0].init(Val, this);
815 Ops[1].init(Index, this);
818 //===----------------------------------------------------------------------===//
819 // BinaryOperator Class
820 //===----------------------------------------------------------------------===//
822 void BinaryOperator::init(BinaryOps iType)
824 Value *LHS = getOperand(0), *RHS = getOperand(1);
825 assert(LHS->getType() == RHS->getType() &&
826 "Binary operator operand types must match!");
832 assert(getType() == LHS->getType() &&
833 "Arithmetic operation should return same type as operands!");
834 assert((getType()->isInteger() || getType()->isFloatingPoint() ||
835 isa<PackedType>(getType())) &&
836 "Tried to create an arithmetic operation on a non-arithmetic type!");
840 assert(getType() == LHS->getType() &&
841 "Logical operation should return same type as operands!");
842 assert((getType()->isIntegral() ||
843 (isa<PackedType>(getType()) &&
844 cast<PackedType>(getType())->getElementType()->isIntegral())) &&
845 "Tried to create a logical operation on a non-integral type!");
847 case SetLT: case SetGT: case SetLE:
848 case SetGE: case SetEQ: case SetNE:
849 assert(getType() == Type::BoolTy && "Setcc must return bool!");
856 BinaryOperator *BinaryOperator::create(BinaryOps Op, Value *S1, Value *S2,
857 const std::string &Name,
858 Instruction *InsertBefore) {
859 assert(S1->getType() == S2->getType() &&
860 "Cannot create binary operator with two operands of differing type!");
862 // Binary comparison operators...
863 case SetLT: case SetGT: case SetLE:
864 case SetGE: case SetEQ: case SetNE:
865 return new SetCondInst(Op, S1, S2, Name, InsertBefore);
868 return new BinaryOperator(Op, S1, S2, S1->getType(), Name, InsertBefore);
872 BinaryOperator *BinaryOperator::create(BinaryOps Op, Value *S1, Value *S2,
873 const std::string &Name,
874 BasicBlock *InsertAtEnd) {
875 BinaryOperator *Res = create(Op, S1, S2, Name);
876 InsertAtEnd->getInstList().push_back(Res);
880 BinaryOperator *BinaryOperator::createNeg(Value *Op, const std::string &Name,
881 Instruction *InsertBefore) {
882 if (!Op->getType()->isFloatingPoint())
883 return new BinaryOperator(Instruction::Sub,
884 Constant::getNullValue(Op->getType()), Op,
885 Op->getType(), Name, InsertBefore);
887 return new BinaryOperator(Instruction::Sub,
888 ConstantFP::get(Op->getType(), -0.0), Op,
889 Op->getType(), Name, InsertBefore);
892 BinaryOperator *BinaryOperator::createNeg(Value *Op, const std::string &Name,
893 BasicBlock *InsertAtEnd) {
894 if (!Op->getType()->isFloatingPoint())
895 return new BinaryOperator(Instruction::Sub,
896 Constant::getNullValue(Op->getType()), Op,
897 Op->getType(), Name, InsertAtEnd);
899 return new BinaryOperator(Instruction::Sub,
900 ConstantFP::get(Op->getType(), -0.0), Op,
901 Op->getType(), Name, InsertAtEnd);
904 BinaryOperator *BinaryOperator::createNot(Value *Op, const std::string &Name,
905 Instruction *InsertBefore) {
906 return new BinaryOperator(Instruction::Xor, Op,
907 ConstantIntegral::getAllOnesValue(Op->getType()),
908 Op->getType(), Name, InsertBefore);
911 BinaryOperator *BinaryOperator::createNot(Value *Op, const std::string &Name,
912 BasicBlock *InsertAtEnd) {
914 if (const PackedType *PTy = dyn_cast<PackedType>(Op->getType())) {
915 // Create a vector of all ones values.
916 Constant *Elt = ConstantIntegral::getAllOnesValue(PTy->getElementType());
918 ConstantPacked::get(std::vector<Constant*>(PTy->getNumElements(), Elt));
920 AllOnes = ConstantIntegral::getAllOnesValue(Op->getType());
923 return new BinaryOperator(Instruction::Xor, Op, AllOnes,
924 Op->getType(), Name, InsertAtEnd);
928 // isConstantAllOnes - Helper function for several functions below
929 static inline bool isConstantAllOnes(const Value *V) {
930 return isa<ConstantIntegral>(V) &&cast<ConstantIntegral>(V)->isAllOnesValue();
933 bool BinaryOperator::isNeg(const Value *V) {
934 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
935 if (Bop->getOpcode() == Instruction::Sub)
936 if (!V->getType()->isFloatingPoint())
937 return Bop->getOperand(0) == Constant::getNullValue(Bop->getType());
939 return Bop->getOperand(0) == ConstantFP::get(Bop->getType(), -0.0);
943 bool BinaryOperator::isNot(const Value *V) {
944 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
945 return (Bop->getOpcode() == Instruction::Xor &&
946 (isConstantAllOnes(Bop->getOperand(1)) ||
947 isConstantAllOnes(Bop->getOperand(0))));
951 Value *BinaryOperator::getNegArgument(Value *BinOp) {
952 assert(isNeg(BinOp) && "getNegArgument from non-'neg' instruction!");
953 return cast<BinaryOperator>(BinOp)->getOperand(1);
956 const Value *BinaryOperator::getNegArgument(const Value *BinOp) {
957 return getNegArgument(const_cast<Value*>(BinOp));
960 Value *BinaryOperator::getNotArgument(Value *BinOp) {
961 assert(isNot(BinOp) && "getNotArgument on non-'not' instruction!");
962 BinaryOperator *BO = cast<BinaryOperator>(BinOp);
963 Value *Op0 = BO->getOperand(0);
964 Value *Op1 = BO->getOperand(1);
965 if (isConstantAllOnes(Op0)) return Op1;
967 assert(isConstantAllOnes(Op1));
971 const Value *BinaryOperator::getNotArgument(const Value *BinOp) {
972 return getNotArgument(const_cast<Value*>(BinOp));
976 // swapOperands - Exchange the two operands to this instruction. This
977 // instruction is safe to use on any binary instruction and does not
978 // modify the semantics of the instruction. If the instruction is
979 // order dependent (SetLT f.e.) the opcode is changed.
981 bool BinaryOperator::swapOperands() {
983 ; // If the instruction is commutative, it is safe to swap the operands
984 else if (SetCondInst *SCI = dyn_cast<SetCondInst>(this))
985 /// FIXME: SetCC instructions shouldn't all have different opcodes.
986 setOpcode(SCI->getSwappedCondition());
988 return true; // Can't commute operands
990 std::swap(Ops[0], Ops[1]);
995 //===----------------------------------------------------------------------===//
997 //===----------------------------------------------------------------------===//
999 SetCondInst::SetCondInst(BinaryOps Opcode, Value *S1, Value *S2,
1000 const std::string &Name, Instruction *InsertBefore)
1001 : BinaryOperator(Opcode, S1, S2, Type::BoolTy, Name, InsertBefore) {
1003 // Make sure it's a valid type... getInverseCondition will assert out if not.
1004 assert(getInverseCondition(Opcode));
1007 SetCondInst::SetCondInst(BinaryOps Opcode, Value *S1, Value *S2,
1008 const std::string &Name, BasicBlock *InsertAtEnd)
1009 : BinaryOperator(Opcode, S1, S2, Type::BoolTy, Name, InsertAtEnd) {
1011 // Make sure it's a valid type... getInverseCondition will assert out if not.
1012 assert(getInverseCondition(Opcode));
1015 // getInverseCondition - Return the inverse of the current condition opcode.
1016 // For example seteq -> setne, setgt -> setle, setlt -> setge, etc...
1018 Instruction::BinaryOps SetCondInst::getInverseCondition(BinaryOps Opcode) {
1021 assert(0 && "Unknown setcc opcode!");
1022 case SetEQ: return SetNE;
1023 case SetNE: return SetEQ;
1024 case SetGT: return SetLE;
1025 case SetLT: return SetGE;
1026 case SetGE: return SetLT;
1027 case SetLE: return SetGT;
1031 // getSwappedCondition - Return the condition opcode that would be the result
1032 // of exchanging the two operands of the setcc instruction without changing
1033 // the result produced. Thus, seteq->seteq, setle->setge, setlt->setgt, etc.
1035 Instruction::BinaryOps SetCondInst::getSwappedCondition(BinaryOps Opcode) {
1037 default: assert(0 && "Unknown setcc instruction!");
1038 case SetEQ: case SetNE: return Opcode;
1039 case SetGT: return SetLT;
1040 case SetLT: return SetGT;
1041 case SetGE: return SetLE;
1042 case SetLE: return SetGE;
1046 //===----------------------------------------------------------------------===//
1047 // SwitchInst Implementation
1048 //===----------------------------------------------------------------------===//
1050 void SwitchInst::init(Value *Value, BasicBlock *Default, unsigned NumCases) {
1051 assert(Value && Default);
1052 ReservedSpace = 2+NumCases*2;
1054 OperandList = new Use[ReservedSpace];
1056 OperandList[0].init(Value, this);
1057 OperandList[1].init(Default, this);
1060 SwitchInst::SwitchInst(const SwitchInst &SI)
1061 : TerminatorInst(Instruction::Switch, new Use[SI.getNumOperands()],
1062 SI.getNumOperands()) {
1063 Use *OL = OperandList, *InOL = SI.OperandList;
1064 for (unsigned i = 0, E = SI.getNumOperands(); i != E; i+=2) {
1065 OL[i].init(InOL[i], this);
1066 OL[i+1].init(InOL[i+1], this);
1070 SwitchInst::~SwitchInst() {
1071 delete [] OperandList;
1075 /// addCase - Add an entry to the switch instruction...
1077 void SwitchInst::addCase(ConstantInt *OnVal, BasicBlock *Dest) {
1078 unsigned OpNo = NumOperands;
1079 if (OpNo+2 > ReservedSpace)
1080 resizeOperands(0); // Get more space!
1081 // Initialize some new operands.
1082 assert(OpNo+1 < ReservedSpace && "Growing didn't work!");
1083 NumOperands = OpNo+2;
1084 OperandList[OpNo].init(OnVal, this);
1085 OperandList[OpNo+1].init(Dest, this);
1088 /// removeCase - This method removes the specified successor from the switch
1089 /// instruction. Note that this cannot be used to remove the default
1090 /// destination (successor #0).
1092 void SwitchInst::removeCase(unsigned idx) {
1093 assert(idx != 0 && "Cannot remove the default case!");
1094 assert(idx*2 < getNumOperands() && "Successor index out of range!!!");
1096 unsigned NumOps = getNumOperands();
1097 Use *OL = OperandList;
1099 // Move everything after this operand down.
1101 // FIXME: we could just swap with the end of the list, then erase. However,
1102 // client might not expect this to happen. The code as it is thrashes the
1103 // use/def lists, which is kinda lame.
1104 for (unsigned i = (idx+1)*2; i != NumOps; i += 2) {
1106 OL[i-2+1] = OL[i+1];
1109 // Nuke the last value.
1110 OL[NumOps-2].set(0);
1111 OL[NumOps-2+1].set(0);
1112 NumOperands = NumOps-2;
1115 /// resizeOperands - resize operands - This adjusts the length of the operands
1116 /// list according to the following behavior:
1117 /// 1. If NumOps == 0, grow the operand list in response to a push_back style
1118 /// of operation. This grows the number of ops by 1.5 times.
1119 /// 2. If NumOps > NumOperands, reserve space for NumOps operands.
1120 /// 3. If NumOps == NumOperands, trim the reserved space.
1122 void SwitchInst::resizeOperands(unsigned NumOps) {
1124 NumOps = getNumOperands()/2*6;
1125 } else if (NumOps*2 > NumOperands) {
1126 // No resize needed.
1127 if (ReservedSpace >= NumOps) return;
1128 } else if (NumOps == NumOperands) {
1129 if (ReservedSpace == NumOps) return;
1134 ReservedSpace = NumOps;
1135 Use *NewOps = new Use[NumOps];
1136 Use *OldOps = OperandList;
1137 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
1138 NewOps[i].init(OldOps[i], this);
1142 OperandList = NewOps;
1146 BasicBlock *SwitchInst::getSuccessorV(unsigned idx) const {
1147 return getSuccessor(idx);
1149 unsigned SwitchInst::getNumSuccessorsV() const {
1150 return getNumSuccessors();
1152 void SwitchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
1153 setSuccessor(idx, B);
1157 // Define these methods here so vtables don't get emitted into every translation
1158 // unit that uses these classes.
1160 GetElementPtrInst *GetElementPtrInst::clone() const {
1161 return new GetElementPtrInst(*this);
1164 BinaryOperator *BinaryOperator::clone() const {
1165 return create(getOpcode(), Ops[0], Ops[1]);
1168 MallocInst *MallocInst::clone() const { return new MallocInst(*this); }
1169 AllocaInst *AllocaInst::clone() const { return new AllocaInst(*this); }
1170 FreeInst *FreeInst::clone() const { return new FreeInst(getOperand(0)); }
1171 LoadInst *LoadInst::clone() const { return new LoadInst(*this); }
1172 StoreInst *StoreInst::clone() const { return new StoreInst(*this); }
1173 CastInst *CastInst::clone() const { return new CastInst(*this); }
1174 CallInst *CallInst::clone() const { return new CallInst(*this); }
1175 ShiftInst *ShiftInst::clone() const { return new ShiftInst(*this); }
1176 SelectInst *SelectInst::clone() const { return new SelectInst(*this); }
1177 VAArgInst *VAArgInst::clone() const { return new VAArgInst(*this); }
1178 ExtractElementInst *ExtractElementInst::clone() const {return new ExtractElementInst(*this); }
1179 PHINode *PHINode::clone() const { return new PHINode(*this); }
1180 ReturnInst *ReturnInst::clone() const { return new ReturnInst(*this); }
1181 BranchInst *BranchInst::clone() const { return new BranchInst(*this); }
1182 SwitchInst *SwitchInst::clone() const { return new SwitchInst(*this); }
1183 InvokeInst *InvokeInst::clone() const { return new InvokeInst(*this); }
1184 UnwindInst *UnwindInst::clone() const { return new UnwindInst(); }
1185 UnreachableInst *UnreachableInst::clone() const { return new UnreachableInst();}