1 //===-- Instructions.cpp - Implement the LLVM instructions ----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements all of the non-inline methods for the LLVM instruction
13 //===----------------------------------------------------------------------===//
15 #include "llvm/Constants.h"
16 #include "llvm/DerivedTypes.h"
17 #include "llvm/Function.h"
18 #include "llvm/Instructions.h"
19 #include "llvm/Support/ErrorHandling.h"
20 #include "llvm/Support/CallSite.h"
21 #include "llvm/Support/ConstantRange.h"
22 #include "llvm/Support/MathExtras.h"
23 #include "llvm/Support/Streams.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 = Context.getConstantInt(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)
1026 // GetElementPtr instructions have undefined results on overflow by default.
1027 setHasNoPointerOverflow(true);
1030 void GetElementPtrInst::init(Value *Ptr, Value *Idx, const std::string &Name) {
1031 assert(NumOperands == 2 && "NumOperands not initialized?");
1032 Use *OL = OperandList;
1038 // GetElementPtr instructions have undefined results on overflow by default.
1039 setHasNoPointerOverflow(true);
1042 GetElementPtrInst::GetElementPtrInst(const GetElementPtrInst &GEPI)
1043 : Instruction(GEPI.getType(), GetElementPtr,
1044 OperandTraits<GetElementPtrInst>::op_end(this)
1045 - GEPI.getNumOperands(),
1046 GEPI.getNumOperands()) {
1047 Use *OL = OperandList;
1048 Use *GEPIOL = GEPI.OperandList;
1049 for (unsigned i = 0, E = NumOperands; i != E; ++i)
1052 // Transfor the hasNoPointerOverflow() value from the original GEPI.
1053 setHasNoPointerOverflow(GEPI.hasNoPointerOverflow());
1056 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx,
1057 const std::string &Name, Instruction *InBe)
1058 : Instruction(Ptr->getType()->getContext().getPointerType(
1059 checkType(getIndexedType(Ptr->getType(),Idx)), retrieveAddrSpace(Ptr)),
1061 OperandTraits<GetElementPtrInst>::op_end(this) - 2,
1063 init(Ptr, Idx, Name);
1066 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx,
1067 const std::string &Name, BasicBlock *IAE)
1068 : Instruction(Ptr->getType()->getContext().getPointerType(
1069 checkType(getIndexedType(Ptr->getType(),Idx)),
1070 retrieveAddrSpace(Ptr)),
1072 OperandTraits<GetElementPtrInst>::op_end(this) - 2,
1074 init(Ptr, Idx, Name);
1077 /// getIndexedType - Returns the type of the element that would be accessed with
1078 /// a gep instruction with the specified parameters.
1080 /// The Idxs pointer should point to a continuous piece of memory containing the
1081 /// indices, either as Value* or uint64_t.
1083 /// A null type is returned if the indices are invalid for the specified
1086 template <typename IndexTy>
1087 static const Type* getIndexedTypeInternal(const Type *Ptr, IndexTy const *Idxs,
1089 const PointerType *PTy = dyn_cast<PointerType>(Ptr);
1090 if (!PTy) return 0; // Type isn't a pointer type!
1091 const Type *Agg = PTy->getElementType();
1093 // Handle the special case of the empty set index set, which is always valid.
1097 // If there is at least one index, the top level type must be sized, otherwise
1098 // it cannot be 'stepped over'. We explicitly allow abstract types (those
1099 // that contain opaque types) under the assumption that it will be resolved to
1100 // a sane type later.
1101 if (!Agg->isSized() && !Agg->isAbstract())
1104 unsigned CurIdx = 1;
1105 for (; CurIdx != NumIdx; ++CurIdx) {
1106 const CompositeType *CT = dyn_cast<CompositeType>(Agg);
1107 if (!CT || isa<PointerType>(CT)) return 0;
1108 IndexTy Index = Idxs[CurIdx];
1109 if (!CT->indexValid(Index)) return 0;
1110 Agg = CT->getTypeAtIndex(Index);
1112 // If the new type forwards to another type, then it is in the middle
1113 // of being refined to another type (and hence, may have dropped all
1114 // references to what it was using before). So, use the new forwarded
1116 if (const Type *Ty = Agg->getForwardedType())
1119 return CurIdx == NumIdx ? Agg : 0;
1122 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr,
1125 return getIndexedTypeInternal(Ptr, Idxs, NumIdx);
1128 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr,
1129 uint64_t const *Idxs,
1131 return getIndexedTypeInternal(Ptr, Idxs, NumIdx);
1134 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr, Value *Idx) {
1135 const PointerType *PTy = dyn_cast<PointerType>(Ptr);
1136 if (!PTy) return 0; // Type isn't a pointer type!
1138 // Check the pointer index.
1139 if (!PTy->indexValid(Idx)) return 0;
1141 return PTy->getElementType();
1145 /// hasAllZeroIndices - Return true if all of the indices of this GEP are
1146 /// zeros. If so, the result pointer and the first operand have the same
1147 /// value, just potentially different types.
1148 bool GetElementPtrInst::hasAllZeroIndices() const {
1149 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1150 if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(i))) {
1151 if (!CI->isZero()) return false;
1159 /// hasAllConstantIndices - Return true if all of the indices of this GEP are
1160 /// constant integers. If so, the result pointer and the first operand have
1161 /// a constant offset between them.
1162 bool GetElementPtrInst::hasAllConstantIndices() const {
1163 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1164 if (!isa<ConstantInt>(getOperand(i)))
1171 //===----------------------------------------------------------------------===//
1172 // ExtractElementInst Implementation
1173 //===----------------------------------------------------------------------===//
1175 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
1176 const std::string &Name,
1177 Instruction *InsertBef)
1178 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1180 OperandTraits<ExtractElementInst>::op_begin(this),
1182 assert(isValidOperands(Val, Index) &&
1183 "Invalid extractelement instruction operands!");
1189 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
1190 const std::string &Name,
1191 BasicBlock *InsertAE)
1192 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1194 OperandTraits<ExtractElementInst>::op_begin(this),
1196 assert(isValidOperands(Val, Index) &&
1197 "Invalid extractelement instruction operands!");
1205 bool ExtractElementInst::isValidOperands(const Value *Val, const Value *Index) {
1206 if (!isa<VectorType>(Val->getType()) || Index->getType() != Type::Int32Ty)
1212 //===----------------------------------------------------------------------===//
1213 // InsertElementInst Implementation
1214 //===----------------------------------------------------------------------===//
1216 InsertElementInst::InsertElementInst(const InsertElementInst &IE)
1217 : Instruction(IE.getType(), InsertElement,
1218 OperandTraits<InsertElementInst>::op_begin(this), 3) {
1219 Op<0>() = IE.Op<0>();
1220 Op<1>() = IE.Op<1>();
1221 Op<2>() = IE.Op<2>();
1223 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
1224 const std::string &Name,
1225 Instruction *InsertBef)
1226 : Instruction(Vec->getType(), InsertElement,
1227 OperandTraits<InsertElementInst>::op_begin(this),
1229 assert(isValidOperands(Vec, Elt, Index) &&
1230 "Invalid insertelement instruction operands!");
1237 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
1238 const std::string &Name,
1239 BasicBlock *InsertAE)
1240 : Instruction(Vec->getType(), InsertElement,
1241 OperandTraits<InsertElementInst>::op_begin(this),
1243 assert(isValidOperands(Vec, Elt, Index) &&
1244 "Invalid insertelement instruction operands!");
1252 bool InsertElementInst::isValidOperands(const Value *Vec, const Value *Elt,
1253 const Value *Index) {
1254 if (!isa<VectorType>(Vec->getType()))
1255 return false; // First operand of insertelement must be vector type.
1257 if (Elt->getType() != cast<VectorType>(Vec->getType())->getElementType())
1258 return false;// Second operand of insertelement must be vector element type.
1260 if (Index->getType() != Type::Int32Ty)
1261 return false; // Third operand of insertelement must be i32.
1266 //===----------------------------------------------------------------------===//
1267 // ShuffleVectorInst Implementation
1268 //===----------------------------------------------------------------------===//
1270 ShuffleVectorInst::ShuffleVectorInst(const ShuffleVectorInst &SV)
1271 : Instruction(SV.getType(), ShuffleVector,
1272 OperandTraits<ShuffleVectorInst>::op_begin(this),
1273 OperandTraits<ShuffleVectorInst>::operands(this)) {
1274 Op<0>() = SV.Op<0>();
1275 Op<1>() = SV.Op<1>();
1276 Op<2>() = SV.Op<2>();
1279 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1280 const std::string &Name,
1281 Instruction *InsertBefore)
1282 : Instruction(V1->getType()->getContext().getVectorType(
1283 cast<VectorType>(V1->getType())->getElementType(),
1284 cast<VectorType>(Mask->getType())->getNumElements()),
1286 OperandTraits<ShuffleVectorInst>::op_begin(this),
1287 OperandTraits<ShuffleVectorInst>::operands(this),
1289 assert(isValidOperands(V1, V2, Mask) &&
1290 "Invalid shuffle vector instruction operands!");
1297 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1298 const std::string &Name,
1299 BasicBlock *InsertAtEnd)
1300 : Instruction(V1->getType(), ShuffleVector,
1301 OperandTraits<ShuffleVectorInst>::op_begin(this),
1302 OperandTraits<ShuffleVectorInst>::operands(this),
1304 assert(isValidOperands(V1, V2, Mask) &&
1305 "Invalid shuffle vector instruction operands!");
1313 bool ShuffleVectorInst::isValidOperands(const Value *V1, const Value *V2,
1314 const Value *Mask) {
1315 if (!isa<VectorType>(V1->getType()) || V1->getType() != V2->getType())
1318 const VectorType *MaskTy = dyn_cast<VectorType>(Mask->getType());
1319 if (!isa<Constant>(Mask) || MaskTy == 0 ||
1320 MaskTy->getElementType() != Type::Int32Ty)
1325 /// getMaskValue - Return the index from the shuffle mask for the specified
1326 /// output result. This is either -1 if the element is undef or a number less
1327 /// than 2*numelements.
1328 int ShuffleVectorInst::getMaskValue(unsigned i) const {
1329 const Constant *Mask = cast<Constant>(getOperand(2));
1330 if (isa<UndefValue>(Mask)) return -1;
1331 if (isa<ConstantAggregateZero>(Mask)) return 0;
1332 const ConstantVector *MaskCV = cast<ConstantVector>(Mask);
1333 assert(i < MaskCV->getNumOperands() && "Index out of range");
1335 if (isa<UndefValue>(MaskCV->getOperand(i)))
1337 return cast<ConstantInt>(MaskCV->getOperand(i))->getZExtValue();
1340 //===----------------------------------------------------------------------===//
1341 // InsertValueInst Class
1342 //===----------------------------------------------------------------------===//
1344 void InsertValueInst::init(Value *Agg, Value *Val, const unsigned *Idx,
1345 unsigned NumIdx, const std::string &Name) {
1346 assert(NumOperands == 2 && "NumOperands not initialized?");
1350 Indices.insert(Indices.end(), Idx, Idx + NumIdx);
1354 void InsertValueInst::init(Value *Agg, Value *Val, unsigned Idx,
1355 const std::string &Name) {
1356 assert(NumOperands == 2 && "NumOperands not initialized?");
1360 Indices.push_back(Idx);
1364 InsertValueInst::InsertValueInst(const InsertValueInst &IVI)
1365 : Instruction(IVI.getType(), InsertValue,
1366 OperandTraits<InsertValueInst>::op_begin(this), 2),
1367 Indices(IVI.Indices) {
1368 Op<0>() = IVI.getOperand(0);
1369 Op<1>() = IVI.getOperand(1);
1372 InsertValueInst::InsertValueInst(Value *Agg,
1375 const std::string &Name,
1376 Instruction *InsertBefore)
1377 : Instruction(Agg->getType(), InsertValue,
1378 OperandTraits<InsertValueInst>::op_begin(this),
1380 init(Agg, Val, Idx, Name);
1383 InsertValueInst::InsertValueInst(Value *Agg,
1386 const std::string &Name,
1387 BasicBlock *InsertAtEnd)
1388 : Instruction(Agg->getType(), InsertValue,
1389 OperandTraits<InsertValueInst>::op_begin(this),
1391 init(Agg, Val, Idx, Name);
1394 //===----------------------------------------------------------------------===//
1395 // ExtractValueInst Class
1396 //===----------------------------------------------------------------------===//
1398 void ExtractValueInst::init(const unsigned *Idx, unsigned NumIdx,
1399 const std::string &Name) {
1400 assert(NumOperands == 1 && "NumOperands not initialized?");
1402 Indices.insert(Indices.end(), Idx, Idx + NumIdx);
1406 void ExtractValueInst::init(unsigned Idx, const std::string &Name) {
1407 assert(NumOperands == 1 && "NumOperands not initialized?");
1409 Indices.push_back(Idx);
1413 ExtractValueInst::ExtractValueInst(const ExtractValueInst &EVI)
1414 : UnaryInstruction(EVI.getType(), ExtractValue, EVI.getOperand(0)),
1415 Indices(EVI.Indices) {
1418 // getIndexedType - Returns the type of the element that would be extracted
1419 // with an extractvalue instruction with the specified parameters.
1421 // A null type is returned if the indices are invalid for the specified
1424 const Type* ExtractValueInst::getIndexedType(const Type *Agg,
1425 const unsigned *Idxs,
1427 unsigned CurIdx = 0;
1428 for (; CurIdx != NumIdx; ++CurIdx) {
1429 const CompositeType *CT = dyn_cast<CompositeType>(Agg);
1430 if (!CT || isa<PointerType>(CT) || isa<VectorType>(CT)) return 0;
1431 unsigned Index = Idxs[CurIdx];
1432 if (!CT->indexValid(Index)) return 0;
1433 Agg = CT->getTypeAtIndex(Index);
1435 // If the new type forwards to another type, then it is in the middle
1436 // of being refined to another type (and hence, may have dropped all
1437 // references to what it was using before). So, use the new forwarded
1439 if (const Type *Ty = Agg->getForwardedType())
1442 return CurIdx == NumIdx ? Agg : 0;
1445 const Type* ExtractValueInst::getIndexedType(const Type *Agg,
1447 return getIndexedType(Agg, &Idx, 1);
1450 //===----------------------------------------------------------------------===//
1451 // BinaryOperator Class
1452 //===----------------------------------------------------------------------===//
1454 /// AdjustIType - Map Add, Sub, and Mul to FAdd, FSub, and FMul when the
1455 /// type is floating-point, to help provide compatibility with an older API.
1457 static BinaryOperator::BinaryOps AdjustIType(BinaryOperator::BinaryOps iType,
1459 // API compatibility: Adjust integer opcodes to floating-point opcodes.
1460 if (Ty->isFPOrFPVector()) {
1461 if (iType == BinaryOperator::Add) iType = BinaryOperator::FAdd;
1462 else if (iType == BinaryOperator::Sub) iType = BinaryOperator::FSub;
1463 else if (iType == BinaryOperator::Mul) iType = BinaryOperator::FMul;
1468 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
1469 const Type *Ty, const std::string &Name,
1470 Instruction *InsertBefore)
1471 : Instruction(Ty, AdjustIType(iType, Ty),
1472 OperandTraits<BinaryOperator>::op_begin(this),
1473 OperandTraits<BinaryOperator>::operands(this),
1477 init(AdjustIType(iType, Ty));
1481 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
1482 const Type *Ty, const std::string &Name,
1483 BasicBlock *InsertAtEnd)
1484 : Instruction(Ty, AdjustIType(iType, Ty),
1485 OperandTraits<BinaryOperator>::op_begin(this),
1486 OperandTraits<BinaryOperator>::operands(this),
1490 init(AdjustIType(iType, Ty));
1495 void BinaryOperator::init(BinaryOps iType) {
1496 Value *LHS = getOperand(0), *RHS = getOperand(1);
1497 LHS = LHS; RHS = RHS; // Silence warnings.
1498 assert(LHS->getType() == RHS->getType() &&
1499 "Binary operator operand types must match!");
1504 assert(getType() == LHS->getType() &&
1505 "Arithmetic operation should return same type as operands!");
1506 assert(getType()->isIntOrIntVector() &&
1507 "Tried to create an integer operation on a non-integer type!");
1509 case FAdd: case FSub:
1511 assert(getType() == LHS->getType() &&
1512 "Arithmetic operation should return same type as operands!");
1513 assert(getType()->isFPOrFPVector() &&
1514 "Tried to create a floating-point operation on a "
1515 "non-floating-point type!");
1519 assert(getType() == LHS->getType() &&
1520 "Arithmetic operation should return same type as operands!");
1521 assert((getType()->isInteger() || (isa<VectorType>(getType()) &&
1522 cast<VectorType>(getType())->getElementType()->isInteger())) &&
1523 "Incorrect operand type (not integer) for S/UDIV");
1526 assert(getType() == LHS->getType() &&
1527 "Arithmetic operation should return same type as operands!");
1528 assert(getType()->isFPOrFPVector() &&
1529 "Incorrect operand type (not floating point) for FDIV");
1533 assert(getType() == LHS->getType() &&
1534 "Arithmetic operation should return same type as operands!");
1535 assert((getType()->isInteger() || (isa<VectorType>(getType()) &&
1536 cast<VectorType>(getType())->getElementType()->isInteger())) &&
1537 "Incorrect operand type (not integer) for S/UREM");
1540 assert(getType() == LHS->getType() &&
1541 "Arithmetic operation should return same type as operands!");
1542 assert(getType()->isFPOrFPVector() &&
1543 "Incorrect operand type (not floating point) for FREM");
1548 assert(getType() == LHS->getType() &&
1549 "Shift 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 shift operation on a non-integral type!");
1557 assert(getType() == LHS->getType() &&
1558 "Logical operation should return same type as operands!");
1559 assert((getType()->isInteger() ||
1560 (isa<VectorType>(getType()) &&
1561 cast<VectorType>(getType())->getElementType()->isInteger())) &&
1562 "Tried to create a logical operation on a non-integral type!");
1570 BinaryOperator *BinaryOperator::Create(BinaryOps Op, Value *S1, Value *S2,
1571 const std::string &Name,
1572 Instruction *InsertBefore) {
1573 assert(S1->getType() == S2->getType() &&
1574 "Cannot create binary operator with two operands of differing type!");
1575 return new BinaryOperator(Op, S1, S2, S1->getType(), Name, InsertBefore);
1578 BinaryOperator *BinaryOperator::Create(BinaryOps Op, Value *S1, Value *S2,
1579 const std::string &Name,
1580 BasicBlock *InsertAtEnd) {
1581 BinaryOperator *Res = Create(Op, S1, S2, Name);
1582 InsertAtEnd->getInstList().push_back(Res);
1586 BinaryOperator *BinaryOperator::CreateNeg(LLVMContext &Context,
1587 Value *Op, const std::string &Name,
1588 Instruction *InsertBefore) {
1589 Value *zero = Context.getZeroValueForNegation(Op->getType());
1590 return new BinaryOperator(Instruction::Sub,
1592 Op->getType(), Name, InsertBefore);
1595 BinaryOperator *BinaryOperator::CreateNeg(LLVMContext &Context,
1596 Value *Op, const std::string &Name,
1597 BasicBlock *InsertAtEnd) {
1598 Value *zero = Context.getZeroValueForNegation(Op->getType());
1599 return new BinaryOperator(Instruction::Sub,
1601 Op->getType(), Name, InsertAtEnd);
1604 BinaryOperator *BinaryOperator::CreateFNeg(LLVMContext &Context,
1605 Value *Op, const std::string &Name,
1606 Instruction *InsertBefore) {
1607 Value *zero = Context.getZeroValueForNegation(Op->getType());
1608 return new BinaryOperator(Instruction::FSub,
1610 Op->getType(), Name, InsertBefore);
1613 BinaryOperator *BinaryOperator::CreateFNeg(LLVMContext &Context,
1614 Value *Op, const std::string &Name,
1615 BasicBlock *InsertAtEnd) {
1616 Value *zero = Context.getZeroValueForNegation(Op->getType());
1617 return new BinaryOperator(Instruction::FSub,
1619 Op->getType(), Name, InsertAtEnd);
1622 BinaryOperator *BinaryOperator::CreateNot(LLVMContext &Context,
1623 Value *Op, const std::string &Name,
1624 Instruction *InsertBefore) {
1626 if (const VectorType *PTy = dyn_cast<VectorType>(Op->getType())) {
1627 C = Context.getAllOnesValue(PTy->getElementType());
1628 C = Context.getConstantVector(
1629 std::vector<Constant*>(PTy->getNumElements(), C));
1631 C = Context.getAllOnesValue(Op->getType());
1634 return new BinaryOperator(Instruction::Xor, Op, C,
1635 Op->getType(), Name, InsertBefore);
1638 BinaryOperator *BinaryOperator::CreateNot(LLVMContext &Context,
1639 Value *Op, const std::string &Name,
1640 BasicBlock *InsertAtEnd) {
1642 if (const VectorType *PTy = dyn_cast<VectorType>(Op->getType())) {
1643 // Create a vector of all ones values.
1644 Constant *Elt = Context.getAllOnesValue(PTy->getElementType());
1645 AllOnes = Context.getConstantVector(
1646 std::vector<Constant*>(PTy->getNumElements(), Elt));
1648 AllOnes = Context.getAllOnesValue(Op->getType());
1651 return new BinaryOperator(Instruction::Xor, Op, AllOnes,
1652 Op->getType(), Name, InsertAtEnd);
1656 // isConstantAllOnes - Helper function for several functions below
1657 static inline bool isConstantAllOnes(const Value *V) {
1658 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V))
1659 return CI->isAllOnesValue();
1660 if (const ConstantVector *CV = dyn_cast<ConstantVector>(V))
1661 return CV->isAllOnesValue();
1665 bool BinaryOperator::isNeg(const Value *V) {
1666 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1667 if (Bop->getOpcode() == Instruction::Sub)
1668 if (Constant* C = dyn_cast<Constant>(Bop->getOperand(0)))
1669 return C->isNegativeZeroValue();
1673 bool BinaryOperator::isFNeg(const Value *V) {
1674 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1675 if (Bop->getOpcode() == Instruction::FSub)
1676 if (Constant* C = dyn_cast<Constant>(Bop->getOperand(0)))
1677 return C->isNegativeZeroValue();
1681 bool BinaryOperator::isNot(const Value *V) {
1682 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1683 return (Bop->getOpcode() == Instruction::Xor &&
1684 (isConstantAllOnes(Bop->getOperand(1)) ||
1685 isConstantAllOnes(Bop->getOperand(0))));
1689 Value *BinaryOperator::getNegArgument(Value *BinOp) {
1690 return cast<BinaryOperator>(BinOp)->getOperand(1);
1693 const Value *BinaryOperator::getNegArgument(const Value *BinOp) {
1694 return getNegArgument(const_cast<Value*>(BinOp));
1697 Value *BinaryOperator::getFNegArgument(Value *BinOp) {
1698 return cast<BinaryOperator>(BinOp)->getOperand(1);
1701 const Value *BinaryOperator::getFNegArgument(const Value *BinOp) {
1702 return getFNegArgument(const_cast<Value*>(BinOp));
1705 Value *BinaryOperator::getNotArgument(Value *BinOp) {
1706 assert(isNot(BinOp) && "getNotArgument on non-'not' instruction!");
1707 BinaryOperator *BO = cast<BinaryOperator>(BinOp);
1708 Value *Op0 = BO->getOperand(0);
1709 Value *Op1 = BO->getOperand(1);
1710 if (isConstantAllOnes(Op0)) return Op1;
1712 assert(isConstantAllOnes(Op1));
1716 const Value *BinaryOperator::getNotArgument(const Value *BinOp) {
1717 return getNotArgument(const_cast<Value*>(BinOp));
1721 // swapOperands - Exchange the two operands to this instruction. This
1722 // instruction is safe to use on any binary instruction and does not
1723 // modify the semantics of the instruction. If the instruction is
1724 // order dependent (SetLT f.e.) the opcode is changed.
1726 bool BinaryOperator::swapOperands() {
1727 if (!isCommutative())
1728 return true; // Can't commute operands
1729 Op<0>().swap(Op<1>());
1733 //===----------------------------------------------------------------------===//
1735 //===----------------------------------------------------------------------===//
1737 // Just determine if this cast only deals with integral->integral conversion.
1738 bool CastInst::isIntegerCast() const {
1739 switch (getOpcode()) {
1740 default: return false;
1741 case Instruction::ZExt:
1742 case Instruction::SExt:
1743 case Instruction::Trunc:
1745 case Instruction::BitCast:
1746 return getOperand(0)->getType()->isInteger() && getType()->isInteger();
1750 bool CastInst::isLosslessCast() const {
1751 // Only BitCast can be lossless, exit fast if we're not BitCast
1752 if (getOpcode() != Instruction::BitCast)
1755 // Identity cast is always lossless
1756 const Type* SrcTy = getOperand(0)->getType();
1757 const Type* DstTy = getType();
1761 // Pointer to pointer is always lossless.
1762 if (isa<PointerType>(SrcTy))
1763 return isa<PointerType>(DstTy);
1764 return false; // Other types have no identity values
1767 /// This function determines if the CastInst does not require any bits to be
1768 /// changed in order to effect the cast. Essentially, it identifies cases where
1769 /// no code gen is necessary for the cast, hence the name no-op cast. For
1770 /// example, the following are all no-op casts:
1771 /// # bitcast i32* %x to i8*
1772 /// # bitcast <2 x i32> %x to <4 x i16>
1773 /// # ptrtoint i32* %x to i32 ; on 32-bit plaforms only
1774 /// @brief Determine if a cast is a no-op.
1775 bool CastInst::isNoopCast(const Type *IntPtrTy) const {
1776 switch (getOpcode()) {
1778 assert(!"Invalid CastOp");
1779 case Instruction::Trunc:
1780 case Instruction::ZExt:
1781 case Instruction::SExt:
1782 case Instruction::FPTrunc:
1783 case Instruction::FPExt:
1784 case Instruction::UIToFP:
1785 case Instruction::SIToFP:
1786 case Instruction::FPToUI:
1787 case Instruction::FPToSI:
1788 return false; // These always modify bits
1789 case Instruction::BitCast:
1790 return true; // BitCast never modifies bits.
1791 case Instruction::PtrToInt:
1792 return IntPtrTy->getScalarSizeInBits() ==
1793 getType()->getScalarSizeInBits();
1794 case Instruction::IntToPtr:
1795 return IntPtrTy->getScalarSizeInBits() ==
1796 getOperand(0)->getType()->getScalarSizeInBits();
1800 /// This function determines if a pair of casts can be eliminated and what
1801 /// opcode should be used in the elimination. This assumes that there are two
1802 /// instructions like this:
1803 /// * %F = firstOpcode SrcTy %x to MidTy
1804 /// * %S = secondOpcode MidTy %F to DstTy
1805 /// The function returns a resultOpcode so these two casts can be replaced with:
1806 /// * %Replacement = resultOpcode %SrcTy %x to DstTy
1807 /// If no such cast is permited, the function returns 0.
1808 unsigned CastInst::isEliminableCastPair(
1809 Instruction::CastOps firstOp, Instruction::CastOps secondOp,
1810 const Type *SrcTy, const Type *MidTy, const Type *DstTy, const Type *IntPtrTy)
1812 // Define the 144 possibilities for these two cast instructions. The values
1813 // in this matrix determine what to do in a given situation and select the
1814 // case in the switch below. The rows correspond to firstOp, the columns
1815 // correspond to secondOp. In looking at the table below, keep in mind
1816 // the following cast properties:
1818 // Size Compare Source Destination
1819 // Operator Src ? Size Type Sign Type Sign
1820 // -------- ------------ ------------------- ---------------------
1821 // TRUNC > Integer Any Integral Any
1822 // ZEXT < Integral Unsigned Integer Any
1823 // SEXT < Integral Signed Integer Any
1824 // FPTOUI n/a FloatPt n/a Integral Unsigned
1825 // FPTOSI n/a FloatPt n/a Integral Signed
1826 // UITOFP n/a Integral Unsigned FloatPt n/a
1827 // SITOFP n/a Integral Signed FloatPt n/a
1828 // FPTRUNC > FloatPt n/a FloatPt n/a
1829 // FPEXT < FloatPt n/a FloatPt n/a
1830 // PTRTOINT n/a Pointer n/a Integral Unsigned
1831 // INTTOPTR n/a Integral Unsigned Pointer n/a
1832 // BITCONVERT = FirstClass n/a FirstClass n/a
1834 // NOTE: some transforms are safe, but we consider them to be non-profitable.
1835 // For example, we could merge "fptoui double to i32" + "zext i32 to i64",
1836 // into "fptoui double to i64", but this loses information about the range
1837 // of the produced value (we no longer know the top-part is all zeros).
1838 // Further this conversion is often much more expensive for typical hardware,
1839 // and causes issues when building libgcc. We disallow fptosi+sext for the
1841 const unsigned numCastOps =
1842 Instruction::CastOpsEnd - Instruction::CastOpsBegin;
1843 static const uint8_t CastResults[numCastOps][numCastOps] = {
1844 // T F F U S F F P I B -+
1845 // R Z S P P I I T P 2 N T |
1846 // U E E 2 2 2 2 R E I T C +- secondOp
1847 // N X X U S F F N X N 2 V |
1848 // C T T I I P P C T T P T -+
1849 { 1, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // Trunc -+
1850 { 8, 1, 9,99,99, 2, 0,99,99,99, 2, 3 }, // ZExt |
1851 { 8, 0, 1,99,99, 0, 2,99,99,99, 0, 3 }, // SExt |
1852 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // FPToUI |
1853 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // FPToSI |
1854 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4 }, // UIToFP +- firstOp
1855 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4 }, // SIToFP |
1856 { 99,99,99, 0, 0,99,99, 1, 0,99,99, 4 }, // FPTrunc |
1857 { 99,99,99, 2, 2,99,99,10, 2,99,99, 4 }, // FPExt |
1858 { 1, 0, 0,99,99, 0, 0,99,99,99, 7, 3 }, // PtrToInt |
1859 { 99,99,99,99,99,99,99,99,99,13,99,12 }, // IntToPtr |
1860 { 5, 5, 5, 6, 6, 5, 5, 6, 6,11, 5, 1 }, // BitCast -+
1863 int ElimCase = CastResults[firstOp-Instruction::CastOpsBegin]
1864 [secondOp-Instruction::CastOpsBegin];
1867 // categorically disallowed
1870 // allowed, use first cast's opcode
1873 // allowed, use second cast's opcode
1876 // no-op cast in second op implies firstOp as long as the DestTy
1878 if (DstTy->isInteger())
1882 // no-op cast in second op implies firstOp as long as the DestTy
1883 // is floating point
1884 if (DstTy->isFloatingPoint())
1888 // no-op cast in first op implies secondOp as long as the SrcTy
1890 if (SrcTy->isInteger())
1894 // no-op cast in first op implies secondOp as long as the SrcTy
1895 // is a floating point
1896 if (SrcTy->isFloatingPoint())
1900 // ptrtoint, inttoptr -> bitcast (ptr -> ptr) if int size is >= ptr size
1901 unsigned PtrSize = IntPtrTy->getScalarSizeInBits();
1902 unsigned MidSize = MidTy->getScalarSizeInBits();
1903 if (MidSize >= PtrSize)
1904 return Instruction::BitCast;
1908 // ext, trunc -> bitcast, if the SrcTy and DstTy are same size
1909 // ext, trunc -> ext, if sizeof(SrcTy) < sizeof(DstTy)
1910 // ext, trunc -> trunc, if sizeof(SrcTy) > sizeof(DstTy)
1911 unsigned SrcSize = SrcTy->getScalarSizeInBits();
1912 unsigned DstSize = DstTy->getScalarSizeInBits();
1913 if (SrcSize == DstSize)
1914 return Instruction::BitCast;
1915 else if (SrcSize < DstSize)
1919 case 9: // zext, sext -> zext, because sext can't sign extend after zext
1920 return Instruction::ZExt;
1922 // fpext followed by ftrunc is allowed if the bit size returned to is
1923 // the same as the original, in which case its just a bitcast
1925 return Instruction::BitCast;
1926 return 0; // If the types are not the same we can't eliminate it.
1928 // bitcast followed by ptrtoint is allowed as long as the bitcast
1929 // is a pointer to pointer cast.
1930 if (isa<PointerType>(SrcTy) && isa<PointerType>(MidTy))
1934 // inttoptr, bitcast -> intptr if bitcast is a ptr to ptr cast
1935 if (isa<PointerType>(MidTy) && isa<PointerType>(DstTy))
1939 // inttoptr, ptrtoint -> bitcast if SrcSize<=PtrSize and SrcSize==DstSize
1940 unsigned PtrSize = IntPtrTy->getScalarSizeInBits();
1941 unsigned SrcSize = SrcTy->getScalarSizeInBits();
1942 unsigned DstSize = DstTy->getScalarSizeInBits();
1943 if (SrcSize <= PtrSize && SrcSize == DstSize)
1944 return Instruction::BitCast;
1948 // cast combination can't happen (error in input). This is for all cases
1949 // where the MidTy is not the same for the two cast instructions.
1950 assert(!"Invalid Cast Combination");
1953 assert(!"Error in CastResults table!!!");
1959 CastInst *CastInst::Create(Instruction::CastOps op, Value *S, const Type *Ty,
1960 const std::string &Name, Instruction *InsertBefore) {
1961 // Construct and return the appropriate CastInst subclass
1963 case Trunc: return new TruncInst (S, Ty, Name, InsertBefore);
1964 case ZExt: return new ZExtInst (S, Ty, Name, InsertBefore);
1965 case SExt: return new SExtInst (S, Ty, Name, InsertBefore);
1966 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertBefore);
1967 case FPExt: return new FPExtInst (S, Ty, Name, InsertBefore);
1968 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertBefore);
1969 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertBefore);
1970 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertBefore);
1971 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertBefore);
1972 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertBefore);
1973 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertBefore);
1974 case BitCast: return new BitCastInst (S, Ty, Name, InsertBefore);
1976 assert(!"Invalid opcode provided");
1981 CastInst *CastInst::Create(Instruction::CastOps op, Value *S, const Type *Ty,
1982 const std::string &Name, BasicBlock *InsertAtEnd) {
1983 // Construct and return the appropriate CastInst subclass
1985 case Trunc: return new TruncInst (S, Ty, Name, InsertAtEnd);
1986 case ZExt: return new ZExtInst (S, Ty, Name, InsertAtEnd);
1987 case SExt: return new SExtInst (S, Ty, Name, InsertAtEnd);
1988 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertAtEnd);
1989 case FPExt: return new FPExtInst (S, Ty, Name, InsertAtEnd);
1990 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertAtEnd);
1991 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertAtEnd);
1992 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertAtEnd);
1993 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertAtEnd);
1994 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertAtEnd);
1995 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertAtEnd);
1996 case BitCast: return new BitCastInst (S, Ty, Name, InsertAtEnd);
1998 assert(!"Invalid opcode provided");
2003 CastInst *CastInst::CreateZExtOrBitCast(Value *S, const Type *Ty,
2004 const std::string &Name,
2005 Instruction *InsertBefore) {
2006 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2007 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2008 return Create(Instruction::ZExt, S, Ty, Name, InsertBefore);
2011 CastInst *CastInst::CreateZExtOrBitCast(Value *S, const Type *Ty,
2012 const std::string &Name,
2013 BasicBlock *InsertAtEnd) {
2014 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2015 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2016 return Create(Instruction::ZExt, S, Ty, Name, InsertAtEnd);
2019 CastInst *CastInst::CreateSExtOrBitCast(Value *S, const Type *Ty,
2020 const std::string &Name,
2021 Instruction *InsertBefore) {
2022 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2023 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2024 return Create(Instruction::SExt, S, Ty, Name, InsertBefore);
2027 CastInst *CastInst::CreateSExtOrBitCast(Value *S, const Type *Ty,
2028 const std::string &Name,
2029 BasicBlock *InsertAtEnd) {
2030 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2031 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2032 return Create(Instruction::SExt, S, Ty, Name, InsertAtEnd);
2035 CastInst *CastInst::CreateTruncOrBitCast(Value *S, const Type *Ty,
2036 const std::string &Name,
2037 Instruction *InsertBefore) {
2038 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2039 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2040 return Create(Instruction::Trunc, S, Ty, Name, InsertBefore);
2043 CastInst *CastInst::CreateTruncOrBitCast(Value *S, const Type *Ty,
2044 const std::string &Name,
2045 BasicBlock *InsertAtEnd) {
2046 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2047 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2048 return Create(Instruction::Trunc, S, Ty, Name, InsertAtEnd);
2051 CastInst *CastInst::CreatePointerCast(Value *S, const Type *Ty,
2052 const std::string &Name,
2053 BasicBlock *InsertAtEnd) {
2054 assert(isa<PointerType>(S->getType()) && "Invalid cast");
2055 assert((Ty->isInteger() || isa<PointerType>(Ty)) &&
2058 if (Ty->isInteger())
2059 return Create(Instruction::PtrToInt, S, Ty, Name, InsertAtEnd);
2060 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2063 /// @brief Create a BitCast or a PtrToInt cast instruction
2064 CastInst *CastInst::CreatePointerCast(Value *S, const Type *Ty,
2065 const std::string &Name,
2066 Instruction *InsertBefore) {
2067 assert(isa<PointerType>(S->getType()) && "Invalid cast");
2068 assert((Ty->isInteger() || isa<PointerType>(Ty)) &&
2071 if (Ty->isInteger())
2072 return Create(Instruction::PtrToInt, S, Ty, Name, InsertBefore);
2073 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2076 CastInst *CastInst::CreateIntegerCast(Value *C, const Type *Ty,
2077 bool isSigned, const std::string &Name,
2078 Instruction *InsertBefore) {
2079 assert(C->getType()->isInteger() && Ty->isInteger() && "Invalid cast");
2080 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2081 unsigned DstBits = Ty->getScalarSizeInBits();
2082 Instruction::CastOps opcode =
2083 (SrcBits == DstBits ? Instruction::BitCast :
2084 (SrcBits > DstBits ? Instruction::Trunc :
2085 (isSigned ? Instruction::SExt : Instruction::ZExt)));
2086 return Create(opcode, C, Ty, Name, InsertBefore);
2089 CastInst *CastInst::CreateIntegerCast(Value *C, const Type *Ty,
2090 bool isSigned, const std::string &Name,
2091 BasicBlock *InsertAtEnd) {
2092 assert(C->getType()->isIntOrIntVector() && Ty->isIntOrIntVector() &&
2094 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2095 unsigned DstBits = Ty->getScalarSizeInBits();
2096 Instruction::CastOps opcode =
2097 (SrcBits == DstBits ? Instruction::BitCast :
2098 (SrcBits > DstBits ? Instruction::Trunc :
2099 (isSigned ? Instruction::SExt : Instruction::ZExt)));
2100 return Create(opcode, C, Ty, Name, InsertAtEnd);
2103 CastInst *CastInst::CreateFPCast(Value *C, const Type *Ty,
2104 const std::string &Name,
2105 Instruction *InsertBefore) {
2106 assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
2108 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2109 unsigned DstBits = Ty->getScalarSizeInBits();
2110 Instruction::CastOps opcode =
2111 (SrcBits == DstBits ? Instruction::BitCast :
2112 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
2113 return Create(opcode, C, Ty, Name, InsertBefore);
2116 CastInst *CastInst::CreateFPCast(Value *C, const Type *Ty,
2117 const std::string &Name,
2118 BasicBlock *InsertAtEnd) {
2119 assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
2121 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2122 unsigned DstBits = Ty->getScalarSizeInBits();
2123 Instruction::CastOps opcode =
2124 (SrcBits == DstBits ? Instruction::BitCast :
2125 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
2126 return Create(opcode, C, Ty, Name, InsertAtEnd);
2129 // Check whether it is valid to call getCastOpcode for these types.
2130 // This routine must be kept in sync with getCastOpcode.
2131 bool CastInst::isCastable(const Type *SrcTy, const Type *DestTy) {
2132 if (!SrcTy->isFirstClassType() || !DestTy->isFirstClassType())
2135 if (SrcTy == DestTy)
2138 // Get the bit sizes, we'll need these
2139 unsigned SrcBits = SrcTy->getScalarSizeInBits(); // 0 for ptr
2140 unsigned DestBits = DestTy->getScalarSizeInBits(); // 0 for ptr
2142 // Run through the possibilities ...
2143 if (DestTy->isInteger()) { // Casting to integral
2144 if (SrcTy->isInteger()) { // Casting from integral
2146 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt
2148 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
2149 // Casting from vector
2150 return DestBits == PTy->getBitWidth();
2151 } else { // Casting from something else
2152 return isa<PointerType>(SrcTy);
2154 } else if (DestTy->isFloatingPoint()) { // Casting to floating pt
2155 if (SrcTy->isInteger()) { // Casting from integral
2157 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt
2159 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
2160 // Casting from vector
2161 return DestBits == PTy->getBitWidth();
2162 } else { // Casting from something else
2165 } else if (const VectorType *DestPTy = dyn_cast<VectorType>(DestTy)) {
2166 // Casting to vector
2167 if (const VectorType *SrcPTy = dyn_cast<VectorType>(SrcTy)) {
2168 // Casting from vector
2169 return DestPTy->getBitWidth() == SrcPTy->getBitWidth();
2170 } else { // Casting from something else
2171 return DestPTy->getBitWidth() == SrcBits;
2173 } else if (isa<PointerType>(DestTy)) { // Casting to pointer
2174 if (isa<PointerType>(SrcTy)) { // Casting from pointer
2176 } else if (SrcTy->isInteger()) { // Casting from integral
2178 } else { // Casting from something else
2181 } else { // Casting to something else
2186 // Provide a way to get a "cast" where the cast opcode is inferred from the
2187 // types and size of the operand. This, basically, is a parallel of the
2188 // logic in the castIsValid function below. This axiom should hold:
2189 // castIsValid( getCastOpcode(Val, Ty), Val, Ty)
2190 // should not assert in castIsValid. In other words, this produces a "correct"
2191 // casting opcode for the arguments passed to it.
2192 // This routine must be kept in sync with isCastable.
2193 Instruction::CastOps
2194 CastInst::getCastOpcode(
2195 const Value *Src, bool SrcIsSigned, const Type *DestTy, bool DestIsSigned) {
2196 // Get the bit sizes, we'll need these
2197 const Type *SrcTy = Src->getType();
2198 unsigned SrcBits = SrcTy->getScalarSizeInBits(); // 0 for ptr
2199 unsigned DestBits = DestTy->getScalarSizeInBits(); // 0 for ptr
2201 assert(SrcTy->isFirstClassType() && DestTy->isFirstClassType() &&
2202 "Only first class types are castable!");
2204 // Run through the possibilities ...
2205 if (DestTy->isInteger()) { // Casting to integral
2206 if (SrcTy->isInteger()) { // Casting from integral
2207 if (DestBits < SrcBits)
2208 return Trunc; // int -> smaller int
2209 else if (DestBits > SrcBits) { // its an extension
2211 return SExt; // signed -> SEXT
2213 return ZExt; // unsigned -> ZEXT
2215 return BitCast; // Same size, No-op cast
2217 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt
2219 return FPToSI; // FP -> sint
2221 return FPToUI; // FP -> uint
2222 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
2223 assert(DestBits == PTy->getBitWidth() &&
2224 "Casting vector to integer of different width");
2226 return BitCast; // Same size, no-op cast
2228 assert(isa<PointerType>(SrcTy) &&
2229 "Casting from a value that is not first-class type");
2230 return PtrToInt; // ptr -> int
2232 } else if (DestTy->isFloatingPoint()) { // Casting to floating pt
2233 if (SrcTy->isInteger()) { // Casting from integral
2235 return SIToFP; // sint -> FP
2237 return UIToFP; // uint -> FP
2238 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt
2239 if (DestBits < SrcBits) {
2240 return FPTrunc; // FP -> smaller FP
2241 } else if (DestBits > SrcBits) {
2242 return FPExt; // FP -> larger FP
2244 return BitCast; // same size, no-op cast
2246 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
2247 assert(DestBits == PTy->getBitWidth() &&
2248 "Casting vector to floating point of different width");
2250 return BitCast; // same size, no-op cast
2252 llvm_unreachable("Casting pointer or non-first class to float");
2254 } else if (const VectorType *DestPTy = dyn_cast<VectorType>(DestTy)) {
2255 if (const VectorType *SrcPTy = dyn_cast<VectorType>(SrcTy)) {
2256 assert(DestPTy->getBitWidth() == SrcPTy->getBitWidth() &&
2257 "Casting vector to vector of different widths");
2259 return BitCast; // vector -> vector
2260 } else if (DestPTy->getBitWidth() == SrcBits) {
2261 return BitCast; // float/int -> vector
2263 assert(!"Illegal cast to vector (wrong type or size)");
2265 } else if (isa<PointerType>(DestTy)) {
2266 if (isa<PointerType>(SrcTy)) {
2267 return BitCast; // ptr -> ptr
2268 } else if (SrcTy->isInteger()) {
2269 return IntToPtr; // int -> ptr
2271 assert(!"Casting pointer to other than pointer or int");
2274 assert(!"Casting to type that is not first-class");
2277 // If we fall through to here we probably hit an assertion cast above
2278 // and assertions are not turned on. Anything we return is an error, so
2279 // BitCast is as good a choice as any.
2283 //===----------------------------------------------------------------------===//
2284 // CastInst SubClass Constructors
2285 //===----------------------------------------------------------------------===//
2287 /// Check that the construction parameters for a CastInst are correct. This
2288 /// could be broken out into the separate constructors but it is useful to have
2289 /// it in one place and to eliminate the redundant code for getting the sizes
2290 /// of the types involved.
2292 CastInst::castIsValid(Instruction::CastOps op, Value *S, const Type *DstTy) {
2294 // Check for type sanity on the arguments
2295 const Type *SrcTy = S->getType();
2296 if (!SrcTy->isFirstClassType() || !DstTy->isFirstClassType())
2299 // Get the size of the types in bits, we'll need this later
2300 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
2301 unsigned DstBitSize = DstTy->getScalarSizeInBits();
2303 // Switch on the opcode provided
2305 default: return false; // This is an input error
2306 case Instruction::Trunc:
2307 return SrcTy->isIntOrIntVector() &&
2308 DstTy->isIntOrIntVector()&& SrcBitSize > DstBitSize;
2309 case Instruction::ZExt:
2310 return SrcTy->isIntOrIntVector() &&
2311 DstTy->isIntOrIntVector()&& SrcBitSize < DstBitSize;
2312 case Instruction::SExt:
2313 return SrcTy->isIntOrIntVector() &&
2314 DstTy->isIntOrIntVector()&& SrcBitSize < DstBitSize;
2315 case Instruction::FPTrunc:
2316 return SrcTy->isFPOrFPVector() &&
2317 DstTy->isFPOrFPVector() &&
2318 SrcBitSize > DstBitSize;
2319 case Instruction::FPExt:
2320 return SrcTy->isFPOrFPVector() &&
2321 DstTy->isFPOrFPVector() &&
2322 SrcBitSize < DstBitSize;
2323 case Instruction::UIToFP:
2324 case Instruction::SIToFP:
2325 if (const VectorType *SVTy = dyn_cast<VectorType>(SrcTy)) {
2326 if (const VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
2327 return SVTy->getElementType()->isIntOrIntVector() &&
2328 DVTy->getElementType()->isFPOrFPVector() &&
2329 SVTy->getNumElements() == DVTy->getNumElements();
2332 return SrcTy->isIntOrIntVector() && DstTy->isFPOrFPVector();
2333 case Instruction::FPToUI:
2334 case Instruction::FPToSI:
2335 if (const VectorType *SVTy = dyn_cast<VectorType>(SrcTy)) {
2336 if (const VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
2337 return SVTy->getElementType()->isFPOrFPVector() &&
2338 DVTy->getElementType()->isIntOrIntVector() &&
2339 SVTy->getNumElements() == DVTy->getNumElements();
2342 return SrcTy->isFPOrFPVector() && DstTy->isIntOrIntVector();
2343 case Instruction::PtrToInt:
2344 return isa<PointerType>(SrcTy) && DstTy->isInteger();
2345 case Instruction::IntToPtr:
2346 return SrcTy->isInteger() && isa<PointerType>(DstTy);
2347 case Instruction::BitCast:
2348 // BitCast implies a no-op cast of type only. No bits change.
2349 // However, you can't cast pointers to anything but pointers.
2350 if (isa<PointerType>(SrcTy) != isa<PointerType>(DstTy))
2353 // Now we know we're not dealing with a pointer/non-pointer mismatch. In all
2354 // these cases, the cast is okay if the source and destination bit widths
2356 return SrcTy->getPrimitiveSizeInBits() == DstTy->getPrimitiveSizeInBits();
2360 TruncInst::TruncInst(
2361 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2362 ) : CastInst(Ty, Trunc, S, Name, InsertBefore) {
2363 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
2366 TruncInst::TruncInst(
2367 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2368 ) : CastInst(Ty, Trunc, S, Name, InsertAtEnd) {
2369 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
2373 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2374 ) : CastInst(Ty, ZExt, S, Name, InsertBefore) {
2375 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
2379 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2380 ) : CastInst(Ty, ZExt, S, Name, InsertAtEnd) {
2381 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
2384 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2385 ) : CastInst(Ty, SExt, S, Name, InsertBefore) {
2386 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
2390 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2391 ) : CastInst(Ty, SExt, S, Name, InsertAtEnd) {
2392 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
2395 FPTruncInst::FPTruncInst(
2396 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2397 ) : CastInst(Ty, FPTrunc, S, Name, InsertBefore) {
2398 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
2401 FPTruncInst::FPTruncInst(
2402 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2403 ) : CastInst(Ty, FPTrunc, S, Name, InsertAtEnd) {
2404 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
2407 FPExtInst::FPExtInst(
2408 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2409 ) : CastInst(Ty, FPExt, S, Name, InsertBefore) {
2410 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
2413 FPExtInst::FPExtInst(
2414 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2415 ) : CastInst(Ty, FPExt, S, Name, InsertAtEnd) {
2416 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
2419 UIToFPInst::UIToFPInst(
2420 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2421 ) : CastInst(Ty, UIToFP, S, Name, InsertBefore) {
2422 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
2425 UIToFPInst::UIToFPInst(
2426 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2427 ) : CastInst(Ty, UIToFP, S, Name, InsertAtEnd) {
2428 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
2431 SIToFPInst::SIToFPInst(
2432 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2433 ) : CastInst(Ty, SIToFP, S, Name, InsertBefore) {
2434 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
2437 SIToFPInst::SIToFPInst(
2438 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2439 ) : CastInst(Ty, SIToFP, S, Name, InsertAtEnd) {
2440 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
2443 FPToUIInst::FPToUIInst(
2444 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2445 ) : CastInst(Ty, FPToUI, S, Name, InsertBefore) {
2446 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
2449 FPToUIInst::FPToUIInst(
2450 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2451 ) : CastInst(Ty, FPToUI, S, Name, InsertAtEnd) {
2452 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
2455 FPToSIInst::FPToSIInst(
2456 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2457 ) : CastInst(Ty, FPToSI, S, Name, InsertBefore) {
2458 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
2461 FPToSIInst::FPToSIInst(
2462 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2463 ) : CastInst(Ty, FPToSI, S, Name, InsertAtEnd) {
2464 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
2467 PtrToIntInst::PtrToIntInst(
2468 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2469 ) : CastInst(Ty, PtrToInt, S, Name, InsertBefore) {
2470 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
2473 PtrToIntInst::PtrToIntInst(
2474 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2475 ) : CastInst(Ty, PtrToInt, S, Name, InsertAtEnd) {
2476 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
2479 IntToPtrInst::IntToPtrInst(
2480 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2481 ) : CastInst(Ty, IntToPtr, S, Name, InsertBefore) {
2482 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
2485 IntToPtrInst::IntToPtrInst(
2486 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2487 ) : CastInst(Ty, IntToPtr, S, Name, InsertAtEnd) {
2488 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
2491 BitCastInst::BitCastInst(
2492 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2493 ) : CastInst(Ty, BitCast, S, Name, InsertBefore) {
2494 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
2497 BitCastInst::BitCastInst(
2498 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2499 ) : CastInst(Ty, BitCast, S, Name, InsertAtEnd) {
2500 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
2503 //===----------------------------------------------------------------------===//
2505 //===----------------------------------------------------------------------===//
2507 CmpInst::CmpInst(const Type *ty, OtherOps op, unsigned short predicate,
2508 Value *LHS, Value *RHS, const std::string &Name,
2509 Instruction *InsertBefore)
2510 : Instruction(ty, op,
2511 OperandTraits<CmpInst>::op_begin(this),
2512 OperandTraits<CmpInst>::operands(this),
2516 SubclassData = predicate;
2520 CmpInst::CmpInst(const Type *ty, OtherOps op, unsigned short predicate,
2521 Value *LHS, Value *RHS, const std::string &Name,
2522 BasicBlock *InsertAtEnd)
2523 : Instruction(ty, op,
2524 OperandTraits<CmpInst>::op_begin(this),
2525 OperandTraits<CmpInst>::operands(this),
2529 SubclassData = predicate;
2534 CmpInst::Create(LLVMContext &Context, OtherOps Op, unsigned short predicate,
2535 Value *S1, Value *S2,
2536 const std::string &Name, Instruction *InsertBefore) {
2537 if (Op == Instruction::ICmp) {
2539 return new ICmpInst(InsertBefore, CmpInst::Predicate(predicate),
2542 return new ICmpInst(Context, CmpInst::Predicate(predicate),
2547 return new FCmpInst(InsertBefore, CmpInst::Predicate(predicate),
2550 return new FCmpInst(Context, CmpInst::Predicate(predicate),
2555 CmpInst::Create(OtherOps Op, unsigned short predicate, Value *S1, Value *S2,
2556 const std::string &Name, BasicBlock *InsertAtEnd) {
2557 if (Op == Instruction::ICmp) {
2558 return new ICmpInst(*InsertAtEnd, CmpInst::Predicate(predicate),
2561 return new FCmpInst(*InsertAtEnd, CmpInst::Predicate(predicate),
2565 void CmpInst::swapOperands() {
2566 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2569 cast<FCmpInst>(this)->swapOperands();
2572 bool CmpInst::isCommutative() {
2573 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2574 return IC->isCommutative();
2575 return cast<FCmpInst>(this)->isCommutative();
2578 bool CmpInst::isEquality() {
2579 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2580 return IC->isEquality();
2581 return cast<FCmpInst>(this)->isEquality();
2585 CmpInst::Predicate CmpInst::getInversePredicate(Predicate pred) {
2587 default: assert(!"Unknown cmp predicate!");
2588 case ICMP_EQ: return ICMP_NE;
2589 case ICMP_NE: return ICMP_EQ;
2590 case ICMP_UGT: return ICMP_ULE;
2591 case ICMP_ULT: return ICMP_UGE;
2592 case ICMP_UGE: return ICMP_ULT;
2593 case ICMP_ULE: return ICMP_UGT;
2594 case ICMP_SGT: return ICMP_SLE;
2595 case ICMP_SLT: return ICMP_SGE;
2596 case ICMP_SGE: return ICMP_SLT;
2597 case ICMP_SLE: return ICMP_SGT;
2599 case FCMP_OEQ: return FCMP_UNE;
2600 case FCMP_ONE: return FCMP_UEQ;
2601 case FCMP_OGT: return FCMP_ULE;
2602 case FCMP_OLT: return FCMP_UGE;
2603 case FCMP_OGE: return FCMP_ULT;
2604 case FCMP_OLE: return FCMP_UGT;
2605 case FCMP_UEQ: return FCMP_ONE;
2606 case FCMP_UNE: return FCMP_OEQ;
2607 case FCMP_UGT: return FCMP_OLE;
2608 case FCMP_ULT: return FCMP_OGE;
2609 case FCMP_UGE: return FCMP_OLT;
2610 case FCMP_ULE: return FCMP_OGT;
2611 case FCMP_ORD: return FCMP_UNO;
2612 case FCMP_UNO: return FCMP_ORD;
2613 case FCMP_TRUE: return FCMP_FALSE;
2614 case FCMP_FALSE: return FCMP_TRUE;
2618 ICmpInst::Predicate ICmpInst::getSignedPredicate(Predicate pred) {
2620 default: assert(! "Unknown icmp predicate!");
2621 case ICMP_EQ: case ICMP_NE:
2622 case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE:
2624 case ICMP_UGT: return ICMP_SGT;
2625 case ICMP_ULT: return ICMP_SLT;
2626 case ICMP_UGE: return ICMP_SGE;
2627 case ICMP_ULE: return ICMP_SLE;
2631 ICmpInst::Predicate ICmpInst::getUnsignedPredicate(Predicate pred) {
2633 default: assert(! "Unknown icmp predicate!");
2634 case ICMP_EQ: case ICMP_NE:
2635 case ICMP_UGT: case ICMP_ULT: case ICMP_UGE: case ICMP_ULE:
2637 case ICMP_SGT: return ICMP_UGT;
2638 case ICMP_SLT: return ICMP_ULT;
2639 case ICMP_SGE: return ICMP_UGE;
2640 case ICMP_SLE: return ICMP_ULE;
2644 bool ICmpInst::isSignedPredicate(Predicate pred) {
2646 default: assert(! "Unknown icmp predicate!");
2647 case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE:
2649 case ICMP_EQ: case ICMP_NE: case ICMP_UGT: case ICMP_ULT:
2650 case ICMP_UGE: case ICMP_ULE:
2655 /// Initialize a set of values that all satisfy the condition with C.
2658 ICmpInst::makeConstantRange(Predicate pred, const APInt &C) {
2661 uint32_t BitWidth = C.getBitWidth();
2663 default: llvm_unreachable("Invalid ICmp opcode to ConstantRange ctor!");
2664 case ICmpInst::ICMP_EQ: Upper++; break;
2665 case ICmpInst::ICMP_NE: Lower++; break;
2666 case ICmpInst::ICMP_ULT: Lower = APInt::getMinValue(BitWidth); break;
2667 case ICmpInst::ICMP_SLT: Lower = APInt::getSignedMinValue(BitWidth); break;
2668 case ICmpInst::ICMP_UGT:
2669 Lower++; Upper = APInt::getMinValue(BitWidth); // Min = Next(Max)
2671 case ICmpInst::ICMP_SGT:
2672 Lower++; Upper = APInt::getSignedMinValue(BitWidth); // Min = Next(Max)
2674 case ICmpInst::ICMP_ULE:
2675 Lower = APInt::getMinValue(BitWidth); Upper++;
2677 case ICmpInst::ICMP_SLE:
2678 Lower = APInt::getSignedMinValue(BitWidth); Upper++;
2680 case ICmpInst::ICMP_UGE:
2681 Upper = APInt::getMinValue(BitWidth); // Min = Next(Max)
2683 case ICmpInst::ICMP_SGE:
2684 Upper = APInt::getSignedMinValue(BitWidth); // Min = Next(Max)
2687 return ConstantRange(Lower, Upper);
2690 CmpInst::Predicate CmpInst::getSwappedPredicate(Predicate pred) {
2692 default: assert(!"Unknown cmp predicate!");
2693 case ICMP_EQ: case ICMP_NE:
2695 case ICMP_SGT: return ICMP_SLT;
2696 case ICMP_SLT: return ICMP_SGT;
2697 case ICMP_SGE: return ICMP_SLE;
2698 case ICMP_SLE: return ICMP_SGE;
2699 case ICMP_UGT: return ICMP_ULT;
2700 case ICMP_ULT: return ICMP_UGT;
2701 case ICMP_UGE: return ICMP_ULE;
2702 case ICMP_ULE: return ICMP_UGE;
2704 case FCMP_FALSE: case FCMP_TRUE:
2705 case FCMP_OEQ: case FCMP_ONE:
2706 case FCMP_UEQ: case FCMP_UNE:
2707 case FCMP_ORD: case FCMP_UNO:
2709 case FCMP_OGT: return FCMP_OLT;
2710 case FCMP_OLT: return FCMP_OGT;
2711 case FCMP_OGE: return FCMP_OLE;
2712 case FCMP_OLE: return FCMP_OGE;
2713 case FCMP_UGT: return FCMP_ULT;
2714 case FCMP_ULT: return FCMP_UGT;
2715 case FCMP_UGE: return FCMP_ULE;
2716 case FCMP_ULE: return FCMP_UGE;
2720 bool CmpInst::isUnsigned(unsigned short predicate) {
2721 switch (predicate) {
2722 default: return false;
2723 case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_ULE: case ICmpInst::ICMP_UGT:
2724 case ICmpInst::ICMP_UGE: return true;
2728 bool CmpInst::isSigned(unsigned short predicate){
2729 switch (predicate) {
2730 default: return false;
2731 case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_SLE: case ICmpInst::ICMP_SGT:
2732 case ICmpInst::ICMP_SGE: return true;
2736 bool CmpInst::isOrdered(unsigned short predicate) {
2737 switch (predicate) {
2738 default: return false;
2739 case FCmpInst::FCMP_OEQ: case FCmpInst::FCMP_ONE: case FCmpInst::FCMP_OGT:
2740 case FCmpInst::FCMP_OLT: case FCmpInst::FCMP_OGE: case FCmpInst::FCMP_OLE:
2741 case FCmpInst::FCMP_ORD: return true;
2745 bool CmpInst::isUnordered(unsigned short predicate) {
2746 switch (predicate) {
2747 default: return false;
2748 case FCmpInst::FCMP_UEQ: case FCmpInst::FCMP_UNE: case FCmpInst::FCMP_UGT:
2749 case FCmpInst::FCMP_ULT: case FCmpInst::FCMP_UGE: case FCmpInst::FCMP_ULE:
2750 case FCmpInst::FCMP_UNO: return true;
2754 //===----------------------------------------------------------------------===//
2755 // SwitchInst Implementation
2756 //===----------------------------------------------------------------------===//
2758 void SwitchInst::init(Value *Value, BasicBlock *Default, unsigned NumCases) {
2759 assert(Value && Default);
2760 ReservedSpace = 2+NumCases*2;
2762 OperandList = allocHungoffUses(ReservedSpace);
2764 OperandList[0] = Value;
2765 OperandList[1] = Default;
2768 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
2769 /// switch on and a default destination. The number of additional cases can
2770 /// be specified here to make memory allocation more efficient. This
2771 /// constructor can also autoinsert before another instruction.
2772 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
2773 Instruction *InsertBefore)
2774 : TerminatorInst(Type::VoidTy, Instruction::Switch, 0, 0, InsertBefore) {
2775 init(Value, Default, NumCases);
2778 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
2779 /// switch on and a default destination. The number of additional cases can
2780 /// be specified here to make memory allocation more efficient. This
2781 /// constructor also autoinserts at the end of the specified BasicBlock.
2782 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
2783 BasicBlock *InsertAtEnd)
2784 : TerminatorInst(Type::VoidTy, Instruction::Switch, 0, 0, InsertAtEnd) {
2785 init(Value, Default, NumCases);
2788 SwitchInst::SwitchInst(const SwitchInst &SI)
2789 : TerminatorInst(Type::VoidTy, Instruction::Switch,
2790 allocHungoffUses(SI.getNumOperands()), SI.getNumOperands()) {
2791 Use *OL = OperandList, *InOL = SI.OperandList;
2792 for (unsigned i = 0, E = SI.getNumOperands(); i != E; i+=2) {
2794 OL[i+1] = InOL[i+1];
2798 SwitchInst::~SwitchInst() {
2799 dropHungoffUses(OperandList);
2803 /// addCase - Add an entry to the switch instruction...
2805 void SwitchInst::addCase(ConstantInt *OnVal, BasicBlock *Dest) {
2806 unsigned OpNo = NumOperands;
2807 if (OpNo+2 > ReservedSpace)
2808 resizeOperands(0); // Get more space!
2809 // Initialize some new operands.
2810 assert(OpNo+1 < ReservedSpace && "Growing didn't work!");
2811 NumOperands = OpNo+2;
2812 OperandList[OpNo] = OnVal;
2813 OperandList[OpNo+1] = Dest;
2816 /// removeCase - This method removes the specified successor from the switch
2817 /// instruction. Note that this cannot be used to remove the default
2818 /// destination (successor #0).
2820 void SwitchInst::removeCase(unsigned idx) {
2821 assert(idx != 0 && "Cannot remove the default case!");
2822 assert(idx*2 < getNumOperands() && "Successor index out of range!!!");
2824 unsigned NumOps = getNumOperands();
2825 Use *OL = OperandList;
2827 // Move everything after this operand down.
2829 // FIXME: we could just swap with the end of the list, then erase. However,
2830 // client might not expect this to happen. The code as it is thrashes the
2831 // use/def lists, which is kinda lame.
2832 for (unsigned i = (idx+1)*2; i != NumOps; i += 2) {
2834 OL[i-2+1] = OL[i+1];
2837 // Nuke the last value.
2838 OL[NumOps-2].set(0);
2839 OL[NumOps-2+1].set(0);
2840 NumOperands = NumOps-2;
2843 /// resizeOperands - resize operands - This adjusts the length of the operands
2844 /// list according to the following behavior:
2845 /// 1. If NumOps == 0, grow the operand list in response to a push_back style
2846 /// of operation. This grows the number of ops by 3 times.
2847 /// 2. If NumOps > NumOperands, reserve space for NumOps operands.
2848 /// 3. If NumOps == NumOperands, trim the reserved space.
2850 void SwitchInst::resizeOperands(unsigned NumOps) {
2851 unsigned e = getNumOperands();
2854 } else if (NumOps*2 > NumOperands) {
2855 // No resize needed.
2856 if (ReservedSpace >= NumOps) return;
2857 } else if (NumOps == NumOperands) {
2858 if (ReservedSpace == NumOps) return;
2863 ReservedSpace = NumOps;
2864 Use *NewOps = allocHungoffUses(NumOps);
2865 Use *OldOps = OperandList;
2866 for (unsigned i = 0; i != e; ++i) {
2867 NewOps[i] = OldOps[i];
2869 OperandList = NewOps;
2870 if (OldOps) Use::zap(OldOps, OldOps + e, true);
2874 BasicBlock *SwitchInst::getSuccessorV(unsigned idx) const {
2875 return getSuccessor(idx);
2877 unsigned SwitchInst::getNumSuccessorsV() const {
2878 return getNumSuccessors();
2880 void SwitchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
2881 setSuccessor(idx, B);
2884 // Define these methods here so vtables don't get emitted into every translation
2885 // unit that uses these classes.
2887 GetElementPtrInst *GetElementPtrInst::clone(LLVMContext&) const {
2888 return new(getNumOperands()) GetElementPtrInst(*this);
2891 BinaryOperator *BinaryOperator::clone(LLVMContext&) const {
2892 return Create(getOpcode(), Op<0>(), Op<1>());
2895 FCmpInst* FCmpInst::clone(LLVMContext &Context) const {
2896 return new FCmpInst(Context, getPredicate(), Op<0>(), Op<1>());
2898 ICmpInst* ICmpInst::clone(LLVMContext &Context) const {
2899 return new ICmpInst(Context, getPredicate(), Op<0>(), Op<1>());
2902 ExtractValueInst *ExtractValueInst::clone(LLVMContext&) const {
2903 return new ExtractValueInst(*this);
2905 InsertValueInst *InsertValueInst::clone(LLVMContext&) const {
2906 return new InsertValueInst(*this);
2909 MallocInst *MallocInst::clone(LLVMContext&) const {
2910 return new MallocInst(*this);
2913 AllocaInst *AllocaInst::clone(LLVMContext&) const {
2914 return new AllocaInst(*this);
2917 FreeInst *FreeInst::clone(LLVMContext&) const {
2918 return new FreeInst(getOperand(0));
2921 LoadInst *LoadInst::clone(LLVMContext&) const {
2922 return new LoadInst(*this);
2925 StoreInst *StoreInst::clone(LLVMContext&) const {
2926 return new StoreInst(*this);
2929 CastInst *TruncInst::clone(LLVMContext&) const {
2930 return new TruncInst(*this);
2933 CastInst *ZExtInst::clone(LLVMContext&) const {
2934 return new ZExtInst(*this);
2937 CastInst *SExtInst::clone(LLVMContext&) const {
2938 return new SExtInst(*this);
2941 CastInst *FPTruncInst::clone(LLVMContext&) const {
2942 return new FPTruncInst(*this);
2945 CastInst *FPExtInst::clone(LLVMContext&) const {
2946 return new FPExtInst(*this);
2949 CastInst *UIToFPInst::clone(LLVMContext&) const {
2950 return new UIToFPInst(*this);
2953 CastInst *SIToFPInst::clone(LLVMContext&) const {
2954 return new SIToFPInst(*this);
2957 CastInst *FPToUIInst::clone(LLVMContext&) const {
2958 return new FPToUIInst(*this);
2961 CastInst *FPToSIInst::clone(LLVMContext&) const {
2962 return new FPToSIInst(*this);
2965 CastInst *PtrToIntInst::clone(LLVMContext&) const {
2966 return new PtrToIntInst(*this);
2969 CastInst *IntToPtrInst::clone(LLVMContext&) const {
2970 return new IntToPtrInst(*this);
2973 CastInst *BitCastInst::clone(LLVMContext&) const {
2974 return new BitCastInst(*this);
2977 CallInst *CallInst::clone(LLVMContext&) const {
2978 return new(getNumOperands()) CallInst(*this);
2981 SelectInst *SelectInst::clone(LLVMContext&) const {
2982 return new(getNumOperands()) SelectInst(*this);
2985 VAArgInst *VAArgInst::clone(LLVMContext&) const {
2986 return new VAArgInst(*this);
2989 ExtractElementInst *ExtractElementInst::clone(LLVMContext&) const {
2990 return new ExtractElementInst(*this);
2993 InsertElementInst *InsertElementInst::clone(LLVMContext&) const {
2994 return InsertElementInst::Create(*this);
2997 ShuffleVectorInst *ShuffleVectorInst::clone(LLVMContext&) const {
2998 return new ShuffleVectorInst(*this);
3001 PHINode *PHINode::clone(LLVMContext&) const {
3002 return new PHINode(*this);
3005 ReturnInst *ReturnInst::clone(LLVMContext&) const {
3006 return new(getNumOperands()) ReturnInst(*this);
3009 BranchInst *BranchInst::clone(LLVMContext&) const {
3010 unsigned Ops(getNumOperands());
3011 return new(Ops, Ops == 1) BranchInst(*this);
3014 SwitchInst *SwitchInst::clone(LLVMContext&) const {
3015 return new SwitchInst(*this);
3018 InvokeInst *InvokeInst::clone(LLVMContext&) const {
3019 return new(getNumOperands()) InvokeInst(*this);
3022 UnwindInst *UnwindInst::clone(LLVMContext&) const {
3023 return new UnwindInst();
3026 UnreachableInst *UnreachableInst::clone(LLVMContext&) const {
3027 return new UnreachableInst();