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/ParameterAttributes.h"
21 #include "llvm/Support/CallSite.h"
22 #include "llvm/Support/ConstantRange.h"
23 #include "llvm/Support/MathExtras.h"
26 unsigned CallSite::getCallingConv() const {
27 if (CallInst *CI = dyn_cast<CallInst>(I))
28 return CI->getCallingConv();
30 return cast<InvokeInst>(I)->getCallingConv();
32 void CallSite::setCallingConv(unsigned CC) {
33 if (CallInst *CI = dyn_cast<CallInst>(I))
34 CI->setCallingConv(CC);
36 cast<InvokeInst>(I)->setCallingConv(CC);
38 const ParamAttrsList* CallSite::getParamAttrs() const {
39 if (CallInst *CI = dyn_cast<CallInst>(I))
40 return CI->getParamAttrs();
42 return cast<InvokeInst>(I)->getParamAttrs();
44 void CallSite::setParamAttrs(const ParamAttrsList *PAL) {
45 if (CallInst *CI = dyn_cast<CallInst>(I))
46 CI->setParamAttrs(PAL);
48 cast<InvokeInst>(I)->setParamAttrs(PAL);
50 bool CallSite::paramHasAttr(uint16_t i, ParameterAttributes attr) const {
51 if (CallInst *CI = dyn_cast<CallInst>(I))
52 return CI->paramHasAttr(i, attr);
54 return cast<InvokeInst>(I)->paramHasAttr(i, attr);
56 bool CallSite::doesNotAccessMemory() const {
57 if (CallInst *CI = dyn_cast<CallInst>(I))
58 return CI->doesNotAccessMemory();
60 return cast<InvokeInst>(I)->doesNotAccessMemory();
62 bool CallSite::onlyReadsMemory() const {
63 if (CallInst *CI = dyn_cast<CallInst>(I))
64 return CI->onlyReadsMemory();
66 return cast<InvokeInst>(I)->onlyReadsMemory();
68 bool CallSite::doesNotThrow() const {
69 if (CallInst *CI = dyn_cast<CallInst>(I))
70 return CI->doesNotThrow();
72 return cast<InvokeInst>(I)->doesNotThrow();
75 //===----------------------------------------------------------------------===//
76 // TerminatorInst Class
77 //===----------------------------------------------------------------------===//
79 // Out of line virtual method, so the vtable, etc has a home.
80 TerminatorInst::~TerminatorInst() {
83 // Out of line virtual method, so the vtable, etc has a home.
84 UnaryInstruction::~UnaryInstruction() {
88 //===----------------------------------------------------------------------===//
90 //===----------------------------------------------------------------------===//
92 PHINode::PHINode(const PHINode &PN)
93 : Instruction(PN.getType(), Instruction::PHI,
94 new Use[PN.getNumOperands()], PN.getNumOperands()),
95 ReservedSpace(PN.getNumOperands()) {
96 Use *OL = OperandList;
97 for (unsigned i = 0, e = PN.getNumOperands(); i != e; i+=2) {
98 OL[i].init(PN.getOperand(i), this);
99 OL[i+1].init(PN.getOperand(i+1), this);
103 PHINode::~PHINode() {
104 delete [] OperandList;
107 // removeIncomingValue - Remove an incoming value. This is useful if a
108 // predecessor basic block is deleted.
109 Value *PHINode::removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty) {
110 unsigned NumOps = getNumOperands();
111 Use *OL = OperandList;
112 assert(Idx*2 < NumOps && "BB not in PHI node!");
113 Value *Removed = OL[Idx*2];
115 // Move everything after this operand down.
117 // FIXME: we could just swap with the end of the list, then erase. However,
118 // client might not expect this to happen. The code as it is thrashes the
119 // use/def lists, which is kinda lame.
120 for (unsigned i = (Idx+1)*2; i != NumOps; i += 2) {
125 // Nuke the last value.
127 OL[NumOps-2+1].set(0);
128 NumOperands = NumOps-2;
130 // If the PHI node is dead, because it has zero entries, nuke it now.
131 if (NumOps == 2 && DeletePHIIfEmpty) {
132 // If anyone is using this PHI, make them use a dummy value instead...
133 replaceAllUsesWith(UndefValue::get(getType()));
139 /// resizeOperands - resize operands - This adjusts the length of the operands
140 /// list according to the following behavior:
141 /// 1. If NumOps == 0, grow the operand list in response to a push_back style
142 /// of operation. This grows the number of ops by 1.5 times.
143 /// 2. If NumOps > NumOperands, reserve space for NumOps operands.
144 /// 3. If NumOps == NumOperands, trim the reserved space.
146 void PHINode::resizeOperands(unsigned NumOps) {
148 NumOps = (getNumOperands())*3/2;
149 if (NumOps < 4) NumOps = 4; // 4 op PHI nodes are VERY common.
150 } else if (NumOps*2 > NumOperands) {
152 if (ReservedSpace >= NumOps) return;
153 } else if (NumOps == NumOperands) {
154 if (ReservedSpace == NumOps) return;
159 ReservedSpace = NumOps;
160 Use *NewOps = new Use[NumOps];
161 Use *OldOps = OperandList;
162 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
163 NewOps[i].init(OldOps[i], this);
167 OperandList = NewOps;
170 /// hasConstantValue - If the specified PHI node always merges together the same
171 /// value, return the value, otherwise return null.
173 Value *PHINode::hasConstantValue(bool AllowNonDominatingInstruction) const {
174 // If the PHI node only has one incoming value, eliminate the PHI node...
175 if (getNumIncomingValues() == 1)
176 if (getIncomingValue(0) != this) // not X = phi X
177 return getIncomingValue(0);
179 return UndefValue::get(getType()); // Self cycle is dead.
181 // Otherwise if all of the incoming values are the same for the PHI, replace
182 // the PHI node with the incoming value.
185 bool HasUndefInput = false;
186 for (unsigned i = 0, e = getNumIncomingValues(); i != e; ++i)
187 if (isa<UndefValue>(getIncomingValue(i)))
188 HasUndefInput = true;
189 else if (getIncomingValue(i) != this) // Not the PHI node itself...
190 if (InVal && getIncomingValue(i) != InVal)
191 return 0; // Not the same, bail out.
193 InVal = getIncomingValue(i);
195 // The only case that could cause InVal to be null is if we have a PHI node
196 // that only has entries for itself. In this case, there is no entry into the
197 // loop, so kill the PHI.
199 if (InVal == 0) InVal = UndefValue::get(getType());
201 // If we have a PHI node like phi(X, undef, X), where X is defined by some
202 // instruction, we cannot always return X as the result of the PHI node. Only
203 // do this if X is not an instruction (thus it must dominate the PHI block),
204 // or if the client is prepared to deal with this possibility.
205 if (HasUndefInput && !AllowNonDominatingInstruction)
206 if (Instruction *IV = dyn_cast<Instruction>(InVal))
207 // If it's in the entry block, it dominates everything.
208 if (IV->getParent() != &IV->getParent()->getParent()->getEntryBlock() ||
210 return 0; // Cannot guarantee that InVal dominates this PHINode.
212 // All of the incoming values are the same, return the value now.
217 //===----------------------------------------------------------------------===//
218 // CallInst Implementation
219 //===----------------------------------------------------------------------===//
221 CallInst::~CallInst() {
222 delete [] OperandList;
224 ParamAttrs->dropRef();
227 void CallInst::init(Value *Func, Value* const *Params, unsigned NumParams) {
229 NumOperands = NumParams+1;
230 Use *OL = OperandList = new Use[NumParams+1];
231 OL[0].init(Func, this);
233 const FunctionType *FTy =
234 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
235 FTy = FTy; // silence warning.
237 assert((NumParams == FTy->getNumParams() ||
238 (FTy->isVarArg() && NumParams > FTy->getNumParams())) &&
239 "Calling a function with bad signature!");
240 for (unsigned i = 0; i != NumParams; ++i) {
241 assert((i >= FTy->getNumParams() ||
242 FTy->getParamType(i) == Params[i]->getType()) &&
243 "Calling a function with a bad signature!");
244 OL[i+1].init(Params[i], this);
248 void CallInst::init(Value *Func, Value *Actual1, Value *Actual2) {
251 Use *OL = OperandList = new Use[3];
252 OL[0].init(Func, this);
253 OL[1].init(Actual1, this);
254 OL[2].init(Actual2, this);
256 const FunctionType *FTy =
257 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
258 FTy = FTy; // silence warning.
260 assert((FTy->getNumParams() == 2 ||
261 (FTy->isVarArg() && FTy->getNumParams() < 2)) &&
262 "Calling a function with bad signature");
263 assert((0 >= FTy->getNumParams() ||
264 FTy->getParamType(0) == Actual1->getType()) &&
265 "Calling a function with a bad signature!");
266 assert((1 >= FTy->getNumParams() ||
267 FTy->getParamType(1) == Actual2->getType()) &&
268 "Calling a function with a bad signature!");
271 void CallInst::init(Value *Func, Value *Actual) {
274 Use *OL = OperandList = new Use[2];
275 OL[0].init(Func, this);
276 OL[1].init(Actual, this);
278 const FunctionType *FTy =
279 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
280 FTy = FTy; // silence warning.
282 assert((FTy->getNumParams() == 1 ||
283 (FTy->isVarArg() && FTy->getNumParams() == 0)) &&
284 "Calling a function with bad signature");
285 assert((0 == FTy->getNumParams() ||
286 FTy->getParamType(0) == Actual->getType()) &&
287 "Calling a function with a bad signature!");
290 void CallInst::init(Value *Func) {
293 Use *OL = OperandList = new Use[1];
294 OL[0].init(Func, this);
296 const FunctionType *FTy =
297 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
298 FTy = FTy; // silence warning.
300 assert(FTy->getNumParams() == 0 && "Calling a function with bad signature");
304 // Leave for llvm-gcc
305 CallInst::CallInst(Value *Func, Value* const *Args, unsigned NumArgs,
306 const std::string &Name, BasicBlock *InsertAtEnd)
307 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
308 ->getElementType())->getReturnType(),
309 Instruction::Call, 0, 0, InsertAtEnd) {
310 init(Func, Args, NumArgs);
313 CallInst::CallInst(Value *Func, Value* const *Args, unsigned NumArgs,
314 const std::string &Name, Instruction *InsertBefore)
315 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
316 ->getElementType())->getReturnType(),
317 Instruction::Call, 0, 0, InsertBefore) {
318 init(Func, Args, NumArgs);
322 CallInst::CallInst(Value *Func, Value *Actual1, Value *Actual2,
323 const std::string &Name, Instruction *InsertBefore)
324 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
325 ->getElementType())->getReturnType(),
326 Instruction::Call, 0, 0, InsertBefore) {
327 init(Func, Actual1, Actual2);
331 CallInst::CallInst(Value *Func, Value *Actual1, Value *Actual2,
332 const std::string &Name, BasicBlock *InsertAtEnd)
333 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
334 ->getElementType())->getReturnType(),
335 Instruction::Call, 0, 0, InsertAtEnd) {
336 init(Func, Actual1, Actual2);
340 CallInst::CallInst(Value *Func, Value* Actual, const std::string &Name,
341 Instruction *InsertBefore)
342 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
343 ->getElementType())->getReturnType(),
344 Instruction::Call, 0, 0, InsertBefore) {
349 CallInst::CallInst(Value *Func, Value* Actual, const std::string &Name,
350 BasicBlock *InsertAtEnd)
351 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
352 ->getElementType())->getReturnType(),
353 Instruction::Call, 0, 0, InsertAtEnd) {
357 CallInst::CallInst(Value *Func, const std::string &Name,
358 Instruction *InsertBefore)
359 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
360 ->getElementType())->getReturnType(),
361 Instruction::Call, 0, 0, InsertBefore) {
366 CallInst::CallInst(Value *Func, const std::string &Name,
367 BasicBlock *InsertAtEnd)
368 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
369 ->getElementType())->getReturnType(),
370 Instruction::Call, 0, 0, InsertAtEnd) {
375 CallInst::CallInst(const CallInst &CI)
376 : Instruction(CI.getType(), Instruction::Call, new Use[CI.getNumOperands()],
377 CI.getNumOperands()),
379 setParamAttrs(CI.getParamAttrs());
380 SubclassData = CI.SubclassData;
381 Use *OL = OperandList;
382 Use *InOL = CI.OperandList;
383 for (unsigned i = 0, e = CI.getNumOperands(); i != e; ++i)
384 OL[i].init(InOL[i], this);
387 void CallInst::setParamAttrs(const ParamAttrsList *newAttrs) {
388 if (ParamAttrs == newAttrs)
392 ParamAttrs->dropRef();
397 ParamAttrs = newAttrs;
400 bool CallInst::paramHasAttr(uint16_t i, ParameterAttributes attr) const {
401 if (ParamAttrs && ParamAttrs->paramHasAttr(i, attr))
403 if (const Function *F = getCalledFunction())
404 return F->paramHasAttr(i, attr);
409 //===----------------------------------------------------------------------===//
410 // InvokeInst Implementation
411 //===----------------------------------------------------------------------===//
413 InvokeInst::~InvokeInst() {
414 delete [] OperandList;
416 ParamAttrs->dropRef();
419 void InvokeInst::init(Value *Fn, BasicBlock *IfNormal, BasicBlock *IfException,
420 Value* const *Args, unsigned NumArgs) {
422 NumOperands = 3+NumArgs;
423 Use *OL = OperandList = new Use[3+NumArgs];
424 OL[0].init(Fn, this);
425 OL[1].init(IfNormal, this);
426 OL[2].init(IfException, this);
427 const FunctionType *FTy =
428 cast<FunctionType>(cast<PointerType>(Fn->getType())->getElementType());
429 FTy = FTy; // silence warning.
431 assert((NumArgs == FTy->getNumParams()) ||
432 (FTy->isVarArg() && NumArgs > FTy->getNumParams()) &&
433 "Calling a function with bad signature");
435 for (unsigned i = 0, e = NumArgs; i != e; i++) {
436 assert((i >= FTy->getNumParams() ||
437 FTy->getParamType(i) == Args[i]->getType()) &&
438 "Invoking a function with a bad signature!");
440 OL[i+3].init(Args[i], this);
444 InvokeInst::InvokeInst(const InvokeInst &II)
445 : TerminatorInst(II.getType(), Instruction::Invoke,
446 new Use[II.getNumOperands()], II.getNumOperands()),
448 setParamAttrs(II.getParamAttrs());
449 SubclassData = II.SubclassData;
450 Use *OL = OperandList, *InOL = II.OperandList;
451 for (unsigned i = 0, e = II.getNumOperands(); i != e; ++i)
452 OL[i].init(InOL[i], this);
455 BasicBlock *InvokeInst::getSuccessorV(unsigned idx) const {
456 return getSuccessor(idx);
458 unsigned InvokeInst::getNumSuccessorsV() const {
459 return getNumSuccessors();
461 void InvokeInst::setSuccessorV(unsigned idx, BasicBlock *B) {
462 return setSuccessor(idx, B);
465 void InvokeInst::setParamAttrs(const ParamAttrsList *newAttrs) {
466 if (ParamAttrs == newAttrs)
470 ParamAttrs->dropRef();
475 ParamAttrs = newAttrs;
478 bool InvokeInst::paramHasAttr(uint16_t i, ParameterAttributes attr) const {
479 if (ParamAttrs && ParamAttrs->paramHasAttr(i, attr))
481 if (const Function *F = getCalledFunction())
482 return F->paramHasAttr(i, attr);
487 //===----------------------------------------------------------------------===//
488 // ReturnInst Implementation
489 //===----------------------------------------------------------------------===//
491 ReturnInst::ReturnInst(const ReturnInst &RI)
492 : TerminatorInst(Type::VoidTy, Instruction::Ret,
493 &RetVal, RI.getNumOperands()) {
494 if (RI.getNumOperands())
495 RetVal.init(RI.RetVal, this);
498 ReturnInst::ReturnInst(Value *retVal, Instruction *InsertBefore)
499 : TerminatorInst(Type::VoidTy, Instruction::Ret, &RetVal, 0, InsertBefore) {
502 ReturnInst::ReturnInst(Value *retVal, BasicBlock *InsertAtEnd)
503 : TerminatorInst(Type::VoidTy, Instruction::Ret, &RetVal, 0, InsertAtEnd) {
506 ReturnInst::ReturnInst(BasicBlock *InsertAtEnd)
507 : TerminatorInst(Type::VoidTy, Instruction::Ret, &RetVal, 0, InsertAtEnd) {
512 void ReturnInst::init(Value *retVal) {
513 if (retVal && retVal->getType() != Type::VoidTy) {
514 assert(!isa<BasicBlock>(retVal) &&
515 "Cannot return basic block. Probably using the incorrect ctor");
517 RetVal.init(retVal, this);
521 unsigned ReturnInst::getNumSuccessorsV() const {
522 return getNumSuccessors();
525 // Out-of-line ReturnInst method, put here so the C++ compiler can choose to
526 // emit the vtable for the class in this translation unit.
527 void ReturnInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
528 assert(0 && "ReturnInst has no successors!");
531 BasicBlock *ReturnInst::getSuccessorV(unsigned idx) const {
532 assert(0 && "ReturnInst has no successors!");
538 //===----------------------------------------------------------------------===//
539 // UnwindInst Implementation
540 //===----------------------------------------------------------------------===//
542 UnwindInst::UnwindInst(Instruction *InsertBefore)
543 : TerminatorInst(Type::VoidTy, Instruction::Unwind, 0, 0, InsertBefore) {
545 UnwindInst::UnwindInst(BasicBlock *InsertAtEnd)
546 : TerminatorInst(Type::VoidTy, Instruction::Unwind, 0, 0, InsertAtEnd) {
550 unsigned UnwindInst::getNumSuccessorsV() const {
551 return getNumSuccessors();
554 void UnwindInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
555 assert(0 && "UnwindInst has no successors!");
558 BasicBlock *UnwindInst::getSuccessorV(unsigned idx) const {
559 assert(0 && "UnwindInst has no successors!");
564 //===----------------------------------------------------------------------===//
565 // UnreachableInst Implementation
566 //===----------------------------------------------------------------------===//
568 UnreachableInst::UnreachableInst(Instruction *InsertBefore)
569 : TerminatorInst(Type::VoidTy, Instruction::Unreachable, 0, 0, InsertBefore) {
571 UnreachableInst::UnreachableInst(BasicBlock *InsertAtEnd)
572 : TerminatorInst(Type::VoidTy, Instruction::Unreachable, 0, 0, InsertAtEnd) {
575 unsigned UnreachableInst::getNumSuccessorsV() const {
576 return getNumSuccessors();
579 void UnreachableInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
580 assert(0 && "UnwindInst has no successors!");
583 BasicBlock *UnreachableInst::getSuccessorV(unsigned idx) const {
584 assert(0 && "UnwindInst has no successors!");
589 //===----------------------------------------------------------------------===//
590 // BranchInst Implementation
591 //===----------------------------------------------------------------------===//
593 void BranchInst::AssertOK() {
595 assert(getCondition()->getType() == Type::Int1Ty &&
596 "May only branch on boolean predicates!");
599 BranchInst::BranchInst(BasicBlock *IfTrue, Instruction *InsertBefore)
600 : TerminatorInst(Type::VoidTy, Instruction::Br, Ops, 1, InsertBefore) {
601 assert(IfTrue != 0 && "Branch destination may not be null!");
602 Ops[0].init(reinterpret_cast<Value*>(IfTrue), this);
604 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
605 Instruction *InsertBefore)
606 : TerminatorInst(Type::VoidTy, Instruction::Br, Ops, 3, InsertBefore) {
607 Ops[0].init(reinterpret_cast<Value*>(IfTrue), this);
608 Ops[1].init(reinterpret_cast<Value*>(IfFalse), this);
609 Ops[2].init(Cond, this);
615 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *InsertAtEnd)
616 : TerminatorInst(Type::VoidTy, Instruction::Br, Ops, 1, InsertAtEnd) {
617 assert(IfTrue != 0 && "Branch destination may not be null!");
618 Ops[0].init(reinterpret_cast<Value*>(IfTrue), this);
621 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
622 BasicBlock *InsertAtEnd)
623 : TerminatorInst(Type::VoidTy, Instruction::Br, Ops, 3, InsertAtEnd) {
624 Ops[0].init(reinterpret_cast<Value*>(IfTrue), this);
625 Ops[1].init(reinterpret_cast<Value*>(IfFalse), this);
626 Ops[2].init(Cond, this);
633 BranchInst::BranchInst(const BranchInst &BI) :
634 TerminatorInst(Type::VoidTy, Instruction::Br, Ops, BI.getNumOperands()) {
635 OperandList[0].init(BI.getOperand(0), this);
636 if (BI.getNumOperands() != 1) {
637 assert(BI.getNumOperands() == 3 && "BR can have 1 or 3 operands!");
638 OperandList[1].init(BI.getOperand(1), this);
639 OperandList[2].init(BI.getOperand(2), this);
643 BasicBlock *BranchInst::getSuccessorV(unsigned idx) const {
644 return getSuccessor(idx);
646 unsigned BranchInst::getNumSuccessorsV() const {
647 return getNumSuccessors();
649 void BranchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
650 setSuccessor(idx, B);
654 //===----------------------------------------------------------------------===//
655 // AllocationInst Implementation
656 //===----------------------------------------------------------------------===//
658 static Value *getAISize(Value *Amt) {
660 Amt = ConstantInt::get(Type::Int32Ty, 1);
662 assert(!isa<BasicBlock>(Amt) &&
663 "Passed basic block into allocation size parameter! Use other ctor");
664 assert(Amt->getType() == Type::Int32Ty &&
665 "Malloc/Allocation array size is not a 32-bit integer!");
670 AllocationInst::AllocationInst(const Type *Ty, Value *ArraySize, unsigned iTy,
671 unsigned Align, const std::string &Name,
672 Instruction *InsertBefore)
673 : UnaryInstruction(PointerType::getUnqual(Ty), iTy, getAISize(ArraySize),
674 InsertBefore), Alignment(Align) {
675 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
676 assert(Ty != Type::VoidTy && "Cannot allocate void!");
680 AllocationInst::AllocationInst(const Type *Ty, Value *ArraySize, unsigned iTy,
681 unsigned Align, const std::string &Name,
682 BasicBlock *InsertAtEnd)
683 : UnaryInstruction(PointerType::getUnqual(Ty), iTy, getAISize(ArraySize),
684 InsertAtEnd), Alignment(Align) {
685 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
686 assert(Ty != Type::VoidTy && "Cannot allocate void!");
690 // Out of line virtual method, so the vtable, etc has a home.
691 AllocationInst::~AllocationInst() {
694 bool AllocationInst::isArrayAllocation() const {
695 if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(0)))
696 return CI->getZExtValue() != 1;
700 const Type *AllocationInst::getAllocatedType() const {
701 return getType()->getElementType();
704 AllocaInst::AllocaInst(const AllocaInst &AI)
705 : AllocationInst(AI.getType()->getElementType(), (Value*)AI.getOperand(0),
706 Instruction::Alloca, AI.getAlignment()) {
709 MallocInst::MallocInst(const MallocInst &MI)
710 : AllocationInst(MI.getType()->getElementType(), (Value*)MI.getOperand(0),
711 Instruction::Malloc, MI.getAlignment()) {
714 //===----------------------------------------------------------------------===//
715 // FreeInst Implementation
716 //===----------------------------------------------------------------------===//
718 void FreeInst::AssertOK() {
719 assert(isa<PointerType>(getOperand(0)->getType()) &&
720 "Can not free something of nonpointer type!");
723 FreeInst::FreeInst(Value *Ptr, Instruction *InsertBefore)
724 : UnaryInstruction(Type::VoidTy, Free, Ptr, InsertBefore) {
728 FreeInst::FreeInst(Value *Ptr, BasicBlock *InsertAtEnd)
729 : UnaryInstruction(Type::VoidTy, Free, Ptr, InsertAtEnd) {
734 //===----------------------------------------------------------------------===//
735 // LoadInst Implementation
736 //===----------------------------------------------------------------------===//
738 void LoadInst::AssertOK() {
739 assert(isa<PointerType>(getOperand(0)->getType()) &&
740 "Ptr must have pointer type.");
743 LoadInst::LoadInst(Value *Ptr, const std::string &Name, Instruction *InsertBef)
744 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
745 Load, Ptr, InsertBef) {
752 LoadInst::LoadInst(Value *Ptr, const std::string &Name, BasicBlock *InsertAE)
753 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
754 Load, Ptr, InsertAE) {
761 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile,
762 Instruction *InsertBef)
763 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
764 Load, Ptr, InsertBef) {
765 setVolatile(isVolatile);
771 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile,
772 unsigned Align, Instruction *InsertBef)
773 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
774 Load, Ptr, InsertBef) {
775 setVolatile(isVolatile);
781 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile,
782 unsigned Align, BasicBlock *InsertAE)
783 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
784 Load, Ptr, InsertAE) {
785 setVolatile(isVolatile);
791 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile,
792 BasicBlock *InsertAE)
793 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
794 Load, Ptr, InsertAE) {
795 setVolatile(isVolatile);
803 LoadInst::LoadInst(Value *Ptr, const char *Name, Instruction *InsertBef)
804 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
805 Load, Ptr, InsertBef) {
809 if (Name && Name[0]) setName(Name);
812 LoadInst::LoadInst(Value *Ptr, const char *Name, BasicBlock *InsertAE)
813 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
814 Load, Ptr, InsertAE) {
818 if (Name && Name[0]) setName(Name);
821 LoadInst::LoadInst(Value *Ptr, const char *Name, bool isVolatile,
822 Instruction *InsertBef)
823 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
824 Load, Ptr, InsertBef) {
825 setVolatile(isVolatile);
828 if (Name && Name[0]) setName(Name);
831 LoadInst::LoadInst(Value *Ptr, const char *Name, bool isVolatile,
832 BasicBlock *InsertAE)
833 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
834 Load, Ptr, InsertAE) {
835 setVolatile(isVolatile);
838 if (Name && Name[0]) setName(Name);
841 void LoadInst::setAlignment(unsigned Align) {
842 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
843 SubclassData = (SubclassData & 1) | ((Log2_32(Align)+1)<<1);
846 //===----------------------------------------------------------------------===//
847 // StoreInst Implementation
848 //===----------------------------------------------------------------------===//
850 void StoreInst::AssertOK() {
851 assert(isa<PointerType>(getOperand(1)->getType()) &&
852 "Ptr must have pointer type!");
853 assert(getOperand(0)->getType() ==
854 cast<PointerType>(getOperand(1)->getType())->getElementType()
855 && "Ptr must be a pointer to Val type!");
859 StoreInst::StoreInst(Value *val, Value *addr, Instruction *InsertBefore)
860 : Instruction(Type::VoidTy, Store, Ops, 2, InsertBefore) {
861 Ops[0].init(val, this);
862 Ops[1].init(addr, this);
868 StoreInst::StoreInst(Value *val, Value *addr, BasicBlock *InsertAtEnd)
869 : Instruction(Type::VoidTy, Store, Ops, 2, InsertAtEnd) {
870 Ops[0].init(val, this);
871 Ops[1].init(addr, this);
877 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
878 Instruction *InsertBefore)
879 : Instruction(Type::VoidTy, Store, Ops, 2, InsertBefore) {
880 Ops[0].init(val, this);
881 Ops[1].init(addr, this);
882 setVolatile(isVolatile);
887 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
888 unsigned Align, Instruction *InsertBefore)
889 : Instruction(Type::VoidTy, Store, Ops, 2, InsertBefore) {
890 Ops[0].init(val, this);
891 Ops[1].init(addr, this);
892 setVolatile(isVolatile);
897 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
898 unsigned Align, BasicBlock *InsertAtEnd)
899 : Instruction(Type::VoidTy, Store, Ops, 2, InsertAtEnd) {
900 Ops[0].init(val, this);
901 Ops[1].init(addr, this);
902 setVolatile(isVolatile);
907 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
908 BasicBlock *InsertAtEnd)
909 : Instruction(Type::VoidTy, Store, Ops, 2, InsertAtEnd) {
910 Ops[0].init(val, this);
911 Ops[1].init(addr, this);
912 setVolatile(isVolatile);
917 void StoreInst::setAlignment(unsigned Align) {
918 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
919 SubclassData = (SubclassData & 1) | ((Log2_32(Align)+1)<<1);
922 //===----------------------------------------------------------------------===//
923 // GetElementPtrInst Implementation
924 //===----------------------------------------------------------------------===//
926 static unsigned retrieveAddrSpace(const Value *Val) {
927 return cast<PointerType>(Val->getType())->getAddressSpace();
930 void GetElementPtrInst::init(Value *Ptr, Value* const *Idx, unsigned NumIdx) {
931 NumOperands = 1+NumIdx;
932 Use *OL = OperandList = new Use[NumOperands];
933 OL[0].init(Ptr, this);
935 for (unsigned i = 0; i != NumIdx; ++i)
936 OL[i+1].init(Idx[i], this);
939 void GetElementPtrInst::init(Value *Ptr, Value *Idx) {
941 Use *OL = OperandList = new Use[2];
942 OL[0].init(Ptr, this);
943 OL[1].init(Idx, this);
946 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx,
947 const std::string &Name, Instruction *InBe)
948 : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),Idx)),
949 retrieveAddrSpace(Ptr)),
950 GetElementPtr, 0, 0, InBe) {
955 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx,
956 const std::string &Name, BasicBlock *IAE)
957 : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),Idx)),
958 retrieveAddrSpace(Ptr)),
959 GetElementPtr, 0, 0, IAE) {
964 GetElementPtrInst::~GetElementPtrInst() {
965 delete[] OperandList;
968 // getIndexedType - Returns the type of the element that would be loaded with
969 // a load instruction with the specified parameters.
971 // A null type is returned if the indices are invalid for the specified
974 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr,
977 bool AllowCompositeLeaf) {
978 if (!isa<PointerType>(Ptr)) return 0; // Type isn't a pointer type!
980 // Handle the special case of the empty set index set...
982 if (AllowCompositeLeaf ||
983 cast<PointerType>(Ptr)->getElementType()->isFirstClassType())
984 return cast<PointerType>(Ptr)->getElementType();
989 while (const CompositeType *CT = dyn_cast<CompositeType>(Ptr)) {
990 if (NumIdx == CurIdx) {
991 if (AllowCompositeLeaf || CT->isFirstClassType()) return Ptr;
992 return 0; // Can't load a whole structure or array!?!?
995 Value *Index = Idxs[CurIdx++];
996 if (isa<PointerType>(CT) && CurIdx != 1)
997 return 0; // Can only index into pointer types at the first index!
998 if (!CT->indexValid(Index)) return 0;
999 Ptr = CT->getTypeAtIndex(Index);
1001 // If the new type forwards to another type, then it is in the middle
1002 // of being refined to another type (and hence, may have dropped all
1003 // references to what it was using before). So, use the new forwarded
1005 if (const Type * Ty = Ptr->getForwardedType()) {
1009 return CurIdx == NumIdx ? Ptr : 0;
1012 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr, Value *Idx) {
1013 const PointerType *PTy = dyn_cast<PointerType>(Ptr);
1014 if (!PTy) return 0; // Type isn't a pointer type!
1016 // Check the pointer index.
1017 if (!PTy->indexValid(Idx)) return 0;
1019 return PTy->getElementType();
1023 /// hasAllZeroIndices - Return true if all of the indices of this GEP are
1024 /// zeros. If so, the result pointer and the first operand have the same
1025 /// value, just potentially different types.
1026 bool GetElementPtrInst::hasAllZeroIndices() const {
1027 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1028 if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(i))) {
1029 if (!CI->isZero()) return false;
1037 /// hasAllConstantIndices - Return true if all of the indices of this GEP are
1038 /// constant integers. If so, the result pointer and the first operand have
1039 /// a constant offset between them.
1040 bool GetElementPtrInst::hasAllConstantIndices() const {
1041 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1042 if (!isa<ConstantInt>(getOperand(i)))
1049 //===----------------------------------------------------------------------===//
1050 // ExtractElementInst Implementation
1051 //===----------------------------------------------------------------------===//
1053 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
1054 const std::string &Name,
1055 Instruction *InsertBef)
1056 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1057 ExtractElement, Ops, 2, InsertBef) {
1058 assert(isValidOperands(Val, Index) &&
1059 "Invalid extractelement instruction operands!");
1060 Ops[0].init(Val, this);
1061 Ops[1].init(Index, this);
1065 ExtractElementInst::ExtractElementInst(Value *Val, unsigned IndexV,
1066 const std::string &Name,
1067 Instruction *InsertBef)
1068 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1069 ExtractElement, Ops, 2, InsertBef) {
1070 Constant *Index = ConstantInt::get(Type::Int32Ty, IndexV);
1071 assert(isValidOperands(Val, Index) &&
1072 "Invalid extractelement instruction operands!");
1073 Ops[0].init(Val, this);
1074 Ops[1].init(Index, this);
1079 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
1080 const std::string &Name,
1081 BasicBlock *InsertAE)
1082 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1083 ExtractElement, Ops, 2, InsertAE) {
1084 assert(isValidOperands(Val, Index) &&
1085 "Invalid extractelement instruction operands!");
1087 Ops[0].init(Val, this);
1088 Ops[1].init(Index, this);
1092 ExtractElementInst::ExtractElementInst(Value *Val, unsigned IndexV,
1093 const std::string &Name,
1094 BasicBlock *InsertAE)
1095 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1096 ExtractElement, Ops, 2, InsertAE) {
1097 Constant *Index = ConstantInt::get(Type::Int32Ty, IndexV);
1098 assert(isValidOperands(Val, Index) &&
1099 "Invalid extractelement instruction operands!");
1101 Ops[0].init(Val, this);
1102 Ops[1].init(Index, this);
1107 bool ExtractElementInst::isValidOperands(const Value *Val, const Value *Index) {
1108 if (!isa<VectorType>(Val->getType()) || Index->getType() != Type::Int32Ty)
1114 //===----------------------------------------------------------------------===//
1115 // InsertElementInst Implementation
1116 //===----------------------------------------------------------------------===//
1118 InsertElementInst::InsertElementInst(const InsertElementInst &IE)
1119 : Instruction(IE.getType(), InsertElement, Ops, 3) {
1120 Ops[0].init(IE.Ops[0], this);
1121 Ops[1].init(IE.Ops[1], this);
1122 Ops[2].init(IE.Ops[2], this);
1124 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
1125 const std::string &Name,
1126 Instruction *InsertBef)
1127 : Instruction(Vec->getType(), InsertElement, Ops, 3, InsertBef) {
1128 assert(isValidOperands(Vec, Elt, Index) &&
1129 "Invalid insertelement instruction operands!");
1130 Ops[0].init(Vec, this);
1131 Ops[1].init(Elt, this);
1132 Ops[2].init(Index, this);
1136 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, unsigned IndexV,
1137 const std::string &Name,
1138 Instruction *InsertBef)
1139 : Instruction(Vec->getType(), InsertElement, Ops, 3, InsertBef) {
1140 Constant *Index = ConstantInt::get(Type::Int32Ty, IndexV);
1141 assert(isValidOperands(Vec, Elt, Index) &&
1142 "Invalid insertelement instruction operands!");
1143 Ops[0].init(Vec, this);
1144 Ops[1].init(Elt, this);
1145 Ops[2].init(Index, this);
1150 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
1151 const std::string &Name,
1152 BasicBlock *InsertAE)
1153 : Instruction(Vec->getType(), InsertElement, Ops, 3, InsertAE) {
1154 assert(isValidOperands(Vec, Elt, Index) &&
1155 "Invalid insertelement instruction operands!");
1157 Ops[0].init(Vec, this);
1158 Ops[1].init(Elt, this);
1159 Ops[2].init(Index, this);
1163 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, unsigned IndexV,
1164 const std::string &Name,
1165 BasicBlock *InsertAE)
1166 : Instruction(Vec->getType(), InsertElement, Ops, 3, InsertAE) {
1167 Constant *Index = ConstantInt::get(Type::Int32Ty, IndexV);
1168 assert(isValidOperands(Vec, Elt, Index) &&
1169 "Invalid insertelement instruction operands!");
1171 Ops[0].init(Vec, this);
1172 Ops[1].init(Elt, this);
1173 Ops[2].init(Index, this);
1177 bool InsertElementInst::isValidOperands(const Value *Vec, const Value *Elt,
1178 const Value *Index) {
1179 if (!isa<VectorType>(Vec->getType()))
1180 return false; // First operand of insertelement must be vector type.
1182 if (Elt->getType() != cast<VectorType>(Vec->getType())->getElementType())
1183 return false;// Second operand of insertelement must be vector element type.
1185 if (Index->getType() != Type::Int32Ty)
1186 return false; // Third operand of insertelement must be uint.
1191 //===----------------------------------------------------------------------===//
1192 // ShuffleVectorInst Implementation
1193 //===----------------------------------------------------------------------===//
1195 ShuffleVectorInst::ShuffleVectorInst(const ShuffleVectorInst &SV)
1196 : Instruction(SV.getType(), ShuffleVector, Ops, 3) {
1197 Ops[0].init(SV.Ops[0], this);
1198 Ops[1].init(SV.Ops[1], this);
1199 Ops[2].init(SV.Ops[2], this);
1202 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1203 const std::string &Name,
1204 Instruction *InsertBefore)
1205 : Instruction(V1->getType(), ShuffleVector, Ops, 3, InsertBefore) {
1206 assert(isValidOperands(V1, V2, Mask) &&
1207 "Invalid shuffle vector instruction operands!");
1208 Ops[0].init(V1, this);
1209 Ops[1].init(V2, this);
1210 Ops[2].init(Mask, this);
1214 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1215 const std::string &Name,
1216 BasicBlock *InsertAtEnd)
1217 : Instruction(V1->getType(), ShuffleVector, Ops, 3, InsertAtEnd) {
1218 assert(isValidOperands(V1, V2, Mask) &&
1219 "Invalid shuffle vector instruction operands!");
1221 Ops[0].init(V1, this);
1222 Ops[1].init(V2, this);
1223 Ops[2].init(Mask, this);
1227 bool ShuffleVectorInst::isValidOperands(const Value *V1, const Value *V2,
1228 const Value *Mask) {
1229 if (!isa<VectorType>(V1->getType())) return false;
1230 if (V1->getType() != V2->getType()) return false;
1231 if (!isa<VectorType>(Mask->getType()) ||
1232 cast<VectorType>(Mask->getType())->getElementType() != Type::Int32Ty ||
1233 cast<VectorType>(Mask->getType())->getNumElements() !=
1234 cast<VectorType>(V1->getType())->getNumElements())
1240 //===----------------------------------------------------------------------===//
1241 // BinaryOperator Class
1242 //===----------------------------------------------------------------------===//
1244 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
1245 const Type *Ty, const std::string &Name,
1246 Instruction *InsertBefore)
1247 : Instruction(Ty, iType, Ops, 2, InsertBefore) {
1248 Ops[0].init(S1, this);
1249 Ops[1].init(S2, this);
1254 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
1255 const Type *Ty, const std::string &Name,
1256 BasicBlock *InsertAtEnd)
1257 : Instruction(Ty, iType, Ops, 2, InsertAtEnd) {
1258 Ops[0].init(S1, this);
1259 Ops[1].init(S2, this);
1265 void BinaryOperator::init(BinaryOps iType) {
1266 Value *LHS = getOperand(0), *RHS = getOperand(1);
1267 LHS = LHS; RHS = RHS; // Silence warnings.
1268 assert(LHS->getType() == RHS->getType() &&
1269 "Binary operator operand types must match!");
1274 assert(getType() == LHS->getType() &&
1275 "Arithmetic operation should return same type as operands!");
1276 assert((getType()->isInteger() || getType()->isFloatingPoint() ||
1277 isa<VectorType>(getType())) &&
1278 "Tried to create an arithmetic operation on a non-arithmetic type!");
1282 assert(getType() == LHS->getType() &&
1283 "Arithmetic operation should return same type as operands!");
1284 assert((getType()->isInteger() || (isa<VectorType>(getType()) &&
1285 cast<VectorType>(getType())->getElementType()->isInteger())) &&
1286 "Incorrect operand type (not integer) for S/UDIV");
1289 assert(getType() == LHS->getType() &&
1290 "Arithmetic operation should return same type as operands!");
1291 assert((getType()->isFloatingPoint() || (isa<VectorType>(getType()) &&
1292 cast<VectorType>(getType())->getElementType()->isFloatingPoint()))
1293 && "Incorrect operand type (not floating point) for FDIV");
1297 assert(getType() == LHS->getType() &&
1298 "Arithmetic operation should return same type as operands!");
1299 assert((getType()->isInteger() || (isa<VectorType>(getType()) &&
1300 cast<VectorType>(getType())->getElementType()->isInteger())) &&
1301 "Incorrect operand type (not integer) for S/UREM");
1304 assert(getType() == LHS->getType() &&
1305 "Arithmetic operation should return same type as operands!");
1306 assert((getType()->isFloatingPoint() || (isa<VectorType>(getType()) &&
1307 cast<VectorType>(getType())->getElementType()->isFloatingPoint()))
1308 && "Incorrect operand type (not floating point) for FREM");
1313 assert(getType() == LHS->getType() &&
1314 "Shift operation should return same type as operands!");
1315 assert(getType()->isInteger() &&
1316 "Shift operation requires integer operands");
1320 assert(getType() == LHS->getType() &&
1321 "Logical operation should return same type as operands!");
1322 assert((getType()->isInteger() ||
1323 (isa<VectorType>(getType()) &&
1324 cast<VectorType>(getType())->getElementType()->isInteger())) &&
1325 "Tried to create a logical operation on a non-integral type!");
1333 BinaryOperator *BinaryOperator::create(BinaryOps Op, Value *S1, Value *S2,
1334 const std::string &Name,
1335 Instruction *InsertBefore) {
1336 assert(S1->getType() == S2->getType() &&
1337 "Cannot create binary operator with two operands of differing type!");
1338 return new BinaryOperator(Op, S1, S2, S1->getType(), Name, InsertBefore);
1341 BinaryOperator *BinaryOperator::create(BinaryOps Op, Value *S1, Value *S2,
1342 const std::string &Name,
1343 BasicBlock *InsertAtEnd) {
1344 BinaryOperator *Res = create(Op, S1, S2, Name);
1345 InsertAtEnd->getInstList().push_back(Res);
1349 BinaryOperator *BinaryOperator::createNeg(Value *Op, const std::string &Name,
1350 Instruction *InsertBefore) {
1351 Value *zero = ConstantExpr::getZeroValueForNegationExpr(Op->getType());
1352 return new BinaryOperator(Instruction::Sub,
1354 Op->getType(), Name, InsertBefore);
1357 BinaryOperator *BinaryOperator::createNeg(Value *Op, const std::string &Name,
1358 BasicBlock *InsertAtEnd) {
1359 Value *zero = ConstantExpr::getZeroValueForNegationExpr(Op->getType());
1360 return new BinaryOperator(Instruction::Sub,
1362 Op->getType(), Name, InsertAtEnd);
1365 BinaryOperator *BinaryOperator::createNot(Value *Op, const std::string &Name,
1366 Instruction *InsertBefore) {
1368 if (const VectorType *PTy = dyn_cast<VectorType>(Op->getType())) {
1369 C = ConstantInt::getAllOnesValue(PTy->getElementType());
1370 C = ConstantVector::get(std::vector<Constant*>(PTy->getNumElements(), C));
1372 C = ConstantInt::getAllOnesValue(Op->getType());
1375 return new BinaryOperator(Instruction::Xor, Op, C,
1376 Op->getType(), Name, InsertBefore);
1379 BinaryOperator *BinaryOperator::createNot(Value *Op, const std::string &Name,
1380 BasicBlock *InsertAtEnd) {
1382 if (const VectorType *PTy = dyn_cast<VectorType>(Op->getType())) {
1383 // Create a vector of all ones values.
1384 Constant *Elt = ConstantInt::getAllOnesValue(PTy->getElementType());
1386 ConstantVector::get(std::vector<Constant*>(PTy->getNumElements(), Elt));
1388 AllOnes = ConstantInt::getAllOnesValue(Op->getType());
1391 return new BinaryOperator(Instruction::Xor, Op, AllOnes,
1392 Op->getType(), Name, InsertAtEnd);
1396 // isConstantAllOnes - Helper function for several functions below
1397 static inline bool isConstantAllOnes(const Value *V) {
1398 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V))
1399 return CI->isAllOnesValue();
1400 if (const ConstantVector *CV = dyn_cast<ConstantVector>(V))
1401 return CV->isAllOnesValue();
1405 bool BinaryOperator::isNeg(const Value *V) {
1406 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1407 if (Bop->getOpcode() == Instruction::Sub)
1408 return Bop->getOperand(0) ==
1409 ConstantExpr::getZeroValueForNegationExpr(Bop->getType());
1413 bool BinaryOperator::isNot(const Value *V) {
1414 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1415 return (Bop->getOpcode() == Instruction::Xor &&
1416 (isConstantAllOnes(Bop->getOperand(1)) ||
1417 isConstantAllOnes(Bop->getOperand(0))));
1421 Value *BinaryOperator::getNegArgument(Value *BinOp) {
1422 assert(isNeg(BinOp) && "getNegArgument from non-'neg' instruction!");
1423 return cast<BinaryOperator>(BinOp)->getOperand(1);
1426 const Value *BinaryOperator::getNegArgument(const Value *BinOp) {
1427 return getNegArgument(const_cast<Value*>(BinOp));
1430 Value *BinaryOperator::getNotArgument(Value *BinOp) {
1431 assert(isNot(BinOp) && "getNotArgument on non-'not' instruction!");
1432 BinaryOperator *BO = cast<BinaryOperator>(BinOp);
1433 Value *Op0 = BO->getOperand(0);
1434 Value *Op1 = BO->getOperand(1);
1435 if (isConstantAllOnes(Op0)) return Op1;
1437 assert(isConstantAllOnes(Op1));
1441 const Value *BinaryOperator::getNotArgument(const Value *BinOp) {
1442 return getNotArgument(const_cast<Value*>(BinOp));
1446 // swapOperands - Exchange the two operands to this instruction. This
1447 // instruction is safe to use on any binary instruction and does not
1448 // modify the semantics of the instruction. If the instruction is
1449 // order dependent (SetLT f.e.) the opcode is changed.
1451 bool BinaryOperator::swapOperands() {
1452 if (!isCommutative())
1453 return true; // Can't commute operands
1454 std::swap(Ops[0], Ops[1]);
1458 //===----------------------------------------------------------------------===//
1460 //===----------------------------------------------------------------------===//
1462 // Just determine if this cast only deals with integral->integral conversion.
1463 bool CastInst::isIntegerCast() const {
1464 switch (getOpcode()) {
1465 default: return false;
1466 case Instruction::ZExt:
1467 case Instruction::SExt:
1468 case Instruction::Trunc:
1470 case Instruction::BitCast:
1471 return getOperand(0)->getType()->isInteger() && getType()->isInteger();
1475 bool CastInst::isLosslessCast() const {
1476 // Only BitCast can be lossless, exit fast if we're not BitCast
1477 if (getOpcode() != Instruction::BitCast)
1480 // Identity cast is always lossless
1481 const Type* SrcTy = getOperand(0)->getType();
1482 const Type* DstTy = getType();
1486 // Pointer to pointer is always lossless.
1487 if (isa<PointerType>(SrcTy))
1488 return isa<PointerType>(DstTy);
1489 return false; // Other types have no identity values
1492 /// This function determines if the CastInst does not require any bits to be
1493 /// changed in order to effect the cast. Essentially, it identifies cases where
1494 /// no code gen is necessary for the cast, hence the name no-op cast. For
1495 /// example, the following are all no-op casts:
1496 /// # bitcast uint %X, int
1497 /// # bitcast uint* %x, sbyte*
1498 /// # bitcast vector< 2 x int > %x, vector< 4 x short>
1499 /// # ptrtoint uint* %x, uint ; on 32-bit plaforms only
1500 /// @brief Determine if a cast is a no-op.
1501 bool CastInst::isNoopCast(const Type *IntPtrTy) const {
1502 switch (getOpcode()) {
1504 assert(!"Invalid CastOp");
1505 case Instruction::Trunc:
1506 case Instruction::ZExt:
1507 case Instruction::SExt:
1508 case Instruction::FPTrunc:
1509 case Instruction::FPExt:
1510 case Instruction::UIToFP:
1511 case Instruction::SIToFP:
1512 case Instruction::FPToUI:
1513 case Instruction::FPToSI:
1514 return false; // These always modify bits
1515 case Instruction::BitCast:
1516 return true; // BitCast never modifies bits.
1517 case Instruction::PtrToInt:
1518 return IntPtrTy->getPrimitiveSizeInBits() ==
1519 getType()->getPrimitiveSizeInBits();
1520 case Instruction::IntToPtr:
1521 return IntPtrTy->getPrimitiveSizeInBits() ==
1522 getOperand(0)->getType()->getPrimitiveSizeInBits();
1526 /// This function determines if a pair of casts can be eliminated and what
1527 /// opcode should be used in the elimination. This assumes that there are two
1528 /// instructions like this:
1529 /// * %F = firstOpcode SrcTy %x to MidTy
1530 /// * %S = secondOpcode MidTy %F to DstTy
1531 /// The function returns a resultOpcode so these two casts can be replaced with:
1532 /// * %Replacement = resultOpcode %SrcTy %x to DstTy
1533 /// If no such cast is permited, the function returns 0.
1534 unsigned CastInst::isEliminableCastPair(
1535 Instruction::CastOps firstOp, Instruction::CastOps secondOp,
1536 const Type *SrcTy, const Type *MidTy, const Type *DstTy, const Type *IntPtrTy)
1538 // Define the 144 possibilities for these two cast instructions. The values
1539 // in this matrix determine what to do in a given situation and select the
1540 // case in the switch below. The rows correspond to firstOp, the columns
1541 // correspond to secondOp. In looking at the table below, keep in mind
1542 // the following cast properties:
1544 // Size Compare Source Destination
1545 // Operator Src ? Size Type Sign Type Sign
1546 // -------- ------------ ------------------- ---------------------
1547 // TRUNC > Integer Any Integral Any
1548 // ZEXT < Integral Unsigned Integer Any
1549 // SEXT < Integral Signed Integer Any
1550 // FPTOUI n/a FloatPt n/a Integral Unsigned
1551 // FPTOSI n/a FloatPt n/a Integral Signed
1552 // UITOFP n/a Integral Unsigned FloatPt n/a
1553 // SITOFP n/a Integral Signed FloatPt n/a
1554 // FPTRUNC > FloatPt n/a FloatPt n/a
1555 // FPEXT < FloatPt n/a FloatPt n/a
1556 // PTRTOINT n/a Pointer n/a Integral Unsigned
1557 // INTTOPTR n/a Integral Unsigned Pointer n/a
1558 // BITCONVERT = FirstClass n/a FirstClass n/a
1560 // NOTE: some transforms are safe, but we consider them to be non-profitable.
1561 // For example, we could merge "fptoui double to uint" + "zext uint to ulong",
1562 // into "fptoui double to ulong", but this loses information about the range
1563 // of the produced value (we no longer know the top-part is all zeros).
1564 // Further this conversion is often much more expensive for typical hardware,
1565 // and causes issues when building libgcc. We disallow fptosi+sext for the
1567 const unsigned numCastOps =
1568 Instruction::CastOpsEnd - Instruction::CastOpsBegin;
1569 static const uint8_t CastResults[numCastOps][numCastOps] = {
1570 // T F F U S F F P I B -+
1571 // R Z S P P I I T P 2 N T |
1572 // U E E 2 2 2 2 R E I T C +- secondOp
1573 // N X X U S F F N X N 2 V |
1574 // C T T I I P P C T T P T -+
1575 { 1, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // Trunc -+
1576 { 8, 1, 9,99,99, 2, 0,99,99,99, 2, 3 }, // ZExt |
1577 { 8, 0, 1,99,99, 0, 2,99,99,99, 0, 3 }, // SExt |
1578 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // FPToUI |
1579 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // FPToSI |
1580 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4 }, // UIToFP +- firstOp
1581 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4 }, // SIToFP |
1582 { 99,99,99, 0, 0,99,99, 1, 0,99,99, 4 }, // FPTrunc |
1583 { 99,99,99, 2, 2,99,99,10, 2,99,99, 4 }, // FPExt |
1584 { 1, 0, 0,99,99, 0, 0,99,99,99, 7, 3 }, // PtrToInt |
1585 { 99,99,99,99,99,99,99,99,99,13,99,12 }, // IntToPtr |
1586 { 5, 5, 5, 6, 6, 5, 5, 6, 6,11, 5, 1 }, // BitCast -+
1589 int ElimCase = CastResults[firstOp-Instruction::CastOpsBegin]
1590 [secondOp-Instruction::CastOpsBegin];
1593 // categorically disallowed
1596 // allowed, use first cast's opcode
1599 // allowed, use second cast's opcode
1602 // no-op cast in second op implies firstOp as long as the DestTy
1604 if (DstTy->isInteger())
1608 // no-op cast in second op implies firstOp as long as the DestTy
1609 // is floating point
1610 if (DstTy->isFloatingPoint())
1614 // no-op cast in first op implies secondOp as long as the SrcTy
1616 if (SrcTy->isInteger())
1620 // no-op cast in first op implies secondOp as long as the SrcTy
1621 // is a floating point
1622 if (SrcTy->isFloatingPoint())
1626 // ptrtoint, inttoptr -> bitcast (ptr -> ptr) if int size is >= ptr size
1627 unsigned PtrSize = IntPtrTy->getPrimitiveSizeInBits();
1628 unsigned MidSize = MidTy->getPrimitiveSizeInBits();
1629 if (MidSize >= PtrSize)
1630 return Instruction::BitCast;
1634 // ext, trunc -> bitcast, if the SrcTy and DstTy are same size
1635 // ext, trunc -> ext, if sizeof(SrcTy) < sizeof(DstTy)
1636 // ext, trunc -> trunc, if sizeof(SrcTy) > sizeof(DstTy)
1637 unsigned SrcSize = SrcTy->getPrimitiveSizeInBits();
1638 unsigned DstSize = DstTy->getPrimitiveSizeInBits();
1639 if (SrcSize == DstSize)
1640 return Instruction::BitCast;
1641 else if (SrcSize < DstSize)
1645 case 9: // zext, sext -> zext, because sext can't sign extend after zext
1646 return Instruction::ZExt;
1648 // fpext followed by ftrunc is allowed if the bit size returned to is
1649 // the same as the original, in which case its just a bitcast
1651 return Instruction::BitCast;
1652 return 0; // If the types are not the same we can't eliminate it.
1654 // bitcast followed by ptrtoint is allowed as long as the bitcast
1655 // is a pointer to pointer cast.
1656 if (isa<PointerType>(SrcTy) && isa<PointerType>(MidTy))
1660 // inttoptr, bitcast -> intptr if bitcast is a ptr to ptr cast
1661 if (isa<PointerType>(MidTy) && isa<PointerType>(DstTy))
1665 // inttoptr, ptrtoint -> bitcast if SrcSize<=PtrSize and SrcSize==DstSize
1666 unsigned PtrSize = IntPtrTy->getPrimitiveSizeInBits();
1667 unsigned SrcSize = SrcTy->getPrimitiveSizeInBits();
1668 unsigned DstSize = DstTy->getPrimitiveSizeInBits();
1669 if (SrcSize <= PtrSize && SrcSize == DstSize)
1670 return Instruction::BitCast;
1674 // cast combination can't happen (error in input). This is for all cases
1675 // where the MidTy is not the same for the two cast instructions.
1676 assert(!"Invalid Cast Combination");
1679 assert(!"Error in CastResults table!!!");
1685 CastInst *CastInst::create(Instruction::CastOps op, Value *S, const Type *Ty,
1686 const std::string &Name, Instruction *InsertBefore) {
1687 // Construct and return the appropriate CastInst subclass
1689 case Trunc: return new TruncInst (S, Ty, Name, InsertBefore);
1690 case ZExt: return new ZExtInst (S, Ty, Name, InsertBefore);
1691 case SExt: return new SExtInst (S, Ty, Name, InsertBefore);
1692 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertBefore);
1693 case FPExt: return new FPExtInst (S, Ty, Name, InsertBefore);
1694 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertBefore);
1695 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertBefore);
1696 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertBefore);
1697 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertBefore);
1698 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertBefore);
1699 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertBefore);
1700 case BitCast: return new BitCastInst (S, Ty, Name, InsertBefore);
1702 assert(!"Invalid opcode provided");
1707 CastInst *CastInst::create(Instruction::CastOps op, Value *S, const Type *Ty,
1708 const std::string &Name, BasicBlock *InsertAtEnd) {
1709 // Construct and return the appropriate CastInst subclass
1711 case Trunc: return new TruncInst (S, Ty, Name, InsertAtEnd);
1712 case ZExt: return new ZExtInst (S, Ty, Name, InsertAtEnd);
1713 case SExt: return new SExtInst (S, Ty, Name, InsertAtEnd);
1714 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertAtEnd);
1715 case FPExt: return new FPExtInst (S, Ty, Name, InsertAtEnd);
1716 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertAtEnd);
1717 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertAtEnd);
1718 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertAtEnd);
1719 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertAtEnd);
1720 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertAtEnd);
1721 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertAtEnd);
1722 case BitCast: return new BitCastInst (S, Ty, Name, InsertAtEnd);
1724 assert(!"Invalid opcode provided");
1729 CastInst *CastInst::createZExtOrBitCast(Value *S, const Type *Ty,
1730 const std::string &Name,
1731 Instruction *InsertBefore) {
1732 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1733 return create(Instruction::BitCast, S, Ty, Name, InsertBefore);
1734 return create(Instruction::ZExt, S, Ty, Name, InsertBefore);
1737 CastInst *CastInst::createZExtOrBitCast(Value *S, const Type *Ty,
1738 const std::string &Name,
1739 BasicBlock *InsertAtEnd) {
1740 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1741 return create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
1742 return create(Instruction::ZExt, S, Ty, Name, InsertAtEnd);
1745 CastInst *CastInst::createSExtOrBitCast(Value *S, const Type *Ty,
1746 const std::string &Name,
1747 Instruction *InsertBefore) {
1748 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1749 return create(Instruction::BitCast, S, Ty, Name, InsertBefore);
1750 return create(Instruction::SExt, S, Ty, Name, InsertBefore);
1753 CastInst *CastInst::createSExtOrBitCast(Value *S, const Type *Ty,
1754 const std::string &Name,
1755 BasicBlock *InsertAtEnd) {
1756 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1757 return create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
1758 return create(Instruction::SExt, S, Ty, Name, InsertAtEnd);
1761 CastInst *CastInst::createTruncOrBitCast(Value *S, const Type *Ty,
1762 const std::string &Name,
1763 Instruction *InsertBefore) {
1764 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1765 return create(Instruction::BitCast, S, Ty, Name, InsertBefore);
1766 return create(Instruction::Trunc, S, Ty, Name, InsertBefore);
1769 CastInst *CastInst::createTruncOrBitCast(Value *S, const Type *Ty,
1770 const std::string &Name,
1771 BasicBlock *InsertAtEnd) {
1772 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1773 return create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
1774 return create(Instruction::Trunc, S, Ty, Name, InsertAtEnd);
1777 CastInst *CastInst::createPointerCast(Value *S, const Type *Ty,
1778 const std::string &Name,
1779 BasicBlock *InsertAtEnd) {
1780 assert(isa<PointerType>(S->getType()) && "Invalid cast");
1781 assert((Ty->isInteger() || isa<PointerType>(Ty)) &&
1784 if (Ty->isInteger())
1785 return create(Instruction::PtrToInt, S, Ty, Name, InsertAtEnd);
1786 return create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
1789 /// @brief Create a BitCast or a PtrToInt cast instruction
1790 CastInst *CastInst::createPointerCast(Value *S, const Type *Ty,
1791 const std::string &Name,
1792 Instruction *InsertBefore) {
1793 assert(isa<PointerType>(S->getType()) && "Invalid cast");
1794 assert((Ty->isInteger() || isa<PointerType>(Ty)) &&
1797 if (Ty->isInteger())
1798 return create(Instruction::PtrToInt, S, Ty, Name, InsertBefore);
1799 return create(Instruction::BitCast, S, Ty, Name, InsertBefore);
1802 CastInst *CastInst::createIntegerCast(Value *C, const Type *Ty,
1803 bool isSigned, const std::string &Name,
1804 Instruction *InsertBefore) {
1805 assert(C->getType()->isInteger() && Ty->isInteger() && "Invalid cast");
1806 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1807 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1808 Instruction::CastOps opcode =
1809 (SrcBits == DstBits ? Instruction::BitCast :
1810 (SrcBits > DstBits ? Instruction::Trunc :
1811 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1812 return create(opcode, C, Ty, Name, InsertBefore);
1815 CastInst *CastInst::createIntegerCast(Value *C, const Type *Ty,
1816 bool isSigned, const std::string &Name,
1817 BasicBlock *InsertAtEnd) {
1818 assert(C->getType()->isInteger() && Ty->isInteger() && "Invalid cast");
1819 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1820 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1821 Instruction::CastOps opcode =
1822 (SrcBits == DstBits ? Instruction::BitCast :
1823 (SrcBits > DstBits ? Instruction::Trunc :
1824 (isSigned ? Instruction::SExt : Instruction::ZExt)));
1825 return create(opcode, C, Ty, Name, InsertAtEnd);
1828 CastInst *CastInst::createFPCast(Value *C, const Type *Ty,
1829 const std::string &Name,
1830 Instruction *InsertBefore) {
1831 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1833 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1834 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1835 Instruction::CastOps opcode =
1836 (SrcBits == DstBits ? Instruction::BitCast :
1837 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
1838 return create(opcode, C, Ty, Name, InsertBefore);
1841 CastInst *CastInst::createFPCast(Value *C, const Type *Ty,
1842 const std::string &Name,
1843 BasicBlock *InsertAtEnd) {
1844 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
1846 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
1847 unsigned DstBits = Ty->getPrimitiveSizeInBits();
1848 Instruction::CastOps opcode =
1849 (SrcBits == DstBits ? Instruction::BitCast :
1850 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
1851 return create(opcode, C, Ty, Name, InsertAtEnd);
1854 // Provide a way to get a "cast" where the cast opcode is inferred from the
1855 // types and size of the operand. This, basically, is a parallel of the
1856 // logic in the castIsValid function below. This axiom should hold:
1857 // castIsValid( getCastOpcode(Val, Ty), Val, Ty)
1858 // should not assert in castIsValid. In other words, this produces a "correct"
1859 // casting opcode for the arguments passed to it.
1860 Instruction::CastOps
1861 CastInst::getCastOpcode(
1862 const Value *Src, bool SrcIsSigned, const Type *DestTy, bool DestIsSigned) {
1863 // Get the bit sizes, we'll need these
1864 const Type *SrcTy = Src->getType();
1865 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); // 0 for ptr/vector
1866 unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr/vector
1868 // Run through the possibilities ...
1869 if (DestTy->isInteger()) { // Casting to integral
1870 if (SrcTy->isInteger()) { // Casting from integral
1871 if (DestBits < SrcBits)
1872 return Trunc; // int -> smaller int
1873 else if (DestBits > SrcBits) { // its an extension
1875 return SExt; // signed -> SEXT
1877 return ZExt; // unsigned -> ZEXT
1879 return BitCast; // Same size, No-op cast
1881 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt
1883 return FPToSI; // FP -> sint
1885 return FPToUI; // FP -> uint
1886 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
1887 assert(DestBits == PTy->getBitWidth() &&
1888 "Casting vector to integer of different width");
1889 return BitCast; // Same size, no-op cast
1891 assert(isa<PointerType>(SrcTy) &&
1892 "Casting from a value that is not first-class type");
1893 return PtrToInt; // ptr -> int
1895 } else if (DestTy->isFloatingPoint()) { // Casting to floating pt
1896 if (SrcTy->isInteger()) { // Casting from integral
1898 return SIToFP; // sint -> FP
1900 return UIToFP; // uint -> FP
1901 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt
1902 if (DestBits < SrcBits) {
1903 return FPTrunc; // FP -> smaller FP
1904 } else if (DestBits > SrcBits) {
1905 return FPExt; // FP -> larger FP
1907 return BitCast; // same size, no-op cast
1909 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
1910 assert(DestBits == PTy->getBitWidth() &&
1911 "Casting vector to floating point of different width");
1912 return BitCast; // same size, no-op cast
1914 assert(0 && "Casting pointer or non-first class to float");
1916 } else if (const VectorType *DestPTy = dyn_cast<VectorType>(DestTy)) {
1917 if (const VectorType *SrcPTy = dyn_cast<VectorType>(SrcTy)) {
1918 assert(DestPTy->getBitWidth() == SrcPTy->getBitWidth() &&
1919 "Casting vector to vector of different widths");
1920 return BitCast; // vector -> vector
1921 } else if (DestPTy->getBitWidth() == SrcBits) {
1922 return BitCast; // float/int -> vector
1924 assert(!"Illegal cast to vector (wrong type or size)");
1926 } else if (isa<PointerType>(DestTy)) {
1927 if (isa<PointerType>(SrcTy)) {
1928 return BitCast; // ptr -> ptr
1929 } else if (SrcTy->isInteger()) {
1930 return IntToPtr; // int -> ptr
1932 assert(!"Casting pointer to other than pointer or int");
1935 assert(!"Casting to type that is not first-class");
1938 // If we fall through to here we probably hit an assertion cast above
1939 // and assertions are not turned on. Anything we return is an error, so
1940 // BitCast is as good a choice as any.
1944 //===----------------------------------------------------------------------===//
1945 // CastInst SubClass Constructors
1946 //===----------------------------------------------------------------------===//
1948 /// Check that the construction parameters for a CastInst are correct. This
1949 /// could be broken out into the separate constructors but it is useful to have
1950 /// it in one place and to eliminate the redundant code for getting the sizes
1951 /// of the types involved.
1953 CastInst::castIsValid(Instruction::CastOps op, Value *S, const Type *DstTy) {
1955 // Check for type sanity on the arguments
1956 const Type *SrcTy = S->getType();
1957 if (!SrcTy->isFirstClassType() || !DstTy->isFirstClassType())
1960 // Get the size of the types in bits, we'll need this later
1961 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
1962 unsigned DstBitSize = DstTy->getPrimitiveSizeInBits();
1964 // Switch on the opcode provided
1966 default: return false; // This is an input error
1967 case Instruction::Trunc:
1968 return SrcTy->isInteger() && DstTy->isInteger()&& SrcBitSize > DstBitSize;
1969 case Instruction::ZExt:
1970 return SrcTy->isInteger() && DstTy->isInteger()&& SrcBitSize < DstBitSize;
1971 case Instruction::SExt:
1972 return SrcTy->isInteger() && DstTy->isInteger()&& SrcBitSize < DstBitSize;
1973 case Instruction::FPTrunc:
1974 return SrcTy->isFloatingPoint() && DstTy->isFloatingPoint() &&
1975 SrcBitSize > DstBitSize;
1976 case Instruction::FPExt:
1977 return SrcTy->isFloatingPoint() && DstTy->isFloatingPoint() &&
1978 SrcBitSize < DstBitSize;
1979 case Instruction::UIToFP:
1980 case Instruction::SIToFP:
1981 if (const VectorType *SVTy = dyn_cast<VectorType>(SrcTy)) {
1982 if (const VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
1983 return SVTy->getElementType()->isInteger() &&
1984 DVTy->getElementType()->isFloatingPoint() &&
1985 SVTy->getNumElements() == DVTy->getNumElements();
1988 return SrcTy->isInteger() && DstTy->isFloatingPoint();
1989 case Instruction::FPToUI:
1990 case Instruction::FPToSI:
1991 if (const VectorType *SVTy = dyn_cast<VectorType>(SrcTy)) {
1992 if (const VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
1993 return SVTy->getElementType()->isFloatingPoint() &&
1994 DVTy->getElementType()->isInteger() &&
1995 SVTy->getNumElements() == DVTy->getNumElements();
1998 return SrcTy->isFloatingPoint() && DstTy->isInteger();
1999 case Instruction::PtrToInt:
2000 return isa<PointerType>(SrcTy) && DstTy->isInteger();
2001 case Instruction::IntToPtr:
2002 return SrcTy->isInteger() && isa<PointerType>(DstTy);
2003 case Instruction::BitCast:
2004 // BitCast implies a no-op cast of type only. No bits change.
2005 // However, you can't cast pointers to anything but pointers.
2006 if (isa<PointerType>(SrcTy) != isa<PointerType>(DstTy))
2009 // Now we know we're not dealing with a pointer/non-poiner mismatch. In all
2010 // these cases, the cast is okay if the source and destination bit widths
2012 return SrcBitSize == DstBitSize;
2016 TruncInst::TruncInst(
2017 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2018 ) : CastInst(Ty, Trunc, S, Name, InsertBefore) {
2019 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
2022 TruncInst::TruncInst(
2023 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2024 ) : CastInst(Ty, Trunc, S, Name, InsertAtEnd) {
2025 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
2029 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2030 ) : CastInst(Ty, ZExt, S, Name, InsertBefore) {
2031 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
2035 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2036 ) : CastInst(Ty, ZExt, S, Name, InsertAtEnd) {
2037 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
2040 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2041 ) : CastInst(Ty, SExt, S, Name, InsertBefore) {
2042 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
2046 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2047 ) : CastInst(Ty, SExt, S, Name, InsertAtEnd) {
2048 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
2051 FPTruncInst::FPTruncInst(
2052 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2053 ) : CastInst(Ty, FPTrunc, S, Name, InsertBefore) {
2054 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
2057 FPTruncInst::FPTruncInst(
2058 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2059 ) : CastInst(Ty, FPTrunc, S, Name, InsertAtEnd) {
2060 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
2063 FPExtInst::FPExtInst(
2064 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2065 ) : CastInst(Ty, FPExt, S, Name, InsertBefore) {
2066 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
2069 FPExtInst::FPExtInst(
2070 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2071 ) : CastInst(Ty, FPExt, S, Name, InsertAtEnd) {
2072 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
2075 UIToFPInst::UIToFPInst(
2076 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2077 ) : CastInst(Ty, UIToFP, S, Name, InsertBefore) {
2078 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
2081 UIToFPInst::UIToFPInst(
2082 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2083 ) : CastInst(Ty, UIToFP, S, Name, InsertAtEnd) {
2084 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
2087 SIToFPInst::SIToFPInst(
2088 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2089 ) : CastInst(Ty, SIToFP, S, Name, InsertBefore) {
2090 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
2093 SIToFPInst::SIToFPInst(
2094 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2095 ) : CastInst(Ty, SIToFP, S, Name, InsertAtEnd) {
2096 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
2099 FPToUIInst::FPToUIInst(
2100 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2101 ) : CastInst(Ty, FPToUI, S, Name, InsertBefore) {
2102 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
2105 FPToUIInst::FPToUIInst(
2106 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2107 ) : CastInst(Ty, FPToUI, S, Name, InsertAtEnd) {
2108 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
2111 FPToSIInst::FPToSIInst(
2112 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2113 ) : CastInst(Ty, FPToSI, S, Name, InsertBefore) {
2114 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
2117 FPToSIInst::FPToSIInst(
2118 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2119 ) : CastInst(Ty, FPToSI, S, Name, InsertAtEnd) {
2120 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
2123 PtrToIntInst::PtrToIntInst(
2124 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2125 ) : CastInst(Ty, PtrToInt, S, Name, InsertBefore) {
2126 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
2129 PtrToIntInst::PtrToIntInst(
2130 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2131 ) : CastInst(Ty, PtrToInt, S, Name, InsertAtEnd) {
2132 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
2135 IntToPtrInst::IntToPtrInst(
2136 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2137 ) : CastInst(Ty, IntToPtr, S, Name, InsertBefore) {
2138 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
2141 IntToPtrInst::IntToPtrInst(
2142 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2143 ) : CastInst(Ty, IntToPtr, S, Name, InsertAtEnd) {
2144 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
2147 BitCastInst::BitCastInst(
2148 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2149 ) : CastInst(Ty, BitCast, S, Name, InsertBefore) {
2150 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
2153 BitCastInst::BitCastInst(
2154 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2155 ) : CastInst(Ty, BitCast, S, Name, InsertAtEnd) {
2156 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
2159 //===----------------------------------------------------------------------===//
2161 //===----------------------------------------------------------------------===//
2163 CmpInst::CmpInst(OtherOps op, unsigned short predicate, Value *LHS, Value *RHS,
2164 const std::string &Name, Instruction *InsertBefore)
2165 : Instruction(Type::Int1Ty, op, Ops, 2, InsertBefore) {
2166 Ops[0].init(LHS, this);
2167 Ops[1].init(RHS, this);
2168 SubclassData = predicate;
2170 if (op == Instruction::ICmp) {
2171 assert(predicate >= ICmpInst::FIRST_ICMP_PREDICATE &&
2172 predicate <= ICmpInst::LAST_ICMP_PREDICATE &&
2173 "Invalid ICmp predicate value");
2174 const Type* Op0Ty = getOperand(0)->getType();
2175 const Type* Op1Ty = getOperand(1)->getType();
2176 assert(Op0Ty == Op1Ty &&
2177 "Both operands to ICmp instruction are not of the same type!");
2178 // Check that the operands are the right type
2179 assert((Op0Ty->isInteger() || isa<PointerType>(Op0Ty)) &&
2180 "Invalid operand types for ICmp instruction");
2183 assert(op == Instruction::FCmp && "Invalid CmpInst opcode");
2184 assert(predicate <= FCmpInst::LAST_FCMP_PREDICATE &&
2185 "Invalid FCmp predicate value");
2186 const Type* Op0Ty = getOperand(0)->getType();
2187 const Type* Op1Ty = getOperand(1)->getType();
2188 assert(Op0Ty == Op1Ty &&
2189 "Both operands to FCmp instruction are not of the same type!");
2190 // Check that the operands are the right type
2191 assert(Op0Ty->isFloatingPoint() &&
2192 "Invalid operand types for FCmp instruction");
2195 CmpInst::CmpInst(OtherOps op, unsigned short predicate, Value *LHS, Value *RHS,
2196 const std::string &Name, BasicBlock *InsertAtEnd)
2197 : Instruction(Type::Int1Ty, op, Ops, 2, InsertAtEnd) {
2198 Ops[0].init(LHS, this);
2199 Ops[1].init(RHS, this);
2200 SubclassData = predicate;
2202 if (op == Instruction::ICmp) {
2203 assert(predicate >= ICmpInst::FIRST_ICMP_PREDICATE &&
2204 predicate <= ICmpInst::LAST_ICMP_PREDICATE &&
2205 "Invalid ICmp predicate value");
2207 const Type* Op0Ty = getOperand(0)->getType();
2208 const Type* Op1Ty = getOperand(1)->getType();
2209 assert(Op0Ty == Op1Ty &&
2210 "Both operands to ICmp instruction are not of the same type!");
2211 // Check that the operands are the right type
2212 assert(Op0Ty->isInteger() || isa<PointerType>(Op0Ty) &&
2213 "Invalid operand types for ICmp instruction");
2216 assert(op == Instruction::FCmp && "Invalid CmpInst opcode");
2217 assert(predicate <= FCmpInst::LAST_FCMP_PREDICATE &&
2218 "Invalid FCmp predicate value");
2219 const Type* Op0Ty = getOperand(0)->getType();
2220 const Type* Op1Ty = getOperand(1)->getType();
2221 assert(Op0Ty == Op1Ty &&
2222 "Both operands to FCmp instruction are not of the same type!");
2223 // Check that the operands are the right type
2224 assert(Op0Ty->isFloatingPoint() &&
2225 "Invalid operand types for FCmp instruction");
2229 CmpInst::create(OtherOps Op, unsigned short predicate, Value *S1, Value *S2,
2230 const std::string &Name, Instruction *InsertBefore) {
2231 if (Op == Instruction::ICmp) {
2232 return new ICmpInst(ICmpInst::Predicate(predicate), S1, S2, Name,
2235 return new FCmpInst(FCmpInst::Predicate(predicate), S1, S2, Name,
2240 CmpInst::create(OtherOps Op, unsigned short predicate, Value *S1, Value *S2,
2241 const std::string &Name, BasicBlock *InsertAtEnd) {
2242 if (Op == Instruction::ICmp) {
2243 return new ICmpInst(ICmpInst::Predicate(predicate), S1, S2, Name,
2246 return new FCmpInst(FCmpInst::Predicate(predicate), S1, S2, Name,
2250 void CmpInst::swapOperands() {
2251 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2254 cast<FCmpInst>(this)->swapOperands();
2257 bool CmpInst::isCommutative() {
2258 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2259 return IC->isCommutative();
2260 return cast<FCmpInst>(this)->isCommutative();
2263 bool CmpInst::isEquality() {
2264 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2265 return IC->isEquality();
2266 return cast<FCmpInst>(this)->isEquality();
2270 ICmpInst::Predicate ICmpInst::getInversePredicate(Predicate pred) {
2273 assert(!"Unknown icmp predicate!");
2274 case ICMP_EQ: return ICMP_NE;
2275 case ICMP_NE: return ICMP_EQ;
2276 case ICMP_UGT: return ICMP_ULE;
2277 case ICMP_ULT: return ICMP_UGE;
2278 case ICMP_UGE: return ICMP_ULT;
2279 case ICMP_ULE: return ICMP_UGT;
2280 case ICMP_SGT: return ICMP_SLE;
2281 case ICMP_SLT: return ICMP_SGE;
2282 case ICMP_SGE: return ICMP_SLT;
2283 case ICMP_SLE: return ICMP_SGT;
2287 ICmpInst::Predicate ICmpInst::getSwappedPredicate(Predicate pred) {
2289 default: assert(! "Unknown icmp predicate!");
2290 case ICMP_EQ: case ICMP_NE:
2292 case ICMP_SGT: return ICMP_SLT;
2293 case ICMP_SLT: return ICMP_SGT;
2294 case ICMP_SGE: return ICMP_SLE;
2295 case ICMP_SLE: return ICMP_SGE;
2296 case ICMP_UGT: return ICMP_ULT;
2297 case ICMP_ULT: return ICMP_UGT;
2298 case ICMP_UGE: return ICMP_ULE;
2299 case ICMP_ULE: return ICMP_UGE;
2303 ICmpInst::Predicate ICmpInst::getSignedPredicate(Predicate pred) {
2305 default: assert(! "Unknown icmp predicate!");
2306 case ICMP_EQ: case ICMP_NE:
2307 case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE:
2309 case ICMP_UGT: return ICMP_SGT;
2310 case ICMP_ULT: return ICMP_SLT;
2311 case ICMP_UGE: return ICMP_SGE;
2312 case ICMP_ULE: return ICMP_SLE;
2316 bool ICmpInst::isSignedPredicate(Predicate pred) {
2318 default: assert(! "Unknown icmp predicate!");
2319 case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE:
2321 case ICMP_EQ: case ICMP_NE: case ICMP_UGT: case ICMP_ULT:
2322 case ICMP_UGE: case ICMP_ULE:
2327 /// Initialize a set of values that all satisfy the condition with C.
2330 ICmpInst::makeConstantRange(Predicate pred, const APInt &C) {
2333 uint32_t BitWidth = C.getBitWidth();
2335 default: assert(0 && "Invalid ICmp opcode to ConstantRange ctor!");
2336 case ICmpInst::ICMP_EQ: Upper++; break;
2337 case ICmpInst::ICMP_NE: Lower++; break;
2338 case ICmpInst::ICMP_ULT: Lower = APInt::getMinValue(BitWidth); break;
2339 case ICmpInst::ICMP_SLT: Lower = APInt::getSignedMinValue(BitWidth); break;
2340 case ICmpInst::ICMP_UGT:
2341 Lower++; Upper = APInt::getMinValue(BitWidth); // Min = Next(Max)
2343 case ICmpInst::ICMP_SGT:
2344 Lower++; Upper = APInt::getSignedMinValue(BitWidth); // Min = Next(Max)
2346 case ICmpInst::ICMP_ULE:
2347 Lower = APInt::getMinValue(BitWidth); Upper++;
2349 case ICmpInst::ICMP_SLE:
2350 Lower = APInt::getSignedMinValue(BitWidth); Upper++;
2352 case ICmpInst::ICMP_UGE:
2353 Upper = APInt::getMinValue(BitWidth); // Min = Next(Max)
2355 case ICmpInst::ICMP_SGE:
2356 Upper = APInt::getSignedMinValue(BitWidth); // Min = Next(Max)
2359 return ConstantRange(Lower, Upper);
2362 FCmpInst::Predicate FCmpInst::getInversePredicate(Predicate pred) {
2365 assert(!"Unknown icmp predicate!");
2366 case FCMP_OEQ: return FCMP_UNE;
2367 case FCMP_ONE: return FCMP_UEQ;
2368 case FCMP_OGT: return FCMP_ULE;
2369 case FCMP_OLT: return FCMP_UGE;
2370 case FCMP_OGE: return FCMP_ULT;
2371 case FCMP_OLE: return FCMP_UGT;
2372 case FCMP_UEQ: return FCMP_ONE;
2373 case FCMP_UNE: return FCMP_OEQ;
2374 case FCMP_UGT: return FCMP_OLE;
2375 case FCMP_ULT: return FCMP_OGE;
2376 case FCMP_UGE: return FCMP_OLT;
2377 case FCMP_ULE: return FCMP_OGT;
2378 case FCMP_ORD: return FCMP_UNO;
2379 case FCMP_UNO: return FCMP_ORD;
2380 case FCMP_TRUE: return FCMP_FALSE;
2381 case FCMP_FALSE: return FCMP_TRUE;
2385 FCmpInst::Predicate FCmpInst::getSwappedPredicate(Predicate pred) {
2387 default: assert(!"Unknown fcmp predicate!");
2388 case FCMP_FALSE: case FCMP_TRUE:
2389 case FCMP_OEQ: case FCMP_ONE:
2390 case FCMP_UEQ: case FCMP_UNE:
2391 case FCMP_ORD: case FCMP_UNO:
2393 case FCMP_OGT: return FCMP_OLT;
2394 case FCMP_OLT: return FCMP_OGT;
2395 case FCMP_OGE: return FCMP_OLE;
2396 case FCMP_OLE: return FCMP_OGE;
2397 case FCMP_UGT: return FCMP_ULT;
2398 case FCMP_ULT: return FCMP_UGT;
2399 case FCMP_UGE: return FCMP_ULE;
2400 case FCMP_ULE: return FCMP_UGE;
2404 bool CmpInst::isUnsigned(unsigned short predicate) {
2405 switch (predicate) {
2406 default: return false;
2407 case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_ULE: case ICmpInst::ICMP_UGT:
2408 case ICmpInst::ICMP_UGE: return true;
2412 bool CmpInst::isSigned(unsigned short predicate){
2413 switch (predicate) {
2414 default: return false;
2415 case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_SLE: case ICmpInst::ICMP_SGT:
2416 case ICmpInst::ICMP_SGE: return true;
2420 bool CmpInst::isOrdered(unsigned short predicate) {
2421 switch (predicate) {
2422 default: return false;
2423 case FCmpInst::FCMP_OEQ: case FCmpInst::FCMP_ONE: case FCmpInst::FCMP_OGT:
2424 case FCmpInst::FCMP_OLT: case FCmpInst::FCMP_OGE: case FCmpInst::FCMP_OLE:
2425 case FCmpInst::FCMP_ORD: return true;
2429 bool CmpInst::isUnordered(unsigned short predicate) {
2430 switch (predicate) {
2431 default: return false;
2432 case FCmpInst::FCMP_UEQ: case FCmpInst::FCMP_UNE: case FCmpInst::FCMP_UGT:
2433 case FCmpInst::FCMP_ULT: case FCmpInst::FCMP_UGE: case FCmpInst::FCMP_ULE:
2434 case FCmpInst::FCMP_UNO: return true;
2438 //===----------------------------------------------------------------------===//
2439 // SwitchInst Implementation
2440 //===----------------------------------------------------------------------===//
2442 void SwitchInst::init(Value *Value, BasicBlock *Default, unsigned NumCases) {
2443 assert(Value && Default);
2444 ReservedSpace = 2+NumCases*2;
2446 OperandList = new Use[ReservedSpace];
2448 OperandList[0].init(Value, this);
2449 OperandList[1].init(Default, this);
2452 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
2453 /// switch on and a default destination. The number of additional cases can
2454 /// be specified here to make memory allocation more efficient. This
2455 /// constructor can also autoinsert before another instruction.
2456 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
2457 Instruction *InsertBefore)
2458 : TerminatorInst(Type::VoidTy, Instruction::Switch, 0, 0, InsertBefore) {
2459 init(Value, Default, NumCases);
2462 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
2463 /// switch on and a default destination. The number of additional cases can
2464 /// be specified here to make memory allocation more efficient. This
2465 /// constructor also autoinserts at the end of the specified BasicBlock.
2466 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
2467 BasicBlock *InsertAtEnd)
2468 : TerminatorInst(Type::VoidTy, Instruction::Switch, 0, 0, InsertAtEnd) {
2469 init(Value, Default, NumCases);
2472 SwitchInst::SwitchInst(const SwitchInst &SI)
2473 : TerminatorInst(Type::VoidTy, Instruction::Switch,
2474 new Use[SI.getNumOperands()], SI.getNumOperands()) {
2475 Use *OL = OperandList, *InOL = SI.OperandList;
2476 for (unsigned i = 0, E = SI.getNumOperands(); i != E; i+=2) {
2477 OL[i].init(InOL[i], this);
2478 OL[i+1].init(InOL[i+1], this);
2482 SwitchInst::~SwitchInst() {
2483 delete [] OperandList;
2487 /// addCase - Add an entry to the switch instruction...
2489 void SwitchInst::addCase(ConstantInt *OnVal, BasicBlock *Dest) {
2490 unsigned OpNo = NumOperands;
2491 if (OpNo+2 > ReservedSpace)
2492 resizeOperands(0); // Get more space!
2493 // Initialize some new operands.
2494 assert(OpNo+1 < ReservedSpace && "Growing didn't work!");
2495 NumOperands = OpNo+2;
2496 OperandList[OpNo].init(OnVal, this);
2497 OperandList[OpNo+1].init(Dest, this);
2500 /// removeCase - This method removes the specified successor from the switch
2501 /// instruction. Note that this cannot be used to remove the default
2502 /// destination (successor #0).
2504 void SwitchInst::removeCase(unsigned idx) {
2505 assert(idx != 0 && "Cannot remove the default case!");
2506 assert(idx*2 < getNumOperands() && "Successor index out of range!!!");
2508 unsigned NumOps = getNumOperands();
2509 Use *OL = OperandList;
2511 // Move everything after this operand down.
2513 // FIXME: we could just swap with the end of the list, then erase. However,
2514 // client might not expect this to happen. The code as it is thrashes the
2515 // use/def lists, which is kinda lame.
2516 for (unsigned i = (idx+1)*2; i != NumOps; i += 2) {
2518 OL[i-2+1] = OL[i+1];
2521 // Nuke the last value.
2522 OL[NumOps-2].set(0);
2523 OL[NumOps-2+1].set(0);
2524 NumOperands = NumOps-2;
2527 /// resizeOperands - resize operands - This adjusts the length of the operands
2528 /// list according to the following behavior:
2529 /// 1. If NumOps == 0, grow the operand list in response to a push_back style
2530 /// of operation. This grows the number of ops by 1.5 times.
2531 /// 2. If NumOps > NumOperands, reserve space for NumOps operands.
2532 /// 3. If NumOps == NumOperands, trim the reserved space.
2534 void SwitchInst::resizeOperands(unsigned NumOps) {
2536 NumOps = getNumOperands()/2*6;
2537 } else if (NumOps*2 > NumOperands) {
2538 // No resize needed.
2539 if (ReservedSpace >= NumOps) return;
2540 } else if (NumOps == NumOperands) {
2541 if (ReservedSpace == NumOps) return;
2546 ReservedSpace = NumOps;
2547 Use *NewOps = new Use[NumOps];
2548 Use *OldOps = OperandList;
2549 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2550 NewOps[i].init(OldOps[i], this);
2554 OperandList = NewOps;
2558 BasicBlock *SwitchInst::getSuccessorV(unsigned idx) const {
2559 return getSuccessor(idx);
2561 unsigned SwitchInst::getNumSuccessorsV() const {
2562 return getNumSuccessors();
2564 void SwitchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
2565 setSuccessor(idx, B);
2569 // Define these methods here so vtables don't get emitted into every translation
2570 // unit that uses these classes.
2572 GetElementPtrInst *GetElementPtrInst::clone() const {
2573 return new GetElementPtrInst(*this);
2576 BinaryOperator *BinaryOperator::clone() const {
2577 return create(getOpcode(), Ops[0], Ops[1]);
2580 FCmpInst* FCmpInst::clone() const {
2581 return new FCmpInst(getPredicate(), Ops[0], Ops[1]);
2583 ICmpInst* ICmpInst::clone() const {
2584 return new ICmpInst(getPredicate(), Ops[0], Ops[1]);
2587 MallocInst *MallocInst::clone() const { return new MallocInst(*this); }
2588 AllocaInst *AllocaInst::clone() const { return new AllocaInst(*this); }
2589 FreeInst *FreeInst::clone() const { return new FreeInst(getOperand(0)); }
2590 LoadInst *LoadInst::clone() const { return new LoadInst(*this); }
2591 StoreInst *StoreInst::clone() const { return new StoreInst(*this); }
2592 CastInst *TruncInst::clone() const { return new TruncInst(*this); }
2593 CastInst *ZExtInst::clone() const { return new ZExtInst(*this); }
2594 CastInst *SExtInst::clone() const { return new SExtInst(*this); }
2595 CastInst *FPTruncInst::clone() const { return new FPTruncInst(*this); }
2596 CastInst *FPExtInst::clone() const { return new FPExtInst(*this); }
2597 CastInst *UIToFPInst::clone() const { return new UIToFPInst(*this); }
2598 CastInst *SIToFPInst::clone() const { return new SIToFPInst(*this); }
2599 CastInst *FPToUIInst::clone() const { return new FPToUIInst(*this); }
2600 CastInst *FPToSIInst::clone() const { return new FPToSIInst(*this); }
2601 CastInst *PtrToIntInst::clone() const { return new PtrToIntInst(*this); }
2602 CastInst *IntToPtrInst::clone() const { return new IntToPtrInst(*this); }
2603 CastInst *BitCastInst::clone() const { return new BitCastInst(*this); }
2604 CallInst *CallInst::clone() const { return new CallInst(*this); }
2605 SelectInst *SelectInst::clone() const { return new SelectInst(*this); }
2606 VAArgInst *VAArgInst::clone() const { return new VAArgInst(*this); }
2608 ExtractElementInst *ExtractElementInst::clone() const {
2609 return new ExtractElementInst(*this);
2611 InsertElementInst *InsertElementInst::clone() const {
2612 return new InsertElementInst(*this);
2614 ShuffleVectorInst *ShuffleVectorInst::clone() const {
2615 return new ShuffleVectorInst(*this);
2617 PHINode *PHINode::clone() const { return new PHINode(*this); }
2618 ReturnInst *ReturnInst::clone() const { return new ReturnInst(*this); }
2619 BranchInst *BranchInst::clone() const { return new BranchInst(*this); }
2620 SwitchInst *SwitchInst::clone() const { return new SwitchInst(*this); }
2621 InvokeInst *InvokeInst::clone() const { return new InvokeInst(*this); }
2622 UnwindInst *UnwindInst::clone() const { return new UnwindInst(); }
2623 UnreachableInst *UnreachableInst::clone() const { return new UnreachableInst();}