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/Operator.h"
20 #include "llvm/Support/ErrorHandling.h"
21 #include "llvm/Support/CallSite.h"
22 #include "llvm/Support/ConstantRange.h"
23 #include "llvm/Support/MathExtras.h"
26 //===----------------------------------------------------------------------===//
28 //===----------------------------------------------------------------------===//
30 #define CALLSITE_DELEGATE_GETTER(METHOD) \
31 Instruction *II(getInstruction()); \
33 ? cast<CallInst>(II)->METHOD \
34 : cast<InvokeInst>(II)->METHOD
36 #define CALLSITE_DELEGATE_SETTER(METHOD) \
37 Instruction *II(getInstruction()); \
39 cast<CallInst>(II)->METHOD; \
41 cast<InvokeInst>(II)->METHOD
43 CallSite::CallSite(Instruction *C) {
44 assert((isa<CallInst>(C) || isa<InvokeInst>(C)) && "Not a call!");
46 I.setInt(isa<CallInst>(C));
48 unsigned CallSite::getCallingConv() const {
49 CALLSITE_DELEGATE_GETTER(getCallingConv());
51 void CallSite::setCallingConv(unsigned CC) {
52 CALLSITE_DELEGATE_SETTER(setCallingConv(CC));
54 const AttrListPtr &CallSite::getAttributes() const {
55 CALLSITE_DELEGATE_GETTER(getAttributes());
57 void CallSite::setAttributes(const AttrListPtr &PAL) {
58 CALLSITE_DELEGATE_SETTER(setAttributes(PAL));
60 bool CallSite::paramHasAttr(uint16_t i, Attributes attr) const {
61 CALLSITE_DELEGATE_GETTER(paramHasAttr(i, attr));
63 uint16_t CallSite::getParamAlignment(uint16_t i) const {
64 CALLSITE_DELEGATE_GETTER(getParamAlignment(i));
66 bool CallSite::doesNotAccessMemory() const {
67 CALLSITE_DELEGATE_GETTER(doesNotAccessMemory());
69 void CallSite::setDoesNotAccessMemory(bool doesNotAccessMemory) {
70 CALLSITE_DELEGATE_SETTER(setDoesNotAccessMemory(doesNotAccessMemory));
72 bool CallSite::onlyReadsMemory() const {
73 CALLSITE_DELEGATE_GETTER(onlyReadsMemory());
75 void CallSite::setOnlyReadsMemory(bool onlyReadsMemory) {
76 CALLSITE_DELEGATE_SETTER(setOnlyReadsMemory(onlyReadsMemory));
78 bool CallSite::doesNotReturn() const {
79 CALLSITE_DELEGATE_GETTER(doesNotReturn());
81 void CallSite::setDoesNotReturn(bool doesNotReturn) {
82 CALLSITE_DELEGATE_SETTER(setDoesNotReturn(doesNotReturn));
84 bool CallSite::doesNotThrow() const {
85 CALLSITE_DELEGATE_GETTER(doesNotThrow());
87 void CallSite::setDoesNotThrow(bool doesNotThrow) {
88 CALLSITE_DELEGATE_SETTER(setDoesNotThrow(doesNotThrow));
91 bool CallSite::hasArgument(const Value *Arg) const {
92 for (arg_iterator AI = this->arg_begin(), E = this->arg_end(); AI != E; ++AI)
98 #undef CALLSITE_DELEGATE_GETTER
99 #undef CALLSITE_DELEGATE_SETTER
101 //===----------------------------------------------------------------------===//
102 // TerminatorInst Class
103 //===----------------------------------------------------------------------===//
105 // Out of line virtual method, so the vtable, etc has a home.
106 TerminatorInst::~TerminatorInst() {
109 //===----------------------------------------------------------------------===//
110 // UnaryInstruction Class
111 //===----------------------------------------------------------------------===//
113 // Out of line virtual method, so the vtable, etc has a home.
114 UnaryInstruction::~UnaryInstruction() {
117 //===----------------------------------------------------------------------===//
119 //===----------------------------------------------------------------------===//
121 /// areInvalidOperands - Return a string if the specified operands are invalid
122 /// for a select operation, otherwise return null.
123 const char *SelectInst::areInvalidOperands(Value *Op0, Value *Op1, Value *Op2) {
124 if (Op1->getType() != Op2->getType())
125 return "both values to select must have same type";
127 if (const VectorType *VT = dyn_cast<VectorType>(Op0->getType())) {
129 if (VT->getElementType() != Type::Int1Ty)
130 return "vector select condition element type must be i1";
131 const VectorType *ET = dyn_cast<VectorType>(Op1->getType());
133 return "selected values for vector select must be vectors";
134 if (ET->getNumElements() != VT->getNumElements())
135 return "vector select requires selected vectors to have "
136 "the same vector length as select condition";
137 } else if (Op0->getType() != Type::Int1Ty) {
138 return "select condition must be i1 or <n x i1>";
144 //===----------------------------------------------------------------------===//
146 //===----------------------------------------------------------------------===//
148 PHINode::PHINode(const PHINode &PN)
149 : Instruction(PN.getType(), Instruction::PHI,
150 allocHungoffUses(PN.getNumOperands()), PN.getNumOperands()),
151 ReservedSpace(PN.getNumOperands()) {
152 Use *OL = OperandList;
153 for (unsigned i = 0, e = PN.getNumOperands(); i != e; i+=2) {
154 OL[i] = PN.getOperand(i);
155 OL[i+1] = PN.getOperand(i+1);
159 PHINode::~PHINode() {
161 dropHungoffUses(OperandList);
164 // removeIncomingValue - Remove an incoming value. This is useful if a
165 // predecessor basic block is deleted.
166 Value *PHINode::removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty) {
167 unsigned NumOps = getNumOperands();
168 Use *OL = OperandList;
169 assert(Idx*2 < NumOps && "BB not in PHI node!");
170 Value *Removed = OL[Idx*2];
172 // Move everything after this operand down.
174 // FIXME: we could just swap with the end of the list, then erase. However,
175 // client might not expect this to happen. The code as it is thrashes the
176 // use/def lists, which is kinda lame.
177 for (unsigned i = (Idx+1)*2; i != NumOps; i += 2) {
182 // Nuke the last value.
184 OL[NumOps-2+1].set(0);
185 NumOperands = NumOps-2;
187 // If the PHI node is dead, because it has zero entries, nuke it now.
188 if (NumOps == 2 && DeletePHIIfEmpty) {
189 // If anyone is using this PHI, make them use a dummy value instead...
190 replaceAllUsesWith(getType()->getContext().getUndef(getType()));
196 /// resizeOperands - resize operands - This adjusts the length of the operands
197 /// list according to the following behavior:
198 /// 1. If NumOps == 0, grow the operand list in response to a push_back style
199 /// of operation. This grows the number of ops by 1.5 times.
200 /// 2. If NumOps > NumOperands, reserve space for NumOps operands.
201 /// 3. If NumOps == NumOperands, trim the reserved space.
203 void PHINode::resizeOperands(unsigned NumOps) {
204 unsigned e = getNumOperands();
207 if (NumOps < 4) NumOps = 4; // 4 op PHI nodes are VERY common.
208 } else if (NumOps*2 > NumOperands) {
210 if (ReservedSpace >= NumOps) return;
211 } else if (NumOps == NumOperands) {
212 if (ReservedSpace == NumOps) return;
217 ReservedSpace = NumOps;
218 Use *OldOps = OperandList;
219 Use *NewOps = allocHungoffUses(NumOps);
220 std::copy(OldOps, OldOps + e, NewOps);
221 OperandList = NewOps;
222 if (OldOps) Use::zap(OldOps, OldOps + e, true);
225 /// hasConstantValue - If the specified PHI node always merges together the same
226 /// value, return the value, otherwise return null.
228 Value *PHINode::hasConstantValue(bool AllowNonDominatingInstruction) const {
229 // If the PHI node only has one incoming value, eliminate the PHI node...
230 if (getNumIncomingValues() == 1) {
231 if (getIncomingValue(0) != this) // not X = phi X
232 return getIncomingValue(0);
235 getType()->getContext().getUndef(getType()); // Self cycle is dead.
238 // Otherwise if all of the incoming values are the same for the PHI, replace
239 // the PHI node with the incoming value.
242 bool HasUndefInput = false;
243 for (unsigned i = 0, e = getNumIncomingValues(); i != e; ++i)
244 if (isa<UndefValue>(getIncomingValue(i))) {
245 HasUndefInput = true;
246 } else if (getIncomingValue(i) != this) { // Not the PHI node itself...
247 if (InVal && getIncomingValue(i) != InVal)
248 return 0; // Not the same, bail out.
250 InVal = getIncomingValue(i);
253 // The only case that could cause InVal to be null is if we have a PHI node
254 // that only has entries for itself. In this case, there is no entry into the
255 // loop, so kill the PHI.
257 if (InVal == 0) InVal = getType()->getContext().getUndef(getType());
259 // If we have a PHI node like phi(X, undef, X), where X is defined by some
260 // instruction, we cannot always return X as the result of the PHI node. Only
261 // do this if X is not an instruction (thus it must dominate the PHI block),
262 // or if the client is prepared to deal with this possibility.
263 if (HasUndefInput && !AllowNonDominatingInstruction)
264 if (Instruction *IV = dyn_cast<Instruction>(InVal))
265 // If it's in the entry block, it dominates everything.
266 if (IV->getParent() != &IV->getParent()->getParent()->getEntryBlock() ||
268 return 0; // Cannot guarantee that InVal dominates this PHINode.
270 // All of the incoming values are the same, return the value now.
275 //===----------------------------------------------------------------------===//
276 // CallInst Implementation
277 //===----------------------------------------------------------------------===//
279 CallInst::~CallInst() {
282 void CallInst::init(Value *Func, Value* const *Params, unsigned NumParams) {
283 assert(NumOperands == NumParams+1 && "NumOperands not set up?");
284 Use *OL = OperandList;
287 const FunctionType *FTy =
288 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
289 FTy = FTy; // silence warning.
291 assert((NumParams == FTy->getNumParams() ||
292 (FTy->isVarArg() && NumParams > FTy->getNumParams())) &&
293 "Calling a function with bad signature!");
294 for (unsigned i = 0; i != NumParams; ++i) {
295 assert((i >= FTy->getNumParams() ||
296 FTy->getParamType(i) == Params[i]->getType()) &&
297 "Calling a function with a bad signature!");
302 void CallInst::init(Value *Func, Value *Actual1, Value *Actual2) {
303 assert(NumOperands == 3 && "NumOperands not set up?");
304 Use *OL = OperandList;
309 const FunctionType *FTy =
310 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
311 FTy = FTy; // silence warning.
313 assert((FTy->getNumParams() == 2 ||
314 (FTy->isVarArg() && FTy->getNumParams() < 2)) &&
315 "Calling a function with bad signature");
316 assert((0 >= FTy->getNumParams() ||
317 FTy->getParamType(0) == Actual1->getType()) &&
318 "Calling a function with a bad signature!");
319 assert((1 >= FTy->getNumParams() ||
320 FTy->getParamType(1) == Actual2->getType()) &&
321 "Calling a function with a bad signature!");
324 void CallInst::init(Value *Func, Value *Actual) {
325 assert(NumOperands == 2 && "NumOperands not set up?");
326 Use *OL = OperandList;
330 const FunctionType *FTy =
331 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
332 FTy = FTy; // silence warning.
334 assert((FTy->getNumParams() == 1 ||
335 (FTy->isVarArg() && FTy->getNumParams() == 0)) &&
336 "Calling a function with bad signature");
337 assert((0 == FTy->getNumParams() ||
338 FTy->getParamType(0) == Actual->getType()) &&
339 "Calling a function with a bad signature!");
342 void CallInst::init(Value *Func) {
343 assert(NumOperands == 1 && "NumOperands not set up?");
344 Use *OL = OperandList;
347 const FunctionType *FTy =
348 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
349 FTy = FTy; // silence warning.
351 assert(FTy->getNumParams() == 0 && "Calling a function with bad signature");
354 CallInst::CallInst(Value *Func, Value* Actual, const std::string &Name,
355 Instruction *InsertBefore)
356 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
357 ->getElementType())->getReturnType(),
359 OperandTraits<CallInst>::op_end(this) - 2,
365 CallInst::CallInst(Value *Func, Value* Actual, const std::string &Name,
366 BasicBlock *InsertAtEnd)
367 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
368 ->getElementType())->getReturnType(),
370 OperandTraits<CallInst>::op_end(this) - 2,
375 CallInst::CallInst(Value *Func, const std::string &Name,
376 Instruction *InsertBefore)
377 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
378 ->getElementType())->getReturnType(),
380 OperandTraits<CallInst>::op_end(this) - 1,
386 CallInst::CallInst(Value *Func, const std::string &Name,
387 BasicBlock *InsertAtEnd)
388 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
389 ->getElementType())->getReturnType(),
391 OperandTraits<CallInst>::op_end(this) - 1,
397 CallInst::CallInst(const CallInst &CI)
398 : Instruction(CI.getType(), Instruction::Call,
399 OperandTraits<CallInst>::op_end(this) - CI.getNumOperands(),
400 CI.getNumOperands()) {
401 setAttributes(CI.getAttributes());
402 SubclassData = CI.SubclassData;
403 Use *OL = OperandList;
404 Use *InOL = CI.OperandList;
405 for (unsigned i = 0, e = CI.getNumOperands(); i != e; ++i)
409 void CallInst::addAttribute(unsigned i, Attributes attr) {
410 AttrListPtr PAL = getAttributes();
411 PAL = PAL.addAttr(i, attr);
415 void CallInst::removeAttribute(unsigned i, Attributes attr) {
416 AttrListPtr PAL = getAttributes();
417 PAL = PAL.removeAttr(i, attr);
421 bool CallInst::paramHasAttr(unsigned i, Attributes attr) const {
422 if (AttributeList.paramHasAttr(i, attr))
424 if (const Function *F = getCalledFunction())
425 return F->paramHasAttr(i, attr);
430 //===----------------------------------------------------------------------===//
431 // InvokeInst Implementation
432 //===----------------------------------------------------------------------===//
434 void InvokeInst::init(Value *Fn, BasicBlock *IfNormal, BasicBlock *IfException,
435 Value* const *Args, unsigned NumArgs) {
436 assert(NumOperands == 3+NumArgs && "NumOperands not set up?");
437 Use *OL = OperandList;
441 const FunctionType *FTy =
442 cast<FunctionType>(cast<PointerType>(Fn->getType())->getElementType());
443 FTy = FTy; // silence warning.
445 assert(((NumArgs == FTy->getNumParams()) ||
446 (FTy->isVarArg() && NumArgs > FTy->getNumParams())) &&
447 "Calling a function with bad signature");
449 for (unsigned i = 0, e = NumArgs; i != e; i++) {
450 assert((i >= FTy->getNumParams() ||
451 FTy->getParamType(i) == Args[i]->getType()) &&
452 "Invoking a function with a bad signature!");
458 InvokeInst::InvokeInst(const InvokeInst &II)
459 : TerminatorInst(II.getType(), Instruction::Invoke,
460 OperandTraits<InvokeInst>::op_end(this)
461 - II.getNumOperands(),
462 II.getNumOperands()) {
463 setAttributes(II.getAttributes());
464 SubclassData = II.SubclassData;
465 Use *OL = OperandList, *InOL = II.OperandList;
466 for (unsigned i = 0, e = II.getNumOperands(); i != e; ++i)
470 BasicBlock *InvokeInst::getSuccessorV(unsigned idx) const {
471 return getSuccessor(idx);
473 unsigned InvokeInst::getNumSuccessorsV() const {
474 return getNumSuccessors();
476 void InvokeInst::setSuccessorV(unsigned idx, BasicBlock *B) {
477 return setSuccessor(idx, B);
480 bool InvokeInst::paramHasAttr(unsigned i, Attributes attr) const {
481 if (AttributeList.paramHasAttr(i, attr))
483 if (const Function *F = getCalledFunction())
484 return F->paramHasAttr(i, attr);
488 void InvokeInst::addAttribute(unsigned i, Attributes attr) {
489 AttrListPtr PAL = getAttributes();
490 PAL = PAL.addAttr(i, attr);
494 void InvokeInst::removeAttribute(unsigned i, Attributes attr) {
495 AttrListPtr PAL = getAttributes();
496 PAL = PAL.removeAttr(i, attr);
501 //===----------------------------------------------------------------------===//
502 // ReturnInst Implementation
503 //===----------------------------------------------------------------------===//
505 ReturnInst::ReturnInst(const ReturnInst &RI)
506 : TerminatorInst(Type::VoidTy, Instruction::Ret,
507 OperandTraits<ReturnInst>::op_end(this) -
509 RI.getNumOperands()) {
510 if (RI.getNumOperands())
511 Op<0>() = RI.Op<0>();
514 ReturnInst::ReturnInst(Value *retVal, Instruction *InsertBefore)
515 : TerminatorInst(Type::VoidTy, Instruction::Ret,
516 OperandTraits<ReturnInst>::op_end(this) - !!retVal, !!retVal,
521 ReturnInst::ReturnInst(Value *retVal, BasicBlock *InsertAtEnd)
522 : TerminatorInst(Type::VoidTy, Instruction::Ret,
523 OperandTraits<ReturnInst>::op_end(this) - !!retVal, !!retVal,
528 ReturnInst::ReturnInst(BasicBlock *InsertAtEnd)
529 : TerminatorInst(Type::VoidTy, Instruction::Ret,
530 OperandTraits<ReturnInst>::op_end(this), 0, InsertAtEnd) {
533 unsigned ReturnInst::getNumSuccessorsV() const {
534 return getNumSuccessors();
537 /// Out-of-line ReturnInst method, put here so the C++ compiler can choose to
538 /// emit the vtable for the class in this translation unit.
539 void ReturnInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
540 llvm_unreachable("ReturnInst has no successors!");
543 BasicBlock *ReturnInst::getSuccessorV(unsigned idx) const {
544 llvm_unreachable("ReturnInst has no successors!");
548 ReturnInst::~ReturnInst() {
551 //===----------------------------------------------------------------------===//
552 // UnwindInst Implementation
553 //===----------------------------------------------------------------------===//
555 UnwindInst::UnwindInst(Instruction *InsertBefore)
556 : TerminatorInst(Type::VoidTy, Instruction::Unwind, 0, 0, InsertBefore) {
558 UnwindInst::UnwindInst(BasicBlock *InsertAtEnd)
559 : TerminatorInst(Type::VoidTy, Instruction::Unwind, 0, 0, InsertAtEnd) {
563 unsigned UnwindInst::getNumSuccessorsV() const {
564 return getNumSuccessors();
567 void UnwindInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
568 llvm_unreachable("UnwindInst has no successors!");
571 BasicBlock *UnwindInst::getSuccessorV(unsigned idx) const {
572 llvm_unreachable("UnwindInst has no successors!");
576 //===----------------------------------------------------------------------===//
577 // UnreachableInst Implementation
578 //===----------------------------------------------------------------------===//
580 UnreachableInst::UnreachableInst(Instruction *InsertBefore)
581 : TerminatorInst(Type::VoidTy, Instruction::Unreachable, 0, 0, InsertBefore) {
583 UnreachableInst::UnreachableInst(BasicBlock *InsertAtEnd)
584 : TerminatorInst(Type::VoidTy, Instruction::Unreachable, 0, 0, InsertAtEnd) {
587 unsigned UnreachableInst::getNumSuccessorsV() const {
588 return getNumSuccessors();
591 void UnreachableInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
592 llvm_unreachable("UnwindInst has no successors!");
595 BasicBlock *UnreachableInst::getSuccessorV(unsigned idx) const {
596 llvm_unreachable("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 Op<-1>() = BI.Op<-1>();
657 if (BI.getNumOperands() != 1) {
658 assert(BI.getNumOperands() == 3 && "BR can have 1 or 3 operands!");
659 Op<-3>() = BI.Op<-3>();
660 Op<-2>() = BI.Op<-2>();
665 Use* Use::getPrefix() {
666 PointerIntPair<Use**, 2, PrevPtrTag> &PotentialPrefix(this[-1].Prev);
667 if (PotentialPrefix.getOpaqueValue())
670 return reinterpret_cast<Use*>((char*)&PotentialPrefix + 1);
673 BranchInst::~BranchInst() {
674 if (NumOperands == 1) {
675 if (Use *Prefix = OperandList->getPrefix()) {
678 // mark OperandList to have a special value for scrutiny
679 // by baseclass destructors and operator delete
680 OperandList = Prefix;
683 OperandList = op_begin();
689 BasicBlock *BranchInst::getSuccessorV(unsigned idx) const {
690 return getSuccessor(idx);
692 unsigned BranchInst::getNumSuccessorsV() const {
693 return getNumSuccessors();
695 void BranchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
696 setSuccessor(idx, B);
700 //===----------------------------------------------------------------------===//
701 // AllocationInst Implementation
702 //===----------------------------------------------------------------------===//
704 static Value *getAISize(LLVMContext &Context, Value *Amt) {
706 Amt = ConstantInt::get(Type::Int32Ty, 1);
708 assert(!isa<BasicBlock>(Amt) &&
709 "Passed basic block into allocation size parameter! Use other ctor");
710 assert(Amt->getType() == Type::Int32Ty &&
711 "Malloc/Allocation array size is not a 32-bit integer!");
716 AllocationInst::AllocationInst(const Type *Ty, Value *ArraySize, unsigned iTy,
717 unsigned Align, const std::string &Name,
718 Instruction *InsertBefore)
719 : UnaryInstruction(Ty->getContext().getPointerTypeUnqual(Ty), iTy,
720 getAISize(Ty->getContext(), ArraySize), InsertBefore) {
722 assert(Ty != Type::VoidTy && "Cannot allocate void!");
726 AllocationInst::AllocationInst(const Type *Ty, Value *ArraySize, unsigned iTy,
727 unsigned Align, const std::string &Name,
728 BasicBlock *InsertAtEnd)
729 : UnaryInstruction(Ty->getContext().getPointerTypeUnqual(Ty), iTy,
730 getAISize(Ty->getContext(), ArraySize), InsertAtEnd) {
732 assert(Ty != Type::VoidTy && "Cannot allocate void!");
736 // Out of line virtual method, so the vtable, etc has a home.
737 AllocationInst::~AllocationInst() {
740 void AllocationInst::setAlignment(unsigned Align) {
741 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
742 SubclassData = Log2_32(Align) + 1;
743 assert(getAlignment() == Align && "Alignment representation error!");
746 bool AllocationInst::isArrayAllocation() const {
747 if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(0)))
748 return CI->getZExtValue() != 1;
752 const Type *AllocationInst::getAllocatedType() const {
753 return getType()->getElementType();
756 AllocaInst::AllocaInst(const AllocaInst &AI)
757 : AllocationInst(AI.getType()->getElementType(),
758 (Value*)AI.getOperand(0), Instruction::Alloca,
762 /// isStaticAlloca - Return true if this alloca is in the entry block of the
763 /// function and is a constant size. If so, the code generator will fold it
764 /// into the prolog/epilog code, so it is basically free.
765 bool AllocaInst::isStaticAlloca() const {
766 // Must be constant size.
767 if (!isa<ConstantInt>(getArraySize())) return false;
769 // Must be in the entry block.
770 const BasicBlock *Parent = getParent();
771 return Parent == &Parent->getParent()->front();
774 MallocInst::MallocInst(const MallocInst &MI)
775 : AllocationInst(MI.getType()->getElementType(),
776 (Value*)MI.getOperand(0), Instruction::Malloc,
780 //===----------------------------------------------------------------------===//
781 // FreeInst Implementation
782 //===----------------------------------------------------------------------===//
784 void FreeInst::AssertOK() {
785 assert(isa<PointerType>(getOperand(0)->getType()) &&
786 "Can not free something of nonpointer type!");
789 FreeInst::FreeInst(Value *Ptr, Instruction *InsertBefore)
790 : UnaryInstruction(Type::VoidTy, Free, Ptr, InsertBefore) {
794 FreeInst::FreeInst(Value *Ptr, BasicBlock *InsertAtEnd)
795 : UnaryInstruction(Type::VoidTy, Free, Ptr, InsertAtEnd) {
800 //===----------------------------------------------------------------------===//
801 // LoadInst Implementation
802 //===----------------------------------------------------------------------===//
804 void LoadInst::AssertOK() {
805 assert(isa<PointerType>(getOperand(0)->getType()) &&
806 "Ptr must have pointer type.");
809 LoadInst::LoadInst(Value *Ptr, const std::string &Name, Instruction *InsertBef)
810 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
811 Load, Ptr, InsertBef) {
818 LoadInst::LoadInst(Value *Ptr, const std::string &Name, BasicBlock *InsertAE)
819 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
820 Load, Ptr, InsertAE) {
827 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile,
828 Instruction *InsertBef)
829 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
830 Load, Ptr, InsertBef) {
831 setVolatile(isVolatile);
837 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile,
838 unsigned Align, Instruction *InsertBef)
839 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
840 Load, Ptr, InsertBef) {
841 setVolatile(isVolatile);
847 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile,
848 unsigned Align, BasicBlock *InsertAE)
849 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
850 Load, Ptr, InsertAE) {
851 setVolatile(isVolatile);
857 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile,
858 BasicBlock *InsertAE)
859 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
860 Load, Ptr, InsertAE) {
861 setVolatile(isVolatile);
869 LoadInst::LoadInst(Value *Ptr, const char *Name, Instruction *InsertBef)
870 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
871 Load, Ptr, InsertBef) {
875 if (Name && Name[0]) setName(Name);
878 LoadInst::LoadInst(Value *Ptr, const char *Name, BasicBlock *InsertAE)
879 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
880 Load, Ptr, InsertAE) {
884 if (Name && Name[0]) setName(Name);
887 LoadInst::LoadInst(Value *Ptr, const char *Name, bool isVolatile,
888 Instruction *InsertBef)
889 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
890 Load, Ptr, InsertBef) {
891 setVolatile(isVolatile);
894 if (Name && Name[0]) setName(Name);
897 LoadInst::LoadInst(Value *Ptr, const char *Name, bool isVolatile,
898 BasicBlock *InsertAE)
899 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
900 Load, Ptr, InsertAE) {
901 setVolatile(isVolatile);
904 if (Name && Name[0]) setName(Name);
907 void LoadInst::setAlignment(unsigned Align) {
908 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
909 SubclassData = (SubclassData & 1) | ((Log2_32(Align)+1)<<1);
912 //===----------------------------------------------------------------------===//
913 // StoreInst Implementation
914 //===----------------------------------------------------------------------===//
916 void StoreInst::AssertOK() {
917 assert(getOperand(0) && getOperand(1) && "Both operands must be non-null!");
918 assert(isa<PointerType>(getOperand(1)->getType()) &&
919 "Ptr must have pointer type!");
920 assert(getOperand(0)->getType() ==
921 cast<PointerType>(getOperand(1)->getType())->getElementType()
922 && "Ptr must be a pointer to Val type!");
926 StoreInst::StoreInst(Value *val, Value *addr, Instruction *InsertBefore)
927 : Instruction(Type::VoidTy, Store,
928 OperandTraits<StoreInst>::op_begin(this),
929 OperandTraits<StoreInst>::operands(this),
938 StoreInst::StoreInst(Value *val, Value *addr, BasicBlock *InsertAtEnd)
939 : Instruction(Type::VoidTy, Store,
940 OperandTraits<StoreInst>::op_begin(this),
941 OperandTraits<StoreInst>::operands(this),
950 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
951 Instruction *InsertBefore)
952 : Instruction(Type::VoidTy, Store,
953 OperandTraits<StoreInst>::op_begin(this),
954 OperandTraits<StoreInst>::operands(this),
958 setVolatile(isVolatile);
963 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
964 unsigned Align, Instruction *InsertBefore)
965 : Instruction(Type::VoidTy, Store,
966 OperandTraits<StoreInst>::op_begin(this),
967 OperandTraits<StoreInst>::operands(this),
971 setVolatile(isVolatile);
976 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
977 unsigned Align, BasicBlock *InsertAtEnd)
978 : Instruction(Type::VoidTy, Store,
979 OperandTraits<StoreInst>::op_begin(this),
980 OperandTraits<StoreInst>::operands(this),
984 setVolatile(isVolatile);
989 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
990 BasicBlock *InsertAtEnd)
991 : Instruction(Type::VoidTy, Store,
992 OperandTraits<StoreInst>::op_begin(this),
993 OperandTraits<StoreInst>::operands(this),
997 setVolatile(isVolatile);
1002 void StoreInst::setAlignment(unsigned Align) {
1003 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
1004 SubclassData = (SubclassData & 1) | ((Log2_32(Align)+1)<<1);
1007 //===----------------------------------------------------------------------===//
1008 // GetElementPtrInst Implementation
1009 //===----------------------------------------------------------------------===//
1011 static unsigned retrieveAddrSpace(const Value *Val) {
1012 return cast<PointerType>(Val->getType())->getAddressSpace();
1015 void GetElementPtrInst::init(Value *Ptr, Value* const *Idx, unsigned NumIdx,
1016 const std::string &Name) {
1017 assert(NumOperands == 1+NumIdx && "NumOperands not initialized?");
1018 Use *OL = OperandList;
1021 for (unsigned i = 0; i != NumIdx; ++i)
1027 void GetElementPtrInst::init(Value *Ptr, Value *Idx, const std::string &Name) {
1028 assert(NumOperands == 2 && "NumOperands not initialized?");
1029 Use *OL = OperandList;
1036 GetElementPtrInst::GetElementPtrInst(const GetElementPtrInst &GEPI)
1037 : Instruction(GEPI.getType(), GetElementPtr,
1038 OperandTraits<GetElementPtrInst>::op_end(this)
1039 - GEPI.getNumOperands(),
1040 GEPI.getNumOperands()) {
1041 Use *OL = OperandList;
1042 Use *GEPIOL = GEPI.OperandList;
1043 for (unsigned i = 0, E = NumOperands; i != E; ++i)
1047 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx,
1048 const std::string &Name, Instruction *InBe)
1049 : Instruction(Ptr->getType()->getContext().getPointerType(
1050 checkType(getIndexedType(Ptr->getType(),Idx)), retrieveAddrSpace(Ptr)),
1052 OperandTraits<GetElementPtrInst>::op_end(this) - 2,
1054 init(Ptr, Idx, Name);
1057 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx,
1058 const std::string &Name, BasicBlock *IAE)
1059 : Instruction(Ptr->getType()->getContext().getPointerType(
1060 checkType(getIndexedType(Ptr->getType(),Idx)),
1061 retrieveAddrSpace(Ptr)),
1063 OperandTraits<GetElementPtrInst>::op_end(this) - 2,
1065 init(Ptr, Idx, Name);
1068 /// getIndexedType - Returns the type of the element that would be accessed with
1069 /// a gep instruction with the specified parameters.
1071 /// The Idxs pointer should point to a continuous piece of memory containing the
1072 /// indices, either as Value* or uint64_t.
1074 /// A null type is returned if the indices are invalid for the specified
1077 template <typename IndexTy>
1078 static const Type* getIndexedTypeInternal(const Type *Ptr, IndexTy const *Idxs,
1080 const PointerType *PTy = dyn_cast<PointerType>(Ptr);
1081 if (!PTy) return 0; // Type isn't a pointer type!
1082 const Type *Agg = PTy->getElementType();
1084 // Handle the special case of the empty set index set, which is always valid.
1088 // If there is at least one index, the top level type must be sized, otherwise
1089 // it cannot be 'stepped over'. We explicitly allow abstract types (those
1090 // that contain opaque types) under the assumption that it will be resolved to
1091 // a sane type later.
1092 if (!Agg->isSized() && !Agg->isAbstract())
1095 unsigned CurIdx = 1;
1096 for (; CurIdx != NumIdx; ++CurIdx) {
1097 const CompositeType *CT = dyn_cast<CompositeType>(Agg);
1098 if (!CT || isa<PointerType>(CT)) return 0;
1099 IndexTy Index = Idxs[CurIdx];
1100 if (!CT->indexValid(Index)) return 0;
1101 Agg = CT->getTypeAtIndex(Index);
1103 // If the new type forwards to another type, then it is in the middle
1104 // of being refined to another type (and hence, may have dropped all
1105 // references to what it was using before). So, use the new forwarded
1107 if (const Type *Ty = Agg->getForwardedType())
1110 return CurIdx == NumIdx ? Agg : 0;
1113 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr,
1116 return getIndexedTypeInternal(Ptr, Idxs, NumIdx);
1119 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr,
1120 uint64_t const *Idxs,
1122 return getIndexedTypeInternal(Ptr, Idxs, NumIdx);
1125 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr, Value *Idx) {
1126 const PointerType *PTy = dyn_cast<PointerType>(Ptr);
1127 if (!PTy) return 0; // Type isn't a pointer type!
1129 // Check the pointer index.
1130 if (!PTy->indexValid(Idx)) return 0;
1132 return PTy->getElementType();
1136 /// hasAllZeroIndices - Return true if all of the indices of this GEP are
1137 /// zeros. If so, the result pointer and the first operand have the same
1138 /// value, just potentially different types.
1139 bool GetElementPtrInst::hasAllZeroIndices() const {
1140 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1141 if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(i))) {
1142 if (!CI->isZero()) return false;
1150 /// hasAllConstantIndices - Return true if all of the indices of this GEP are
1151 /// constant integers. If so, the result pointer and the first operand have
1152 /// a constant offset between them.
1153 bool GetElementPtrInst::hasAllConstantIndices() const {
1154 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1155 if (!isa<ConstantInt>(getOperand(i)))
1162 //===----------------------------------------------------------------------===//
1163 // ExtractElementInst Implementation
1164 //===----------------------------------------------------------------------===//
1166 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
1167 const std::string &Name,
1168 Instruction *InsertBef)
1169 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1171 OperandTraits<ExtractElementInst>::op_begin(this),
1173 assert(isValidOperands(Val, Index) &&
1174 "Invalid extractelement instruction operands!");
1180 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
1181 const std::string &Name,
1182 BasicBlock *InsertAE)
1183 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1185 OperandTraits<ExtractElementInst>::op_begin(this),
1187 assert(isValidOperands(Val, Index) &&
1188 "Invalid extractelement instruction operands!");
1196 bool ExtractElementInst::isValidOperands(const Value *Val, const Value *Index) {
1197 if (!isa<VectorType>(Val->getType()) || Index->getType() != Type::Int32Ty)
1203 //===----------------------------------------------------------------------===//
1204 // InsertElementInst Implementation
1205 //===----------------------------------------------------------------------===//
1207 InsertElementInst::InsertElementInst(const InsertElementInst &IE)
1208 : Instruction(IE.getType(), InsertElement,
1209 OperandTraits<InsertElementInst>::op_begin(this), 3) {
1210 Op<0>() = IE.Op<0>();
1211 Op<1>() = IE.Op<1>();
1212 Op<2>() = IE.Op<2>();
1214 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
1215 const std::string &Name,
1216 Instruction *InsertBef)
1217 : Instruction(Vec->getType(), InsertElement,
1218 OperandTraits<InsertElementInst>::op_begin(this),
1220 assert(isValidOperands(Vec, Elt, Index) &&
1221 "Invalid insertelement instruction operands!");
1228 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
1229 const std::string &Name,
1230 BasicBlock *InsertAE)
1231 : Instruction(Vec->getType(), InsertElement,
1232 OperandTraits<InsertElementInst>::op_begin(this),
1234 assert(isValidOperands(Vec, Elt, Index) &&
1235 "Invalid insertelement instruction operands!");
1243 bool InsertElementInst::isValidOperands(const Value *Vec, const Value *Elt,
1244 const Value *Index) {
1245 if (!isa<VectorType>(Vec->getType()))
1246 return false; // First operand of insertelement must be vector type.
1248 if (Elt->getType() != cast<VectorType>(Vec->getType())->getElementType())
1249 return false;// Second operand of insertelement must be vector element type.
1251 if (Index->getType() != Type::Int32Ty)
1252 return false; // Third operand of insertelement must be i32.
1257 //===----------------------------------------------------------------------===//
1258 // ShuffleVectorInst Implementation
1259 //===----------------------------------------------------------------------===//
1261 ShuffleVectorInst::ShuffleVectorInst(const ShuffleVectorInst &SV)
1262 : Instruction(SV.getType(), ShuffleVector,
1263 OperandTraits<ShuffleVectorInst>::op_begin(this),
1264 OperandTraits<ShuffleVectorInst>::operands(this)) {
1265 Op<0>() = SV.Op<0>();
1266 Op<1>() = SV.Op<1>();
1267 Op<2>() = SV.Op<2>();
1270 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1271 const std::string &Name,
1272 Instruction *InsertBefore)
1273 : Instruction(V1->getType()->getContext().getVectorType(
1274 cast<VectorType>(V1->getType())->getElementType(),
1275 cast<VectorType>(Mask->getType())->getNumElements()),
1277 OperandTraits<ShuffleVectorInst>::op_begin(this),
1278 OperandTraits<ShuffleVectorInst>::operands(this),
1280 assert(isValidOperands(V1, V2, Mask) &&
1281 "Invalid shuffle vector instruction operands!");
1288 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1289 const std::string &Name,
1290 BasicBlock *InsertAtEnd)
1291 : Instruction(V1->getType(), ShuffleVector,
1292 OperandTraits<ShuffleVectorInst>::op_begin(this),
1293 OperandTraits<ShuffleVectorInst>::operands(this),
1295 assert(isValidOperands(V1, V2, Mask) &&
1296 "Invalid shuffle vector instruction operands!");
1304 bool ShuffleVectorInst::isValidOperands(const Value *V1, const Value *V2,
1305 const Value *Mask) {
1306 if (!isa<VectorType>(V1->getType()) || V1->getType() != V2->getType())
1309 const VectorType *MaskTy = dyn_cast<VectorType>(Mask->getType());
1310 if (!isa<Constant>(Mask) || MaskTy == 0 ||
1311 MaskTy->getElementType() != Type::Int32Ty)
1316 /// getMaskValue - Return the index from the shuffle mask for the specified
1317 /// output result. This is either -1 if the element is undef or a number less
1318 /// than 2*numelements.
1319 int ShuffleVectorInst::getMaskValue(unsigned i) const {
1320 const Constant *Mask = cast<Constant>(getOperand(2));
1321 if (isa<UndefValue>(Mask)) return -1;
1322 if (isa<ConstantAggregateZero>(Mask)) return 0;
1323 const ConstantVector *MaskCV = cast<ConstantVector>(Mask);
1324 assert(i < MaskCV->getNumOperands() && "Index out of range");
1326 if (isa<UndefValue>(MaskCV->getOperand(i)))
1328 return cast<ConstantInt>(MaskCV->getOperand(i))->getZExtValue();
1331 //===----------------------------------------------------------------------===//
1332 // InsertValueInst Class
1333 //===----------------------------------------------------------------------===//
1335 void InsertValueInst::init(Value *Agg, Value *Val, const unsigned *Idx,
1336 unsigned NumIdx, const std::string &Name) {
1337 assert(NumOperands == 2 && "NumOperands not initialized?");
1341 Indices.insert(Indices.end(), Idx, Idx + NumIdx);
1345 void InsertValueInst::init(Value *Agg, Value *Val, unsigned Idx,
1346 const std::string &Name) {
1347 assert(NumOperands == 2 && "NumOperands not initialized?");
1351 Indices.push_back(Idx);
1355 InsertValueInst::InsertValueInst(const InsertValueInst &IVI)
1356 : Instruction(IVI.getType(), InsertValue,
1357 OperandTraits<InsertValueInst>::op_begin(this), 2),
1358 Indices(IVI.Indices) {
1359 Op<0>() = IVI.getOperand(0);
1360 Op<1>() = IVI.getOperand(1);
1363 InsertValueInst::InsertValueInst(Value *Agg,
1366 const std::string &Name,
1367 Instruction *InsertBefore)
1368 : Instruction(Agg->getType(), InsertValue,
1369 OperandTraits<InsertValueInst>::op_begin(this),
1371 init(Agg, Val, Idx, Name);
1374 InsertValueInst::InsertValueInst(Value *Agg,
1377 const std::string &Name,
1378 BasicBlock *InsertAtEnd)
1379 : Instruction(Agg->getType(), InsertValue,
1380 OperandTraits<InsertValueInst>::op_begin(this),
1382 init(Agg, Val, Idx, Name);
1385 //===----------------------------------------------------------------------===//
1386 // ExtractValueInst Class
1387 //===----------------------------------------------------------------------===//
1389 void ExtractValueInst::init(const unsigned *Idx, unsigned NumIdx,
1390 const std::string &Name) {
1391 assert(NumOperands == 1 && "NumOperands not initialized?");
1393 Indices.insert(Indices.end(), Idx, Idx + NumIdx);
1397 void ExtractValueInst::init(unsigned Idx, const std::string &Name) {
1398 assert(NumOperands == 1 && "NumOperands not initialized?");
1400 Indices.push_back(Idx);
1404 ExtractValueInst::ExtractValueInst(const ExtractValueInst &EVI)
1405 : UnaryInstruction(EVI.getType(), ExtractValue, EVI.getOperand(0)),
1406 Indices(EVI.Indices) {
1409 // getIndexedType - Returns the type of the element that would be extracted
1410 // with an extractvalue instruction with the specified parameters.
1412 // A null type is returned if the indices are invalid for the specified
1415 const Type* ExtractValueInst::getIndexedType(const Type *Agg,
1416 const unsigned *Idxs,
1418 unsigned CurIdx = 0;
1419 for (; CurIdx != NumIdx; ++CurIdx) {
1420 const CompositeType *CT = dyn_cast<CompositeType>(Agg);
1421 if (!CT || isa<PointerType>(CT) || isa<VectorType>(CT)) return 0;
1422 unsigned Index = Idxs[CurIdx];
1423 if (!CT->indexValid(Index)) return 0;
1424 Agg = CT->getTypeAtIndex(Index);
1426 // If the new type forwards to another type, then it is in the middle
1427 // of being refined to another type (and hence, may have dropped all
1428 // references to what it was using before). So, use the new forwarded
1430 if (const Type *Ty = Agg->getForwardedType())
1433 return CurIdx == NumIdx ? Agg : 0;
1436 const Type* ExtractValueInst::getIndexedType(const Type *Agg,
1438 return getIndexedType(Agg, &Idx, 1);
1441 //===----------------------------------------------------------------------===//
1442 // BinaryOperator Class
1443 //===----------------------------------------------------------------------===//
1445 /// AdjustIType - Map Add, Sub, and Mul to FAdd, FSub, and FMul when the
1446 /// type is floating-point, to help provide compatibility with an older API.
1448 static BinaryOperator::BinaryOps AdjustIType(BinaryOperator::BinaryOps iType,
1450 // API compatibility: Adjust integer opcodes to floating-point opcodes.
1451 if (Ty->isFPOrFPVector()) {
1452 if (iType == BinaryOperator::Add) iType = BinaryOperator::FAdd;
1453 else if (iType == BinaryOperator::Sub) iType = BinaryOperator::FSub;
1454 else if (iType == BinaryOperator::Mul) iType = BinaryOperator::FMul;
1459 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
1460 const Type *Ty, const std::string &Name,
1461 Instruction *InsertBefore)
1462 : Instruction(Ty, AdjustIType(iType, Ty),
1463 OperandTraits<BinaryOperator>::op_begin(this),
1464 OperandTraits<BinaryOperator>::operands(this),
1468 init(AdjustIType(iType, Ty));
1472 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
1473 const Type *Ty, const std::string &Name,
1474 BasicBlock *InsertAtEnd)
1475 : Instruction(Ty, AdjustIType(iType, Ty),
1476 OperandTraits<BinaryOperator>::op_begin(this),
1477 OperandTraits<BinaryOperator>::operands(this),
1481 init(AdjustIType(iType, Ty));
1486 void BinaryOperator::init(BinaryOps iType) {
1487 Value *LHS = getOperand(0), *RHS = getOperand(1);
1488 LHS = LHS; RHS = RHS; // Silence warnings.
1489 assert(LHS->getType() == RHS->getType() &&
1490 "Binary operator operand types must match!");
1495 assert(getType() == LHS->getType() &&
1496 "Arithmetic operation should return same type as operands!");
1497 assert(getType()->isIntOrIntVector() &&
1498 "Tried to create an integer operation on a non-integer type!");
1500 case FAdd: case FSub:
1502 assert(getType() == LHS->getType() &&
1503 "Arithmetic operation should return same type as operands!");
1504 assert(getType()->isFPOrFPVector() &&
1505 "Tried to create a floating-point operation on a "
1506 "non-floating-point type!");
1510 assert(getType() == LHS->getType() &&
1511 "Arithmetic operation should return same type as operands!");
1512 assert((getType()->isInteger() || (isa<VectorType>(getType()) &&
1513 cast<VectorType>(getType())->getElementType()->isInteger())) &&
1514 "Incorrect operand type (not integer) for S/UDIV");
1517 assert(getType() == LHS->getType() &&
1518 "Arithmetic operation should return same type as operands!");
1519 assert(getType()->isFPOrFPVector() &&
1520 "Incorrect operand type (not floating point) for FDIV");
1524 assert(getType() == LHS->getType() &&
1525 "Arithmetic operation should return same type as operands!");
1526 assert((getType()->isInteger() || (isa<VectorType>(getType()) &&
1527 cast<VectorType>(getType())->getElementType()->isInteger())) &&
1528 "Incorrect operand type (not integer) for S/UREM");
1531 assert(getType() == LHS->getType() &&
1532 "Arithmetic operation should return same type as operands!");
1533 assert(getType()->isFPOrFPVector() &&
1534 "Incorrect operand type (not floating point) for FREM");
1539 assert(getType() == LHS->getType() &&
1540 "Shift operation should return same type as operands!");
1541 assert((getType()->isInteger() ||
1542 (isa<VectorType>(getType()) &&
1543 cast<VectorType>(getType())->getElementType()->isInteger())) &&
1544 "Tried to create a shift operation on a non-integral type!");
1548 assert(getType() == LHS->getType() &&
1549 "Logical operation should return same type as operands!");
1550 assert((getType()->isInteger() ||
1551 (isa<VectorType>(getType()) &&
1552 cast<VectorType>(getType())->getElementType()->isInteger())) &&
1553 "Tried to create a logical operation on a non-integral type!");
1561 BinaryOperator *BinaryOperator::Create(BinaryOps Op, Value *S1, Value *S2,
1562 const std::string &Name,
1563 Instruction *InsertBefore) {
1564 assert(S1->getType() == S2->getType() &&
1565 "Cannot create binary operator with two operands of differing type!");
1566 return new BinaryOperator(Op, S1, S2, S1->getType(), Name, InsertBefore);
1569 BinaryOperator *BinaryOperator::Create(BinaryOps Op, Value *S1, Value *S2,
1570 const std::string &Name,
1571 BasicBlock *InsertAtEnd) {
1572 BinaryOperator *Res = Create(Op, S1, S2, Name);
1573 InsertAtEnd->getInstList().push_back(Res);
1577 BinaryOperator *BinaryOperator::CreateNeg(LLVMContext &Context,
1578 Value *Op, const std::string &Name,
1579 Instruction *InsertBefore) {
1580 Value *zero = Context.getZeroValueForNegation(Op->getType());
1581 return new BinaryOperator(Instruction::Sub,
1583 Op->getType(), Name, InsertBefore);
1586 BinaryOperator *BinaryOperator::CreateNeg(LLVMContext &Context,
1587 Value *Op, const std::string &Name,
1588 BasicBlock *InsertAtEnd) {
1589 Value *zero = Context.getZeroValueForNegation(Op->getType());
1590 return new BinaryOperator(Instruction::Sub,
1592 Op->getType(), Name, InsertAtEnd);
1595 BinaryOperator *BinaryOperator::CreateFNeg(LLVMContext &Context,
1596 Value *Op, const std::string &Name,
1597 Instruction *InsertBefore) {
1598 Value *zero = Context.getZeroValueForNegation(Op->getType());
1599 return new BinaryOperator(Instruction::FSub,
1601 Op->getType(), Name, InsertBefore);
1604 BinaryOperator *BinaryOperator::CreateFNeg(LLVMContext &Context,
1605 Value *Op, const std::string &Name,
1606 BasicBlock *InsertAtEnd) {
1607 Value *zero = Context.getZeroValueForNegation(Op->getType());
1608 return new BinaryOperator(Instruction::FSub,
1610 Op->getType(), Name, InsertAtEnd);
1613 BinaryOperator *BinaryOperator::CreateNot(LLVMContext &Context,
1614 Value *Op, const std::string &Name,
1615 Instruction *InsertBefore) {
1617 if (const VectorType *PTy = dyn_cast<VectorType>(Op->getType())) {
1618 C = Context.getAllOnesValue(PTy->getElementType());
1619 C = Context.getConstantVector(
1620 std::vector<Constant*>(PTy->getNumElements(), C));
1622 C = Context.getAllOnesValue(Op->getType());
1625 return new BinaryOperator(Instruction::Xor, Op, C,
1626 Op->getType(), Name, InsertBefore);
1629 BinaryOperator *BinaryOperator::CreateNot(LLVMContext &Context,
1630 Value *Op, const std::string &Name,
1631 BasicBlock *InsertAtEnd) {
1633 if (const VectorType *PTy = dyn_cast<VectorType>(Op->getType())) {
1634 // Create a vector of all ones values.
1635 Constant *Elt = Context.getAllOnesValue(PTy->getElementType());
1636 AllOnes = Context.getConstantVector(
1637 std::vector<Constant*>(PTy->getNumElements(), Elt));
1639 AllOnes = Context.getAllOnesValue(Op->getType());
1642 return new BinaryOperator(Instruction::Xor, Op, AllOnes,
1643 Op->getType(), Name, InsertAtEnd);
1647 // isConstantAllOnes - Helper function for several functions below
1648 static inline bool isConstantAllOnes(const Value *V) {
1649 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V))
1650 return CI->isAllOnesValue();
1651 if (const ConstantVector *CV = dyn_cast<ConstantVector>(V))
1652 return CV->isAllOnesValue();
1656 bool BinaryOperator::isNeg(const Value *V) {
1657 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1658 if (Bop->getOpcode() == Instruction::Sub)
1659 if (Constant* C = dyn_cast<Constant>(Bop->getOperand(0)))
1660 return C->isNegativeZeroValue();
1664 bool BinaryOperator::isFNeg(const Value *V) {
1665 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1666 if (Bop->getOpcode() == Instruction::FSub)
1667 if (Constant* C = dyn_cast<Constant>(Bop->getOperand(0)))
1668 return C->isNegativeZeroValue();
1672 bool BinaryOperator::isNot(const Value *V) {
1673 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1674 return (Bop->getOpcode() == Instruction::Xor &&
1675 (isConstantAllOnes(Bop->getOperand(1)) ||
1676 isConstantAllOnes(Bop->getOperand(0))));
1680 Value *BinaryOperator::getNegArgument(Value *BinOp) {
1681 return cast<BinaryOperator>(BinOp)->getOperand(1);
1684 const Value *BinaryOperator::getNegArgument(const Value *BinOp) {
1685 return getNegArgument(const_cast<Value*>(BinOp));
1688 Value *BinaryOperator::getFNegArgument(Value *BinOp) {
1689 return cast<BinaryOperator>(BinOp)->getOperand(1);
1692 const Value *BinaryOperator::getFNegArgument(const Value *BinOp) {
1693 return getFNegArgument(const_cast<Value*>(BinOp));
1696 Value *BinaryOperator::getNotArgument(Value *BinOp) {
1697 assert(isNot(BinOp) && "getNotArgument on non-'not' instruction!");
1698 BinaryOperator *BO = cast<BinaryOperator>(BinOp);
1699 Value *Op0 = BO->getOperand(0);
1700 Value *Op1 = BO->getOperand(1);
1701 if (isConstantAllOnes(Op0)) return Op1;
1703 assert(isConstantAllOnes(Op1));
1707 const Value *BinaryOperator::getNotArgument(const Value *BinOp) {
1708 return getNotArgument(const_cast<Value*>(BinOp));
1712 // swapOperands - Exchange the two operands to this instruction. This
1713 // instruction is safe to use on any binary instruction and does not
1714 // modify the semantics of the instruction. If the instruction is
1715 // order dependent (SetLT f.e.) the opcode is changed.
1717 bool BinaryOperator::swapOperands() {
1718 if (!isCommutative())
1719 return true; // Can't commute operands
1720 Op<0>().swap(Op<1>());
1724 //===----------------------------------------------------------------------===//
1726 //===----------------------------------------------------------------------===//
1728 // Just determine if this cast only deals with integral->integral conversion.
1729 bool CastInst::isIntegerCast() const {
1730 switch (getOpcode()) {
1731 default: return false;
1732 case Instruction::ZExt:
1733 case Instruction::SExt:
1734 case Instruction::Trunc:
1736 case Instruction::BitCast:
1737 return getOperand(0)->getType()->isInteger() && getType()->isInteger();
1741 bool CastInst::isLosslessCast() const {
1742 // Only BitCast can be lossless, exit fast if we're not BitCast
1743 if (getOpcode() != Instruction::BitCast)
1746 // Identity cast is always lossless
1747 const Type* SrcTy = getOperand(0)->getType();
1748 const Type* DstTy = getType();
1752 // Pointer to pointer is always lossless.
1753 if (isa<PointerType>(SrcTy))
1754 return isa<PointerType>(DstTy);
1755 return false; // Other types have no identity values
1758 /// This function determines if the CastInst does not require any bits to be
1759 /// changed in order to effect the cast. Essentially, it identifies cases where
1760 /// no code gen is necessary for the cast, hence the name no-op cast. For
1761 /// example, the following are all no-op casts:
1762 /// # bitcast i32* %x to i8*
1763 /// # bitcast <2 x i32> %x to <4 x i16>
1764 /// # ptrtoint i32* %x to i32 ; on 32-bit plaforms only
1765 /// @brief Determine if a cast is a no-op.
1766 bool CastInst::isNoopCast(const Type *IntPtrTy) const {
1767 switch (getOpcode()) {
1769 assert(!"Invalid CastOp");
1770 case Instruction::Trunc:
1771 case Instruction::ZExt:
1772 case Instruction::SExt:
1773 case Instruction::FPTrunc:
1774 case Instruction::FPExt:
1775 case Instruction::UIToFP:
1776 case Instruction::SIToFP:
1777 case Instruction::FPToUI:
1778 case Instruction::FPToSI:
1779 return false; // These always modify bits
1780 case Instruction::BitCast:
1781 return true; // BitCast never modifies bits.
1782 case Instruction::PtrToInt:
1783 return IntPtrTy->getScalarSizeInBits() ==
1784 getType()->getScalarSizeInBits();
1785 case Instruction::IntToPtr:
1786 return IntPtrTy->getScalarSizeInBits() ==
1787 getOperand(0)->getType()->getScalarSizeInBits();
1791 /// This function determines if a pair of casts can be eliminated and what
1792 /// opcode should be used in the elimination. This assumes that there are two
1793 /// instructions like this:
1794 /// * %F = firstOpcode SrcTy %x to MidTy
1795 /// * %S = secondOpcode MidTy %F to DstTy
1796 /// The function returns a resultOpcode so these two casts can be replaced with:
1797 /// * %Replacement = resultOpcode %SrcTy %x to DstTy
1798 /// If no such cast is permited, the function returns 0.
1799 unsigned CastInst::isEliminableCastPair(
1800 Instruction::CastOps firstOp, Instruction::CastOps secondOp,
1801 const Type *SrcTy, const Type *MidTy, const Type *DstTy, const Type *IntPtrTy)
1803 // Define the 144 possibilities for these two cast instructions. The values
1804 // in this matrix determine what to do in a given situation and select the
1805 // case in the switch below. The rows correspond to firstOp, the columns
1806 // correspond to secondOp. In looking at the table below, keep in mind
1807 // the following cast properties:
1809 // Size Compare Source Destination
1810 // Operator Src ? Size Type Sign Type Sign
1811 // -------- ------------ ------------------- ---------------------
1812 // TRUNC > Integer Any Integral Any
1813 // ZEXT < Integral Unsigned Integer Any
1814 // SEXT < Integral Signed Integer Any
1815 // FPTOUI n/a FloatPt n/a Integral Unsigned
1816 // FPTOSI n/a FloatPt n/a Integral Signed
1817 // UITOFP n/a Integral Unsigned FloatPt n/a
1818 // SITOFP n/a Integral Signed FloatPt n/a
1819 // FPTRUNC > FloatPt n/a FloatPt n/a
1820 // FPEXT < FloatPt n/a FloatPt n/a
1821 // PTRTOINT n/a Pointer n/a Integral Unsigned
1822 // INTTOPTR n/a Integral Unsigned Pointer n/a
1823 // BITCONVERT = FirstClass n/a FirstClass n/a
1825 // NOTE: some transforms are safe, but we consider them to be non-profitable.
1826 // For example, we could merge "fptoui double to i32" + "zext i32 to i64",
1827 // into "fptoui double to i64", but this loses information about the range
1828 // of the produced value (we no longer know the top-part is all zeros).
1829 // Further this conversion is often much more expensive for typical hardware,
1830 // and causes issues when building libgcc. We disallow fptosi+sext for the
1832 const unsigned numCastOps =
1833 Instruction::CastOpsEnd - Instruction::CastOpsBegin;
1834 static const uint8_t CastResults[numCastOps][numCastOps] = {
1835 // T F F U S F F P I B -+
1836 // R Z S P P I I T P 2 N T |
1837 // U E E 2 2 2 2 R E I T C +- secondOp
1838 // N X X U S F F N X N 2 V |
1839 // C T T I I P P C T T P T -+
1840 { 1, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // Trunc -+
1841 { 8, 1, 9,99,99, 2, 0,99,99,99, 2, 3 }, // ZExt |
1842 { 8, 0, 1,99,99, 0, 2,99,99,99, 0, 3 }, // SExt |
1843 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // FPToUI |
1844 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // FPToSI |
1845 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4 }, // UIToFP +- firstOp
1846 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4 }, // SIToFP |
1847 { 99,99,99, 0, 0,99,99, 1, 0,99,99, 4 }, // FPTrunc |
1848 { 99,99,99, 2, 2,99,99,10, 2,99,99, 4 }, // FPExt |
1849 { 1, 0, 0,99,99, 0, 0,99,99,99, 7, 3 }, // PtrToInt |
1850 { 99,99,99,99,99,99,99,99,99,13,99,12 }, // IntToPtr |
1851 { 5, 5, 5, 6, 6, 5, 5, 6, 6,11, 5, 1 }, // BitCast -+
1854 int ElimCase = CastResults[firstOp-Instruction::CastOpsBegin]
1855 [secondOp-Instruction::CastOpsBegin];
1858 // categorically disallowed
1861 // allowed, use first cast's opcode
1864 // allowed, use second cast's opcode
1867 // no-op cast in second op implies firstOp as long as the DestTy
1869 if (DstTy->isInteger())
1873 // no-op cast in second op implies firstOp as long as the DestTy
1874 // is floating point
1875 if (DstTy->isFloatingPoint())
1879 // no-op cast in first op implies secondOp as long as the SrcTy
1881 if (SrcTy->isInteger())
1885 // no-op cast in first op implies secondOp as long as the SrcTy
1886 // is a floating point
1887 if (SrcTy->isFloatingPoint())
1891 // ptrtoint, inttoptr -> bitcast (ptr -> ptr) if int size is >= ptr size
1894 unsigned PtrSize = IntPtrTy->getScalarSizeInBits();
1895 unsigned MidSize = MidTy->getScalarSizeInBits();
1896 if (MidSize >= PtrSize)
1897 return Instruction::BitCast;
1901 // ext, trunc -> bitcast, if the SrcTy and DstTy are same size
1902 // ext, trunc -> ext, if sizeof(SrcTy) < sizeof(DstTy)
1903 // ext, trunc -> trunc, if sizeof(SrcTy) > sizeof(DstTy)
1904 unsigned SrcSize = SrcTy->getScalarSizeInBits();
1905 unsigned DstSize = DstTy->getScalarSizeInBits();
1906 if (SrcSize == DstSize)
1907 return Instruction::BitCast;
1908 else if (SrcSize < DstSize)
1912 case 9: // zext, sext -> zext, because sext can't sign extend after zext
1913 return Instruction::ZExt;
1915 // fpext followed by ftrunc is allowed if the bit size returned to is
1916 // the same as the original, in which case its just a bitcast
1918 return Instruction::BitCast;
1919 return 0; // If the types are not the same we can't eliminate it.
1921 // bitcast followed by ptrtoint is allowed as long as the bitcast
1922 // is a pointer to pointer cast.
1923 if (isa<PointerType>(SrcTy) && isa<PointerType>(MidTy))
1927 // inttoptr, bitcast -> intptr if bitcast is a ptr to ptr cast
1928 if (isa<PointerType>(MidTy) && isa<PointerType>(DstTy))
1932 // inttoptr, ptrtoint -> bitcast if SrcSize<=PtrSize and SrcSize==DstSize
1935 unsigned PtrSize = IntPtrTy->getScalarSizeInBits();
1936 unsigned SrcSize = SrcTy->getScalarSizeInBits();
1937 unsigned DstSize = DstTy->getScalarSizeInBits();
1938 if (SrcSize <= PtrSize && SrcSize == DstSize)
1939 return Instruction::BitCast;
1943 // cast combination can't happen (error in input). This is for all cases
1944 // where the MidTy is not the same for the two cast instructions.
1945 assert(!"Invalid Cast Combination");
1948 assert(!"Error in CastResults table!!!");
1954 CastInst *CastInst::Create(Instruction::CastOps op, Value *S, const Type *Ty,
1955 const std::string &Name, Instruction *InsertBefore) {
1956 // Construct and return the appropriate CastInst subclass
1958 case Trunc: return new TruncInst (S, Ty, Name, InsertBefore);
1959 case ZExt: return new ZExtInst (S, Ty, Name, InsertBefore);
1960 case SExt: return new SExtInst (S, Ty, Name, InsertBefore);
1961 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertBefore);
1962 case FPExt: return new FPExtInst (S, Ty, Name, InsertBefore);
1963 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertBefore);
1964 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertBefore);
1965 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertBefore);
1966 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertBefore);
1967 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertBefore);
1968 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertBefore);
1969 case BitCast: return new BitCastInst (S, Ty, Name, InsertBefore);
1971 assert(!"Invalid opcode provided");
1976 CastInst *CastInst::Create(Instruction::CastOps op, Value *S, const Type *Ty,
1977 const std::string &Name, BasicBlock *InsertAtEnd) {
1978 // Construct and return the appropriate CastInst subclass
1980 case Trunc: return new TruncInst (S, Ty, Name, InsertAtEnd);
1981 case ZExt: return new ZExtInst (S, Ty, Name, InsertAtEnd);
1982 case SExt: return new SExtInst (S, Ty, Name, InsertAtEnd);
1983 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertAtEnd);
1984 case FPExt: return new FPExtInst (S, Ty, Name, InsertAtEnd);
1985 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertAtEnd);
1986 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertAtEnd);
1987 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertAtEnd);
1988 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertAtEnd);
1989 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertAtEnd);
1990 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertAtEnd);
1991 case BitCast: return new BitCastInst (S, Ty, Name, InsertAtEnd);
1993 assert(!"Invalid opcode provided");
1998 CastInst *CastInst::CreateZExtOrBitCast(Value *S, const Type *Ty,
1999 const std::string &Name,
2000 Instruction *InsertBefore) {
2001 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2002 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2003 return Create(Instruction::ZExt, S, Ty, Name, InsertBefore);
2006 CastInst *CastInst::CreateZExtOrBitCast(Value *S, const Type *Ty,
2007 const std::string &Name,
2008 BasicBlock *InsertAtEnd) {
2009 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2010 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2011 return Create(Instruction::ZExt, S, Ty, Name, InsertAtEnd);
2014 CastInst *CastInst::CreateSExtOrBitCast(Value *S, const Type *Ty,
2015 const std::string &Name,
2016 Instruction *InsertBefore) {
2017 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2018 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2019 return Create(Instruction::SExt, S, Ty, Name, InsertBefore);
2022 CastInst *CastInst::CreateSExtOrBitCast(Value *S, const Type *Ty,
2023 const std::string &Name,
2024 BasicBlock *InsertAtEnd) {
2025 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2026 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2027 return Create(Instruction::SExt, S, Ty, Name, InsertAtEnd);
2030 CastInst *CastInst::CreateTruncOrBitCast(Value *S, const Type *Ty,
2031 const std::string &Name,
2032 Instruction *InsertBefore) {
2033 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2034 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2035 return Create(Instruction::Trunc, S, Ty, Name, InsertBefore);
2038 CastInst *CastInst::CreateTruncOrBitCast(Value *S, const Type *Ty,
2039 const std::string &Name,
2040 BasicBlock *InsertAtEnd) {
2041 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2042 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2043 return Create(Instruction::Trunc, S, Ty, Name, InsertAtEnd);
2046 CastInst *CastInst::CreatePointerCast(Value *S, const Type *Ty,
2047 const std::string &Name,
2048 BasicBlock *InsertAtEnd) {
2049 assert(isa<PointerType>(S->getType()) && "Invalid cast");
2050 assert((Ty->isInteger() || isa<PointerType>(Ty)) &&
2053 if (Ty->isInteger())
2054 return Create(Instruction::PtrToInt, S, Ty, Name, InsertAtEnd);
2055 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2058 /// @brief Create a BitCast or a PtrToInt cast instruction
2059 CastInst *CastInst::CreatePointerCast(Value *S, const Type *Ty,
2060 const std::string &Name,
2061 Instruction *InsertBefore) {
2062 assert(isa<PointerType>(S->getType()) && "Invalid cast");
2063 assert((Ty->isInteger() || isa<PointerType>(Ty)) &&
2066 if (Ty->isInteger())
2067 return Create(Instruction::PtrToInt, S, Ty, Name, InsertBefore);
2068 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2071 CastInst *CastInst::CreateIntegerCast(Value *C, const Type *Ty,
2072 bool isSigned, const std::string &Name,
2073 Instruction *InsertBefore) {
2074 assert(C->getType()->isInteger() && Ty->isInteger() && "Invalid cast");
2075 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2076 unsigned DstBits = Ty->getScalarSizeInBits();
2077 Instruction::CastOps opcode =
2078 (SrcBits == DstBits ? Instruction::BitCast :
2079 (SrcBits > DstBits ? Instruction::Trunc :
2080 (isSigned ? Instruction::SExt : Instruction::ZExt)));
2081 return Create(opcode, C, Ty, Name, InsertBefore);
2084 CastInst *CastInst::CreateIntegerCast(Value *C, const Type *Ty,
2085 bool isSigned, const std::string &Name,
2086 BasicBlock *InsertAtEnd) {
2087 assert(C->getType()->isIntOrIntVector() && Ty->isIntOrIntVector() &&
2089 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2090 unsigned DstBits = Ty->getScalarSizeInBits();
2091 Instruction::CastOps opcode =
2092 (SrcBits == DstBits ? Instruction::BitCast :
2093 (SrcBits > DstBits ? Instruction::Trunc :
2094 (isSigned ? Instruction::SExt : Instruction::ZExt)));
2095 return Create(opcode, C, Ty, Name, InsertAtEnd);
2098 CastInst *CastInst::CreateFPCast(Value *C, const Type *Ty,
2099 const std::string &Name,
2100 Instruction *InsertBefore) {
2101 assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
2103 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2104 unsigned DstBits = Ty->getScalarSizeInBits();
2105 Instruction::CastOps opcode =
2106 (SrcBits == DstBits ? Instruction::BitCast :
2107 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
2108 return Create(opcode, C, Ty, Name, InsertBefore);
2111 CastInst *CastInst::CreateFPCast(Value *C, const Type *Ty,
2112 const std::string &Name,
2113 BasicBlock *InsertAtEnd) {
2114 assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
2116 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2117 unsigned DstBits = Ty->getScalarSizeInBits();
2118 Instruction::CastOps opcode =
2119 (SrcBits == DstBits ? Instruction::BitCast :
2120 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
2121 return Create(opcode, C, Ty, Name, InsertAtEnd);
2124 // Check whether it is valid to call getCastOpcode for these types.
2125 // This routine must be kept in sync with getCastOpcode.
2126 bool CastInst::isCastable(const Type *SrcTy, const Type *DestTy) {
2127 if (!SrcTy->isFirstClassType() || !DestTy->isFirstClassType())
2130 if (SrcTy == DestTy)
2133 // Get the bit sizes, we'll need these
2134 unsigned SrcBits = SrcTy->getScalarSizeInBits(); // 0 for ptr
2135 unsigned DestBits = DestTy->getScalarSizeInBits(); // 0 for ptr
2137 // Run through the possibilities ...
2138 if (DestTy->isInteger()) { // Casting to integral
2139 if (SrcTy->isInteger()) { // Casting from integral
2141 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt
2143 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
2144 // Casting from vector
2145 return DestBits == PTy->getBitWidth();
2146 } else { // Casting from something else
2147 return isa<PointerType>(SrcTy);
2149 } else if (DestTy->isFloatingPoint()) { // Casting to floating pt
2150 if (SrcTy->isInteger()) { // Casting from integral
2152 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt
2154 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
2155 // Casting from vector
2156 return DestBits == PTy->getBitWidth();
2157 } else { // Casting from something else
2160 } else if (const VectorType *DestPTy = dyn_cast<VectorType>(DestTy)) {
2161 // Casting to vector
2162 if (const VectorType *SrcPTy = dyn_cast<VectorType>(SrcTy)) {
2163 // Casting from vector
2164 return DestPTy->getBitWidth() == SrcPTy->getBitWidth();
2165 } else { // Casting from something else
2166 return DestPTy->getBitWidth() == SrcBits;
2168 } else if (isa<PointerType>(DestTy)) { // Casting to pointer
2169 if (isa<PointerType>(SrcTy)) { // Casting from pointer
2171 } else if (SrcTy->isInteger()) { // Casting from integral
2173 } else { // Casting from something else
2176 } else { // Casting to something else
2181 // Provide a way to get a "cast" where the cast opcode is inferred from the
2182 // types and size of the operand. This, basically, is a parallel of the
2183 // logic in the castIsValid function below. This axiom should hold:
2184 // castIsValid( getCastOpcode(Val, Ty), Val, Ty)
2185 // should not assert in castIsValid. In other words, this produces a "correct"
2186 // casting opcode for the arguments passed to it.
2187 // This routine must be kept in sync with isCastable.
2188 Instruction::CastOps
2189 CastInst::getCastOpcode(
2190 const Value *Src, bool SrcIsSigned, const Type *DestTy, bool DestIsSigned) {
2191 // Get the bit sizes, we'll need these
2192 const Type *SrcTy = Src->getType();
2193 unsigned SrcBits = SrcTy->getScalarSizeInBits(); // 0 for ptr
2194 unsigned DestBits = DestTy->getScalarSizeInBits(); // 0 for ptr
2196 assert(SrcTy->isFirstClassType() && DestTy->isFirstClassType() &&
2197 "Only first class types are castable!");
2199 // Run through the possibilities ...
2200 if (DestTy->isInteger()) { // Casting to integral
2201 if (SrcTy->isInteger()) { // Casting from integral
2202 if (DestBits < SrcBits)
2203 return Trunc; // int -> smaller int
2204 else if (DestBits > SrcBits) { // its an extension
2206 return SExt; // signed -> SEXT
2208 return ZExt; // unsigned -> ZEXT
2210 return BitCast; // Same size, No-op cast
2212 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt
2214 return FPToSI; // FP -> sint
2216 return FPToUI; // FP -> uint
2217 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
2218 assert(DestBits == PTy->getBitWidth() &&
2219 "Casting vector to integer of different width");
2221 return BitCast; // Same size, no-op cast
2223 assert(isa<PointerType>(SrcTy) &&
2224 "Casting from a value that is not first-class type");
2225 return PtrToInt; // ptr -> int
2227 } else if (DestTy->isFloatingPoint()) { // Casting to floating pt
2228 if (SrcTy->isInteger()) { // Casting from integral
2230 return SIToFP; // sint -> FP
2232 return UIToFP; // uint -> FP
2233 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt
2234 if (DestBits < SrcBits) {
2235 return FPTrunc; // FP -> smaller FP
2236 } else if (DestBits > SrcBits) {
2237 return FPExt; // FP -> larger FP
2239 return BitCast; // same size, no-op cast
2241 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
2242 assert(DestBits == PTy->getBitWidth() &&
2243 "Casting vector to floating point of different width");
2245 return BitCast; // same size, no-op cast
2247 llvm_unreachable("Casting pointer or non-first class to float");
2249 } else if (const VectorType *DestPTy = dyn_cast<VectorType>(DestTy)) {
2250 if (const VectorType *SrcPTy = dyn_cast<VectorType>(SrcTy)) {
2251 assert(DestPTy->getBitWidth() == SrcPTy->getBitWidth() &&
2252 "Casting vector to vector of different widths");
2254 return BitCast; // vector -> vector
2255 } else if (DestPTy->getBitWidth() == SrcBits) {
2256 return BitCast; // float/int -> vector
2258 assert(!"Illegal cast to vector (wrong type or size)");
2260 } else if (isa<PointerType>(DestTy)) {
2261 if (isa<PointerType>(SrcTy)) {
2262 return BitCast; // ptr -> ptr
2263 } else if (SrcTy->isInteger()) {
2264 return IntToPtr; // int -> ptr
2266 assert(!"Casting pointer to other than pointer or int");
2269 assert(!"Casting to type that is not first-class");
2272 // If we fall through to here we probably hit an assertion cast above
2273 // and assertions are not turned on. Anything we return is an error, so
2274 // BitCast is as good a choice as any.
2278 //===----------------------------------------------------------------------===//
2279 // CastInst SubClass Constructors
2280 //===----------------------------------------------------------------------===//
2282 /// Check that the construction parameters for a CastInst are correct. This
2283 /// could be broken out into the separate constructors but it is useful to have
2284 /// it in one place and to eliminate the redundant code for getting the sizes
2285 /// of the types involved.
2287 CastInst::castIsValid(Instruction::CastOps op, Value *S, const Type *DstTy) {
2289 // Check for type sanity on the arguments
2290 const Type *SrcTy = S->getType();
2291 if (!SrcTy->isFirstClassType() || !DstTy->isFirstClassType())
2294 // Get the size of the types in bits, we'll need this later
2295 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
2296 unsigned DstBitSize = DstTy->getScalarSizeInBits();
2298 // Switch on the opcode provided
2300 default: return false; // This is an input error
2301 case Instruction::Trunc:
2302 return SrcTy->isIntOrIntVector() &&
2303 DstTy->isIntOrIntVector()&& SrcBitSize > DstBitSize;
2304 case Instruction::ZExt:
2305 return SrcTy->isIntOrIntVector() &&
2306 DstTy->isIntOrIntVector()&& SrcBitSize < DstBitSize;
2307 case Instruction::SExt:
2308 return SrcTy->isIntOrIntVector() &&
2309 DstTy->isIntOrIntVector()&& SrcBitSize < DstBitSize;
2310 case Instruction::FPTrunc:
2311 return SrcTy->isFPOrFPVector() &&
2312 DstTy->isFPOrFPVector() &&
2313 SrcBitSize > DstBitSize;
2314 case Instruction::FPExt:
2315 return SrcTy->isFPOrFPVector() &&
2316 DstTy->isFPOrFPVector() &&
2317 SrcBitSize < DstBitSize;
2318 case Instruction::UIToFP:
2319 case Instruction::SIToFP:
2320 if (const VectorType *SVTy = dyn_cast<VectorType>(SrcTy)) {
2321 if (const VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
2322 return SVTy->getElementType()->isIntOrIntVector() &&
2323 DVTy->getElementType()->isFPOrFPVector() &&
2324 SVTy->getNumElements() == DVTy->getNumElements();
2327 return SrcTy->isIntOrIntVector() && DstTy->isFPOrFPVector();
2328 case Instruction::FPToUI:
2329 case Instruction::FPToSI:
2330 if (const VectorType *SVTy = dyn_cast<VectorType>(SrcTy)) {
2331 if (const VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
2332 return SVTy->getElementType()->isFPOrFPVector() &&
2333 DVTy->getElementType()->isIntOrIntVector() &&
2334 SVTy->getNumElements() == DVTy->getNumElements();
2337 return SrcTy->isFPOrFPVector() && DstTy->isIntOrIntVector();
2338 case Instruction::PtrToInt:
2339 return isa<PointerType>(SrcTy) && DstTy->isInteger();
2340 case Instruction::IntToPtr:
2341 return SrcTy->isInteger() && isa<PointerType>(DstTy);
2342 case Instruction::BitCast:
2343 // BitCast implies a no-op cast of type only. No bits change.
2344 // However, you can't cast pointers to anything but pointers.
2345 if (isa<PointerType>(SrcTy) != isa<PointerType>(DstTy))
2348 // Now we know we're not dealing with a pointer/non-pointer mismatch. In all
2349 // these cases, the cast is okay if the source and destination bit widths
2351 return SrcTy->getPrimitiveSizeInBits() == DstTy->getPrimitiveSizeInBits();
2355 TruncInst::TruncInst(
2356 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2357 ) : CastInst(Ty, Trunc, S, Name, InsertBefore) {
2358 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
2361 TruncInst::TruncInst(
2362 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2363 ) : CastInst(Ty, Trunc, S, Name, InsertAtEnd) {
2364 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
2368 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2369 ) : CastInst(Ty, ZExt, S, Name, InsertBefore) {
2370 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
2374 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2375 ) : CastInst(Ty, ZExt, S, Name, InsertAtEnd) {
2376 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
2379 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2380 ) : CastInst(Ty, SExt, S, Name, InsertBefore) {
2381 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
2385 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2386 ) : CastInst(Ty, SExt, S, Name, InsertAtEnd) {
2387 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
2390 FPTruncInst::FPTruncInst(
2391 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2392 ) : CastInst(Ty, FPTrunc, S, Name, InsertBefore) {
2393 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
2396 FPTruncInst::FPTruncInst(
2397 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2398 ) : CastInst(Ty, FPTrunc, S, Name, InsertAtEnd) {
2399 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
2402 FPExtInst::FPExtInst(
2403 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2404 ) : CastInst(Ty, FPExt, S, Name, InsertBefore) {
2405 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
2408 FPExtInst::FPExtInst(
2409 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2410 ) : CastInst(Ty, FPExt, S, Name, InsertAtEnd) {
2411 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
2414 UIToFPInst::UIToFPInst(
2415 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2416 ) : CastInst(Ty, UIToFP, S, Name, InsertBefore) {
2417 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
2420 UIToFPInst::UIToFPInst(
2421 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2422 ) : CastInst(Ty, UIToFP, S, Name, InsertAtEnd) {
2423 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
2426 SIToFPInst::SIToFPInst(
2427 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2428 ) : CastInst(Ty, SIToFP, S, Name, InsertBefore) {
2429 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
2432 SIToFPInst::SIToFPInst(
2433 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2434 ) : CastInst(Ty, SIToFP, S, Name, InsertAtEnd) {
2435 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
2438 FPToUIInst::FPToUIInst(
2439 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2440 ) : CastInst(Ty, FPToUI, S, Name, InsertBefore) {
2441 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
2444 FPToUIInst::FPToUIInst(
2445 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2446 ) : CastInst(Ty, FPToUI, S, Name, InsertAtEnd) {
2447 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
2450 FPToSIInst::FPToSIInst(
2451 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2452 ) : CastInst(Ty, FPToSI, S, Name, InsertBefore) {
2453 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
2456 FPToSIInst::FPToSIInst(
2457 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2458 ) : CastInst(Ty, FPToSI, S, Name, InsertAtEnd) {
2459 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
2462 PtrToIntInst::PtrToIntInst(
2463 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2464 ) : CastInst(Ty, PtrToInt, S, Name, InsertBefore) {
2465 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
2468 PtrToIntInst::PtrToIntInst(
2469 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2470 ) : CastInst(Ty, PtrToInt, S, Name, InsertAtEnd) {
2471 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
2474 IntToPtrInst::IntToPtrInst(
2475 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2476 ) : CastInst(Ty, IntToPtr, S, Name, InsertBefore) {
2477 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
2480 IntToPtrInst::IntToPtrInst(
2481 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2482 ) : CastInst(Ty, IntToPtr, S, Name, InsertAtEnd) {
2483 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
2486 BitCastInst::BitCastInst(
2487 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2488 ) : CastInst(Ty, BitCast, S, Name, InsertBefore) {
2489 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
2492 BitCastInst::BitCastInst(
2493 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2494 ) : CastInst(Ty, BitCast, S, Name, InsertAtEnd) {
2495 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
2498 //===----------------------------------------------------------------------===//
2500 //===----------------------------------------------------------------------===//
2502 CmpInst::CmpInst(const Type *ty, OtherOps op, unsigned short predicate,
2503 Value *LHS, Value *RHS, const std::string &Name,
2504 Instruction *InsertBefore)
2505 : Instruction(ty, op,
2506 OperandTraits<CmpInst>::op_begin(this),
2507 OperandTraits<CmpInst>::operands(this),
2511 SubclassData = predicate;
2515 CmpInst::CmpInst(const Type *ty, OtherOps op, unsigned short predicate,
2516 Value *LHS, Value *RHS, const std::string &Name,
2517 BasicBlock *InsertAtEnd)
2518 : Instruction(ty, op,
2519 OperandTraits<CmpInst>::op_begin(this),
2520 OperandTraits<CmpInst>::operands(this),
2524 SubclassData = predicate;
2529 CmpInst::Create(LLVMContext &Context, OtherOps Op, unsigned short predicate,
2530 Value *S1, Value *S2,
2531 const std::string &Name, Instruction *InsertBefore) {
2532 if (Op == Instruction::ICmp) {
2534 return new ICmpInst(InsertBefore, CmpInst::Predicate(predicate),
2537 return new ICmpInst(Context, CmpInst::Predicate(predicate),
2542 return new FCmpInst(InsertBefore, CmpInst::Predicate(predicate),
2545 return new FCmpInst(Context, CmpInst::Predicate(predicate),
2550 CmpInst::Create(OtherOps Op, unsigned short predicate, Value *S1, Value *S2,
2551 const std::string &Name, BasicBlock *InsertAtEnd) {
2552 if (Op == Instruction::ICmp) {
2553 return new ICmpInst(*InsertAtEnd, CmpInst::Predicate(predicate),
2556 return new FCmpInst(*InsertAtEnd, CmpInst::Predicate(predicate),
2560 void CmpInst::swapOperands() {
2561 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2564 cast<FCmpInst>(this)->swapOperands();
2567 bool CmpInst::isCommutative() {
2568 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2569 return IC->isCommutative();
2570 return cast<FCmpInst>(this)->isCommutative();
2573 bool CmpInst::isEquality() {
2574 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2575 return IC->isEquality();
2576 return cast<FCmpInst>(this)->isEquality();
2580 CmpInst::Predicate CmpInst::getInversePredicate(Predicate pred) {
2582 default: assert(!"Unknown cmp predicate!");
2583 case ICMP_EQ: return ICMP_NE;
2584 case ICMP_NE: return ICMP_EQ;
2585 case ICMP_UGT: return ICMP_ULE;
2586 case ICMP_ULT: return ICMP_UGE;
2587 case ICMP_UGE: return ICMP_ULT;
2588 case ICMP_ULE: return ICMP_UGT;
2589 case ICMP_SGT: return ICMP_SLE;
2590 case ICMP_SLT: return ICMP_SGE;
2591 case ICMP_SGE: return ICMP_SLT;
2592 case ICMP_SLE: return ICMP_SGT;
2594 case FCMP_OEQ: return FCMP_UNE;
2595 case FCMP_ONE: return FCMP_UEQ;
2596 case FCMP_OGT: return FCMP_ULE;
2597 case FCMP_OLT: return FCMP_UGE;
2598 case FCMP_OGE: return FCMP_ULT;
2599 case FCMP_OLE: return FCMP_UGT;
2600 case FCMP_UEQ: return FCMP_ONE;
2601 case FCMP_UNE: return FCMP_OEQ;
2602 case FCMP_UGT: return FCMP_OLE;
2603 case FCMP_ULT: return FCMP_OGE;
2604 case FCMP_UGE: return FCMP_OLT;
2605 case FCMP_ULE: return FCMP_OGT;
2606 case FCMP_ORD: return FCMP_UNO;
2607 case FCMP_UNO: return FCMP_ORD;
2608 case FCMP_TRUE: return FCMP_FALSE;
2609 case FCMP_FALSE: return FCMP_TRUE;
2613 ICmpInst::Predicate ICmpInst::getSignedPredicate(Predicate pred) {
2615 default: assert(! "Unknown icmp predicate!");
2616 case ICMP_EQ: case ICMP_NE:
2617 case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE:
2619 case ICMP_UGT: return ICMP_SGT;
2620 case ICMP_ULT: return ICMP_SLT;
2621 case ICMP_UGE: return ICMP_SGE;
2622 case ICMP_ULE: return ICMP_SLE;
2626 ICmpInst::Predicate ICmpInst::getUnsignedPredicate(Predicate pred) {
2628 default: assert(! "Unknown icmp predicate!");
2629 case ICMP_EQ: case ICMP_NE:
2630 case ICMP_UGT: case ICMP_ULT: case ICMP_UGE: case ICMP_ULE:
2632 case ICMP_SGT: return ICMP_UGT;
2633 case ICMP_SLT: return ICMP_ULT;
2634 case ICMP_SGE: return ICMP_UGE;
2635 case ICMP_SLE: return ICMP_ULE;
2639 bool ICmpInst::isSignedPredicate(Predicate pred) {
2641 default: assert(! "Unknown icmp predicate!");
2642 case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE:
2644 case ICMP_EQ: case ICMP_NE: case ICMP_UGT: case ICMP_ULT:
2645 case ICMP_UGE: case ICMP_ULE:
2650 /// Initialize a set of values that all satisfy the condition with C.
2653 ICmpInst::makeConstantRange(Predicate pred, const APInt &C) {
2656 uint32_t BitWidth = C.getBitWidth();
2658 default: llvm_unreachable("Invalid ICmp opcode to ConstantRange ctor!");
2659 case ICmpInst::ICMP_EQ: Upper++; break;
2660 case ICmpInst::ICMP_NE: Lower++; break;
2661 case ICmpInst::ICMP_ULT: Lower = APInt::getMinValue(BitWidth); break;
2662 case ICmpInst::ICMP_SLT: Lower = APInt::getSignedMinValue(BitWidth); break;
2663 case ICmpInst::ICMP_UGT:
2664 Lower++; Upper = APInt::getMinValue(BitWidth); // Min = Next(Max)
2666 case ICmpInst::ICMP_SGT:
2667 Lower++; Upper = APInt::getSignedMinValue(BitWidth); // Min = Next(Max)
2669 case ICmpInst::ICMP_ULE:
2670 Lower = APInt::getMinValue(BitWidth); Upper++;
2672 case ICmpInst::ICMP_SLE:
2673 Lower = APInt::getSignedMinValue(BitWidth); Upper++;
2675 case ICmpInst::ICMP_UGE:
2676 Upper = APInt::getMinValue(BitWidth); // Min = Next(Max)
2678 case ICmpInst::ICMP_SGE:
2679 Upper = APInt::getSignedMinValue(BitWidth); // Min = Next(Max)
2682 return ConstantRange(Lower, Upper);
2685 CmpInst::Predicate CmpInst::getSwappedPredicate(Predicate pred) {
2687 default: assert(!"Unknown cmp predicate!");
2688 case ICMP_EQ: case ICMP_NE:
2690 case ICMP_SGT: return ICMP_SLT;
2691 case ICMP_SLT: return ICMP_SGT;
2692 case ICMP_SGE: return ICMP_SLE;
2693 case ICMP_SLE: return ICMP_SGE;
2694 case ICMP_UGT: return ICMP_ULT;
2695 case ICMP_ULT: return ICMP_UGT;
2696 case ICMP_UGE: return ICMP_ULE;
2697 case ICMP_ULE: return ICMP_UGE;
2699 case FCMP_FALSE: case FCMP_TRUE:
2700 case FCMP_OEQ: case FCMP_ONE:
2701 case FCMP_UEQ: case FCMP_UNE:
2702 case FCMP_ORD: case FCMP_UNO:
2704 case FCMP_OGT: return FCMP_OLT;
2705 case FCMP_OLT: return FCMP_OGT;
2706 case FCMP_OGE: return FCMP_OLE;
2707 case FCMP_OLE: return FCMP_OGE;
2708 case FCMP_UGT: return FCMP_ULT;
2709 case FCMP_ULT: return FCMP_UGT;
2710 case FCMP_UGE: return FCMP_ULE;
2711 case FCMP_ULE: return FCMP_UGE;
2715 bool CmpInst::isUnsigned(unsigned short predicate) {
2716 switch (predicate) {
2717 default: return false;
2718 case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_ULE: case ICmpInst::ICMP_UGT:
2719 case ICmpInst::ICMP_UGE: return true;
2723 bool CmpInst::isSigned(unsigned short predicate){
2724 switch (predicate) {
2725 default: return false;
2726 case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_SLE: case ICmpInst::ICMP_SGT:
2727 case ICmpInst::ICMP_SGE: return true;
2731 bool CmpInst::isOrdered(unsigned short predicate) {
2732 switch (predicate) {
2733 default: return false;
2734 case FCmpInst::FCMP_OEQ: case FCmpInst::FCMP_ONE: case FCmpInst::FCMP_OGT:
2735 case FCmpInst::FCMP_OLT: case FCmpInst::FCMP_OGE: case FCmpInst::FCMP_OLE:
2736 case FCmpInst::FCMP_ORD: return true;
2740 bool CmpInst::isUnordered(unsigned short predicate) {
2741 switch (predicate) {
2742 default: return false;
2743 case FCmpInst::FCMP_UEQ: case FCmpInst::FCMP_UNE: case FCmpInst::FCMP_UGT:
2744 case FCmpInst::FCMP_ULT: case FCmpInst::FCMP_UGE: case FCmpInst::FCMP_ULE:
2745 case FCmpInst::FCMP_UNO: return true;
2749 //===----------------------------------------------------------------------===//
2750 // SwitchInst Implementation
2751 //===----------------------------------------------------------------------===//
2753 void SwitchInst::init(Value *Value, BasicBlock *Default, unsigned NumCases) {
2754 assert(Value && Default);
2755 ReservedSpace = 2+NumCases*2;
2757 OperandList = allocHungoffUses(ReservedSpace);
2759 OperandList[0] = Value;
2760 OperandList[1] = Default;
2763 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
2764 /// switch on and a default destination. The number of additional cases can
2765 /// be specified here to make memory allocation more efficient. This
2766 /// constructor can also autoinsert before another instruction.
2767 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
2768 Instruction *InsertBefore)
2769 : TerminatorInst(Type::VoidTy, Instruction::Switch, 0, 0, InsertBefore) {
2770 init(Value, Default, NumCases);
2773 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
2774 /// switch on and a default destination. The number of additional cases can
2775 /// be specified here to make memory allocation more efficient. This
2776 /// constructor also autoinserts at the end of the specified BasicBlock.
2777 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
2778 BasicBlock *InsertAtEnd)
2779 : TerminatorInst(Type::VoidTy, Instruction::Switch, 0, 0, InsertAtEnd) {
2780 init(Value, Default, NumCases);
2783 SwitchInst::SwitchInst(const SwitchInst &SI)
2784 : TerminatorInst(Type::VoidTy, Instruction::Switch,
2785 allocHungoffUses(SI.getNumOperands()), SI.getNumOperands()) {
2786 Use *OL = OperandList, *InOL = SI.OperandList;
2787 for (unsigned i = 0, E = SI.getNumOperands(); i != E; i+=2) {
2789 OL[i+1] = InOL[i+1];
2793 SwitchInst::~SwitchInst() {
2794 dropHungoffUses(OperandList);
2798 /// addCase - Add an entry to the switch instruction...
2800 void SwitchInst::addCase(ConstantInt *OnVal, BasicBlock *Dest) {
2801 unsigned OpNo = NumOperands;
2802 if (OpNo+2 > ReservedSpace)
2803 resizeOperands(0); // Get more space!
2804 // Initialize some new operands.
2805 assert(OpNo+1 < ReservedSpace && "Growing didn't work!");
2806 NumOperands = OpNo+2;
2807 OperandList[OpNo] = OnVal;
2808 OperandList[OpNo+1] = Dest;
2811 /// removeCase - This method removes the specified successor from the switch
2812 /// instruction. Note that this cannot be used to remove the default
2813 /// destination (successor #0).
2815 void SwitchInst::removeCase(unsigned idx) {
2816 assert(idx != 0 && "Cannot remove the default case!");
2817 assert(idx*2 < getNumOperands() && "Successor index out of range!!!");
2819 unsigned NumOps = getNumOperands();
2820 Use *OL = OperandList;
2822 // Move everything after this operand down.
2824 // FIXME: we could just swap with the end of the list, then erase. However,
2825 // client might not expect this to happen. The code as it is thrashes the
2826 // use/def lists, which is kinda lame.
2827 for (unsigned i = (idx+1)*2; i != NumOps; i += 2) {
2829 OL[i-2+1] = OL[i+1];
2832 // Nuke the last value.
2833 OL[NumOps-2].set(0);
2834 OL[NumOps-2+1].set(0);
2835 NumOperands = NumOps-2;
2838 /// resizeOperands - resize operands - This adjusts the length of the operands
2839 /// list according to the following behavior:
2840 /// 1. If NumOps == 0, grow the operand list in response to a push_back style
2841 /// of operation. This grows the number of ops by 3 times.
2842 /// 2. If NumOps > NumOperands, reserve space for NumOps operands.
2843 /// 3. If NumOps == NumOperands, trim the reserved space.
2845 void SwitchInst::resizeOperands(unsigned NumOps) {
2846 unsigned e = getNumOperands();
2849 } else if (NumOps*2 > NumOperands) {
2850 // No resize needed.
2851 if (ReservedSpace >= NumOps) return;
2852 } else if (NumOps == NumOperands) {
2853 if (ReservedSpace == NumOps) return;
2858 ReservedSpace = NumOps;
2859 Use *NewOps = allocHungoffUses(NumOps);
2860 Use *OldOps = OperandList;
2861 for (unsigned i = 0; i != e; ++i) {
2862 NewOps[i] = OldOps[i];
2864 OperandList = NewOps;
2865 if (OldOps) Use::zap(OldOps, OldOps + e, true);
2869 BasicBlock *SwitchInst::getSuccessorV(unsigned idx) const {
2870 return getSuccessor(idx);
2872 unsigned SwitchInst::getNumSuccessorsV() const {
2873 return getNumSuccessors();
2875 void SwitchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
2876 setSuccessor(idx, B);
2879 // Define these methods here so vtables don't get emitted into every translation
2880 // unit that uses these classes.
2882 GetElementPtrInst *GetElementPtrInst::clone(LLVMContext&) const {
2883 return new(getNumOperands()) GetElementPtrInst(*this);
2886 BinaryOperator *BinaryOperator::clone(LLVMContext&) const {
2887 return Create(getOpcode(), Op<0>(), Op<1>());
2890 FCmpInst* FCmpInst::clone(LLVMContext &Context) const {
2891 return new FCmpInst(Context, getPredicate(), Op<0>(), Op<1>());
2893 ICmpInst* ICmpInst::clone(LLVMContext &Context) const {
2894 return new ICmpInst(Context, getPredicate(), Op<0>(), Op<1>());
2897 ExtractValueInst *ExtractValueInst::clone(LLVMContext&) const {
2898 return new ExtractValueInst(*this);
2900 InsertValueInst *InsertValueInst::clone(LLVMContext&) const {
2901 return new InsertValueInst(*this);
2904 MallocInst *MallocInst::clone(LLVMContext&) const {
2905 return new MallocInst(*this);
2908 AllocaInst *AllocaInst::clone(LLVMContext&) const {
2909 return new AllocaInst(*this);
2912 FreeInst *FreeInst::clone(LLVMContext&) const {
2913 return new FreeInst(getOperand(0));
2916 LoadInst *LoadInst::clone(LLVMContext&) const {
2917 return new LoadInst(*this);
2920 StoreInst *StoreInst::clone(LLVMContext&) const {
2921 return new StoreInst(*this);
2924 CastInst *TruncInst::clone(LLVMContext&) const {
2925 return new TruncInst(*this);
2928 CastInst *ZExtInst::clone(LLVMContext&) const {
2929 return new ZExtInst(*this);
2932 CastInst *SExtInst::clone(LLVMContext&) const {
2933 return new SExtInst(*this);
2936 CastInst *FPTruncInst::clone(LLVMContext&) const {
2937 return new FPTruncInst(*this);
2940 CastInst *FPExtInst::clone(LLVMContext&) const {
2941 return new FPExtInst(*this);
2944 CastInst *UIToFPInst::clone(LLVMContext&) const {
2945 return new UIToFPInst(*this);
2948 CastInst *SIToFPInst::clone(LLVMContext&) const {
2949 return new SIToFPInst(*this);
2952 CastInst *FPToUIInst::clone(LLVMContext&) const {
2953 return new FPToUIInst(*this);
2956 CastInst *FPToSIInst::clone(LLVMContext&) const {
2957 return new FPToSIInst(*this);
2960 CastInst *PtrToIntInst::clone(LLVMContext&) const {
2961 return new PtrToIntInst(*this);
2964 CastInst *IntToPtrInst::clone(LLVMContext&) const {
2965 return new IntToPtrInst(*this);
2968 CastInst *BitCastInst::clone(LLVMContext&) const {
2969 return new BitCastInst(*this);
2972 CallInst *CallInst::clone(LLVMContext&) const {
2973 return new(getNumOperands()) CallInst(*this);
2976 SelectInst *SelectInst::clone(LLVMContext&) const {
2977 return new(getNumOperands()) SelectInst(*this);
2980 VAArgInst *VAArgInst::clone(LLVMContext&) const {
2981 return new VAArgInst(*this);
2984 ExtractElementInst *ExtractElementInst::clone(LLVMContext&) const {
2985 return ExtractElementInst::Create(*this);
2988 InsertElementInst *InsertElementInst::clone(LLVMContext&) const {
2989 return InsertElementInst::Create(*this);
2992 ShuffleVectorInst *ShuffleVectorInst::clone(LLVMContext&) const {
2993 return new ShuffleVectorInst(*this);
2996 PHINode *PHINode::clone(LLVMContext&) const {
2997 return new PHINode(*this);
3000 ReturnInst *ReturnInst::clone(LLVMContext&) const {
3001 return new(getNumOperands()) ReturnInst(*this);
3004 BranchInst *BranchInst::clone(LLVMContext&) const {
3005 unsigned Ops(getNumOperands());
3006 return new(Ops, Ops == 1) BranchInst(*this);
3009 SwitchInst *SwitchInst::clone(LLVMContext&) const {
3010 return new SwitchInst(*this);
3013 InvokeInst *InvokeInst::clone(LLVMContext&) const {
3014 return new(getNumOperands()) InvokeInst(*this);
3017 UnwindInst *UnwindInst::clone(LLVMContext&) const {
3018 return new UnwindInst();
3021 UnreachableInst *UnreachableInst::clone(LLVMContext&) const {
3022 return new UnreachableInst();