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 #define CALLSITE_DELEGATE_GETTER(METHOD) \
29 Instruction *II(getInstruction()); \
31 ? cast<CallInst>(II)->METHOD \
32 : cast<InvokeInst>(II)->METHOD
34 #define CALLSITE_DELEGATE_SETTER(METHOD) \
35 Instruction *II(getInstruction()); \
37 cast<CallInst>(II)->METHOD; \
39 cast<InvokeInst>(II)->METHOD
41 CallSite::CallSite(Instruction *C) {
42 assert((isa<CallInst>(C) || isa<InvokeInst>(C)) && "Not a call!");
44 I.setInt(isa<CallInst>(C));
46 unsigned CallSite::getCallingConv() const {
47 CALLSITE_DELEGATE_GETTER(getCallingConv());
49 void CallSite::setCallingConv(unsigned CC) {
50 CALLSITE_DELEGATE_SETTER(setCallingConv(CC));
52 const AttrListPtr &CallSite::getAttributes() const {
53 CALLSITE_DELEGATE_GETTER(getAttributes());
55 void CallSite::setAttributes(const AttrListPtr &PAL) {
56 CALLSITE_DELEGATE_SETTER(setAttributes(PAL));
58 bool CallSite::paramHasAttr(uint16_t i, Attributes attr) const {
59 CALLSITE_DELEGATE_GETTER(paramHasAttr(i, attr));
61 uint16_t CallSite::getParamAlignment(uint16_t i) const {
62 CALLSITE_DELEGATE_GETTER(getParamAlignment(i));
64 bool CallSite::doesNotAccessMemory() const {
65 CALLSITE_DELEGATE_GETTER(doesNotAccessMemory());
67 void CallSite::setDoesNotAccessMemory(bool doesNotAccessMemory) {
68 CALLSITE_DELEGATE_SETTER(setDoesNotAccessMemory(doesNotAccessMemory));
70 bool CallSite::onlyReadsMemory() const {
71 CALLSITE_DELEGATE_GETTER(onlyReadsMemory());
73 void CallSite::setOnlyReadsMemory(bool onlyReadsMemory) {
74 CALLSITE_DELEGATE_SETTER(setOnlyReadsMemory(onlyReadsMemory));
76 bool CallSite::doesNotReturn() const {
77 CALLSITE_DELEGATE_GETTER(doesNotReturn());
79 void CallSite::setDoesNotReturn(bool doesNotReturn) {
80 CALLSITE_DELEGATE_SETTER(setDoesNotReturn(doesNotReturn));
82 bool CallSite::doesNotThrow() const {
83 CALLSITE_DELEGATE_GETTER(doesNotThrow());
85 void CallSite::setDoesNotThrow(bool doesNotThrow) {
86 CALLSITE_DELEGATE_SETTER(setDoesNotThrow(doesNotThrow));
89 bool CallSite::hasArgument(const Value *Arg) const {
90 for (arg_iterator AI = this->arg_begin(), E = this->arg_end(); AI != E; ++AI)
96 User::op_iterator CallSite::getCallee() const {
97 Instruction *II(getInstruction());
99 ? cast<CallInst>(II)->op_begin()
100 : cast<InvokeInst>(II)->op_end() - 3; // Skip BB, BB, Function
103 #undef CALLSITE_DELEGATE_GETTER
104 #undef CALLSITE_DELEGATE_SETTER
106 //===----------------------------------------------------------------------===//
107 // TerminatorInst Class
108 //===----------------------------------------------------------------------===//
110 // Out of line virtual method, so the vtable, etc has a home.
111 TerminatorInst::~TerminatorInst() {
114 //===----------------------------------------------------------------------===//
115 // UnaryInstruction Class
116 //===----------------------------------------------------------------------===//
118 // Out of line virtual method, so the vtable, etc has a home.
119 UnaryInstruction::~UnaryInstruction() {
122 //===----------------------------------------------------------------------===//
124 //===----------------------------------------------------------------------===//
126 /// areInvalidOperands - Return a string if the specified operands are invalid
127 /// for a select operation, otherwise return null.
128 const char *SelectInst::areInvalidOperands(Value *Op0, Value *Op1, Value *Op2) {
129 if (Op1->getType() != Op2->getType())
130 return "both values to select must have same type";
132 if (const VectorType *VT = dyn_cast<VectorType>(Op0->getType())) {
134 if (VT->getElementType() != Type::Int1Ty)
135 return "vector select condition element type must be i1";
136 const VectorType *ET = dyn_cast<VectorType>(Op1->getType());
138 return "selected values for vector select must be vectors";
139 if (ET->getNumElements() != VT->getNumElements())
140 return "vector select requires selected vectors to have "
141 "the same vector length as select condition";
142 } else if (Op0->getType() != Type::Int1Ty) {
143 return "select condition must be i1 or <n x i1>";
149 //===----------------------------------------------------------------------===//
151 //===----------------------------------------------------------------------===//
153 PHINode::PHINode(const PHINode &PN)
154 : Instruction(PN.getType(), Instruction::PHI,
155 allocHungoffUses(PN.getNumOperands()), PN.getNumOperands()),
156 ReservedSpace(PN.getNumOperands()) {
157 Use *OL = OperandList;
158 for (unsigned i = 0, e = PN.getNumOperands(); i != e; i+=2) {
159 OL[i] = PN.getOperand(i);
160 OL[i+1] = PN.getOperand(i+1);
164 PHINode::~PHINode() {
166 dropHungoffUses(OperandList);
169 // removeIncomingValue - Remove an incoming value. This is useful if a
170 // predecessor basic block is deleted.
171 Value *PHINode::removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty) {
172 unsigned NumOps = getNumOperands();
173 Use *OL = OperandList;
174 assert(Idx*2 < NumOps && "BB not in PHI node!");
175 Value *Removed = OL[Idx*2];
177 // Move everything after this operand down.
179 // FIXME: we could just swap with the end of the list, then erase. However,
180 // client might not expect this to happen. The code as it is thrashes the
181 // use/def lists, which is kinda lame.
182 for (unsigned i = (Idx+1)*2; i != NumOps; i += 2) {
187 // Nuke the last value.
189 OL[NumOps-2+1].set(0);
190 NumOperands = NumOps-2;
192 // If the PHI node is dead, because it has zero entries, nuke it now.
193 if (NumOps == 2 && DeletePHIIfEmpty) {
194 // If anyone is using this PHI, make them use a dummy value instead...
195 replaceAllUsesWith(UndefValue::get(getType()));
201 /// resizeOperands - resize operands - This adjusts the length of the operands
202 /// list according to the following behavior:
203 /// 1. If NumOps == 0, grow the operand list in response to a push_back style
204 /// of operation. This grows the number of ops by 1.5 times.
205 /// 2. If NumOps > NumOperands, reserve space for NumOps operands.
206 /// 3. If NumOps == NumOperands, trim the reserved space.
208 void PHINode::resizeOperands(unsigned NumOps) {
209 unsigned e = getNumOperands();
212 if (NumOps < 4) NumOps = 4; // 4 op PHI nodes are VERY common.
213 } else if (NumOps*2 > NumOperands) {
215 if (ReservedSpace >= NumOps) return;
216 } else if (NumOps == NumOperands) {
217 if (ReservedSpace == NumOps) return;
222 ReservedSpace = NumOps;
223 Use *OldOps = OperandList;
224 Use *NewOps = allocHungoffUses(NumOps);
225 std::copy(OldOps, OldOps + e, NewOps);
226 OperandList = NewOps;
227 if (OldOps) Use::zap(OldOps, OldOps + e, true);
230 /// hasConstantValue - If the specified PHI node always merges together the same
231 /// value, return the value, otherwise return null.
233 Value *PHINode::hasConstantValue(bool AllowNonDominatingInstruction) const {
234 // If the PHI node only has one incoming value, eliminate the PHI node...
235 if (getNumIncomingValues() == 1) {
236 if (getIncomingValue(0) != this) // not X = phi X
237 return getIncomingValue(0);
239 return UndefValue::get(getType()); // Self cycle is dead.
242 // Otherwise if all of the incoming values are the same for the PHI, replace
243 // the PHI node with the incoming value.
246 bool HasUndefInput = false;
247 for (unsigned i = 0, e = getNumIncomingValues(); i != e; ++i)
248 if (isa<UndefValue>(getIncomingValue(i))) {
249 HasUndefInput = true;
250 } else if (getIncomingValue(i) != this) { // Not the PHI node itself...
251 if (InVal && getIncomingValue(i) != InVal)
252 return 0; // Not the same, bail out.
254 InVal = getIncomingValue(i);
257 // The only case that could cause InVal to be null is if we have a PHI node
258 // that only has entries for itself. In this case, there is no entry into the
259 // loop, so kill the PHI.
261 if (InVal == 0) InVal = UndefValue::get(getType());
263 // If we have a PHI node like phi(X, undef, X), where X is defined by some
264 // instruction, we cannot always return X as the result of the PHI node. Only
265 // do this if X is not an instruction (thus it must dominate the PHI block),
266 // or if the client is prepared to deal with this possibility.
267 if (HasUndefInput && !AllowNonDominatingInstruction)
268 if (Instruction *IV = dyn_cast<Instruction>(InVal))
269 // If it's in the entry block, it dominates everything.
270 if (IV->getParent() != &IV->getParent()->getParent()->getEntryBlock() ||
272 return 0; // Cannot guarantee that InVal dominates this PHINode.
274 // All of the incoming values are the same, return the value now.
279 //===----------------------------------------------------------------------===//
280 // CallInst Implementation
281 //===----------------------------------------------------------------------===//
283 CallInst::~CallInst() {
286 void CallInst::init(Value *Func, Value* const *Params, unsigned NumParams) {
287 assert(NumOperands == NumParams+1 && "NumOperands not set up?");
288 Use *OL = OperandList;
291 const FunctionType *FTy =
292 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
293 FTy = FTy; // silence warning.
295 assert((NumParams == FTy->getNumParams() ||
296 (FTy->isVarArg() && NumParams > FTy->getNumParams())) &&
297 "Calling a function with bad signature!");
298 for (unsigned i = 0; i != NumParams; ++i) {
299 assert((i >= FTy->getNumParams() ||
300 FTy->getParamType(i) == Params[i]->getType()) &&
301 "Calling a function with a bad signature!");
306 void CallInst::init(Value *Func, Value *Actual1, Value *Actual2) {
307 assert(NumOperands == 3 && "NumOperands not set up?");
308 Use *OL = OperandList;
313 const FunctionType *FTy =
314 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
315 FTy = FTy; // silence warning.
317 assert((FTy->getNumParams() == 2 ||
318 (FTy->isVarArg() && FTy->getNumParams() < 2)) &&
319 "Calling a function with bad signature");
320 assert((0 >= FTy->getNumParams() ||
321 FTy->getParamType(0) == Actual1->getType()) &&
322 "Calling a function with a bad signature!");
323 assert((1 >= FTy->getNumParams() ||
324 FTy->getParamType(1) == Actual2->getType()) &&
325 "Calling a function with a bad signature!");
328 void CallInst::init(Value *Func, Value *Actual) {
329 assert(NumOperands == 2 && "NumOperands not set up?");
330 Use *OL = OperandList;
334 const FunctionType *FTy =
335 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
336 FTy = FTy; // silence warning.
338 assert((FTy->getNumParams() == 1 ||
339 (FTy->isVarArg() && FTy->getNumParams() == 0)) &&
340 "Calling a function with bad signature");
341 assert((0 == FTy->getNumParams() ||
342 FTy->getParamType(0) == Actual->getType()) &&
343 "Calling a function with a bad signature!");
346 void CallInst::init(Value *Func) {
347 assert(NumOperands == 1 && "NumOperands not set up?");
348 Use *OL = OperandList;
351 const FunctionType *FTy =
352 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
353 FTy = FTy; // silence warning.
355 assert(FTy->getNumParams() == 0 && "Calling a function with bad signature");
358 CallInst::CallInst(Value *Func, Value* Actual, const std::string &Name,
359 Instruction *InsertBefore)
360 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
361 ->getElementType())->getReturnType(),
363 OperandTraits<CallInst>::op_end(this) - 2,
369 CallInst::CallInst(Value *Func, Value* Actual, const std::string &Name,
370 BasicBlock *InsertAtEnd)
371 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
372 ->getElementType())->getReturnType(),
374 OperandTraits<CallInst>::op_end(this) - 2,
379 CallInst::CallInst(Value *Func, const std::string &Name,
380 Instruction *InsertBefore)
381 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
382 ->getElementType())->getReturnType(),
384 OperandTraits<CallInst>::op_end(this) - 1,
390 CallInst::CallInst(Value *Func, const std::string &Name,
391 BasicBlock *InsertAtEnd)
392 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
393 ->getElementType())->getReturnType(),
395 OperandTraits<CallInst>::op_end(this) - 1,
401 CallInst::CallInst(const CallInst &CI)
402 : Instruction(CI.getType(), Instruction::Call,
403 OperandTraits<CallInst>::op_end(this) - CI.getNumOperands(),
404 CI.getNumOperands()) {
405 setAttributes(CI.getAttributes());
406 SubclassData = CI.SubclassData;
407 Use *OL = OperandList;
408 Use *InOL = CI.OperandList;
409 for (unsigned i = 0, e = CI.getNumOperands(); i != e; ++i)
413 void CallInst::addAttribute(unsigned i, Attributes attr) {
414 AttrListPtr PAL = getAttributes();
415 PAL = PAL.addAttr(i, attr);
419 void CallInst::removeAttribute(unsigned i, Attributes attr) {
420 AttrListPtr PAL = getAttributes();
421 PAL = PAL.removeAttr(i, attr);
425 bool CallInst::paramHasAttr(unsigned i, Attributes attr) const {
426 if (AttributeList.paramHasAttr(i, attr))
428 if (const Function *F = getCalledFunction())
429 return F->paramHasAttr(i, attr);
434 //===----------------------------------------------------------------------===//
435 // InvokeInst Implementation
436 //===----------------------------------------------------------------------===//
438 void InvokeInst::init(Value *Fn, BasicBlock *IfNormal, BasicBlock *IfException,
439 Value* const *Args, unsigned NumArgs) {
440 assert(NumOperands == 3+NumArgs && "NumOperands not set up?");
443 Op<-1>() = IfException;
444 const FunctionType *FTy =
445 cast<FunctionType>(cast<PointerType>(Fn->getType())->getElementType());
446 FTy = FTy; // silence warning.
448 assert(((NumArgs == FTy->getNumParams()) ||
449 (FTy->isVarArg() && NumArgs > FTy->getNumParams())) &&
450 "Calling a function with bad signature");
452 Use *OL = OperandList;
453 for (unsigned i = 0, e = NumArgs; i != e; i++) {
454 assert((i >= FTy->getNumParams() ||
455 FTy->getParamType(i) == Args[i]->getType()) &&
456 "Invoking a function with a bad signature!");
462 InvokeInst::InvokeInst(const InvokeInst &II)
463 : TerminatorInst(II.getType(), Instruction::Invoke,
464 OperandTraits<InvokeInst>::op_end(this)
465 - II.getNumOperands(),
466 II.getNumOperands()) {
467 setAttributes(II.getAttributes());
468 SubclassData = II.SubclassData;
469 Use *OL = OperandList, *InOL = II.OperandList;
470 for (unsigned i = 0, e = II.getNumOperands(); i != e; ++i)
474 BasicBlock *InvokeInst::getSuccessorV(unsigned idx) const {
475 return getSuccessor(idx);
477 unsigned InvokeInst::getNumSuccessorsV() const {
478 return getNumSuccessors();
480 void InvokeInst::setSuccessorV(unsigned idx, BasicBlock *B) {
481 return setSuccessor(idx, B);
484 bool InvokeInst::paramHasAttr(unsigned i, Attributes attr) const {
485 if (AttributeList.paramHasAttr(i, attr))
487 if (const Function *F = getCalledFunction())
488 return F->paramHasAttr(i, attr);
492 void InvokeInst::addAttribute(unsigned i, Attributes attr) {
493 AttrListPtr PAL = getAttributes();
494 PAL = PAL.addAttr(i, attr);
498 void InvokeInst::removeAttribute(unsigned i, Attributes attr) {
499 AttrListPtr PAL = getAttributes();
500 PAL = PAL.removeAttr(i, attr);
505 //===----------------------------------------------------------------------===//
506 // ReturnInst Implementation
507 //===----------------------------------------------------------------------===//
509 ReturnInst::ReturnInst(const ReturnInst &RI)
510 : TerminatorInst(Type::VoidTy, Instruction::Ret,
511 OperandTraits<ReturnInst>::op_end(this) -
513 RI.getNumOperands()) {
514 if (RI.getNumOperands())
515 Op<0>() = RI.Op<0>();
518 ReturnInst::ReturnInst(Value *retVal, Instruction *InsertBefore)
519 : TerminatorInst(Type::VoidTy, Instruction::Ret,
520 OperandTraits<ReturnInst>::op_end(this) - !!retVal, !!retVal,
525 ReturnInst::ReturnInst(Value *retVal, BasicBlock *InsertAtEnd)
526 : TerminatorInst(Type::VoidTy, Instruction::Ret,
527 OperandTraits<ReturnInst>::op_end(this) - !!retVal, !!retVal,
532 ReturnInst::ReturnInst(BasicBlock *InsertAtEnd)
533 : TerminatorInst(Type::VoidTy, Instruction::Ret,
534 OperandTraits<ReturnInst>::op_end(this), 0, InsertAtEnd) {
537 unsigned ReturnInst::getNumSuccessorsV() const {
538 return getNumSuccessors();
541 /// Out-of-line ReturnInst method, put here so the C++ compiler can choose to
542 /// emit the vtable for the class in this translation unit.
543 void ReturnInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
544 assert(0 && "ReturnInst has no successors!");
547 BasicBlock *ReturnInst::getSuccessorV(unsigned idx) const {
548 assert(0 && "ReturnInst has no successors!");
553 ReturnInst::~ReturnInst() {
556 //===----------------------------------------------------------------------===//
557 // UnwindInst Implementation
558 //===----------------------------------------------------------------------===//
560 UnwindInst::UnwindInst(Instruction *InsertBefore)
561 : TerminatorInst(Type::VoidTy, Instruction::Unwind, 0, 0, InsertBefore) {
563 UnwindInst::UnwindInst(BasicBlock *InsertAtEnd)
564 : TerminatorInst(Type::VoidTy, Instruction::Unwind, 0, 0, InsertAtEnd) {
568 unsigned UnwindInst::getNumSuccessorsV() const {
569 return getNumSuccessors();
572 void UnwindInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
573 assert(0 && "UnwindInst has no successors!");
576 BasicBlock *UnwindInst::getSuccessorV(unsigned idx) const {
577 assert(0 && "UnwindInst has no successors!");
582 //===----------------------------------------------------------------------===//
583 // UnreachableInst Implementation
584 //===----------------------------------------------------------------------===//
586 UnreachableInst::UnreachableInst(Instruction *InsertBefore)
587 : TerminatorInst(Type::VoidTy, Instruction::Unreachable, 0, 0, InsertBefore) {
589 UnreachableInst::UnreachableInst(BasicBlock *InsertAtEnd)
590 : TerminatorInst(Type::VoidTy, Instruction::Unreachable, 0, 0, InsertAtEnd) {
593 unsigned UnreachableInst::getNumSuccessorsV() const {
594 return getNumSuccessors();
597 void UnreachableInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
598 assert(0 && "UnwindInst has no successors!");
601 BasicBlock *UnreachableInst::getSuccessorV(unsigned idx) const {
602 assert(0 && "UnwindInst has no successors!");
607 //===----------------------------------------------------------------------===//
608 // BranchInst Implementation
609 //===----------------------------------------------------------------------===//
611 void BranchInst::AssertOK() {
613 assert(getCondition()->getType() == Type::Int1Ty &&
614 "May only branch on boolean predicates!");
617 BranchInst::BranchInst(BasicBlock *IfTrue, Instruction *InsertBefore)
618 : TerminatorInst(Type::VoidTy, Instruction::Br,
619 OperandTraits<BranchInst>::op_end(this) - 1,
621 assert(IfTrue != 0 && "Branch destination may not be null!");
624 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
625 Instruction *InsertBefore)
626 : TerminatorInst(Type::VoidTy, Instruction::Br,
627 OperandTraits<BranchInst>::op_end(this) - 3,
637 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *InsertAtEnd)
638 : TerminatorInst(Type::VoidTy, Instruction::Br,
639 OperandTraits<BranchInst>::op_end(this) - 1,
641 assert(IfTrue != 0 && "Branch destination may not be null!");
645 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
646 BasicBlock *InsertAtEnd)
647 : TerminatorInst(Type::VoidTy, Instruction::Br,
648 OperandTraits<BranchInst>::op_end(this) - 3,
659 BranchInst::BranchInst(const BranchInst &BI) :
660 TerminatorInst(Type::VoidTy, Instruction::Br,
661 OperandTraits<BranchInst>::op_end(this) - BI.getNumOperands(),
662 BI.getNumOperands()) {
663 Op<-1>() = BI.Op<-1>();
664 if (BI.getNumOperands() != 1) {
665 assert(BI.getNumOperands() == 3 && "BR can have 1 or 3 operands!");
666 Op<-3>() = BI.Op<-3>();
667 Op<-2>() = BI.Op<-2>();
672 Use* Use::getPrefix() {
673 PointerIntPair<Use**, 2, PrevPtrTag> &PotentialPrefix(this[-1].Prev);
674 if (PotentialPrefix.getOpaqueValue())
677 return reinterpret_cast<Use*>((char*)&PotentialPrefix + 1);
680 BranchInst::~BranchInst() {
681 if (NumOperands == 1) {
682 if (Use *Prefix = OperandList->getPrefix()) {
685 // mark OperandList to have a special value for scrutiny
686 // by baseclass destructors and operator delete
687 OperandList = Prefix;
690 OperandList = op_begin();
696 BasicBlock *BranchInst::getSuccessorV(unsigned idx) const {
697 return getSuccessor(idx);
699 unsigned BranchInst::getNumSuccessorsV() const {
700 return getNumSuccessors();
702 void BranchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
703 setSuccessor(idx, B);
707 //===----------------------------------------------------------------------===//
708 // AllocationInst Implementation
709 //===----------------------------------------------------------------------===//
711 static Value *getAISize(Value *Amt) {
713 Amt = ConstantInt::get(Type::Int32Ty, 1);
715 assert(!isa<BasicBlock>(Amt) &&
716 "Passed basic block into allocation size parameter! Use other ctor");
717 assert(Amt->getType() == Type::Int32Ty &&
718 "Malloc/Allocation array size is not a 32-bit integer!");
723 AllocationInst::AllocationInst(const Type *Ty, Value *ArraySize, unsigned iTy,
724 unsigned Align, const std::string &Name,
725 Instruction *InsertBefore)
726 : UnaryInstruction(PointerType::getUnqual(Ty), iTy, getAISize(ArraySize),
729 assert(Ty != Type::VoidTy && "Cannot allocate void!");
733 AllocationInst::AllocationInst(const Type *Ty, Value *ArraySize, unsigned iTy,
734 unsigned Align, const std::string &Name,
735 BasicBlock *InsertAtEnd)
736 : UnaryInstruction(PointerType::getUnqual(Ty), iTy, getAISize(ArraySize),
739 assert(Ty != Type::VoidTy && "Cannot allocate void!");
743 // Out of line virtual method, so the vtable, etc has a home.
744 AllocationInst::~AllocationInst() {
747 void AllocationInst::setAlignment(unsigned Align) {
748 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
749 SubclassData = Log2_32(Align) + 1;
750 assert(getAlignment() == Align && "Alignment representation error!");
753 bool AllocationInst::isArrayAllocation() const {
754 if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(0)))
755 return CI->getZExtValue() != 1;
759 const Type *AllocationInst::getAllocatedType() const {
760 return getType()->getElementType();
763 AllocaInst::AllocaInst(const AllocaInst &AI)
764 : AllocationInst(AI.getType()->getElementType(), (Value*)AI.getOperand(0),
765 Instruction::Alloca, AI.getAlignment()) {
768 /// isStaticAlloca - Return true if this alloca is in the entry block of the
769 /// function and is a constant size. If so, the code generator will fold it
770 /// into the prolog/epilog code, so it is basically free.
771 bool AllocaInst::isStaticAlloca() const {
772 // Must be constant size.
773 if (!isa<ConstantInt>(getArraySize())) return false;
775 // Must be in the entry block.
776 const BasicBlock *Parent = getParent();
777 return Parent == &Parent->getParent()->front();
780 MallocInst::MallocInst(const MallocInst &MI)
781 : AllocationInst(MI.getType()->getElementType(), (Value*)MI.getOperand(0),
782 Instruction::Malloc, MI.getAlignment()) {
785 //===----------------------------------------------------------------------===//
786 // FreeInst Implementation
787 //===----------------------------------------------------------------------===//
789 void FreeInst::AssertOK() {
790 assert(isa<PointerType>(getOperand(0)->getType()) &&
791 "Can not free something of nonpointer type!");
794 FreeInst::FreeInst(Value *Ptr, Instruction *InsertBefore)
795 : UnaryInstruction(Type::VoidTy, Free, Ptr, InsertBefore) {
799 FreeInst::FreeInst(Value *Ptr, BasicBlock *InsertAtEnd)
800 : UnaryInstruction(Type::VoidTy, Free, Ptr, InsertAtEnd) {
805 //===----------------------------------------------------------------------===//
806 // LoadInst Implementation
807 //===----------------------------------------------------------------------===//
809 void LoadInst::AssertOK() {
810 assert(isa<PointerType>(getOperand(0)->getType()) &&
811 "Ptr must have pointer type.");
814 LoadInst::LoadInst(Value *Ptr, const std::string &Name, Instruction *InsertBef)
815 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
816 Load, Ptr, InsertBef) {
823 LoadInst::LoadInst(Value *Ptr, const std::string &Name, BasicBlock *InsertAE)
824 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
825 Load, Ptr, InsertAE) {
832 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile,
833 Instruction *InsertBef)
834 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
835 Load, Ptr, InsertBef) {
836 setVolatile(isVolatile);
842 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile,
843 unsigned Align, Instruction *InsertBef)
844 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
845 Load, Ptr, InsertBef) {
846 setVolatile(isVolatile);
852 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile,
853 unsigned Align, BasicBlock *InsertAE)
854 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
855 Load, Ptr, InsertAE) {
856 setVolatile(isVolatile);
862 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile,
863 BasicBlock *InsertAE)
864 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
865 Load, Ptr, InsertAE) {
866 setVolatile(isVolatile);
874 LoadInst::LoadInst(Value *Ptr, const char *Name, Instruction *InsertBef)
875 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
876 Load, Ptr, InsertBef) {
880 if (Name && Name[0]) setName(Name);
883 LoadInst::LoadInst(Value *Ptr, const char *Name, BasicBlock *InsertAE)
884 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
885 Load, Ptr, InsertAE) {
889 if (Name && Name[0]) setName(Name);
892 LoadInst::LoadInst(Value *Ptr, const char *Name, bool isVolatile,
893 Instruction *InsertBef)
894 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
895 Load, Ptr, InsertBef) {
896 setVolatile(isVolatile);
899 if (Name && Name[0]) setName(Name);
902 LoadInst::LoadInst(Value *Ptr, const char *Name, bool isVolatile,
903 BasicBlock *InsertAE)
904 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
905 Load, Ptr, InsertAE) {
906 setVolatile(isVolatile);
909 if (Name && Name[0]) setName(Name);
912 void LoadInst::setAlignment(unsigned Align) {
913 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
914 SubclassData = (SubclassData & 1) | ((Log2_32(Align)+1)<<1);
917 //===----------------------------------------------------------------------===//
918 // StoreInst Implementation
919 //===----------------------------------------------------------------------===//
921 void StoreInst::AssertOK() {
922 assert(getOperand(0) && getOperand(1) && "Both operands must be non-null!");
923 assert(isa<PointerType>(getOperand(1)->getType()) &&
924 "Ptr must have pointer type!");
925 assert(getOperand(0)->getType() ==
926 cast<PointerType>(getOperand(1)->getType())->getElementType()
927 && "Ptr must be a pointer to Val type!");
931 StoreInst::StoreInst(Value *val, Value *addr, Instruction *InsertBefore)
932 : Instruction(Type::VoidTy, Store,
933 OperandTraits<StoreInst>::op_begin(this),
934 OperandTraits<StoreInst>::operands(this),
943 StoreInst::StoreInst(Value *val, Value *addr, BasicBlock *InsertAtEnd)
944 : Instruction(Type::VoidTy, Store,
945 OperandTraits<StoreInst>::op_begin(this),
946 OperandTraits<StoreInst>::operands(this),
955 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
956 Instruction *InsertBefore)
957 : Instruction(Type::VoidTy, Store,
958 OperandTraits<StoreInst>::op_begin(this),
959 OperandTraits<StoreInst>::operands(this),
963 setVolatile(isVolatile);
968 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
969 unsigned Align, Instruction *InsertBefore)
970 : Instruction(Type::VoidTy, Store,
971 OperandTraits<StoreInst>::op_begin(this),
972 OperandTraits<StoreInst>::operands(this),
976 setVolatile(isVolatile);
981 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
982 unsigned Align, BasicBlock *InsertAtEnd)
983 : Instruction(Type::VoidTy, Store,
984 OperandTraits<StoreInst>::op_begin(this),
985 OperandTraits<StoreInst>::operands(this),
989 setVolatile(isVolatile);
994 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
995 BasicBlock *InsertAtEnd)
996 : Instruction(Type::VoidTy, Store,
997 OperandTraits<StoreInst>::op_begin(this),
998 OperandTraits<StoreInst>::operands(this),
1002 setVolatile(isVolatile);
1007 void StoreInst::setAlignment(unsigned Align) {
1008 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
1009 SubclassData = (SubclassData & 1) | ((Log2_32(Align)+1)<<1);
1012 //===----------------------------------------------------------------------===//
1013 // GetElementPtrInst Implementation
1014 //===----------------------------------------------------------------------===//
1016 static unsigned retrieveAddrSpace(const Value *Val) {
1017 return cast<PointerType>(Val->getType())->getAddressSpace();
1020 void GetElementPtrInst::init(Value *Ptr, Value* const *Idx, unsigned NumIdx,
1021 const std::string &Name) {
1022 assert(NumOperands == 1+NumIdx && "NumOperands not initialized?");
1023 Use *OL = OperandList;
1026 for (unsigned i = 0; i != NumIdx; ++i)
1032 void GetElementPtrInst::init(Value *Ptr, Value *Idx, const std::string &Name) {
1033 assert(NumOperands == 2 && "NumOperands not initialized?");
1034 Use *OL = OperandList;
1041 GetElementPtrInst::GetElementPtrInst(const GetElementPtrInst &GEPI)
1042 : Instruction(GEPI.getType(), GetElementPtr,
1043 OperandTraits<GetElementPtrInst>::op_end(this)
1044 - GEPI.getNumOperands(),
1045 GEPI.getNumOperands()) {
1046 Use *OL = OperandList;
1047 Use *GEPIOL = GEPI.OperandList;
1048 for (unsigned i = 0, E = NumOperands; i != E; ++i)
1052 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx,
1053 const std::string &Name, Instruction *InBe)
1054 : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),Idx)),
1055 retrieveAddrSpace(Ptr)),
1057 OperandTraits<GetElementPtrInst>::op_end(this) - 2,
1059 init(Ptr, Idx, Name);
1062 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx,
1063 const std::string &Name, BasicBlock *IAE)
1064 : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),Idx)),
1065 retrieveAddrSpace(Ptr)),
1067 OperandTraits<GetElementPtrInst>::op_end(this) - 2,
1069 init(Ptr, Idx, Name);
1072 /// getIndexedType - Returns the type of the element that would be accessed with
1073 /// a gep instruction with the specified parameters.
1075 /// The Idxs pointer should point to a continuous piece of memory containing the
1076 /// indices, either as Value* or uint64_t.
1078 /// A null type is returned if the indices are invalid for the specified
1081 template <typename IndexTy>
1082 static const Type* getIndexedTypeInternal(const Type *Ptr, IndexTy const *Idxs,
1084 const PointerType *PTy = dyn_cast<PointerType>(Ptr);
1085 if (!PTy) return 0; // Type isn't a pointer type!
1086 const Type *Agg = PTy->getElementType();
1088 // Handle the special case of the empty set index set, which is always valid.
1092 // If there is at least one index, the top level type must be sized, otherwise
1093 // it cannot be 'stepped over'. We explicitly allow abstract types (those
1094 // that contain opaque types) under the assumption that it will be resolved to
1095 // a sane type later.
1096 if (!Agg->isSized() && !Agg->isAbstract())
1099 unsigned CurIdx = 1;
1100 for (; CurIdx != NumIdx; ++CurIdx) {
1101 const CompositeType *CT = dyn_cast<CompositeType>(Agg);
1102 if (!CT || isa<PointerType>(CT)) return 0;
1103 IndexTy Index = Idxs[CurIdx];
1104 if (!CT->indexValid(Index)) return 0;
1105 Agg = CT->getTypeAtIndex(Index);
1107 // If the new type forwards to another type, then it is in the middle
1108 // of being refined to another type (and hence, may have dropped all
1109 // references to what it was using before). So, use the new forwarded
1111 if (const Type *Ty = Agg->getForwardedType())
1114 return CurIdx == NumIdx ? Agg : 0;
1117 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr,
1120 return getIndexedTypeInternal(Ptr, Idxs, NumIdx);
1123 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr,
1124 uint64_t const *Idxs,
1126 return getIndexedTypeInternal(Ptr, Idxs, NumIdx);
1129 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr, Value *Idx) {
1130 const PointerType *PTy = dyn_cast<PointerType>(Ptr);
1131 if (!PTy) return 0; // Type isn't a pointer type!
1133 // Check the pointer index.
1134 if (!PTy->indexValid(Idx)) return 0;
1136 return PTy->getElementType();
1140 /// hasAllZeroIndices - Return true if all of the indices of this GEP are
1141 /// zeros. If so, the result pointer and the first operand have the same
1142 /// value, just potentially different types.
1143 bool GetElementPtrInst::hasAllZeroIndices() const {
1144 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1145 if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(i))) {
1146 if (!CI->isZero()) return false;
1154 /// hasAllConstantIndices - Return true if all of the indices of this GEP are
1155 /// constant integers. If so, the result pointer and the first operand have
1156 /// a constant offset between them.
1157 bool GetElementPtrInst::hasAllConstantIndices() const {
1158 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1159 if (!isa<ConstantInt>(getOperand(i)))
1166 //===----------------------------------------------------------------------===//
1167 // ExtractElementInst Implementation
1168 //===----------------------------------------------------------------------===//
1170 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
1171 const std::string &Name,
1172 Instruction *InsertBef)
1173 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1175 OperandTraits<ExtractElementInst>::op_begin(this),
1177 assert(isValidOperands(Val, Index) &&
1178 "Invalid extractelement instruction operands!");
1184 ExtractElementInst::ExtractElementInst(Value *Val, unsigned IndexV,
1185 const std::string &Name,
1186 Instruction *InsertBef)
1187 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1189 OperandTraits<ExtractElementInst>::op_begin(this),
1191 Constant *Index = ConstantInt::get(Type::Int32Ty, IndexV);
1192 assert(isValidOperands(Val, Index) &&
1193 "Invalid extractelement instruction operands!");
1200 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
1201 const std::string &Name,
1202 BasicBlock *InsertAE)
1203 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1205 OperandTraits<ExtractElementInst>::op_begin(this),
1207 assert(isValidOperands(Val, Index) &&
1208 "Invalid extractelement instruction operands!");
1215 ExtractElementInst::ExtractElementInst(Value *Val, unsigned IndexV,
1216 const std::string &Name,
1217 BasicBlock *InsertAE)
1218 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1220 OperandTraits<ExtractElementInst>::op_begin(this),
1222 Constant *Index = ConstantInt::get(Type::Int32Ty, IndexV);
1223 assert(isValidOperands(Val, Index) &&
1224 "Invalid extractelement instruction operands!");
1232 bool ExtractElementInst::isValidOperands(const Value *Val, const Value *Index) {
1233 if (!isa<VectorType>(Val->getType()) || Index->getType() != Type::Int32Ty)
1239 //===----------------------------------------------------------------------===//
1240 // InsertElementInst Implementation
1241 //===----------------------------------------------------------------------===//
1243 InsertElementInst::InsertElementInst(const InsertElementInst &IE)
1244 : Instruction(IE.getType(), InsertElement,
1245 OperandTraits<InsertElementInst>::op_begin(this), 3) {
1246 Op<0>() = IE.Op<0>();
1247 Op<1>() = IE.Op<1>();
1248 Op<2>() = IE.Op<2>();
1250 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
1251 const std::string &Name,
1252 Instruction *InsertBef)
1253 : Instruction(Vec->getType(), InsertElement,
1254 OperandTraits<InsertElementInst>::op_begin(this),
1256 assert(isValidOperands(Vec, Elt, Index) &&
1257 "Invalid insertelement instruction operands!");
1264 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, unsigned IndexV,
1265 const std::string &Name,
1266 Instruction *InsertBef)
1267 : Instruction(Vec->getType(), InsertElement,
1268 OperandTraits<InsertElementInst>::op_begin(this),
1270 Constant *Index = ConstantInt::get(Type::Int32Ty, IndexV);
1271 assert(isValidOperands(Vec, Elt, Index) &&
1272 "Invalid insertelement instruction operands!");
1280 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
1281 const std::string &Name,
1282 BasicBlock *InsertAE)
1283 : Instruction(Vec->getType(), InsertElement,
1284 OperandTraits<InsertElementInst>::op_begin(this),
1286 assert(isValidOperands(Vec, Elt, Index) &&
1287 "Invalid insertelement instruction operands!");
1295 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, unsigned IndexV,
1296 const std::string &Name,
1297 BasicBlock *InsertAE)
1298 : Instruction(Vec->getType(), InsertElement,
1299 OperandTraits<InsertElementInst>::op_begin(this),
1301 Constant *Index = ConstantInt::get(Type::Int32Ty, IndexV);
1302 assert(isValidOperands(Vec, Elt, Index) &&
1303 "Invalid insertelement instruction operands!");
1311 bool InsertElementInst::isValidOperands(const Value *Vec, const Value *Elt,
1312 const Value *Index) {
1313 if (!isa<VectorType>(Vec->getType()))
1314 return false; // First operand of insertelement must be vector type.
1316 if (Elt->getType() != cast<VectorType>(Vec->getType())->getElementType())
1317 return false;// Second operand of insertelement must be vector element type.
1319 if (Index->getType() != Type::Int32Ty)
1320 return false; // Third operand of insertelement must be uint.
1325 //===----------------------------------------------------------------------===//
1326 // ShuffleVectorInst Implementation
1327 //===----------------------------------------------------------------------===//
1329 ShuffleVectorInst::ShuffleVectorInst(const ShuffleVectorInst &SV)
1330 : Instruction(SV.getType(), ShuffleVector,
1331 OperandTraits<ShuffleVectorInst>::op_begin(this),
1332 OperandTraits<ShuffleVectorInst>::operands(this)) {
1333 Op<0>() = SV.Op<0>();
1334 Op<1>() = SV.Op<1>();
1335 Op<2>() = SV.Op<2>();
1338 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1339 const std::string &Name,
1340 Instruction *InsertBefore)
1341 : Instruction(VectorType::get(cast<VectorType>(V1->getType())->getElementType(),
1342 cast<VectorType>(Mask->getType())->getNumElements()),
1344 OperandTraits<ShuffleVectorInst>::op_begin(this),
1345 OperandTraits<ShuffleVectorInst>::operands(this),
1347 assert(isValidOperands(V1, V2, Mask) &&
1348 "Invalid shuffle vector instruction operands!");
1355 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1356 const std::string &Name,
1357 BasicBlock *InsertAtEnd)
1358 : Instruction(V1->getType(), ShuffleVector,
1359 OperandTraits<ShuffleVectorInst>::op_begin(this),
1360 OperandTraits<ShuffleVectorInst>::operands(this),
1362 assert(isValidOperands(V1, V2, Mask) &&
1363 "Invalid shuffle vector instruction operands!");
1371 bool ShuffleVectorInst::isValidOperands(const Value *V1, const Value *V2,
1372 const Value *Mask) {
1373 if (!isa<VectorType>(V1->getType()) || V1->getType() != V2->getType())
1376 const VectorType *MaskTy = dyn_cast<VectorType>(Mask->getType());
1377 if (!isa<Constant>(Mask) || MaskTy == 0 ||
1378 MaskTy->getElementType() != Type::Int32Ty)
1383 /// getMaskValue - Return the index from the shuffle mask for the specified
1384 /// output result. This is either -1 if the element is undef or a number less
1385 /// than 2*numelements.
1386 int ShuffleVectorInst::getMaskValue(unsigned i) const {
1387 const Constant *Mask = cast<Constant>(getOperand(2));
1388 if (isa<UndefValue>(Mask)) return -1;
1389 if (isa<ConstantAggregateZero>(Mask)) return 0;
1390 const ConstantVector *MaskCV = cast<ConstantVector>(Mask);
1391 assert(i < MaskCV->getNumOperands() && "Index out of range");
1393 if (isa<UndefValue>(MaskCV->getOperand(i)))
1395 return cast<ConstantInt>(MaskCV->getOperand(i))->getZExtValue();
1398 //===----------------------------------------------------------------------===//
1399 // InsertValueInst Class
1400 //===----------------------------------------------------------------------===//
1402 void InsertValueInst::init(Value *Agg, Value *Val, const unsigned *Idx,
1403 unsigned NumIdx, const std::string &Name) {
1404 assert(NumOperands == 2 && "NumOperands not initialized?");
1408 Indices.insert(Indices.end(), Idx, Idx + NumIdx);
1412 void InsertValueInst::init(Value *Agg, Value *Val, unsigned Idx,
1413 const std::string &Name) {
1414 assert(NumOperands == 2 && "NumOperands not initialized?");
1418 Indices.push_back(Idx);
1422 InsertValueInst::InsertValueInst(const InsertValueInst &IVI)
1423 : Instruction(IVI.getType(), InsertValue,
1424 OperandTraits<InsertValueInst>::op_begin(this), 2),
1425 Indices(IVI.Indices) {
1426 Op<0>() = IVI.getOperand(0);
1427 Op<1>() = IVI.getOperand(1);
1430 InsertValueInst::InsertValueInst(Value *Agg,
1433 const std::string &Name,
1434 Instruction *InsertBefore)
1435 : Instruction(Agg->getType(), InsertValue,
1436 OperandTraits<InsertValueInst>::op_begin(this),
1438 init(Agg, Val, Idx, Name);
1441 InsertValueInst::InsertValueInst(Value *Agg,
1444 const std::string &Name,
1445 BasicBlock *InsertAtEnd)
1446 : Instruction(Agg->getType(), InsertValue,
1447 OperandTraits<InsertValueInst>::op_begin(this),
1449 init(Agg, Val, Idx, Name);
1452 //===----------------------------------------------------------------------===//
1453 // ExtractValueInst Class
1454 //===----------------------------------------------------------------------===//
1456 void ExtractValueInst::init(const unsigned *Idx, unsigned NumIdx,
1457 const std::string &Name) {
1458 assert(NumOperands == 1 && "NumOperands not initialized?");
1460 Indices.insert(Indices.end(), Idx, Idx + NumIdx);
1464 void ExtractValueInst::init(unsigned Idx, const std::string &Name) {
1465 assert(NumOperands == 1 && "NumOperands not initialized?");
1467 Indices.push_back(Idx);
1471 ExtractValueInst::ExtractValueInst(const ExtractValueInst &EVI)
1472 : UnaryInstruction(EVI.getType(), ExtractValue, EVI.getOperand(0)),
1473 Indices(EVI.Indices) {
1476 // getIndexedType - Returns the type of the element that would be extracted
1477 // with an extractvalue instruction with the specified parameters.
1479 // A null type is returned if the indices are invalid for the specified
1482 const Type* ExtractValueInst::getIndexedType(const Type *Agg,
1483 const unsigned *Idxs,
1485 unsigned CurIdx = 0;
1486 for (; CurIdx != NumIdx; ++CurIdx) {
1487 const CompositeType *CT = dyn_cast<CompositeType>(Agg);
1488 if (!CT || isa<PointerType>(CT) || isa<VectorType>(CT)) return 0;
1489 unsigned Index = Idxs[CurIdx];
1490 if (!CT->indexValid(Index)) return 0;
1491 Agg = CT->getTypeAtIndex(Index);
1493 // If the new type forwards to another type, then it is in the middle
1494 // of being refined to another type (and hence, may have dropped all
1495 // references to what it was using before). So, use the new forwarded
1497 if (const Type *Ty = Agg->getForwardedType())
1500 return CurIdx == NumIdx ? Agg : 0;
1503 const Type* ExtractValueInst::getIndexedType(const Type *Agg,
1505 return getIndexedType(Agg, &Idx, 1);
1508 //===----------------------------------------------------------------------===//
1509 // BinaryOperator Class
1510 //===----------------------------------------------------------------------===//
1512 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
1513 const Type *Ty, const std::string &Name,
1514 Instruction *InsertBefore)
1515 : Instruction(Ty, iType,
1516 OperandTraits<BinaryOperator>::op_begin(this),
1517 OperandTraits<BinaryOperator>::operands(this),
1525 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
1526 const Type *Ty, const std::string &Name,
1527 BasicBlock *InsertAtEnd)
1528 : Instruction(Ty, iType,
1529 OperandTraits<BinaryOperator>::op_begin(this),
1530 OperandTraits<BinaryOperator>::operands(this),
1539 void BinaryOperator::init(BinaryOps iType) {
1540 Value *LHS = getOperand(0), *RHS = getOperand(1);
1541 LHS = LHS; RHS = RHS; // Silence warnings.
1542 assert(LHS->getType() == RHS->getType() &&
1543 "Binary operator operand types must match!");
1548 assert(getType() == LHS->getType() &&
1549 "Arithmetic operation should return same type as operands!");
1550 assert((getType()->isInteger() || getType()->isFloatingPoint() ||
1551 isa<VectorType>(getType())) &&
1552 "Tried to create an arithmetic operation on a non-arithmetic type!");
1556 assert(getType() == LHS->getType() &&
1557 "Arithmetic operation should return same type as operands!");
1558 assert((getType()->isInteger() || (isa<VectorType>(getType()) &&
1559 cast<VectorType>(getType())->getElementType()->isInteger())) &&
1560 "Incorrect operand type (not integer) for S/UDIV");
1563 assert(getType() == LHS->getType() &&
1564 "Arithmetic operation should return same type as operands!");
1565 assert((getType()->isFloatingPoint() || (isa<VectorType>(getType()) &&
1566 cast<VectorType>(getType())->getElementType()->isFloatingPoint()))
1567 && "Incorrect operand type (not floating point) for FDIV");
1571 assert(getType() == LHS->getType() &&
1572 "Arithmetic operation should return same type as operands!");
1573 assert((getType()->isInteger() || (isa<VectorType>(getType()) &&
1574 cast<VectorType>(getType())->getElementType()->isInteger())) &&
1575 "Incorrect operand type (not integer) for S/UREM");
1578 assert(getType() == LHS->getType() &&
1579 "Arithmetic operation should return same type as operands!");
1580 assert((getType()->isFloatingPoint() || (isa<VectorType>(getType()) &&
1581 cast<VectorType>(getType())->getElementType()->isFloatingPoint()))
1582 && "Incorrect operand type (not floating point) for FREM");
1587 assert(getType() == LHS->getType() &&
1588 "Shift operation should return same type as operands!");
1589 assert((getType()->isInteger() ||
1590 (isa<VectorType>(getType()) &&
1591 cast<VectorType>(getType())->getElementType()->isInteger())) &&
1592 "Tried to create a shift operation on a non-integral type!");
1596 assert(getType() == LHS->getType() &&
1597 "Logical operation should return same type as operands!");
1598 assert((getType()->isInteger() ||
1599 (isa<VectorType>(getType()) &&
1600 cast<VectorType>(getType())->getElementType()->isInteger())) &&
1601 "Tried to create a logical operation on a non-integral type!");
1609 BinaryOperator *BinaryOperator::Create(BinaryOps Op, Value *S1, Value *S2,
1610 const std::string &Name,
1611 Instruction *InsertBefore) {
1612 assert(S1->getType() == S2->getType() &&
1613 "Cannot create binary operator with two operands of differing type!");
1614 return new BinaryOperator(Op, S1, S2, S1->getType(), Name, InsertBefore);
1617 BinaryOperator *BinaryOperator::Create(BinaryOps Op, Value *S1, Value *S2,
1618 const std::string &Name,
1619 BasicBlock *InsertAtEnd) {
1620 BinaryOperator *Res = Create(Op, S1, S2, Name);
1621 InsertAtEnd->getInstList().push_back(Res);
1625 BinaryOperator *BinaryOperator::CreateNeg(Value *Op, const std::string &Name,
1626 Instruction *InsertBefore) {
1627 Value *zero = ConstantExpr::getZeroValueForNegationExpr(Op->getType());
1628 return new BinaryOperator(Instruction::Sub,
1630 Op->getType(), Name, InsertBefore);
1633 BinaryOperator *BinaryOperator::CreateNeg(Value *Op, const std::string &Name,
1634 BasicBlock *InsertAtEnd) {
1635 Value *zero = ConstantExpr::getZeroValueForNegationExpr(Op->getType());
1636 return new BinaryOperator(Instruction::Sub,
1638 Op->getType(), Name, InsertAtEnd);
1641 BinaryOperator *BinaryOperator::CreateNot(Value *Op, const std::string &Name,
1642 Instruction *InsertBefore) {
1644 if (const VectorType *PTy = dyn_cast<VectorType>(Op->getType())) {
1645 C = ConstantInt::getAllOnesValue(PTy->getElementType());
1646 C = ConstantVector::get(std::vector<Constant*>(PTy->getNumElements(), C));
1648 C = ConstantInt::getAllOnesValue(Op->getType());
1651 return new BinaryOperator(Instruction::Xor, Op, C,
1652 Op->getType(), Name, InsertBefore);
1655 BinaryOperator *BinaryOperator::CreateNot(Value *Op, const std::string &Name,
1656 BasicBlock *InsertAtEnd) {
1658 if (const VectorType *PTy = dyn_cast<VectorType>(Op->getType())) {
1659 // Create a vector of all ones values.
1660 Constant *Elt = ConstantInt::getAllOnesValue(PTy->getElementType());
1662 ConstantVector::get(std::vector<Constant*>(PTy->getNumElements(), Elt));
1664 AllOnes = ConstantInt::getAllOnesValue(Op->getType());
1667 return new BinaryOperator(Instruction::Xor, Op, AllOnes,
1668 Op->getType(), Name, InsertAtEnd);
1672 // isConstantAllOnes - Helper function for several functions below
1673 static inline bool isConstantAllOnes(const Value *V) {
1674 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V))
1675 return CI->isAllOnesValue();
1676 if (const ConstantVector *CV = dyn_cast<ConstantVector>(V))
1677 return CV->isAllOnesValue();
1681 bool BinaryOperator::isNeg(const Value *V) {
1682 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1683 if (Bop->getOpcode() == Instruction::Sub)
1684 return Bop->getOperand(0) ==
1685 ConstantExpr::getZeroValueForNegationExpr(Bop->getType());
1689 bool BinaryOperator::isNot(const Value *V) {
1690 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1691 return (Bop->getOpcode() == Instruction::Xor &&
1692 (isConstantAllOnes(Bop->getOperand(1)) ||
1693 isConstantAllOnes(Bop->getOperand(0))));
1697 Value *BinaryOperator::getNegArgument(Value *BinOp) {
1698 assert(isNeg(BinOp) && "getNegArgument from non-'neg' instruction!");
1699 return cast<BinaryOperator>(BinOp)->getOperand(1);
1702 const Value *BinaryOperator::getNegArgument(const Value *BinOp) {
1703 return getNegArgument(const_cast<Value*>(BinOp));
1706 Value *BinaryOperator::getNotArgument(Value *BinOp) {
1707 assert(isNot(BinOp) && "getNotArgument on non-'not' instruction!");
1708 BinaryOperator *BO = cast<BinaryOperator>(BinOp);
1709 Value *Op0 = BO->getOperand(0);
1710 Value *Op1 = BO->getOperand(1);
1711 if (isConstantAllOnes(Op0)) return Op1;
1713 assert(isConstantAllOnes(Op1));
1717 const Value *BinaryOperator::getNotArgument(const Value *BinOp) {
1718 return getNotArgument(const_cast<Value*>(BinOp));
1722 // swapOperands - Exchange the two operands to this instruction. This
1723 // instruction is safe to use on any binary instruction and does not
1724 // modify the semantics of the instruction. If the instruction is
1725 // order dependent (SetLT f.e.) the opcode is changed.
1727 bool BinaryOperator::swapOperands() {
1728 if (!isCommutative())
1729 return true; // Can't commute operands
1730 Op<0>().swap(Op<1>());
1734 //===----------------------------------------------------------------------===//
1736 //===----------------------------------------------------------------------===//
1738 // Just determine if this cast only deals with integral->integral conversion.
1739 bool CastInst::isIntegerCast() const {
1740 switch (getOpcode()) {
1741 default: return false;
1742 case Instruction::ZExt:
1743 case Instruction::SExt:
1744 case Instruction::Trunc:
1746 case Instruction::BitCast:
1747 return getOperand(0)->getType()->isInteger() && getType()->isInteger();
1751 bool CastInst::isLosslessCast() const {
1752 // Only BitCast can be lossless, exit fast if we're not BitCast
1753 if (getOpcode() != Instruction::BitCast)
1756 // Identity cast is always lossless
1757 const Type* SrcTy = getOperand(0)->getType();
1758 const Type* DstTy = getType();
1762 // Pointer to pointer is always lossless.
1763 if (isa<PointerType>(SrcTy))
1764 return isa<PointerType>(DstTy);
1765 return false; // Other types have no identity values
1768 /// This function determines if the CastInst does not require any bits to be
1769 /// changed in order to effect the cast. Essentially, it identifies cases where
1770 /// no code gen is necessary for the cast, hence the name no-op cast. For
1771 /// example, the following are all no-op casts:
1772 /// # bitcast i32* %x to i8*
1773 /// # bitcast <2 x i32> %x to <4 x i16>
1774 /// # ptrtoint i32* %x to i32 ; on 32-bit plaforms only
1775 /// @brief Determine if a cast is a no-op.
1776 bool CastInst::isNoopCast(const Type *IntPtrTy) const {
1777 switch (getOpcode()) {
1779 assert(!"Invalid CastOp");
1780 case Instruction::Trunc:
1781 case Instruction::ZExt:
1782 case Instruction::SExt:
1783 case Instruction::FPTrunc:
1784 case Instruction::FPExt:
1785 case Instruction::UIToFP:
1786 case Instruction::SIToFP:
1787 case Instruction::FPToUI:
1788 case Instruction::FPToSI:
1789 return false; // These always modify bits
1790 case Instruction::BitCast:
1791 return true; // BitCast never modifies bits.
1792 case Instruction::PtrToInt:
1793 return IntPtrTy->getPrimitiveSizeInBits() ==
1794 getType()->getPrimitiveSizeInBits();
1795 case Instruction::IntToPtr:
1796 return IntPtrTy->getPrimitiveSizeInBits() ==
1797 getOperand(0)->getType()->getPrimitiveSizeInBits();
1801 /// This function determines if a pair of casts can be eliminated and what
1802 /// opcode should be used in the elimination. This assumes that there are two
1803 /// instructions like this:
1804 /// * %F = firstOpcode SrcTy %x to MidTy
1805 /// * %S = secondOpcode MidTy %F to DstTy
1806 /// The function returns a resultOpcode so these two casts can be replaced with:
1807 /// * %Replacement = resultOpcode %SrcTy %x to DstTy
1808 /// If no such cast is permited, the function returns 0.
1809 unsigned CastInst::isEliminableCastPair(
1810 Instruction::CastOps firstOp, Instruction::CastOps secondOp,
1811 const Type *SrcTy, const Type *MidTy, const Type *DstTy, const Type *IntPtrTy)
1813 // Define the 144 possibilities for these two cast instructions. The values
1814 // in this matrix determine what to do in a given situation and select the
1815 // case in the switch below. The rows correspond to firstOp, the columns
1816 // correspond to secondOp. In looking at the table below, keep in mind
1817 // the following cast properties:
1819 // Size Compare Source Destination
1820 // Operator Src ? Size Type Sign Type Sign
1821 // -------- ------------ ------------------- ---------------------
1822 // TRUNC > Integer Any Integral Any
1823 // ZEXT < Integral Unsigned Integer Any
1824 // SEXT < Integral Signed Integer Any
1825 // FPTOUI n/a FloatPt n/a Integral Unsigned
1826 // FPTOSI n/a FloatPt n/a Integral Signed
1827 // UITOFP n/a Integral Unsigned FloatPt n/a
1828 // SITOFP n/a Integral Signed FloatPt n/a
1829 // FPTRUNC > FloatPt n/a FloatPt n/a
1830 // FPEXT < FloatPt n/a FloatPt n/a
1831 // PTRTOINT n/a Pointer n/a Integral Unsigned
1832 // INTTOPTR n/a Integral Unsigned Pointer n/a
1833 // BITCONVERT = FirstClass n/a FirstClass n/a
1835 // NOTE: some transforms are safe, but we consider them to be non-profitable.
1836 // For example, we could merge "fptoui double to uint" + "zext uint to ulong",
1837 // into "fptoui double to ulong", but this loses information about the range
1838 // of the produced value (we no longer know the top-part is all zeros).
1839 // Further this conversion is often much more expensive for typical hardware,
1840 // and causes issues when building libgcc. We disallow fptosi+sext for the
1842 const unsigned numCastOps =
1843 Instruction::CastOpsEnd - Instruction::CastOpsBegin;
1844 static const uint8_t CastResults[numCastOps][numCastOps] = {
1845 // T F F U S F F P I B -+
1846 // R Z S P P I I T P 2 N T |
1847 // U E E 2 2 2 2 R E I T C +- secondOp
1848 // N X X U S F F N X N 2 V |
1849 // C T T I I P P C T T P T -+
1850 { 1, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // Trunc -+
1851 { 8, 1, 9,99,99, 2, 0,99,99,99, 2, 3 }, // ZExt |
1852 { 8, 0, 1,99,99, 0, 2,99,99,99, 0, 3 }, // SExt |
1853 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // FPToUI |
1854 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // FPToSI |
1855 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4 }, // UIToFP +- firstOp
1856 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4 }, // SIToFP |
1857 { 99,99,99, 0, 0,99,99, 1, 0,99,99, 4 }, // FPTrunc |
1858 { 99,99,99, 2, 2,99,99,10, 2,99,99, 4 }, // FPExt |
1859 { 1, 0, 0,99,99, 0, 0,99,99,99, 7, 3 }, // PtrToInt |
1860 { 99,99,99,99,99,99,99,99,99,13,99,12 }, // IntToPtr |
1861 { 5, 5, 5, 6, 6, 5, 5, 6, 6,11, 5, 1 }, // BitCast -+
1864 int ElimCase = CastResults[firstOp-Instruction::CastOpsBegin]
1865 [secondOp-Instruction::CastOpsBegin];
1868 // categorically disallowed
1871 // allowed, use first cast's opcode
1874 // allowed, use second cast's opcode
1877 // no-op cast in second op implies firstOp as long as the DestTy
1879 if (DstTy->isInteger())
1883 // no-op cast in second op implies firstOp as long as the DestTy
1884 // is floating point
1885 if (DstTy->isFloatingPoint())
1889 // no-op cast in first op implies secondOp as long as the SrcTy
1891 if (SrcTy->isInteger())
1895 // no-op cast in first op implies secondOp as long as the SrcTy
1896 // is a floating point
1897 if (SrcTy->isFloatingPoint())
1901 // ptrtoint, inttoptr -> bitcast (ptr -> ptr) if int size is >= ptr size
1902 unsigned PtrSize = IntPtrTy->getPrimitiveSizeInBits();
1903 unsigned MidSize = MidTy->getPrimitiveSizeInBits();
1904 if (MidSize >= PtrSize)
1905 return Instruction::BitCast;
1909 // ext, trunc -> bitcast, if the SrcTy and DstTy are same size
1910 // ext, trunc -> ext, if sizeof(SrcTy) < sizeof(DstTy)
1911 // ext, trunc -> trunc, if sizeof(SrcTy) > sizeof(DstTy)
1912 unsigned SrcSize = SrcTy->getPrimitiveSizeInBits();
1913 unsigned DstSize = DstTy->getPrimitiveSizeInBits();
1914 if (SrcSize == DstSize)
1915 return Instruction::BitCast;
1916 else if (SrcSize < DstSize)
1920 case 9: // zext, sext -> zext, because sext can't sign extend after zext
1921 return Instruction::ZExt;
1923 // fpext followed by ftrunc is allowed if the bit size returned to is
1924 // the same as the original, in which case its just a bitcast
1926 return Instruction::BitCast;
1927 return 0; // If the types are not the same we can't eliminate it.
1929 // bitcast followed by ptrtoint is allowed as long as the bitcast
1930 // is a pointer to pointer cast.
1931 if (isa<PointerType>(SrcTy) && isa<PointerType>(MidTy))
1935 // inttoptr, bitcast -> intptr if bitcast is a ptr to ptr cast
1936 if (isa<PointerType>(MidTy) && isa<PointerType>(DstTy))
1940 // inttoptr, ptrtoint -> bitcast if SrcSize<=PtrSize and SrcSize==DstSize
1941 unsigned PtrSize = IntPtrTy->getPrimitiveSizeInBits();
1942 unsigned SrcSize = SrcTy->getPrimitiveSizeInBits();
1943 unsigned DstSize = DstTy->getPrimitiveSizeInBits();
1944 if (SrcSize <= PtrSize && SrcSize == DstSize)
1945 return Instruction::BitCast;
1949 // cast combination can't happen (error in input). This is for all cases
1950 // where the MidTy is not the same for the two cast instructions.
1951 assert(!"Invalid Cast Combination");
1954 assert(!"Error in CastResults table!!!");
1960 CastInst *CastInst::Create(Instruction::CastOps op, Value *S, const Type *Ty,
1961 const std::string &Name, Instruction *InsertBefore) {
1962 // Construct and return the appropriate CastInst subclass
1964 case Trunc: return new TruncInst (S, Ty, Name, InsertBefore);
1965 case ZExt: return new ZExtInst (S, Ty, Name, InsertBefore);
1966 case SExt: return new SExtInst (S, Ty, Name, InsertBefore);
1967 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertBefore);
1968 case FPExt: return new FPExtInst (S, Ty, Name, InsertBefore);
1969 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertBefore);
1970 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertBefore);
1971 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertBefore);
1972 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertBefore);
1973 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertBefore);
1974 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertBefore);
1975 case BitCast: return new BitCastInst (S, Ty, Name, InsertBefore);
1977 assert(!"Invalid opcode provided");
1982 CastInst *CastInst::Create(Instruction::CastOps op, Value *S, const Type *Ty,
1983 const std::string &Name, BasicBlock *InsertAtEnd) {
1984 // Construct and return the appropriate CastInst subclass
1986 case Trunc: return new TruncInst (S, Ty, Name, InsertAtEnd);
1987 case ZExt: return new ZExtInst (S, Ty, Name, InsertAtEnd);
1988 case SExt: return new SExtInst (S, Ty, Name, InsertAtEnd);
1989 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertAtEnd);
1990 case FPExt: return new FPExtInst (S, Ty, Name, InsertAtEnd);
1991 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertAtEnd);
1992 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertAtEnd);
1993 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertAtEnd);
1994 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertAtEnd);
1995 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertAtEnd);
1996 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertAtEnd);
1997 case BitCast: return new BitCastInst (S, Ty, Name, InsertAtEnd);
1999 assert(!"Invalid opcode provided");
2004 CastInst *CastInst::CreateZExtOrBitCast(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::ZExt, S, Ty, Name, InsertBefore);
2012 CastInst *CastInst::CreateZExtOrBitCast(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::ZExt, S, Ty, Name, InsertAtEnd);
2020 CastInst *CastInst::CreateSExtOrBitCast(Value *S, const Type *Ty,
2021 const std::string &Name,
2022 Instruction *InsertBefore) {
2023 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
2024 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2025 return Create(Instruction::SExt, S, Ty, Name, InsertBefore);
2028 CastInst *CastInst::CreateSExtOrBitCast(Value *S, const Type *Ty,
2029 const std::string &Name,
2030 BasicBlock *InsertAtEnd) {
2031 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
2032 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2033 return Create(Instruction::SExt, S, Ty, Name, InsertAtEnd);
2036 CastInst *CastInst::CreateTruncOrBitCast(Value *S, const Type *Ty,
2037 const std::string &Name,
2038 Instruction *InsertBefore) {
2039 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
2040 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2041 return Create(Instruction::Trunc, S, Ty, Name, InsertBefore);
2044 CastInst *CastInst::CreateTruncOrBitCast(Value *S, const Type *Ty,
2045 const std::string &Name,
2046 BasicBlock *InsertAtEnd) {
2047 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
2048 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2049 return Create(Instruction::Trunc, S, Ty, Name, InsertAtEnd);
2052 CastInst *CastInst::CreatePointerCast(Value *S, const Type *Ty,
2053 const std::string &Name,
2054 BasicBlock *InsertAtEnd) {
2055 assert(isa<PointerType>(S->getType()) && "Invalid cast");
2056 assert((Ty->isInteger() || isa<PointerType>(Ty)) &&
2059 if (Ty->isInteger())
2060 return Create(Instruction::PtrToInt, S, Ty, Name, InsertAtEnd);
2061 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2064 /// @brief Create a BitCast or a PtrToInt cast instruction
2065 CastInst *CastInst::CreatePointerCast(Value *S, const Type *Ty,
2066 const std::string &Name,
2067 Instruction *InsertBefore) {
2068 assert(isa<PointerType>(S->getType()) && "Invalid cast");
2069 assert((Ty->isInteger() || isa<PointerType>(Ty)) &&
2072 if (Ty->isInteger())
2073 return Create(Instruction::PtrToInt, S, Ty, Name, InsertBefore);
2074 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2077 CastInst *CastInst::CreateIntegerCast(Value *C, const Type *Ty,
2078 bool isSigned, const std::string &Name,
2079 Instruction *InsertBefore) {
2080 assert(C->getType()->isInteger() && Ty->isInteger() && "Invalid cast");
2081 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
2082 unsigned DstBits = Ty->getPrimitiveSizeInBits();
2083 Instruction::CastOps opcode =
2084 (SrcBits == DstBits ? Instruction::BitCast :
2085 (SrcBits > DstBits ? Instruction::Trunc :
2086 (isSigned ? Instruction::SExt : Instruction::ZExt)));
2087 return Create(opcode, C, Ty, Name, InsertBefore);
2090 CastInst *CastInst::CreateIntegerCast(Value *C, const Type *Ty,
2091 bool isSigned, const std::string &Name,
2092 BasicBlock *InsertAtEnd) {
2093 assert(C->getType()->isInteger() && Ty->isInteger() && "Invalid cast");
2094 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
2095 unsigned DstBits = Ty->getPrimitiveSizeInBits();
2096 Instruction::CastOps opcode =
2097 (SrcBits == DstBits ? Instruction::BitCast :
2098 (SrcBits > DstBits ? Instruction::Trunc :
2099 (isSigned ? Instruction::SExt : Instruction::ZExt)));
2100 return Create(opcode, C, Ty, Name, InsertAtEnd);
2103 CastInst *CastInst::CreateFPCast(Value *C, const Type *Ty,
2104 const std::string &Name,
2105 Instruction *InsertBefore) {
2106 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
2108 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
2109 unsigned DstBits = Ty->getPrimitiveSizeInBits();
2110 Instruction::CastOps opcode =
2111 (SrcBits == DstBits ? Instruction::BitCast :
2112 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
2113 return Create(opcode, C, Ty, Name, InsertBefore);
2116 CastInst *CastInst::CreateFPCast(Value *C, const Type *Ty,
2117 const std::string &Name,
2118 BasicBlock *InsertAtEnd) {
2119 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
2121 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
2122 unsigned DstBits = Ty->getPrimitiveSizeInBits();
2123 Instruction::CastOps opcode =
2124 (SrcBits == DstBits ? Instruction::BitCast :
2125 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
2126 return Create(opcode, C, Ty, Name, InsertAtEnd);
2129 // Check whether it is valid to call getCastOpcode for these types.
2130 // This routine must be kept in sync with getCastOpcode.
2131 bool CastInst::isCastable(const Type *SrcTy, const Type *DestTy) {
2132 if (!SrcTy->isFirstClassType() || !DestTy->isFirstClassType())
2135 if (SrcTy == DestTy)
2138 // Get the bit sizes, we'll need these
2139 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); // 0 for ptr/vector
2140 unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr/vector
2142 // Run through the possibilities ...
2143 if (DestTy->isInteger()) { // Casting to integral
2144 if (SrcTy->isInteger()) { // Casting from integral
2146 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt
2148 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
2149 // Casting from vector
2150 return DestBits == PTy->getBitWidth();
2151 } else { // Casting from something else
2152 return isa<PointerType>(SrcTy);
2154 } else if (DestTy->isFloatingPoint()) { // Casting to floating pt
2155 if (SrcTy->isInteger()) { // Casting from integral
2157 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt
2159 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
2160 // Casting from vector
2161 return DestBits == PTy->getBitWidth();
2162 } else { // Casting from something else
2165 } else if (const VectorType *DestPTy = dyn_cast<VectorType>(DestTy)) {
2166 // Casting to vector
2167 if (const VectorType *SrcPTy = dyn_cast<VectorType>(SrcTy)) {
2168 // Casting from vector
2169 return DestPTy->getBitWidth() == SrcPTy->getBitWidth();
2170 } else { // Casting from something else
2171 return DestPTy->getBitWidth() == SrcBits;
2173 } else if (isa<PointerType>(DestTy)) { // Casting to pointer
2174 if (isa<PointerType>(SrcTy)) { // Casting from pointer
2176 } else if (SrcTy->isInteger()) { // Casting from integral
2178 } else { // Casting from something else
2181 } else { // Casting to something else
2186 // Provide a way to get a "cast" where the cast opcode is inferred from the
2187 // types and size of the operand. This, basically, is a parallel of the
2188 // logic in the castIsValid function below. This axiom should hold:
2189 // castIsValid( getCastOpcode(Val, Ty), Val, Ty)
2190 // should not assert in castIsValid. In other words, this produces a "correct"
2191 // casting opcode for the arguments passed to it.
2192 // This routine must be kept in sync with isCastable.
2193 Instruction::CastOps
2194 CastInst::getCastOpcode(
2195 const Value *Src, bool SrcIsSigned, const Type *DestTy, bool DestIsSigned) {
2196 // Get the bit sizes, we'll need these
2197 const Type *SrcTy = Src->getType();
2198 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); // 0 for ptr/vector
2199 unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr/vector
2201 assert(SrcTy->isFirstClassType() && DestTy->isFirstClassType() &&
2202 "Only first class types are castable!");
2204 // Run through the possibilities ...
2205 if (DestTy->isInteger()) { // Casting to integral
2206 if (SrcTy->isInteger()) { // Casting from integral
2207 if (DestBits < SrcBits)
2208 return Trunc; // int -> smaller int
2209 else if (DestBits > SrcBits) { // its an extension
2211 return SExt; // signed -> SEXT
2213 return ZExt; // unsigned -> ZEXT
2215 return BitCast; // Same size, No-op cast
2217 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt
2219 return FPToSI; // FP -> sint
2221 return FPToUI; // FP -> uint
2222 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
2223 assert(DestBits == PTy->getBitWidth() &&
2224 "Casting vector to integer of different width");
2226 return BitCast; // Same size, no-op cast
2228 assert(isa<PointerType>(SrcTy) &&
2229 "Casting from a value that is not first-class type");
2230 return PtrToInt; // ptr -> int
2232 } else if (DestTy->isFloatingPoint()) { // Casting to floating pt
2233 if (SrcTy->isInteger()) { // Casting from integral
2235 return SIToFP; // sint -> FP
2237 return UIToFP; // uint -> FP
2238 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt
2239 if (DestBits < SrcBits) {
2240 return FPTrunc; // FP -> smaller FP
2241 } else if (DestBits > SrcBits) {
2242 return FPExt; // FP -> larger FP
2244 return BitCast; // same size, no-op cast
2246 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
2247 assert(DestBits == PTy->getBitWidth() &&
2248 "Casting vector to floating point of different width");
2250 return BitCast; // same size, no-op cast
2252 assert(0 && "Casting pointer or non-first class to float");
2254 } else if (const VectorType *DestPTy = dyn_cast<VectorType>(DestTy)) {
2255 if (const VectorType *SrcPTy = dyn_cast<VectorType>(SrcTy)) {
2256 assert(DestPTy->getBitWidth() == SrcPTy->getBitWidth() &&
2257 "Casting vector to vector of different widths");
2259 return BitCast; // vector -> vector
2260 } else if (DestPTy->getBitWidth() == SrcBits) {
2261 return BitCast; // float/int -> vector
2263 assert(!"Illegal cast to vector (wrong type or size)");
2265 } else if (isa<PointerType>(DestTy)) {
2266 if (isa<PointerType>(SrcTy)) {
2267 return BitCast; // ptr -> ptr
2268 } else if (SrcTy->isInteger()) {
2269 return IntToPtr; // int -> ptr
2271 assert(!"Casting pointer to other than pointer or int");
2274 assert(!"Casting to type that is not first-class");
2277 // If we fall through to here we probably hit an assertion cast above
2278 // and assertions are not turned on. Anything we return is an error, so
2279 // BitCast is as good a choice as any.
2283 //===----------------------------------------------------------------------===//
2284 // CastInst SubClass Constructors
2285 //===----------------------------------------------------------------------===//
2287 /// Check that the construction parameters for a CastInst are correct. This
2288 /// could be broken out into the separate constructors but it is useful to have
2289 /// it in one place and to eliminate the redundant code for getting the sizes
2290 /// of the types involved.
2292 CastInst::castIsValid(Instruction::CastOps op, Value *S, const Type *DstTy) {
2294 // Check for type sanity on the arguments
2295 const Type *SrcTy = S->getType();
2296 if (!SrcTy->isFirstClassType() || !DstTy->isFirstClassType())
2299 // Get the size of the types in bits, we'll need this later
2300 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
2301 unsigned DstBitSize = DstTy->getPrimitiveSizeInBits();
2303 // Switch on the opcode provided
2305 default: return false; // This is an input error
2306 case Instruction::Trunc:
2307 return SrcTy->isIntOrIntVector() &&
2308 DstTy->isIntOrIntVector()&& SrcBitSize > DstBitSize;
2309 case Instruction::ZExt:
2310 return SrcTy->isIntOrIntVector() &&
2311 DstTy->isIntOrIntVector()&& SrcBitSize < DstBitSize;
2312 case Instruction::SExt:
2313 return SrcTy->isIntOrIntVector() &&
2314 DstTy->isIntOrIntVector()&& SrcBitSize < DstBitSize;
2315 case Instruction::FPTrunc:
2316 return SrcTy->isFPOrFPVector() &&
2317 DstTy->isFPOrFPVector() &&
2318 SrcBitSize > DstBitSize;
2319 case Instruction::FPExt:
2320 return SrcTy->isFPOrFPVector() &&
2321 DstTy->isFPOrFPVector() &&
2322 SrcBitSize < DstBitSize;
2323 case Instruction::UIToFP:
2324 case Instruction::SIToFP:
2325 if (const VectorType *SVTy = dyn_cast<VectorType>(SrcTy)) {
2326 if (const VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
2327 return SVTy->getElementType()->isIntOrIntVector() &&
2328 DVTy->getElementType()->isFPOrFPVector() &&
2329 SVTy->getNumElements() == DVTy->getNumElements();
2332 return SrcTy->isIntOrIntVector() && DstTy->isFPOrFPVector();
2333 case Instruction::FPToUI:
2334 case Instruction::FPToSI:
2335 if (const VectorType *SVTy = dyn_cast<VectorType>(SrcTy)) {
2336 if (const VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
2337 return SVTy->getElementType()->isFPOrFPVector() &&
2338 DVTy->getElementType()->isIntOrIntVector() &&
2339 SVTy->getNumElements() == DVTy->getNumElements();
2342 return SrcTy->isFPOrFPVector() && DstTy->isIntOrIntVector();
2343 case Instruction::PtrToInt:
2344 return isa<PointerType>(SrcTy) && DstTy->isInteger();
2345 case Instruction::IntToPtr:
2346 return SrcTy->isInteger() && isa<PointerType>(DstTy);
2347 case Instruction::BitCast:
2348 // BitCast implies a no-op cast of type only. No bits change.
2349 // However, you can't cast pointers to anything but pointers.
2350 if (isa<PointerType>(SrcTy) != isa<PointerType>(DstTy))
2353 // Now we know we're not dealing with a pointer/non-pointer mismatch. In all
2354 // these cases, the cast is okay if the source and destination bit widths
2356 return SrcBitSize == DstBitSize;
2360 TruncInst::TruncInst(
2361 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2362 ) : CastInst(Ty, Trunc, S, Name, InsertBefore) {
2363 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
2366 TruncInst::TruncInst(
2367 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2368 ) : CastInst(Ty, Trunc, S, Name, InsertAtEnd) {
2369 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
2373 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2374 ) : CastInst(Ty, ZExt, S, Name, InsertBefore) {
2375 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
2379 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2380 ) : CastInst(Ty, ZExt, S, Name, InsertAtEnd) {
2381 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
2384 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2385 ) : CastInst(Ty, SExt, S, Name, InsertBefore) {
2386 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
2390 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2391 ) : CastInst(Ty, SExt, S, Name, InsertAtEnd) {
2392 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
2395 FPTruncInst::FPTruncInst(
2396 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2397 ) : CastInst(Ty, FPTrunc, S, Name, InsertBefore) {
2398 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
2401 FPTruncInst::FPTruncInst(
2402 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2403 ) : CastInst(Ty, FPTrunc, S, Name, InsertAtEnd) {
2404 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
2407 FPExtInst::FPExtInst(
2408 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2409 ) : CastInst(Ty, FPExt, S, Name, InsertBefore) {
2410 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
2413 FPExtInst::FPExtInst(
2414 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2415 ) : CastInst(Ty, FPExt, S, Name, InsertAtEnd) {
2416 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
2419 UIToFPInst::UIToFPInst(
2420 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2421 ) : CastInst(Ty, UIToFP, S, Name, InsertBefore) {
2422 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
2425 UIToFPInst::UIToFPInst(
2426 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2427 ) : CastInst(Ty, UIToFP, S, Name, InsertAtEnd) {
2428 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
2431 SIToFPInst::SIToFPInst(
2432 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2433 ) : CastInst(Ty, SIToFP, S, Name, InsertBefore) {
2434 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
2437 SIToFPInst::SIToFPInst(
2438 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2439 ) : CastInst(Ty, SIToFP, S, Name, InsertAtEnd) {
2440 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
2443 FPToUIInst::FPToUIInst(
2444 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2445 ) : CastInst(Ty, FPToUI, S, Name, InsertBefore) {
2446 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
2449 FPToUIInst::FPToUIInst(
2450 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2451 ) : CastInst(Ty, FPToUI, S, Name, InsertAtEnd) {
2452 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
2455 FPToSIInst::FPToSIInst(
2456 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2457 ) : CastInst(Ty, FPToSI, S, Name, InsertBefore) {
2458 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
2461 FPToSIInst::FPToSIInst(
2462 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2463 ) : CastInst(Ty, FPToSI, S, Name, InsertAtEnd) {
2464 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
2467 PtrToIntInst::PtrToIntInst(
2468 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2469 ) : CastInst(Ty, PtrToInt, S, Name, InsertBefore) {
2470 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
2473 PtrToIntInst::PtrToIntInst(
2474 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2475 ) : CastInst(Ty, PtrToInt, S, Name, InsertAtEnd) {
2476 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
2479 IntToPtrInst::IntToPtrInst(
2480 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2481 ) : CastInst(Ty, IntToPtr, S, Name, InsertBefore) {
2482 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
2485 IntToPtrInst::IntToPtrInst(
2486 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2487 ) : CastInst(Ty, IntToPtr, S, Name, InsertAtEnd) {
2488 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
2491 BitCastInst::BitCastInst(
2492 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2493 ) : CastInst(Ty, BitCast, S, Name, InsertBefore) {
2494 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
2497 BitCastInst::BitCastInst(
2498 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2499 ) : CastInst(Ty, BitCast, S, Name, InsertAtEnd) {
2500 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
2503 //===----------------------------------------------------------------------===//
2505 //===----------------------------------------------------------------------===//
2507 CmpInst::CmpInst(const Type *ty, OtherOps op, unsigned short predicate,
2508 Value *LHS, Value *RHS, const std::string &Name,
2509 Instruction *InsertBefore)
2510 : Instruction(ty, op,
2511 OperandTraits<CmpInst>::op_begin(this),
2512 OperandTraits<CmpInst>::operands(this),
2516 SubclassData = predicate;
2520 CmpInst::CmpInst(const Type *ty, OtherOps op, unsigned short predicate,
2521 Value *LHS, Value *RHS, const std::string &Name,
2522 BasicBlock *InsertAtEnd)
2523 : Instruction(ty, op,
2524 OperandTraits<CmpInst>::op_begin(this),
2525 OperandTraits<CmpInst>::operands(this),
2529 SubclassData = predicate;
2534 CmpInst::Create(OtherOps Op, unsigned short predicate, Value *S1, Value *S2,
2535 const std::string &Name, Instruction *InsertBefore) {
2536 if (Op == Instruction::ICmp) {
2537 return new ICmpInst(CmpInst::Predicate(predicate), S1, S2, Name,
2540 if (Op == Instruction::FCmp) {
2541 return new FCmpInst(CmpInst::Predicate(predicate), S1, S2, Name,
2544 if (Op == Instruction::VICmp) {
2545 return new VICmpInst(CmpInst::Predicate(predicate), S1, S2, Name,
2548 return new VFCmpInst(CmpInst::Predicate(predicate), S1, S2, Name,
2553 CmpInst::Create(OtherOps Op, unsigned short predicate, Value *S1, Value *S2,
2554 const std::string &Name, BasicBlock *InsertAtEnd) {
2555 if (Op == Instruction::ICmp) {
2556 return new ICmpInst(CmpInst::Predicate(predicate), S1, S2, Name,
2559 if (Op == Instruction::FCmp) {
2560 return new FCmpInst(CmpInst::Predicate(predicate), S1, S2, Name,
2563 if (Op == Instruction::VICmp) {
2564 return new VICmpInst(CmpInst::Predicate(predicate), S1, S2, Name,
2567 return new VFCmpInst(CmpInst::Predicate(predicate), S1, S2, Name,
2571 void CmpInst::swapOperands() {
2572 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2575 cast<FCmpInst>(this)->swapOperands();
2578 bool CmpInst::isCommutative() {
2579 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2580 return IC->isCommutative();
2581 return cast<FCmpInst>(this)->isCommutative();
2584 bool CmpInst::isEquality() {
2585 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2586 return IC->isEquality();
2587 return cast<FCmpInst>(this)->isEquality();
2591 CmpInst::Predicate CmpInst::getInversePredicate(Predicate pred) {
2593 default: assert(!"Unknown cmp predicate!");
2594 case ICMP_EQ: return ICMP_NE;
2595 case ICMP_NE: return ICMP_EQ;
2596 case ICMP_UGT: return ICMP_ULE;
2597 case ICMP_ULT: return ICMP_UGE;
2598 case ICMP_UGE: return ICMP_ULT;
2599 case ICMP_ULE: return ICMP_UGT;
2600 case ICMP_SGT: return ICMP_SLE;
2601 case ICMP_SLT: return ICMP_SGE;
2602 case ICMP_SGE: return ICMP_SLT;
2603 case ICMP_SLE: return ICMP_SGT;
2605 case FCMP_OEQ: return FCMP_UNE;
2606 case FCMP_ONE: return FCMP_UEQ;
2607 case FCMP_OGT: return FCMP_ULE;
2608 case FCMP_OLT: return FCMP_UGE;
2609 case FCMP_OGE: return FCMP_ULT;
2610 case FCMP_OLE: return FCMP_UGT;
2611 case FCMP_UEQ: return FCMP_ONE;
2612 case FCMP_UNE: return FCMP_OEQ;
2613 case FCMP_UGT: return FCMP_OLE;
2614 case FCMP_ULT: return FCMP_OGE;
2615 case FCMP_UGE: return FCMP_OLT;
2616 case FCMP_ULE: return FCMP_OGT;
2617 case FCMP_ORD: return FCMP_UNO;
2618 case FCMP_UNO: return FCMP_ORD;
2619 case FCMP_TRUE: return FCMP_FALSE;
2620 case FCMP_FALSE: return FCMP_TRUE;
2624 ICmpInst::Predicate ICmpInst::getSignedPredicate(Predicate pred) {
2626 default: assert(! "Unknown icmp predicate!");
2627 case ICMP_EQ: case ICMP_NE:
2628 case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE:
2630 case ICMP_UGT: return ICMP_SGT;
2631 case ICMP_ULT: return ICMP_SLT;
2632 case ICMP_UGE: return ICMP_SGE;
2633 case ICMP_ULE: return ICMP_SLE;
2637 ICmpInst::Predicate ICmpInst::getUnsignedPredicate(Predicate pred) {
2639 default: assert(! "Unknown icmp predicate!");
2640 case ICMP_EQ: case ICMP_NE:
2641 case ICMP_UGT: case ICMP_ULT: case ICMP_UGE: case ICMP_ULE:
2643 case ICMP_SGT: return ICMP_UGT;
2644 case ICMP_SLT: return ICMP_ULT;
2645 case ICMP_SGE: return ICMP_UGE;
2646 case ICMP_SLE: return ICMP_ULE;
2650 bool ICmpInst::isSignedPredicate(Predicate pred) {
2652 default: assert(! "Unknown icmp predicate!");
2653 case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE:
2655 case ICMP_EQ: case ICMP_NE: case ICMP_UGT: case ICMP_ULT:
2656 case ICMP_UGE: case ICMP_ULE:
2661 /// Initialize a set of values that all satisfy the condition with C.
2664 ICmpInst::makeConstantRange(Predicate pred, const APInt &C) {
2667 uint32_t BitWidth = C.getBitWidth();
2669 default: assert(0 && "Invalid ICmp opcode to ConstantRange ctor!");
2670 case ICmpInst::ICMP_EQ: Upper++; break;
2671 case ICmpInst::ICMP_NE: Lower++; break;
2672 case ICmpInst::ICMP_ULT: Lower = APInt::getMinValue(BitWidth); break;
2673 case ICmpInst::ICMP_SLT: Lower = APInt::getSignedMinValue(BitWidth); break;
2674 case ICmpInst::ICMP_UGT:
2675 Lower++; Upper = APInt::getMinValue(BitWidth); // Min = Next(Max)
2677 case ICmpInst::ICMP_SGT:
2678 Lower++; Upper = APInt::getSignedMinValue(BitWidth); // Min = Next(Max)
2680 case ICmpInst::ICMP_ULE:
2681 Lower = APInt::getMinValue(BitWidth); Upper++;
2683 case ICmpInst::ICMP_SLE:
2684 Lower = APInt::getSignedMinValue(BitWidth); Upper++;
2686 case ICmpInst::ICMP_UGE:
2687 Upper = APInt::getMinValue(BitWidth); // Min = Next(Max)
2689 case ICmpInst::ICMP_SGE:
2690 Upper = APInt::getSignedMinValue(BitWidth); // Min = Next(Max)
2693 return ConstantRange(Lower, Upper);
2696 CmpInst::Predicate CmpInst::getSwappedPredicate(Predicate pred) {
2698 default: assert(!"Unknown cmp predicate!");
2699 case ICMP_EQ: case ICMP_NE:
2701 case ICMP_SGT: return ICMP_SLT;
2702 case ICMP_SLT: return ICMP_SGT;
2703 case ICMP_SGE: return ICMP_SLE;
2704 case ICMP_SLE: return ICMP_SGE;
2705 case ICMP_UGT: return ICMP_ULT;
2706 case ICMP_ULT: return ICMP_UGT;
2707 case ICMP_UGE: return ICMP_ULE;
2708 case ICMP_ULE: return ICMP_UGE;
2710 case FCMP_FALSE: case FCMP_TRUE:
2711 case FCMP_OEQ: case FCMP_ONE:
2712 case FCMP_UEQ: case FCMP_UNE:
2713 case FCMP_ORD: case FCMP_UNO:
2715 case FCMP_OGT: return FCMP_OLT;
2716 case FCMP_OLT: return FCMP_OGT;
2717 case FCMP_OGE: return FCMP_OLE;
2718 case FCMP_OLE: return FCMP_OGE;
2719 case FCMP_UGT: return FCMP_ULT;
2720 case FCMP_ULT: return FCMP_UGT;
2721 case FCMP_UGE: return FCMP_ULE;
2722 case FCMP_ULE: return FCMP_UGE;
2726 bool CmpInst::isUnsigned(unsigned short predicate) {
2727 switch (predicate) {
2728 default: return false;
2729 case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_ULE: case ICmpInst::ICMP_UGT:
2730 case ICmpInst::ICMP_UGE: return true;
2734 bool CmpInst::isSigned(unsigned short predicate){
2735 switch (predicate) {
2736 default: return false;
2737 case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_SLE: case ICmpInst::ICMP_SGT:
2738 case ICmpInst::ICMP_SGE: return true;
2742 bool CmpInst::isOrdered(unsigned short predicate) {
2743 switch (predicate) {
2744 default: return false;
2745 case FCmpInst::FCMP_OEQ: case FCmpInst::FCMP_ONE: case FCmpInst::FCMP_OGT:
2746 case FCmpInst::FCMP_OLT: case FCmpInst::FCMP_OGE: case FCmpInst::FCMP_OLE:
2747 case FCmpInst::FCMP_ORD: return true;
2751 bool CmpInst::isUnordered(unsigned short predicate) {
2752 switch (predicate) {
2753 default: return false;
2754 case FCmpInst::FCMP_UEQ: case FCmpInst::FCMP_UNE: case FCmpInst::FCMP_UGT:
2755 case FCmpInst::FCMP_ULT: case FCmpInst::FCMP_UGE: case FCmpInst::FCMP_ULE:
2756 case FCmpInst::FCMP_UNO: return true;
2760 //===----------------------------------------------------------------------===//
2761 // SwitchInst Implementation
2762 //===----------------------------------------------------------------------===//
2764 void SwitchInst::init(Value *Value, BasicBlock *Default, unsigned NumCases) {
2765 assert(Value && Default);
2766 ReservedSpace = 2+NumCases*2;
2768 OperandList = allocHungoffUses(ReservedSpace);
2770 OperandList[0] = Value;
2771 OperandList[1] = Default;
2774 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
2775 /// switch on and a default destination. The number of additional cases can
2776 /// be specified here to make memory allocation more efficient. This
2777 /// constructor can also autoinsert before another instruction.
2778 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
2779 Instruction *InsertBefore)
2780 : TerminatorInst(Type::VoidTy, Instruction::Switch, 0, 0, InsertBefore) {
2781 init(Value, Default, NumCases);
2784 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
2785 /// switch on and a default destination. The number of additional cases can
2786 /// be specified here to make memory allocation more efficient. This
2787 /// constructor also autoinserts at the end of the specified BasicBlock.
2788 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
2789 BasicBlock *InsertAtEnd)
2790 : TerminatorInst(Type::VoidTy, Instruction::Switch, 0, 0, InsertAtEnd) {
2791 init(Value, Default, NumCases);
2794 SwitchInst::SwitchInst(const SwitchInst &SI)
2795 : TerminatorInst(Type::VoidTy, Instruction::Switch,
2796 allocHungoffUses(SI.getNumOperands()), SI.getNumOperands()) {
2797 Use *OL = OperandList, *InOL = SI.OperandList;
2798 for (unsigned i = 0, E = SI.getNumOperands(); i != E; i+=2) {
2800 OL[i+1] = InOL[i+1];
2804 SwitchInst::~SwitchInst() {
2805 dropHungoffUses(OperandList);
2809 /// addCase - Add an entry to the switch instruction...
2811 void SwitchInst::addCase(ConstantInt *OnVal, BasicBlock *Dest) {
2812 unsigned OpNo = NumOperands;
2813 if (OpNo+2 > ReservedSpace)
2814 resizeOperands(0); // Get more space!
2815 // Initialize some new operands.
2816 assert(OpNo+1 < ReservedSpace && "Growing didn't work!");
2817 NumOperands = OpNo+2;
2818 OperandList[OpNo] = OnVal;
2819 OperandList[OpNo+1] = Dest;
2822 /// removeCase - This method removes the specified successor from the switch
2823 /// instruction. Note that this cannot be used to remove the default
2824 /// destination (successor #0).
2826 void SwitchInst::removeCase(unsigned idx) {
2827 assert(idx != 0 && "Cannot remove the default case!");
2828 assert(idx*2 < getNumOperands() && "Successor index out of range!!!");
2830 unsigned NumOps = getNumOperands();
2831 Use *OL = OperandList;
2833 // Move everything after this operand down.
2835 // FIXME: we could just swap with the end of the list, then erase. However,
2836 // client might not expect this to happen. The code as it is thrashes the
2837 // use/def lists, which is kinda lame.
2838 for (unsigned i = (idx+1)*2; i != NumOps; i += 2) {
2840 OL[i-2+1] = OL[i+1];
2843 // Nuke the last value.
2844 OL[NumOps-2].set(0);
2845 OL[NumOps-2+1].set(0);
2846 NumOperands = NumOps-2;
2849 /// resizeOperands - resize operands - This adjusts the length of the operands
2850 /// list according to the following behavior:
2851 /// 1. If NumOps == 0, grow the operand list in response to a push_back style
2852 /// of operation. This grows the number of ops by 3 times.
2853 /// 2. If NumOps > NumOperands, reserve space for NumOps operands.
2854 /// 3. If NumOps == NumOperands, trim the reserved space.
2856 void SwitchInst::resizeOperands(unsigned NumOps) {
2857 unsigned e = getNumOperands();
2860 } else if (NumOps*2 > NumOperands) {
2861 // No resize needed.
2862 if (ReservedSpace >= NumOps) return;
2863 } else if (NumOps == NumOperands) {
2864 if (ReservedSpace == NumOps) return;
2869 ReservedSpace = NumOps;
2870 Use *NewOps = allocHungoffUses(NumOps);
2871 Use *OldOps = OperandList;
2872 for (unsigned i = 0; i != e; ++i) {
2873 NewOps[i] = OldOps[i];
2875 OperandList = NewOps;
2876 if (OldOps) Use::zap(OldOps, OldOps + e, true);
2880 BasicBlock *SwitchInst::getSuccessorV(unsigned idx) const {
2881 return getSuccessor(idx);
2883 unsigned SwitchInst::getNumSuccessorsV() const {
2884 return getNumSuccessors();
2886 void SwitchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
2887 setSuccessor(idx, B);
2890 // Define these methods here so vtables don't get emitted into every translation
2891 // unit that uses these classes.
2893 GetElementPtrInst *GetElementPtrInst::clone() const {
2894 return new(getNumOperands()) GetElementPtrInst(*this);
2897 BinaryOperator *BinaryOperator::clone() const {
2898 return Create(getOpcode(), Op<0>(), Op<1>());
2901 FCmpInst* FCmpInst::clone() const {
2902 return new FCmpInst(getPredicate(), Op<0>(), Op<1>());
2904 ICmpInst* ICmpInst::clone() const {
2905 return new ICmpInst(getPredicate(), Op<0>(), Op<1>());
2908 VFCmpInst* VFCmpInst::clone() const {
2909 return new VFCmpInst(getPredicate(), Op<0>(), Op<1>());
2911 VICmpInst* VICmpInst::clone() const {
2912 return new VICmpInst(getPredicate(), Op<0>(), Op<1>());
2915 ExtractValueInst *ExtractValueInst::clone() const {
2916 return new ExtractValueInst(*this);
2918 InsertValueInst *InsertValueInst::clone() const {
2919 return new InsertValueInst(*this);
2923 MallocInst *MallocInst::clone() const { return new MallocInst(*this); }
2924 AllocaInst *AllocaInst::clone() const { return new AllocaInst(*this); }
2925 FreeInst *FreeInst::clone() const { return new FreeInst(getOperand(0)); }
2926 LoadInst *LoadInst::clone() const { return new LoadInst(*this); }
2927 StoreInst *StoreInst::clone() const { return new StoreInst(*this); }
2928 CastInst *TruncInst::clone() const { return new TruncInst(*this); }
2929 CastInst *ZExtInst::clone() const { return new ZExtInst(*this); }
2930 CastInst *SExtInst::clone() const { return new SExtInst(*this); }
2931 CastInst *FPTruncInst::clone() const { return new FPTruncInst(*this); }
2932 CastInst *FPExtInst::clone() const { return new FPExtInst(*this); }
2933 CastInst *UIToFPInst::clone() const { return new UIToFPInst(*this); }
2934 CastInst *SIToFPInst::clone() const { return new SIToFPInst(*this); }
2935 CastInst *FPToUIInst::clone() const { return new FPToUIInst(*this); }
2936 CastInst *FPToSIInst::clone() const { return new FPToSIInst(*this); }
2937 CastInst *PtrToIntInst::clone() const { return new PtrToIntInst(*this); }
2938 CastInst *IntToPtrInst::clone() const { return new IntToPtrInst(*this); }
2939 CastInst *BitCastInst::clone() const { return new BitCastInst(*this); }
2940 CallInst *CallInst::clone() const {
2941 return new(getNumOperands()) CallInst(*this);
2943 SelectInst *SelectInst::clone() const {
2944 return new(getNumOperands()) SelectInst(*this);
2946 VAArgInst *VAArgInst::clone() const { return new VAArgInst(*this); }
2948 ExtractElementInst *ExtractElementInst::clone() const {
2949 return new ExtractElementInst(*this);
2951 InsertElementInst *InsertElementInst::clone() const {
2952 return InsertElementInst::Create(*this);
2954 ShuffleVectorInst *ShuffleVectorInst::clone() const {
2955 return new ShuffleVectorInst(*this);
2957 PHINode *PHINode::clone() const { return new PHINode(*this); }
2958 ReturnInst *ReturnInst::clone() const {
2959 return new(getNumOperands()) ReturnInst(*this);
2961 BranchInst *BranchInst::clone() const {
2962 unsigned Ops(getNumOperands());
2963 return new(Ops, Ops == 1) BranchInst(*this);
2965 SwitchInst *SwitchInst::clone() const { return new SwitchInst(*this); }
2966 InvokeInst *InvokeInst::clone() const {
2967 return new(getNumOperands()) InvokeInst(*this);
2969 UnwindInst *UnwindInst::clone() const { return new UnwindInst(); }
2970 UnreachableInst *UnreachableInst::clone() const { return new UnreachableInst();}