1 //===-- Instructions.cpp - Implement the LLVM instructions ----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // 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/Constants.h"
16 #include "llvm/DerivedTypes.h"
17 #include "llvm/Function.h"
18 #include "llvm/Instructions.h"
19 #include "llvm/Support/CallSite.h"
20 #include "llvm/Support/ConstantRange.h"
21 #include "llvm/Support/MathExtras.h"
24 //===----------------------------------------------------------------------===//
26 //===----------------------------------------------------------------------===//
28 CallSite::CallSite(Instruction *C) {
29 assert((isa<CallInst>(C) || isa<InvokeInst>(C)) && "Not a call!");
32 unsigned CallSite::getCallingConv() const {
33 if (CallInst *CI = dyn_cast<CallInst>(I))
34 return CI->getCallingConv();
36 return cast<InvokeInst>(I)->getCallingConv();
38 void CallSite::setCallingConv(unsigned CC) {
39 if (CallInst *CI = dyn_cast<CallInst>(I))
40 CI->setCallingConv(CC);
42 cast<InvokeInst>(I)->setCallingConv(CC);
44 const PAListPtr &CallSite::getParamAttrs() const {
45 if (CallInst *CI = dyn_cast<CallInst>(I))
46 return CI->getParamAttrs();
48 return cast<InvokeInst>(I)->getParamAttrs();
50 void CallSite::setParamAttrs(const PAListPtr &PAL) {
51 if (CallInst *CI = dyn_cast<CallInst>(I))
52 CI->setParamAttrs(PAL);
54 cast<InvokeInst>(I)->setParamAttrs(PAL);
56 bool CallSite::paramHasAttr(uint16_t i, ParameterAttributes attr) const {
57 if (CallInst *CI = dyn_cast<CallInst>(I))
58 return CI->paramHasAttr(i, attr);
60 return cast<InvokeInst>(I)->paramHasAttr(i, attr);
62 uint16_t CallSite::getParamAlignment(uint16_t i) const {
63 if (CallInst *CI = dyn_cast<CallInst>(I))
64 return CI->getParamAlignment(i);
66 return cast<InvokeInst>(I)->getParamAlignment(i);
69 bool CallSite::doesNotAccessMemory() const {
70 if (CallInst *CI = dyn_cast<CallInst>(I))
71 return CI->doesNotAccessMemory();
73 return cast<InvokeInst>(I)->doesNotAccessMemory();
75 bool CallSite::onlyReadsMemory() const {
76 if (CallInst *CI = dyn_cast<CallInst>(I))
77 return CI->onlyReadsMemory();
79 return cast<InvokeInst>(I)->onlyReadsMemory();
81 bool CallSite::doesNotThrow() const {
82 if (CallInst *CI = dyn_cast<CallInst>(I))
83 return CI->doesNotThrow();
85 return cast<InvokeInst>(I)->doesNotThrow();
87 void CallSite::setDoesNotThrow(bool doesNotThrow) {
88 if (CallInst *CI = dyn_cast<CallInst>(I))
89 CI->setDoesNotThrow(doesNotThrow);
91 cast<InvokeInst>(I)->setDoesNotThrow(doesNotThrow);
94 //===----------------------------------------------------------------------===//
95 // TerminatorInst Class
96 //===----------------------------------------------------------------------===//
98 // Out of line virtual method, so the vtable, etc has a home.
99 TerminatorInst::~TerminatorInst() {
102 //===----------------------------------------------------------------------===//
103 // UnaryInstruction Class
104 //===----------------------------------------------------------------------===//
106 // Out of line virtual method, so the vtable, etc has a home.
107 UnaryInstruction::~UnaryInstruction() {
110 //===----------------------------------------------------------------------===//
112 //===----------------------------------------------------------------------===//
114 PHINode::PHINode(const PHINode &PN)
115 : Instruction(PN.getType(), Instruction::PHI,
116 allocHungoffUses(PN.getNumOperands()), PN.getNumOperands()),
117 ReservedSpace(PN.getNumOperands()) {
118 Use *OL = OperandList;
119 for (unsigned i = 0, e = PN.getNumOperands(); i != e; i+=2) {
120 OL[i] = PN.getOperand(i);
121 OL[i+1] = PN.getOperand(i+1);
125 PHINode::~PHINode() {
126 dropHungoffUses(OperandList);
129 // removeIncomingValue - Remove an incoming value. This is useful if a
130 // predecessor basic block is deleted.
131 Value *PHINode::removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty) {
132 unsigned NumOps = getNumOperands();
133 Use *OL = OperandList;
134 assert(Idx*2 < NumOps && "BB not in PHI node!");
135 Value *Removed = OL[Idx*2];
137 // Move everything after this operand down.
139 // FIXME: we could just swap with the end of the list, then erase. However,
140 // client might not expect this to happen. The code as it is thrashes the
141 // use/def lists, which is kinda lame.
142 for (unsigned i = (Idx+1)*2; i != NumOps; i += 2) {
147 // Nuke the last value.
149 OL[NumOps-2+1].set(0);
150 NumOperands = NumOps-2;
152 // If the PHI node is dead, because it has zero entries, nuke it now.
153 if (NumOps == 2 && DeletePHIIfEmpty) {
154 // If anyone is using this PHI, make them use a dummy value instead...
155 replaceAllUsesWith(UndefValue::get(getType()));
161 /// resizeOperands - resize operands - This adjusts the length of the operands
162 /// list according to the following behavior:
163 /// 1. If NumOps == 0, grow the operand list in response to a push_back style
164 /// of operation. This grows the number of ops by 1.5 times.
165 /// 2. If NumOps > NumOperands, reserve space for NumOps operands.
166 /// 3. If NumOps == NumOperands, trim the reserved space.
168 void PHINode::resizeOperands(unsigned NumOps) {
169 unsigned e = getNumOperands();
172 if (NumOps < 4) NumOps = 4; // 4 op PHI nodes are VERY common.
173 } else if (NumOps*2 > NumOperands) {
175 if (ReservedSpace >= NumOps) return;
176 } else if (NumOps == NumOperands) {
177 if (ReservedSpace == NumOps) return;
182 ReservedSpace = NumOps;
183 Use *OldOps = OperandList;
184 Use *NewOps = allocHungoffUses(NumOps);
185 for (unsigned i = 0; i != e; ++i) {
186 NewOps[i] = OldOps[i];
188 OperandList = NewOps;
189 if (OldOps) Use::zap(OldOps, OldOps + e, true);
192 /// hasConstantValue - If the specified PHI node always merges together the same
193 /// value, return the value, otherwise return null.
195 Value *PHINode::hasConstantValue(bool AllowNonDominatingInstruction) const {
196 // If the PHI node only has one incoming value, eliminate the PHI node...
197 if (getNumIncomingValues() == 1) {
198 if (getIncomingValue(0) != this) // not X = phi X
199 return getIncomingValue(0);
201 return UndefValue::get(getType()); // Self cycle is dead.
204 // Otherwise if all of the incoming values are the same for the PHI, replace
205 // the PHI node with the incoming value.
208 bool HasUndefInput = false;
209 for (unsigned i = 0, e = getNumIncomingValues(); i != e; ++i)
210 if (isa<UndefValue>(getIncomingValue(i))) {
211 HasUndefInput = true;
212 } else if (getIncomingValue(i) != this) { // Not the PHI node itself...
213 if (InVal && getIncomingValue(i) != InVal)
214 return 0; // Not the same, bail out.
216 InVal = getIncomingValue(i);
219 // The only case that could cause InVal to be null is if we have a PHI node
220 // that only has entries for itself. In this case, there is no entry into the
221 // loop, so kill the PHI.
223 if (InVal == 0) InVal = UndefValue::get(getType());
225 // If we have a PHI node like phi(X, undef, X), where X is defined by some
226 // instruction, we cannot always return X as the result of the PHI node. Only
227 // do this if X is not an instruction (thus it must dominate the PHI block),
228 // or if the client is prepared to deal with this possibility.
229 if (HasUndefInput && !AllowNonDominatingInstruction)
230 if (Instruction *IV = dyn_cast<Instruction>(InVal))
231 // If it's in the entry block, it dominates everything.
232 if (IV->getParent() != &IV->getParent()->getParent()->getEntryBlock() ||
234 return 0; // Cannot guarantee that InVal dominates this PHINode.
236 // All of the incoming values are the same, return the value now.
241 //===----------------------------------------------------------------------===//
242 // CallInst Implementation
243 //===----------------------------------------------------------------------===//
245 CallInst::~CallInst() {
248 void CallInst::init(Value *Func, Value* const *Params, unsigned NumParams) {
249 assert(NumOperands == NumParams+1 && "NumOperands not set up?");
250 Use *OL = OperandList;
253 const FunctionType *FTy =
254 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
255 FTy = FTy; // silence warning.
257 assert((NumParams == FTy->getNumParams() ||
258 (FTy->isVarArg() && NumParams > FTy->getNumParams())) &&
259 "Calling a function with bad signature!");
260 for (unsigned i = 0; i != NumParams; ++i) {
261 assert((i >= FTy->getNumParams() ||
262 FTy->getParamType(i) == Params[i]->getType()) &&
263 "Calling a function with a bad signature!");
268 void CallInst::init(Value *Func, Value *Actual1, Value *Actual2) {
269 assert(NumOperands == 3 && "NumOperands not set up?");
270 Use *OL = OperandList;
275 const FunctionType *FTy =
276 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
277 FTy = FTy; // silence warning.
279 assert((FTy->getNumParams() == 2 ||
280 (FTy->isVarArg() && FTy->getNumParams() < 2)) &&
281 "Calling a function with bad signature");
282 assert((0 >= FTy->getNumParams() ||
283 FTy->getParamType(0) == Actual1->getType()) &&
284 "Calling a function with a bad signature!");
285 assert((1 >= FTy->getNumParams() ||
286 FTy->getParamType(1) == Actual2->getType()) &&
287 "Calling a function with a bad signature!");
290 void CallInst::init(Value *Func, Value *Actual) {
291 assert(NumOperands == 2 && "NumOperands not set up?");
292 Use *OL = OperandList;
296 const FunctionType *FTy =
297 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
298 FTy = FTy; // silence warning.
300 assert((FTy->getNumParams() == 1 ||
301 (FTy->isVarArg() && FTy->getNumParams() == 0)) &&
302 "Calling a function with bad signature");
303 assert((0 == FTy->getNumParams() ||
304 FTy->getParamType(0) == Actual->getType()) &&
305 "Calling a function with a bad signature!");
308 void CallInst::init(Value *Func) {
309 assert(NumOperands == 1 && "NumOperands not set up?");
310 Use *OL = OperandList;
313 const FunctionType *FTy =
314 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
315 FTy = FTy; // silence warning.
317 assert(FTy->getNumParams() == 0 && "Calling a function with bad signature");
320 CallInst::CallInst(Value *Func, Value* Actual, const std::string &Name,
321 Instruction *InsertBefore)
322 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
323 ->getElementType())->getReturnType(),
325 OperandTraits<CallInst>::op_end(this) - 2,
331 CallInst::CallInst(Value *Func, Value* Actual, const std::string &Name,
332 BasicBlock *InsertAtEnd)
333 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
334 ->getElementType())->getReturnType(),
336 OperandTraits<CallInst>::op_end(this) - 2,
341 CallInst::CallInst(Value *Func, const std::string &Name,
342 Instruction *InsertBefore)
343 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
344 ->getElementType())->getReturnType(),
346 OperandTraits<CallInst>::op_end(this) - 1,
352 CallInst::CallInst(Value *Func, const std::string &Name,
353 BasicBlock *InsertAtEnd)
354 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
355 ->getElementType())->getReturnType(),
357 OperandTraits<CallInst>::op_end(this) - 1,
363 CallInst::CallInst(const CallInst &CI)
364 : Instruction(CI.getType(), Instruction::Call,
365 OperandTraits<CallInst>::op_end(this) - CI.getNumOperands(),
366 CI.getNumOperands()) {
367 setParamAttrs(CI.getParamAttrs());
368 SubclassData = CI.SubclassData;
369 Use *OL = OperandList;
370 Use *InOL = CI.OperandList;
371 for (unsigned i = 0, e = CI.getNumOperands(); i != e; ++i)
375 void CallInst::addParamAttr(unsigned i, ParameterAttributes attr) {
376 PAListPtr PAL = getParamAttrs();
377 PAL = PAL.addAttr(i, attr);
381 bool CallInst::paramHasAttr(unsigned i, ParameterAttributes attr) const {
382 if (ParamAttrs.paramHasAttr(i, attr))
384 if (const Function *F = getCalledFunction())
385 return F->paramHasAttr(i, attr);
389 void CallInst::setDoesNotThrow(bool doesNotThrow) {
390 PAListPtr PAL = getParamAttrs();
392 PAL = PAL.addAttr(0, ParamAttr::NoUnwind);
394 PAL = PAL.removeAttr(0, ParamAttr::NoUnwind);
399 //===----------------------------------------------------------------------===//
400 // InvokeInst Implementation
401 //===----------------------------------------------------------------------===//
403 void InvokeInst::init(Value *Fn, BasicBlock *IfNormal, BasicBlock *IfException,
404 Value* const *Args, unsigned NumArgs) {
405 assert(NumOperands == 3+NumArgs && "NumOperands not set up?");
406 Use *OL = OperandList;
410 const FunctionType *FTy =
411 cast<FunctionType>(cast<PointerType>(Fn->getType())->getElementType());
412 FTy = FTy; // silence warning.
414 assert(((NumArgs == FTy->getNumParams()) ||
415 (FTy->isVarArg() && NumArgs > FTy->getNumParams())) &&
416 "Calling a function with bad signature");
418 for (unsigned i = 0, e = NumArgs; i != e; i++) {
419 assert((i >= FTy->getNumParams() ||
420 FTy->getParamType(i) == Args[i]->getType()) &&
421 "Invoking a function with a bad signature!");
427 InvokeInst::InvokeInst(const InvokeInst &II)
428 : TerminatorInst(II.getType(), Instruction::Invoke,
429 OperandTraits<InvokeInst>::op_end(this)
430 - II.getNumOperands(),
431 II.getNumOperands()) {
432 setParamAttrs(II.getParamAttrs());
433 SubclassData = II.SubclassData;
434 Use *OL = OperandList, *InOL = II.OperandList;
435 for (unsigned i = 0, e = II.getNumOperands(); i != e; ++i)
439 BasicBlock *InvokeInst::getSuccessorV(unsigned idx) const {
440 return getSuccessor(idx);
442 unsigned InvokeInst::getNumSuccessorsV() const {
443 return getNumSuccessors();
445 void InvokeInst::setSuccessorV(unsigned idx, BasicBlock *B) {
446 return setSuccessor(idx, B);
449 bool InvokeInst::paramHasAttr(unsigned i, ParameterAttributes attr) const {
450 if (ParamAttrs.paramHasAttr(i, attr))
452 if (const Function *F = getCalledFunction())
453 return F->paramHasAttr(i, attr);
457 void InvokeInst::addParamAttr(unsigned i, ParameterAttributes attr) {
458 PAListPtr PAL = getParamAttrs();
459 PAL = PAL.addAttr(i, attr);
463 void InvokeInst::setDoesNotThrow(bool doesNotThrow) {
464 PAListPtr PAL = getParamAttrs();
466 PAL = PAL.addAttr(0, ParamAttr::NoUnwind);
468 PAL = PAL.removeAttr(0, ParamAttr::NoUnwind);
473 //===----------------------------------------------------------------------===//
474 // ReturnInst Implementation
475 //===----------------------------------------------------------------------===//
477 ReturnInst::ReturnInst(const ReturnInst &RI)
478 : TerminatorInst(Type::VoidTy, Instruction::Ret,
479 OperandTraits<ReturnInst>::op_end(this)
480 - RI.getNumOperands(),
481 RI.getNumOperands()) {
482 unsigned N = RI.getNumOperands();
484 Op<0>() = RI.Op<0>();
486 Use *OL = OperandList;
487 for (unsigned i = 0; i < N; ++i)
488 OL[i] = RI.getOperand(i);
492 ReturnInst::ReturnInst(Value *retVal, Instruction *InsertBefore)
493 : TerminatorInst(Type::VoidTy, Instruction::Ret,
494 OperandTraits<ReturnInst>::op_end(this) - (retVal != 0),
495 retVal != 0, InsertBefore) {
499 ReturnInst::ReturnInst(Value *retVal, BasicBlock *InsertAtEnd)
500 : TerminatorInst(Type::VoidTy, Instruction::Ret,
501 OperandTraits<ReturnInst>::op_end(this) - (retVal != 0),
502 retVal != 0, InsertAtEnd) {
506 ReturnInst::ReturnInst(BasicBlock *InsertAtEnd)
507 : TerminatorInst(Type::VoidTy, Instruction::Ret,
508 OperandTraits<ReturnInst>::op_end(this),
512 ReturnInst::ReturnInst(Value * const* retVals, unsigned N,
513 Instruction *InsertBefore)
514 : TerminatorInst(Type::VoidTy, Instruction::Ret,
515 OperandTraits<ReturnInst>::op_end(this) - N,
520 ReturnInst::ReturnInst(Value * const* retVals, unsigned N,
521 BasicBlock *InsertAtEnd)
522 : TerminatorInst(Type::VoidTy, Instruction::Ret,
523 OperandTraits<ReturnInst>::op_end(this) - N,
529 void ReturnInst::init(Value * const* retVals, unsigned N) {
530 assert (N > 0 && "Invalid operands numbers in ReturnInst init");
533 if (NumOperands == 1) {
535 if (V->getType() == Type::VoidTy)
541 Use *OL = OperandList;
542 for (unsigned i = 0; i < NumOperands; ++i) {
543 Value *V = *retVals++;
544 assert(!isa<BasicBlock>(V) &&
545 "Cannot return basic block. Probably using the incorrect ctor");
550 unsigned ReturnInst::getNumSuccessorsV() const {
551 return getNumSuccessors();
554 /// Out-of-line ReturnInst method, put here so the C++ compiler can choose to
555 /// emit the vtable for the class in this translation unit.
556 void ReturnInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
557 assert(0 && "ReturnInst has no successors!");
560 BasicBlock *ReturnInst::getSuccessorV(unsigned idx) const {
561 assert(0 && "ReturnInst has no successors!");
566 ReturnInst::~ReturnInst() {
569 //===----------------------------------------------------------------------===//
570 // UnwindInst Implementation
571 //===----------------------------------------------------------------------===//
573 UnwindInst::UnwindInst(Instruction *InsertBefore)
574 : TerminatorInst(Type::VoidTy, Instruction::Unwind, 0, 0, InsertBefore) {
576 UnwindInst::UnwindInst(BasicBlock *InsertAtEnd)
577 : TerminatorInst(Type::VoidTy, Instruction::Unwind, 0, 0, InsertAtEnd) {
581 unsigned UnwindInst::getNumSuccessorsV() const {
582 return getNumSuccessors();
585 void UnwindInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
586 assert(0 && "UnwindInst has no successors!");
589 BasicBlock *UnwindInst::getSuccessorV(unsigned idx) const {
590 assert(0 && "UnwindInst has no successors!");
595 //===----------------------------------------------------------------------===//
596 // UnreachableInst Implementation
597 //===----------------------------------------------------------------------===//
599 UnreachableInst::UnreachableInst(Instruction *InsertBefore)
600 : TerminatorInst(Type::VoidTy, Instruction::Unreachable, 0, 0, InsertBefore) {
602 UnreachableInst::UnreachableInst(BasicBlock *InsertAtEnd)
603 : TerminatorInst(Type::VoidTy, Instruction::Unreachable, 0, 0, InsertAtEnd) {
606 unsigned UnreachableInst::getNumSuccessorsV() const {
607 return getNumSuccessors();
610 void UnreachableInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
611 assert(0 && "UnwindInst has no successors!");
614 BasicBlock *UnreachableInst::getSuccessorV(unsigned idx) const {
615 assert(0 && "UnwindInst has no successors!");
620 //===----------------------------------------------------------------------===//
621 // BranchInst Implementation
622 //===----------------------------------------------------------------------===//
624 void BranchInst::AssertOK() {
626 assert(getCondition()->getType() == Type::Int1Ty &&
627 "May only branch on boolean predicates!");
630 BranchInst::BranchInst(BasicBlock *IfTrue, Instruction *InsertBefore)
631 : TerminatorInst(Type::VoidTy, Instruction::Br,
632 OperandTraits<BranchInst>::op_end(this) - 1,
634 assert(IfTrue != 0 && "Branch destination may not be null!");
637 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
638 Instruction *InsertBefore)
639 : TerminatorInst(Type::VoidTy, Instruction::Br,
640 OperandTraits<BranchInst>::op_end(this) - 3,
650 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *InsertAtEnd)
651 : TerminatorInst(Type::VoidTy, Instruction::Br,
652 OperandTraits<BranchInst>::op_end(this) - 1,
654 assert(IfTrue != 0 && "Branch destination may not be null!");
658 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
659 BasicBlock *InsertAtEnd)
660 : TerminatorInst(Type::VoidTy, Instruction::Br,
661 OperandTraits<BranchInst>::op_end(this) - 3,
672 BranchInst::BranchInst(const BranchInst &BI) :
673 TerminatorInst(Type::VoidTy, Instruction::Br,
674 OperandTraits<BranchInst>::op_end(this) - BI.getNumOperands(),
675 BI.getNumOperands()) {
676 OperandList[0] = BI.getOperand(0);
677 if (BI.getNumOperands() != 1) {
678 assert(BI.getNumOperands() == 3 && "BR can have 1 or 3 operands!");
679 OperandList[1] = BI.getOperand(1);
680 OperandList[2] = BI.getOperand(2);
684 BasicBlock *BranchInst::getSuccessorV(unsigned idx) const {
685 return getSuccessor(idx);
687 unsigned BranchInst::getNumSuccessorsV() const {
688 return getNumSuccessors();
690 void BranchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
691 setSuccessor(idx, B);
695 //===----------------------------------------------------------------------===//
696 // AllocationInst Implementation
697 //===----------------------------------------------------------------------===//
699 static Value *getAISize(Value *Amt) {
701 Amt = ConstantInt::get(Type::Int32Ty, 1);
703 assert(!isa<BasicBlock>(Amt) &&
704 "Passed basic block into allocation size parameter! Use other ctor");
705 assert(Amt->getType() == Type::Int32Ty &&
706 "Malloc/Allocation array size is not a 32-bit integer!");
711 AllocationInst::AllocationInst(const Type *Ty, Value *ArraySize, unsigned iTy,
712 unsigned Align, const std::string &Name,
713 Instruction *InsertBefore)
714 : UnaryInstruction(PointerType::getUnqual(Ty), iTy, getAISize(ArraySize),
717 assert(Ty != Type::VoidTy && "Cannot allocate void!");
721 AllocationInst::AllocationInst(const Type *Ty, Value *ArraySize, unsigned iTy,
722 unsigned Align, const std::string &Name,
723 BasicBlock *InsertAtEnd)
724 : UnaryInstruction(PointerType::getUnqual(Ty), iTy, getAISize(ArraySize),
727 assert(Ty != Type::VoidTy && "Cannot allocate void!");
731 // Out of line virtual method, so the vtable, etc has a home.
732 AllocationInst::~AllocationInst() {
735 void AllocationInst::setAlignment(unsigned Align) {
736 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
737 SubclassData = Log2_32(Align) + 1;
738 assert(getAlignment() == Align && "Alignment representation error!");
741 bool AllocationInst::isArrayAllocation() const {
742 if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(0)))
743 return CI->getZExtValue() != 1;
747 const Type *AllocationInst::getAllocatedType() const {
748 return getType()->getElementType();
751 AllocaInst::AllocaInst(const AllocaInst &AI)
752 : AllocationInst(AI.getType()->getElementType(), (Value*)AI.getOperand(0),
753 Instruction::Alloca, AI.getAlignment()) {
756 MallocInst::MallocInst(const MallocInst &MI)
757 : AllocationInst(MI.getType()->getElementType(), (Value*)MI.getOperand(0),
758 Instruction::Malloc, MI.getAlignment()) {
761 //===----------------------------------------------------------------------===//
762 // FreeInst Implementation
763 //===----------------------------------------------------------------------===//
765 void FreeInst::AssertOK() {
766 assert(isa<PointerType>(getOperand(0)->getType()) &&
767 "Can not free something of nonpointer type!");
770 FreeInst::FreeInst(Value *Ptr, Instruction *InsertBefore)
771 : UnaryInstruction(Type::VoidTy, Free, Ptr, InsertBefore) {
775 FreeInst::FreeInst(Value *Ptr, BasicBlock *InsertAtEnd)
776 : UnaryInstruction(Type::VoidTy, Free, Ptr, InsertAtEnd) {
781 //===----------------------------------------------------------------------===//
782 // LoadInst Implementation
783 //===----------------------------------------------------------------------===//
785 void LoadInst::AssertOK() {
786 assert(isa<PointerType>(getOperand(0)->getType()) &&
787 "Ptr must have pointer type.");
790 LoadInst::LoadInst(Value *Ptr, const std::string &Name, Instruction *InsertBef)
791 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
792 Load, Ptr, InsertBef) {
799 LoadInst::LoadInst(Value *Ptr, const std::string &Name, BasicBlock *InsertAE)
800 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
801 Load, Ptr, InsertAE) {
808 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile,
809 Instruction *InsertBef)
810 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
811 Load, Ptr, InsertBef) {
812 setVolatile(isVolatile);
818 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile,
819 unsigned Align, Instruction *InsertBef)
820 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
821 Load, Ptr, InsertBef) {
822 setVolatile(isVolatile);
828 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile,
829 unsigned Align, BasicBlock *InsertAE)
830 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
831 Load, Ptr, InsertAE) {
832 setVolatile(isVolatile);
838 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile,
839 BasicBlock *InsertAE)
840 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
841 Load, Ptr, InsertAE) {
842 setVolatile(isVolatile);
850 LoadInst::LoadInst(Value *Ptr, const char *Name, Instruction *InsertBef)
851 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
852 Load, Ptr, InsertBef) {
856 if (Name && Name[0]) setName(Name);
859 LoadInst::LoadInst(Value *Ptr, const char *Name, BasicBlock *InsertAE)
860 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
861 Load, Ptr, InsertAE) {
865 if (Name && Name[0]) setName(Name);
868 LoadInst::LoadInst(Value *Ptr, const char *Name, bool isVolatile,
869 Instruction *InsertBef)
870 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
871 Load, Ptr, InsertBef) {
872 setVolatile(isVolatile);
875 if (Name && Name[0]) setName(Name);
878 LoadInst::LoadInst(Value *Ptr, const char *Name, bool isVolatile,
879 BasicBlock *InsertAE)
880 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
881 Load, Ptr, InsertAE) {
882 setVolatile(isVolatile);
885 if (Name && Name[0]) setName(Name);
888 void LoadInst::setAlignment(unsigned Align) {
889 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
890 SubclassData = (SubclassData & 1) | ((Log2_32(Align)+1)<<1);
893 //===----------------------------------------------------------------------===//
894 // StoreInst Implementation
895 //===----------------------------------------------------------------------===//
897 void StoreInst::AssertOK() {
898 assert(isa<PointerType>(getOperand(1)->getType()) &&
899 "Ptr must have pointer type!");
900 assert(getOperand(0)->getType() ==
901 cast<PointerType>(getOperand(1)->getType())->getElementType()
902 && "Ptr must be a pointer to Val type!");
906 StoreInst::StoreInst(Value *val, Value *addr, Instruction *InsertBefore)
907 : Instruction(Type::VoidTy, Store,
908 OperandTraits<StoreInst>::op_begin(this),
909 OperandTraits<StoreInst>::operands(this),
918 StoreInst::StoreInst(Value *val, Value *addr, BasicBlock *InsertAtEnd)
919 : Instruction(Type::VoidTy, Store,
920 OperandTraits<StoreInst>::op_begin(this),
921 OperandTraits<StoreInst>::operands(this),
930 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
931 Instruction *InsertBefore)
932 : Instruction(Type::VoidTy, Store,
933 OperandTraits<StoreInst>::op_begin(this),
934 OperandTraits<StoreInst>::operands(this),
938 setVolatile(isVolatile);
943 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
944 unsigned Align, Instruction *InsertBefore)
945 : Instruction(Type::VoidTy, Store,
946 OperandTraits<StoreInst>::op_begin(this),
947 OperandTraits<StoreInst>::operands(this),
951 setVolatile(isVolatile);
956 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
957 unsigned Align, BasicBlock *InsertAtEnd)
958 : Instruction(Type::VoidTy, Store,
959 OperandTraits<StoreInst>::op_begin(this),
960 OperandTraits<StoreInst>::operands(this),
964 setVolatile(isVolatile);
969 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
970 BasicBlock *InsertAtEnd)
971 : Instruction(Type::VoidTy, Store,
972 OperandTraits<StoreInst>::op_begin(this),
973 OperandTraits<StoreInst>::operands(this),
977 setVolatile(isVolatile);
982 void StoreInst::setAlignment(unsigned Align) {
983 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
984 SubclassData = (SubclassData & 1) | ((Log2_32(Align)+1)<<1);
987 //===----------------------------------------------------------------------===//
988 // GetElementPtrInst Implementation
989 //===----------------------------------------------------------------------===//
991 static unsigned retrieveAddrSpace(const Value *Val) {
992 return cast<PointerType>(Val->getType())->getAddressSpace();
995 void GetElementPtrInst::init(Value *Ptr, Value* const *Idx, unsigned NumIdx, const std::string &Name) {
996 assert(NumOperands == 1+NumIdx && "NumOperands not initialized?");
997 Use *OL = OperandList;
1000 for (unsigned i = 0; i != NumIdx; ++i)
1006 void GetElementPtrInst::init(Value *Ptr, Value *Idx, const std::string &Name) {
1007 assert(NumOperands == 2 && "NumOperands not initialized?");
1008 Use *OL = OperandList;
1015 GetElementPtrInst::GetElementPtrInst(const GetElementPtrInst &GEPI)
1016 : Instruction(GEPI.getType(), GetElementPtr,
1017 OperandTraits<GetElementPtrInst>::op_end(this)
1018 - GEPI.getNumOperands(),
1019 GEPI.getNumOperands()) {
1020 Use *OL = OperandList;
1021 Use *GEPIOL = GEPI.OperandList;
1022 for (unsigned i = 0, E = NumOperands; i != E; ++i)
1026 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx,
1027 const std::string &Name, Instruction *InBe)
1028 : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),Idx)),
1029 retrieveAddrSpace(Ptr)),
1031 OperandTraits<GetElementPtrInst>::op_end(this) - 2,
1033 init(Ptr, Idx, Name);
1036 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx,
1037 const std::string &Name, BasicBlock *IAE)
1038 : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),Idx)),
1039 retrieveAddrSpace(Ptr)),
1041 OperandTraits<GetElementPtrInst>::op_end(this) - 2,
1043 init(Ptr, Idx, Name);
1046 // getIndexedType - Returns the type of the element that would be loaded with
1047 // a load instruction with the specified parameters.
1049 // A null type is returned if the indices are invalid for the specified
1052 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr,
1055 const PointerType *PTy = dyn_cast<PointerType>(Ptr);
1056 if (!PTy) return 0; // Type isn't a pointer type!
1057 const Type *Agg = PTy->getElementType();
1059 // Handle the special case of the empty set index set...
1063 unsigned CurIdx = 1;
1064 for (; CurIdx != NumIdx; ++CurIdx) {
1065 const CompositeType *CT = dyn_cast<CompositeType>(Agg);
1066 if (!CT || isa<PointerType>(CT)) return 0;
1067 Value *Index = Idxs[CurIdx];
1068 if (!CT->indexValid(Index)) return 0;
1069 Agg = CT->getTypeAtIndex(Index);
1071 // If the new type forwards to another type, then it is in the middle
1072 // of being refined to another type (and hence, may have dropped all
1073 // references to what it was using before). So, use the new forwarded
1075 if (const Type *Ty = Agg->getForwardedType())
1078 return CurIdx == NumIdx ? Agg : 0;
1081 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr, Value *Idx) {
1082 const PointerType *PTy = dyn_cast<PointerType>(Ptr);
1083 if (!PTy) return 0; // Type isn't a pointer type!
1085 // Check the pointer index.
1086 if (!PTy->indexValid(Idx)) return 0;
1088 return PTy->getElementType();
1092 /// hasAllZeroIndices - Return true if all of the indices of this GEP are
1093 /// zeros. If so, the result pointer and the first operand have the same
1094 /// value, just potentially different types.
1095 bool GetElementPtrInst::hasAllZeroIndices() const {
1096 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1097 if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(i))) {
1098 if (!CI->isZero()) return false;
1106 /// hasAllConstantIndices - Return true if all of the indices of this GEP are
1107 /// constant integers. If so, the result pointer and the first operand have
1108 /// a constant offset between them.
1109 bool GetElementPtrInst::hasAllConstantIndices() const {
1110 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1111 if (!isa<ConstantInt>(getOperand(i)))
1118 //===----------------------------------------------------------------------===//
1119 // ExtractElementInst Implementation
1120 //===----------------------------------------------------------------------===//
1122 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
1123 const std::string &Name,
1124 Instruction *InsertBef)
1125 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1127 OperandTraits<ExtractElementInst>::op_begin(this),
1129 assert(isValidOperands(Val, Index) &&
1130 "Invalid extractelement instruction operands!");
1136 ExtractElementInst::ExtractElementInst(Value *Val, unsigned IndexV,
1137 const std::string &Name,
1138 Instruction *InsertBef)
1139 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1141 OperandTraits<ExtractElementInst>::op_begin(this),
1143 Constant *Index = ConstantInt::get(Type::Int32Ty, IndexV);
1144 assert(isValidOperands(Val, Index) &&
1145 "Invalid extractelement instruction operands!");
1152 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
1153 const std::string &Name,
1154 BasicBlock *InsertAE)
1155 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1157 OperandTraits<ExtractElementInst>::op_begin(this),
1159 assert(isValidOperands(Val, Index) &&
1160 "Invalid extractelement instruction operands!");
1167 ExtractElementInst::ExtractElementInst(Value *Val, unsigned IndexV,
1168 const std::string &Name,
1169 BasicBlock *InsertAE)
1170 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1172 OperandTraits<ExtractElementInst>::op_begin(this),
1174 Constant *Index = ConstantInt::get(Type::Int32Ty, IndexV);
1175 assert(isValidOperands(Val, Index) &&
1176 "Invalid extractelement instruction operands!");
1184 bool ExtractElementInst::isValidOperands(const Value *Val, const Value *Index) {
1185 if (!isa<VectorType>(Val->getType()) || Index->getType() != Type::Int32Ty)
1191 //===----------------------------------------------------------------------===//
1192 // InsertElementInst Implementation
1193 //===----------------------------------------------------------------------===//
1195 InsertElementInst::InsertElementInst(const InsertElementInst &IE)
1196 : Instruction(IE.getType(), InsertElement,
1197 OperandTraits<InsertElementInst>::op_begin(this), 3) {
1198 Op<0>() = IE.Op<0>();
1199 Op<1>() = IE.Op<1>();
1200 Op<2>() = IE.Op<2>();
1202 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
1203 const std::string &Name,
1204 Instruction *InsertBef)
1205 : Instruction(Vec->getType(), InsertElement,
1206 OperandTraits<InsertElementInst>::op_begin(this),
1208 assert(isValidOperands(Vec, Elt, Index) &&
1209 "Invalid insertelement instruction operands!");
1216 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, unsigned IndexV,
1217 const std::string &Name,
1218 Instruction *InsertBef)
1219 : Instruction(Vec->getType(), InsertElement,
1220 OperandTraits<InsertElementInst>::op_begin(this),
1222 Constant *Index = ConstantInt::get(Type::Int32Ty, IndexV);
1223 assert(isValidOperands(Vec, Elt, Index) &&
1224 "Invalid insertelement instruction operands!");
1232 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
1233 const std::string &Name,
1234 BasicBlock *InsertAE)
1235 : Instruction(Vec->getType(), InsertElement,
1236 OperandTraits<InsertElementInst>::op_begin(this),
1238 assert(isValidOperands(Vec, Elt, Index) &&
1239 "Invalid insertelement instruction operands!");
1247 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, unsigned IndexV,
1248 const std::string &Name,
1249 BasicBlock *InsertAE)
1250 : Instruction(Vec->getType(), InsertElement,
1251 OperandTraits<InsertElementInst>::op_begin(this),
1253 Constant *Index = ConstantInt::get(Type::Int32Ty, IndexV);
1254 assert(isValidOperands(Vec, Elt, Index) &&
1255 "Invalid insertelement instruction operands!");
1263 bool InsertElementInst::isValidOperands(const Value *Vec, const Value *Elt,
1264 const Value *Index) {
1265 if (!isa<VectorType>(Vec->getType()))
1266 return false; // First operand of insertelement must be vector type.
1268 if (Elt->getType() != cast<VectorType>(Vec->getType())->getElementType())
1269 return false;// Second operand of insertelement must be vector element type.
1271 if (Index->getType() != Type::Int32Ty)
1272 return false; // Third operand of insertelement must be uint.
1277 //===----------------------------------------------------------------------===//
1278 // ShuffleVectorInst Implementation
1279 //===----------------------------------------------------------------------===//
1281 ShuffleVectorInst::ShuffleVectorInst(const ShuffleVectorInst &SV)
1282 : Instruction(SV.getType(), ShuffleVector,
1283 OperandTraits<ShuffleVectorInst>::op_begin(this),
1284 OperandTraits<ShuffleVectorInst>::operands(this)) {
1285 Op<0>() = SV.Op<0>();
1286 Op<1>() = SV.Op<1>();
1287 Op<2>() = SV.Op<2>();
1290 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1291 const std::string &Name,
1292 Instruction *InsertBefore)
1293 : Instruction(V1->getType(), ShuffleVector,
1294 OperandTraits<ShuffleVectorInst>::op_begin(this),
1295 OperandTraits<ShuffleVectorInst>::operands(this),
1297 assert(isValidOperands(V1, V2, Mask) &&
1298 "Invalid shuffle vector instruction operands!");
1305 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1306 const std::string &Name,
1307 BasicBlock *InsertAtEnd)
1308 : Instruction(V1->getType(), ShuffleVector,
1309 OperandTraits<ShuffleVectorInst>::op_begin(this),
1310 OperandTraits<ShuffleVectorInst>::operands(this),
1312 assert(isValidOperands(V1, V2, Mask) &&
1313 "Invalid shuffle vector instruction operands!");
1321 bool ShuffleVectorInst::isValidOperands(const Value *V1, const Value *V2,
1322 const Value *Mask) {
1323 if (!isa<VectorType>(V1->getType()) ||
1324 V1->getType() != V2->getType())
1327 const VectorType *MaskTy = dyn_cast<VectorType>(Mask->getType());
1328 if (!isa<Constant>(Mask) || MaskTy == 0 ||
1329 MaskTy->getElementType() != Type::Int32Ty ||
1330 MaskTy->getNumElements() !=
1331 cast<VectorType>(V1->getType())->getNumElements())
1336 /// getMaskValue - Return the index from the shuffle mask for the specified
1337 /// output result. This is either -1 if the element is undef or a number less
1338 /// than 2*numelements.
1339 int ShuffleVectorInst::getMaskValue(unsigned i) const {
1340 const Constant *Mask = cast<Constant>(getOperand(2));
1341 if (isa<UndefValue>(Mask)) return -1;
1342 if (isa<ConstantAggregateZero>(Mask)) return 0;
1343 const ConstantVector *MaskCV = cast<ConstantVector>(Mask);
1344 assert(i < MaskCV->getNumOperands() && "Index out of range");
1346 if (isa<UndefValue>(MaskCV->getOperand(i)))
1348 return cast<ConstantInt>(MaskCV->getOperand(i))->getZExtValue();
1351 //===----------------------------------------------------------------------===//
1352 // InsertValueInst Class
1353 //===----------------------------------------------------------------------===//
1355 void InsertValueInst::init(Value *Agg, Value *Val, const unsigned *Idx,
1356 unsigned NumIdx, const std::string &Name) {
1357 assert(NumOperands == 2 && "NumOperands not initialized?");
1361 Indices.insert(Indices.end(), Idx, Idx + NumIdx);
1365 void InsertValueInst::init(Value *Agg, Value *Val, unsigned Idx,
1366 const std::string &Name) {
1367 assert(NumOperands == 2 && "NumOperands not initialized?");
1371 Indices.push_back(Idx);
1375 InsertValueInst::InsertValueInst(const InsertValueInst &IVI)
1376 : Instruction(IVI.getType(), InsertValue,
1377 OperandTraits<InsertValueInst>::op_begin(this), 2),
1378 Indices(IVI.Indices) {
1381 InsertValueInst::InsertValueInst(Value *Agg,
1384 const std::string &Name,
1385 Instruction *InsertBefore)
1386 : Instruction(Agg->getType(), InsertValue,
1387 OperandTraits<InsertValueInst>::op_begin(this),
1389 init(Agg, Val, Idx, Name);
1392 InsertValueInst::InsertValueInst(Value *Agg,
1395 const std::string &Name,
1396 BasicBlock *InsertAtEnd)
1397 : Instruction(Agg->getType(), InsertValue,
1398 OperandTraits<InsertValueInst>::op_begin(this),
1400 init(Agg, Val, Idx, Name);
1403 //===----------------------------------------------------------------------===//
1404 // ExtractValueInst Class
1405 //===----------------------------------------------------------------------===//
1407 void ExtractValueInst::init(Value *Agg, const unsigned *Idx, unsigned NumIdx, const std::string &Name) {
1408 assert(NumOperands == 1 && "NumOperands not initialized?");
1411 Indices.insert(Indices.end(), Idx, Idx + NumIdx);
1415 void ExtractValueInst::init(Value *Agg, unsigned Idx, const std::string &Name) {
1416 assert(NumOperands == 1 && "NumOperands not initialized?");
1419 Indices.push_back(Idx);
1423 ExtractValueInst::ExtractValueInst(const ExtractValueInst &EVI)
1424 : Instruction(reinterpret_cast<const Type*>(EVI.getType()), ExtractValue,
1425 OperandTraits<ExtractValueInst>::op_begin(this), 1),
1426 Indices(EVI.Indices) {
1429 // getIndexedType - Returns the type of the element that would be extracted
1430 // with an extractvalue instruction with the specified parameters.
1432 // A null type is returned if the indices are invalid for the specified
1435 const Type* ExtractValueInst::getIndexedType(const Type *Agg,
1436 const unsigned *Idxs,
1438 unsigned CurIdx = 0;
1439 for (; CurIdx != NumIdx; ++CurIdx) {
1440 const CompositeType *CT = dyn_cast<CompositeType>(Agg);
1441 if (!CT || isa<PointerType>(CT) || isa<VectorType>(CT)) return 0;
1442 unsigned Index = Idxs[CurIdx];
1443 if (!CT->indexValid(Index)) return 0;
1444 Agg = CT->getTypeAtIndex(Index);
1446 // If the new type forwards to another type, then it is in the middle
1447 // of being refined to another type (and hence, may have dropped all
1448 // references to what it was using before). So, use the new forwarded
1450 if (const Type *Ty = Agg->getForwardedType())
1453 return CurIdx == NumIdx ? Agg : 0;
1456 ExtractValueInst::ExtractValueInst(Value *Agg,
1458 const std::string &Name,
1459 BasicBlock *InsertAtEnd)
1460 : Instruction(checkType(getIndexedType(Agg->getType(), &Idx, 1)),
1462 OperandTraits<ExtractValueInst>::op_begin(this),
1464 init(Agg, Idx, Name);
1467 ExtractValueInst::ExtractValueInst(Value *Agg,
1469 const std::string &Name,
1470 Instruction *InsertBefore)
1471 : Instruction(checkType(getIndexedType(Agg->getType(), &Idx, 1)),
1473 OperandTraits<ExtractValueInst>::op_begin(this),
1475 init(Agg, Idx, Name);
1478 //===----------------------------------------------------------------------===//
1479 // BinaryOperator Class
1480 //===----------------------------------------------------------------------===//
1482 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
1483 const Type *Ty, const std::string &Name,
1484 Instruction *InsertBefore)
1485 : Instruction(Ty, iType,
1486 OperandTraits<BinaryOperator>::op_begin(this),
1487 OperandTraits<BinaryOperator>::operands(this),
1495 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
1496 const Type *Ty, const std::string &Name,
1497 BasicBlock *InsertAtEnd)
1498 : Instruction(Ty, iType,
1499 OperandTraits<BinaryOperator>::op_begin(this),
1500 OperandTraits<BinaryOperator>::operands(this),
1509 void BinaryOperator::init(BinaryOps iType) {
1510 Value *LHS = getOperand(0), *RHS = getOperand(1);
1511 LHS = LHS; RHS = RHS; // Silence warnings.
1512 assert(LHS->getType() == RHS->getType() &&
1513 "Binary operator operand types must match!");
1518 assert(getType() == LHS->getType() &&
1519 "Arithmetic operation should return same type as operands!");
1520 assert((getType()->isInteger() || getType()->isFloatingPoint() ||
1521 isa<VectorType>(getType())) &&
1522 "Tried to create an arithmetic operation on a non-arithmetic type!");
1526 assert(getType() == LHS->getType() &&
1527 "Arithmetic operation should return same type as operands!");
1528 assert((getType()->isInteger() || (isa<VectorType>(getType()) &&
1529 cast<VectorType>(getType())->getElementType()->isInteger())) &&
1530 "Incorrect operand type (not integer) for S/UDIV");
1533 assert(getType() == LHS->getType() &&
1534 "Arithmetic operation should return same type as operands!");
1535 assert((getType()->isFloatingPoint() || (isa<VectorType>(getType()) &&
1536 cast<VectorType>(getType())->getElementType()->isFloatingPoint()))
1537 && "Incorrect operand type (not floating point) for FDIV");
1541 assert(getType() == LHS->getType() &&
1542 "Arithmetic operation should return same type as operands!");
1543 assert((getType()->isInteger() || (isa<VectorType>(getType()) &&
1544 cast<VectorType>(getType())->getElementType()->isInteger())) &&
1545 "Incorrect operand type (not integer) for S/UREM");
1548 assert(getType() == LHS->getType() &&
1549 "Arithmetic operation should return same type as operands!");
1550 assert((getType()->isFloatingPoint() || (isa<VectorType>(getType()) &&
1551 cast<VectorType>(getType())->getElementType()->isFloatingPoint()))
1552 && "Incorrect operand type (not floating point) for FREM");
1557 assert(getType() == LHS->getType() &&
1558 "Shift operation should return same type as operands!");
1559 assert(getType()->isInteger() &&
1560 "Shift operation requires integer operands");
1564 assert(getType() == LHS->getType() &&
1565 "Logical operation should return same type as operands!");
1566 assert((getType()->isInteger() ||
1567 (isa<VectorType>(getType()) &&
1568 cast<VectorType>(getType())->getElementType()->isInteger())) &&
1569 "Tried to create a logical operation on a non-integral type!");
1577 BinaryOperator *BinaryOperator::Create(BinaryOps Op, Value *S1, Value *S2,
1578 const std::string &Name,
1579 Instruction *InsertBefore) {
1580 assert(S1->getType() == S2->getType() &&
1581 "Cannot create binary operator with two operands of differing type!");
1582 return new BinaryOperator(Op, S1, S2, S1->getType(), Name, InsertBefore);
1585 BinaryOperator *BinaryOperator::Create(BinaryOps Op, Value *S1, Value *S2,
1586 const std::string &Name,
1587 BasicBlock *InsertAtEnd) {
1588 BinaryOperator *Res = Create(Op, S1, S2, Name);
1589 InsertAtEnd->getInstList().push_back(Res);
1593 BinaryOperator *BinaryOperator::CreateNeg(Value *Op, const std::string &Name,
1594 Instruction *InsertBefore) {
1595 Value *zero = ConstantExpr::getZeroValueForNegationExpr(Op->getType());
1596 return new BinaryOperator(Instruction::Sub,
1598 Op->getType(), Name, InsertBefore);
1601 BinaryOperator *BinaryOperator::CreateNeg(Value *Op, const std::string &Name,
1602 BasicBlock *InsertAtEnd) {
1603 Value *zero = ConstantExpr::getZeroValueForNegationExpr(Op->getType());
1604 return new BinaryOperator(Instruction::Sub,
1606 Op->getType(), Name, InsertAtEnd);
1609 BinaryOperator *BinaryOperator::CreateNot(Value *Op, const std::string &Name,
1610 Instruction *InsertBefore) {
1612 if (const VectorType *PTy = dyn_cast<VectorType>(Op->getType())) {
1613 C = ConstantInt::getAllOnesValue(PTy->getElementType());
1614 C = ConstantVector::get(std::vector<Constant*>(PTy->getNumElements(), C));
1616 C = ConstantInt::getAllOnesValue(Op->getType());
1619 return new BinaryOperator(Instruction::Xor, Op, C,
1620 Op->getType(), Name, InsertBefore);
1623 BinaryOperator *BinaryOperator::CreateNot(Value *Op, const std::string &Name,
1624 BasicBlock *InsertAtEnd) {
1626 if (const VectorType *PTy = dyn_cast<VectorType>(Op->getType())) {
1627 // Create a vector of all ones values.
1628 Constant *Elt = ConstantInt::getAllOnesValue(PTy->getElementType());
1630 ConstantVector::get(std::vector<Constant*>(PTy->getNumElements(), Elt));
1632 AllOnes = ConstantInt::getAllOnesValue(Op->getType());
1635 return new BinaryOperator(Instruction::Xor, Op, AllOnes,
1636 Op->getType(), Name, InsertAtEnd);
1640 // isConstantAllOnes - Helper function for several functions below
1641 static inline bool isConstantAllOnes(const Value *V) {
1642 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V))
1643 return CI->isAllOnesValue();
1644 if (const ConstantVector *CV = dyn_cast<ConstantVector>(V))
1645 return CV->isAllOnesValue();
1649 bool BinaryOperator::isNeg(const Value *V) {
1650 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1651 if (Bop->getOpcode() == Instruction::Sub)
1652 return Bop->getOperand(0) ==
1653 ConstantExpr::getZeroValueForNegationExpr(Bop->getType());
1657 bool BinaryOperator::isNot(const Value *V) {
1658 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1659 return (Bop->getOpcode() == Instruction::Xor &&
1660 (isConstantAllOnes(Bop->getOperand(1)) ||
1661 isConstantAllOnes(Bop->getOperand(0))));
1665 Value *BinaryOperator::getNegArgument(Value *BinOp) {
1666 assert(isNeg(BinOp) && "getNegArgument from non-'neg' instruction!");
1667 return cast<BinaryOperator>(BinOp)->getOperand(1);
1670 const Value *BinaryOperator::getNegArgument(const Value *BinOp) {
1671 return getNegArgument(const_cast<Value*>(BinOp));
1674 Value *BinaryOperator::getNotArgument(Value *BinOp) {
1675 assert(isNot(BinOp) && "getNotArgument on non-'not' instruction!");
1676 BinaryOperator *BO = cast<BinaryOperator>(BinOp);
1677 Value *Op0 = BO->getOperand(0);
1678 Value *Op1 = BO->getOperand(1);
1679 if (isConstantAllOnes(Op0)) return Op1;
1681 assert(isConstantAllOnes(Op1));
1685 const Value *BinaryOperator::getNotArgument(const Value *BinOp) {
1686 return getNotArgument(const_cast<Value*>(BinOp));
1690 // swapOperands - Exchange the two operands to this instruction. This
1691 // instruction is safe to use on any binary instruction and does not
1692 // modify the semantics of the instruction. If the instruction is
1693 // order dependent (SetLT f.e.) the opcode is changed.
1695 bool BinaryOperator::swapOperands() {
1696 if (!isCommutative())
1697 return true; // Can't commute operands
1698 Op<0>().swap(Op<1>());
1702 //===----------------------------------------------------------------------===//
1704 //===----------------------------------------------------------------------===//
1706 // Just determine if this cast only deals with integral->integral conversion.
1707 bool CastInst::isIntegerCast() const {
1708 switch (getOpcode()) {
1709 default: return false;
1710 case Instruction::ZExt:
1711 case Instruction::SExt:
1712 case Instruction::Trunc:
1714 case Instruction::BitCast:
1715 return getOperand(0)->getType()->isInteger() && getType()->isInteger();
1719 bool CastInst::isLosslessCast() const {
1720 // Only BitCast can be lossless, exit fast if we're not BitCast
1721 if (getOpcode() != Instruction::BitCast)
1724 // Identity cast is always lossless
1725 const Type* SrcTy = getOperand(0)->getType();
1726 const Type* DstTy = getType();
1730 // Pointer to pointer is always lossless.
1731 if (isa<PointerType>(SrcTy))
1732 return isa<PointerType>(DstTy);
1733 return false; // Other types have no identity values
1736 /// This function determines if the CastInst does not require any bits to be
1737 /// changed in order to effect the cast. Essentially, it identifies cases where
1738 /// no code gen is necessary for the cast, hence the name no-op cast. For
1739 /// example, the following are all no-op casts:
1740 /// # bitcast i32* %x to i8*
1741 /// # bitcast <2 x i32> %x to <4 x i16>
1742 /// # ptrtoint i32* %x to i32 ; on 32-bit plaforms only
1743 /// @brief Determine if a cast is a no-op.
1744 bool CastInst::isNoopCast(const Type *IntPtrTy) const {
1745 switch (getOpcode()) {
1747 assert(!"Invalid CastOp");
1748 case Instruction::Trunc:
1749 case Instruction::ZExt:
1750 case Instruction::SExt:
1751 case Instruction::FPTrunc:
1752 case Instruction::FPExt:
1753 case Instruction::UIToFP:
1754 case Instruction::SIToFP:
1755 case Instruction::FPToUI:
1756 case Instruction::FPToSI:
1757 return false; // These always modify bits
1758 case Instruction::BitCast:
1759 return true; // BitCast never modifies bits.
1760 case Instruction::PtrToInt:
1761 return IntPtrTy->getPrimitiveSizeInBits() ==
1762 getType()->getPrimitiveSizeInBits();
1763 case Instruction::IntToPtr:
1764 return IntPtrTy->getPrimitiveSizeInBits() ==
1765 getOperand(0)->getType()->getPrimitiveSizeInBits();
1769 /// This function determines if a pair of casts can be eliminated and what
1770 /// opcode should be used in the elimination. This assumes that there are two
1771 /// instructions like this:
1772 /// * %F = firstOpcode SrcTy %x to MidTy
1773 /// * %S = secondOpcode MidTy %F to DstTy
1774 /// The function returns a resultOpcode so these two casts can be replaced with:
1775 /// * %Replacement = resultOpcode %SrcTy %x to DstTy
1776 /// If no such cast is permited, the function returns 0.
1777 unsigned CastInst::isEliminableCastPair(
1778 Instruction::CastOps firstOp, Instruction::CastOps secondOp,
1779 const Type *SrcTy, const Type *MidTy, const Type *DstTy, const Type *IntPtrTy)
1781 // Define the 144 possibilities for these two cast instructions. The values
1782 // in this matrix determine what to do in a given situation and select the
1783 // case in the switch below. The rows correspond to firstOp, the columns
1784 // correspond to secondOp. In looking at the table below, keep in mind
1785 // the following cast properties:
1787 // Size Compare Source Destination
1788 // Operator Src ? Size Type Sign Type Sign
1789 // -------- ------------ ------------------- ---------------------
1790 // TRUNC > Integer Any Integral Any
1791 // ZEXT < Integral Unsigned Integer Any
1792 // SEXT < Integral Signed Integer Any
1793 // FPTOUI n/a FloatPt n/a Integral Unsigned
1794 // FPTOSI n/a FloatPt n/a Integral Signed
1795 // UITOFP n/a Integral Unsigned FloatPt n/a
1796 // SITOFP n/a Integral Signed FloatPt n/a
1797 // FPTRUNC > FloatPt n/a FloatPt n/a
1798 // FPEXT < FloatPt n/a FloatPt n/a
1799 // PTRTOINT n/a Pointer n/a Integral Unsigned
1800 // INTTOPTR n/a Integral Unsigned Pointer n/a
1801 // BITCONVERT = FirstClass n/a FirstClass n/a
1803 // NOTE: some transforms are safe, but we consider them to be non-profitable.
1804 // For example, we could merge "fptoui double to uint" + "zext uint to ulong",
1805 // into "fptoui double to ulong", but this loses information about the range
1806 // of the produced value (we no longer know the top-part is all zeros).
1807 // Further this conversion is often much more expensive for typical hardware,
1808 // and causes issues when building libgcc. We disallow fptosi+sext for the
1810 const unsigned numCastOps =
1811 Instruction::CastOpsEnd - Instruction::CastOpsBegin;
1812 static const uint8_t CastResults[numCastOps][numCastOps] = {
1813 // T F F U S F F P I B -+
1814 // R Z S P P I I T P 2 N T |
1815 // U E E 2 2 2 2 R E I T C +- secondOp
1816 // N X X U S F F N X N 2 V |
1817 // C T T I I P P C T T P T -+
1818 { 1, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // Trunc -+
1819 { 8, 1, 9,99,99, 2, 0,99,99,99, 2, 3 }, // ZExt |
1820 { 8, 0, 1,99,99, 0, 2,99,99,99, 0, 3 }, // SExt |
1821 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // FPToUI |
1822 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // FPToSI |
1823 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4 }, // UIToFP +- firstOp
1824 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4 }, // SIToFP |
1825 { 99,99,99, 0, 0,99,99, 1, 0,99,99, 4 }, // FPTrunc |
1826 { 99,99,99, 2, 2,99,99,10, 2,99,99, 4 }, // FPExt |
1827 { 1, 0, 0,99,99, 0, 0,99,99,99, 7, 3 }, // PtrToInt |
1828 { 99,99,99,99,99,99,99,99,99,13,99,12 }, // IntToPtr |
1829 { 5, 5, 5, 6, 6, 5, 5, 6, 6,11, 5, 1 }, // BitCast -+
1832 int ElimCase = CastResults[firstOp-Instruction::CastOpsBegin]
1833 [secondOp-Instruction::CastOpsBegin];
1836 // categorically disallowed
1839 // allowed, use first cast's opcode
1842 // allowed, use second cast's opcode
1845 // no-op cast in second op implies firstOp as long as the DestTy
1847 if (DstTy->isInteger())
1851 // no-op cast in second op implies firstOp as long as the DestTy
1852 // is floating point
1853 if (DstTy->isFloatingPoint())
1857 // no-op cast in first op implies secondOp as long as the SrcTy
1859 if (SrcTy->isInteger())
1863 // no-op cast in first op implies secondOp as long as the SrcTy
1864 // is a floating point
1865 if (SrcTy->isFloatingPoint())
1869 // ptrtoint, inttoptr -> bitcast (ptr -> ptr) if int size is >= ptr size
1870 unsigned PtrSize = IntPtrTy->getPrimitiveSizeInBits();
1871 unsigned MidSize = MidTy->getPrimitiveSizeInBits();
1872 if (MidSize >= PtrSize)
1873 return Instruction::BitCast;
1877 // ext, trunc -> bitcast, if the SrcTy and DstTy are same size
1878 // ext, trunc -> ext, if sizeof(SrcTy) < sizeof(DstTy)
1879 // ext, trunc -> trunc, if sizeof(SrcTy) > sizeof(DstTy)
1880 unsigned SrcSize = SrcTy->getPrimitiveSizeInBits();
1881 unsigned DstSize = DstTy->getPrimitiveSizeInBits();
1882 if (SrcSize == DstSize)
1883 return Instruction::BitCast;
1884 else if (SrcSize < DstSize)
1888 case 9: // zext, sext -> zext, because sext can't sign extend after zext
1889 return Instruction::ZExt;
1891 // fpext followed by ftrunc is allowed if the bit size returned to is
1892 // the same as the original, in which case its just a bitcast
1894 return Instruction::BitCast;
1895 return 0; // If the types are not the same we can't eliminate it.
1897 // bitcast followed by ptrtoint is allowed as long as the bitcast
1898 // is a pointer to pointer cast.
1899 if (isa<PointerType>(SrcTy) && isa<PointerType>(MidTy))
1903 // inttoptr, bitcast -> intptr if bitcast is a ptr to ptr cast
1904 if (isa<PointerType>(MidTy) && isa<PointerType>(DstTy))
1908 // inttoptr, ptrtoint -> bitcast if SrcSize<=PtrSize and SrcSize==DstSize
1909 unsigned PtrSize = IntPtrTy->getPrimitiveSizeInBits();
1910 unsigned SrcSize = SrcTy->getPrimitiveSizeInBits();
1911 unsigned DstSize = DstTy->getPrimitiveSizeInBits();
1912 if (SrcSize <= PtrSize && SrcSize == DstSize)
1913 return Instruction::BitCast;
1917 // cast combination can't happen (error in input). This is for all cases
1918 // where the MidTy is not the same for the two cast instructions.
1919 assert(!"Invalid Cast Combination");
1922 assert(!"Error in CastResults table!!!");
1928 CastInst *CastInst::Create(Instruction::CastOps op, Value *S, const Type *Ty,
1929 const std::string &Name, Instruction *InsertBefore) {
1930 // Construct and return the appropriate CastInst subclass
1932 case Trunc: return new TruncInst (S, Ty, Name, InsertBefore);
1933 case ZExt: return new ZExtInst (S, Ty, Name, InsertBefore);
1934 case SExt: return new SExtInst (S, Ty, Name, InsertBefore);
1935 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertBefore);
1936 case FPExt: return new FPExtInst (S, Ty, Name, InsertBefore);
1937 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertBefore);
1938 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertBefore);
1939 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertBefore);
1940 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertBefore);
1941 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertBefore);
1942 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertBefore);
1943 case BitCast: return new BitCastInst (S, Ty, Name, InsertBefore);
1945 assert(!"Invalid opcode provided");
1950 CastInst *CastInst::Create(Instruction::CastOps op, Value *S, const Type *Ty,
1951 const std::string &Name, BasicBlock *InsertAtEnd) {
1952 // Construct and return the appropriate CastInst subclass
1954 case Trunc: return new TruncInst (S, Ty, Name, InsertAtEnd);
1955 case ZExt: return new ZExtInst (S, Ty, Name, InsertAtEnd);
1956 case SExt: return new SExtInst (S, Ty, Name, InsertAtEnd);
1957 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertAtEnd);
1958 case FPExt: return new FPExtInst (S, Ty, Name, InsertAtEnd);
1959 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertAtEnd);
1960 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertAtEnd);
1961 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertAtEnd);
1962 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertAtEnd);
1963 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertAtEnd);
1964 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertAtEnd);
1965 case BitCast: return new BitCastInst (S, Ty, Name, InsertAtEnd);
1967 assert(!"Invalid opcode provided");
1972 CastInst *CastInst::CreateZExtOrBitCast(Value *S, const Type *Ty,
1973 const std::string &Name,
1974 Instruction *InsertBefore) {
1975 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1976 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
1977 return Create(Instruction::ZExt, S, Ty, Name, InsertBefore);
1980 CastInst *CastInst::CreateZExtOrBitCast(Value *S, const Type *Ty,
1981 const std::string &Name,
1982 BasicBlock *InsertAtEnd) {
1983 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1984 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
1985 return Create(Instruction::ZExt, S, Ty, Name, InsertAtEnd);
1988 CastInst *CastInst::CreateSExtOrBitCast(Value *S, const Type *Ty,
1989 const std::string &Name,
1990 Instruction *InsertBefore) {
1991 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1992 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
1993 return Create(Instruction::SExt, S, Ty, Name, InsertBefore);
1996 CastInst *CastInst::CreateSExtOrBitCast(Value *S, const Type *Ty,
1997 const std::string &Name,
1998 BasicBlock *InsertAtEnd) {
1999 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
2000 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2001 return Create(Instruction::SExt, S, Ty, Name, InsertAtEnd);
2004 CastInst *CastInst::CreateTruncOrBitCast(Value *S, const Type *Ty,
2005 const std::string &Name,
2006 Instruction *InsertBefore) {
2007 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
2008 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2009 return Create(Instruction::Trunc, S, Ty, Name, InsertBefore);
2012 CastInst *CastInst::CreateTruncOrBitCast(Value *S, const Type *Ty,
2013 const std::string &Name,
2014 BasicBlock *InsertAtEnd) {
2015 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
2016 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2017 return Create(Instruction::Trunc, S, Ty, Name, InsertAtEnd);
2020 CastInst *CastInst::CreatePointerCast(Value *S, const Type *Ty,
2021 const std::string &Name,
2022 BasicBlock *InsertAtEnd) {
2023 assert(isa<PointerType>(S->getType()) && "Invalid cast");
2024 assert((Ty->isInteger() || isa<PointerType>(Ty)) &&
2027 if (Ty->isInteger())
2028 return Create(Instruction::PtrToInt, S, Ty, Name, InsertAtEnd);
2029 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2032 /// @brief Create a BitCast or a PtrToInt cast instruction
2033 CastInst *CastInst::CreatePointerCast(Value *S, const Type *Ty,
2034 const std::string &Name,
2035 Instruction *InsertBefore) {
2036 assert(isa<PointerType>(S->getType()) && "Invalid cast");
2037 assert((Ty->isInteger() || isa<PointerType>(Ty)) &&
2040 if (Ty->isInteger())
2041 return Create(Instruction::PtrToInt, S, Ty, Name, InsertBefore);
2042 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2045 CastInst *CastInst::CreateIntegerCast(Value *C, const Type *Ty,
2046 bool isSigned, const std::string &Name,
2047 Instruction *InsertBefore) {
2048 assert(C->getType()->isInteger() && Ty->isInteger() && "Invalid cast");
2049 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
2050 unsigned DstBits = Ty->getPrimitiveSizeInBits();
2051 Instruction::CastOps opcode =
2052 (SrcBits == DstBits ? Instruction::BitCast :
2053 (SrcBits > DstBits ? Instruction::Trunc :
2054 (isSigned ? Instruction::SExt : Instruction::ZExt)));
2055 return Create(opcode, C, Ty, Name, InsertBefore);
2058 CastInst *CastInst::CreateIntegerCast(Value *C, const Type *Ty,
2059 bool isSigned, const std::string &Name,
2060 BasicBlock *InsertAtEnd) {
2061 assert(C->getType()->isInteger() && Ty->isInteger() && "Invalid cast");
2062 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
2063 unsigned DstBits = Ty->getPrimitiveSizeInBits();
2064 Instruction::CastOps opcode =
2065 (SrcBits == DstBits ? Instruction::BitCast :
2066 (SrcBits > DstBits ? Instruction::Trunc :
2067 (isSigned ? Instruction::SExt : Instruction::ZExt)));
2068 return Create(opcode, C, Ty, Name, InsertAtEnd);
2071 CastInst *CastInst::CreateFPCast(Value *C, const Type *Ty,
2072 const std::string &Name,
2073 Instruction *InsertBefore) {
2074 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
2076 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
2077 unsigned DstBits = Ty->getPrimitiveSizeInBits();
2078 Instruction::CastOps opcode =
2079 (SrcBits == DstBits ? Instruction::BitCast :
2080 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
2081 return Create(opcode, C, Ty, Name, InsertBefore);
2084 CastInst *CastInst::CreateFPCast(Value *C, const Type *Ty,
2085 const std::string &Name,
2086 BasicBlock *InsertAtEnd) {
2087 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
2089 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
2090 unsigned DstBits = Ty->getPrimitiveSizeInBits();
2091 Instruction::CastOps opcode =
2092 (SrcBits == DstBits ? Instruction::BitCast :
2093 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
2094 return Create(opcode, C, Ty, Name, InsertAtEnd);
2097 // Check whether it is valid to call getCastOpcode for these types.
2098 // This routine must be kept in sync with getCastOpcode.
2099 bool CastInst::isCastable(const Type *SrcTy, const Type *DestTy) {
2100 if (!SrcTy->isFirstClassType() || !DestTy->isFirstClassType())
2103 if (SrcTy == DestTy)
2106 // Get the bit sizes, we'll need these
2107 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); // 0 for ptr/vector
2108 unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr/vector
2110 // Run through the possibilities ...
2111 if (DestTy->isInteger()) { // Casting to integral
2112 if (SrcTy->isInteger()) { // Casting from integral
2114 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt
2116 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
2117 // Casting from vector
2118 return DestBits == PTy->getBitWidth();
2119 } else { // Casting from something else
2120 return isa<PointerType>(SrcTy);
2122 } else if (DestTy->isFloatingPoint()) { // Casting to floating pt
2123 if (SrcTy->isInteger()) { // Casting from integral
2125 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt
2127 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
2128 // Casting from vector
2129 return DestBits == PTy->getBitWidth();
2130 } else { // Casting from something else
2133 } else if (const VectorType *DestPTy = dyn_cast<VectorType>(DestTy)) {
2134 // Casting to vector
2135 if (const VectorType *SrcPTy = dyn_cast<VectorType>(SrcTy)) {
2136 // Casting from vector
2137 return DestPTy->getBitWidth() == SrcPTy->getBitWidth();
2138 } else { // Casting from something else
2139 return DestPTy->getBitWidth() == SrcBits;
2141 } else if (isa<PointerType>(DestTy)) { // Casting to pointer
2142 if (isa<PointerType>(SrcTy)) { // Casting from pointer
2144 } else if (SrcTy->isInteger()) { // Casting from integral
2146 } else { // Casting from something else
2149 } else { // Casting to something else
2154 // Provide a way to get a "cast" where the cast opcode is inferred from the
2155 // types and size of the operand. This, basically, is a parallel of the
2156 // logic in the castIsValid function below. This axiom should hold:
2157 // castIsValid( getCastOpcode(Val, Ty), Val, Ty)
2158 // should not assert in castIsValid. In other words, this produces a "correct"
2159 // casting opcode for the arguments passed to it.
2160 // This routine must be kept in sync with isCastable.
2161 Instruction::CastOps
2162 CastInst::getCastOpcode(
2163 const Value *Src, bool SrcIsSigned, const Type *DestTy, bool DestIsSigned) {
2164 // Get the bit sizes, we'll need these
2165 const Type *SrcTy = Src->getType();
2166 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); // 0 for ptr/vector
2167 unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr/vector
2169 assert(SrcTy->isFirstClassType() && DestTy->isFirstClassType() &&
2170 "Only first class types are castable!");
2172 // Run through the possibilities ...
2173 if (DestTy->isInteger()) { // Casting to integral
2174 if (SrcTy->isInteger()) { // Casting from integral
2175 if (DestBits < SrcBits)
2176 return Trunc; // int -> smaller int
2177 else if (DestBits > SrcBits) { // its an extension
2179 return SExt; // signed -> SEXT
2181 return ZExt; // unsigned -> ZEXT
2183 return BitCast; // Same size, No-op cast
2185 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt
2187 return FPToSI; // FP -> sint
2189 return FPToUI; // FP -> uint
2190 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
2191 assert(DestBits == PTy->getBitWidth() &&
2192 "Casting vector to integer of different width");
2193 return BitCast; // Same size, no-op cast
2195 assert(isa<PointerType>(SrcTy) &&
2196 "Casting from a value that is not first-class type");
2197 return PtrToInt; // ptr -> int
2199 } else if (DestTy->isFloatingPoint()) { // Casting to floating pt
2200 if (SrcTy->isInteger()) { // Casting from integral
2202 return SIToFP; // sint -> FP
2204 return UIToFP; // uint -> FP
2205 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt
2206 if (DestBits < SrcBits) {
2207 return FPTrunc; // FP -> smaller FP
2208 } else if (DestBits > SrcBits) {
2209 return FPExt; // FP -> larger FP
2211 return BitCast; // same size, no-op cast
2213 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
2214 assert(DestBits == PTy->getBitWidth() &&
2215 "Casting vector to floating point of different width");
2216 return BitCast; // same size, no-op cast
2218 assert(0 && "Casting pointer or non-first class to float");
2220 } else if (const VectorType *DestPTy = dyn_cast<VectorType>(DestTy)) {
2221 if (const VectorType *SrcPTy = dyn_cast<VectorType>(SrcTy)) {
2222 assert(DestPTy->getBitWidth() == SrcPTy->getBitWidth() &&
2223 "Casting vector to vector of different widths");
2224 return BitCast; // vector -> vector
2225 } else if (DestPTy->getBitWidth() == SrcBits) {
2226 return BitCast; // float/int -> vector
2228 assert(!"Illegal cast to vector (wrong type or size)");
2230 } else if (isa<PointerType>(DestTy)) {
2231 if (isa<PointerType>(SrcTy)) {
2232 return BitCast; // ptr -> ptr
2233 } else if (SrcTy->isInteger()) {
2234 return IntToPtr; // int -> ptr
2236 assert(!"Casting pointer to other than pointer or int");
2239 assert(!"Casting to type that is not first-class");
2242 // If we fall through to here we probably hit an assertion cast above
2243 // and assertions are not turned on. Anything we return is an error, so
2244 // BitCast is as good a choice as any.
2248 //===----------------------------------------------------------------------===//
2249 // CastInst SubClass Constructors
2250 //===----------------------------------------------------------------------===//
2252 /// Check that the construction parameters for a CastInst are correct. This
2253 /// could be broken out into the separate constructors but it is useful to have
2254 /// it in one place and to eliminate the redundant code for getting the sizes
2255 /// of the types involved.
2257 CastInst::castIsValid(Instruction::CastOps op, Value *S, const Type *DstTy) {
2259 // Check for type sanity on the arguments
2260 const Type *SrcTy = S->getType();
2261 if (!SrcTy->isFirstClassType() || !DstTy->isFirstClassType())
2264 // Get the size of the types in bits, we'll need this later
2265 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
2266 unsigned DstBitSize = DstTy->getPrimitiveSizeInBits();
2268 // Switch on the opcode provided
2270 default: return false; // This is an input error
2271 case Instruction::Trunc:
2272 return SrcTy->isInteger() && DstTy->isInteger()&& SrcBitSize > DstBitSize;
2273 case Instruction::ZExt:
2274 return SrcTy->isInteger() && DstTy->isInteger()&& SrcBitSize < DstBitSize;
2275 case Instruction::SExt:
2276 return SrcTy->isInteger() && DstTy->isInteger()&& SrcBitSize < DstBitSize;
2277 case Instruction::FPTrunc:
2278 return SrcTy->isFloatingPoint() && DstTy->isFloatingPoint() &&
2279 SrcBitSize > DstBitSize;
2280 case Instruction::FPExt:
2281 return SrcTy->isFloatingPoint() && DstTy->isFloatingPoint() &&
2282 SrcBitSize < DstBitSize;
2283 case Instruction::UIToFP:
2284 case Instruction::SIToFP:
2285 if (const VectorType *SVTy = dyn_cast<VectorType>(SrcTy)) {
2286 if (const VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
2287 return SVTy->getElementType()->isInteger() &&
2288 DVTy->getElementType()->isFloatingPoint() &&
2289 SVTy->getNumElements() == DVTy->getNumElements();
2292 return SrcTy->isInteger() && DstTy->isFloatingPoint();
2293 case Instruction::FPToUI:
2294 case Instruction::FPToSI:
2295 if (const VectorType *SVTy = dyn_cast<VectorType>(SrcTy)) {
2296 if (const VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
2297 return SVTy->getElementType()->isFloatingPoint() &&
2298 DVTy->getElementType()->isInteger() &&
2299 SVTy->getNumElements() == DVTy->getNumElements();
2302 return SrcTy->isFloatingPoint() && DstTy->isInteger();
2303 case Instruction::PtrToInt:
2304 return isa<PointerType>(SrcTy) && DstTy->isInteger();
2305 case Instruction::IntToPtr:
2306 return SrcTy->isInteger() && isa<PointerType>(DstTy);
2307 case Instruction::BitCast:
2308 // BitCast implies a no-op cast of type only. No bits change.
2309 // However, you can't cast pointers to anything but pointers.
2310 if (isa<PointerType>(SrcTy) != isa<PointerType>(DstTy))
2313 // Now we know we're not dealing with a pointer/non-pointer mismatch. In all
2314 // these cases, the cast is okay if the source and destination bit widths
2316 return SrcBitSize == DstBitSize;
2320 TruncInst::TruncInst(
2321 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2322 ) : CastInst(Ty, Trunc, S, Name, InsertBefore) {
2323 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
2326 TruncInst::TruncInst(
2327 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2328 ) : CastInst(Ty, Trunc, S, Name, InsertAtEnd) {
2329 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
2333 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2334 ) : CastInst(Ty, ZExt, S, Name, InsertBefore) {
2335 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
2339 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2340 ) : CastInst(Ty, ZExt, S, Name, InsertAtEnd) {
2341 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
2344 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2345 ) : CastInst(Ty, SExt, S, Name, InsertBefore) {
2346 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
2350 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2351 ) : CastInst(Ty, SExt, S, Name, InsertAtEnd) {
2352 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
2355 FPTruncInst::FPTruncInst(
2356 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2357 ) : CastInst(Ty, FPTrunc, S, Name, InsertBefore) {
2358 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
2361 FPTruncInst::FPTruncInst(
2362 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2363 ) : CastInst(Ty, FPTrunc, S, Name, InsertAtEnd) {
2364 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
2367 FPExtInst::FPExtInst(
2368 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2369 ) : CastInst(Ty, FPExt, S, Name, InsertBefore) {
2370 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
2373 FPExtInst::FPExtInst(
2374 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2375 ) : CastInst(Ty, FPExt, S, Name, InsertAtEnd) {
2376 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
2379 UIToFPInst::UIToFPInst(
2380 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2381 ) : CastInst(Ty, UIToFP, S, Name, InsertBefore) {
2382 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
2385 UIToFPInst::UIToFPInst(
2386 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2387 ) : CastInst(Ty, UIToFP, S, Name, InsertAtEnd) {
2388 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
2391 SIToFPInst::SIToFPInst(
2392 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2393 ) : CastInst(Ty, SIToFP, S, Name, InsertBefore) {
2394 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
2397 SIToFPInst::SIToFPInst(
2398 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2399 ) : CastInst(Ty, SIToFP, S, Name, InsertAtEnd) {
2400 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
2403 FPToUIInst::FPToUIInst(
2404 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2405 ) : CastInst(Ty, FPToUI, S, Name, InsertBefore) {
2406 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
2409 FPToUIInst::FPToUIInst(
2410 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2411 ) : CastInst(Ty, FPToUI, S, Name, InsertAtEnd) {
2412 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
2415 FPToSIInst::FPToSIInst(
2416 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2417 ) : CastInst(Ty, FPToSI, S, Name, InsertBefore) {
2418 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
2421 FPToSIInst::FPToSIInst(
2422 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2423 ) : CastInst(Ty, FPToSI, S, Name, InsertAtEnd) {
2424 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
2427 PtrToIntInst::PtrToIntInst(
2428 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2429 ) : CastInst(Ty, PtrToInt, S, Name, InsertBefore) {
2430 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
2433 PtrToIntInst::PtrToIntInst(
2434 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2435 ) : CastInst(Ty, PtrToInt, S, Name, InsertAtEnd) {
2436 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
2439 IntToPtrInst::IntToPtrInst(
2440 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2441 ) : CastInst(Ty, IntToPtr, S, Name, InsertBefore) {
2442 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
2445 IntToPtrInst::IntToPtrInst(
2446 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2447 ) : CastInst(Ty, IntToPtr, S, Name, InsertAtEnd) {
2448 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
2451 BitCastInst::BitCastInst(
2452 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2453 ) : CastInst(Ty, BitCast, S, Name, InsertBefore) {
2454 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
2457 BitCastInst::BitCastInst(
2458 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2459 ) : CastInst(Ty, BitCast, S, Name, InsertAtEnd) {
2460 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
2463 //===----------------------------------------------------------------------===//
2465 //===----------------------------------------------------------------------===//
2467 CmpInst::CmpInst(const Type *ty, OtherOps op, unsigned short predicate,
2468 Value *LHS, Value *RHS, const std::string &Name,
2469 Instruction *InsertBefore)
2470 : Instruction(ty, op,
2471 OperandTraits<CmpInst>::op_begin(this),
2472 OperandTraits<CmpInst>::operands(this),
2476 SubclassData = predicate;
2480 CmpInst::CmpInst(const Type *ty, OtherOps op, unsigned short predicate,
2481 Value *LHS, Value *RHS, const std::string &Name,
2482 BasicBlock *InsertAtEnd)
2483 : Instruction(ty, op,
2484 OperandTraits<CmpInst>::op_begin(this),
2485 OperandTraits<CmpInst>::operands(this),
2489 SubclassData = predicate;
2494 CmpInst::Create(OtherOps Op, unsigned short predicate, Value *S1, Value *S2,
2495 const std::string &Name, Instruction *InsertBefore) {
2496 if (Op == Instruction::ICmp) {
2497 return new ICmpInst(CmpInst::Predicate(predicate), S1, S2, Name,
2500 if (Op == Instruction::FCmp) {
2501 return new FCmpInst(CmpInst::Predicate(predicate), S1, S2, Name,
2504 if (Op == Instruction::VICmp) {
2505 return new VICmpInst(CmpInst::Predicate(predicate), S1, S2, Name,
2508 return new VFCmpInst(CmpInst::Predicate(predicate), S1, S2, Name,
2513 CmpInst::Create(OtherOps Op, unsigned short predicate, Value *S1, Value *S2,
2514 const std::string &Name, BasicBlock *InsertAtEnd) {
2515 if (Op == Instruction::ICmp) {
2516 return new ICmpInst(CmpInst::Predicate(predicate), S1, S2, Name,
2519 if (Op == Instruction::FCmp) {
2520 return new FCmpInst(CmpInst::Predicate(predicate), S1, S2, Name,
2523 if (Op == Instruction::VICmp) {
2524 return new VICmpInst(CmpInst::Predicate(predicate), S1, S2, Name,
2527 return new VFCmpInst(CmpInst::Predicate(predicate), S1, S2, Name,
2531 void CmpInst::swapOperands() {
2532 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2535 cast<FCmpInst>(this)->swapOperands();
2538 bool CmpInst::isCommutative() {
2539 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2540 return IC->isCommutative();
2541 return cast<FCmpInst>(this)->isCommutative();
2544 bool CmpInst::isEquality() {
2545 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2546 return IC->isEquality();
2547 return cast<FCmpInst>(this)->isEquality();
2551 CmpInst::Predicate CmpInst::getInversePredicate(Predicate pred) {
2553 default: assert(!"Unknown cmp predicate!");
2554 case ICMP_EQ: return ICMP_NE;
2555 case ICMP_NE: return ICMP_EQ;
2556 case ICMP_UGT: return ICMP_ULE;
2557 case ICMP_ULT: return ICMP_UGE;
2558 case ICMP_UGE: return ICMP_ULT;
2559 case ICMP_ULE: return ICMP_UGT;
2560 case ICMP_SGT: return ICMP_SLE;
2561 case ICMP_SLT: return ICMP_SGE;
2562 case ICMP_SGE: return ICMP_SLT;
2563 case ICMP_SLE: return ICMP_SGT;
2565 case FCMP_OEQ: return FCMP_UNE;
2566 case FCMP_ONE: return FCMP_UEQ;
2567 case FCMP_OGT: return FCMP_ULE;
2568 case FCMP_OLT: return FCMP_UGE;
2569 case FCMP_OGE: return FCMP_ULT;
2570 case FCMP_OLE: return FCMP_UGT;
2571 case FCMP_UEQ: return FCMP_ONE;
2572 case FCMP_UNE: return FCMP_OEQ;
2573 case FCMP_UGT: return FCMP_OLE;
2574 case FCMP_ULT: return FCMP_OGE;
2575 case FCMP_UGE: return FCMP_OLT;
2576 case FCMP_ULE: return FCMP_OGT;
2577 case FCMP_ORD: return FCMP_UNO;
2578 case FCMP_UNO: return FCMP_ORD;
2579 case FCMP_TRUE: return FCMP_FALSE;
2580 case FCMP_FALSE: return FCMP_TRUE;
2584 ICmpInst::Predicate ICmpInst::getSignedPredicate(Predicate pred) {
2586 default: assert(! "Unknown icmp predicate!");
2587 case ICMP_EQ: case ICMP_NE:
2588 case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE:
2590 case ICMP_UGT: return ICMP_SGT;
2591 case ICMP_ULT: return ICMP_SLT;
2592 case ICMP_UGE: return ICMP_SGE;
2593 case ICMP_ULE: return ICMP_SLE;
2597 ICmpInst::Predicate ICmpInst::getUnsignedPredicate(Predicate pred) {
2599 default: assert(! "Unknown icmp predicate!");
2600 case ICMP_EQ: case ICMP_NE:
2601 case ICMP_UGT: case ICMP_ULT: case ICMP_UGE: case ICMP_ULE:
2603 case ICMP_SGT: return ICMP_UGT;
2604 case ICMP_SLT: return ICMP_ULT;
2605 case ICMP_SGE: return ICMP_UGE;
2606 case ICMP_SLE: return ICMP_ULE;
2610 bool ICmpInst::isSignedPredicate(Predicate pred) {
2612 default: assert(! "Unknown icmp predicate!");
2613 case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE:
2615 case ICMP_EQ: case ICMP_NE: case ICMP_UGT: case ICMP_ULT:
2616 case ICMP_UGE: case ICMP_ULE:
2621 /// Initialize a set of values that all satisfy the condition with C.
2624 ICmpInst::makeConstantRange(Predicate pred, const APInt &C) {
2627 uint32_t BitWidth = C.getBitWidth();
2629 default: assert(0 && "Invalid ICmp opcode to ConstantRange ctor!");
2630 case ICmpInst::ICMP_EQ: Upper++; break;
2631 case ICmpInst::ICMP_NE: Lower++; break;
2632 case ICmpInst::ICMP_ULT: Lower = APInt::getMinValue(BitWidth); break;
2633 case ICmpInst::ICMP_SLT: Lower = APInt::getSignedMinValue(BitWidth); break;
2634 case ICmpInst::ICMP_UGT:
2635 Lower++; Upper = APInt::getMinValue(BitWidth); // Min = Next(Max)
2637 case ICmpInst::ICMP_SGT:
2638 Lower++; Upper = APInt::getSignedMinValue(BitWidth); // Min = Next(Max)
2640 case ICmpInst::ICMP_ULE:
2641 Lower = APInt::getMinValue(BitWidth); Upper++;
2643 case ICmpInst::ICMP_SLE:
2644 Lower = APInt::getSignedMinValue(BitWidth); Upper++;
2646 case ICmpInst::ICMP_UGE:
2647 Upper = APInt::getMinValue(BitWidth); // Min = Next(Max)
2649 case ICmpInst::ICMP_SGE:
2650 Upper = APInt::getSignedMinValue(BitWidth); // Min = Next(Max)
2653 return ConstantRange(Lower, Upper);
2656 CmpInst::Predicate CmpInst::getSwappedPredicate(Predicate pred) {
2658 default: assert(!"Unknown cmp predicate!");
2659 case ICMP_EQ: case ICMP_NE:
2661 case ICMP_SGT: return ICMP_SLT;
2662 case ICMP_SLT: return ICMP_SGT;
2663 case ICMP_SGE: return ICMP_SLE;
2664 case ICMP_SLE: return ICMP_SGE;
2665 case ICMP_UGT: return ICMP_ULT;
2666 case ICMP_ULT: return ICMP_UGT;
2667 case ICMP_UGE: return ICMP_ULE;
2668 case ICMP_ULE: return ICMP_UGE;
2670 case FCMP_FALSE: case FCMP_TRUE:
2671 case FCMP_OEQ: case FCMP_ONE:
2672 case FCMP_UEQ: case FCMP_UNE:
2673 case FCMP_ORD: case FCMP_UNO:
2675 case FCMP_OGT: return FCMP_OLT;
2676 case FCMP_OLT: return FCMP_OGT;
2677 case FCMP_OGE: return FCMP_OLE;
2678 case FCMP_OLE: return FCMP_OGE;
2679 case FCMP_UGT: return FCMP_ULT;
2680 case FCMP_ULT: return FCMP_UGT;
2681 case FCMP_UGE: return FCMP_ULE;
2682 case FCMP_ULE: return FCMP_UGE;
2686 bool CmpInst::isUnsigned(unsigned short predicate) {
2687 switch (predicate) {
2688 default: return false;
2689 case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_ULE: case ICmpInst::ICMP_UGT:
2690 case ICmpInst::ICMP_UGE: return true;
2694 bool CmpInst::isSigned(unsigned short predicate){
2695 switch (predicate) {
2696 default: return false;
2697 case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_SLE: case ICmpInst::ICMP_SGT:
2698 case ICmpInst::ICMP_SGE: return true;
2702 bool CmpInst::isOrdered(unsigned short predicate) {
2703 switch (predicate) {
2704 default: return false;
2705 case FCmpInst::FCMP_OEQ: case FCmpInst::FCMP_ONE: case FCmpInst::FCMP_OGT:
2706 case FCmpInst::FCMP_OLT: case FCmpInst::FCMP_OGE: case FCmpInst::FCMP_OLE:
2707 case FCmpInst::FCMP_ORD: return true;
2711 bool CmpInst::isUnordered(unsigned short predicate) {
2712 switch (predicate) {
2713 default: return false;
2714 case FCmpInst::FCMP_UEQ: case FCmpInst::FCMP_UNE: case FCmpInst::FCMP_UGT:
2715 case FCmpInst::FCMP_ULT: case FCmpInst::FCMP_UGE: case FCmpInst::FCMP_ULE:
2716 case FCmpInst::FCMP_UNO: return true;
2720 //===----------------------------------------------------------------------===//
2721 // SwitchInst Implementation
2722 //===----------------------------------------------------------------------===//
2724 void SwitchInst::init(Value *Value, BasicBlock *Default, unsigned NumCases) {
2725 assert(Value && Default);
2726 ReservedSpace = 2+NumCases*2;
2728 OperandList = allocHungoffUses(ReservedSpace);
2730 OperandList[0] = Value;
2731 OperandList[1] = Default;
2734 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
2735 /// switch on and a default destination. The number of additional cases can
2736 /// be specified here to make memory allocation more efficient. This
2737 /// constructor can also autoinsert before another instruction.
2738 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
2739 Instruction *InsertBefore)
2740 : TerminatorInst(Type::VoidTy, Instruction::Switch, 0, 0, InsertBefore) {
2741 init(Value, Default, NumCases);
2744 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
2745 /// switch on and a default destination. The number of additional cases can
2746 /// be specified here to make memory allocation more efficient. This
2747 /// constructor also autoinserts at the end of the specified BasicBlock.
2748 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
2749 BasicBlock *InsertAtEnd)
2750 : TerminatorInst(Type::VoidTy, Instruction::Switch, 0, 0, InsertAtEnd) {
2751 init(Value, Default, NumCases);
2754 SwitchInst::SwitchInst(const SwitchInst &SI)
2755 : TerminatorInst(Type::VoidTy, Instruction::Switch,
2756 allocHungoffUses(SI.getNumOperands()), SI.getNumOperands()) {
2757 Use *OL = OperandList, *InOL = SI.OperandList;
2758 for (unsigned i = 0, E = SI.getNumOperands(); i != E; i+=2) {
2760 OL[i+1] = InOL[i+1];
2764 SwitchInst::~SwitchInst() {
2765 dropHungoffUses(OperandList);
2769 /// addCase - Add an entry to the switch instruction...
2771 void SwitchInst::addCase(ConstantInt *OnVal, BasicBlock *Dest) {
2772 unsigned OpNo = NumOperands;
2773 if (OpNo+2 > ReservedSpace)
2774 resizeOperands(0); // Get more space!
2775 // Initialize some new operands.
2776 assert(OpNo+1 < ReservedSpace && "Growing didn't work!");
2777 NumOperands = OpNo+2;
2778 OperandList[OpNo] = OnVal;
2779 OperandList[OpNo+1] = Dest;
2782 /// removeCase - This method removes the specified successor from the switch
2783 /// instruction. Note that this cannot be used to remove the default
2784 /// destination (successor #0).
2786 void SwitchInst::removeCase(unsigned idx) {
2787 assert(idx != 0 && "Cannot remove the default case!");
2788 assert(idx*2 < getNumOperands() && "Successor index out of range!!!");
2790 unsigned NumOps = getNumOperands();
2791 Use *OL = OperandList;
2793 // Move everything after this operand down.
2795 // FIXME: we could just swap with the end of the list, then erase. However,
2796 // client might not expect this to happen. The code as it is thrashes the
2797 // use/def lists, which is kinda lame.
2798 for (unsigned i = (idx+1)*2; i != NumOps; i += 2) {
2800 OL[i-2+1] = OL[i+1];
2803 // Nuke the last value.
2804 OL[NumOps-2].set(0);
2805 OL[NumOps-2+1].set(0);
2806 NumOperands = NumOps-2;
2809 /// resizeOperands - resize operands - This adjusts the length of the operands
2810 /// list according to the following behavior:
2811 /// 1. If NumOps == 0, grow the operand list in response to a push_back style
2812 /// of operation. This grows the number of ops by 3 times.
2813 /// 2. If NumOps > NumOperands, reserve space for NumOps operands.
2814 /// 3. If NumOps == NumOperands, trim the reserved space.
2816 void SwitchInst::resizeOperands(unsigned NumOps) {
2817 unsigned e = getNumOperands();
2820 } else if (NumOps*2 > NumOperands) {
2821 // No resize needed.
2822 if (ReservedSpace >= NumOps) return;
2823 } else if (NumOps == NumOperands) {
2824 if (ReservedSpace == NumOps) return;
2829 ReservedSpace = NumOps;
2830 Use *NewOps = allocHungoffUses(NumOps);
2831 Use *OldOps = OperandList;
2832 for (unsigned i = 0; i != e; ++i) {
2833 NewOps[i] = OldOps[i];
2835 OperandList = NewOps;
2836 if (OldOps) Use::zap(OldOps, OldOps + e, true);
2840 BasicBlock *SwitchInst::getSuccessorV(unsigned idx) const {
2841 return getSuccessor(idx);
2843 unsigned SwitchInst::getNumSuccessorsV() const {
2844 return getNumSuccessors();
2846 void SwitchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
2847 setSuccessor(idx, B);
2850 //===----------------------------------------------------------------------===//
2851 // GetResultInst Implementation
2852 //===----------------------------------------------------------------------===//
2854 GetResultInst::GetResultInst(Value *Aggregate, unsigned Index,
2855 const std::string &Name,
2856 Instruction *InsertBef)
2857 : UnaryInstruction(cast<StructType>(Aggregate->getType())
2858 ->getElementType(Index),
2859 GetResult, Aggregate, InsertBef),
2861 assert(isValidOperands(Aggregate, Index)
2862 && "Invalid GetResultInst operands!");
2866 bool GetResultInst::isValidOperands(const Value *Aggregate, unsigned Index) {
2870 if (const StructType *STy = dyn_cast<StructType>(Aggregate->getType())) {
2871 unsigned NumElements = STy->getNumElements();
2872 if (Index >= NumElements || NumElements == 0)
2875 // getresult aggregate value's element types are restricted to
2876 // avoid nested aggregates.
2877 for (unsigned i = 0; i < NumElements; ++i)
2878 if (!STy->getElementType(i)->isFirstClassType())
2881 // Otherwise, Aggregate is valid.
2887 // Define these methods here so vtables don't get emitted into every translation
2888 // unit that uses these classes.
2890 GetElementPtrInst *GetElementPtrInst::clone() const {
2891 return new(getNumOperands()) GetElementPtrInst(*this);
2894 BinaryOperator *BinaryOperator::clone() const {
2895 return Create(getOpcode(), Op<0>(), Op<1>());
2898 FCmpInst* FCmpInst::clone() const {
2899 return new FCmpInst(getPredicate(), Op<0>(), Op<1>());
2901 ICmpInst* ICmpInst::clone() const {
2902 return new ICmpInst(getPredicate(), Op<0>(), Op<1>());
2905 VFCmpInst* VFCmpInst::clone() const {
2906 return new VFCmpInst(getPredicate(), Op<0>(), Op<1>());
2908 VICmpInst* VICmpInst::clone() const {
2909 return new VICmpInst(getPredicate(), Op<0>(), Op<1>());
2912 ExtractValueInst *ExtractValueInst::clone() const {
2913 return new ExtractValueInst(*this);
2915 InsertValueInst *InsertValueInst::clone() const {
2916 return new InsertValueInst(*this);
2920 MallocInst *MallocInst::clone() const { return new MallocInst(*this); }
2921 AllocaInst *AllocaInst::clone() const { return new AllocaInst(*this); }
2922 FreeInst *FreeInst::clone() const { return new FreeInst(getOperand(0)); }
2923 LoadInst *LoadInst::clone() const { return new LoadInst(*this); }
2924 StoreInst *StoreInst::clone() const { return new StoreInst(*this); }
2925 CastInst *TruncInst::clone() const { return new TruncInst(*this); }
2926 CastInst *ZExtInst::clone() const { return new ZExtInst(*this); }
2927 CastInst *SExtInst::clone() const { return new SExtInst(*this); }
2928 CastInst *FPTruncInst::clone() const { return new FPTruncInst(*this); }
2929 CastInst *FPExtInst::clone() const { return new FPExtInst(*this); }
2930 CastInst *UIToFPInst::clone() const { return new UIToFPInst(*this); }
2931 CastInst *SIToFPInst::clone() const { return new SIToFPInst(*this); }
2932 CastInst *FPToUIInst::clone() const { return new FPToUIInst(*this); }
2933 CastInst *FPToSIInst::clone() const { return new FPToSIInst(*this); }
2934 CastInst *PtrToIntInst::clone() const { return new PtrToIntInst(*this); }
2935 CastInst *IntToPtrInst::clone() const { return new IntToPtrInst(*this); }
2936 CastInst *BitCastInst::clone() const { return new BitCastInst(*this); }
2937 CallInst *CallInst::clone() const {
2938 return new(getNumOperands()) CallInst(*this);
2940 SelectInst *SelectInst::clone() const {
2941 return new(getNumOperands()) SelectInst(*this);
2943 VAArgInst *VAArgInst::clone() const { return new VAArgInst(*this); }
2945 ExtractElementInst *ExtractElementInst::clone() const {
2946 return new ExtractElementInst(*this);
2948 InsertElementInst *InsertElementInst::clone() const {
2949 return InsertElementInst::Create(*this);
2951 ShuffleVectorInst *ShuffleVectorInst::clone() const {
2952 return new ShuffleVectorInst(*this);
2954 PHINode *PHINode::clone() const { return new PHINode(*this); }
2955 ReturnInst *ReturnInst::clone() const {
2956 return new(getNumOperands()) ReturnInst(*this);
2958 BranchInst *BranchInst::clone() const {
2959 return new(getNumOperands()) BranchInst(*this);
2961 SwitchInst *SwitchInst::clone() const { return new SwitchInst(*this); }
2962 InvokeInst *InvokeInst::clone() const {
2963 return new(getNumOperands()) InvokeInst(*this);
2965 UnwindInst *UnwindInst::clone() const { return new UnwindInst(); }
2966 UnreachableInst *UnreachableInst::clone() const { return new UnreachableInst();}
2967 GetResultInst *GetResultInst::clone() const { return new GetResultInst(*this); }