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(UndefValue::get(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);
234 return UndefValue::get(getType()); // Self cycle is dead.
237 // Otherwise if all of the incoming values are the same for the PHI, replace
238 // the PHI node with the incoming value.
241 bool HasUndefInput = false;
242 for (unsigned i = 0, e = getNumIncomingValues(); i != e; ++i)
243 if (isa<UndefValue>(getIncomingValue(i))) {
244 HasUndefInput = true;
245 } else if (getIncomingValue(i) != this) { // Not the PHI node itself...
246 if (InVal && getIncomingValue(i) != InVal)
247 return 0; // Not the same, bail out.
249 InVal = getIncomingValue(i);
252 // The only case that could cause InVal to be null is if we have a PHI node
253 // that only has entries for itself. In this case, there is no entry into the
254 // loop, so kill the PHI.
256 if (InVal == 0) InVal = UndefValue::get(getType());
258 // If we have a PHI node like phi(X, undef, X), where X is defined by some
259 // instruction, we cannot always return X as the result of the PHI node. Only
260 // do this if X is not an instruction (thus it must dominate the PHI block),
261 // or if the client is prepared to deal with this possibility.
262 if (HasUndefInput && !AllowNonDominatingInstruction)
263 if (Instruction *IV = dyn_cast<Instruction>(InVal))
264 // If it's in the entry block, it dominates everything.
265 if (IV->getParent() != &IV->getParent()->getParent()->getEntryBlock() ||
267 return 0; // Cannot guarantee that InVal dominates this PHINode.
269 // All of the incoming values are the same, return the value now.
274 //===----------------------------------------------------------------------===//
275 // CallInst Implementation
276 //===----------------------------------------------------------------------===//
278 CallInst::~CallInst() {
281 void CallInst::init(Value *Func, Value* const *Params, unsigned NumParams) {
282 assert(NumOperands == NumParams+1 && "NumOperands not set up?");
283 Use *OL = OperandList;
286 const FunctionType *FTy =
287 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
288 FTy = FTy; // silence warning.
290 assert((NumParams == FTy->getNumParams() ||
291 (FTy->isVarArg() && NumParams > FTy->getNumParams())) &&
292 "Calling a function with bad signature!");
293 for (unsigned i = 0; i != NumParams; ++i) {
294 assert((i >= FTy->getNumParams() ||
295 FTy->getParamType(i) == Params[i]->getType()) &&
296 "Calling a function with a bad signature!");
301 void CallInst::init(Value *Func, Value *Actual1, Value *Actual2) {
302 assert(NumOperands == 3 && "NumOperands not set up?");
303 Use *OL = OperandList;
308 const FunctionType *FTy =
309 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
310 FTy = FTy; // silence warning.
312 assert((FTy->getNumParams() == 2 ||
313 (FTy->isVarArg() && FTy->getNumParams() < 2)) &&
314 "Calling a function with bad signature");
315 assert((0 >= FTy->getNumParams() ||
316 FTy->getParamType(0) == Actual1->getType()) &&
317 "Calling a function with a bad signature!");
318 assert((1 >= FTy->getNumParams() ||
319 FTy->getParamType(1) == Actual2->getType()) &&
320 "Calling a function with a bad signature!");
323 void CallInst::init(Value *Func, Value *Actual) {
324 assert(NumOperands == 2 && "NumOperands not set up?");
325 Use *OL = OperandList;
329 const FunctionType *FTy =
330 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
331 FTy = FTy; // silence warning.
333 assert((FTy->getNumParams() == 1 ||
334 (FTy->isVarArg() && FTy->getNumParams() == 0)) &&
335 "Calling a function with bad signature");
336 assert((0 == FTy->getNumParams() ||
337 FTy->getParamType(0) == Actual->getType()) &&
338 "Calling a function with a bad signature!");
341 void CallInst::init(Value *Func) {
342 assert(NumOperands == 1 && "NumOperands not set up?");
343 Use *OL = OperandList;
346 const FunctionType *FTy =
347 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
348 FTy = FTy; // silence warning.
350 assert(FTy->getNumParams() == 0 && "Calling a function with bad signature");
353 CallInst::CallInst(Value *Func, Value* Actual, const std::string &Name,
354 Instruction *InsertBefore)
355 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
356 ->getElementType())->getReturnType(),
358 OperandTraits<CallInst>::op_end(this) - 2,
364 CallInst::CallInst(Value *Func, Value* Actual, const std::string &Name,
365 BasicBlock *InsertAtEnd)
366 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
367 ->getElementType())->getReturnType(),
369 OperandTraits<CallInst>::op_end(this) - 2,
374 CallInst::CallInst(Value *Func, const std::string &Name,
375 Instruction *InsertBefore)
376 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
377 ->getElementType())->getReturnType(),
379 OperandTraits<CallInst>::op_end(this) - 1,
385 CallInst::CallInst(Value *Func, const std::string &Name,
386 BasicBlock *InsertAtEnd)
387 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
388 ->getElementType())->getReturnType(),
390 OperandTraits<CallInst>::op_end(this) - 1,
396 CallInst::CallInst(const CallInst &CI)
397 : Instruction(CI.getType(), Instruction::Call,
398 OperandTraits<CallInst>::op_end(this) - CI.getNumOperands(),
399 CI.getNumOperands()) {
400 setAttributes(CI.getAttributes());
401 SubclassData = CI.SubclassData;
402 Use *OL = OperandList;
403 Use *InOL = CI.OperandList;
404 for (unsigned i = 0, e = CI.getNumOperands(); i != e; ++i)
408 void CallInst::addAttribute(unsigned i, Attributes attr) {
409 AttrListPtr PAL = getAttributes();
410 PAL = PAL.addAttr(i, attr);
414 void CallInst::removeAttribute(unsigned i, Attributes attr) {
415 AttrListPtr PAL = getAttributes();
416 PAL = PAL.removeAttr(i, attr);
420 bool CallInst::paramHasAttr(unsigned i, Attributes attr) const {
421 if (AttributeList.paramHasAttr(i, attr))
423 if (const Function *F = getCalledFunction())
424 return F->paramHasAttr(i, attr);
429 //===----------------------------------------------------------------------===//
430 // InvokeInst Implementation
431 //===----------------------------------------------------------------------===//
433 void InvokeInst::init(Value *Fn, BasicBlock *IfNormal, BasicBlock *IfException,
434 Value* const *Args, unsigned NumArgs) {
435 assert(NumOperands == 3+NumArgs && "NumOperands not set up?");
436 Use *OL = OperandList;
440 const FunctionType *FTy =
441 cast<FunctionType>(cast<PointerType>(Fn->getType())->getElementType());
442 FTy = FTy; // silence warning.
444 assert(((NumArgs == FTy->getNumParams()) ||
445 (FTy->isVarArg() && NumArgs > FTy->getNumParams())) &&
446 "Calling a function with bad signature");
448 for (unsigned i = 0, e = NumArgs; i != e; i++) {
449 assert((i >= FTy->getNumParams() ||
450 FTy->getParamType(i) == Args[i]->getType()) &&
451 "Invoking a function with a bad signature!");
457 InvokeInst::InvokeInst(const InvokeInst &II)
458 : TerminatorInst(II.getType(), Instruction::Invoke,
459 OperandTraits<InvokeInst>::op_end(this)
460 - II.getNumOperands(),
461 II.getNumOperands()) {
462 setAttributes(II.getAttributes());
463 SubclassData = II.SubclassData;
464 Use *OL = OperandList, *InOL = II.OperandList;
465 for (unsigned i = 0, e = II.getNumOperands(); i != e; ++i)
469 BasicBlock *InvokeInst::getSuccessorV(unsigned idx) const {
470 return getSuccessor(idx);
472 unsigned InvokeInst::getNumSuccessorsV() const {
473 return getNumSuccessors();
475 void InvokeInst::setSuccessorV(unsigned idx, BasicBlock *B) {
476 return setSuccessor(idx, B);
479 bool InvokeInst::paramHasAttr(unsigned i, Attributes attr) const {
480 if (AttributeList.paramHasAttr(i, attr))
482 if (const Function *F = getCalledFunction())
483 return F->paramHasAttr(i, attr);
487 void InvokeInst::addAttribute(unsigned i, Attributes attr) {
488 AttrListPtr PAL = getAttributes();
489 PAL = PAL.addAttr(i, attr);
493 void InvokeInst::removeAttribute(unsigned i, Attributes attr) {
494 AttrListPtr PAL = getAttributes();
495 PAL = PAL.removeAttr(i, attr);
500 //===----------------------------------------------------------------------===//
501 // ReturnInst Implementation
502 //===----------------------------------------------------------------------===//
504 ReturnInst::ReturnInst(const ReturnInst &RI)
505 : TerminatorInst(Type::VoidTy, Instruction::Ret,
506 OperandTraits<ReturnInst>::op_end(this) -
508 RI.getNumOperands()) {
509 if (RI.getNumOperands())
510 Op<0>() = RI.Op<0>();
513 ReturnInst::ReturnInst(Value *retVal, Instruction *InsertBefore)
514 : TerminatorInst(Type::VoidTy, Instruction::Ret,
515 OperandTraits<ReturnInst>::op_end(this) - !!retVal, !!retVal,
520 ReturnInst::ReturnInst(Value *retVal, BasicBlock *InsertAtEnd)
521 : TerminatorInst(Type::VoidTy, Instruction::Ret,
522 OperandTraits<ReturnInst>::op_end(this) - !!retVal, !!retVal,
527 ReturnInst::ReturnInst(BasicBlock *InsertAtEnd)
528 : TerminatorInst(Type::VoidTy, Instruction::Ret,
529 OperandTraits<ReturnInst>::op_end(this), 0, InsertAtEnd) {
532 unsigned ReturnInst::getNumSuccessorsV() const {
533 return getNumSuccessors();
536 /// Out-of-line ReturnInst method, put here so the C++ compiler can choose to
537 /// emit the vtable for the class in this translation unit.
538 void ReturnInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
539 LLVM_UNREACHABLE("ReturnInst has no successors!");
542 BasicBlock *ReturnInst::getSuccessorV(unsigned idx) const {
543 LLVM_UNREACHABLE("ReturnInst has no successors!");
547 ReturnInst::~ReturnInst() {
550 //===----------------------------------------------------------------------===//
551 // UnwindInst Implementation
552 //===----------------------------------------------------------------------===//
554 UnwindInst::UnwindInst(Instruction *InsertBefore)
555 : TerminatorInst(Type::VoidTy, Instruction::Unwind, 0, 0, InsertBefore) {
557 UnwindInst::UnwindInst(BasicBlock *InsertAtEnd)
558 : TerminatorInst(Type::VoidTy, Instruction::Unwind, 0, 0, InsertAtEnd) {
562 unsigned UnwindInst::getNumSuccessorsV() const {
563 return getNumSuccessors();
566 void UnwindInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
567 LLVM_UNREACHABLE("UnwindInst has no successors!");
570 BasicBlock *UnwindInst::getSuccessorV(unsigned idx) const {
571 LLVM_UNREACHABLE("UnwindInst has no successors!");
575 //===----------------------------------------------------------------------===//
576 // UnreachableInst Implementation
577 //===----------------------------------------------------------------------===//
579 UnreachableInst::UnreachableInst(Instruction *InsertBefore)
580 : TerminatorInst(Type::VoidTy, Instruction::Unreachable, 0, 0, InsertBefore) {
582 UnreachableInst::UnreachableInst(BasicBlock *InsertAtEnd)
583 : TerminatorInst(Type::VoidTy, Instruction::Unreachable, 0, 0, InsertAtEnd) {
586 unsigned UnreachableInst::getNumSuccessorsV() const {
587 return getNumSuccessors();
590 void UnreachableInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
591 LLVM_UNREACHABLE("UnwindInst has no successors!");
594 BasicBlock *UnreachableInst::getSuccessorV(unsigned idx) const {
595 LLVM_UNREACHABLE("UnwindInst has no successors!");
599 //===----------------------------------------------------------------------===//
600 // BranchInst Implementation
601 //===----------------------------------------------------------------------===//
603 void BranchInst::AssertOK() {
605 assert(getCondition()->getType() == Type::Int1Ty &&
606 "May only branch on boolean predicates!");
609 BranchInst::BranchInst(BasicBlock *IfTrue, Instruction *InsertBefore)
610 : TerminatorInst(Type::VoidTy, Instruction::Br,
611 OperandTraits<BranchInst>::op_end(this) - 1,
613 assert(IfTrue != 0 && "Branch destination may not be null!");
616 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
617 Instruction *InsertBefore)
618 : TerminatorInst(Type::VoidTy, Instruction::Br,
619 OperandTraits<BranchInst>::op_end(this) - 3,
629 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *InsertAtEnd)
630 : TerminatorInst(Type::VoidTy, Instruction::Br,
631 OperandTraits<BranchInst>::op_end(this) - 1,
633 assert(IfTrue != 0 && "Branch destination may not be null!");
637 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
638 BasicBlock *InsertAtEnd)
639 : TerminatorInst(Type::VoidTy, Instruction::Br,
640 OperandTraits<BranchInst>::op_end(this) - 3,
651 BranchInst::BranchInst(const BranchInst &BI) :
652 TerminatorInst(Type::VoidTy, Instruction::Br,
653 OperandTraits<BranchInst>::op_end(this) - BI.getNumOperands(),
654 BI.getNumOperands()) {
655 Op<-1>() = BI.Op<-1>();
656 if (BI.getNumOperands() != 1) {
657 assert(BI.getNumOperands() == 3 && "BR can have 1 or 3 operands!");
658 Op<-3>() = BI.Op<-3>();
659 Op<-2>() = BI.Op<-2>();
664 Use* Use::getPrefix() {
665 PointerIntPair<Use**, 2, PrevPtrTag> &PotentialPrefix(this[-1].Prev);
666 if (PotentialPrefix.getOpaqueValue())
669 return reinterpret_cast<Use*>((char*)&PotentialPrefix + 1);
672 BranchInst::~BranchInst() {
673 if (NumOperands == 1) {
674 if (Use *Prefix = OperandList->getPrefix()) {
677 // mark OperandList to have a special value for scrutiny
678 // by baseclass destructors and operator delete
679 OperandList = Prefix;
682 OperandList = op_begin();
688 BasicBlock *BranchInst::getSuccessorV(unsigned idx) const {
689 return getSuccessor(idx);
691 unsigned BranchInst::getNumSuccessorsV() const {
692 return getNumSuccessors();
694 void BranchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
695 setSuccessor(idx, B);
699 //===----------------------------------------------------------------------===//
700 // AllocationInst Implementation
701 //===----------------------------------------------------------------------===//
703 static Value *getAISize(Value *Amt) {
705 Amt = ConstantInt::get(Type::Int32Ty, 1);
707 assert(!isa<BasicBlock>(Amt) &&
708 "Passed basic block into allocation size parameter! Use other ctor");
709 assert(Amt->getType() == Type::Int32Ty &&
710 "Malloc/Allocation array size is not a 32-bit integer!");
715 AllocationInst::AllocationInst(const Type *Ty, Value *ArraySize, unsigned iTy,
716 unsigned Align, const std::string &Name,
717 Instruction *InsertBefore)
718 : UnaryInstruction(PointerType::getUnqual(Ty), iTy, getAISize(ArraySize),
721 assert(Ty != Type::VoidTy && "Cannot allocate void!");
725 AllocationInst::AllocationInst(const Type *Ty, Value *ArraySize, unsigned iTy,
726 unsigned Align, const std::string &Name,
727 BasicBlock *InsertAtEnd)
728 : UnaryInstruction(PointerType::getUnqual(Ty), iTy, getAISize(ArraySize),
731 assert(Ty != Type::VoidTy && "Cannot allocate void!");
735 // Out of line virtual method, so the vtable, etc has a home.
736 AllocationInst::~AllocationInst() {
739 void AllocationInst::setAlignment(unsigned Align) {
740 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
741 SubclassData = Log2_32(Align) + 1;
742 assert(getAlignment() == Align && "Alignment representation error!");
745 bool AllocationInst::isArrayAllocation() const {
746 if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(0)))
747 return CI->getZExtValue() != 1;
751 const Type *AllocationInst::getAllocatedType() const {
752 return getType()->getElementType();
755 AllocaInst::AllocaInst(const AllocaInst &AI)
756 : AllocationInst(AI.getType()->getElementType(), (Value*)AI.getOperand(0),
757 Instruction::Alloca, AI.getAlignment()) {
760 /// isStaticAlloca - Return true if this alloca is in the entry block of the
761 /// function and is a constant size. If so, the code generator will fold it
762 /// into the prolog/epilog code, so it is basically free.
763 bool AllocaInst::isStaticAlloca() const {
764 // Must be constant size.
765 if (!isa<ConstantInt>(getArraySize())) return false;
767 // Must be in the entry block.
768 const BasicBlock *Parent = getParent();
769 return Parent == &Parent->getParent()->front();
772 MallocInst::MallocInst(const MallocInst &MI)
773 : AllocationInst(MI.getType()->getElementType(), (Value*)MI.getOperand(0),
774 Instruction::Malloc, MI.getAlignment()) {
777 //===----------------------------------------------------------------------===//
778 // FreeInst Implementation
779 //===----------------------------------------------------------------------===//
781 void FreeInst::AssertOK() {
782 assert(isa<PointerType>(getOperand(0)->getType()) &&
783 "Can not free something of nonpointer type!");
786 FreeInst::FreeInst(Value *Ptr, Instruction *InsertBefore)
787 : UnaryInstruction(Type::VoidTy, Free, Ptr, InsertBefore) {
791 FreeInst::FreeInst(Value *Ptr, BasicBlock *InsertAtEnd)
792 : UnaryInstruction(Type::VoidTy, Free, Ptr, InsertAtEnd) {
797 //===----------------------------------------------------------------------===//
798 // LoadInst Implementation
799 //===----------------------------------------------------------------------===//
801 void LoadInst::AssertOK() {
802 assert(isa<PointerType>(getOperand(0)->getType()) &&
803 "Ptr must have pointer type.");
806 LoadInst::LoadInst(Value *Ptr, const std::string &Name, Instruction *InsertBef)
807 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
808 Load, Ptr, InsertBef) {
815 LoadInst::LoadInst(Value *Ptr, const std::string &Name, BasicBlock *InsertAE)
816 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
817 Load, Ptr, InsertAE) {
824 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile,
825 Instruction *InsertBef)
826 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
827 Load, Ptr, InsertBef) {
828 setVolatile(isVolatile);
834 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile,
835 unsigned Align, Instruction *InsertBef)
836 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
837 Load, Ptr, InsertBef) {
838 setVolatile(isVolatile);
844 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile,
845 unsigned Align, BasicBlock *InsertAE)
846 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
847 Load, Ptr, InsertAE) {
848 setVolatile(isVolatile);
854 LoadInst::LoadInst(Value *Ptr, const std::string &Name, bool isVolatile,
855 BasicBlock *InsertAE)
856 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
857 Load, Ptr, InsertAE) {
858 setVolatile(isVolatile);
866 LoadInst::LoadInst(Value *Ptr, const char *Name, Instruction *InsertBef)
867 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
868 Load, Ptr, InsertBef) {
872 if (Name && Name[0]) setName(Name);
875 LoadInst::LoadInst(Value *Ptr, const char *Name, BasicBlock *InsertAE)
876 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
877 Load, Ptr, InsertAE) {
881 if (Name && Name[0]) setName(Name);
884 LoadInst::LoadInst(Value *Ptr, const char *Name, bool isVolatile,
885 Instruction *InsertBef)
886 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
887 Load, Ptr, InsertBef) {
888 setVolatile(isVolatile);
891 if (Name && Name[0]) setName(Name);
894 LoadInst::LoadInst(Value *Ptr, const char *Name, bool isVolatile,
895 BasicBlock *InsertAE)
896 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
897 Load, Ptr, InsertAE) {
898 setVolatile(isVolatile);
901 if (Name && Name[0]) setName(Name);
904 void LoadInst::setAlignment(unsigned Align) {
905 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
906 SubclassData = (SubclassData & 1) | ((Log2_32(Align)+1)<<1);
909 //===----------------------------------------------------------------------===//
910 // StoreInst Implementation
911 //===----------------------------------------------------------------------===//
913 void StoreInst::AssertOK() {
914 assert(getOperand(0) && getOperand(1) && "Both operands must be non-null!");
915 assert(isa<PointerType>(getOperand(1)->getType()) &&
916 "Ptr must have pointer type!");
917 assert(getOperand(0)->getType() ==
918 cast<PointerType>(getOperand(1)->getType())->getElementType()
919 && "Ptr must be a pointer to Val type!");
923 StoreInst::StoreInst(Value *val, Value *addr, Instruction *InsertBefore)
924 : Instruction(Type::VoidTy, Store,
925 OperandTraits<StoreInst>::op_begin(this),
926 OperandTraits<StoreInst>::operands(this),
935 StoreInst::StoreInst(Value *val, Value *addr, BasicBlock *InsertAtEnd)
936 : Instruction(Type::VoidTy, Store,
937 OperandTraits<StoreInst>::op_begin(this),
938 OperandTraits<StoreInst>::operands(this),
947 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
948 Instruction *InsertBefore)
949 : Instruction(Type::VoidTy, Store,
950 OperandTraits<StoreInst>::op_begin(this),
951 OperandTraits<StoreInst>::operands(this),
955 setVolatile(isVolatile);
960 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
961 unsigned Align, Instruction *InsertBefore)
962 : Instruction(Type::VoidTy, Store,
963 OperandTraits<StoreInst>::op_begin(this),
964 OperandTraits<StoreInst>::operands(this),
968 setVolatile(isVolatile);
973 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
974 unsigned Align, BasicBlock *InsertAtEnd)
975 : Instruction(Type::VoidTy, Store,
976 OperandTraits<StoreInst>::op_begin(this),
977 OperandTraits<StoreInst>::operands(this),
981 setVolatile(isVolatile);
986 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
987 BasicBlock *InsertAtEnd)
988 : Instruction(Type::VoidTy, Store,
989 OperandTraits<StoreInst>::op_begin(this),
990 OperandTraits<StoreInst>::operands(this),
994 setVolatile(isVolatile);
999 void StoreInst::setAlignment(unsigned Align) {
1000 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
1001 SubclassData = (SubclassData & 1) | ((Log2_32(Align)+1)<<1);
1004 //===----------------------------------------------------------------------===//
1005 // GetElementPtrInst Implementation
1006 //===----------------------------------------------------------------------===//
1008 static unsigned retrieveAddrSpace(const Value *Val) {
1009 return cast<PointerType>(Val->getType())->getAddressSpace();
1012 void GetElementPtrInst::init(Value *Ptr, Value* const *Idx, unsigned NumIdx,
1013 const std::string &Name) {
1014 assert(NumOperands == 1+NumIdx && "NumOperands not initialized?");
1015 Use *OL = OperandList;
1018 for (unsigned i = 0; i != NumIdx; ++i)
1024 void GetElementPtrInst::init(Value *Ptr, Value *Idx, const std::string &Name) {
1025 assert(NumOperands == 2 && "NumOperands not initialized?");
1026 Use *OL = OperandList;
1033 GetElementPtrInst::GetElementPtrInst(const GetElementPtrInst &GEPI)
1034 : Instruction(GEPI.getType(), GetElementPtr,
1035 OperandTraits<GetElementPtrInst>::op_end(this)
1036 - GEPI.getNumOperands(),
1037 GEPI.getNumOperands()) {
1038 Use *OL = OperandList;
1039 Use *GEPIOL = GEPI.OperandList;
1040 for (unsigned i = 0, E = NumOperands; i != E; ++i)
1044 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx,
1045 const std::string &Name, Instruction *InBe)
1046 : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),Idx)),
1047 retrieveAddrSpace(Ptr)),
1049 OperandTraits<GetElementPtrInst>::op_end(this) - 2,
1051 init(Ptr, Idx, Name);
1054 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx,
1055 const std::string &Name, BasicBlock *IAE)
1056 : Instruction(PointerType::get(checkType(getIndexedType(Ptr->getType(),Idx)),
1057 retrieveAddrSpace(Ptr)),
1059 OperandTraits<GetElementPtrInst>::op_end(this) - 2,
1061 init(Ptr, Idx, Name);
1064 /// getIndexedType - Returns the type of the element that would be accessed with
1065 /// a gep instruction with the specified parameters.
1067 /// The Idxs pointer should point to a continuous piece of memory containing the
1068 /// indices, either as Value* or uint64_t.
1070 /// A null type is returned if the indices are invalid for the specified
1073 template <typename IndexTy>
1074 static const Type* getIndexedTypeInternal(const Type *Ptr, IndexTy const *Idxs,
1076 const PointerType *PTy = dyn_cast<PointerType>(Ptr);
1077 if (!PTy) return 0; // Type isn't a pointer type!
1078 const Type *Agg = PTy->getElementType();
1080 // Handle the special case of the empty set index set, which is always valid.
1084 // If there is at least one index, the top level type must be sized, otherwise
1085 // it cannot be 'stepped over'. We explicitly allow abstract types (those
1086 // that contain opaque types) under the assumption that it will be resolved to
1087 // a sane type later.
1088 if (!Agg->isSized() && !Agg->isAbstract())
1091 unsigned CurIdx = 1;
1092 for (; CurIdx != NumIdx; ++CurIdx) {
1093 const CompositeType *CT = dyn_cast<CompositeType>(Agg);
1094 if (!CT || isa<PointerType>(CT)) return 0;
1095 IndexTy Index = Idxs[CurIdx];
1096 if (!CT->indexValid(Index)) return 0;
1097 Agg = CT->getTypeAtIndex(Index);
1099 // If the new type forwards to another type, then it is in the middle
1100 // of being refined to another type (and hence, may have dropped all
1101 // references to what it was using before). So, use the new forwarded
1103 if (const Type *Ty = Agg->getForwardedType())
1106 return CurIdx == NumIdx ? Agg : 0;
1109 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr,
1112 return getIndexedTypeInternal(Ptr, Idxs, NumIdx);
1115 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr,
1116 uint64_t const *Idxs,
1118 return getIndexedTypeInternal(Ptr, Idxs, NumIdx);
1121 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr, Value *Idx) {
1122 const PointerType *PTy = dyn_cast<PointerType>(Ptr);
1123 if (!PTy) return 0; // Type isn't a pointer type!
1125 // Check the pointer index.
1126 if (!PTy->indexValid(Idx)) return 0;
1128 return PTy->getElementType();
1132 /// hasAllZeroIndices - Return true if all of the indices of this GEP are
1133 /// zeros. If so, the result pointer and the first operand have the same
1134 /// value, just potentially different types.
1135 bool GetElementPtrInst::hasAllZeroIndices() const {
1136 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1137 if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(i))) {
1138 if (!CI->isZero()) return false;
1146 /// hasAllConstantIndices - Return true if all of the indices of this GEP are
1147 /// constant integers. If so, the result pointer and the first operand have
1148 /// a constant offset between them.
1149 bool GetElementPtrInst::hasAllConstantIndices() const {
1150 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1151 if (!isa<ConstantInt>(getOperand(i)))
1158 //===----------------------------------------------------------------------===//
1159 // ExtractElementInst Implementation
1160 //===----------------------------------------------------------------------===//
1162 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
1163 const std::string &Name,
1164 Instruction *InsertBef)
1165 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1167 OperandTraits<ExtractElementInst>::op_begin(this),
1169 assert(isValidOperands(Val, Index) &&
1170 "Invalid extractelement instruction operands!");
1176 ExtractElementInst::ExtractElementInst(Value *Val, unsigned IndexV,
1177 const std::string &Name,
1178 Instruction *InsertBef)
1179 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1181 OperandTraits<ExtractElementInst>::op_begin(this),
1183 Constant *Index = ConstantInt::get(Type::Int32Ty, IndexV);
1184 assert(isValidOperands(Val, Index) &&
1185 "Invalid extractelement instruction operands!");
1192 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
1193 const std::string &Name,
1194 BasicBlock *InsertAE)
1195 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1197 OperandTraits<ExtractElementInst>::op_begin(this),
1199 assert(isValidOperands(Val, Index) &&
1200 "Invalid extractelement instruction operands!");
1207 ExtractElementInst::ExtractElementInst(Value *Val, unsigned IndexV,
1208 const std::string &Name,
1209 BasicBlock *InsertAE)
1210 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1212 OperandTraits<ExtractElementInst>::op_begin(this),
1214 Constant *Index = ConstantInt::get(Type::Int32Ty, IndexV);
1215 assert(isValidOperands(Val, Index) &&
1216 "Invalid extractelement instruction operands!");
1224 bool ExtractElementInst::isValidOperands(const Value *Val, const Value *Index) {
1225 if (!isa<VectorType>(Val->getType()) || Index->getType() != Type::Int32Ty)
1231 //===----------------------------------------------------------------------===//
1232 // InsertElementInst Implementation
1233 //===----------------------------------------------------------------------===//
1235 InsertElementInst::InsertElementInst(const InsertElementInst &IE)
1236 : Instruction(IE.getType(), InsertElement,
1237 OperandTraits<InsertElementInst>::op_begin(this), 3) {
1238 Op<0>() = IE.Op<0>();
1239 Op<1>() = IE.Op<1>();
1240 Op<2>() = IE.Op<2>();
1242 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
1243 const std::string &Name,
1244 Instruction *InsertBef)
1245 : Instruction(Vec->getType(), InsertElement,
1246 OperandTraits<InsertElementInst>::op_begin(this),
1248 assert(isValidOperands(Vec, Elt, Index) &&
1249 "Invalid insertelement instruction operands!");
1256 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, unsigned IndexV,
1257 const std::string &Name,
1258 Instruction *InsertBef)
1259 : Instruction(Vec->getType(), InsertElement,
1260 OperandTraits<InsertElementInst>::op_begin(this),
1262 Constant *Index = ConstantInt::get(Type::Int32Ty, IndexV);
1263 assert(isValidOperands(Vec, Elt, Index) &&
1264 "Invalid insertelement instruction operands!");
1272 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
1273 const std::string &Name,
1274 BasicBlock *InsertAE)
1275 : Instruction(Vec->getType(), InsertElement,
1276 OperandTraits<InsertElementInst>::op_begin(this),
1278 assert(isValidOperands(Vec, Elt, Index) &&
1279 "Invalid insertelement instruction operands!");
1287 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, unsigned IndexV,
1288 const std::string &Name,
1289 BasicBlock *InsertAE)
1290 : Instruction(Vec->getType(), InsertElement,
1291 OperandTraits<InsertElementInst>::op_begin(this),
1293 Constant *Index = ConstantInt::get(Type::Int32Ty, IndexV);
1294 assert(isValidOperands(Vec, Elt, Index) &&
1295 "Invalid insertelement instruction operands!");
1303 bool InsertElementInst::isValidOperands(const Value *Vec, const Value *Elt,
1304 const Value *Index) {
1305 if (!isa<VectorType>(Vec->getType()))
1306 return false; // First operand of insertelement must be vector type.
1308 if (Elt->getType() != cast<VectorType>(Vec->getType())->getElementType())
1309 return false;// Second operand of insertelement must be vector element type.
1311 if (Index->getType() != Type::Int32Ty)
1312 return false; // Third operand of insertelement must be i32.
1317 //===----------------------------------------------------------------------===//
1318 // ShuffleVectorInst Implementation
1319 //===----------------------------------------------------------------------===//
1321 ShuffleVectorInst::ShuffleVectorInst(const ShuffleVectorInst &SV)
1322 : Instruction(SV.getType(), ShuffleVector,
1323 OperandTraits<ShuffleVectorInst>::op_begin(this),
1324 OperandTraits<ShuffleVectorInst>::operands(this)) {
1325 Op<0>() = SV.Op<0>();
1326 Op<1>() = SV.Op<1>();
1327 Op<2>() = SV.Op<2>();
1330 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1331 const std::string &Name,
1332 Instruction *InsertBefore)
1333 : Instruction(VectorType::get(cast<VectorType>(V1->getType())->getElementType(),
1334 cast<VectorType>(Mask->getType())->getNumElements()),
1336 OperandTraits<ShuffleVectorInst>::op_begin(this),
1337 OperandTraits<ShuffleVectorInst>::operands(this),
1339 assert(isValidOperands(V1, V2, Mask) &&
1340 "Invalid shuffle vector instruction operands!");
1347 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1348 const std::string &Name,
1349 BasicBlock *InsertAtEnd)
1350 : Instruction(V1->getType(), ShuffleVector,
1351 OperandTraits<ShuffleVectorInst>::op_begin(this),
1352 OperandTraits<ShuffleVectorInst>::operands(this),
1354 assert(isValidOperands(V1, V2, Mask) &&
1355 "Invalid shuffle vector instruction operands!");
1363 bool ShuffleVectorInst::isValidOperands(const Value *V1, const Value *V2,
1364 const Value *Mask) {
1365 if (!isa<VectorType>(V1->getType()) || V1->getType() != V2->getType())
1368 const VectorType *MaskTy = dyn_cast<VectorType>(Mask->getType());
1369 if (!isa<Constant>(Mask) || MaskTy == 0 ||
1370 MaskTy->getElementType() != Type::Int32Ty)
1375 /// getMaskValue - Return the index from the shuffle mask for the specified
1376 /// output result. This is either -1 if the element is undef or a number less
1377 /// than 2*numelements.
1378 int ShuffleVectorInst::getMaskValue(unsigned i) const {
1379 const Constant *Mask = cast<Constant>(getOperand(2));
1380 if (isa<UndefValue>(Mask)) return -1;
1381 if (isa<ConstantAggregateZero>(Mask)) return 0;
1382 const ConstantVector *MaskCV = cast<ConstantVector>(Mask);
1383 assert(i < MaskCV->getNumOperands() && "Index out of range");
1385 if (isa<UndefValue>(MaskCV->getOperand(i)))
1387 return cast<ConstantInt>(MaskCV->getOperand(i))->getZExtValue();
1390 //===----------------------------------------------------------------------===//
1391 // InsertValueInst Class
1392 //===----------------------------------------------------------------------===//
1394 void InsertValueInst::init(Value *Agg, Value *Val, const unsigned *Idx,
1395 unsigned NumIdx, const std::string &Name) {
1396 assert(NumOperands == 2 && "NumOperands not initialized?");
1400 Indices.insert(Indices.end(), Idx, Idx + NumIdx);
1404 void InsertValueInst::init(Value *Agg, Value *Val, unsigned Idx,
1405 const std::string &Name) {
1406 assert(NumOperands == 2 && "NumOperands not initialized?");
1410 Indices.push_back(Idx);
1414 InsertValueInst::InsertValueInst(const InsertValueInst &IVI)
1415 : Instruction(IVI.getType(), InsertValue,
1416 OperandTraits<InsertValueInst>::op_begin(this), 2),
1417 Indices(IVI.Indices) {
1418 Op<0>() = IVI.getOperand(0);
1419 Op<1>() = IVI.getOperand(1);
1422 InsertValueInst::InsertValueInst(Value *Agg,
1425 const std::string &Name,
1426 Instruction *InsertBefore)
1427 : Instruction(Agg->getType(), InsertValue,
1428 OperandTraits<InsertValueInst>::op_begin(this),
1430 init(Agg, Val, Idx, Name);
1433 InsertValueInst::InsertValueInst(Value *Agg,
1436 const std::string &Name,
1437 BasicBlock *InsertAtEnd)
1438 : Instruction(Agg->getType(), InsertValue,
1439 OperandTraits<InsertValueInst>::op_begin(this),
1441 init(Agg, Val, Idx, Name);
1444 //===----------------------------------------------------------------------===//
1445 // ExtractValueInst Class
1446 //===----------------------------------------------------------------------===//
1448 void ExtractValueInst::init(const unsigned *Idx, unsigned NumIdx,
1449 const std::string &Name) {
1450 assert(NumOperands == 1 && "NumOperands not initialized?");
1452 Indices.insert(Indices.end(), Idx, Idx + NumIdx);
1456 void ExtractValueInst::init(unsigned Idx, const std::string &Name) {
1457 assert(NumOperands == 1 && "NumOperands not initialized?");
1459 Indices.push_back(Idx);
1463 ExtractValueInst::ExtractValueInst(const ExtractValueInst &EVI)
1464 : UnaryInstruction(EVI.getType(), ExtractValue, EVI.getOperand(0)),
1465 Indices(EVI.Indices) {
1468 // getIndexedType - Returns the type of the element that would be extracted
1469 // with an extractvalue instruction with the specified parameters.
1471 // A null type is returned if the indices are invalid for the specified
1474 const Type* ExtractValueInst::getIndexedType(const Type *Agg,
1475 const unsigned *Idxs,
1477 unsigned CurIdx = 0;
1478 for (; CurIdx != NumIdx; ++CurIdx) {
1479 const CompositeType *CT = dyn_cast<CompositeType>(Agg);
1480 if (!CT || isa<PointerType>(CT) || isa<VectorType>(CT)) return 0;
1481 unsigned Index = Idxs[CurIdx];
1482 if (!CT->indexValid(Index)) return 0;
1483 Agg = CT->getTypeAtIndex(Index);
1485 // If the new type forwards to another type, then it is in the middle
1486 // of being refined to another type (and hence, may have dropped all
1487 // references to what it was using before). So, use the new forwarded
1489 if (const Type *Ty = Agg->getForwardedType())
1492 return CurIdx == NumIdx ? Agg : 0;
1495 const Type* ExtractValueInst::getIndexedType(const Type *Agg,
1497 return getIndexedType(Agg, &Idx, 1);
1500 //===----------------------------------------------------------------------===//
1501 // BinaryOperator Class
1502 //===----------------------------------------------------------------------===//
1504 /// AdjustIType - Map Add, Sub, and Mul to FAdd, FSub, and FMul when the
1505 /// type is floating-point, to help provide compatibility with an older API.
1507 static BinaryOperator::BinaryOps AdjustIType(BinaryOperator::BinaryOps iType,
1509 // API compatibility: Adjust integer opcodes to floating-point opcodes.
1510 if (Ty->isFPOrFPVector()) {
1511 if (iType == BinaryOperator::Add) iType = BinaryOperator::FAdd;
1512 else if (iType == BinaryOperator::Sub) iType = BinaryOperator::FSub;
1513 else if (iType == BinaryOperator::Mul) iType = BinaryOperator::FMul;
1518 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
1519 const Type *Ty, const std::string &Name,
1520 Instruction *InsertBefore)
1521 : Instruction(Ty, AdjustIType(iType, Ty),
1522 OperandTraits<BinaryOperator>::op_begin(this),
1523 OperandTraits<BinaryOperator>::operands(this),
1527 init(AdjustIType(iType, Ty));
1531 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
1532 const Type *Ty, const std::string &Name,
1533 BasicBlock *InsertAtEnd)
1534 : Instruction(Ty, AdjustIType(iType, Ty),
1535 OperandTraits<BinaryOperator>::op_begin(this),
1536 OperandTraits<BinaryOperator>::operands(this),
1540 init(AdjustIType(iType, Ty));
1545 void BinaryOperator::init(BinaryOps iType) {
1546 Value *LHS = getOperand(0), *RHS = getOperand(1);
1547 LHS = LHS; RHS = RHS; // Silence warnings.
1548 assert(LHS->getType() == RHS->getType() &&
1549 "Binary operator operand types must match!");
1554 assert(getType() == LHS->getType() &&
1555 "Arithmetic operation should return same type as operands!");
1556 assert(getType()->isIntOrIntVector() &&
1557 "Tried to create an integer operation on a non-integer type!");
1559 case FAdd: case FSub:
1561 assert(getType() == LHS->getType() &&
1562 "Arithmetic operation should return same type as operands!");
1563 assert(getType()->isFPOrFPVector() &&
1564 "Tried to create a floating-point operation on a "
1565 "non-floating-point type!");
1569 assert(getType() == LHS->getType() &&
1570 "Arithmetic operation should return same type as operands!");
1571 assert((getType()->isInteger() || (isa<VectorType>(getType()) &&
1572 cast<VectorType>(getType())->getElementType()->isInteger())) &&
1573 "Incorrect operand type (not integer) for S/UDIV");
1576 assert(getType() == LHS->getType() &&
1577 "Arithmetic operation should return same type as operands!");
1578 assert(getType()->isFPOrFPVector() &&
1579 "Incorrect operand type (not floating point) for FDIV");
1583 assert(getType() == LHS->getType() &&
1584 "Arithmetic operation should return same type as operands!");
1585 assert((getType()->isInteger() || (isa<VectorType>(getType()) &&
1586 cast<VectorType>(getType())->getElementType()->isInteger())) &&
1587 "Incorrect operand type (not integer) for S/UREM");
1590 assert(getType() == LHS->getType() &&
1591 "Arithmetic operation should return same type as operands!");
1592 assert(getType()->isFPOrFPVector() &&
1593 "Incorrect operand type (not floating point) for FREM");
1598 assert(getType() == LHS->getType() &&
1599 "Shift operation should return same type as operands!");
1600 assert((getType()->isInteger() ||
1601 (isa<VectorType>(getType()) &&
1602 cast<VectorType>(getType())->getElementType()->isInteger())) &&
1603 "Tried to create a shift operation on a non-integral type!");
1607 assert(getType() == LHS->getType() &&
1608 "Logical operation should return same type as operands!");
1609 assert((getType()->isInteger() ||
1610 (isa<VectorType>(getType()) &&
1611 cast<VectorType>(getType())->getElementType()->isInteger())) &&
1612 "Tried to create a logical operation on a non-integral type!");
1620 BinaryOperator *BinaryOperator::Create(BinaryOps Op, Value *S1, Value *S2,
1621 const std::string &Name,
1622 Instruction *InsertBefore) {
1623 assert(S1->getType() == S2->getType() &&
1624 "Cannot create binary operator with two operands of differing type!");
1625 return new BinaryOperator(Op, S1, S2, S1->getType(), Name, InsertBefore);
1628 BinaryOperator *BinaryOperator::Create(BinaryOps Op, Value *S1, Value *S2,
1629 const std::string &Name,
1630 BasicBlock *InsertAtEnd) {
1631 BinaryOperator *Res = Create(Op, S1, S2, Name);
1632 InsertAtEnd->getInstList().push_back(Res);
1636 BinaryOperator *BinaryOperator::CreateNeg(Value *Op, const std::string &Name,
1637 Instruction *InsertBefore) {
1638 Value *zero = ConstantExpr::getZeroValueForNegationExpr(Op->getType());
1639 return new BinaryOperator(Instruction::Sub,
1641 Op->getType(), Name, InsertBefore);
1644 BinaryOperator *BinaryOperator::CreateNeg(Value *Op, const std::string &Name,
1645 BasicBlock *InsertAtEnd) {
1646 Value *zero = ConstantExpr::getZeroValueForNegationExpr(Op->getType());
1647 return new BinaryOperator(Instruction::Sub,
1649 Op->getType(), Name, InsertAtEnd);
1652 BinaryOperator *BinaryOperator::CreateFNeg(Value *Op, const std::string &Name,
1653 Instruction *InsertBefore) {
1654 Value *zero = ConstantExpr::getZeroValueForNegationExpr(Op->getType());
1655 return new BinaryOperator(Instruction::FSub,
1657 Op->getType(), Name, InsertBefore);
1660 BinaryOperator *BinaryOperator::CreateFNeg(Value *Op, const std::string &Name,
1661 BasicBlock *InsertAtEnd) {
1662 Value *zero = ConstantExpr::getZeroValueForNegationExpr(Op->getType());
1663 return new BinaryOperator(Instruction::FSub,
1665 Op->getType(), Name, InsertAtEnd);
1668 BinaryOperator *BinaryOperator::CreateNot(Value *Op, const std::string &Name,
1669 Instruction *InsertBefore) {
1671 if (const VectorType *PTy = dyn_cast<VectorType>(Op->getType())) {
1672 C = ConstantInt::getAllOnesValue(PTy->getElementType());
1673 C = ConstantVector::get(std::vector<Constant*>(PTy->getNumElements(), C));
1675 C = ConstantInt::getAllOnesValue(Op->getType());
1678 return new BinaryOperator(Instruction::Xor, Op, C,
1679 Op->getType(), Name, InsertBefore);
1682 BinaryOperator *BinaryOperator::CreateNot(Value *Op, const std::string &Name,
1683 BasicBlock *InsertAtEnd) {
1685 if (const VectorType *PTy = dyn_cast<VectorType>(Op->getType())) {
1686 // Create a vector of all ones values.
1687 Constant *Elt = ConstantInt::getAllOnesValue(PTy->getElementType());
1689 ConstantVector::get(std::vector<Constant*>(PTy->getNumElements(), Elt));
1691 AllOnes = ConstantInt::getAllOnesValue(Op->getType());
1694 return new BinaryOperator(Instruction::Xor, Op, AllOnes,
1695 Op->getType(), Name, InsertAtEnd);
1699 // isConstantAllOnes - Helper function for several functions below
1700 static inline bool isConstantAllOnes(const Value *V) {
1701 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V))
1702 return CI->isAllOnesValue();
1703 if (const ConstantVector *CV = dyn_cast<ConstantVector>(V))
1704 return CV->isAllOnesValue();
1708 bool BinaryOperator::isNeg(const Value *V) {
1709 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1710 if (Bop->getOpcode() == Instruction::Sub)
1711 return Bop->getOperand(0) ==
1712 ConstantExpr::getZeroValueForNegationExpr(Bop->getType());
1716 bool BinaryOperator::isFNeg(const Value *V) {
1717 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1718 if (Bop->getOpcode() == Instruction::FSub)
1719 return Bop->getOperand(0) ==
1720 ConstantExpr::getZeroValueForNegationExpr(Bop->getType());
1724 bool BinaryOperator::isNot(const Value *V) {
1725 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1726 return (Bop->getOpcode() == Instruction::Xor &&
1727 (isConstantAllOnes(Bop->getOperand(1)) ||
1728 isConstantAllOnes(Bop->getOperand(0))));
1732 Value *BinaryOperator::getNegArgument(Value *BinOp) {
1733 assert(isNeg(BinOp) && "getNegArgument from non-'neg' instruction!");
1734 return cast<BinaryOperator>(BinOp)->getOperand(1);
1737 const Value *BinaryOperator::getNegArgument(const Value *BinOp) {
1738 return getNegArgument(const_cast<Value*>(BinOp));
1741 Value *BinaryOperator::getFNegArgument(Value *BinOp) {
1742 assert(isFNeg(BinOp) && "getFNegArgument from non-'fneg' instruction!");
1743 return cast<BinaryOperator>(BinOp)->getOperand(1);
1746 const Value *BinaryOperator::getFNegArgument(const Value *BinOp) {
1747 return getFNegArgument(const_cast<Value*>(BinOp));
1750 Value *BinaryOperator::getNotArgument(Value *BinOp) {
1751 assert(isNot(BinOp) && "getNotArgument on non-'not' instruction!");
1752 BinaryOperator *BO = cast<BinaryOperator>(BinOp);
1753 Value *Op0 = BO->getOperand(0);
1754 Value *Op1 = BO->getOperand(1);
1755 if (isConstantAllOnes(Op0)) return Op1;
1757 assert(isConstantAllOnes(Op1));
1761 const Value *BinaryOperator::getNotArgument(const Value *BinOp) {
1762 return getNotArgument(const_cast<Value*>(BinOp));
1766 // swapOperands - Exchange the two operands to this instruction. This
1767 // instruction is safe to use on any binary instruction and does not
1768 // modify the semantics of the instruction. If the instruction is
1769 // order dependent (SetLT f.e.) the opcode is changed.
1771 bool BinaryOperator::swapOperands() {
1772 if (!isCommutative())
1773 return true; // Can't commute operands
1774 Op<0>().swap(Op<1>());
1778 //===----------------------------------------------------------------------===//
1780 //===----------------------------------------------------------------------===//
1782 // Just determine if this cast only deals with integral->integral conversion.
1783 bool CastInst::isIntegerCast() const {
1784 switch (getOpcode()) {
1785 default: return false;
1786 case Instruction::ZExt:
1787 case Instruction::SExt:
1788 case Instruction::Trunc:
1790 case Instruction::BitCast:
1791 return getOperand(0)->getType()->isInteger() && getType()->isInteger();
1795 bool CastInst::isLosslessCast() const {
1796 // Only BitCast can be lossless, exit fast if we're not BitCast
1797 if (getOpcode() != Instruction::BitCast)
1800 // Identity cast is always lossless
1801 const Type* SrcTy = getOperand(0)->getType();
1802 const Type* DstTy = getType();
1806 // Pointer to pointer is always lossless.
1807 if (isa<PointerType>(SrcTy))
1808 return isa<PointerType>(DstTy);
1809 return false; // Other types have no identity values
1812 /// This function determines if the CastInst does not require any bits to be
1813 /// changed in order to effect the cast. Essentially, it identifies cases where
1814 /// no code gen is necessary for the cast, hence the name no-op cast. For
1815 /// example, the following are all no-op casts:
1816 /// # bitcast i32* %x to i8*
1817 /// # bitcast <2 x i32> %x to <4 x i16>
1818 /// # ptrtoint i32* %x to i32 ; on 32-bit plaforms only
1819 /// @brief Determine if a cast is a no-op.
1820 bool CastInst::isNoopCast(const Type *IntPtrTy) const {
1821 switch (getOpcode()) {
1823 assert(!"Invalid CastOp");
1824 case Instruction::Trunc:
1825 case Instruction::ZExt:
1826 case Instruction::SExt:
1827 case Instruction::FPTrunc:
1828 case Instruction::FPExt:
1829 case Instruction::UIToFP:
1830 case Instruction::SIToFP:
1831 case Instruction::FPToUI:
1832 case Instruction::FPToSI:
1833 return false; // These always modify bits
1834 case Instruction::BitCast:
1835 return true; // BitCast never modifies bits.
1836 case Instruction::PtrToInt:
1837 return IntPtrTy->getScalarSizeInBits() ==
1838 getType()->getScalarSizeInBits();
1839 case Instruction::IntToPtr:
1840 return IntPtrTy->getScalarSizeInBits() ==
1841 getOperand(0)->getType()->getScalarSizeInBits();
1845 /// This function determines if a pair of casts can be eliminated and what
1846 /// opcode should be used in the elimination. This assumes that there are two
1847 /// instructions like this:
1848 /// * %F = firstOpcode SrcTy %x to MidTy
1849 /// * %S = secondOpcode MidTy %F to DstTy
1850 /// The function returns a resultOpcode so these two casts can be replaced with:
1851 /// * %Replacement = resultOpcode %SrcTy %x to DstTy
1852 /// If no such cast is permited, the function returns 0.
1853 unsigned CastInst::isEliminableCastPair(
1854 Instruction::CastOps firstOp, Instruction::CastOps secondOp,
1855 const Type *SrcTy, const Type *MidTy, const Type *DstTy, const Type *IntPtrTy)
1857 // Define the 144 possibilities for these two cast instructions. The values
1858 // in this matrix determine what to do in a given situation and select the
1859 // case in the switch below. The rows correspond to firstOp, the columns
1860 // correspond to secondOp. In looking at the table below, keep in mind
1861 // the following cast properties:
1863 // Size Compare Source Destination
1864 // Operator Src ? Size Type Sign Type Sign
1865 // -------- ------------ ------------------- ---------------------
1866 // TRUNC > Integer Any Integral Any
1867 // ZEXT < Integral Unsigned Integer Any
1868 // SEXT < Integral Signed Integer Any
1869 // FPTOUI n/a FloatPt n/a Integral Unsigned
1870 // FPTOSI n/a FloatPt n/a Integral Signed
1871 // UITOFP n/a Integral Unsigned FloatPt n/a
1872 // SITOFP n/a Integral Signed FloatPt n/a
1873 // FPTRUNC > FloatPt n/a FloatPt n/a
1874 // FPEXT < FloatPt n/a FloatPt n/a
1875 // PTRTOINT n/a Pointer n/a Integral Unsigned
1876 // INTTOPTR n/a Integral Unsigned Pointer n/a
1877 // BITCONVERT = FirstClass n/a FirstClass n/a
1879 // NOTE: some transforms are safe, but we consider them to be non-profitable.
1880 // For example, we could merge "fptoui double to i32" + "zext i32 to i64",
1881 // into "fptoui double to i64", but this loses information about the range
1882 // of the produced value (we no longer know the top-part is all zeros).
1883 // Further this conversion is often much more expensive for typical hardware,
1884 // and causes issues when building libgcc. We disallow fptosi+sext for the
1886 const unsigned numCastOps =
1887 Instruction::CastOpsEnd - Instruction::CastOpsBegin;
1888 static const uint8_t CastResults[numCastOps][numCastOps] = {
1889 // T F F U S F F P I B -+
1890 // R Z S P P I I T P 2 N T |
1891 // U E E 2 2 2 2 R E I T C +- secondOp
1892 // N X X U S F F N X N 2 V |
1893 // C T T I I P P C T T P T -+
1894 { 1, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // Trunc -+
1895 { 8, 1, 9,99,99, 2, 0,99,99,99, 2, 3 }, // ZExt |
1896 { 8, 0, 1,99,99, 0, 2,99,99,99, 0, 3 }, // SExt |
1897 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // FPToUI |
1898 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // FPToSI |
1899 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4 }, // UIToFP +- firstOp
1900 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4 }, // SIToFP |
1901 { 99,99,99, 0, 0,99,99, 1, 0,99,99, 4 }, // FPTrunc |
1902 { 99,99,99, 2, 2,99,99,10, 2,99,99, 4 }, // FPExt |
1903 { 1, 0, 0,99,99, 0, 0,99,99,99, 7, 3 }, // PtrToInt |
1904 { 99,99,99,99,99,99,99,99,99,13,99,12 }, // IntToPtr |
1905 { 5, 5, 5, 6, 6, 5, 5, 6, 6,11, 5, 1 }, // BitCast -+
1908 int ElimCase = CastResults[firstOp-Instruction::CastOpsBegin]
1909 [secondOp-Instruction::CastOpsBegin];
1912 // categorically disallowed
1915 // allowed, use first cast's opcode
1918 // allowed, use second cast's opcode
1921 // no-op cast in second op implies firstOp as long as the DestTy
1923 if (DstTy->isInteger())
1927 // no-op cast in second op implies firstOp as long as the DestTy
1928 // is floating point
1929 if (DstTy->isFloatingPoint())
1933 // no-op cast in first op implies secondOp as long as the SrcTy
1935 if (SrcTy->isInteger())
1939 // no-op cast in first op implies secondOp as long as the SrcTy
1940 // is a floating point
1941 if (SrcTy->isFloatingPoint())
1945 // ptrtoint, inttoptr -> bitcast (ptr -> ptr) if int size is >= ptr size
1946 unsigned PtrSize = IntPtrTy->getScalarSizeInBits();
1947 unsigned MidSize = MidTy->getScalarSizeInBits();
1948 if (MidSize >= PtrSize)
1949 return Instruction::BitCast;
1953 // ext, trunc -> bitcast, if the SrcTy and DstTy are same size
1954 // ext, trunc -> ext, if sizeof(SrcTy) < sizeof(DstTy)
1955 // ext, trunc -> trunc, if sizeof(SrcTy) > sizeof(DstTy)
1956 unsigned SrcSize = SrcTy->getScalarSizeInBits();
1957 unsigned DstSize = DstTy->getScalarSizeInBits();
1958 if (SrcSize == DstSize)
1959 return Instruction::BitCast;
1960 else if (SrcSize < DstSize)
1964 case 9: // zext, sext -> zext, because sext can't sign extend after zext
1965 return Instruction::ZExt;
1967 // fpext followed by ftrunc is allowed if the bit size returned to is
1968 // the same as the original, in which case its just a bitcast
1970 return Instruction::BitCast;
1971 return 0; // If the types are not the same we can't eliminate it.
1973 // bitcast followed by ptrtoint is allowed as long as the bitcast
1974 // is a pointer to pointer cast.
1975 if (isa<PointerType>(SrcTy) && isa<PointerType>(MidTy))
1979 // inttoptr, bitcast -> intptr if bitcast is a ptr to ptr cast
1980 if (isa<PointerType>(MidTy) && isa<PointerType>(DstTy))
1984 // inttoptr, ptrtoint -> bitcast if SrcSize<=PtrSize and SrcSize==DstSize
1985 unsigned PtrSize = IntPtrTy->getScalarSizeInBits();
1986 unsigned SrcSize = SrcTy->getScalarSizeInBits();
1987 unsigned DstSize = DstTy->getScalarSizeInBits();
1988 if (SrcSize <= PtrSize && SrcSize == DstSize)
1989 return Instruction::BitCast;
1993 // cast combination can't happen (error in input). This is for all cases
1994 // where the MidTy is not the same for the two cast instructions.
1995 assert(!"Invalid Cast Combination");
1998 assert(!"Error in CastResults table!!!");
2004 CastInst *CastInst::Create(Instruction::CastOps op, Value *S, const Type *Ty,
2005 const std::string &Name, Instruction *InsertBefore) {
2006 // Construct and return the appropriate CastInst subclass
2008 case Trunc: return new TruncInst (S, Ty, Name, InsertBefore);
2009 case ZExt: return new ZExtInst (S, Ty, Name, InsertBefore);
2010 case SExt: return new SExtInst (S, Ty, Name, InsertBefore);
2011 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertBefore);
2012 case FPExt: return new FPExtInst (S, Ty, Name, InsertBefore);
2013 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertBefore);
2014 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertBefore);
2015 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertBefore);
2016 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertBefore);
2017 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertBefore);
2018 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertBefore);
2019 case BitCast: return new BitCastInst (S, Ty, Name, InsertBefore);
2021 assert(!"Invalid opcode provided");
2026 CastInst *CastInst::Create(Instruction::CastOps op, Value *S, const Type *Ty,
2027 const std::string &Name, BasicBlock *InsertAtEnd) {
2028 // Construct and return the appropriate CastInst subclass
2030 case Trunc: return new TruncInst (S, Ty, Name, InsertAtEnd);
2031 case ZExt: return new ZExtInst (S, Ty, Name, InsertAtEnd);
2032 case SExt: return new SExtInst (S, Ty, Name, InsertAtEnd);
2033 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertAtEnd);
2034 case FPExt: return new FPExtInst (S, Ty, Name, InsertAtEnd);
2035 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertAtEnd);
2036 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertAtEnd);
2037 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertAtEnd);
2038 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertAtEnd);
2039 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertAtEnd);
2040 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertAtEnd);
2041 case BitCast: return new BitCastInst (S, Ty, Name, InsertAtEnd);
2043 assert(!"Invalid opcode provided");
2048 CastInst *CastInst::CreateZExtOrBitCast(Value *S, const Type *Ty,
2049 const std::string &Name,
2050 Instruction *InsertBefore) {
2051 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2052 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2053 return Create(Instruction::ZExt, S, Ty, Name, InsertBefore);
2056 CastInst *CastInst::CreateZExtOrBitCast(Value *S, const Type *Ty,
2057 const std::string &Name,
2058 BasicBlock *InsertAtEnd) {
2059 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2060 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2061 return Create(Instruction::ZExt, S, Ty, Name, InsertAtEnd);
2064 CastInst *CastInst::CreateSExtOrBitCast(Value *S, const Type *Ty,
2065 const std::string &Name,
2066 Instruction *InsertBefore) {
2067 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2068 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2069 return Create(Instruction::SExt, S, Ty, Name, InsertBefore);
2072 CastInst *CastInst::CreateSExtOrBitCast(Value *S, const Type *Ty,
2073 const std::string &Name,
2074 BasicBlock *InsertAtEnd) {
2075 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2076 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2077 return Create(Instruction::SExt, S, Ty, Name, InsertAtEnd);
2080 CastInst *CastInst::CreateTruncOrBitCast(Value *S, const Type *Ty,
2081 const std::string &Name,
2082 Instruction *InsertBefore) {
2083 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2084 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2085 return Create(Instruction::Trunc, S, Ty, Name, InsertBefore);
2088 CastInst *CastInst::CreateTruncOrBitCast(Value *S, const Type *Ty,
2089 const std::string &Name,
2090 BasicBlock *InsertAtEnd) {
2091 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2092 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2093 return Create(Instruction::Trunc, S, Ty, Name, InsertAtEnd);
2096 CastInst *CastInst::CreatePointerCast(Value *S, const Type *Ty,
2097 const std::string &Name,
2098 BasicBlock *InsertAtEnd) {
2099 assert(isa<PointerType>(S->getType()) && "Invalid cast");
2100 assert((Ty->isInteger() || isa<PointerType>(Ty)) &&
2103 if (Ty->isInteger())
2104 return Create(Instruction::PtrToInt, S, Ty, Name, InsertAtEnd);
2105 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2108 /// @brief Create a BitCast or a PtrToInt cast instruction
2109 CastInst *CastInst::CreatePointerCast(Value *S, const Type *Ty,
2110 const std::string &Name,
2111 Instruction *InsertBefore) {
2112 assert(isa<PointerType>(S->getType()) && "Invalid cast");
2113 assert((Ty->isInteger() || isa<PointerType>(Ty)) &&
2116 if (Ty->isInteger())
2117 return Create(Instruction::PtrToInt, S, Ty, Name, InsertBefore);
2118 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2121 CastInst *CastInst::CreateIntegerCast(Value *C, const Type *Ty,
2122 bool isSigned, const std::string &Name,
2123 Instruction *InsertBefore) {
2124 assert(C->getType()->isInteger() && Ty->isInteger() && "Invalid cast");
2125 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2126 unsigned DstBits = Ty->getScalarSizeInBits();
2127 Instruction::CastOps opcode =
2128 (SrcBits == DstBits ? Instruction::BitCast :
2129 (SrcBits > DstBits ? Instruction::Trunc :
2130 (isSigned ? Instruction::SExt : Instruction::ZExt)));
2131 return Create(opcode, C, Ty, Name, InsertBefore);
2134 CastInst *CastInst::CreateIntegerCast(Value *C, const Type *Ty,
2135 bool isSigned, const std::string &Name,
2136 BasicBlock *InsertAtEnd) {
2137 assert(C->getType()->isIntOrIntVector() && Ty->isIntOrIntVector() &&
2139 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2140 unsigned DstBits = Ty->getScalarSizeInBits();
2141 Instruction::CastOps opcode =
2142 (SrcBits == DstBits ? Instruction::BitCast :
2143 (SrcBits > DstBits ? Instruction::Trunc :
2144 (isSigned ? Instruction::SExt : Instruction::ZExt)));
2145 return Create(opcode, C, Ty, Name, InsertAtEnd);
2148 CastInst *CastInst::CreateFPCast(Value *C, const Type *Ty,
2149 const std::string &Name,
2150 Instruction *InsertBefore) {
2151 assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
2153 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2154 unsigned DstBits = Ty->getScalarSizeInBits();
2155 Instruction::CastOps opcode =
2156 (SrcBits == DstBits ? Instruction::BitCast :
2157 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
2158 return Create(opcode, C, Ty, Name, InsertBefore);
2161 CastInst *CastInst::CreateFPCast(Value *C, const Type *Ty,
2162 const std::string &Name,
2163 BasicBlock *InsertAtEnd) {
2164 assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
2166 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2167 unsigned DstBits = Ty->getScalarSizeInBits();
2168 Instruction::CastOps opcode =
2169 (SrcBits == DstBits ? Instruction::BitCast :
2170 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
2171 return Create(opcode, C, Ty, Name, InsertAtEnd);
2174 // Check whether it is valid to call getCastOpcode for these types.
2175 // This routine must be kept in sync with getCastOpcode.
2176 bool CastInst::isCastable(const Type *SrcTy, const Type *DestTy) {
2177 if (!SrcTy->isFirstClassType() || !DestTy->isFirstClassType())
2180 if (SrcTy == DestTy)
2183 // Get the bit sizes, we'll need these
2184 unsigned SrcBits = SrcTy->getScalarSizeInBits(); // 0 for ptr
2185 unsigned DestBits = DestTy->getScalarSizeInBits(); // 0 for ptr
2187 // Run through the possibilities ...
2188 if (DestTy->isInteger()) { // Casting to integral
2189 if (SrcTy->isInteger()) { // Casting from integral
2191 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt
2193 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
2194 // Casting from vector
2195 return DestBits == PTy->getBitWidth();
2196 } else { // Casting from something else
2197 return isa<PointerType>(SrcTy);
2199 } else if (DestTy->isFloatingPoint()) { // Casting to floating pt
2200 if (SrcTy->isInteger()) { // Casting from integral
2202 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt
2204 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
2205 // Casting from vector
2206 return DestBits == PTy->getBitWidth();
2207 } else { // Casting from something else
2210 } else if (const VectorType *DestPTy = dyn_cast<VectorType>(DestTy)) {
2211 // Casting to vector
2212 if (const VectorType *SrcPTy = dyn_cast<VectorType>(SrcTy)) {
2213 // Casting from vector
2214 return DestPTy->getBitWidth() == SrcPTy->getBitWidth();
2215 } else { // Casting from something else
2216 return DestPTy->getBitWidth() == SrcBits;
2218 } else if (isa<PointerType>(DestTy)) { // Casting to pointer
2219 if (isa<PointerType>(SrcTy)) { // Casting from pointer
2221 } else if (SrcTy->isInteger()) { // Casting from integral
2223 } else { // Casting from something else
2226 } else { // Casting to something else
2231 // Provide a way to get a "cast" where the cast opcode is inferred from the
2232 // types and size of the operand. This, basically, is a parallel of the
2233 // logic in the castIsValid function below. This axiom should hold:
2234 // castIsValid( getCastOpcode(Val, Ty), Val, Ty)
2235 // should not assert in castIsValid. In other words, this produces a "correct"
2236 // casting opcode for the arguments passed to it.
2237 // This routine must be kept in sync with isCastable.
2238 Instruction::CastOps
2239 CastInst::getCastOpcode(
2240 const Value *Src, bool SrcIsSigned, const Type *DestTy, bool DestIsSigned) {
2241 // Get the bit sizes, we'll need these
2242 const Type *SrcTy = Src->getType();
2243 unsigned SrcBits = SrcTy->getScalarSizeInBits(); // 0 for ptr
2244 unsigned DestBits = DestTy->getScalarSizeInBits(); // 0 for ptr
2246 assert(SrcTy->isFirstClassType() && DestTy->isFirstClassType() &&
2247 "Only first class types are castable!");
2249 // Run through the possibilities ...
2250 if (DestTy->isInteger()) { // Casting to integral
2251 if (SrcTy->isInteger()) { // Casting from integral
2252 if (DestBits < SrcBits)
2253 return Trunc; // int -> smaller int
2254 else if (DestBits > SrcBits) { // its an extension
2256 return SExt; // signed -> SEXT
2258 return ZExt; // unsigned -> ZEXT
2260 return BitCast; // Same size, No-op cast
2262 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt
2264 return FPToSI; // FP -> sint
2266 return FPToUI; // FP -> uint
2267 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
2268 assert(DestBits == PTy->getBitWidth() &&
2269 "Casting vector to integer of different width");
2271 return BitCast; // Same size, no-op cast
2273 assert(isa<PointerType>(SrcTy) &&
2274 "Casting from a value that is not first-class type");
2275 return PtrToInt; // ptr -> int
2277 } else if (DestTy->isFloatingPoint()) { // Casting to floating pt
2278 if (SrcTy->isInteger()) { // Casting from integral
2280 return SIToFP; // sint -> FP
2282 return UIToFP; // uint -> FP
2283 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt
2284 if (DestBits < SrcBits) {
2285 return FPTrunc; // FP -> smaller FP
2286 } else if (DestBits > SrcBits) {
2287 return FPExt; // FP -> larger FP
2289 return BitCast; // same size, no-op cast
2291 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
2292 assert(DestBits == PTy->getBitWidth() &&
2293 "Casting vector to floating point of different width");
2295 return BitCast; // same size, no-op cast
2297 LLVM_UNREACHABLE("Casting pointer or non-first class to float");
2299 } else if (const VectorType *DestPTy = dyn_cast<VectorType>(DestTy)) {
2300 if (const VectorType *SrcPTy = dyn_cast<VectorType>(SrcTy)) {
2301 assert(DestPTy->getBitWidth() == SrcPTy->getBitWidth() &&
2302 "Casting vector to vector of different widths");
2304 return BitCast; // vector -> vector
2305 } else if (DestPTy->getBitWidth() == SrcBits) {
2306 return BitCast; // float/int -> vector
2308 assert(!"Illegal cast to vector (wrong type or size)");
2310 } else if (isa<PointerType>(DestTy)) {
2311 if (isa<PointerType>(SrcTy)) {
2312 return BitCast; // ptr -> ptr
2313 } else if (SrcTy->isInteger()) {
2314 return IntToPtr; // int -> ptr
2316 assert(!"Casting pointer to other than pointer or int");
2319 assert(!"Casting to type that is not first-class");
2322 // If we fall through to here we probably hit an assertion cast above
2323 // and assertions are not turned on. Anything we return is an error, so
2324 // BitCast is as good a choice as any.
2328 //===----------------------------------------------------------------------===//
2329 // CastInst SubClass Constructors
2330 //===----------------------------------------------------------------------===//
2332 /// Check that the construction parameters for a CastInst are correct. This
2333 /// could be broken out into the separate constructors but it is useful to have
2334 /// it in one place and to eliminate the redundant code for getting the sizes
2335 /// of the types involved.
2337 CastInst::castIsValid(Instruction::CastOps op, Value *S, const Type *DstTy) {
2339 // Check for type sanity on the arguments
2340 const Type *SrcTy = S->getType();
2341 if (!SrcTy->isFirstClassType() || !DstTy->isFirstClassType())
2344 // Get the size of the types in bits, we'll need this later
2345 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
2346 unsigned DstBitSize = DstTy->getScalarSizeInBits();
2348 // Switch on the opcode provided
2350 default: return false; // This is an input error
2351 case Instruction::Trunc:
2352 return SrcTy->isIntOrIntVector() &&
2353 DstTy->isIntOrIntVector()&& SrcBitSize > DstBitSize;
2354 case Instruction::ZExt:
2355 return SrcTy->isIntOrIntVector() &&
2356 DstTy->isIntOrIntVector()&& SrcBitSize < DstBitSize;
2357 case Instruction::SExt:
2358 return SrcTy->isIntOrIntVector() &&
2359 DstTy->isIntOrIntVector()&& SrcBitSize < DstBitSize;
2360 case Instruction::FPTrunc:
2361 return SrcTy->isFPOrFPVector() &&
2362 DstTy->isFPOrFPVector() &&
2363 SrcBitSize > DstBitSize;
2364 case Instruction::FPExt:
2365 return SrcTy->isFPOrFPVector() &&
2366 DstTy->isFPOrFPVector() &&
2367 SrcBitSize < DstBitSize;
2368 case Instruction::UIToFP:
2369 case Instruction::SIToFP:
2370 if (const VectorType *SVTy = dyn_cast<VectorType>(SrcTy)) {
2371 if (const VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
2372 return SVTy->getElementType()->isIntOrIntVector() &&
2373 DVTy->getElementType()->isFPOrFPVector() &&
2374 SVTy->getNumElements() == DVTy->getNumElements();
2377 return SrcTy->isIntOrIntVector() && DstTy->isFPOrFPVector();
2378 case Instruction::FPToUI:
2379 case Instruction::FPToSI:
2380 if (const VectorType *SVTy = dyn_cast<VectorType>(SrcTy)) {
2381 if (const VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
2382 return SVTy->getElementType()->isFPOrFPVector() &&
2383 DVTy->getElementType()->isIntOrIntVector() &&
2384 SVTy->getNumElements() == DVTy->getNumElements();
2387 return SrcTy->isFPOrFPVector() && DstTy->isIntOrIntVector();
2388 case Instruction::PtrToInt:
2389 return isa<PointerType>(SrcTy) && DstTy->isInteger();
2390 case Instruction::IntToPtr:
2391 return SrcTy->isInteger() && isa<PointerType>(DstTy);
2392 case Instruction::BitCast:
2393 // BitCast implies a no-op cast of type only. No bits change.
2394 // However, you can't cast pointers to anything but pointers.
2395 if (isa<PointerType>(SrcTy) != isa<PointerType>(DstTy))
2398 // Now we know we're not dealing with a pointer/non-pointer mismatch. In all
2399 // these cases, the cast is okay if the source and destination bit widths
2401 return SrcTy->getPrimitiveSizeInBits() == DstTy->getPrimitiveSizeInBits();
2405 TruncInst::TruncInst(
2406 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2407 ) : CastInst(Ty, Trunc, S, Name, InsertBefore) {
2408 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
2411 TruncInst::TruncInst(
2412 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2413 ) : CastInst(Ty, Trunc, S, Name, InsertAtEnd) {
2414 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
2418 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2419 ) : CastInst(Ty, ZExt, S, Name, InsertBefore) {
2420 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
2424 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2425 ) : CastInst(Ty, ZExt, S, Name, InsertAtEnd) {
2426 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
2429 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2430 ) : CastInst(Ty, SExt, S, Name, InsertBefore) {
2431 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
2435 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2436 ) : CastInst(Ty, SExt, S, Name, InsertAtEnd) {
2437 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
2440 FPTruncInst::FPTruncInst(
2441 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2442 ) : CastInst(Ty, FPTrunc, S, Name, InsertBefore) {
2443 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
2446 FPTruncInst::FPTruncInst(
2447 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2448 ) : CastInst(Ty, FPTrunc, S, Name, InsertAtEnd) {
2449 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
2452 FPExtInst::FPExtInst(
2453 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2454 ) : CastInst(Ty, FPExt, S, Name, InsertBefore) {
2455 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
2458 FPExtInst::FPExtInst(
2459 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2460 ) : CastInst(Ty, FPExt, S, Name, InsertAtEnd) {
2461 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
2464 UIToFPInst::UIToFPInst(
2465 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2466 ) : CastInst(Ty, UIToFP, S, Name, InsertBefore) {
2467 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
2470 UIToFPInst::UIToFPInst(
2471 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2472 ) : CastInst(Ty, UIToFP, S, Name, InsertAtEnd) {
2473 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
2476 SIToFPInst::SIToFPInst(
2477 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2478 ) : CastInst(Ty, SIToFP, S, Name, InsertBefore) {
2479 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
2482 SIToFPInst::SIToFPInst(
2483 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2484 ) : CastInst(Ty, SIToFP, S, Name, InsertAtEnd) {
2485 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
2488 FPToUIInst::FPToUIInst(
2489 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2490 ) : CastInst(Ty, FPToUI, S, Name, InsertBefore) {
2491 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
2494 FPToUIInst::FPToUIInst(
2495 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2496 ) : CastInst(Ty, FPToUI, S, Name, InsertAtEnd) {
2497 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
2500 FPToSIInst::FPToSIInst(
2501 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2502 ) : CastInst(Ty, FPToSI, S, Name, InsertBefore) {
2503 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
2506 FPToSIInst::FPToSIInst(
2507 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2508 ) : CastInst(Ty, FPToSI, S, Name, InsertAtEnd) {
2509 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
2512 PtrToIntInst::PtrToIntInst(
2513 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2514 ) : CastInst(Ty, PtrToInt, S, Name, InsertBefore) {
2515 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
2518 PtrToIntInst::PtrToIntInst(
2519 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2520 ) : CastInst(Ty, PtrToInt, S, Name, InsertAtEnd) {
2521 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
2524 IntToPtrInst::IntToPtrInst(
2525 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2526 ) : CastInst(Ty, IntToPtr, S, Name, InsertBefore) {
2527 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
2530 IntToPtrInst::IntToPtrInst(
2531 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2532 ) : CastInst(Ty, IntToPtr, S, Name, InsertAtEnd) {
2533 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
2536 BitCastInst::BitCastInst(
2537 Value *S, const Type *Ty, const std::string &Name, Instruction *InsertBefore
2538 ) : CastInst(Ty, BitCast, S, Name, InsertBefore) {
2539 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
2542 BitCastInst::BitCastInst(
2543 Value *S, const Type *Ty, const std::string &Name, BasicBlock *InsertAtEnd
2544 ) : CastInst(Ty, BitCast, S, Name, InsertAtEnd) {
2545 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
2548 //===----------------------------------------------------------------------===//
2550 //===----------------------------------------------------------------------===//
2552 CmpInst::CmpInst(const Type *ty, OtherOps op, unsigned short predicate,
2553 Value *LHS, Value *RHS, const std::string &Name,
2554 Instruction *InsertBefore)
2555 : Instruction(ty, op,
2556 OperandTraits<CmpInst>::op_begin(this),
2557 OperandTraits<CmpInst>::operands(this),
2561 SubclassData = predicate;
2565 CmpInst::CmpInst(const Type *ty, OtherOps op, unsigned short predicate,
2566 Value *LHS, Value *RHS, const std::string &Name,
2567 BasicBlock *InsertAtEnd)
2568 : Instruction(ty, op,
2569 OperandTraits<CmpInst>::op_begin(this),
2570 OperandTraits<CmpInst>::operands(this),
2574 SubclassData = predicate;
2579 CmpInst::Create(LLVMContext &Context, OtherOps Op, unsigned short predicate,
2580 Value *S1, Value *S2,
2581 const std::string &Name, Instruction *InsertBefore) {
2582 if (Op == Instruction::ICmp) {
2584 return new ICmpInst(InsertBefore, CmpInst::Predicate(predicate),
2587 return new ICmpInst(Context, CmpInst::Predicate(predicate),
2592 return new FCmpInst(InsertBefore, CmpInst::Predicate(predicate),
2595 return new FCmpInst(Context, CmpInst::Predicate(predicate),
2600 CmpInst::Create(OtherOps Op, unsigned short predicate, Value *S1, Value *S2,
2601 const std::string &Name, BasicBlock *InsertAtEnd) {
2602 if (Op == Instruction::ICmp) {
2603 return new ICmpInst(*InsertAtEnd, CmpInst::Predicate(predicate),
2606 return new FCmpInst(*InsertAtEnd, CmpInst::Predicate(predicate),
2610 void CmpInst::swapOperands() {
2611 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2614 cast<FCmpInst>(this)->swapOperands();
2617 bool CmpInst::isCommutative() {
2618 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2619 return IC->isCommutative();
2620 return cast<FCmpInst>(this)->isCommutative();
2623 bool CmpInst::isEquality() {
2624 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2625 return IC->isEquality();
2626 return cast<FCmpInst>(this)->isEquality();
2630 CmpInst::Predicate CmpInst::getInversePredicate(Predicate pred) {
2632 default: assert(!"Unknown cmp predicate!");
2633 case ICMP_EQ: return ICMP_NE;
2634 case ICMP_NE: return ICMP_EQ;
2635 case ICMP_UGT: return ICMP_ULE;
2636 case ICMP_ULT: return ICMP_UGE;
2637 case ICMP_UGE: return ICMP_ULT;
2638 case ICMP_ULE: return ICMP_UGT;
2639 case ICMP_SGT: return ICMP_SLE;
2640 case ICMP_SLT: return ICMP_SGE;
2641 case ICMP_SGE: return ICMP_SLT;
2642 case ICMP_SLE: return ICMP_SGT;
2644 case FCMP_OEQ: return FCMP_UNE;
2645 case FCMP_ONE: return FCMP_UEQ;
2646 case FCMP_OGT: return FCMP_ULE;
2647 case FCMP_OLT: return FCMP_UGE;
2648 case FCMP_OGE: return FCMP_ULT;
2649 case FCMP_OLE: return FCMP_UGT;
2650 case FCMP_UEQ: return FCMP_ONE;
2651 case FCMP_UNE: return FCMP_OEQ;
2652 case FCMP_UGT: return FCMP_OLE;
2653 case FCMP_ULT: return FCMP_OGE;
2654 case FCMP_UGE: return FCMP_OLT;
2655 case FCMP_ULE: return FCMP_OGT;
2656 case FCMP_ORD: return FCMP_UNO;
2657 case FCMP_UNO: return FCMP_ORD;
2658 case FCMP_TRUE: return FCMP_FALSE;
2659 case FCMP_FALSE: return FCMP_TRUE;
2663 ICmpInst::Predicate ICmpInst::getSignedPredicate(Predicate pred) {
2665 default: assert(! "Unknown icmp predicate!");
2666 case ICMP_EQ: case ICMP_NE:
2667 case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE:
2669 case ICMP_UGT: return ICMP_SGT;
2670 case ICMP_ULT: return ICMP_SLT;
2671 case ICMP_UGE: return ICMP_SGE;
2672 case ICMP_ULE: return ICMP_SLE;
2676 ICmpInst::Predicate ICmpInst::getUnsignedPredicate(Predicate pred) {
2678 default: assert(! "Unknown icmp predicate!");
2679 case ICMP_EQ: case ICMP_NE:
2680 case ICMP_UGT: case ICMP_ULT: case ICMP_UGE: case ICMP_ULE:
2682 case ICMP_SGT: return ICMP_UGT;
2683 case ICMP_SLT: return ICMP_ULT;
2684 case ICMP_SGE: return ICMP_UGE;
2685 case ICMP_SLE: return ICMP_ULE;
2689 bool ICmpInst::isSignedPredicate(Predicate pred) {
2691 default: assert(! "Unknown icmp predicate!");
2692 case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE:
2694 case ICMP_EQ: case ICMP_NE: case ICMP_UGT: case ICMP_ULT:
2695 case ICMP_UGE: case ICMP_ULE:
2700 /// Initialize a set of values that all satisfy the condition with C.
2703 ICmpInst::makeConstantRange(Predicate pred, const APInt &C) {
2706 uint32_t BitWidth = C.getBitWidth();
2708 default: LLVM_UNREACHABLE("Invalid ICmp opcode to ConstantRange ctor!");
2709 case ICmpInst::ICMP_EQ: Upper++; break;
2710 case ICmpInst::ICMP_NE: Lower++; break;
2711 case ICmpInst::ICMP_ULT: Lower = APInt::getMinValue(BitWidth); break;
2712 case ICmpInst::ICMP_SLT: Lower = APInt::getSignedMinValue(BitWidth); break;
2713 case ICmpInst::ICMP_UGT:
2714 Lower++; Upper = APInt::getMinValue(BitWidth); // Min = Next(Max)
2716 case ICmpInst::ICMP_SGT:
2717 Lower++; Upper = APInt::getSignedMinValue(BitWidth); // Min = Next(Max)
2719 case ICmpInst::ICMP_ULE:
2720 Lower = APInt::getMinValue(BitWidth); Upper++;
2722 case ICmpInst::ICMP_SLE:
2723 Lower = APInt::getSignedMinValue(BitWidth); Upper++;
2725 case ICmpInst::ICMP_UGE:
2726 Upper = APInt::getMinValue(BitWidth); // Min = Next(Max)
2728 case ICmpInst::ICMP_SGE:
2729 Upper = APInt::getSignedMinValue(BitWidth); // Min = Next(Max)
2732 return ConstantRange(Lower, Upper);
2735 CmpInst::Predicate CmpInst::getSwappedPredicate(Predicate pred) {
2737 default: assert(!"Unknown cmp predicate!");
2738 case ICMP_EQ: case ICMP_NE:
2740 case ICMP_SGT: return ICMP_SLT;
2741 case ICMP_SLT: return ICMP_SGT;
2742 case ICMP_SGE: return ICMP_SLE;
2743 case ICMP_SLE: return ICMP_SGE;
2744 case ICMP_UGT: return ICMP_ULT;
2745 case ICMP_ULT: return ICMP_UGT;
2746 case ICMP_UGE: return ICMP_ULE;
2747 case ICMP_ULE: return ICMP_UGE;
2749 case FCMP_FALSE: case FCMP_TRUE:
2750 case FCMP_OEQ: case FCMP_ONE:
2751 case FCMP_UEQ: case FCMP_UNE:
2752 case FCMP_ORD: case FCMP_UNO:
2754 case FCMP_OGT: return FCMP_OLT;
2755 case FCMP_OLT: return FCMP_OGT;
2756 case FCMP_OGE: return FCMP_OLE;
2757 case FCMP_OLE: return FCMP_OGE;
2758 case FCMP_UGT: return FCMP_ULT;
2759 case FCMP_ULT: return FCMP_UGT;
2760 case FCMP_UGE: return FCMP_ULE;
2761 case FCMP_ULE: return FCMP_UGE;
2765 bool CmpInst::isUnsigned(unsigned short predicate) {
2766 switch (predicate) {
2767 default: return false;
2768 case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_ULE: case ICmpInst::ICMP_UGT:
2769 case ICmpInst::ICMP_UGE: return true;
2773 bool CmpInst::isSigned(unsigned short predicate){
2774 switch (predicate) {
2775 default: return false;
2776 case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_SLE: case ICmpInst::ICMP_SGT:
2777 case ICmpInst::ICMP_SGE: return true;
2781 bool CmpInst::isOrdered(unsigned short predicate) {
2782 switch (predicate) {
2783 default: return false;
2784 case FCmpInst::FCMP_OEQ: case FCmpInst::FCMP_ONE: case FCmpInst::FCMP_OGT:
2785 case FCmpInst::FCMP_OLT: case FCmpInst::FCMP_OGE: case FCmpInst::FCMP_OLE:
2786 case FCmpInst::FCMP_ORD: return true;
2790 bool CmpInst::isUnordered(unsigned short predicate) {
2791 switch (predicate) {
2792 default: return false;
2793 case FCmpInst::FCMP_UEQ: case FCmpInst::FCMP_UNE: case FCmpInst::FCMP_UGT:
2794 case FCmpInst::FCMP_ULT: case FCmpInst::FCMP_UGE: case FCmpInst::FCMP_ULE:
2795 case FCmpInst::FCMP_UNO: return true;
2799 //===----------------------------------------------------------------------===//
2800 // SwitchInst Implementation
2801 //===----------------------------------------------------------------------===//
2803 void SwitchInst::init(Value *Value, BasicBlock *Default, unsigned NumCases) {
2804 assert(Value && Default);
2805 ReservedSpace = 2+NumCases*2;
2807 OperandList = allocHungoffUses(ReservedSpace);
2809 OperandList[0] = Value;
2810 OperandList[1] = Default;
2813 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
2814 /// switch on and a default destination. The number of additional cases can
2815 /// be specified here to make memory allocation more efficient. This
2816 /// constructor can also autoinsert before another instruction.
2817 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
2818 Instruction *InsertBefore)
2819 : TerminatorInst(Type::VoidTy, Instruction::Switch, 0, 0, InsertBefore) {
2820 init(Value, Default, NumCases);
2823 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
2824 /// switch on and a default destination. The number of additional cases can
2825 /// be specified here to make memory allocation more efficient. This
2826 /// constructor also autoinserts at the end of the specified BasicBlock.
2827 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
2828 BasicBlock *InsertAtEnd)
2829 : TerminatorInst(Type::VoidTy, Instruction::Switch, 0, 0, InsertAtEnd) {
2830 init(Value, Default, NumCases);
2833 SwitchInst::SwitchInst(const SwitchInst &SI)
2834 : TerminatorInst(Type::VoidTy, Instruction::Switch,
2835 allocHungoffUses(SI.getNumOperands()), SI.getNumOperands()) {
2836 Use *OL = OperandList, *InOL = SI.OperandList;
2837 for (unsigned i = 0, E = SI.getNumOperands(); i != E; i+=2) {
2839 OL[i+1] = InOL[i+1];
2843 SwitchInst::~SwitchInst() {
2844 dropHungoffUses(OperandList);
2848 /// addCase - Add an entry to the switch instruction...
2850 void SwitchInst::addCase(ConstantInt *OnVal, BasicBlock *Dest) {
2851 unsigned OpNo = NumOperands;
2852 if (OpNo+2 > ReservedSpace)
2853 resizeOperands(0); // Get more space!
2854 // Initialize some new operands.
2855 assert(OpNo+1 < ReservedSpace && "Growing didn't work!");
2856 NumOperands = OpNo+2;
2857 OperandList[OpNo] = OnVal;
2858 OperandList[OpNo+1] = Dest;
2861 /// removeCase - This method removes the specified successor from the switch
2862 /// instruction. Note that this cannot be used to remove the default
2863 /// destination (successor #0).
2865 void SwitchInst::removeCase(unsigned idx) {
2866 assert(idx != 0 && "Cannot remove the default case!");
2867 assert(idx*2 < getNumOperands() && "Successor index out of range!!!");
2869 unsigned NumOps = getNumOperands();
2870 Use *OL = OperandList;
2872 // Move everything after this operand down.
2874 // FIXME: we could just swap with the end of the list, then erase. However,
2875 // client might not expect this to happen. The code as it is thrashes the
2876 // use/def lists, which is kinda lame.
2877 for (unsigned i = (idx+1)*2; i != NumOps; i += 2) {
2879 OL[i-2+1] = OL[i+1];
2882 // Nuke the last value.
2883 OL[NumOps-2].set(0);
2884 OL[NumOps-2+1].set(0);
2885 NumOperands = NumOps-2;
2888 /// resizeOperands - resize operands - This adjusts the length of the operands
2889 /// list according to the following behavior:
2890 /// 1. If NumOps == 0, grow the operand list in response to a push_back style
2891 /// of operation. This grows the number of ops by 3 times.
2892 /// 2. If NumOps > NumOperands, reserve space for NumOps operands.
2893 /// 3. If NumOps == NumOperands, trim the reserved space.
2895 void SwitchInst::resizeOperands(unsigned NumOps) {
2896 unsigned e = getNumOperands();
2899 } else if (NumOps*2 > NumOperands) {
2900 // No resize needed.
2901 if (ReservedSpace >= NumOps) return;
2902 } else if (NumOps == NumOperands) {
2903 if (ReservedSpace == NumOps) return;
2908 ReservedSpace = NumOps;
2909 Use *NewOps = allocHungoffUses(NumOps);
2910 Use *OldOps = OperandList;
2911 for (unsigned i = 0; i != e; ++i) {
2912 NewOps[i] = OldOps[i];
2914 OperandList = NewOps;
2915 if (OldOps) Use::zap(OldOps, OldOps + e, true);
2919 BasicBlock *SwitchInst::getSuccessorV(unsigned idx) const {
2920 return getSuccessor(idx);
2922 unsigned SwitchInst::getNumSuccessorsV() const {
2923 return getNumSuccessors();
2925 void SwitchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
2926 setSuccessor(idx, B);
2929 // Define these methods here so vtables don't get emitted into every translation
2930 // unit that uses these classes.
2932 GetElementPtrInst *GetElementPtrInst::clone(LLVMContext&) const {
2933 return new(getNumOperands()) GetElementPtrInst(*this);
2936 BinaryOperator *BinaryOperator::clone(LLVMContext&) const {
2937 return Create(getOpcode(), Op<0>(), Op<1>());
2940 FCmpInst* FCmpInst::clone(LLVMContext &Context) const {
2941 return new FCmpInst(Context, getPredicate(), Op<0>(), Op<1>());
2943 ICmpInst* ICmpInst::clone(LLVMContext &Context) const {
2944 return new ICmpInst(Context, getPredicate(), Op<0>(), Op<1>());
2947 ExtractValueInst *ExtractValueInst::clone(LLVMContext&) const {
2948 return new ExtractValueInst(*this);
2950 InsertValueInst *InsertValueInst::clone(LLVMContext&) const {
2951 return new InsertValueInst(*this);
2954 MallocInst *MallocInst::clone(LLVMContext&) const {
2955 return new MallocInst(*this);
2958 AllocaInst *AllocaInst::clone(LLVMContext&) const {
2959 return new AllocaInst(*this);
2962 FreeInst *FreeInst::clone(LLVMContext&) const {
2963 return new FreeInst(getOperand(0));
2966 LoadInst *LoadInst::clone(LLVMContext&) const {
2967 return new LoadInst(*this);
2970 StoreInst *StoreInst::clone(LLVMContext&) const {
2971 return new StoreInst(*this);
2974 CastInst *TruncInst::clone(LLVMContext&) const {
2975 return new TruncInst(*this);
2978 CastInst *ZExtInst::clone(LLVMContext&) const {
2979 return new ZExtInst(*this);
2982 CastInst *SExtInst::clone(LLVMContext&) const {
2983 return new SExtInst(*this);
2986 CastInst *FPTruncInst::clone(LLVMContext&) const {
2987 return new FPTruncInst(*this);
2990 CastInst *FPExtInst::clone(LLVMContext&) const {
2991 return new FPExtInst(*this);
2994 CastInst *UIToFPInst::clone(LLVMContext&) const {
2995 return new UIToFPInst(*this);
2998 CastInst *SIToFPInst::clone(LLVMContext&) const {
2999 return new SIToFPInst(*this);
3002 CastInst *FPToUIInst::clone(LLVMContext&) const {
3003 return new FPToUIInst(*this);
3006 CastInst *FPToSIInst::clone(LLVMContext&) const {
3007 return new FPToSIInst(*this);
3010 CastInst *PtrToIntInst::clone(LLVMContext&) const {
3011 return new PtrToIntInst(*this);
3014 CastInst *IntToPtrInst::clone(LLVMContext&) const {
3015 return new IntToPtrInst(*this);
3018 CastInst *BitCastInst::clone(LLVMContext&) const {
3019 return new BitCastInst(*this);
3022 CallInst *CallInst::clone(LLVMContext&) const {
3023 return new(getNumOperands()) CallInst(*this);
3026 SelectInst *SelectInst::clone(LLVMContext&) const {
3027 return new(getNumOperands()) SelectInst(*this);
3030 VAArgInst *VAArgInst::clone(LLVMContext&) const {
3031 return new VAArgInst(*this);
3034 ExtractElementInst *ExtractElementInst::clone(LLVMContext&) const {
3035 return new ExtractElementInst(*this);
3038 InsertElementInst *InsertElementInst::clone(LLVMContext&) const {
3039 return InsertElementInst::Create(*this);
3042 ShuffleVectorInst *ShuffleVectorInst::clone(LLVMContext&) const {
3043 return new ShuffleVectorInst(*this);
3046 PHINode *PHINode::clone(LLVMContext&) const {
3047 return new PHINode(*this);
3050 ReturnInst *ReturnInst::clone(LLVMContext&) const {
3051 return new(getNumOperands()) ReturnInst(*this);
3054 BranchInst *BranchInst::clone(LLVMContext&) const {
3055 unsigned Ops(getNumOperands());
3056 return new(Ops, Ops == 1) BranchInst(*this);
3059 SwitchInst *SwitchInst::clone(LLVMContext&) const {
3060 return new SwitchInst(*this);
3063 InvokeInst *InvokeInst::clone(LLVMContext&) const {
3064 return new(getNumOperands()) InvokeInst(*this);
3067 UnwindInst *UnwindInst::clone(LLVMContext&) const {
3068 return new UnwindInst();
3071 UnreachableInst *UnreachableInst::clone(LLVMContext&) const {
3072 return new UnreachableInst();