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 loaded with
1041 // a load 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,
1051 IndexTy const *Idxs,
1053 const PointerType *PTy = dyn_cast<PointerType>(Ptr);
1054 if (!PTy) return 0; // Type isn't a pointer type!
1055 const Type *Agg = PTy->getElementType();
1057 // Handle the special case of the empty set index set...
1061 unsigned CurIdx = 1;
1062 for (; CurIdx != NumIdx; ++CurIdx) {
1063 const CompositeType *CT = dyn_cast<CompositeType>(Agg);
1064 if (!CT || isa<PointerType>(CT)) return 0;
1065 IndexTy Index = Idxs[CurIdx];
1066 if (!CT->indexValid(Index)) return 0;
1067 Agg = CT->getTypeAtIndex(Index);
1069 // If the new type forwards to another type, then it is in the middle
1070 // of being refined to another type (and hence, may have dropped all
1071 // references to what it was using before). So, use the new forwarded
1073 if (const Type *Ty = Agg->getForwardedType())
1076 return CurIdx == NumIdx ? Agg : 0;
1079 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr,
1082 return getIndexedTypeInternal(Ptr, Idxs, NumIdx);
1085 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr,
1086 uint64_t const *Idxs,
1088 return getIndexedTypeInternal(Ptr, Idxs, NumIdx);
1091 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr, Value *Idx) {
1092 const PointerType *PTy = dyn_cast<PointerType>(Ptr);
1093 if (!PTy) return 0; // Type isn't a pointer type!
1095 // Check the pointer index.
1096 if (!PTy->indexValid(Idx)) return 0;
1098 return PTy->getElementType();
1102 /// hasAllZeroIndices - Return true if all of the indices of this GEP are
1103 /// zeros. If so, the result pointer and the first operand have the same
1104 /// value, just potentially different types.
1105 bool GetElementPtrInst::hasAllZeroIndices() const {
1106 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1107 if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(i))) {
1108 if (!CI->isZero()) return false;
1116 /// hasAllConstantIndices - Return true if all of the indices of this GEP are
1117 /// constant integers. If so, the result pointer and the first operand have
1118 /// a constant offset between them.
1119 bool GetElementPtrInst::hasAllConstantIndices() const {
1120 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1121 if (!isa<ConstantInt>(getOperand(i)))
1128 //===----------------------------------------------------------------------===//
1129 // ExtractElementInst Implementation
1130 //===----------------------------------------------------------------------===//
1132 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
1133 const std::string &Name,
1134 Instruction *InsertBef)
1135 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1137 OperandTraits<ExtractElementInst>::op_begin(this),
1139 assert(isValidOperands(Val, Index) &&
1140 "Invalid extractelement instruction operands!");
1146 ExtractElementInst::ExtractElementInst(Value *Val, unsigned IndexV,
1147 const std::string &Name,
1148 Instruction *InsertBef)
1149 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1151 OperandTraits<ExtractElementInst>::op_begin(this),
1153 Constant *Index = ConstantInt::get(Type::Int32Ty, IndexV);
1154 assert(isValidOperands(Val, Index) &&
1155 "Invalid extractelement instruction operands!");
1162 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
1163 const std::string &Name,
1164 BasicBlock *InsertAE)
1165 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1167 OperandTraits<ExtractElementInst>::op_begin(this),
1169 assert(isValidOperands(Val, Index) &&
1170 "Invalid extractelement instruction operands!");
1177 ExtractElementInst::ExtractElementInst(Value *Val, unsigned IndexV,
1178 const std::string &Name,
1179 BasicBlock *InsertAE)
1180 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1182 OperandTraits<ExtractElementInst>::op_begin(this),
1184 Constant *Index = ConstantInt::get(Type::Int32Ty, IndexV);
1185 assert(isValidOperands(Val, Index) &&
1186 "Invalid extractelement instruction operands!");
1194 bool ExtractElementInst::isValidOperands(const Value *Val, const Value *Index) {
1195 if (!isa<VectorType>(Val->getType()) || Index->getType() != Type::Int32Ty)
1201 //===----------------------------------------------------------------------===//
1202 // InsertElementInst Implementation
1203 //===----------------------------------------------------------------------===//
1205 InsertElementInst::InsertElementInst(const InsertElementInst &IE)
1206 : Instruction(IE.getType(), InsertElement,
1207 OperandTraits<InsertElementInst>::op_begin(this), 3) {
1208 Op<0>() = IE.Op<0>();
1209 Op<1>() = IE.Op<1>();
1210 Op<2>() = IE.Op<2>();
1212 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
1213 const std::string &Name,
1214 Instruction *InsertBef)
1215 : Instruction(Vec->getType(), InsertElement,
1216 OperandTraits<InsertElementInst>::op_begin(this),
1218 assert(isValidOperands(Vec, Elt, Index) &&
1219 "Invalid insertelement instruction operands!");
1226 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, unsigned IndexV,
1227 const std::string &Name,
1228 Instruction *InsertBef)
1229 : Instruction(Vec->getType(), InsertElement,
1230 OperandTraits<InsertElementInst>::op_begin(this),
1232 Constant *Index = ConstantInt::get(Type::Int32Ty, IndexV);
1233 assert(isValidOperands(Vec, Elt, Index) &&
1234 "Invalid insertelement instruction operands!");
1242 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
1243 const std::string &Name,
1244 BasicBlock *InsertAE)
1245 : Instruction(Vec->getType(), InsertElement,
1246 OperandTraits<InsertElementInst>::op_begin(this),
1248 assert(isValidOperands(Vec, Elt, Index) &&
1249 "Invalid insertelement instruction operands!");
1257 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, unsigned IndexV,
1258 const std::string &Name,
1259 BasicBlock *InsertAE)
1260 : Instruction(Vec->getType(), InsertElement,
1261 OperandTraits<InsertElementInst>::op_begin(this),
1263 Constant *Index = ConstantInt::get(Type::Int32Ty, IndexV);
1264 assert(isValidOperands(Vec, Elt, Index) &&
1265 "Invalid insertelement instruction operands!");
1273 bool InsertElementInst::isValidOperands(const Value *Vec, const Value *Elt,
1274 const Value *Index) {
1275 if (!isa<VectorType>(Vec->getType()))
1276 return false; // First operand of insertelement must be vector type.
1278 if (Elt->getType() != cast<VectorType>(Vec->getType())->getElementType())
1279 return false;// Second operand of insertelement must be vector element type.
1281 if (Index->getType() != Type::Int32Ty)
1282 return false; // Third operand of insertelement must be uint.
1287 //===----------------------------------------------------------------------===//
1288 // ShuffleVectorInst Implementation
1289 //===----------------------------------------------------------------------===//
1291 ShuffleVectorInst::ShuffleVectorInst(const ShuffleVectorInst &SV)
1292 : Instruction(SV.getType(), ShuffleVector,
1293 OperandTraits<ShuffleVectorInst>::op_begin(this),
1294 OperandTraits<ShuffleVectorInst>::operands(this)) {
1295 Op<0>() = SV.Op<0>();
1296 Op<1>() = SV.Op<1>();
1297 Op<2>() = SV.Op<2>();
1300 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1301 const std::string &Name,
1302 Instruction *InsertBefore)
1303 : Instruction(VectorType::get(cast<VectorType>(V1->getType())->getElementType(),
1304 cast<VectorType>(Mask->getType())->getNumElements()),
1306 OperandTraits<ShuffleVectorInst>::op_begin(this),
1307 OperandTraits<ShuffleVectorInst>::operands(this),
1309 assert(isValidOperands(V1, V2, Mask) &&
1310 "Invalid shuffle vector instruction operands!");
1317 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1318 const std::string &Name,
1319 BasicBlock *InsertAtEnd)
1320 : Instruction(V1->getType(), ShuffleVector,
1321 OperandTraits<ShuffleVectorInst>::op_begin(this),
1322 OperandTraits<ShuffleVectorInst>::operands(this),
1324 assert(isValidOperands(V1, V2, Mask) &&
1325 "Invalid shuffle vector instruction operands!");
1333 bool ShuffleVectorInst::isValidOperands(const Value *V1, const Value *V2,
1334 const Value *Mask) {
1335 if (!isa<VectorType>(V1->getType()) || V1->getType() != V2->getType())
1338 const VectorType *MaskTy = dyn_cast<VectorType>(Mask->getType());
1339 if (!isa<Constant>(Mask) || MaskTy == 0 ||
1340 MaskTy->getElementType() != Type::Int32Ty)
1345 /// getMaskValue - Return the index from the shuffle mask for the specified
1346 /// output result. This is either -1 if the element is undef or a number less
1347 /// than 2*numelements.
1348 int ShuffleVectorInst::getMaskValue(unsigned i) const {
1349 const Constant *Mask = cast<Constant>(getOperand(2));
1350 if (isa<UndefValue>(Mask)) return -1;
1351 if (isa<ConstantAggregateZero>(Mask)) return 0;
1352 const ConstantVector *MaskCV = cast<ConstantVector>(Mask);
1353 assert(i < MaskCV->getNumOperands() && "Index out of range");
1355 if (isa<UndefValue>(MaskCV->getOperand(i)))
1357 return cast<ConstantInt>(MaskCV->getOperand(i))->getZExtValue();
1360 //===----------------------------------------------------------------------===//
1361 // InsertValueInst Class
1362 //===----------------------------------------------------------------------===//
1364 void InsertValueInst::init(Value *Agg, Value *Val, const unsigned *Idx,
1365 unsigned NumIdx, const std::string &Name) {
1366 assert(NumOperands == 2 && "NumOperands not initialized?");
1370 Indices.insert(Indices.end(), Idx, Idx + NumIdx);
1374 void InsertValueInst::init(Value *Agg, Value *Val, unsigned Idx,
1375 const std::string &Name) {
1376 assert(NumOperands == 2 && "NumOperands not initialized?");
1380 Indices.push_back(Idx);
1384 InsertValueInst::InsertValueInst(const InsertValueInst &IVI)
1385 : Instruction(IVI.getType(), InsertValue,
1386 OperandTraits<InsertValueInst>::op_begin(this), 2),
1387 Indices(IVI.Indices) {
1388 Op<0>() = IVI.getOperand(0);
1389 Op<1>() = IVI.getOperand(1);
1392 InsertValueInst::InsertValueInst(Value *Agg,
1395 const std::string &Name,
1396 Instruction *InsertBefore)
1397 : Instruction(Agg->getType(), InsertValue,
1398 OperandTraits<InsertValueInst>::op_begin(this),
1400 init(Agg, Val, Idx, Name);
1403 InsertValueInst::InsertValueInst(Value *Agg,
1406 const std::string &Name,
1407 BasicBlock *InsertAtEnd)
1408 : Instruction(Agg->getType(), InsertValue,
1409 OperandTraits<InsertValueInst>::op_begin(this),
1411 init(Agg, Val, Idx, Name);
1414 //===----------------------------------------------------------------------===//
1415 // ExtractValueInst Class
1416 //===----------------------------------------------------------------------===//
1418 void ExtractValueInst::init(const unsigned *Idx, unsigned NumIdx,
1419 const std::string &Name) {
1420 assert(NumOperands == 1 && "NumOperands not initialized?");
1422 Indices.insert(Indices.end(), Idx, Idx + NumIdx);
1426 void ExtractValueInst::init(unsigned Idx, const std::string &Name) {
1427 assert(NumOperands == 1 && "NumOperands not initialized?");
1429 Indices.push_back(Idx);
1433 ExtractValueInst::ExtractValueInst(const ExtractValueInst &EVI)
1434 : UnaryInstruction(EVI.getType(), ExtractValue, EVI.getOperand(0)),
1435 Indices(EVI.Indices) {
1438 // getIndexedType - Returns the type of the element that would be extracted
1439 // with an extractvalue instruction with the specified parameters.
1441 // A null type is returned if the indices are invalid for the specified
1444 const Type* ExtractValueInst::getIndexedType(const Type *Agg,
1445 const unsigned *Idxs,
1447 unsigned CurIdx = 0;
1448 for (; CurIdx != NumIdx; ++CurIdx) {
1449 const CompositeType *CT = dyn_cast<CompositeType>(Agg);
1450 if (!CT || isa<PointerType>(CT) || isa<VectorType>(CT)) return 0;
1451 unsigned Index = Idxs[CurIdx];
1452 if (!CT->indexValid(Index)) return 0;
1453 Agg = CT->getTypeAtIndex(Index);
1455 // If the new type forwards to another type, then it is in the middle
1456 // of being refined to another type (and hence, may have dropped all
1457 // references to what it was using before). So, use the new forwarded
1459 if (const Type *Ty = Agg->getForwardedType())
1462 return CurIdx == NumIdx ? Agg : 0;
1465 const Type* ExtractValueInst::getIndexedType(const Type *Agg,
1467 return getIndexedType(Agg, &Idx, 1);
1470 //===----------------------------------------------------------------------===//
1471 // BinaryOperator Class
1472 //===----------------------------------------------------------------------===//
1474 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
1475 const Type *Ty, const std::string &Name,
1476 Instruction *InsertBefore)
1477 : Instruction(Ty, iType,
1478 OperandTraits<BinaryOperator>::op_begin(this),
1479 OperandTraits<BinaryOperator>::operands(this),
1487 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
1488 const Type *Ty, const std::string &Name,
1489 BasicBlock *InsertAtEnd)
1490 : Instruction(Ty, iType,
1491 OperandTraits<BinaryOperator>::op_begin(this),
1492 OperandTraits<BinaryOperator>::operands(this),
1501 void BinaryOperator::init(BinaryOps iType) {
1502 Value *LHS = getOperand(0), *RHS = getOperand(1);
1503 LHS = LHS; RHS = RHS; // Silence warnings.
1504 assert(LHS->getType() == RHS->getType() &&
1505 "Binary operator operand types must match!");
1510 assert(getType() == LHS->getType() &&
1511 "Arithmetic operation should return same type as operands!");
1512 assert((getType()->isInteger() || getType()->isFloatingPoint() ||
1513 isa<VectorType>(getType())) &&
1514 "Tried to create an arithmetic operation on a non-arithmetic type!");
1518 assert(getType() == LHS->getType() &&
1519 "Arithmetic operation should return same type as operands!");
1520 assert((getType()->isInteger() || (isa<VectorType>(getType()) &&
1521 cast<VectorType>(getType())->getElementType()->isInteger())) &&
1522 "Incorrect operand type (not integer) for S/UDIV");
1525 assert(getType() == LHS->getType() &&
1526 "Arithmetic operation should return same type as operands!");
1527 assert((getType()->isFloatingPoint() || (isa<VectorType>(getType()) &&
1528 cast<VectorType>(getType())->getElementType()->isFloatingPoint()))
1529 && "Incorrect operand type (not floating point) for FDIV");
1533 assert(getType() == LHS->getType() &&
1534 "Arithmetic operation should return same type as operands!");
1535 assert((getType()->isInteger() || (isa<VectorType>(getType()) &&
1536 cast<VectorType>(getType())->getElementType()->isInteger())) &&
1537 "Incorrect operand type (not integer) for S/UREM");
1540 assert(getType() == LHS->getType() &&
1541 "Arithmetic operation should return same type as operands!");
1542 assert((getType()->isFloatingPoint() || (isa<VectorType>(getType()) &&
1543 cast<VectorType>(getType())->getElementType()->isFloatingPoint()))
1544 && "Incorrect operand type (not floating point) for FREM");
1549 assert(getType() == LHS->getType() &&
1550 "Shift operation should return same type as operands!");
1551 assert((getType()->isInteger() ||
1552 (isa<VectorType>(getType()) &&
1553 cast<VectorType>(getType())->getElementType()->isInteger())) &&
1554 "Tried to create a shift operation on a non-integral type!");
1558 assert(getType() == LHS->getType() &&
1559 "Logical operation should return same type as operands!");
1560 assert((getType()->isInteger() ||
1561 (isa<VectorType>(getType()) &&
1562 cast<VectorType>(getType())->getElementType()->isInteger())) &&
1563 "Tried to create a logical operation on a non-integral type!");
1571 BinaryOperator *BinaryOperator::Create(BinaryOps Op, Value *S1, Value *S2,
1572 const std::string &Name,
1573 Instruction *InsertBefore) {
1574 assert(S1->getType() == S2->getType() &&
1575 "Cannot create binary operator with two operands of differing type!");
1576 return new BinaryOperator(Op, S1, S2, S1->getType(), Name, InsertBefore);
1579 BinaryOperator *BinaryOperator::Create(BinaryOps Op, Value *S1, Value *S2,
1580 const std::string &Name,
1581 BasicBlock *InsertAtEnd) {
1582 BinaryOperator *Res = Create(Op, S1, S2, Name);
1583 InsertAtEnd->getInstList().push_back(Res);
1587 BinaryOperator *BinaryOperator::CreateNeg(Value *Op, const std::string &Name,
1588 Instruction *InsertBefore) {
1589 Value *zero = ConstantExpr::getZeroValueForNegationExpr(Op->getType());
1590 return new BinaryOperator(Instruction::Sub,
1592 Op->getType(), Name, InsertBefore);
1595 BinaryOperator *BinaryOperator::CreateNeg(Value *Op, const std::string &Name,
1596 BasicBlock *InsertAtEnd) {
1597 Value *zero = ConstantExpr::getZeroValueForNegationExpr(Op->getType());
1598 return new BinaryOperator(Instruction::Sub,
1600 Op->getType(), Name, InsertAtEnd);
1603 BinaryOperator *BinaryOperator::CreateNot(Value *Op, const std::string &Name,
1604 Instruction *InsertBefore) {
1606 if (const VectorType *PTy = dyn_cast<VectorType>(Op->getType())) {
1607 C = ConstantInt::getAllOnesValue(PTy->getElementType());
1608 C = ConstantVector::get(std::vector<Constant*>(PTy->getNumElements(), C));
1610 C = ConstantInt::getAllOnesValue(Op->getType());
1613 return new BinaryOperator(Instruction::Xor, Op, C,
1614 Op->getType(), Name, InsertBefore);
1617 BinaryOperator *BinaryOperator::CreateNot(Value *Op, const std::string &Name,
1618 BasicBlock *InsertAtEnd) {
1620 if (const VectorType *PTy = dyn_cast<VectorType>(Op->getType())) {
1621 // Create a vector of all ones values.
1622 Constant *Elt = ConstantInt::getAllOnesValue(PTy->getElementType());
1624 ConstantVector::get(std::vector<Constant*>(PTy->getNumElements(), Elt));
1626 AllOnes = ConstantInt::getAllOnesValue(Op->getType());
1629 return new BinaryOperator(Instruction::Xor, Op, AllOnes,
1630 Op->getType(), Name, InsertAtEnd);
1634 // isConstantAllOnes - Helper function for several functions below
1635 static inline bool isConstantAllOnes(const Value *V) {
1636 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V))
1637 return CI->isAllOnesValue();
1638 if (const ConstantVector *CV = dyn_cast<ConstantVector>(V))
1639 return CV->isAllOnesValue();
1643 bool BinaryOperator::isNeg(const Value *V) {
1644 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1645 if (Bop->getOpcode() == Instruction::Sub)
1646 return Bop->getOperand(0) ==
1647 ConstantExpr::getZeroValueForNegationExpr(Bop->getType());
1651 bool BinaryOperator::isNot(const Value *V) {
1652 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1653 return (Bop->getOpcode() == Instruction::Xor &&
1654 (isConstantAllOnes(Bop->getOperand(1)) ||
1655 isConstantAllOnes(Bop->getOperand(0))));
1659 Value *BinaryOperator::getNegArgument(Value *BinOp) {
1660 assert(isNeg(BinOp) && "getNegArgument from non-'neg' instruction!");
1661 return cast<BinaryOperator>(BinOp)->getOperand(1);
1664 const Value *BinaryOperator::getNegArgument(const Value *BinOp) {
1665 return getNegArgument(const_cast<Value*>(BinOp));
1668 Value *BinaryOperator::getNotArgument(Value *BinOp) {
1669 assert(isNot(BinOp) && "getNotArgument on non-'not' instruction!");
1670 BinaryOperator *BO = cast<BinaryOperator>(BinOp);
1671 Value *Op0 = BO->getOperand(0);
1672 Value *Op1 = BO->getOperand(1);
1673 if (isConstantAllOnes(Op0)) return Op1;
1675 assert(isConstantAllOnes(Op1));
1679 const Value *BinaryOperator::getNotArgument(const Value *BinOp) {
1680 return getNotArgument(const_cast<Value*>(BinOp));
1684 // swapOperands - Exchange the two operands to this instruction. This
1685 // instruction is safe to use on any binary instruction and does not
1686 // modify the semantics of the instruction. If the instruction is
1687 // order dependent (SetLT f.e.) the opcode is changed.
1689 bool BinaryOperator::swapOperands() {
1690 if (!isCommutative())
1691 return true; // Can't commute operands
1692 Op<0>().swap(Op<1>());
1696 //===----------------------------------------------------------------------===//
1698 //===----------------------------------------------------------------------===//
1700 // Just determine if this cast only deals with integral->integral conversion.
1701 bool CastInst::isIntegerCast() const {
1702 switch (getOpcode()) {
1703 default: return false;
1704 case Instruction::ZExt:
1705 case Instruction::SExt:
1706 case Instruction::Trunc:
1708 case Instruction::BitCast:
1709 return getOperand(0)->getType()->isInteger() && getType()->isInteger();
1713 bool CastInst::isLosslessCast() const {
1714 // Only BitCast can be lossless, exit fast if we're not BitCast
1715 if (getOpcode() != Instruction::BitCast)
1718 // Identity cast is always lossless
1719 const Type* SrcTy = getOperand(0)->getType();
1720 const Type* DstTy = getType();
1724 // Pointer to pointer is always lossless.
1725 if (isa<PointerType>(SrcTy))
1726 return isa<PointerType>(DstTy);
1727 return false; // Other types have no identity values
1730 /// This function determines if the CastInst does not require any bits to be
1731 /// changed in order to effect the cast. Essentially, it identifies cases where
1732 /// no code gen is necessary for the cast, hence the name no-op cast. For
1733 /// example, the following are all no-op casts:
1734 /// # bitcast i32* %x to i8*
1735 /// # bitcast <2 x i32> %x to <4 x i16>
1736 /// # ptrtoint i32* %x to i32 ; on 32-bit plaforms only
1737 /// @brief Determine if a cast is a no-op.
1738 bool CastInst::isNoopCast(const Type *IntPtrTy) const {
1739 switch (getOpcode()) {
1741 assert(!"Invalid CastOp");
1742 case Instruction::Trunc:
1743 case Instruction::ZExt:
1744 case Instruction::SExt:
1745 case Instruction::FPTrunc:
1746 case Instruction::FPExt:
1747 case Instruction::UIToFP:
1748 case Instruction::SIToFP:
1749 case Instruction::FPToUI:
1750 case Instruction::FPToSI:
1751 return false; // These always modify bits
1752 case Instruction::BitCast:
1753 return true; // BitCast never modifies bits.
1754 case Instruction::PtrToInt:
1755 return IntPtrTy->getPrimitiveSizeInBits() ==
1756 getType()->getPrimitiveSizeInBits();
1757 case Instruction::IntToPtr:
1758 return IntPtrTy->getPrimitiveSizeInBits() ==
1759 getOperand(0)->getType()->getPrimitiveSizeInBits();
1763 /// This function determines if a pair of casts can be eliminated and what
1764 /// opcode should be used in the elimination. This assumes that there are two
1765 /// instructions like this:
1766 /// * %F = firstOpcode SrcTy %x to MidTy
1767 /// * %S = secondOpcode MidTy %F to DstTy
1768 /// The function returns a resultOpcode so these two casts can be replaced with:
1769 /// * %Replacement = resultOpcode %SrcTy %x to DstTy
1770 /// If no such cast is permited, the function returns 0.
1771 unsigned CastInst::isEliminableCastPair(
1772 Instruction::CastOps firstOp, Instruction::CastOps secondOp,
1773 const Type *SrcTy, const Type *MidTy, const Type *DstTy, const Type *IntPtrTy)
1775 // Define the 144 possibilities for these two cast instructions. The values
1776 // in this matrix determine what to do in a given situation and select the
1777 // case in the switch below. The rows correspond to firstOp, the columns
1778 // correspond to secondOp. In looking at the table below, keep in mind
1779 // the following cast properties:
1781 // Size Compare Source Destination
1782 // Operator Src ? Size Type Sign Type Sign
1783 // -------- ------------ ------------------- ---------------------
1784 // TRUNC > Integer Any Integral Any
1785 // ZEXT < Integral Unsigned Integer Any
1786 // SEXT < Integral Signed Integer Any
1787 // FPTOUI n/a FloatPt n/a Integral Unsigned
1788 // FPTOSI n/a FloatPt n/a Integral Signed
1789 // UITOFP n/a Integral Unsigned FloatPt n/a
1790 // SITOFP n/a Integral Signed FloatPt n/a
1791 // FPTRUNC > FloatPt n/a FloatPt n/a
1792 // FPEXT < FloatPt n/a FloatPt n/a
1793 // PTRTOINT n/a Pointer n/a Integral Unsigned
1794 // INTTOPTR n/a Integral Unsigned Pointer n/a
1795 // BITCONVERT = FirstClass n/a FirstClass n/a
1797 // NOTE: some transforms are safe, but we consider them to be non-profitable.
1798 // For example, we could merge "fptoui double to uint" + "zext uint to ulong",
1799 // into "fptoui double to ulong", but this loses information about the range
1800 // of the produced value (we no longer know the top-part is all zeros).
1801 // Further this conversion is often much more expensive for typical hardware,
1802 // and causes issues when building libgcc. We disallow fptosi+sext for the
1804 const unsigned numCastOps =
1805 Instruction::CastOpsEnd - Instruction::CastOpsBegin;
1806 static const uint8_t CastResults[numCastOps][numCastOps] = {
1807 // T F F U S F F P I B -+
1808 // R Z S P P I I T P 2 N T |
1809 // U E E 2 2 2 2 R E I T C +- secondOp
1810 // N X X U S F F N X N 2 V |
1811 // C T T I I P P C T T P T -+
1812 { 1, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // Trunc -+
1813 { 8, 1, 9,99,99, 2, 0,99,99,99, 2, 3 }, // ZExt |
1814 { 8, 0, 1,99,99, 0, 2,99,99,99, 0, 3 }, // SExt |
1815 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // FPToUI |
1816 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // FPToSI |
1817 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4 }, // UIToFP +- firstOp
1818 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4 }, // SIToFP |
1819 { 99,99,99, 0, 0,99,99, 1, 0,99,99, 4 }, // FPTrunc |
1820 { 99,99,99, 2, 2,99,99,10, 2,99,99, 4 }, // FPExt |
1821 { 1, 0, 0,99,99, 0, 0,99,99,99, 7, 3 }, // PtrToInt |
1822 { 99,99,99,99,99,99,99,99,99,13,99,12 }, // IntToPtr |
1823 { 5, 5, 5, 6, 6, 5, 5, 6, 6,11, 5, 1 }, // BitCast -+
1826 int ElimCase = CastResults[firstOp-Instruction::CastOpsBegin]
1827 [secondOp-Instruction::CastOpsBegin];
1830 // categorically disallowed
1833 // allowed, use first cast's opcode
1836 // allowed, use second cast's opcode
1839 // no-op cast in second op implies firstOp as long as the DestTy
1841 if (DstTy->isInteger())
1845 // no-op cast in second op implies firstOp as long as the DestTy
1846 // is floating point
1847 if (DstTy->isFloatingPoint())
1851 // no-op cast in first op implies secondOp as long as the SrcTy
1853 if (SrcTy->isInteger())
1857 // no-op cast in first op implies secondOp as long as the SrcTy
1858 // is a floating point
1859 if (SrcTy->isFloatingPoint())
1863 // ptrtoint, inttoptr -> bitcast (ptr -> ptr) if int size is >= ptr size
1864 unsigned PtrSize = IntPtrTy->getPrimitiveSizeInBits();
1865 unsigned MidSize = MidTy->getPrimitiveSizeInBits();
1866 if (MidSize >= PtrSize)
1867 return Instruction::BitCast;
1871 // ext, trunc -> bitcast, if the SrcTy and DstTy are same size
1872 // ext, trunc -> ext, if sizeof(SrcTy) < sizeof(DstTy)
1873 // ext, trunc -> trunc, if sizeof(SrcTy) > sizeof(DstTy)
1874 unsigned SrcSize = SrcTy->getPrimitiveSizeInBits();
1875 unsigned DstSize = DstTy->getPrimitiveSizeInBits();
1876 if (SrcSize == DstSize)
1877 return Instruction::BitCast;
1878 else if (SrcSize < DstSize)
1882 case 9: // zext, sext -> zext, because sext can't sign extend after zext
1883 return Instruction::ZExt;
1885 // fpext followed by ftrunc is allowed if the bit size returned to is
1886 // the same as the original, in which case its just a bitcast
1888 return Instruction::BitCast;
1889 return 0; // If the types are not the same we can't eliminate it.
1891 // bitcast followed by ptrtoint is allowed as long as the bitcast
1892 // is a pointer to pointer cast.
1893 if (isa<PointerType>(SrcTy) && isa<PointerType>(MidTy))
1897 // inttoptr, bitcast -> intptr if bitcast is a ptr to ptr cast
1898 if (isa<PointerType>(MidTy) && isa<PointerType>(DstTy))
1902 // inttoptr, ptrtoint -> bitcast if SrcSize<=PtrSize and SrcSize==DstSize
1903 unsigned PtrSize = IntPtrTy->getPrimitiveSizeInBits();
1904 unsigned SrcSize = SrcTy->getPrimitiveSizeInBits();
1905 unsigned DstSize = DstTy->getPrimitiveSizeInBits();
1906 if (SrcSize <= PtrSize && SrcSize == DstSize)
1907 return Instruction::BitCast;
1911 // cast combination can't happen (error in input). This is for all cases
1912 // where the MidTy is not the same for the two cast instructions.
1913 assert(!"Invalid Cast Combination");
1916 assert(!"Error in CastResults table!!!");
1922 CastInst *CastInst::Create(Instruction::CastOps op, Value *S, const Type *Ty,
1923 const std::string &Name, Instruction *InsertBefore) {
1924 // Construct and return the appropriate CastInst subclass
1926 case Trunc: return new TruncInst (S, Ty, Name, InsertBefore);
1927 case ZExt: return new ZExtInst (S, Ty, Name, InsertBefore);
1928 case SExt: return new SExtInst (S, Ty, Name, InsertBefore);
1929 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertBefore);
1930 case FPExt: return new FPExtInst (S, Ty, Name, InsertBefore);
1931 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertBefore);
1932 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertBefore);
1933 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertBefore);
1934 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertBefore);
1935 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertBefore);
1936 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertBefore);
1937 case BitCast: return new BitCastInst (S, Ty, Name, InsertBefore);
1939 assert(!"Invalid opcode provided");
1944 CastInst *CastInst::Create(Instruction::CastOps op, Value *S, const Type *Ty,
1945 const std::string &Name, BasicBlock *InsertAtEnd) {
1946 // Construct and return the appropriate CastInst subclass
1948 case Trunc: return new TruncInst (S, Ty, Name, InsertAtEnd);
1949 case ZExt: return new ZExtInst (S, Ty, Name, InsertAtEnd);
1950 case SExt: return new SExtInst (S, Ty, Name, InsertAtEnd);
1951 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertAtEnd);
1952 case FPExt: return new FPExtInst (S, Ty, Name, InsertAtEnd);
1953 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertAtEnd);
1954 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertAtEnd);
1955 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertAtEnd);
1956 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertAtEnd);
1957 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertAtEnd);
1958 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertAtEnd);
1959 case BitCast: return new BitCastInst (S, Ty, Name, InsertAtEnd);
1961 assert(!"Invalid opcode provided");
1966 CastInst *CastInst::CreateZExtOrBitCast(Value *S, const Type *Ty,
1967 const std::string &Name,
1968 Instruction *InsertBefore) {
1969 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1970 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
1971 return Create(Instruction::ZExt, S, Ty, Name, InsertBefore);
1974 CastInst *CastInst::CreateZExtOrBitCast(Value *S, const Type *Ty,
1975 const std::string &Name,
1976 BasicBlock *InsertAtEnd) {
1977 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1978 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
1979 return Create(Instruction::ZExt, S, Ty, Name, InsertAtEnd);
1982 CastInst *CastInst::CreateSExtOrBitCast(Value *S, const Type *Ty,
1983 const std::string &Name,
1984 Instruction *InsertBefore) {
1985 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1986 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
1987 return Create(Instruction::SExt, S, Ty, Name, InsertBefore);
1990 CastInst *CastInst::CreateSExtOrBitCast(Value *S, const Type *Ty,
1991 const std::string &Name,
1992 BasicBlock *InsertAtEnd) {
1993 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
1994 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
1995 return Create(Instruction::SExt, S, Ty, Name, InsertAtEnd);
1998 CastInst *CastInst::CreateTruncOrBitCast(Value *S, const Type *Ty,
1999 const std::string &Name,
2000 Instruction *InsertBefore) {
2001 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
2002 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2003 return Create(Instruction::Trunc, S, Ty, Name, InsertBefore);
2006 CastInst *CastInst::CreateTruncOrBitCast(Value *S, const Type *Ty,
2007 const std::string &Name,
2008 BasicBlock *InsertAtEnd) {
2009 if (S->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
2010 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2011 return Create(Instruction::Trunc, S, Ty, Name, InsertAtEnd);
2014 CastInst *CastInst::CreatePointerCast(Value *S, const Type *Ty,
2015 const std::string &Name,
2016 BasicBlock *InsertAtEnd) {
2017 assert(isa<PointerType>(S->getType()) && "Invalid cast");
2018 assert((Ty->isInteger() || isa<PointerType>(Ty)) &&
2021 if (Ty->isInteger())
2022 return Create(Instruction::PtrToInt, S, Ty, Name, InsertAtEnd);
2023 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2026 /// @brief Create a BitCast or a PtrToInt cast instruction
2027 CastInst *CastInst::CreatePointerCast(Value *S, const Type *Ty,
2028 const std::string &Name,
2029 Instruction *InsertBefore) {
2030 assert(isa<PointerType>(S->getType()) && "Invalid cast");
2031 assert((Ty->isInteger() || isa<PointerType>(Ty)) &&
2034 if (Ty->isInteger())
2035 return Create(Instruction::PtrToInt, S, Ty, Name, InsertBefore);
2036 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2039 CastInst *CastInst::CreateIntegerCast(Value *C, const Type *Ty,
2040 bool isSigned, const std::string &Name,
2041 Instruction *InsertBefore) {
2042 assert(C->getType()->isInteger() && Ty->isInteger() && "Invalid cast");
2043 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
2044 unsigned DstBits = Ty->getPrimitiveSizeInBits();
2045 Instruction::CastOps opcode =
2046 (SrcBits == DstBits ? Instruction::BitCast :
2047 (SrcBits > DstBits ? Instruction::Trunc :
2048 (isSigned ? Instruction::SExt : Instruction::ZExt)));
2049 return Create(opcode, C, Ty, Name, InsertBefore);
2052 CastInst *CastInst::CreateIntegerCast(Value *C, const Type *Ty,
2053 bool isSigned, const std::string &Name,
2054 BasicBlock *InsertAtEnd) {
2055 assert(C->getType()->isInteger() && Ty->isInteger() && "Invalid cast");
2056 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
2057 unsigned DstBits = Ty->getPrimitiveSizeInBits();
2058 Instruction::CastOps opcode =
2059 (SrcBits == DstBits ? Instruction::BitCast :
2060 (SrcBits > DstBits ? Instruction::Trunc :
2061 (isSigned ? Instruction::SExt : Instruction::ZExt)));
2062 return Create(opcode, C, Ty, Name, InsertAtEnd);
2065 CastInst *CastInst::CreateFPCast(Value *C, const Type *Ty,
2066 const std::string &Name,
2067 Instruction *InsertBefore) {
2068 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
2070 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
2071 unsigned DstBits = Ty->getPrimitiveSizeInBits();
2072 Instruction::CastOps opcode =
2073 (SrcBits == DstBits ? Instruction::BitCast :
2074 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
2075 return Create(opcode, C, Ty, Name, InsertBefore);
2078 CastInst *CastInst::CreateFPCast(Value *C, const Type *Ty,
2079 const std::string &Name,
2080 BasicBlock *InsertAtEnd) {
2081 assert(C->getType()->isFloatingPoint() && Ty->isFloatingPoint() &&
2083 unsigned SrcBits = C->getType()->getPrimitiveSizeInBits();
2084 unsigned DstBits = Ty->getPrimitiveSizeInBits();
2085 Instruction::CastOps opcode =
2086 (SrcBits == DstBits ? Instruction::BitCast :
2087 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
2088 return Create(opcode, C, Ty, Name, InsertAtEnd);
2091 // Check whether it is valid to call getCastOpcode for these types.
2092 // This routine must be kept in sync with getCastOpcode.
2093 bool CastInst::isCastable(const Type *SrcTy, const Type *DestTy) {
2094 if (!SrcTy->isFirstClassType() || !DestTy->isFirstClassType())
2097 if (SrcTy == DestTy)
2100 // Get the bit sizes, we'll need these
2101 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); // 0 for ptr/vector
2102 unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr/vector
2104 // Run through the possibilities ...
2105 if (DestTy->isInteger()) { // Casting to integral
2106 if (SrcTy->isInteger()) { // Casting from integral
2108 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt
2110 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
2111 // Casting from vector
2112 return DestBits == PTy->getBitWidth();
2113 } else { // Casting from something else
2114 return isa<PointerType>(SrcTy);
2116 } else if (DestTy->isFloatingPoint()) { // Casting to floating pt
2117 if (SrcTy->isInteger()) { // Casting from integral
2119 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt
2121 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
2122 // Casting from vector
2123 return DestBits == PTy->getBitWidth();
2124 } else { // Casting from something else
2127 } else if (const VectorType *DestPTy = dyn_cast<VectorType>(DestTy)) {
2128 // Casting to vector
2129 if (const VectorType *SrcPTy = dyn_cast<VectorType>(SrcTy)) {
2130 // Casting from vector
2131 return DestPTy->getBitWidth() == SrcPTy->getBitWidth();
2132 } else { // Casting from something else
2133 return DestPTy->getBitWidth() == SrcBits;
2135 } else if (isa<PointerType>(DestTy)) { // Casting to pointer
2136 if (isa<PointerType>(SrcTy)) { // Casting from pointer
2138 } else if (SrcTy->isInteger()) { // Casting from integral
2140 } else { // Casting from something else
2143 } else { // Casting to something else
2148 // Provide a way to get a "cast" where the cast opcode is inferred from the
2149 // types and size of the operand. This, basically, is a parallel of the
2150 // logic in the castIsValid function below. This axiom should hold:
2151 // castIsValid( getCastOpcode(Val, Ty), Val, Ty)
2152 // should not assert in castIsValid. In other words, this produces a "correct"
2153 // casting opcode for the arguments passed to it.
2154 // This routine must be kept in sync with isCastable.
2155 Instruction::CastOps
2156 CastInst::getCastOpcode(
2157 const Value *Src, bool SrcIsSigned, const Type *DestTy, bool DestIsSigned) {
2158 // Get the bit sizes, we'll need these
2159 const Type *SrcTy = Src->getType();
2160 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); // 0 for ptr/vector
2161 unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr/vector
2163 assert(SrcTy->isFirstClassType() && DestTy->isFirstClassType() &&
2164 "Only first class types are castable!");
2166 // Run through the possibilities ...
2167 if (DestTy->isInteger()) { // Casting to integral
2168 if (SrcTy->isInteger()) { // Casting from integral
2169 if (DestBits < SrcBits)
2170 return Trunc; // int -> smaller int
2171 else if (DestBits > SrcBits) { // its an extension
2173 return SExt; // signed -> SEXT
2175 return ZExt; // unsigned -> ZEXT
2177 return BitCast; // Same size, No-op cast
2179 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt
2181 return FPToSI; // FP -> sint
2183 return FPToUI; // FP -> uint
2184 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
2185 assert(DestBits == PTy->getBitWidth() &&
2186 "Casting vector to integer of different width");
2188 return BitCast; // Same size, no-op cast
2190 assert(isa<PointerType>(SrcTy) &&
2191 "Casting from a value that is not first-class type");
2192 return PtrToInt; // ptr -> int
2194 } else if (DestTy->isFloatingPoint()) { // Casting to floating pt
2195 if (SrcTy->isInteger()) { // Casting from integral
2197 return SIToFP; // sint -> FP
2199 return UIToFP; // uint -> FP
2200 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt
2201 if (DestBits < SrcBits) {
2202 return FPTrunc; // FP -> smaller FP
2203 } else if (DestBits > SrcBits) {
2204 return FPExt; // FP -> larger FP
2206 return BitCast; // same size, no-op cast
2208 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
2209 assert(DestBits == PTy->getBitWidth() &&
2210 "Casting vector to floating point of different width");
2212 return BitCast; // same size, no-op cast
2214 assert(0 && "Casting pointer or non-first class to float");
2216 } else if (const VectorType *DestPTy = dyn_cast<VectorType>(DestTy)) {
2217 if (const VectorType *SrcPTy = dyn_cast<VectorType>(SrcTy)) {
2218 assert(DestPTy->getBitWidth() == SrcPTy->getBitWidth() &&
2219 "Casting vector to vector of different widths");
2221 return BitCast; // vector -> vector
2222 } else if (DestPTy->getBitWidth() == SrcBits) {
2223 return BitCast; // float/int -> vector
2225 assert(!"Illegal cast to vector (wrong type or size)");
2227 } else if (isa<PointerType>(DestTy)) {
2228 if (isa<PointerType>(SrcTy)) {
2229 return BitCast; // ptr -> ptr
2230 } else if (SrcTy->isInteger()) {
2231 return IntToPtr; // int -> ptr
2233 assert(!"Casting pointer to other than pointer or int");
2236 assert(!"Casting to type that is not first-class");
2239 // If we fall through to here we probably hit an assertion cast above
2240 // and assertions are not turned on. Anything we return is an error, so
2241 // BitCast is as good a choice as any.
2245 //===----------------------------------------------------------------------===//
2246 // CastInst SubClass Constructors
2247 //===----------------------------------------------------------------------===//
2249 /// Check that the construction parameters for a CastInst are correct. This
2250 /// could be broken out into the separate constructors but it is useful to have
2251 /// it in one place and to eliminate the redundant code for getting the sizes
2252 /// of the types involved.
2254 CastInst::castIsValid(Instruction::CastOps op, Value *S, const Type *DstTy) {
2256 // Check for type sanity on the arguments
2257 const Type *SrcTy = S->getType();
2258 if (!SrcTy->isFirstClassType() || !DstTy->isFirstClassType())
2261 // Get the size of the types in bits, we'll need this later
2262 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
2263 unsigned DstBitSize = DstTy->getPrimitiveSizeInBits();
2265 // Switch on the opcode provided
2267 default: return false; // This is an input error
2268 case Instruction::Trunc:
2269 return SrcTy->isIntOrIntVector() &&
2270 DstTy->isIntOrIntVector()&& SrcBitSize > DstBitSize;
2271 case Instruction::ZExt:
2272 return SrcTy->isIntOrIntVector() &&
2273 DstTy->isIntOrIntVector()&& SrcBitSize < DstBitSize;
2274 case Instruction::SExt:
2275 return SrcTy->isIntOrIntVector() &&
2276 DstTy->isIntOrIntVector()&& SrcBitSize < DstBitSize;
2277 case Instruction::FPTrunc:
2278 return SrcTy->isFPOrFPVector() &&
2279 DstTy->isFPOrFPVector() &&
2280 SrcBitSize > DstBitSize;
2281 case Instruction::FPExt:
2282 return SrcTy->isFPOrFPVector() &&
2283 DstTy->isFPOrFPVector() &&
2284 SrcBitSize < DstBitSize;
2285 case Instruction::UIToFP:
2286 case Instruction::SIToFP:
2287 if (const VectorType *SVTy = dyn_cast<VectorType>(SrcTy)) {
2288 if (const VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
2289 return SVTy->getElementType()->isIntOrIntVector() &&
2290 DVTy->getElementType()->isFPOrFPVector() &&
2291 SVTy->getNumElements() == DVTy->getNumElements();
2294 return SrcTy->isIntOrIntVector() && DstTy->isFPOrFPVector();
2295 case Instruction::FPToUI:
2296 case Instruction::FPToSI:
2297 if (const VectorType *SVTy = dyn_cast<VectorType>(SrcTy)) {
2298 if (const VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
2299 return SVTy->getElementType()->isFPOrFPVector() &&
2300 DVTy->getElementType()->isIntOrIntVector() &&
2301 SVTy->getNumElements() == DVTy->getNumElements();
2304 return SrcTy->isFPOrFPVector() && DstTy->isIntOrIntVector();
2305 case Instruction::PtrToInt:
2306 return isa<PointerType>(SrcTy) && DstTy->isInteger();
2307 case Instruction::IntToPtr:
2308 return SrcTy->isInteger() && isa<PointerType>(DstTy);
2309 case Instruction::BitCast:
2310 // BitCast implies a no-op cast of type only. No bits change.
2311 // However, you can't cast pointers to anything but pointers.
2312 if (isa<PointerType>(SrcTy) != isa<PointerType>(DstTy))
2315 // Now we know we're not dealing with a pointer/non-pointer mismatch. In all
2316 // these cases, the cast is okay if the source and destination bit widths
2318 return SrcBitSize == DstBitSize;
2322 TruncInst::TruncInst(
2323 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2324 ) : CastInst(Ty, Trunc, S, Name, InsertBefore) {
2325 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
2328 TruncInst::TruncInst(
2329 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2330 ) : CastInst(Ty, Trunc, S, Name, InsertAtEnd) {
2331 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
2335 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2336 ) : CastInst(Ty, ZExt, S, Name, InsertBefore) {
2337 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
2341 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2342 ) : CastInst(Ty, ZExt, S, Name, InsertAtEnd) {
2343 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
2346 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2347 ) : CastInst(Ty, SExt, S, Name, InsertBefore) {
2348 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
2352 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2353 ) : CastInst(Ty, SExt, S, Name, InsertAtEnd) {
2354 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
2357 FPTruncInst::FPTruncInst(
2358 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2359 ) : CastInst(Ty, FPTrunc, S, Name, InsertBefore) {
2360 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
2363 FPTruncInst::FPTruncInst(
2364 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2365 ) : CastInst(Ty, FPTrunc, S, Name, InsertAtEnd) {
2366 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
2369 FPExtInst::FPExtInst(
2370 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2371 ) : CastInst(Ty, FPExt, S, Name, InsertBefore) {
2372 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
2375 FPExtInst::FPExtInst(
2376 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2377 ) : CastInst(Ty, FPExt, S, Name, InsertAtEnd) {
2378 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
2381 UIToFPInst::UIToFPInst(
2382 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2383 ) : CastInst(Ty, UIToFP, S, Name, InsertBefore) {
2384 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
2387 UIToFPInst::UIToFPInst(
2388 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2389 ) : CastInst(Ty, UIToFP, S, Name, InsertAtEnd) {
2390 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
2393 SIToFPInst::SIToFPInst(
2394 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2395 ) : CastInst(Ty, SIToFP, S, Name, InsertBefore) {
2396 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
2399 SIToFPInst::SIToFPInst(
2400 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2401 ) : CastInst(Ty, SIToFP, S, Name, InsertAtEnd) {
2402 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
2405 FPToUIInst::FPToUIInst(
2406 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2407 ) : CastInst(Ty, FPToUI, S, Name, InsertBefore) {
2408 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
2411 FPToUIInst::FPToUIInst(
2412 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2413 ) : CastInst(Ty, FPToUI, S, Name, InsertAtEnd) {
2414 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
2417 FPToSIInst::FPToSIInst(
2418 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2419 ) : CastInst(Ty, FPToSI, S, Name, InsertBefore) {
2420 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
2423 FPToSIInst::FPToSIInst(
2424 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2425 ) : CastInst(Ty, FPToSI, S, Name, InsertAtEnd) {
2426 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
2429 PtrToIntInst::PtrToIntInst(
2430 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2431 ) : CastInst(Ty, PtrToInt, S, Name, InsertBefore) {
2432 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
2435 PtrToIntInst::PtrToIntInst(
2436 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2437 ) : CastInst(Ty, PtrToInt, S, Name, InsertAtEnd) {
2438 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
2441 IntToPtrInst::IntToPtrInst(
2442 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2443 ) : CastInst(Ty, IntToPtr, S, Name, InsertBefore) {
2444 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
2447 IntToPtrInst::IntToPtrInst(
2448 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2449 ) : CastInst(Ty, IntToPtr, S, Name, InsertAtEnd) {
2450 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
2453 BitCastInst::BitCastInst(
2454 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2455 ) : CastInst(Ty, BitCast, S, Name, InsertBefore) {
2456 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
2459 BitCastInst::BitCastInst(
2460 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2461 ) : CastInst(Ty, BitCast, S, Name, InsertAtEnd) {
2462 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
2465 //===----------------------------------------------------------------------===//
2467 //===----------------------------------------------------------------------===//
2469 CmpInst::CmpInst(const Type *ty, OtherOps op, unsigned short predicate,
2470 Value *LHS, Value *RHS, const std::string &Name,
2471 Instruction *InsertBefore)
2472 : Instruction(ty, op,
2473 OperandTraits<CmpInst>::op_begin(this),
2474 OperandTraits<CmpInst>::operands(this),
2478 SubclassData = predicate;
2482 CmpInst::CmpInst(const Type *ty, OtherOps op, unsigned short predicate,
2483 Value *LHS, Value *RHS, const std::string &Name,
2484 BasicBlock *InsertAtEnd)
2485 : Instruction(ty, op,
2486 OperandTraits<CmpInst>::op_begin(this),
2487 OperandTraits<CmpInst>::operands(this),
2491 SubclassData = predicate;
2496 CmpInst::Create(OtherOps Op, unsigned short predicate, Value *S1, Value *S2,
2497 const std::string &Name, Instruction *InsertBefore) {
2498 if (Op == Instruction::ICmp) {
2499 return new ICmpInst(CmpInst::Predicate(predicate), S1, S2, Name,
2502 if (Op == Instruction::FCmp) {
2503 return new FCmpInst(CmpInst::Predicate(predicate), S1, S2, Name,
2506 if (Op == Instruction::VICmp) {
2507 return new VICmpInst(CmpInst::Predicate(predicate), S1, S2, Name,
2510 return new VFCmpInst(CmpInst::Predicate(predicate), S1, S2, Name,
2515 CmpInst::Create(OtherOps Op, unsigned short predicate, Value *S1, Value *S2,
2516 const std::string &Name, BasicBlock *InsertAtEnd) {
2517 if (Op == Instruction::ICmp) {
2518 return new ICmpInst(CmpInst::Predicate(predicate), S1, S2, Name,
2521 if (Op == Instruction::FCmp) {
2522 return new FCmpInst(CmpInst::Predicate(predicate), S1, S2, Name,
2525 if (Op == Instruction::VICmp) {
2526 return new VICmpInst(CmpInst::Predicate(predicate), S1, S2, Name,
2529 return new VFCmpInst(CmpInst::Predicate(predicate), S1, S2, Name,
2533 void CmpInst::swapOperands() {
2534 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2537 cast<FCmpInst>(this)->swapOperands();
2540 bool CmpInst::isCommutative() {
2541 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2542 return IC->isCommutative();
2543 return cast<FCmpInst>(this)->isCommutative();
2546 bool CmpInst::isEquality() {
2547 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2548 return IC->isEquality();
2549 return cast<FCmpInst>(this)->isEquality();
2553 CmpInst::Predicate CmpInst::getInversePredicate(Predicate pred) {
2555 default: assert(!"Unknown cmp predicate!");
2556 case ICMP_EQ: return ICMP_NE;
2557 case ICMP_NE: return ICMP_EQ;
2558 case ICMP_UGT: return ICMP_ULE;
2559 case ICMP_ULT: return ICMP_UGE;
2560 case ICMP_UGE: return ICMP_ULT;
2561 case ICMP_ULE: return ICMP_UGT;
2562 case ICMP_SGT: return ICMP_SLE;
2563 case ICMP_SLT: return ICMP_SGE;
2564 case ICMP_SGE: return ICMP_SLT;
2565 case ICMP_SLE: return ICMP_SGT;
2567 case FCMP_OEQ: return FCMP_UNE;
2568 case FCMP_ONE: return FCMP_UEQ;
2569 case FCMP_OGT: return FCMP_ULE;
2570 case FCMP_OLT: return FCMP_UGE;
2571 case FCMP_OGE: return FCMP_ULT;
2572 case FCMP_OLE: return FCMP_UGT;
2573 case FCMP_UEQ: return FCMP_ONE;
2574 case FCMP_UNE: return FCMP_OEQ;
2575 case FCMP_UGT: return FCMP_OLE;
2576 case FCMP_ULT: return FCMP_OGE;
2577 case FCMP_UGE: return FCMP_OLT;
2578 case FCMP_ULE: return FCMP_OGT;
2579 case FCMP_ORD: return FCMP_UNO;
2580 case FCMP_UNO: return FCMP_ORD;
2581 case FCMP_TRUE: return FCMP_FALSE;
2582 case FCMP_FALSE: return FCMP_TRUE;
2586 ICmpInst::Predicate ICmpInst::getSignedPredicate(Predicate pred) {
2588 default: assert(! "Unknown icmp predicate!");
2589 case ICMP_EQ: case ICMP_NE:
2590 case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE:
2592 case ICMP_UGT: return ICMP_SGT;
2593 case ICMP_ULT: return ICMP_SLT;
2594 case ICMP_UGE: return ICMP_SGE;
2595 case ICMP_ULE: return ICMP_SLE;
2599 ICmpInst::Predicate ICmpInst::getUnsignedPredicate(Predicate pred) {
2601 default: assert(! "Unknown icmp predicate!");
2602 case ICMP_EQ: case ICMP_NE:
2603 case ICMP_UGT: case ICMP_ULT: case ICMP_UGE: case ICMP_ULE:
2605 case ICMP_SGT: return ICMP_UGT;
2606 case ICMP_SLT: return ICMP_ULT;
2607 case ICMP_SGE: return ICMP_UGE;
2608 case ICMP_SLE: return ICMP_ULE;
2612 bool ICmpInst::isSignedPredicate(Predicate pred) {
2614 default: assert(! "Unknown icmp predicate!");
2615 case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE:
2617 case ICMP_EQ: case ICMP_NE: case ICMP_UGT: case ICMP_ULT:
2618 case ICMP_UGE: case ICMP_ULE:
2623 /// Initialize a set of values that all satisfy the condition with C.
2626 ICmpInst::makeConstantRange(Predicate pred, const APInt &C) {
2629 uint32_t BitWidth = C.getBitWidth();
2631 default: assert(0 && "Invalid ICmp opcode to ConstantRange ctor!");
2632 case ICmpInst::ICMP_EQ: Upper++; break;
2633 case ICmpInst::ICMP_NE: Lower++; break;
2634 case ICmpInst::ICMP_ULT: Lower = APInt::getMinValue(BitWidth); break;
2635 case ICmpInst::ICMP_SLT: Lower = APInt::getSignedMinValue(BitWidth); break;
2636 case ICmpInst::ICMP_UGT:
2637 Lower++; Upper = APInt::getMinValue(BitWidth); // Min = Next(Max)
2639 case ICmpInst::ICMP_SGT:
2640 Lower++; Upper = APInt::getSignedMinValue(BitWidth); // Min = Next(Max)
2642 case ICmpInst::ICMP_ULE:
2643 Lower = APInt::getMinValue(BitWidth); Upper++;
2645 case ICmpInst::ICMP_SLE:
2646 Lower = APInt::getSignedMinValue(BitWidth); Upper++;
2648 case ICmpInst::ICMP_UGE:
2649 Upper = APInt::getMinValue(BitWidth); // Min = Next(Max)
2651 case ICmpInst::ICMP_SGE:
2652 Upper = APInt::getSignedMinValue(BitWidth); // Min = Next(Max)
2655 return ConstantRange(Lower, Upper);
2658 CmpInst::Predicate CmpInst::getSwappedPredicate(Predicate pred) {
2660 default: assert(!"Unknown cmp predicate!");
2661 case ICMP_EQ: case ICMP_NE:
2663 case ICMP_SGT: return ICMP_SLT;
2664 case ICMP_SLT: return ICMP_SGT;
2665 case ICMP_SGE: return ICMP_SLE;
2666 case ICMP_SLE: return ICMP_SGE;
2667 case ICMP_UGT: return ICMP_ULT;
2668 case ICMP_ULT: return ICMP_UGT;
2669 case ICMP_UGE: return ICMP_ULE;
2670 case ICMP_ULE: return ICMP_UGE;
2672 case FCMP_FALSE: case FCMP_TRUE:
2673 case FCMP_OEQ: case FCMP_ONE:
2674 case FCMP_UEQ: case FCMP_UNE:
2675 case FCMP_ORD: case FCMP_UNO:
2677 case FCMP_OGT: return FCMP_OLT;
2678 case FCMP_OLT: return FCMP_OGT;
2679 case FCMP_OGE: return FCMP_OLE;
2680 case FCMP_OLE: return FCMP_OGE;
2681 case FCMP_UGT: return FCMP_ULT;
2682 case FCMP_ULT: return FCMP_UGT;
2683 case FCMP_UGE: return FCMP_ULE;
2684 case FCMP_ULE: return FCMP_UGE;
2688 bool CmpInst::isUnsigned(unsigned short predicate) {
2689 switch (predicate) {
2690 default: return false;
2691 case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_ULE: case ICmpInst::ICMP_UGT:
2692 case ICmpInst::ICMP_UGE: return true;
2696 bool CmpInst::isSigned(unsigned short predicate){
2697 switch (predicate) {
2698 default: return false;
2699 case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_SLE: case ICmpInst::ICMP_SGT:
2700 case ICmpInst::ICMP_SGE: return true;
2704 bool CmpInst::isOrdered(unsigned short predicate) {
2705 switch (predicate) {
2706 default: return false;
2707 case FCmpInst::FCMP_OEQ: case FCmpInst::FCMP_ONE: case FCmpInst::FCMP_OGT:
2708 case FCmpInst::FCMP_OLT: case FCmpInst::FCMP_OGE: case FCmpInst::FCMP_OLE:
2709 case FCmpInst::FCMP_ORD: return true;
2713 bool CmpInst::isUnordered(unsigned short predicate) {
2714 switch (predicate) {
2715 default: return false;
2716 case FCmpInst::FCMP_UEQ: case FCmpInst::FCMP_UNE: case FCmpInst::FCMP_UGT:
2717 case FCmpInst::FCMP_ULT: case FCmpInst::FCMP_UGE: case FCmpInst::FCMP_ULE:
2718 case FCmpInst::FCMP_UNO: return true;
2722 //===----------------------------------------------------------------------===//
2723 // SwitchInst Implementation
2724 //===----------------------------------------------------------------------===//
2726 void SwitchInst::init(Value *Value, BasicBlock *Default, unsigned NumCases) {
2727 assert(Value && Default);
2728 ReservedSpace = 2+NumCases*2;
2730 OperandList = allocHungoffUses(ReservedSpace);
2732 OperandList[0] = Value;
2733 OperandList[1] = Default;
2736 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
2737 /// switch on and a default destination. The number of additional cases can
2738 /// be specified here to make memory allocation more efficient. This
2739 /// constructor can also autoinsert before another instruction.
2740 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
2741 Instruction *InsertBefore)
2742 : TerminatorInst(Type::VoidTy, Instruction::Switch, 0, 0, InsertBefore) {
2743 init(Value, Default, NumCases);
2746 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
2747 /// switch on and a default destination. The number of additional cases can
2748 /// be specified here to make memory allocation more efficient. This
2749 /// constructor also autoinserts at the end of the specified BasicBlock.
2750 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
2751 BasicBlock *InsertAtEnd)
2752 : TerminatorInst(Type::VoidTy, Instruction::Switch, 0, 0, InsertAtEnd) {
2753 init(Value, Default, NumCases);
2756 SwitchInst::SwitchInst(const SwitchInst &SI)
2757 : TerminatorInst(Type::VoidTy, Instruction::Switch,
2758 allocHungoffUses(SI.getNumOperands()), SI.getNumOperands()) {
2759 Use *OL = OperandList, *InOL = SI.OperandList;
2760 for (unsigned i = 0, E = SI.getNumOperands(); i != E; i+=2) {
2762 OL[i+1] = InOL[i+1];
2766 SwitchInst::~SwitchInst() {
2767 dropHungoffUses(OperandList);
2771 /// addCase - Add an entry to the switch instruction...
2773 void SwitchInst::addCase(ConstantInt *OnVal, BasicBlock *Dest) {
2774 unsigned OpNo = NumOperands;
2775 if (OpNo+2 > ReservedSpace)
2776 resizeOperands(0); // Get more space!
2777 // Initialize some new operands.
2778 assert(OpNo+1 < ReservedSpace && "Growing didn't work!");
2779 NumOperands = OpNo+2;
2780 OperandList[OpNo] = OnVal;
2781 OperandList[OpNo+1] = Dest;
2784 /// removeCase - This method removes the specified successor from the switch
2785 /// instruction. Note that this cannot be used to remove the default
2786 /// destination (successor #0).
2788 void SwitchInst::removeCase(unsigned idx) {
2789 assert(idx != 0 && "Cannot remove the default case!");
2790 assert(idx*2 < getNumOperands() && "Successor index out of range!!!");
2792 unsigned NumOps = getNumOperands();
2793 Use *OL = OperandList;
2795 // Move everything after this operand down.
2797 // FIXME: we could just swap with the end of the list, then erase. However,
2798 // client might not expect this to happen. The code as it is thrashes the
2799 // use/def lists, which is kinda lame.
2800 for (unsigned i = (idx+1)*2; i != NumOps; i += 2) {
2802 OL[i-2+1] = OL[i+1];
2805 // Nuke the last value.
2806 OL[NumOps-2].set(0);
2807 OL[NumOps-2+1].set(0);
2808 NumOperands = NumOps-2;
2811 /// resizeOperands - resize operands - This adjusts the length of the operands
2812 /// list according to the following behavior:
2813 /// 1. If NumOps == 0, grow the operand list in response to a push_back style
2814 /// of operation. This grows the number of ops by 3 times.
2815 /// 2. If NumOps > NumOperands, reserve space for NumOps operands.
2816 /// 3. If NumOps == NumOperands, trim the reserved space.
2818 void SwitchInst::resizeOperands(unsigned NumOps) {
2819 unsigned e = getNumOperands();
2822 } else if (NumOps*2 > NumOperands) {
2823 // No resize needed.
2824 if (ReservedSpace >= NumOps) return;
2825 } else if (NumOps == NumOperands) {
2826 if (ReservedSpace == NumOps) return;
2831 ReservedSpace = NumOps;
2832 Use *NewOps = allocHungoffUses(NumOps);
2833 Use *OldOps = OperandList;
2834 for (unsigned i = 0; i != e; ++i) {
2835 NewOps[i] = OldOps[i];
2837 OperandList = NewOps;
2838 if (OldOps) Use::zap(OldOps, OldOps + e, true);
2842 BasicBlock *SwitchInst::getSuccessorV(unsigned idx) const {
2843 return getSuccessor(idx);
2845 unsigned SwitchInst::getNumSuccessorsV() const {
2846 return getNumSuccessors();
2848 void SwitchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
2849 setSuccessor(idx, B);
2852 // Define these methods here so vtables don't get emitted into every translation
2853 // unit that uses these classes.
2855 GetElementPtrInst *GetElementPtrInst::clone() const {
2856 return new(getNumOperands()) GetElementPtrInst(*this);
2859 BinaryOperator *BinaryOperator::clone() const {
2860 return Create(getOpcode(), Op<0>(), Op<1>());
2863 FCmpInst* FCmpInst::clone() const {
2864 return new FCmpInst(getPredicate(), Op<0>(), Op<1>());
2866 ICmpInst* ICmpInst::clone() const {
2867 return new ICmpInst(getPredicate(), Op<0>(), Op<1>());
2870 VFCmpInst* VFCmpInst::clone() const {
2871 return new VFCmpInst(getPredicate(), Op<0>(), Op<1>());
2873 VICmpInst* VICmpInst::clone() const {
2874 return new VICmpInst(getPredicate(), Op<0>(), Op<1>());
2877 ExtractValueInst *ExtractValueInst::clone() const {
2878 return new ExtractValueInst(*this);
2880 InsertValueInst *InsertValueInst::clone() const {
2881 return new InsertValueInst(*this);
2885 MallocInst *MallocInst::clone() const { return new MallocInst(*this); }
2886 AllocaInst *AllocaInst::clone() const { return new AllocaInst(*this); }
2887 FreeInst *FreeInst::clone() const { return new FreeInst(getOperand(0)); }
2888 LoadInst *LoadInst::clone() const { return new LoadInst(*this); }
2889 StoreInst *StoreInst::clone() const { return new StoreInst(*this); }
2890 CastInst *TruncInst::clone() const { return new TruncInst(*this); }
2891 CastInst *ZExtInst::clone() const { return new ZExtInst(*this); }
2892 CastInst *SExtInst::clone() const { return new SExtInst(*this); }
2893 CastInst *FPTruncInst::clone() const { return new FPTruncInst(*this); }
2894 CastInst *FPExtInst::clone() const { return new FPExtInst(*this); }
2895 CastInst *UIToFPInst::clone() const { return new UIToFPInst(*this); }
2896 CastInst *SIToFPInst::clone() const { return new SIToFPInst(*this); }
2897 CastInst *FPToUIInst::clone() const { return new FPToUIInst(*this); }
2898 CastInst *FPToSIInst::clone() const { return new FPToSIInst(*this); }
2899 CastInst *PtrToIntInst::clone() const { return new PtrToIntInst(*this); }
2900 CastInst *IntToPtrInst::clone() const { return new IntToPtrInst(*this); }
2901 CastInst *BitCastInst::clone() const { return new BitCastInst(*this); }
2902 CallInst *CallInst::clone() const {
2903 return new(getNumOperands()) CallInst(*this);
2905 SelectInst *SelectInst::clone() const {
2906 return new(getNumOperands()) SelectInst(*this);
2908 VAArgInst *VAArgInst::clone() const { return new VAArgInst(*this); }
2910 ExtractElementInst *ExtractElementInst::clone() const {
2911 return new ExtractElementInst(*this);
2913 InsertElementInst *InsertElementInst::clone() const {
2914 return InsertElementInst::Create(*this);
2916 ShuffleVectorInst *ShuffleVectorInst::clone() const {
2917 return new ShuffleVectorInst(*this);
2919 PHINode *PHINode::clone() const { return new PHINode(*this); }
2920 ReturnInst *ReturnInst::clone() const {
2921 return new(getNumOperands()) ReturnInst(*this);
2923 BranchInst *BranchInst::clone() const {
2924 return new(getNumOperands()) BranchInst(*this);
2926 SwitchInst *SwitchInst::clone() const { return new SwitchInst(*this); }
2927 InvokeInst *InvokeInst::clone() const {
2928 return new(getNumOperands()) InvokeInst(*this);
2930 UnwindInst *UnwindInst::clone() const { return new UnwindInst(); }
2931 UnreachableInst *UnreachableInst::clone() const { return new UnreachableInst();}