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 #undef CALLSITE_DELEGATE_GETTER
97 #undef CALLSITE_DELEGATE_SETTER
99 //===----------------------------------------------------------------------===//
100 // TerminatorInst Class
101 //===----------------------------------------------------------------------===//
103 // Out of line virtual method, so the vtable, etc has a home.
104 TerminatorInst::~TerminatorInst() {
107 //===----------------------------------------------------------------------===//
108 // UnaryInstruction Class
109 //===----------------------------------------------------------------------===//
111 // Out of line virtual method, so the vtable, etc has a home.
112 UnaryInstruction::~UnaryInstruction() {
115 //===----------------------------------------------------------------------===//
117 //===----------------------------------------------------------------------===//
119 /// areInvalidOperands - Return a string if the specified operands are invalid
120 /// for a select operation, otherwise return null.
121 const char *SelectInst::areInvalidOperands(Value *Op0, Value *Op1, Value *Op2) {
122 if (Op1->getType() != Op2->getType())
123 return "both values to select must have same type";
125 if (const VectorType *VT = dyn_cast<VectorType>(Op0->getType())) {
127 if (VT->getElementType() != Type::Int1Ty)
128 return "vector select condition element type must be i1";
129 const VectorType *ET = dyn_cast<VectorType>(Op1->getType());
131 return "selected values for vector select must be vectors";
132 if (ET->getNumElements() != VT->getNumElements())
133 return "vector select requires selected vectors to have "
134 "the same vector length as select condition";
135 } else if (Op0->getType() != Type::Int1Ty) {
136 return "select condition must be i1 or <n x i1>";
142 //===----------------------------------------------------------------------===//
144 //===----------------------------------------------------------------------===//
146 PHINode::PHINode(const PHINode &PN)
147 : Instruction(PN.getType(), Instruction::PHI,
148 allocHungoffUses(PN.getNumOperands()), PN.getNumOperands()),
149 ReservedSpace(PN.getNumOperands()) {
150 Use *OL = OperandList;
151 for (unsigned i = 0, e = PN.getNumOperands(); i != e; i+=2) {
152 OL[i] = PN.getOperand(i);
153 OL[i+1] = PN.getOperand(i+1);
157 PHINode::~PHINode() {
159 dropHungoffUses(OperandList);
162 // removeIncomingValue - Remove an incoming value. This is useful if a
163 // predecessor basic block is deleted.
164 Value *PHINode::removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty) {
165 unsigned NumOps = getNumOperands();
166 Use *OL = OperandList;
167 assert(Idx*2 < NumOps && "BB not in PHI node!");
168 Value *Removed = OL[Idx*2];
170 // Move everything after this operand down.
172 // FIXME: we could just swap with the end of the list, then erase. However,
173 // client might not expect this to happen. The code as it is thrashes the
174 // use/def lists, which is kinda lame.
175 for (unsigned i = (Idx+1)*2; i != NumOps; i += 2) {
180 // Nuke the last value.
182 OL[NumOps-2+1].set(0);
183 NumOperands = NumOps-2;
185 // If the PHI node is dead, because it has zero entries, nuke it now.
186 if (NumOps == 2 && DeletePHIIfEmpty) {
187 // If anyone is using this PHI, make them use a dummy value instead...
188 replaceAllUsesWith(UndefValue::get(getType()));
194 /// resizeOperands - resize operands - This adjusts the length of the operands
195 /// list according to the following behavior:
196 /// 1. If NumOps == 0, grow the operand list in response to a push_back style
197 /// of operation. This grows the number of ops by 1.5 times.
198 /// 2. If NumOps > NumOperands, reserve space for NumOps operands.
199 /// 3. If NumOps == NumOperands, trim the reserved space.
201 void PHINode::resizeOperands(unsigned NumOps) {
202 unsigned e = getNumOperands();
205 if (NumOps < 4) NumOps = 4; // 4 op PHI nodes are VERY common.
206 } else if (NumOps*2 > NumOperands) {
208 if (ReservedSpace >= NumOps) return;
209 } else if (NumOps == NumOperands) {
210 if (ReservedSpace == NumOps) return;
215 ReservedSpace = NumOps;
216 Use *OldOps = OperandList;
217 Use *NewOps = allocHungoffUses(NumOps);
218 std::copy(OldOps, OldOps + e, NewOps);
219 OperandList = NewOps;
220 if (OldOps) Use::zap(OldOps, OldOps + e, true);
223 /// hasConstantValue - If the specified PHI node always merges together the same
224 /// value, return the value, otherwise return null.
226 Value *PHINode::hasConstantValue(bool AllowNonDominatingInstruction) const {
227 // If the PHI node only has one incoming value, eliminate the PHI node...
228 if (getNumIncomingValues() == 1) {
229 if (getIncomingValue(0) != this) // not X = phi X
230 return getIncomingValue(0);
232 return UndefValue::get(getType()); // Self cycle is dead.
235 // Otherwise if all of the incoming values are the same for the PHI, replace
236 // the PHI node with the incoming value.
239 bool HasUndefInput = false;
240 for (unsigned i = 0, e = getNumIncomingValues(); i != e; ++i)
241 if (isa<UndefValue>(getIncomingValue(i))) {
242 HasUndefInput = true;
243 } else if (getIncomingValue(i) != this) { // Not the PHI node itself...
244 if (InVal && getIncomingValue(i) != InVal)
245 return 0; // Not the same, bail out.
247 InVal = getIncomingValue(i);
250 // The only case that could cause InVal to be null is if we have a PHI node
251 // that only has entries for itself. In this case, there is no entry into the
252 // loop, so kill the PHI.
254 if (InVal == 0) InVal = UndefValue::get(getType());
256 // If we have a PHI node like phi(X, undef, X), where X is defined by some
257 // instruction, we cannot always return X as the result of the PHI node. Only
258 // do this if X is not an instruction (thus it must dominate the PHI block),
259 // or if the client is prepared to deal with this possibility.
260 if (HasUndefInput && !AllowNonDominatingInstruction)
261 if (Instruction *IV = dyn_cast<Instruction>(InVal))
262 // If it's in the entry block, it dominates everything.
263 if (IV->getParent() != &IV->getParent()->getParent()->getEntryBlock() ||
265 return 0; // Cannot guarantee that InVal dominates this PHINode.
267 // All of the incoming values are the same, return the value now.
272 //===----------------------------------------------------------------------===//
273 // CallInst Implementation
274 //===----------------------------------------------------------------------===//
276 CallInst::~CallInst() {
279 void CallInst::init(Value *Func, Value* const *Params, unsigned NumParams) {
280 assert(NumOperands == NumParams+1 && "NumOperands not set up?");
281 Use *OL = OperandList;
284 const FunctionType *FTy =
285 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
286 FTy = FTy; // silence warning.
288 assert((NumParams == FTy->getNumParams() ||
289 (FTy->isVarArg() && NumParams > FTy->getNumParams())) &&
290 "Calling a function with bad signature!");
291 for (unsigned i = 0; i != NumParams; ++i) {
292 assert((i >= FTy->getNumParams() ||
293 FTy->getParamType(i) == Params[i]->getType()) &&
294 "Calling a function with a bad signature!");
299 void CallInst::init(Value *Func, Value *Actual1, Value *Actual2) {
300 assert(NumOperands == 3 && "NumOperands not set up?");
301 Use *OL = OperandList;
306 const FunctionType *FTy =
307 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
308 FTy = FTy; // silence warning.
310 assert((FTy->getNumParams() == 2 ||
311 (FTy->isVarArg() && FTy->getNumParams() < 2)) &&
312 "Calling a function with bad signature");
313 assert((0 >= FTy->getNumParams() ||
314 FTy->getParamType(0) == Actual1->getType()) &&
315 "Calling a function with a bad signature!");
316 assert((1 >= FTy->getNumParams() ||
317 FTy->getParamType(1) == Actual2->getType()) &&
318 "Calling a function with a bad signature!");
321 void CallInst::init(Value *Func, Value *Actual) {
322 assert(NumOperands == 2 && "NumOperands not set up?");
323 Use *OL = OperandList;
327 const FunctionType *FTy =
328 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
329 FTy = FTy; // silence warning.
331 assert((FTy->getNumParams() == 1 ||
332 (FTy->isVarArg() && FTy->getNumParams() == 0)) &&
333 "Calling a function with bad signature");
334 assert((0 == FTy->getNumParams() ||
335 FTy->getParamType(0) == Actual->getType()) &&
336 "Calling a function with a bad signature!");
339 void CallInst::init(Value *Func) {
340 assert(NumOperands == 1 && "NumOperands not set up?");
341 Use *OL = OperandList;
344 const FunctionType *FTy =
345 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
346 FTy = FTy; // silence warning.
348 assert(FTy->getNumParams() == 0 && "Calling a function with bad signature");
351 CallInst::CallInst(Value *Func, Value* Actual, const std::string &Name,
352 Instruction *InsertBefore)
353 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
354 ->getElementType())->getReturnType(),
356 OperandTraits<CallInst>::op_end(this) - 2,
362 CallInst::CallInst(Value *Func, Value* Actual, const std::string &Name,
363 BasicBlock *InsertAtEnd)
364 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
365 ->getElementType())->getReturnType(),
367 OperandTraits<CallInst>::op_end(this) - 2,
372 CallInst::CallInst(Value *Func, const std::string &Name,
373 Instruction *InsertBefore)
374 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
375 ->getElementType())->getReturnType(),
377 OperandTraits<CallInst>::op_end(this) - 1,
383 CallInst::CallInst(Value *Func, const std::string &Name,
384 BasicBlock *InsertAtEnd)
385 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
386 ->getElementType())->getReturnType(),
388 OperandTraits<CallInst>::op_end(this) - 1,
394 CallInst::CallInst(const CallInst &CI)
395 : Instruction(CI.getType(), Instruction::Call,
396 OperandTraits<CallInst>::op_end(this) - CI.getNumOperands(),
397 CI.getNumOperands()) {
398 setAttributes(CI.getAttributes());
399 SubclassData = CI.SubclassData;
400 Use *OL = OperandList;
401 Use *InOL = CI.OperandList;
402 for (unsigned i = 0, e = CI.getNumOperands(); i != e; ++i)
406 void CallInst::addAttribute(unsigned i, Attributes attr) {
407 AttrListPtr PAL = getAttributes();
408 PAL = PAL.addAttr(i, attr);
412 void CallInst::removeAttribute(unsigned i, Attributes attr) {
413 AttrListPtr PAL = getAttributes();
414 PAL = PAL.removeAttr(i, attr);
418 bool CallInst::paramHasAttr(unsigned i, Attributes attr) const {
419 if (AttributeList.paramHasAttr(i, attr))
421 if (const Function *F = getCalledFunction())
422 return F->paramHasAttr(i, attr);
427 //===----------------------------------------------------------------------===//
428 // InvokeInst Implementation
429 //===----------------------------------------------------------------------===//
431 void InvokeInst::init(Value *Fn, BasicBlock *IfNormal, BasicBlock *IfException,
432 Value* const *Args, unsigned NumArgs) {
433 assert(NumOperands == 3+NumArgs && "NumOperands not set up?");
434 Use *OL = OperandList;
438 const FunctionType *FTy =
439 cast<FunctionType>(cast<PointerType>(Fn->getType())->getElementType());
440 FTy = FTy; // silence warning.
442 assert(((NumArgs == FTy->getNumParams()) ||
443 (FTy->isVarArg() && NumArgs > FTy->getNumParams())) &&
444 "Calling a function with bad signature");
446 for (unsigned i = 0, e = NumArgs; i != e; i++) {
447 assert((i >= FTy->getNumParams() ||
448 FTy->getParamType(i) == Args[i]->getType()) &&
449 "Invoking a function with a bad signature!");
455 InvokeInst::InvokeInst(const InvokeInst &II)
456 : TerminatorInst(II.getType(), Instruction::Invoke,
457 OperandTraits<InvokeInst>::op_end(this)
458 - II.getNumOperands(),
459 II.getNumOperands()) {
460 setAttributes(II.getAttributes());
461 SubclassData = II.SubclassData;
462 Use *OL = OperandList, *InOL = II.OperandList;
463 for (unsigned i = 0, e = II.getNumOperands(); i != e; ++i)
467 BasicBlock *InvokeInst::getSuccessorV(unsigned idx) const {
468 return getSuccessor(idx);
470 unsigned InvokeInst::getNumSuccessorsV() const {
471 return getNumSuccessors();
473 void InvokeInst::setSuccessorV(unsigned idx, BasicBlock *B) {
474 return setSuccessor(idx, B);
477 bool InvokeInst::paramHasAttr(unsigned i, Attributes attr) const {
478 if (AttributeList.paramHasAttr(i, attr))
480 if (const Function *F = getCalledFunction())
481 return F->paramHasAttr(i, attr);
485 void InvokeInst::addAttribute(unsigned i, Attributes attr) {
486 AttrListPtr PAL = getAttributes();
487 PAL = PAL.addAttr(i, attr);
491 void InvokeInst::removeAttribute(unsigned i, Attributes attr) {
492 AttrListPtr PAL = getAttributes();
493 PAL = PAL.removeAttr(i, attr);
498 //===----------------------------------------------------------------------===//
499 // ReturnInst Implementation
500 //===----------------------------------------------------------------------===//
502 ReturnInst::ReturnInst(const ReturnInst &RI)
503 : TerminatorInst(Type::VoidTy, Instruction::Ret,
504 OperandTraits<ReturnInst>::op_end(this) -
506 RI.getNumOperands()) {
507 if (RI.getNumOperands())
508 Op<0>() = RI.Op<0>();
511 ReturnInst::ReturnInst(Value *retVal, Instruction *InsertBefore)
512 : TerminatorInst(Type::VoidTy, Instruction::Ret,
513 OperandTraits<ReturnInst>::op_end(this) - !!retVal, !!retVal,
518 ReturnInst::ReturnInst(Value *retVal, BasicBlock *InsertAtEnd)
519 : TerminatorInst(Type::VoidTy, Instruction::Ret,
520 OperandTraits<ReturnInst>::op_end(this) - !!retVal, !!retVal,
525 ReturnInst::ReturnInst(BasicBlock *InsertAtEnd)
526 : TerminatorInst(Type::VoidTy, Instruction::Ret,
527 OperandTraits<ReturnInst>::op_end(this), 0, InsertAtEnd) {
530 unsigned ReturnInst::getNumSuccessorsV() const {
531 return getNumSuccessors();
534 /// Out-of-line ReturnInst method, put here so the C++ compiler can choose to
535 /// emit the vtable for the class in this translation unit.
536 void ReturnInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
537 assert(0 && "ReturnInst has no successors!");
540 BasicBlock *ReturnInst::getSuccessorV(unsigned idx) const {
541 assert(0 && "ReturnInst has no successors!");
546 ReturnInst::~ReturnInst() {
549 //===----------------------------------------------------------------------===//
550 // UnwindInst Implementation
551 //===----------------------------------------------------------------------===//
553 UnwindInst::UnwindInst(Instruction *InsertBefore)
554 : TerminatorInst(Type::VoidTy, Instruction::Unwind, 0, 0, InsertBefore) {
556 UnwindInst::UnwindInst(BasicBlock *InsertAtEnd)
557 : TerminatorInst(Type::VoidTy, Instruction::Unwind, 0, 0, InsertAtEnd) {
561 unsigned UnwindInst::getNumSuccessorsV() const {
562 return getNumSuccessors();
565 void UnwindInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
566 assert(0 && "UnwindInst has no successors!");
569 BasicBlock *UnwindInst::getSuccessorV(unsigned idx) const {
570 assert(0 && "UnwindInst has no successors!");
575 //===----------------------------------------------------------------------===//
576 // UnreachableInst Implementation
577 //===----------------------------------------------------------------------===//
579 UnreachableInst::UnreachableInst(Instruction *InsertBefore)
580 : TerminatorInst(Type::VoidTy, Instruction::Unreachable, 0, 0, InsertBefore) {
582 UnreachableInst::UnreachableInst(BasicBlock *InsertAtEnd)
583 : TerminatorInst(Type::VoidTy, Instruction::Unreachable, 0, 0, InsertAtEnd) {
586 unsigned UnreachableInst::getNumSuccessorsV() const {
587 return getNumSuccessors();
590 void UnreachableInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
591 assert(0 && "UnwindInst has no successors!");
594 BasicBlock *UnreachableInst::getSuccessorV(unsigned idx) const {
595 assert(0 && "UnwindInst has no successors!");
600 //===----------------------------------------------------------------------===//
601 // BranchInst Implementation
602 //===----------------------------------------------------------------------===//
604 void BranchInst::AssertOK() {
606 assert(getCondition()->getType() == Type::Int1Ty &&
607 "May only branch on boolean predicates!");
610 BranchInst::BranchInst(BasicBlock *IfTrue, Instruction *InsertBefore)
611 : TerminatorInst(Type::VoidTy, Instruction::Br,
612 OperandTraits<BranchInst>::op_end(this) - 1,
614 assert(IfTrue != 0 && "Branch destination may not be null!");
617 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
618 Instruction *InsertBefore)
619 : TerminatorInst(Type::VoidTy, Instruction::Br,
620 OperandTraits<BranchInst>::op_end(this) - 3,
630 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *InsertAtEnd)
631 : TerminatorInst(Type::VoidTy, Instruction::Br,
632 OperandTraits<BranchInst>::op_end(this) - 1,
634 assert(IfTrue != 0 && "Branch destination may not be null!");
638 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
639 BasicBlock *InsertAtEnd)
640 : TerminatorInst(Type::VoidTy, Instruction::Br,
641 OperandTraits<BranchInst>::op_end(this) - 3,
652 BranchInst::BranchInst(const BranchInst &BI) :
653 TerminatorInst(Type::VoidTy, Instruction::Br,
654 OperandTraits<BranchInst>::op_end(this) - BI.getNumOperands(),
655 BI.getNumOperands()) {
656 OperandList[0] = BI.getOperand(0);
657 if (BI.getNumOperands() != 1) {
658 assert(BI.getNumOperands() == 3 && "BR can have 1 or 3 operands!");
659 OperandList[1] = BI.getOperand(1);
660 OperandList[2] = BI.getOperand(2);
664 BasicBlock *BranchInst::getSuccessorV(unsigned idx) const {
665 return getSuccessor(idx);
667 unsigned BranchInst::getNumSuccessorsV() const {
668 return getNumSuccessors();
670 void BranchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
671 setSuccessor(idx, B);
675 //===----------------------------------------------------------------------===//
676 // AllocationInst Implementation
677 //===----------------------------------------------------------------------===//
679 static Value *getAISize(Value *Amt) {
681 Amt = ConstantInt::get(Type::Int32Ty, 1);
683 assert(!isa<BasicBlock>(Amt) &&
684 "Passed basic block into allocation size parameter! Use other ctor");
685 assert(Amt->getType() == Type::Int32Ty &&
686 "Malloc/Allocation array size is not a 32-bit integer!");
691 AllocationInst::AllocationInst(const Type *Ty, Value *ArraySize, unsigned iTy,
692 unsigned Align, const std::string &Name,
693 Instruction *InsertBefore)
694 : UnaryInstruction(PointerType::getUnqual(Ty), iTy, getAISize(ArraySize),
697 assert(Ty != Type::VoidTy && "Cannot allocate void!");
701 AllocationInst::AllocationInst(const Type *Ty, Value *ArraySize, unsigned iTy,
702 unsigned Align, const std::string &Name,
703 BasicBlock *InsertAtEnd)
704 : UnaryInstruction(PointerType::getUnqual(Ty), iTy, getAISize(ArraySize),
707 assert(Ty != Type::VoidTy && "Cannot allocate void!");
711 // Out of line virtual method, so the vtable, etc has a home.
712 AllocationInst::~AllocationInst() {
715 void AllocationInst::setAlignment(unsigned Align) {
716 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
717 SubclassData = Log2_32(Align) + 1;
718 assert(getAlignment() == Align && "Alignment representation error!");
721 bool AllocationInst::isArrayAllocation() const {
722 if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(0)))
723 return CI->getZExtValue() != 1;
727 const Type *AllocationInst::getAllocatedType() const {
728 return getType()->getElementType();
731 AllocaInst::AllocaInst(const AllocaInst &AI)
732 : AllocationInst(AI.getType()->getElementType(), (Value*)AI.getOperand(0),
733 Instruction::Alloca, AI.getAlignment()) {
736 /// isStaticAlloca - Return true if this alloca is in the entry block of the
737 /// function and is a constant size. If so, the code generator will fold it
738 /// into the prolog/epilog code, so it is basically free.
739 bool AllocaInst::isStaticAlloca() const {
740 // Must be constant size.
741 if (!isa<ConstantInt>(getArraySize())) return false;
743 // Must be in the entry block.
744 const BasicBlock *Parent = getParent();
745 return Parent == &Parent->getParent()->front();
748 MallocInst::MallocInst(const MallocInst &MI)
749 : AllocationInst(MI.getType()->getElementType(), (Value*)MI.getOperand(0),
750 Instruction::Malloc, MI.getAlignment()) {
753 //===----------------------------------------------------------------------===//
754 // FreeInst Implementation
755 //===----------------------------------------------------------------------===//
757 void FreeInst::AssertOK() {
758 assert(isa<PointerType>(getOperand(0)->getType()) &&
759 "Can not free something of nonpointer type!");
762 FreeInst::FreeInst(Value *Ptr, Instruction *InsertBefore)
763 : UnaryInstruction(Type::VoidTy, Free, Ptr, InsertBefore) {
767 FreeInst::FreeInst(Value *Ptr, BasicBlock *InsertAtEnd)
768 : UnaryInstruction(Type::VoidTy, Free, Ptr, InsertAtEnd) {
773 //===----------------------------------------------------------------------===//
774 // LoadInst Implementation
775 //===----------------------------------------------------------------------===//
777 void LoadInst::AssertOK() {
778 assert(isa<PointerType>(getOperand(0)->getType()) &&
779 "Ptr must have pointer type.");
782 LoadInst::LoadInst(Value *Ptr, const std::string &Name, Instruction *InsertBef)
783 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
784 Load, Ptr, InsertBef) {
791 LoadInst::LoadInst(Value *Ptr, const std::string &Name, BasicBlock *InsertAE)
792 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
793 Load, Ptr, InsertAE) {
800 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile,
801 Instruction *InsertBef)
802 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
803 Load, Ptr, InsertBef) {
804 setVolatile(isVolatile);
810 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile,
811 unsigned Align, Instruction *InsertBef)
812 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
813 Load, Ptr, InsertBef) {
814 setVolatile(isVolatile);
820 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile,
821 unsigned Align, BasicBlock *InsertAE)
822 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
823 Load, Ptr, InsertAE) {
824 setVolatile(isVolatile);
830 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile,
831 BasicBlock *InsertAE)
832 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
833 Load, Ptr, InsertAE) {
834 setVolatile(isVolatile);
842 LoadInst::LoadInst(Value *Ptr, const char *Name, Instruction *InsertBef)
843 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
844 Load, Ptr, InsertBef) {
848 if (Name && Name[0]) setName(Name);
851 LoadInst::LoadInst(Value *Ptr, const char *Name, BasicBlock *InsertAE)
852 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
853 Load, Ptr, InsertAE) {
857 if (Name && Name[0]) setName(Name);
860 LoadInst::LoadInst(Value *Ptr, const char *Name, bool isVolatile,
861 Instruction *InsertBef)
862 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
863 Load, Ptr, InsertBef) {
864 setVolatile(isVolatile);
867 if (Name && Name[0]) setName(Name);
870 LoadInst::LoadInst(Value *Ptr, const char *Name, bool isVolatile,
871 BasicBlock *InsertAE)
872 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
873 Load, Ptr, InsertAE) {
874 setVolatile(isVolatile);
877 if (Name && Name[0]) setName(Name);
880 void LoadInst::setAlignment(unsigned Align) {
881 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
882 SubclassData = (SubclassData & 1) | ((Log2_32(Align)+1)<<1);
885 //===----------------------------------------------------------------------===//
886 // StoreInst Implementation
887 //===----------------------------------------------------------------------===//
889 void StoreInst::AssertOK() {
890 assert(getOperand(0) && getOperand(1) && "Both operands must be non-null!");
891 assert(isa<PointerType>(getOperand(1)->getType()) &&
892 "Ptr must have pointer type!");
893 assert(getOperand(0)->getType() ==
894 cast<PointerType>(getOperand(1)->getType())->getElementType()
895 && "Ptr must be a pointer to Val type!");
899 StoreInst::StoreInst(Value *val, Value *addr, Instruction *InsertBefore)
900 : Instruction(Type::VoidTy, Store,
901 OperandTraits<StoreInst>::op_begin(this),
902 OperandTraits<StoreInst>::operands(this),
911 StoreInst::StoreInst(Value *val, Value *addr, BasicBlock *InsertAtEnd)
912 : Instruction(Type::VoidTy, Store,
913 OperandTraits<StoreInst>::op_begin(this),
914 OperandTraits<StoreInst>::operands(this),
923 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
924 Instruction *InsertBefore)
925 : Instruction(Type::VoidTy, Store,
926 OperandTraits<StoreInst>::op_begin(this),
927 OperandTraits<StoreInst>::operands(this),
931 setVolatile(isVolatile);
936 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
937 unsigned Align, Instruction *InsertBefore)
938 : Instruction(Type::VoidTy, Store,
939 OperandTraits<StoreInst>::op_begin(this),
940 OperandTraits<StoreInst>::operands(this),
944 setVolatile(isVolatile);
949 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
950 unsigned Align, BasicBlock *InsertAtEnd)
951 : Instruction(Type::VoidTy, Store,
952 OperandTraits<StoreInst>::op_begin(this),
953 OperandTraits<StoreInst>::operands(this),
957 setVolatile(isVolatile);
962 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
963 BasicBlock *InsertAtEnd)
964 : Instruction(Type::VoidTy, Store,
965 OperandTraits<StoreInst>::op_begin(this),
966 OperandTraits<StoreInst>::operands(this),
970 setVolatile(isVolatile);
975 void StoreInst::setAlignment(unsigned Align) {
976 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
977 SubclassData = (SubclassData & 1) | ((Log2_32(Align)+1)<<1);
980 //===----------------------------------------------------------------------===//
981 // GetElementPtrInst Implementation
982 //===----------------------------------------------------------------------===//
984 static unsigned retrieveAddrSpace(const Value *Val) {
985 return cast<PointerType>(Val->getType())->getAddressSpace();
988 void GetElementPtrInst::init(Value *Ptr, Value* const *Idx, unsigned NumIdx,
989 const std::string &Name) {
990 assert(NumOperands == 1+NumIdx && "NumOperands not initialized?");
991 Use *OL = OperandList;
994 for (unsigned i = 0; i != NumIdx; ++i)
1000 void GetElementPtrInst::init(Value *Ptr, Value *Idx, const std::string &Name) {
1001 assert(NumOperands == 2 && "NumOperands not initialized?");
1002 Use *OL = OperandList;
1009 GetElementPtrInst::GetElementPtrInst(const GetElementPtrInst &GEPI)
1010 : Instruction(GEPI.getType(), GetElementPtr,
1011 OperandTraits<GetElementPtrInst>::op_end(this)
1012 - GEPI.getNumOperands(),
1013 GEPI.getNumOperands()) {
1014 Use *OL = OperandList;
1015 Use *GEPIOL = GEPI.OperandList;
1016 for (unsigned i = 0, E = NumOperands; i != E; ++i)
1020 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx,
1021 const std::string &Name, Instruction *InBe)
1022 : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),Idx)),
1023 retrieveAddrSpace(Ptr)),
1025 OperandTraits<GetElementPtrInst>::op_end(this) - 2,
1027 init(Ptr, Idx, Name);
1030 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx,
1031 const std::string &Name, BasicBlock *IAE)
1032 : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),Idx)),
1033 retrieveAddrSpace(Ptr)),
1035 OperandTraits<GetElementPtrInst>::op_end(this) - 2,
1037 init(Ptr, Idx, Name);
1040 /// getIndexedType - Returns the type of the element that would be accessed with
1041 /// a gep instruction with the specified parameters.
1043 /// The Idxs pointer should point to a continuous piece of memory containing the
1044 /// indices, either as Value* or uint64_t.
1046 /// A null type is returned if the indices are invalid for the specified
1049 template <typename IndexTy>
1050 static const Type* getIndexedTypeInternal(const Type *Ptr, IndexTy const *Idxs,
1052 const PointerType *PTy = dyn_cast<PointerType>(Ptr);
1053 if (!PTy) return 0; // Type isn't a pointer type!
1054 const Type *Agg = PTy->getElementType();
1056 // Handle the special case of the empty set index set, which is always valid.
1060 // If there is at least one index, the top level type must be sized, otherwise
1061 // it cannot be 'stepped over'.
1062 if (!Agg->isSized())
1065 unsigned CurIdx = 1;
1066 for (; CurIdx != NumIdx; ++CurIdx) {
1067 const CompositeType *CT = dyn_cast<CompositeType>(Agg);
1068 if (!CT || isa<PointerType>(CT)) return 0;
1069 IndexTy Index = Idxs[CurIdx];
1070 if (!CT->indexValid(Index)) return 0;
1071 Agg = CT->getTypeAtIndex(Index);
1073 // If the new type forwards to another type, then it is in the middle
1074 // of being refined to another type (and hence, may have dropped all
1075 // references to what it was using before). So, use the new forwarded
1077 if (const Type *Ty = Agg->getForwardedType())
1080 return CurIdx == NumIdx ? Agg : 0;
1083 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr,
1086 return getIndexedTypeInternal(Ptr, Idxs, NumIdx);
1089 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr,
1090 uint64_t const *Idxs,
1092 return getIndexedTypeInternal(Ptr, Idxs, NumIdx);
1095 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr, Value *Idx) {
1096 const PointerType *PTy = dyn_cast<PointerType>(Ptr);
1097 if (!PTy) return 0; // Type isn't a pointer type!
1099 // Check the pointer index.
1100 if (!PTy->indexValid(Idx)) return 0;
1102 return PTy->getElementType();
1106 /// hasAllZeroIndices - Return true if all of the indices of this GEP are
1107 /// zeros. If so, the result pointer and the first operand have the same
1108 /// value, just potentially different types.
1109 bool GetElementPtrInst::hasAllZeroIndices() const {
1110 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1111 if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(i))) {
1112 if (!CI->isZero()) return false;
1120 /// hasAllConstantIndices - Return true if all of the indices of this GEP are
1121 /// constant integers. If so, the result pointer and the first operand have
1122 /// a constant offset between them.
1123 bool GetElementPtrInst::hasAllConstantIndices() const {
1124 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1125 if (!isa<ConstantInt>(getOperand(i)))
1132 //===----------------------------------------------------------------------===//
1133 // ExtractElementInst Implementation
1134 //===----------------------------------------------------------------------===//
1136 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
1137 const std::string &Name,
1138 Instruction *InsertBef)
1139 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1141 OperandTraits<ExtractElementInst>::op_begin(this),
1143 assert(isValidOperands(Val, Index) &&
1144 "Invalid extractelement instruction operands!");
1150 ExtractElementInst::ExtractElementInst(Value *Val, unsigned IndexV,
1151 const std::string &Name,
1152 Instruction *InsertBef)
1153 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1155 OperandTraits<ExtractElementInst>::op_begin(this),
1157 Constant *Index = ConstantInt::get(Type::Int32Ty, IndexV);
1158 assert(isValidOperands(Val, Index) &&
1159 "Invalid extractelement instruction operands!");
1166 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
1167 const std::string &Name,
1168 BasicBlock *InsertAE)
1169 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1171 OperandTraits<ExtractElementInst>::op_begin(this),
1173 assert(isValidOperands(Val, Index) &&
1174 "Invalid extractelement instruction operands!");
1181 ExtractElementInst::ExtractElementInst(Value *Val, unsigned IndexV,
1182 const std::string &Name,
1183 BasicBlock *InsertAE)
1184 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1186 OperandTraits<ExtractElementInst>::op_begin(this),
1188 Constant *Index = ConstantInt::get(Type::Int32Ty, IndexV);
1189 assert(isValidOperands(Val, Index) &&
1190 "Invalid extractelement instruction operands!");
1198 bool ExtractElementInst::isValidOperands(const Value *Val, const Value *Index) {
1199 if (!isa<VectorType>(Val->getType()) || Index->getType() != Type::Int32Ty)
1205 //===----------------------------------------------------------------------===//
1206 // InsertElementInst Implementation
1207 //===----------------------------------------------------------------------===//
1209 InsertElementInst::InsertElementInst(const InsertElementInst &IE)
1210 : Instruction(IE.getType(), InsertElement,
1211 OperandTraits<InsertElementInst>::op_begin(this), 3) {
1212 Op<0>() = IE.Op<0>();
1213 Op<1>() = IE.Op<1>();
1214 Op<2>() = IE.Op<2>();
1216 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
1217 const std::string &Name,
1218 Instruction *InsertBef)
1219 : Instruction(Vec->getType(), InsertElement,
1220 OperandTraits<InsertElementInst>::op_begin(this),
1222 assert(isValidOperands(Vec, Elt, Index) &&
1223 "Invalid insertelement instruction operands!");
1230 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, unsigned IndexV,
1231 const std::string &Name,
1232 Instruction *InsertBef)
1233 : Instruction(Vec->getType(), InsertElement,
1234 OperandTraits<InsertElementInst>::op_begin(this),
1236 Constant *Index = ConstantInt::get(Type::Int32Ty, IndexV);
1237 assert(isValidOperands(Vec, Elt, Index) &&
1238 "Invalid insertelement instruction operands!");
1246 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
1247 const std::string &Name,
1248 BasicBlock *InsertAE)
1249 : Instruction(Vec->getType(), InsertElement,
1250 OperandTraits<InsertElementInst>::op_begin(this),
1252 assert(isValidOperands(Vec, Elt, Index) &&
1253 "Invalid insertelement instruction operands!");
1261 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, unsigned IndexV,
1262 const std::string &Name,
1263 BasicBlock *InsertAE)
1264 : Instruction(Vec->getType(), InsertElement,
1265 OperandTraits<InsertElementInst>::op_begin(this),
1267 Constant *Index = ConstantInt::get(Type::Int32Ty, IndexV);
1268 assert(isValidOperands(Vec, Elt, Index) &&
1269 "Invalid insertelement instruction operands!");
1277 bool InsertElementInst::isValidOperands(const Value *Vec, const Value *Elt,
1278 const Value *Index) {
1279 if (!isa<VectorType>(Vec->getType()))
1280 return false; // First operand of insertelement must be vector type.
1282 if (Elt->getType() != cast<VectorType>(Vec->getType())->getElementType())
1283 return false;// Second operand of insertelement must be vector element type.
1285 if (Index->getType() != Type::Int32Ty)
1286 return false; // Third operand of insertelement must be uint.
1291 //===----------------------------------------------------------------------===//
1292 // ShuffleVectorInst Implementation
1293 //===----------------------------------------------------------------------===//
1295 ShuffleVectorInst::ShuffleVectorInst(const ShuffleVectorInst &SV)
1296 : Instruction(SV.getType(), ShuffleVector,
1297 OperandTraits<ShuffleVectorInst>::op_begin(this),
1298 OperandTraits<ShuffleVectorInst>::operands(this)) {
1299 Op<0>() = SV.Op<0>();
1300 Op<1>() = SV.Op<1>();
1301 Op<2>() = SV.Op<2>();
1304 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1305 const std::string &Name,
1306 Instruction *InsertBefore)
1307 : Instruction(VectorType::get(cast<VectorType>(V1->getType())->getElementType(),
1308 cast<VectorType>(Mask->getType())->getNumElements()),
1310 OperandTraits<ShuffleVectorInst>::op_begin(this),
1311 OperandTraits<ShuffleVectorInst>::operands(this),
1313 assert(isValidOperands(V1, V2, Mask) &&
1314 "Invalid shuffle vector instruction operands!");
1321 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1322 const std::string &Name,
1323 BasicBlock *InsertAtEnd)
1324 : Instruction(V1->getType(), ShuffleVector,
1325 OperandTraits<ShuffleVectorInst>::op_begin(this),
1326 OperandTraits<ShuffleVectorInst>::operands(this),
1328 assert(isValidOperands(V1, V2, Mask) &&
1329 "Invalid shuffle vector instruction operands!");
1337 bool ShuffleVectorInst::isValidOperands(const Value *V1, const Value *V2,
1338 const Value *Mask) {
1339 if (!isa<VectorType>(V1->getType()) || V1->getType() != V2->getType())
1342 const VectorType *MaskTy = dyn_cast<VectorType>(Mask->getType());
1343 if (!isa<Constant>(Mask) || MaskTy == 0 ||
1344 MaskTy->getElementType() != Type::Int32Ty)
1349 /// getMaskValue - Return the index from the shuffle mask for the specified
1350 /// output result. This is either -1 if the element is undef or a number less
1351 /// than 2*numelements.
1352 int ShuffleVectorInst::getMaskValue(unsigned i) const {
1353 const Constant *Mask = cast<Constant>(getOperand(2));
1354 if (isa<UndefValue>(Mask)) return -1;
1355 if (isa<ConstantAggregateZero>(Mask)) return 0;
1356 const ConstantVector *MaskCV = cast<ConstantVector>(Mask);
1357 assert(i < MaskCV->getNumOperands() && "Index out of range");
1359 if (isa<UndefValue>(MaskCV->getOperand(i)))
1361 return cast<ConstantInt>(MaskCV->getOperand(i))->getZExtValue();
1364 //===----------------------------------------------------------------------===//
1365 // InsertValueInst Class
1366 //===----------------------------------------------------------------------===//
1368 void InsertValueInst::init(Value *Agg, Value *Val, const unsigned *Idx,
1369 unsigned NumIdx, const std::string &Name) {
1370 assert(NumOperands == 2 && "NumOperands not initialized?");
1374 Indices.insert(Indices.end(), Idx, Idx + NumIdx);
1378 void InsertValueInst::init(Value *Agg, Value *Val, unsigned Idx,
1379 const std::string &Name) {
1380 assert(NumOperands == 2 && "NumOperands not initialized?");
1384 Indices.push_back(Idx);
1388 InsertValueInst::InsertValueInst(const InsertValueInst &IVI)
1389 : Instruction(IVI.getType(), InsertValue,
1390 OperandTraits<InsertValueInst>::op_begin(this), 2),
1391 Indices(IVI.Indices) {
1392 Op<0>() = IVI.getOperand(0);
1393 Op<1>() = IVI.getOperand(1);
1396 InsertValueInst::InsertValueInst(Value *Agg,
1399 const std::string &Name,
1400 Instruction *InsertBefore)
1401 : Instruction(Agg->getType(), InsertValue,
1402 OperandTraits<InsertValueInst>::op_begin(this),
1404 init(Agg, Val, Idx, Name);
1407 InsertValueInst::InsertValueInst(Value *Agg,
1410 const std::string &Name,
1411 BasicBlock *InsertAtEnd)
1412 : Instruction(Agg->getType(), InsertValue,
1413 OperandTraits<InsertValueInst>::op_begin(this),
1415 init(Agg, Val, Idx, Name);
1418 //===----------------------------------------------------------------------===//
1419 // ExtractValueInst Class
1420 //===----------------------------------------------------------------------===//
1422 void ExtractValueInst::init(const unsigned *Idx, unsigned NumIdx,
1423 const std::string &Name) {
1424 assert(NumOperands == 1 && "NumOperands not initialized?");
1426 Indices.insert(Indices.end(), Idx, Idx + NumIdx);
1430 void ExtractValueInst::init(unsigned Idx, const std::string &Name) {
1431 assert(NumOperands == 1 && "NumOperands not initialized?");
1433 Indices.push_back(Idx);
1437 ExtractValueInst::ExtractValueInst(const ExtractValueInst &EVI)
1438 : UnaryInstruction(EVI.getType(), ExtractValue, EVI.getOperand(0)),
1439 Indices(EVI.Indices) {
1442 // getIndexedType - Returns the type of the element that would be extracted
1443 // with an extractvalue instruction with the specified parameters.
1445 // A null type is returned if the indices are invalid for the specified
1448 const Type* ExtractValueInst::getIndexedType(const Type *Agg,
1449 const unsigned *Idxs,
1451 unsigned CurIdx = 0;
1452 for (; CurIdx != NumIdx; ++CurIdx) {
1453 const CompositeType *CT = dyn_cast<CompositeType>(Agg);
1454 if (!CT || isa<PointerType>(CT) || isa<VectorType>(CT)) return 0;
1455 unsigned Index = Idxs[CurIdx];
1456 if (!CT->indexValid(Index)) return 0;
1457 Agg = CT->getTypeAtIndex(Index);
1459 // If the new type forwards to another type, then it is in the middle
1460 // of being refined to another type (and hence, may have dropped all
1461 // references to what it was using before). So, use the new forwarded
1463 if (const Type *Ty = Agg->getForwardedType())
1466 return CurIdx == NumIdx ? Agg : 0;
1469 const Type* ExtractValueInst::getIndexedType(const Type *Agg,
1471 return getIndexedType(Agg, &Idx, 1);
1474 //===----------------------------------------------------------------------===//
1475 // BinaryOperator Class
1476 //===----------------------------------------------------------------------===//
1478 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
1479 const Type *Ty, const std::string &Name,
1480 Instruction *InsertBefore)
1481 : Instruction(Ty, iType,
1482 OperandTraits<BinaryOperator>::op_begin(this),
1483 OperandTraits<BinaryOperator>::operands(this),
1491 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
1492 const Type *Ty, const std::string &Name,
1493 BasicBlock *InsertAtEnd)
1494 : Instruction(Ty, iType,
1495 OperandTraits<BinaryOperator>::op_begin(this),
1496 OperandTraits<BinaryOperator>::operands(this),
1505 void BinaryOperator::init(BinaryOps iType) {
1506 Value *LHS = getOperand(0), *RHS = getOperand(1);
1507 LHS = LHS; RHS = RHS; // Silence warnings.
1508 assert(LHS->getType() == RHS->getType() &&
1509 "Binary operator operand types must match!");
1514 assert(getType() == LHS->getType() &&
1515 "Arithmetic operation should return same type as operands!");
1516 assert((getType()->isInteger() || getType()->isFloatingPoint() ||
1517 isa<VectorType>(getType())) &&
1518 "Tried to create an arithmetic operation on a non-arithmetic type!");
1522 assert(getType() == LHS->getType() &&
1523 "Arithmetic operation should return same type as operands!");
1524 assert((getType()->isInteger() || (isa<VectorType>(getType()) &&
1525 cast<VectorType>(getType())->getElementType()->isInteger())) &&
1526 "Incorrect operand type (not integer) for S/UDIV");
1529 assert(getType() == LHS->getType() &&
1530 "Arithmetic operation should return same type as operands!");
1531 assert((getType()->isFloatingPoint() || (isa<VectorType>(getType()) &&
1532 cast<VectorType>(getType())->getElementType()->isFloatingPoint()))
1533 && "Incorrect operand type (not floating point) for FDIV");
1537 assert(getType() == LHS->getType() &&
1538 "Arithmetic operation should return same type as operands!");
1539 assert((getType()->isInteger() || (isa<VectorType>(getType()) &&
1540 cast<VectorType>(getType())->getElementType()->isInteger())) &&
1541 "Incorrect operand type (not integer) for S/UREM");
1544 assert(getType() == LHS->getType() &&
1545 "Arithmetic operation should return same type as operands!");
1546 assert((getType()->isFloatingPoint() || (isa<VectorType>(getType()) &&
1547 cast<VectorType>(getType())->getElementType()->isFloatingPoint()))
1548 && "Incorrect operand type (not floating point) for FREM");
1553 assert(getType() == LHS->getType() &&
1554 "Shift operation should return same type as operands!");
1555 assert((getType()->isInteger() ||
1556 (isa<VectorType>(getType()) &&
1557 cast<VectorType>(getType())->getElementType()->isInteger())) &&
1558 "Tried to create a shift operation on a non-integral type!");
1562 assert(getType() == LHS->getType() &&
1563 "Logical operation should return same type as operands!");
1564 assert((getType()->isInteger() ||
1565 (isa<VectorType>(getType()) &&
1566 cast<VectorType>(getType())->getElementType()->isInteger())) &&
1567 "Tried to create a logical operation on a non-integral type!");
1575 BinaryOperator *BinaryOperator::Create(BinaryOps Op, Value *S1, Value *S2,
1576 const std::string &Name,
1577 Instruction *InsertBefore) {
1578 assert(S1->getType() == S2->getType() &&
1579 "Cannot create binary operator with two operands of differing type!");
1580 return new BinaryOperator(Op, S1, S2, S1->getType(), Name, InsertBefore);
1583 BinaryOperator *BinaryOperator::Create(BinaryOps Op, Value *S1, Value *S2,
1584 const std::string &Name,
1585 BasicBlock *InsertAtEnd) {
1586 BinaryOperator *Res = Create(Op, S1, S2, Name);
1587 InsertAtEnd->getInstList().push_back(Res);
1591 BinaryOperator *BinaryOperator::CreateNeg(Value *Op, const std::string &Name,
1592 Instruction *InsertBefore) {
1593 Value *zero = ConstantExpr::getZeroValueForNegationExpr(Op->getType());
1594 return new BinaryOperator(Instruction::Sub,
1596 Op->getType(), Name, InsertBefore);
1599 BinaryOperator *BinaryOperator::CreateNeg(Value *Op, const std::string &Name,
1600 BasicBlock *InsertAtEnd) {
1601 Value *zero = ConstantExpr::getZeroValueForNegationExpr(Op->getType());
1602 return new BinaryOperator(Instruction::Sub,
1604 Op->getType(), Name, InsertAtEnd);
1607 BinaryOperator *BinaryOperator::CreateNot(Value *Op, const std::string &Name,
1608 Instruction *InsertBefore) {
1610 if (const VectorType *PTy = dyn_cast<VectorType>(Op->getType())) {
1611 C = ConstantInt::getAllOnesValue(PTy->getElementType());
1612 C = ConstantVector::get(std::vector<Constant*>(PTy->getNumElements(), C));
1614 C = ConstantInt::getAllOnesValue(Op->getType());
1617 return new BinaryOperator(Instruction::Xor, Op, C,
1618 Op->getType(), Name, InsertBefore);
1621 BinaryOperator *BinaryOperator::CreateNot(Value *Op, const std::string &Name,
1622 BasicBlock *InsertAtEnd) {
1624 if (const VectorType *PTy = dyn_cast<VectorType>(Op->getType())) {
1625 // Create a vector of all ones values.
1626 Constant *Elt = ConstantInt::getAllOnesValue(PTy->getElementType());
1628 ConstantVector::get(std::vector<Constant*>(PTy->getNumElements(), Elt));
1630 AllOnes = ConstantInt::getAllOnesValue(Op->getType());
1633 return new BinaryOperator(Instruction::Xor, Op, AllOnes,
1634 Op->getType(), Name, InsertAtEnd);
1638 // isConstantAllOnes - Helper function for several functions below
1639 static inline bool isConstantAllOnes(const Value *V) {
1640 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V))
1641 return CI->isAllOnesValue();
1642 if (const ConstantVector *CV = dyn_cast<ConstantVector>(V))
1643 return CV->isAllOnesValue();
1647 bool BinaryOperator::isNeg(const Value *V) {
1648 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1649 if (Bop->getOpcode() == Instruction::Sub)
1650 return Bop->getOperand(0) ==
1651 ConstantExpr::getZeroValueForNegationExpr(Bop->getType());
1655 bool BinaryOperator::isNot(const Value *V) {
1656 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1657 return (Bop->getOpcode() == Instruction::Xor &&
1658 (isConstantAllOnes(Bop->getOperand(1)) ||
1659 isConstantAllOnes(Bop->getOperand(0))));
1663 Value *BinaryOperator::getNegArgument(Value *BinOp) {
1664 assert(isNeg(BinOp) && "getNegArgument from non-'neg' instruction!");
1665 return cast<BinaryOperator>(BinOp)->getOperand(1);
1668 const Value *BinaryOperator::getNegArgument(const Value *BinOp) {
1669 return getNegArgument(const_cast<Value*>(BinOp));
1672 Value *BinaryOperator::getNotArgument(Value *BinOp) {
1673 assert(isNot(BinOp) && "getNotArgument on non-'not' instruction!");
1674 BinaryOperator *BO = cast<BinaryOperator>(BinOp);
1675 Value *Op0 = BO->getOperand(0);
1676 Value *Op1 = BO->getOperand(1);
1677 if (isConstantAllOnes(Op0)) return Op1;
1679 assert(isConstantAllOnes(Op1));
1683 const Value *BinaryOperator::getNotArgument(const Value *BinOp) {
1684 return getNotArgument(const_cast<Value*>(BinOp));
1688 // swapOperands - Exchange the two operands to this instruction. This
1689 // instruction is safe to use on any binary instruction and does not
1690 // modify the semantics of the instruction. If the instruction is
1691 // order dependent (SetLT f.e.) the opcode is changed.
1693 bool BinaryOperator::swapOperands() {
1694 if (!isCommutative())
1695 return true; // Can't commute operands
1696 Op<0>().swap(Op<1>());
1700 //===----------------------------------------------------------------------===//
1702 //===----------------------------------------------------------------------===//
1704 // Just determine if this cast only deals with integral->integral conversion.
1705 bool CastInst::isIntegerCast() const {
1706 switch (getOpcode()) {
1707 default: return false;
1708 case Instruction::ZExt:
1709 case Instruction::SExt:
1710 case Instruction::Trunc:
1712 case Instruction::BitCast:
1713 return getOperand(0)->getType()->isInteger() && getType()->isInteger();
1717 bool CastInst::isLosslessCast() const {
1718 // Only BitCast can be lossless, exit fast if we're not BitCast
1719 if (getOpcode() != Instruction::BitCast)
1722 // Identity cast is always lossless
1723 const Type* SrcTy = getOperand(0)->getType();
1724 const Type* DstTy = getType();
1728 // Pointer to pointer is always lossless.
1729 if (isa<PointerType>(SrcTy))
1730 return isa<PointerType>(DstTy);
1731 return false; // Other types have no identity values
1734 /// This function determines if the CastInst does not require any bits to be
1735 /// changed in order to effect the cast. Essentially, it identifies cases where
1736 /// no code gen is necessary for the cast, hence the name no-op cast. For
1737 /// example, the following are all no-op casts:
1738 /// # bitcast i32* %x to i8*
1739 /// # bitcast <2 x i32> %x to <4 x i16>
1740 /// # ptrtoint i32* %x to i32 ; on 32-bit plaforms only
1741 /// @brief Determine if a cast is a no-op.
1742 bool CastInst::isNoopCast(const Type *IntPtrTy) const {
1743 switch (getOpcode()) {
1745 assert(!"Invalid CastOp");
1746 case Instruction::Trunc:
1747 case Instruction::ZExt:
1748 case Instruction::SExt:
1749 case Instruction::FPTrunc:
1750 case Instruction::FPExt:
1751 case Instruction::UIToFP:
1752 case Instruction::SIToFP:
1753 case Instruction::FPToUI:
1754 case Instruction::FPToSI:
1755 return false; // These always modify bits
1756 case Instruction::BitCast:
1757 return true; // BitCast never modifies bits.
1758 case Instruction::PtrToInt:
1759 return IntPtrTy->getPrimitiveSizeInBits() ==
1760 getType()->getPrimitiveSizeInBits();
1761 case Instruction::IntToPtr:
1762 return IntPtrTy->getPrimitiveSizeInBits() ==
1763 getOperand(0)->getType()->getPrimitiveSizeInBits();
1767 /// This function determines if a pair of casts can be eliminated and what
1768 /// opcode should be used in the elimination. This assumes that there are two
1769 /// instructions like this:
1770 /// * %F = firstOpcode SrcTy %x to MidTy
1771 /// * %S = secondOpcode MidTy %F to DstTy
1772 /// The function returns a resultOpcode so these two casts can be replaced with:
1773 /// * %Replacement = resultOpcode %SrcTy %x to DstTy
1774 /// If no such cast is permited, the function returns 0.
1775 unsigned CastInst::isEliminableCastPair(
1776 Instruction::CastOps firstOp, Instruction::CastOps secondOp,
1777 const Type *SrcTy, const Type *MidTy, const Type *DstTy, const Type *IntPtrTy)
1779 // Define the 144 possibilities for these two cast instructions. The values
1780 // in this matrix determine what to do in a given situation and select the
1781 // case in the switch below. The rows correspond to firstOp, the columns
1782 // correspond to secondOp. In looking at the table below, keep in mind
1783 // the following cast properties:
1785 // Size Compare Source Destination
1786 // Operator Src ? Size Type Sign Type Sign
1787 // -------- ------------ ------------------- ---------------------
1788 // TRUNC > Integer Any Integral Any
1789 // ZEXT < Integral Unsigned Integer Any
1790 // SEXT < Integral Signed Integer Any
1791 // FPTOUI n/a FloatPt n/a Integral Unsigned
1792 // FPTOSI n/a FloatPt n/a Integral Signed
1793 // UITOFP n/a Integral Unsigned FloatPt n/a
1794 // SITOFP n/a Integral Signed FloatPt n/a
1795 // FPTRUNC > FloatPt n/a FloatPt n/a
1796 // FPEXT < FloatPt n/a FloatPt n/a
1797 // PTRTOINT n/a Pointer n/a Integral Unsigned
1798 // INTTOPTR n/a Integral Unsigned Pointer n/a
1799 // BITCONVERT = FirstClass n/a FirstClass n/a
1801 // NOTE: some transforms are safe, but we consider them to be non-profitable.
1802 // For example, we could merge "fptoui double to uint" + "zext uint to ulong",
1803 // into "fptoui double to ulong", but this loses information about the range
1804 // of the produced value (we no longer know the top-part is all zeros).
1805 // Further this conversion is often much more expensive for typical hardware,
1806 // and causes issues when building libgcc. We disallow fptosi+sext for the
1808 const unsigned numCastOps =
1809 Instruction::CastOpsEnd - Instruction::CastOpsBegin;
1810 static const uint8_t CastResults[numCastOps][numCastOps] = {
1811 // T F F U S F F P I B -+
1812 // R Z S P P I I T P 2 N T |
1813 // U E E 2 2 2 2 R E I T C +- secondOp
1814 // N X X U S F F N X N 2 V |
1815 // C T T I I P P C T T P T -+
1816 { 1, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // Trunc -+
1817 { 8, 1, 9,99,99, 2, 0,99,99,99, 2, 3 }, // ZExt |
1818 { 8, 0, 1,99,99, 0, 2,99,99,99, 0, 3 }, // SExt |
1819 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // FPToUI |
1820 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // FPToSI |
1821 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4 }, // UIToFP +- firstOp
1822 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4 }, // SIToFP |
1823 { 99,99,99, 0, 0,99,99, 1, 0,99,99, 4 }, // FPTrunc |
1824 { 99,99,99, 2, 2,99,99,10, 2,99,99, 4 }, // FPExt |
1825 { 1, 0, 0,99,99, 0, 0,99,99,99, 7, 3 }, // PtrToInt |
1826 { 99,99,99,99,99,99,99,99,99,13,99,12 }, // IntToPtr |
1827 { 5, 5, 5, 6, 6, 5, 5, 6, 6,11, 5, 1 }, // BitCast -+
1830 int ElimCase = CastResults[firstOp-Instruction::CastOpsBegin]
1831 [secondOp-Instruction::CastOpsBegin];
1834 // categorically disallowed
1837 // allowed, use first cast's opcode
1840 // allowed, use second cast's opcode
1843 // no-op cast in second op implies firstOp as long as the DestTy
1845 if (DstTy->isInteger())
1849 // no-op cast in second op implies firstOp as long as the DestTy
1850 // is floating point
1851 if (DstTy->isFloatingPoint())
1855 // no-op cast in first op implies secondOp as long as the SrcTy
1857 if (SrcTy->isInteger())
1861 // no-op cast in first op implies secondOp as long as the SrcTy
1862 // is a floating point
1863 if (SrcTy->isFloatingPoint())
1867 // ptrtoint, inttoptr -> bitcast (ptr -> ptr) if int size is >= ptr size
1868 unsigned PtrSize = IntPtrTy->getPrimitiveSizeInBits();
1869 unsigned MidSize = MidTy->getPrimitiveSizeInBits();
1870 if (MidSize >= PtrSize)
1871 return Instruction::BitCast;
1875 // ext, trunc -> bitcast, if the SrcTy and DstTy are same size
1876 // ext, trunc -> ext, if sizeof(SrcTy) < sizeof(DstTy)
1877 // ext, trunc -> trunc, if sizeof(SrcTy) > sizeof(DstTy)
1878 unsigned SrcSize = SrcTy->getPrimitiveSizeInBits();
1879 unsigned DstSize = DstTy->getPrimitiveSizeInBits();
1880 if (SrcSize == DstSize)
1881 return Instruction::BitCast;
1882 else if (SrcSize < DstSize)
1886 case 9: // zext, sext -> zext, because sext can't sign extend after zext
1887 return Instruction::ZExt;
1889 // fpext followed by ftrunc is allowed if the bit size returned to is
1890 // the same as the original, in which case its just a bitcast
1892 return Instruction::BitCast;
1893 return 0; // If the types are not the same we can't eliminate it.
1895 // bitcast followed by ptrtoint is allowed as long as the bitcast
1896 // is a pointer to pointer cast.
1897 if (isa<PointerType>(SrcTy) && isa<PointerType>(MidTy))
1901 // inttoptr, bitcast -> intptr if bitcast is a ptr to ptr cast
1902 if (isa<PointerType>(MidTy) && isa<PointerType>(DstTy))
1906 // inttoptr, ptrtoint -> bitcast if SrcSize<=PtrSize and SrcSize==DstSize
1907 unsigned PtrSize = IntPtrTy->getPrimitiveSizeInBits();
1908 unsigned SrcSize = SrcTy->getPrimitiveSizeInBits();
1909 unsigned DstSize = DstTy->getPrimitiveSizeInBits();
1910 if (SrcSize <= PtrSize && SrcSize == DstSize)
1911 return Instruction::BitCast;
1915 // cast combination can't happen (error in input). This is for all cases
1916 // where the MidTy is not the same for the two cast instructions.
1917 assert(!"Invalid Cast Combination");
1920 assert(!"Error in CastResults table!!!");
1926 CastInst *CastInst::Create(Instruction::CastOps op, Value *S, const Type *Ty,
1927 const std::string &Name, Instruction *InsertBefore) {
1928 // Construct and return the appropriate CastInst subclass
1930 case Trunc: return new TruncInst (S, Ty, Name, InsertBefore);
1931 case ZExt: return new ZExtInst (S, Ty, Name, InsertBefore);
1932 case SExt: return new SExtInst (S, Ty, Name, InsertBefore);
1933 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertBefore);
1934 case FPExt: return new FPExtInst (S, Ty, Name, InsertBefore);
1935 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertBefore);
1936 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertBefore);
1937 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertBefore);
1938 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertBefore);
1939 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertBefore);
1940 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertBefore);
1941 case BitCast: return new BitCastInst (S, Ty, Name, InsertBefore);
1943 assert(!"Invalid opcode provided");
1948 CastInst *CastInst::Create(Instruction::CastOps op, Value *S, const Type *Ty,
1949 const std::string &Name, BasicBlock *InsertAtEnd) {
1950 // Construct and return the appropriate CastInst subclass
1952 case Trunc: return new TruncInst (S, Ty, Name, InsertAtEnd);
1953 case ZExt: return new ZExtInst (S, Ty, Name, InsertAtEnd);
1954 case SExt: return new SExtInst (S, Ty, Name, InsertAtEnd);
1955 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertAtEnd);
1956 case FPExt: return new FPExtInst (S, Ty, Name, InsertAtEnd);
1957 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertAtEnd);
1958 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertAtEnd);
1959 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertAtEnd);
1960 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertAtEnd);
1961 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertAtEnd);
1962 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertAtEnd);
1963 case BitCast: return new BitCastInst (S, Ty, Name, InsertAtEnd);
1965 assert(!"Invalid opcode provided");
1970 CastInst *CastInst::CreateZExtOrBitCast(Value *S, const Type *Ty,
1971 const std::string &Name,
1972 Instruction *InsertBefore) {
1973 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1974 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
1975 return Create(Instruction::ZExt, S, Ty, Name, InsertBefore);
1978 CastInst *CastInst::CreateZExtOrBitCast(Value *S, const Type *Ty,
1979 const std::string &Name,
1980 BasicBlock *InsertAtEnd) {
1981 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1982 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
1983 return Create(Instruction::ZExt, S, Ty, Name, InsertAtEnd);
1986 CastInst *CastInst::CreateSExtOrBitCast(Value *S, const Type *Ty,
1987 const std::string &Name,
1988 Instruction *InsertBefore) {
1989 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1990 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
1991 return Create(Instruction::SExt, S, Ty, Name, InsertBefore);
1994 CastInst *CastInst::CreateSExtOrBitCast(Value *S, const Type *Ty,
1995 const std::string &Name,
1996 BasicBlock *InsertAtEnd) {
1997 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1998 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
1999 return Create(Instruction::SExt, S, Ty, Name, InsertAtEnd);
2002 CastInst *CastInst::CreateTruncOrBitCast(Value *S, const Type *Ty,
2003 const std::string &Name,
2004 Instruction *InsertBefore) {
2005 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
2006 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2007 return Create(Instruction::Trunc, S, Ty, Name, InsertBefore);
2010 CastInst *CastInst::CreateTruncOrBitCast(Value *S, const Type *Ty,
2011 const std::string &Name,
2012 BasicBlock *InsertAtEnd) {
2013 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
2014 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2015 return Create(Instruction::Trunc, S, Ty, Name, InsertAtEnd);
2018 CastInst *CastInst::CreatePointerCast(Value *S, const Type *Ty,
2019 const std::string &Name,
2020 BasicBlock *InsertAtEnd) {
2021 assert(isa<PointerType>(S->getType()) && "Invalid cast");
2022 assert((Ty->isInteger() || isa<PointerType>(Ty)) &&
2025 if (Ty->isInteger())
2026 return Create(Instruction::PtrToInt, S, Ty, Name, InsertAtEnd);
2027 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2030 /// @brief Create a BitCast or a PtrToInt cast instruction
2031 CastInst *CastInst::CreatePointerCast(Value *S, const Type *Ty,
2032 const std::string &Name,
2033 Instruction *InsertBefore) {
2034 assert(isa<PointerType>(S->getType()) && "Invalid cast");
2035 assert((Ty->isInteger() || isa<PointerType>(Ty)) &&
2038 if (Ty->isInteger())
2039 return Create(Instruction::PtrToInt, S, Ty, Name, InsertBefore);
2040 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2043 CastInst *CastInst::CreateIntegerCast(Value *C, const Type *Ty,
2044 bool isSigned, const std::string &Name,
2045 Instruction *InsertBefore) {
2046 assert(C->getType()->isInteger() && Ty->isInteger() && "Invalid cast");
2047 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
2048 unsigned DstBits = Ty->getPrimitiveSizeInBits();
2049 Instruction::CastOps opcode =
2050 (SrcBits == DstBits ? Instruction::BitCast :
2051 (SrcBits > DstBits ? Instruction::Trunc :
2052 (isSigned ? Instruction::SExt : Instruction::ZExt)));
2053 return Create(opcode, C, Ty, Name, InsertBefore);
2056 CastInst *CastInst::CreateIntegerCast(Value *C, const Type *Ty,
2057 bool isSigned, const std::string &Name,
2058 BasicBlock *InsertAtEnd) {
2059 assert(C->getType()->isInteger() && Ty->isInteger() && "Invalid cast");
2060 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
2061 unsigned DstBits = Ty->getPrimitiveSizeInBits();
2062 Instruction::CastOps opcode =
2063 (SrcBits == DstBits ? Instruction::BitCast :
2064 (SrcBits > DstBits ? Instruction::Trunc :
2065 (isSigned ? Instruction::SExt : Instruction::ZExt)));
2066 return Create(opcode, C, Ty, Name, InsertAtEnd);
2069 CastInst *CastInst::CreateFPCast(Value *C, const Type *Ty,
2070 const std::string &Name,
2071 Instruction *InsertBefore) {
2072 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
2074 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
2075 unsigned DstBits = Ty->getPrimitiveSizeInBits();
2076 Instruction::CastOps opcode =
2077 (SrcBits == DstBits ? Instruction::BitCast :
2078 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
2079 return Create(opcode, C, Ty, Name, InsertBefore);
2082 CastInst *CastInst::CreateFPCast(Value *C, const Type *Ty,
2083 const std::string &Name,
2084 BasicBlock *InsertAtEnd) {
2085 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
2087 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
2088 unsigned DstBits = Ty->getPrimitiveSizeInBits();
2089 Instruction::CastOps opcode =
2090 (SrcBits == DstBits ? Instruction::BitCast :
2091 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
2092 return Create(opcode, C, Ty, Name, InsertAtEnd);
2095 // Check whether it is valid to call getCastOpcode for these types.
2096 // This routine must be kept in sync with getCastOpcode.
2097 bool CastInst::isCastable(const Type *SrcTy, const Type *DestTy) {
2098 if (!SrcTy->isFirstClassType() || !DestTy->isFirstClassType())
2101 if (SrcTy == DestTy)
2104 // Get the bit sizes, we'll need these
2105 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); // 0 for ptr/vector
2106 unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr/vector
2108 // Run through the possibilities ...
2109 if (DestTy->isInteger()) { // Casting to integral
2110 if (SrcTy->isInteger()) { // Casting from integral
2112 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt
2114 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
2115 // Casting from vector
2116 return DestBits == PTy->getBitWidth();
2117 } else { // Casting from something else
2118 return isa<PointerType>(SrcTy);
2120 } else if (DestTy->isFloatingPoint()) { // Casting to floating pt
2121 if (SrcTy->isInteger()) { // Casting from integral
2123 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt
2125 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
2126 // Casting from vector
2127 return DestBits == PTy->getBitWidth();
2128 } else { // Casting from something else
2131 } else if (const VectorType *DestPTy = dyn_cast<VectorType>(DestTy)) {
2132 // Casting to vector
2133 if (const VectorType *SrcPTy = dyn_cast<VectorType>(SrcTy)) {
2134 // Casting from vector
2135 return DestPTy->getBitWidth() == SrcPTy->getBitWidth();
2136 } else { // Casting from something else
2137 return DestPTy->getBitWidth() == SrcBits;
2139 } else if (isa<PointerType>(DestTy)) { // Casting to pointer
2140 if (isa<PointerType>(SrcTy)) { // Casting from pointer
2142 } else if (SrcTy->isInteger()) { // Casting from integral
2144 } else { // Casting from something else
2147 } else { // Casting to something else
2152 // Provide a way to get a "cast" where the cast opcode is inferred from the
2153 // types and size of the operand. This, basically, is a parallel of the
2154 // logic in the castIsValid function below. This axiom should hold:
2155 // castIsValid( getCastOpcode(Val, Ty), Val, Ty)
2156 // should not assert in castIsValid. In other words, this produces a "correct"
2157 // casting opcode for the arguments passed to it.
2158 // This routine must be kept in sync with isCastable.
2159 Instruction::CastOps
2160 CastInst::getCastOpcode(
2161 const Value *Src, bool SrcIsSigned, const Type *DestTy, bool DestIsSigned) {
2162 // Get the bit sizes, we'll need these
2163 const Type *SrcTy = Src->getType();
2164 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); // 0 for ptr/vector
2165 unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr/vector
2167 assert(SrcTy->isFirstClassType() && DestTy->isFirstClassType() &&
2168 "Only first class types are castable!");
2170 // Run through the possibilities ...
2171 if (DestTy->isInteger()) { // Casting to integral
2172 if (SrcTy->isInteger()) { // Casting from integral
2173 if (DestBits < SrcBits)
2174 return Trunc; // int -> smaller int
2175 else if (DestBits > SrcBits) { // its an extension
2177 return SExt; // signed -> SEXT
2179 return ZExt; // unsigned -> ZEXT
2181 return BitCast; // Same size, No-op cast
2183 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt
2185 return FPToSI; // FP -> sint
2187 return FPToUI; // FP -> uint
2188 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
2189 assert(DestBits == PTy->getBitWidth() &&
2190 "Casting vector to integer of different width");
2192 return BitCast; // Same size, no-op cast
2194 assert(isa<PointerType>(SrcTy) &&
2195 "Casting from a value that is not first-class type");
2196 return PtrToInt; // ptr -> int
2198 } else if (DestTy->isFloatingPoint()) { // Casting to floating pt
2199 if (SrcTy->isInteger()) { // Casting from integral
2201 return SIToFP; // sint -> FP
2203 return UIToFP; // uint -> FP
2204 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt
2205 if (DestBits < SrcBits) {
2206 return FPTrunc; // FP -> smaller FP
2207 } else if (DestBits > SrcBits) {
2208 return FPExt; // FP -> larger FP
2210 return BitCast; // same size, no-op cast
2212 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
2213 assert(DestBits == PTy->getBitWidth() &&
2214 "Casting vector to floating point of different width");
2216 return BitCast; // same size, no-op cast
2218 assert(0 && "Casting pointer or non-first class to float");
2220 } else if (const VectorType *DestPTy = dyn_cast<VectorType>(DestTy)) {
2221 if (const VectorType *SrcPTy = dyn_cast<VectorType>(SrcTy)) {
2222 assert(DestPTy->getBitWidth() == SrcPTy->getBitWidth() &&
2223 "Casting vector to vector of different widths");
2225 return BitCast; // vector -> vector
2226 } else if (DestPTy->getBitWidth() == SrcBits) {
2227 return BitCast; // float/int -> vector
2229 assert(!"Illegal cast to vector (wrong type or size)");
2231 } else if (isa<PointerType>(DestTy)) {
2232 if (isa<PointerType>(SrcTy)) {
2233 return BitCast; // ptr -> ptr
2234 } else if (SrcTy->isInteger()) {
2235 return IntToPtr; // int -> ptr
2237 assert(!"Casting pointer to other than pointer or int");
2240 assert(!"Casting to type that is not first-class");
2243 // If we fall through to here we probably hit an assertion cast above
2244 // and assertions are not turned on. Anything we return is an error, so
2245 // BitCast is as good a choice as any.
2249 //===----------------------------------------------------------------------===//
2250 // CastInst SubClass Constructors
2251 //===----------------------------------------------------------------------===//
2253 /// Check that the construction parameters for a CastInst are correct. This
2254 /// could be broken out into the separate constructors but it is useful to have
2255 /// it in one place and to eliminate the redundant code for getting the sizes
2256 /// of the types involved.
2258 CastInst::castIsValid(Instruction::CastOps op, Value *S, const Type *DstTy) {
2260 // Check for type sanity on the arguments
2261 const Type *SrcTy = S->getType();
2262 if (!SrcTy->isFirstClassType() || !DstTy->isFirstClassType())
2265 // Get the size of the types in bits, we'll need this later
2266 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
2267 unsigned DstBitSize = DstTy->getPrimitiveSizeInBits();
2269 // Switch on the opcode provided
2271 default: return false; // This is an input error
2272 case Instruction::Trunc:
2273 return SrcTy->isIntOrIntVector() &&
2274 DstTy->isIntOrIntVector()&& SrcBitSize > DstBitSize;
2275 case Instruction::ZExt:
2276 return SrcTy->isIntOrIntVector() &&
2277 DstTy->isIntOrIntVector()&& SrcBitSize < DstBitSize;
2278 case Instruction::SExt:
2279 return SrcTy->isIntOrIntVector() &&
2280 DstTy->isIntOrIntVector()&& SrcBitSize < DstBitSize;
2281 case Instruction::FPTrunc:
2282 return SrcTy->isFPOrFPVector() &&
2283 DstTy->isFPOrFPVector() &&
2284 SrcBitSize > DstBitSize;
2285 case Instruction::FPExt:
2286 return SrcTy->isFPOrFPVector() &&
2287 DstTy->isFPOrFPVector() &&
2288 SrcBitSize < DstBitSize;
2289 case Instruction::UIToFP:
2290 case Instruction::SIToFP:
2291 if (const VectorType *SVTy = dyn_cast<VectorType>(SrcTy)) {
2292 if (const VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
2293 return SVTy->getElementType()->isIntOrIntVector() &&
2294 DVTy->getElementType()->isFPOrFPVector() &&
2295 SVTy->getNumElements() == DVTy->getNumElements();
2298 return SrcTy->isIntOrIntVector() && DstTy->isFPOrFPVector();
2299 case Instruction::FPToUI:
2300 case Instruction::FPToSI:
2301 if (const VectorType *SVTy = dyn_cast<VectorType>(SrcTy)) {
2302 if (const VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
2303 return SVTy->getElementType()->isFPOrFPVector() &&
2304 DVTy->getElementType()->isIntOrIntVector() &&
2305 SVTy->getNumElements() == DVTy->getNumElements();
2308 return SrcTy->isFPOrFPVector() && DstTy->isIntOrIntVector();
2309 case Instruction::PtrToInt:
2310 return isa<PointerType>(SrcTy) && DstTy->isInteger();
2311 case Instruction::IntToPtr:
2312 return SrcTy->isInteger() && isa<PointerType>(DstTy);
2313 case Instruction::BitCast:
2314 // BitCast implies a no-op cast of type only. No bits change.
2315 // However, you can't cast pointers to anything but pointers.
2316 if (isa<PointerType>(SrcTy) != isa<PointerType>(DstTy))
2319 // Now we know we're not dealing with a pointer/non-pointer mismatch. In all
2320 // these cases, the cast is okay if the source and destination bit widths
2322 return SrcBitSize == DstBitSize;
2326 TruncInst::TruncInst(
2327 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2328 ) : CastInst(Ty, Trunc, S, Name, InsertBefore) {
2329 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
2332 TruncInst::TruncInst(
2333 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2334 ) : CastInst(Ty, Trunc, S, Name, InsertAtEnd) {
2335 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
2339 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2340 ) : CastInst(Ty, ZExt, S, Name, InsertBefore) {
2341 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
2345 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2346 ) : CastInst(Ty, ZExt, S, Name, InsertAtEnd) {
2347 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
2350 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2351 ) : CastInst(Ty, SExt, S, Name, InsertBefore) {
2352 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
2356 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2357 ) : CastInst(Ty, SExt, S, Name, InsertAtEnd) {
2358 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
2361 FPTruncInst::FPTruncInst(
2362 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2363 ) : CastInst(Ty, FPTrunc, S, Name, InsertBefore) {
2364 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
2367 FPTruncInst::FPTruncInst(
2368 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2369 ) : CastInst(Ty, FPTrunc, S, Name, InsertAtEnd) {
2370 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
2373 FPExtInst::FPExtInst(
2374 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2375 ) : CastInst(Ty, FPExt, S, Name, InsertBefore) {
2376 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
2379 FPExtInst::FPExtInst(
2380 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2381 ) : CastInst(Ty, FPExt, S, Name, InsertAtEnd) {
2382 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
2385 UIToFPInst::UIToFPInst(
2386 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2387 ) : CastInst(Ty, UIToFP, S, Name, InsertBefore) {
2388 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
2391 UIToFPInst::UIToFPInst(
2392 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2393 ) : CastInst(Ty, UIToFP, S, Name, InsertAtEnd) {
2394 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
2397 SIToFPInst::SIToFPInst(
2398 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2399 ) : CastInst(Ty, SIToFP, S, Name, InsertBefore) {
2400 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
2403 SIToFPInst::SIToFPInst(
2404 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2405 ) : CastInst(Ty, SIToFP, S, Name, InsertAtEnd) {
2406 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
2409 FPToUIInst::FPToUIInst(
2410 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2411 ) : CastInst(Ty, FPToUI, S, Name, InsertBefore) {
2412 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
2415 FPToUIInst::FPToUIInst(
2416 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2417 ) : CastInst(Ty, FPToUI, S, Name, InsertAtEnd) {
2418 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
2421 FPToSIInst::FPToSIInst(
2422 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2423 ) : CastInst(Ty, FPToSI, S, Name, InsertBefore) {
2424 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
2427 FPToSIInst::FPToSIInst(
2428 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2429 ) : CastInst(Ty, FPToSI, S, Name, InsertAtEnd) {
2430 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
2433 PtrToIntInst::PtrToIntInst(
2434 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2435 ) : CastInst(Ty, PtrToInt, S, Name, InsertBefore) {
2436 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
2439 PtrToIntInst::PtrToIntInst(
2440 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2441 ) : CastInst(Ty, PtrToInt, S, Name, InsertAtEnd) {
2442 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
2445 IntToPtrInst::IntToPtrInst(
2446 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2447 ) : CastInst(Ty, IntToPtr, S, Name, InsertBefore) {
2448 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
2451 IntToPtrInst::IntToPtrInst(
2452 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2453 ) : CastInst(Ty, IntToPtr, S, Name, InsertAtEnd) {
2454 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
2457 BitCastInst::BitCastInst(
2458 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2459 ) : CastInst(Ty, BitCast, S, Name, InsertBefore) {
2460 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
2463 BitCastInst::BitCastInst(
2464 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2465 ) : CastInst(Ty, BitCast, S, Name, InsertAtEnd) {
2466 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
2469 //===----------------------------------------------------------------------===//
2471 //===----------------------------------------------------------------------===//
2473 CmpInst::CmpInst(const Type *ty, OtherOps op, unsigned short predicate,
2474 Value *LHS, Value *RHS, const std::string &Name,
2475 Instruction *InsertBefore)
2476 : Instruction(ty, op,
2477 OperandTraits<CmpInst>::op_begin(this),
2478 OperandTraits<CmpInst>::operands(this),
2482 SubclassData = predicate;
2486 CmpInst::CmpInst(const Type *ty, OtherOps op, unsigned short predicate,
2487 Value *LHS, Value *RHS, const std::string &Name,
2488 BasicBlock *InsertAtEnd)
2489 : Instruction(ty, op,
2490 OperandTraits<CmpInst>::op_begin(this),
2491 OperandTraits<CmpInst>::operands(this),
2495 SubclassData = predicate;
2500 CmpInst::Create(OtherOps Op, unsigned short predicate, Value *S1, Value *S2,
2501 const std::string &Name, Instruction *InsertBefore) {
2502 if (Op == Instruction::ICmp) {
2503 return new ICmpInst(CmpInst::Predicate(predicate), S1, S2, Name,
2506 if (Op == Instruction::FCmp) {
2507 return new FCmpInst(CmpInst::Predicate(predicate), S1, S2, Name,
2510 if (Op == Instruction::VICmp) {
2511 return new VICmpInst(CmpInst::Predicate(predicate), S1, S2, Name,
2514 return new VFCmpInst(CmpInst::Predicate(predicate), S1, S2, Name,
2519 CmpInst::Create(OtherOps Op, unsigned short predicate, Value *S1, Value *S2,
2520 const std::string &Name, BasicBlock *InsertAtEnd) {
2521 if (Op == Instruction::ICmp) {
2522 return new ICmpInst(CmpInst::Predicate(predicate), S1, S2, Name,
2525 if (Op == Instruction::FCmp) {
2526 return new FCmpInst(CmpInst::Predicate(predicate), S1, S2, Name,
2529 if (Op == Instruction::VICmp) {
2530 return new VICmpInst(CmpInst::Predicate(predicate), S1, S2, Name,
2533 return new VFCmpInst(CmpInst::Predicate(predicate), S1, S2, Name,
2537 void CmpInst::swapOperands() {
2538 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2541 cast<FCmpInst>(this)->swapOperands();
2544 bool CmpInst::isCommutative() {
2545 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2546 return IC->isCommutative();
2547 return cast<FCmpInst>(this)->isCommutative();
2550 bool CmpInst::isEquality() {
2551 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2552 return IC->isEquality();
2553 return cast<FCmpInst>(this)->isEquality();
2557 CmpInst::Predicate CmpInst::getInversePredicate(Predicate pred) {
2559 default: assert(!"Unknown cmp predicate!");
2560 case ICMP_EQ: return ICMP_NE;
2561 case ICMP_NE: return ICMP_EQ;
2562 case ICMP_UGT: return ICMP_ULE;
2563 case ICMP_ULT: return ICMP_UGE;
2564 case ICMP_UGE: return ICMP_ULT;
2565 case ICMP_ULE: return ICMP_UGT;
2566 case ICMP_SGT: return ICMP_SLE;
2567 case ICMP_SLT: return ICMP_SGE;
2568 case ICMP_SGE: return ICMP_SLT;
2569 case ICMP_SLE: return ICMP_SGT;
2571 case FCMP_OEQ: return FCMP_UNE;
2572 case FCMP_ONE: return FCMP_UEQ;
2573 case FCMP_OGT: return FCMP_ULE;
2574 case FCMP_OLT: return FCMP_UGE;
2575 case FCMP_OGE: return FCMP_ULT;
2576 case FCMP_OLE: return FCMP_UGT;
2577 case FCMP_UEQ: return FCMP_ONE;
2578 case FCMP_UNE: return FCMP_OEQ;
2579 case FCMP_UGT: return FCMP_OLE;
2580 case FCMP_ULT: return FCMP_OGE;
2581 case FCMP_UGE: return FCMP_OLT;
2582 case FCMP_ULE: return FCMP_OGT;
2583 case FCMP_ORD: return FCMP_UNO;
2584 case FCMP_UNO: return FCMP_ORD;
2585 case FCMP_TRUE: return FCMP_FALSE;
2586 case FCMP_FALSE: return FCMP_TRUE;
2590 ICmpInst::Predicate ICmpInst::getSignedPredicate(Predicate pred) {
2592 default: assert(! "Unknown icmp predicate!");
2593 case ICMP_EQ: case ICMP_NE:
2594 case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE:
2596 case ICMP_UGT: return ICMP_SGT;
2597 case ICMP_ULT: return ICMP_SLT;
2598 case ICMP_UGE: return ICMP_SGE;
2599 case ICMP_ULE: return ICMP_SLE;
2603 ICmpInst::Predicate ICmpInst::getUnsignedPredicate(Predicate pred) {
2605 default: assert(! "Unknown icmp predicate!");
2606 case ICMP_EQ: case ICMP_NE:
2607 case ICMP_UGT: case ICMP_ULT: case ICMP_UGE: case ICMP_ULE:
2609 case ICMP_SGT: return ICMP_UGT;
2610 case ICMP_SLT: return ICMP_ULT;
2611 case ICMP_SGE: return ICMP_UGE;
2612 case ICMP_SLE: return ICMP_ULE;
2616 bool ICmpInst::isSignedPredicate(Predicate pred) {
2618 default: assert(! "Unknown icmp predicate!");
2619 case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE:
2621 case ICMP_EQ: case ICMP_NE: case ICMP_UGT: case ICMP_ULT:
2622 case ICMP_UGE: case ICMP_ULE:
2627 /// Initialize a set of values that all satisfy the condition with C.
2630 ICmpInst::makeConstantRange(Predicate pred, const APInt &C) {
2633 uint32_t BitWidth = C.getBitWidth();
2635 default: assert(0 && "Invalid ICmp opcode to ConstantRange ctor!");
2636 case ICmpInst::ICMP_EQ: Upper++; break;
2637 case ICmpInst::ICMP_NE: Lower++; break;
2638 case ICmpInst::ICMP_ULT: Lower = APInt::getMinValue(BitWidth); break;
2639 case ICmpInst::ICMP_SLT: Lower = APInt::getSignedMinValue(BitWidth); break;
2640 case ICmpInst::ICMP_UGT:
2641 Lower++; Upper = APInt::getMinValue(BitWidth); // Min = Next(Max)
2643 case ICmpInst::ICMP_SGT:
2644 Lower++; Upper = APInt::getSignedMinValue(BitWidth); // Min = Next(Max)
2646 case ICmpInst::ICMP_ULE:
2647 Lower = APInt::getMinValue(BitWidth); Upper++;
2649 case ICmpInst::ICMP_SLE:
2650 Lower = APInt::getSignedMinValue(BitWidth); Upper++;
2652 case ICmpInst::ICMP_UGE:
2653 Upper = APInt::getMinValue(BitWidth); // Min = Next(Max)
2655 case ICmpInst::ICMP_SGE:
2656 Upper = APInt::getSignedMinValue(BitWidth); // Min = Next(Max)
2659 return ConstantRange(Lower, Upper);
2662 CmpInst::Predicate CmpInst::getSwappedPredicate(Predicate pred) {
2664 default: assert(!"Unknown cmp predicate!");
2665 case ICMP_EQ: case ICMP_NE:
2667 case ICMP_SGT: return ICMP_SLT;
2668 case ICMP_SLT: return ICMP_SGT;
2669 case ICMP_SGE: return ICMP_SLE;
2670 case ICMP_SLE: return ICMP_SGE;
2671 case ICMP_UGT: return ICMP_ULT;
2672 case ICMP_ULT: return ICMP_UGT;
2673 case ICMP_UGE: return ICMP_ULE;
2674 case ICMP_ULE: return ICMP_UGE;
2676 case FCMP_FALSE: case FCMP_TRUE:
2677 case FCMP_OEQ: case FCMP_ONE:
2678 case FCMP_UEQ: case FCMP_UNE:
2679 case FCMP_ORD: case FCMP_UNO:
2681 case FCMP_OGT: return FCMP_OLT;
2682 case FCMP_OLT: return FCMP_OGT;
2683 case FCMP_OGE: return FCMP_OLE;
2684 case FCMP_OLE: return FCMP_OGE;
2685 case FCMP_UGT: return FCMP_ULT;
2686 case FCMP_ULT: return FCMP_UGT;
2687 case FCMP_UGE: return FCMP_ULE;
2688 case FCMP_ULE: return FCMP_UGE;
2692 bool CmpInst::isUnsigned(unsigned short predicate) {
2693 switch (predicate) {
2694 default: return false;
2695 case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_ULE: case ICmpInst::ICMP_UGT:
2696 case ICmpInst::ICMP_UGE: return true;
2700 bool CmpInst::isSigned(unsigned short predicate){
2701 switch (predicate) {
2702 default: return false;
2703 case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_SLE: case ICmpInst::ICMP_SGT:
2704 case ICmpInst::ICMP_SGE: return true;
2708 bool CmpInst::isOrdered(unsigned short predicate) {
2709 switch (predicate) {
2710 default: return false;
2711 case FCmpInst::FCMP_OEQ: case FCmpInst::FCMP_ONE: case FCmpInst::FCMP_OGT:
2712 case FCmpInst::FCMP_OLT: case FCmpInst::FCMP_OGE: case FCmpInst::FCMP_OLE:
2713 case FCmpInst::FCMP_ORD: return true;
2717 bool CmpInst::isUnordered(unsigned short predicate) {
2718 switch (predicate) {
2719 default: return false;
2720 case FCmpInst::FCMP_UEQ: case FCmpInst::FCMP_UNE: case FCmpInst::FCMP_UGT:
2721 case FCmpInst::FCMP_ULT: case FCmpInst::FCMP_UGE: case FCmpInst::FCMP_ULE:
2722 case FCmpInst::FCMP_UNO: return true;
2726 //===----------------------------------------------------------------------===//
2727 // SwitchInst Implementation
2728 //===----------------------------------------------------------------------===//
2730 void SwitchInst::init(Value *Value, BasicBlock *Default, unsigned NumCases) {
2731 assert(Value && Default);
2732 ReservedSpace = 2+NumCases*2;
2734 OperandList = allocHungoffUses(ReservedSpace);
2736 OperandList[0] = Value;
2737 OperandList[1] = Default;
2740 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
2741 /// switch on and a default destination. The number of additional cases can
2742 /// be specified here to make memory allocation more efficient. This
2743 /// constructor can also autoinsert before another instruction.
2744 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
2745 Instruction *InsertBefore)
2746 : TerminatorInst(Type::VoidTy, Instruction::Switch, 0, 0, InsertBefore) {
2747 init(Value, Default, NumCases);
2750 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
2751 /// switch on and a default destination. The number of additional cases can
2752 /// be specified here to make memory allocation more efficient. This
2753 /// constructor also autoinserts at the end of the specified BasicBlock.
2754 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
2755 BasicBlock *InsertAtEnd)
2756 : TerminatorInst(Type::VoidTy, Instruction::Switch, 0, 0, InsertAtEnd) {
2757 init(Value, Default, NumCases);
2760 SwitchInst::SwitchInst(const SwitchInst &SI)
2761 : TerminatorInst(Type::VoidTy, Instruction::Switch,
2762 allocHungoffUses(SI.getNumOperands()), SI.getNumOperands()) {
2763 Use *OL = OperandList, *InOL = SI.OperandList;
2764 for (unsigned i = 0, E = SI.getNumOperands(); i != E; i+=2) {
2766 OL[i+1] = InOL[i+1];
2770 SwitchInst::~SwitchInst() {
2771 dropHungoffUses(OperandList);
2775 /// addCase - Add an entry to the switch instruction...
2777 void SwitchInst::addCase(ConstantInt *OnVal, BasicBlock *Dest) {
2778 unsigned OpNo = NumOperands;
2779 if (OpNo+2 > ReservedSpace)
2780 resizeOperands(0); // Get more space!
2781 // Initialize some new operands.
2782 assert(OpNo+1 < ReservedSpace && "Growing didn't work!");
2783 NumOperands = OpNo+2;
2784 OperandList[OpNo] = OnVal;
2785 OperandList[OpNo+1] = Dest;
2788 /// removeCase - This method removes the specified successor from the switch
2789 /// instruction. Note that this cannot be used to remove the default
2790 /// destination (successor #0).
2792 void SwitchInst::removeCase(unsigned idx) {
2793 assert(idx != 0 && "Cannot remove the default case!");
2794 assert(idx*2 < getNumOperands() && "Successor index out of range!!!");
2796 unsigned NumOps = getNumOperands();
2797 Use *OL = OperandList;
2799 // Move everything after this operand down.
2801 // FIXME: we could just swap with the end of the list, then erase. However,
2802 // client might not expect this to happen. The code as it is thrashes the
2803 // use/def lists, which is kinda lame.
2804 for (unsigned i = (idx+1)*2; i != NumOps; i += 2) {
2806 OL[i-2+1] = OL[i+1];
2809 // Nuke the last value.
2810 OL[NumOps-2].set(0);
2811 OL[NumOps-2+1].set(0);
2812 NumOperands = NumOps-2;
2815 /// resizeOperands - resize operands - This adjusts the length of the operands
2816 /// list according to the following behavior:
2817 /// 1. If NumOps == 0, grow the operand list in response to a push_back style
2818 /// of operation. This grows the number of ops by 3 times.
2819 /// 2. If NumOps > NumOperands, reserve space for NumOps operands.
2820 /// 3. If NumOps == NumOperands, trim the reserved space.
2822 void SwitchInst::resizeOperands(unsigned NumOps) {
2823 unsigned e = getNumOperands();
2826 } else if (NumOps*2 > NumOperands) {
2827 // No resize needed.
2828 if (ReservedSpace >= NumOps) return;
2829 } else if (NumOps == NumOperands) {
2830 if (ReservedSpace == NumOps) return;
2835 ReservedSpace = NumOps;
2836 Use *NewOps = allocHungoffUses(NumOps);
2837 Use *OldOps = OperandList;
2838 for (unsigned i = 0; i != e; ++i) {
2839 NewOps[i] = OldOps[i];
2841 OperandList = NewOps;
2842 if (OldOps) Use::zap(OldOps, OldOps + e, true);
2846 BasicBlock *SwitchInst::getSuccessorV(unsigned idx) const {
2847 return getSuccessor(idx);
2849 unsigned SwitchInst::getNumSuccessorsV() const {
2850 return getNumSuccessors();
2852 void SwitchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
2853 setSuccessor(idx, B);
2856 // Define these methods here so vtables don't get emitted into every translation
2857 // unit that uses these classes.
2859 GetElementPtrInst *GetElementPtrInst::clone() const {
2860 return new(getNumOperands()) GetElementPtrInst(*this);
2863 BinaryOperator *BinaryOperator::clone() const {
2864 return Create(getOpcode(), Op<0>(), Op<1>());
2867 FCmpInst* FCmpInst::clone() const {
2868 return new FCmpInst(getPredicate(), Op<0>(), Op<1>());
2870 ICmpInst* ICmpInst::clone() const {
2871 return new ICmpInst(getPredicate(), Op<0>(), Op<1>());
2874 VFCmpInst* VFCmpInst::clone() const {
2875 return new VFCmpInst(getPredicate(), Op<0>(), Op<1>());
2877 VICmpInst* VICmpInst::clone() const {
2878 return new VICmpInst(getPredicate(), Op<0>(), Op<1>());
2881 ExtractValueInst *ExtractValueInst::clone() const {
2882 return new ExtractValueInst(*this);
2884 InsertValueInst *InsertValueInst::clone() const {
2885 return new InsertValueInst(*this);
2889 MallocInst *MallocInst::clone() const { return new MallocInst(*this); }
2890 AllocaInst *AllocaInst::clone() const { return new AllocaInst(*this); }
2891 FreeInst *FreeInst::clone() const { return new FreeInst(getOperand(0)); }
2892 LoadInst *LoadInst::clone() const { return new LoadInst(*this); }
2893 StoreInst *StoreInst::clone() const { return new StoreInst(*this); }
2894 CastInst *TruncInst::clone() const { return new TruncInst(*this); }
2895 CastInst *ZExtInst::clone() const { return new ZExtInst(*this); }
2896 CastInst *SExtInst::clone() const { return new SExtInst(*this); }
2897 CastInst *FPTruncInst::clone() const { return new FPTruncInst(*this); }
2898 CastInst *FPExtInst::clone() const { return new FPExtInst(*this); }
2899 CastInst *UIToFPInst::clone() const { return new UIToFPInst(*this); }
2900 CastInst *SIToFPInst::clone() const { return new SIToFPInst(*this); }
2901 CastInst *FPToUIInst::clone() const { return new FPToUIInst(*this); }
2902 CastInst *FPToSIInst::clone() const { return new FPToSIInst(*this); }
2903 CastInst *PtrToIntInst::clone() const { return new PtrToIntInst(*this); }
2904 CastInst *IntToPtrInst::clone() const { return new IntToPtrInst(*this); }
2905 CastInst *BitCastInst::clone() const { return new BitCastInst(*this); }
2906 CallInst *CallInst::clone() const {
2907 return new(getNumOperands()) CallInst(*this);
2909 SelectInst *SelectInst::clone() const {
2910 return new(getNumOperands()) SelectInst(*this);
2912 VAArgInst *VAArgInst::clone() const { return new VAArgInst(*this); }
2914 ExtractElementInst *ExtractElementInst::clone() const {
2915 return new ExtractElementInst(*this);
2917 InsertElementInst *InsertElementInst::clone() const {
2918 return InsertElementInst::Create(*this);
2920 ShuffleVectorInst *ShuffleVectorInst::clone() const {
2921 return new ShuffleVectorInst(*this);
2923 PHINode *PHINode::clone() const { return new PHINode(*this); }
2924 ReturnInst *ReturnInst::clone() const {
2925 return new(getNumOperands()) ReturnInst(*this);
2927 BranchInst *BranchInst::clone() const {
2928 return new(getNumOperands()) BranchInst(*this);
2930 SwitchInst *SwitchInst::clone() const { return new SwitchInst(*this); }
2931 InvokeInst *InvokeInst::clone() const {
2932 return new(getNumOperands()) InvokeInst(*this);
2934 UnwindInst *UnwindInst::clone() const { return new UnwindInst(); }
2935 UnreachableInst *UnreachableInst::clone() const { return new UnreachableInst();}