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/Module.h"
20 #include "llvm/Operator.h"
21 #include "llvm/Analysis/Dominators.h"
22 #include "llvm/Support/ErrorHandling.h"
23 #include "llvm/Support/CallSite.h"
24 #include "llvm/Support/ConstantRange.h"
25 #include "llvm/Support/MathExtras.h"
28 //===----------------------------------------------------------------------===//
30 //===----------------------------------------------------------------------===//
32 #define CALLSITE_DELEGATE_GETTER(METHOD) \
33 Instruction *II(getInstruction()); \
35 ? cast<CallInst>(II)->METHOD \
36 : cast<InvokeInst>(II)->METHOD
38 #define CALLSITE_DELEGATE_SETTER(METHOD) \
39 Instruction *II(getInstruction()); \
41 cast<CallInst>(II)->METHOD; \
43 cast<InvokeInst>(II)->METHOD
45 CallSite::CallSite(Instruction *C) {
46 assert((isa<CallInst>(C) || isa<InvokeInst>(C)) && "Not a call!");
48 I.setInt(isa<CallInst>(C));
50 CallingConv::ID CallSite::getCallingConv() const {
51 CALLSITE_DELEGATE_GETTER(getCallingConv());
53 void CallSite::setCallingConv(CallingConv::ID CC) {
54 CALLSITE_DELEGATE_SETTER(setCallingConv(CC));
56 const AttrListPtr &CallSite::getAttributes() const {
57 CALLSITE_DELEGATE_GETTER(getAttributes());
59 void CallSite::setAttributes(const AttrListPtr &PAL) {
60 CALLSITE_DELEGATE_SETTER(setAttributes(PAL));
62 bool CallSite::paramHasAttr(uint16_t i, Attributes attr) const {
63 CALLSITE_DELEGATE_GETTER(paramHasAttr(i, attr));
65 uint16_t CallSite::getParamAlignment(uint16_t i) const {
66 CALLSITE_DELEGATE_GETTER(getParamAlignment(i));
68 bool CallSite::doesNotAccessMemory() const {
69 CALLSITE_DELEGATE_GETTER(doesNotAccessMemory());
71 void CallSite::setDoesNotAccessMemory(bool doesNotAccessMemory) {
72 CALLSITE_DELEGATE_SETTER(setDoesNotAccessMemory(doesNotAccessMemory));
74 bool CallSite::onlyReadsMemory() const {
75 CALLSITE_DELEGATE_GETTER(onlyReadsMemory());
77 void CallSite::setOnlyReadsMemory(bool onlyReadsMemory) {
78 CALLSITE_DELEGATE_SETTER(setOnlyReadsMemory(onlyReadsMemory));
80 bool CallSite::doesNotReturn() const {
81 CALLSITE_DELEGATE_GETTER(doesNotReturn());
83 void CallSite::setDoesNotReturn(bool doesNotReturn) {
84 CALLSITE_DELEGATE_SETTER(setDoesNotReturn(doesNotReturn));
86 bool CallSite::doesNotThrow() const {
87 CALLSITE_DELEGATE_GETTER(doesNotThrow());
89 void CallSite::setDoesNotThrow(bool doesNotThrow) {
90 CALLSITE_DELEGATE_SETTER(setDoesNotThrow(doesNotThrow));
93 bool CallSite::hasArgument(const Value *Arg) const {
94 for (arg_iterator AI = this->arg_begin(), E = this->arg_end(); AI != E; ++AI)
100 #undef CALLSITE_DELEGATE_GETTER
101 #undef CALLSITE_DELEGATE_SETTER
103 //===----------------------------------------------------------------------===//
104 // TerminatorInst Class
105 //===----------------------------------------------------------------------===//
107 // Out of line virtual method, so the vtable, etc has a home.
108 TerminatorInst::~TerminatorInst() {
111 //===----------------------------------------------------------------------===//
112 // UnaryInstruction Class
113 //===----------------------------------------------------------------------===//
115 // Out of line virtual method, so the vtable, etc has a home.
116 UnaryInstruction::~UnaryInstruction() {
119 //===----------------------------------------------------------------------===//
121 //===----------------------------------------------------------------------===//
123 /// areInvalidOperands - Return a string if the specified operands are invalid
124 /// for a select operation, otherwise return null.
125 const char *SelectInst::areInvalidOperands(Value *Op0, Value *Op1, Value *Op2) {
126 if (Op1->getType() != Op2->getType())
127 return "both values to select must have same type";
129 if (const VectorType *VT = dyn_cast<VectorType>(Op0->getType())) {
131 if (VT->getElementType() != Type::getInt1Ty(Op0->getContext()))
132 return "vector select condition element type must be i1";
133 const VectorType *ET = dyn_cast<VectorType>(Op1->getType());
135 return "selected values for vector select must be vectors";
136 if (ET->getNumElements() != VT->getNumElements())
137 return "vector select requires selected vectors to have "
138 "the same vector length as select condition";
139 } else if (Op0->getType() != Type::getInt1Ty(Op0->getContext())) {
140 return "select condition must be i1 or <n x i1>";
146 //===----------------------------------------------------------------------===//
148 //===----------------------------------------------------------------------===//
150 PHINode::PHINode(const PHINode &PN)
151 : Instruction(PN.getType(), Instruction::PHI,
152 allocHungoffUses(PN.getNumOperands()), PN.getNumOperands()),
153 ReservedSpace(PN.getNumOperands()) {
154 Use *OL = OperandList;
155 for (unsigned i = 0, e = PN.getNumOperands(); i != e; i+=2) {
156 OL[i] = PN.getOperand(i);
157 OL[i+1] = PN.getOperand(i+1);
159 SubclassOptionalData = PN.SubclassOptionalData;
162 PHINode::~PHINode() {
164 dropHungoffUses(OperandList);
167 // removeIncomingValue - Remove an incoming value. This is useful if a
168 // predecessor basic block is deleted.
169 Value *PHINode::removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty) {
170 unsigned NumOps = getNumOperands();
171 Use *OL = OperandList;
172 assert(Idx*2 < NumOps && "BB not in PHI node!");
173 Value *Removed = OL[Idx*2];
175 // Move everything after this operand down.
177 // FIXME: we could just swap with the end of the list, then erase. However,
178 // client might not expect this to happen. The code as it is thrashes the
179 // use/def lists, which is kinda lame.
180 for (unsigned i = (Idx+1)*2; i != NumOps; i += 2) {
185 // Nuke the last value.
187 OL[NumOps-2+1].set(0);
188 NumOperands = NumOps-2;
190 // If the PHI node is dead, because it has zero entries, nuke it now.
191 if (NumOps == 2 && DeletePHIIfEmpty) {
192 // If anyone is using this PHI, make them use a dummy value instead...
193 replaceAllUsesWith(UndefValue::get(getType()));
199 /// resizeOperands - resize operands - This adjusts the length of the operands
200 /// list according to the following behavior:
201 /// 1. If NumOps == 0, grow the operand list in response to a push_back style
202 /// of operation. This grows the number of ops by 1.5 times.
203 /// 2. If NumOps > NumOperands, reserve space for NumOps operands.
204 /// 3. If NumOps == NumOperands, trim the reserved space.
206 void PHINode::resizeOperands(unsigned NumOps) {
207 unsigned e = getNumOperands();
210 if (NumOps < 4) NumOps = 4; // 4 op PHI nodes are VERY common.
211 } else if (NumOps*2 > NumOperands) {
213 if (ReservedSpace >= NumOps) return;
214 } else if (NumOps == NumOperands) {
215 if (ReservedSpace == NumOps) return;
220 ReservedSpace = NumOps;
221 Use *OldOps = OperandList;
222 Use *NewOps = allocHungoffUses(NumOps);
223 std::copy(OldOps, OldOps + e, NewOps);
224 OperandList = NewOps;
225 if (OldOps) Use::zap(OldOps, OldOps + e, true);
228 /// hasConstantValue - If the specified PHI node always merges together the same
229 /// value, return the value, otherwise return null.
231 /// If the PHI has undef operands, but all the rest of the operands are
232 /// some unique value, return that value if it can be proved that the
233 /// value dominates the PHI. If DT is null, use a conservative check,
234 /// otherwise use DT to test for dominance.
236 Value *PHINode::hasConstantValue(DominatorTree *DT) const {
237 // If the PHI node only has one incoming value, eliminate the PHI node...
238 if (getNumIncomingValues() == 1) {
239 if (getIncomingValue(0) != this) // not X = phi X
240 return getIncomingValue(0);
242 return UndefValue::get(getType()); // Self cycle is dead.
245 // Otherwise if all of the incoming values are the same for the PHI, replace
246 // the PHI node with the incoming value.
249 bool HasUndefInput = false;
250 for (unsigned i = 0, e = getNumIncomingValues(); i != e; ++i)
251 if (isa<UndefValue>(getIncomingValue(i))) {
252 HasUndefInput = true;
253 } else if (getIncomingValue(i) != this) { // Not the PHI node itself...
254 if (InVal && getIncomingValue(i) != InVal)
255 return 0; // Not the same, bail out.
257 InVal = getIncomingValue(i);
260 // The only case that could cause InVal to be null is if we have a PHI node
261 // that only has entries for itself. In this case, there is no entry into the
262 // loop, so kill the PHI.
264 if (InVal == 0) InVal = UndefValue::get(getType());
266 // If we have a PHI node like phi(X, undef, X), where X is defined by some
267 // instruction, we cannot always return X as the result of the PHI node. Only
268 // do this if X is not an instruction (thus it must dominate the PHI block),
269 // or if the client is prepared to deal with this possibility.
271 if (Instruction *IV = dyn_cast<Instruction>(InVal)) {
273 // We have a DominatorTree. Do a precise test.
274 if (!DT->dominates(IV, this))
277 // If it's in the entry block, it dominates everything.
278 if (IV->getParent() != &IV->getParent()->getParent()->getEntryBlock() ||
280 return 0; // Cannot guarantee that InVal dominates this PHINode.
284 // All of the incoming values are the same, return the value now.
289 //===----------------------------------------------------------------------===//
290 // CallInst Implementation
291 //===----------------------------------------------------------------------===//
293 CallInst::~CallInst() {
296 void CallInst::init(Value *Func, Value* const *Params, unsigned NumParams) {
297 assert(NumOperands == NumParams+1 && "NumOperands not set up?");
298 Use *OL = OperandList;
301 const FunctionType *FTy =
302 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
303 FTy = FTy; // silence warning.
305 assert((NumParams == FTy->getNumParams() ||
306 (FTy->isVarArg() && NumParams > FTy->getNumParams())) &&
307 "Calling a function with bad signature!");
308 for (unsigned i = 0; i != NumParams; ++i) {
309 assert((i >= FTy->getNumParams() ||
310 FTy->getParamType(i) == Params[i]->getType()) &&
311 "Calling a function with a bad signature!");
316 void CallInst::init(Value *Func, Value *Actual1, Value *Actual2) {
317 assert(NumOperands == 3 && "NumOperands not set up?");
318 Use *OL = OperandList;
323 const FunctionType *FTy =
324 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
325 FTy = FTy; // silence warning.
327 assert((FTy->getNumParams() == 2 ||
328 (FTy->isVarArg() && FTy->getNumParams() < 2)) &&
329 "Calling a function with bad signature");
330 assert((0 >= FTy->getNumParams() ||
331 FTy->getParamType(0) == Actual1->getType()) &&
332 "Calling a function with a bad signature!");
333 assert((1 >= FTy->getNumParams() ||
334 FTy->getParamType(1) == Actual2->getType()) &&
335 "Calling a function with a bad signature!");
338 void CallInst::init(Value *Func, Value *Actual) {
339 assert(NumOperands == 2 && "NumOperands not set up?");
340 Use *OL = OperandList;
344 const FunctionType *FTy =
345 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
346 FTy = FTy; // silence warning.
348 assert((FTy->getNumParams() == 1 ||
349 (FTy->isVarArg() && FTy->getNumParams() == 0)) &&
350 "Calling a function with bad signature");
351 assert((0 == FTy->getNumParams() ||
352 FTy->getParamType(0) == Actual->getType()) &&
353 "Calling a function with a bad signature!");
356 void CallInst::init(Value *Func) {
357 assert(NumOperands == 1 && "NumOperands not set up?");
358 Use *OL = OperandList;
361 const FunctionType *FTy =
362 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
363 FTy = FTy; // silence warning.
365 assert(FTy->getNumParams() == 0 && "Calling a function with bad signature");
368 CallInst::CallInst(Value *Func, Value* Actual, const Twine &Name,
369 Instruction *InsertBefore)
370 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
371 ->getElementType())->getReturnType(),
373 OperandTraits<CallInst>::op_end(this) - 2,
379 CallInst::CallInst(Value *Func, Value* Actual, const Twine &Name,
380 BasicBlock *InsertAtEnd)
381 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
382 ->getElementType())->getReturnType(),
384 OperandTraits<CallInst>::op_end(this) - 2,
389 CallInst::CallInst(Value *Func, const Twine &Name,
390 Instruction *InsertBefore)
391 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
392 ->getElementType())->getReturnType(),
394 OperandTraits<CallInst>::op_end(this) - 1,
400 CallInst::CallInst(Value *Func, const Twine &Name,
401 BasicBlock *InsertAtEnd)
402 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
403 ->getElementType())->getReturnType(),
405 OperandTraits<CallInst>::op_end(this) - 1,
411 CallInst::CallInst(const CallInst &CI)
412 : Instruction(CI.getType(), Instruction::Call,
413 OperandTraits<CallInst>::op_end(this) - CI.getNumOperands(),
414 CI.getNumOperands()) {
415 setAttributes(CI.getAttributes());
416 SubclassData = CI.SubclassData;
417 Use *OL = OperandList;
418 Use *InOL = CI.OperandList;
419 for (unsigned i = 0, e = CI.getNumOperands(); i != e; ++i)
421 SubclassOptionalData = CI.SubclassOptionalData;
424 void CallInst::addAttribute(unsigned i, Attributes attr) {
425 AttrListPtr PAL = getAttributes();
426 PAL = PAL.addAttr(i, attr);
430 void CallInst::removeAttribute(unsigned i, Attributes attr) {
431 AttrListPtr PAL = getAttributes();
432 PAL = PAL.removeAttr(i, attr);
436 bool CallInst::paramHasAttr(unsigned i, Attributes attr) const {
437 if (AttributeList.paramHasAttr(i, attr))
439 if (const Function *F = getCalledFunction())
440 return F->paramHasAttr(i, attr);
444 /// IsConstantOne - Return true only if val is constant int 1
445 static bool IsConstantOne(Value *val) {
446 assert(val && "IsConstantOne does not work with NULL val");
447 return isa<ConstantInt>(val) && cast<ConstantInt>(val)->isOne();
450 static Value *checkArraySize(Value *Amt, const Type *IntPtrTy) {
452 Amt = ConstantInt::get(IntPtrTy, 1);
454 assert(!isa<BasicBlock>(Amt) &&
455 "Passed basic block into malloc size parameter! Use other ctor");
456 assert(Amt->getType() == IntPtrTy &&
457 "Malloc array size is not an intptr!");
462 static Value *createMalloc(Instruction *InsertBefore, BasicBlock *InsertAtEnd,
463 const Type *IntPtrTy, const Type *AllocTy,
464 Value *ArraySize, const Twine &NameStr) {
465 assert(((!InsertBefore && InsertAtEnd) || (InsertBefore && !InsertAtEnd)) &&
466 "createMalloc needs either InsertBefore or InsertAtEnd");
468 // malloc(type) becomes:
469 // bitcast (i8* malloc(typeSize)) to type*
470 // malloc(type, arraySize) becomes:
471 // bitcast (i8 *malloc(typeSize*arraySize)) to type*
472 Value *AllocSize = ConstantExpr::getSizeOf(AllocTy);
473 AllocSize = ConstantExpr::getTruncOrBitCast(cast<Constant>(AllocSize),
475 ArraySize = checkArraySize(ArraySize, IntPtrTy);
477 if (!IsConstantOne(ArraySize)) {
478 if (IsConstantOne(AllocSize)) {
479 AllocSize = ArraySize; // Operand * 1 = Operand
480 } else if (Constant *CO = dyn_cast<Constant>(ArraySize)) {
481 Constant *Scale = ConstantExpr::getIntegerCast(CO, IntPtrTy,
483 // Malloc arg is constant product of type size and array size
484 AllocSize = ConstantExpr::getMul(Scale, cast<Constant>(AllocSize));
486 // Multiply type size by the array size...
488 AllocSize = BinaryOperator::CreateMul(ArraySize, AllocSize,
489 "mallocsize", InsertBefore);
491 AllocSize = BinaryOperator::CreateMul(ArraySize, AllocSize,
492 "mallocsize", InsertAtEnd);
496 assert(AllocSize->getType() == IntPtrTy && "malloc arg is wrong size");
497 // Create the call to Malloc.
498 BasicBlock* BB = InsertBefore ? InsertBefore->getParent() : InsertAtEnd;
499 Module* M = BB->getParent()->getParent();
500 const Type *BPTy = PointerType::getUnqual(Type::getInt8Ty(BB->getContext()));
501 // prototype malloc as "void *malloc(size_t)"
502 Constant *MallocF = M->getOrInsertFunction("malloc", BPTy, IntPtrTy, NULL);
503 if (!cast<Function>(MallocF)->doesNotAlias(0))
504 cast<Function>(MallocF)->setDoesNotAlias(0);
505 const PointerType *AllocPtrType = PointerType::getUnqual(AllocTy);
506 CallInst *MCall = NULL;
509 MCall = CallInst::Create(MallocF, AllocSize, "malloccall", InsertBefore);
510 // Create a cast instruction to convert to the right type...
511 MCast = new BitCastInst(MCall, AllocPtrType, NameStr, InsertBefore);
513 MCall = CallInst::Create(MallocF, AllocSize, "malloccall", InsertAtEnd);
514 // Create a cast instruction to convert to the right type...
515 MCast = new BitCastInst(MCall, AllocPtrType, NameStr);
517 MCall->setTailCall();
518 assert(MCall->getType() != Type::getVoidTy(BB->getContext()) &&
519 "Malloc has void return type");
524 /// CreateMalloc - Generate the IR for a call to malloc:
525 /// 1. Compute the malloc call's argument as the specified type's size,
526 /// possibly multiplied by the array size if the array size is not
528 /// 2. Call malloc with that argument.
529 /// 3. Bitcast the result of the malloc call to the specified type.
530 Value *CallInst::CreateMalloc(Instruction *InsertBefore, const Type *IntPtrTy,
531 const Type *AllocTy, Value *ArraySize,
533 return createMalloc(InsertBefore, NULL, IntPtrTy, AllocTy, ArraySize, Name);
536 /// CreateMalloc - Generate the IR for a call to malloc:
537 /// 1. Compute the malloc call's argument as the specified type's size,
538 /// possibly multiplied by the array size if the array size is not
540 /// 2. Call malloc with that argument.
541 /// 3. Bitcast the result of the malloc call to the specified type.
542 /// Note: This function does not add the bitcast to the basic block, that is the
543 /// responsibility of the caller.
544 Value *CallInst::CreateMalloc(BasicBlock *InsertAtEnd, const Type *IntPtrTy,
545 const Type *AllocTy, Value *ArraySize,
547 return createMalloc(NULL, InsertAtEnd, IntPtrTy, AllocTy, ArraySize, Name);
550 //===----------------------------------------------------------------------===//
551 // InvokeInst Implementation
552 //===----------------------------------------------------------------------===//
554 void InvokeInst::init(Value *Fn, BasicBlock *IfNormal, BasicBlock *IfException,
555 Value* const *Args, unsigned NumArgs) {
556 assert(NumOperands == 3+NumArgs && "NumOperands not set up?");
557 Use *OL = OperandList;
561 const FunctionType *FTy =
562 cast<FunctionType>(cast<PointerType>(Fn->getType())->getElementType());
563 FTy = FTy; // silence warning.
565 assert(((NumArgs == FTy->getNumParams()) ||
566 (FTy->isVarArg() && NumArgs > FTy->getNumParams())) &&
567 "Calling a function with bad signature");
569 for (unsigned i = 0, e = NumArgs; i != e; i++) {
570 assert((i >= FTy->getNumParams() ||
571 FTy->getParamType(i) == Args[i]->getType()) &&
572 "Invoking a function with a bad signature!");
578 InvokeInst::InvokeInst(const InvokeInst &II)
579 : TerminatorInst(II.getType(), Instruction::Invoke,
580 OperandTraits<InvokeInst>::op_end(this)
581 - II.getNumOperands(),
582 II.getNumOperands()) {
583 setAttributes(II.getAttributes());
584 SubclassData = II.SubclassData;
585 Use *OL = OperandList, *InOL = II.OperandList;
586 for (unsigned i = 0, e = II.getNumOperands(); i != e; ++i)
588 SubclassOptionalData = II.SubclassOptionalData;
591 BasicBlock *InvokeInst::getSuccessorV(unsigned idx) const {
592 return getSuccessor(idx);
594 unsigned InvokeInst::getNumSuccessorsV() const {
595 return getNumSuccessors();
597 void InvokeInst::setSuccessorV(unsigned idx, BasicBlock *B) {
598 return setSuccessor(idx, B);
601 bool InvokeInst::paramHasAttr(unsigned i, Attributes attr) const {
602 if (AttributeList.paramHasAttr(i, attr))
604 if (const Function *F = getCalledFunction())
605 return F->paramHasAttr(i, attr);
609 void InvokeInst::addAttribute(unsigned i, Attributes attr) {
610 AttrListPtr PAL = getAttributes();
611 PAL = PAL.addAttr(i, attr);
615 void InvokeInst::removeAttribute(unsigned i, Attributes attr) {
616 AttrListPtr PAL = getAttributes();
617 PAL = PAL.removeAttr(i, attr);
622 //===----------------------------------------------------------------------===//
623 // ReturnInst Implementation
624 //===----------------------------------------------------------------------===//
626 ReturnInst::ReturnInst(const ReturnInst &RI)
627 : TerminatorInst(Type::getVoidTy(RI.getContext()), Instruction::Ret,
628 OperandTraits<ReturnInst>::op_end(this) -
630 RI.getNumOperands()) {
631 if (RI.getNumOperands())
632 Op<0>() = RI.Op<0>();
633 SubclassOptionalData = RI.SubclassOptionalData;
636 ReturnInst::ReturnInst(LLVMContext &C, Value *retVal, Instruction *InsertBefore)
637 : TerminatorInst(Type::getVoidTy(C), Instruction::Ret,
638 OperandTraits<ReturnInst>::op_end(this) - !!retVal, !!retVal,
643 ReturnInst::ReturnInst(LLVMContext &C, Value *retVal, BasicBlock *InsertAtEnd)
644 : TerminatorInst(Type::getVoidTy(C), Instruction::Ret,
645 OperandTraits<ReturnInst>::op_end(this) - !!retVal, !!retVal,
650 ReturnInst::ReturnInst(LLVMContext &Context, BasicBlock *InsertAtEnd)
651 : TerminatorInst(Type::getVoidTy(Context), Instruction::Ret,
652 OperandTraits<ReturnInst>::op_end(this), 0, InsertAtEnd) {
655 unsigned ReturnInst::getNumSuccessorsV() const {
656 return getNumSuccessors();
659 /// Out-of-line ReturnInst method, put here so the C++ compiler can choose to
660 /// emit the vtable for the class in this translation unit.
661 void ReturnInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
662 llvm_unreachable("ReturnInst has no successors!");
665 BasicBlock *ReturnInst::getSuccessorV(unsigned idx) const {
666 llvm_unreachable("ReturnInst has no successors!");
670 ReturnInst::~ReturnInst() {
673 //===----------------------------------------------------------------------===//
674 // UnwindInst Implementation
675 //===----------------------------------------------------------------------===//
677 UnwindInst::UnwindInst(LLVMContext &Context, Instruction *InsertBefore)
678 : TerminatorInst(Type::getVoidTy(Context), Instruction::Unwind,
679 0, 0, InsertBefore) {
681 UnwindInst::UnwindInst(LLVMContext &Context, BasicBlock *InsertAtEnd)
682 : TerminatorInst(Type::getVoidTy(Context), Instruction::Unwind,
687 unsigned UnwindInst::getNumSuccessorsV() const {
688 return getNumSuccessors();
691 void UnwindInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
692 llvm_unreachable("UnwindInst has no successors!");
695 BasicBlock *UnwindInst::getSuccessorV(unsigned idx) const {
696 llvm_unreachable("UnwindInst has no successors!");
700 //===----------------------------------------------------------------------===//
701 // UnreachableInst Implementation
702 //===----------------------------------------------------------------------===//
704 UnreachableInst::UnreachableInst(LLVMContext &Context,
705 Instruction *InsertBefore)
706 : TerminatorInst(Type::getVoidTy(Context), Instruction::Unreachable,
707 0, 0, InsertBefore) {
709 UnreachableInst::UnreachableInst(LLVMContext &Context, BasicBlock *InsertAtEnd)
710 : TerminatorInst(Type::getVoidTy(Context), Instruction::Unreachable,
714 unsigned UnreachableInst::getNumSuccessorsV() const {
715 return getNumSuccessors();
718 void UnreachableInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
719 llvm_unreachable("UnwindInst has no successors!");
722 BasicBlock *UnreachableInst::getSuccessorV(unsigned idx) const {
723 llvm_unreachable("UnwindInst has no successors!");
727 //===----------------------------------------------------------------------===//
728 // BranchInst Implementation
729 //===----------------------------------------------------------------------===//
731 void BranchInst::AssertOK() {
733 assert(getCondition()->getType() == Type::getInt1Ty(getContext()) &&
734 "May only branch on boolean predicates!");
737 BranchInst::BranchInst(BasicBlock *IfTrue, Instruction *InsertBefore)
738 : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
739 OperandTraits<BranchInst>::op_end(this) - 1,
741 assert(IfTrue != 0 && "Branch destination may not be null!");
744 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
745 Instruction *InsertBefore)
746 : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
747 OperandTraits<BranchInst>::op_end(this) - 3,
757 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *InsertAtEnd)
758 : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
759 OperandTraits<BranchInst>::op_end(this) - 1,
761 assert(IfTrue != 0 && "Branch destination may not be null!");
765 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
766 BasicBlock *InsertAtEnd)
767 : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
768 OperandTraits<BranchInst>::op_end(this) - 3,
779 BranchInst::BranchInst(const BranchInst &BI) :
780 TerminatorInst(Type::getVoidTy(BI.getContext()), Instruction::Br,
781 OperandTraits<BranchInst>::op_end(this) - BI.getNumOperands(),
782 BI.getNumOperands()) {
783 Op<-1>() = BI.Op<-1>();
784 if (BI.getNumOperands() != 1) {
785 assert(BI.getNumOperands() == 3 && "BR can have 1 or 3 operands!");
786 Op<-3>() = BI.Op<-3>();
787 Op<-2>() = BI.Op<-2>();
789 SubclassOptionalData = BI.SubclassOptionalData;
793 Use* Use::getPrefix() {
794 PointerIntPair<Use**, 2, PrevPtrTag> &PotentialPrefix(this[-1].Prev);
795 if (PotentialPrefix.getOpaqueValue())
798 return reinterpret_cast<Use*>((char*)&PotentialPrefix + 1);
801 BranchInst::~BranchInst() {
802 if (NumOperands == 1) {
803 if (Use *Prefix = OperandList->getPrefix()) {
806 // mark OperandList to have a special value for scrutiny
807 // by baseclass destructors and operator delete
808 OperandList = Prefix;
811 OperandList = op_begin();
817 BasicBlock *BranchInst::getSuccessorV(unsigned idx) const {
818 return getSuccessor(idx);
820 unsigned BranchInst::getNumSuccessorsV() const {
821 return getNumSuccessors();
823 void BranchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
824 setSuccessor(idx, B);
828 //===----------------------------------------------------------------------===//
829 // AllocationInst Implementation
830 //===----------------------------------------------------------------------===//
832 static Value *getAISize(LLVMContext &Context, Value *Amt) {
834 Amt = ConstantInt::get(Type::getInt32Ty(Context), 1);
836 assert(!isa<BasicBlock>(Amt) &&
837 "Passed basic block into allocation size parameter! Use other ctor");
838 assert(Amt->getType() == Type::getInt32Ty(Context) &&
839 "Malloc/Allocation array size is not a 32-bit integer!");
844 AllocationInst::AllocationInst(const Type *Ty, Value *ArraySize, unsigned iTy,
845 unsigned Align, const Twine &Name,
846 Instruction *InsertBefore)
847 : UnaryInstruction(PointerType::getUnqual(Ty), iTy,
848 getAISize(Ty->getContext(), ArraySize), InsertBefore) {
850 assert(Ty != Type::getVoidTy(Ty->getContext()) && "Cannot allocate void!");
854 AllocationInst::AllocationInst(const Type *Ty, Value *ArraySize, unsigned iTy,
855 unsigned Align, const Twine &Name,
856 BasicBlock *InsertAtEnd)
857 : UnaryInstruction(PointerType::getUnqual(Ty), iTy,
858 getAISize(Ty->getContext(), ArraySize), InsertAtEnd) {
860 assert(Ty != Type::getVoidTy(Ty->getContext()) && "Cannot allocate void!");
864 // Out of line virtual method, so the vtable, etc has a home.
865 AllocationInst::~AllocationInst() {
868 void AllocationInst::setAlignment(unsigned Align) {
869 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
870 SubclassData = Log2_32(Align) + 1;
871 assert(getAlignment() == Align && "Alignment representation error!");
874 bool AllocationInst::isArrayAllocation() const {
875 if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(0)))
876 return CI->getZExtValue() != 1;
880 const Type *AllocationInst::getAllocatedType() const {
881 return getType()->getElementType();
884 /// isStaticAlloca - Return true if this alloca is in the entry block of the
885 /// function and is a constant size. If so, the code generator will fold it
886 /// into the prolog/epilog code, so it is basically free.
887 bool AllocaInst::isStaticAlloca() const {
888 // Must be constant size.
889 if (!isa<ConstantInt>(getArraySize())) return false;
891 // Must be in the entry block.
892 const BasicBlock *Parent = getParent();
893 return Parent == &Parent->getParent()->front();
896 //===----------------------------------------------------------------------===//
897 // FreeInst Implementation
898 //===----------------------------------------------------------------------===//
900 void FreeInst::AssertOK() {
901 assert(isa<PointerType>(getOperand(0)->getType()) &&
902 "Can not free something of nonpointer type!");
905 FreeInst::FreeInst(Value *Ptr, Instruction *InsertBefore)
906 : UnaryInstruction(Type::getVoidTy(Ptr->getContext()),
907 Free, Ptr, InsertBefore) {
911 FreeInst::FreeInst(Value *Ptr, BasicBlock *InsertAtEnd)
912 : UnaryInstruction(Type::getVoidTy(Ptr->getContext()),
913 Free, Ptr, InsertAtEnd) {
918 //===----------------------------------------------------------------------===//
919 // LoadInst Implementation
920 //===----------------------------------------------------------------------===//
922 void LoadInst::AssertOK() {
923 assert(isa<PointerType>(getOperand(0)->getType()) &&
924 "Ptr must have pointer type.");
927 LoadInst::LoadInst(Value *Ptr, const Twine &Name, Instruction *InsertBef)
928 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
929 Load, Ptr, InsertBef) {
936 LoadInst::LoadInst(Value *Ptr, const Twine &Name, BasicBlock *InsertAE)
937 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
938 Load, Ptr, InsertAE) {
945 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
946 Instruction *InsertBef)
947 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
948 Load, Ptr, InsertBef) {
949 setVolatile(isVolatile);
955 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
956 unsigned Align, Instruction *InsertBef)
957 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
958 Load, Ptr, InsertBef) {
959 setVolatile(isVolatile);
965 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
966 unsigned Align, BasicBlock *InsertAE)
967 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
968 Load, Ptr, InsertAE) {
969 setVolatile(isVolatile);
975 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
976 BasicBlock *InsertAE)
977 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
978 Load, Ptr, InsertAE) {
979 setVolatile(isVolatile);
987 LoadInst::LoadInst(Value *Ptr, const char *Name, Instruction *InsertBef)
988 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
989 Load, Ptr, InsertBef) {
993 if (Name && Name[0]) setName(Name);
996 LoadInst::LoadInst(Value *Ptr, const char *Name, BasicBlock *InsertAE)
997 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
998 Load, Ptr, InsertAE) {
1002 if (Name && Name[0]) setName(Name);
1005 LoadInst::LoadInst(Value *Ptr, const char *Name, bool isVolatile,
1006 Instruction *InsertBef)
1007 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1008 Load, Ptr, InsertBef) {
1009 setVolatile(isVolatile);
1012 if (Name && Name[0]) setName(Name);
1015 LoadInst::LoadInst(Value *Ptr, const char *Name, bool isVolatile,
1016 BasicBlock *InsertAE)
1017 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1018 Load, Ptr, InsertAE) {
1019 setVolatile(isVolatile);
1022 if (Name && Name[0]) setName(Name);
1025 void LoadInst::setAlignment(unsigned Align) {
1026 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
1027 SubclassData = (SubclassData & 1) | ((Log2_32(Align)+1)<<1);
1030 //===----------------------------------------------------------------------===//
1031 // StoreInst Implementation
1032 //===----------------------------------------------------------------------===//
1034 void StoreInst::AssertOK() {
1035 assert(getOperand(0) && getOperand(1) && "Both operands must be non-null!");
1036 assert(isa<PointerType>(getOperand(1)->getType()) &&
1037 "Ptr must have pointer type!");
1038 assert(getOperand(0)->getType() ==
1039 cast<PointerType>(getOperand(1)->getType())->getElementType()
1040 && "Ptr must be a pointer to Val type!");
1044 StoreInst::StoreInst(Value *val, Value *addr, Instruction *InsertBefore)
1045 : Instruction(Type::getVoidTy(val->getContext()), Store,
1046 OperandTraits<StoreInst>::op_begin(this),
1047 OperandTraits<StoreInst>::operands(this),
1056 StoreInst::StoreInst(Value *val, Value *addr, BasicBlock *InsertAtEnd)
1057 : Instruction(Type::getVoidTy(val->getContext()), Store,
1058 OperandTraits<StoreInst>::op_begin(this),
1059 OperandTraits<StoreInst>::operands(this),
1068 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1069 Instruction *InsertBefore)
1070 : Instruction(Type::getVoidTy(val->getContext()), Store,
1071 OperandTraits<StoreInst>::op_begin(this),
1072 OperandTraits<StoreInst>::operands(this),
1076 setVolatile(isVolatile);
1081 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1082 unsigned Align, Instruction *InsertBefore)
1083 : Instruction(Type::getVoidTy(val->getContext()), Store,
1084 OperandTraits<StoreInst>::op_begin(this),
1085 OperandTraits<StoreInst>::operands(this),
1089 setVolatile(isVolatile);
1090 setAlignment(Align);
1094 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1095 unsigned Align, BasicBlock *InsertAtEnd)
1096 : Instruction(Type::getVoidTy(val->getContext()), Store,
1097 OperandTraits<StoreInst>::op_begin(this),
1098 OperandTraits<StoreInst>::operands(this),
1102 setVolatile(isVolatile);
1103 setAlignment(Align);
1107 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1108 BasicBlock *InsertAtEnd)
1109 : Instruction(Type::getVoidTy(val->getContext()), Store,
1110 OperandTraits<StoreInst>::op_begin(this),
1111 OperandTraits<StoreInst>::operands(this),
1115 setVolatile(isVolatile);
1120 void StoreInst::setAlignment(unsigned Align) {
1121 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
1122 SubclassData = (SubclassData & 1) | ((Log2_32(Align)+1)<<1);
1125 //===----------------------------------------------------------------------===//
1126 // GetElementPtrInst Implementation
1127 //===----------------------------------------------------------------------===//
1129 static unsigned retrieveAddrSpace(const Value *Val) {
1130 return cast<PointerType>(Val->getType())->getAddressSpace();
1133 void GetElementPtrInst::init(Value *Ptr, Value* const *Idx, unsigned NumIdx,
1134 const Twine &Name) {
1135 assert(NumOperands == 1+NumIdx && "NumOperands not initialized?");
1136 Use *OL = OperandList;
1139 for (unsigned i = 0; i != NumIdx; ++i)
1145 void GetElementPtrInst::init(Value *Ptr, Value *Idx, const Twine &Name) {
1146 assert(NumOperands == 2 && "NumOperands not initialized?");
1147 Use *OL = OperandList;
1154 GetElementPtrInst::GetElementPtrInst(const GetElementPtrInst &GEPI)
1155 : Instruction(GEPI.getType(), GetElementPtr,
1156 OperandTraits<GetElementPtrInst>::op_end(this)
1157 - GEPI.getNumOperands(),
1158 GEPI.getNumOperands()) {
1159 Use *OL = OperandList;
1160 Use *GEPIOL = GEPI.OperandList;
1161 for (unsigned i = 0, E = NumOperands; i != E; ++i)
1163 SubclassOptionalData = GEPI.SubclassOptionalData;
1166 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx,
1167 const Twine &Name, Instruction *InBe)
1168 : Instruction(PointerType::get(
1169 checkType(getIndexedType(Ptr->getType(),Idx)), retrieveAddrSpace(Ptr)),
1171 OperandTraits<GetElementPtrInst>::op_end(this) - 2,
1173 init(Ptr, Idx, Name);
1176 GetElementPtrInst::GetElementPtrInst(Value *Ptr, Value *Idx,
1177 const Twine &Name, BasicBlock *IAE)
1178 : Instruction(PointerType::get(
1179 checkType(getIndexedType(Ptr->getType(),Idx)),
1180 retrieveAddrSpace(Ptr)),
1182 OperandTraits<GetElementPtrInst>::op_end(this) - 2,
1184 init(Ptr, Idx, Name);
1187 /// getIndexedType - Returns the type of the element that would be accessed with
1188 /// a gep instruction with the specified parameters.
1190 /// The Idxs pointer should point to a continuous piece of memory containing the
1191 /// indices, either as Value* or uint64_t.
1193 /// A null type is returned if the indices are invalid for the specified
1196 template <typename IndexTy>
1197 static const Type* getIndexedTypeInternal(const Type *Ptr, IndexTy const *Idxs,
1199 const PointerType *PTy = dyn_cast<PointerType>(Ptr);
1200 if (!PTy) return 0; // Type isn't a pointer type!
1201 const Type *Agg = PTy->getElementType();
1203 // Handle the special case of the empty set index set, which is always valid.
1207 // If there is at least one index, the top level type must be sized, otherwise
1208 // it cannot be 'stepped over'. We explicitly allow abstract types (those
1209 // that contain opaque types) under the assumption that it will be resolved to
1210 // a sane type later.
1211 if (!Agg->isSized() && !Agg->isAbstract())
1214 unsigned CurIdx = 1;
1215 for (; CurIdx != NumIdx; ++CurIdx) {
1216 const CompositeType *CT = dyn_cast<CompositeType>(Agg);
1217 if (!CT || isa<PointerType>(CT)) return 0;
1218 IndexTy Index = Idxs[CurIdx];
1219 if (!CT->indexValid(Index)) return 0;
1220 Agg = CT->getTypeAtIndex(Index);
1222 // If the new type forwards to another type, then it is in the middle
1223 // of being refined to another type (and hence, may have dropped all
1224 // references to what it was using before). So, use the new forwarded
1226 if (const Type *Ty = Agg->getForwardedType())
1229 return CurIdx == NumIdx ? Agg : 0;
1232 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr,
1235 return getIndexedTypeInternal(Ptr, Idxs, NumIdx);
1238 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr,
1239 uint64_t const *Idxs,
1241 return getIndexedTypeInternal(Ptr, Idxs, NumIdx);
1244 const Type* GetElementPtrInst::getIndexedType(const Type *Ptr, Value *Idx) {
1245 const PointerType *PTy = dyn_cast<PointerType>(Ptr);
1246 if (!PTy) return 0; // Type isn't a pointer type!
1248 // Check the pointer index.
1249 if (!PTy->indexValid(Idx)) return 0;
1251 return PTy->getElementType();
1255 /// hasAllZeroIndices - Return true if all of the indices of this GEP are
1256 /// zeros. If so, the result pointer and the first operand have the same
1257 /// value, just potentially different types.
1258 bool GetElementPtrInst::hasAllZeroIndices() const {
1259 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1260 if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(i))) {
1261 if (!CI->isZero()) return false;
1269 /// hasAllConstantIndices - Return true if all of the indices of this GEP are
1270 /// constant integers. If so, the result pointer and the first operand have
1271 /// a constant offset between them.
1272 bool GetElementPtrInst::hasAllConstantIndices() const {
1273 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1274 if (!isa<ConstantInt>(getOperand(i)))
1280 void GetElementPtrInst::setIsInBounds(bool B) {
1281 cast<GEPOperator>(this)->setIsInBounds(B);
1284 //===----------------------------------------------------------------------===//
1285 // ExtractElementInst Implementation
1286 //===----------------------------------------------------------------------===//
1288 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
1290 Instruction *InsertBef)
1291 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1293 OperandTraits<ExtractElementInst>::op_begin(this),
1295 assert(isValidOperands(Val, Index) &&
1296 "Invalid extractelement instruction operands!");
1302 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
1304 BasicBlock *InsertAE)
1305 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1307 OperandTraits<ExtractElementInst>::op_begin(this),
1309 assert(isValidOperands(Val, Index) &&
1310 "Invalid extractelement instruction operands!");
1318 bool ExtractElementInst::isValidOperands(const Value *Val, const Value *Index) {
1319 if (!isa<VectorType>(Val->getType()) ||
1320 Index->getType() != Type::getInt32Ty(Val->getContext()))
1326 //===----------------------------------------------------------------------===//
1327 // InsertElementInst Implementation
1328 //===----------------------------------------------------------------------===//
1330 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
1332 Instruction *InsertBef)
1333 : Instruction(Vec->getType(), InsertElement,
1334 OperandTraits<InsertElementInst>::op_begin(this),
1336 assert(isValidOperands(Vec, Elt, Index) &&
1337 "Invalid insertelement instruction operands!");
1344 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
1346 BasicBlock *InsertAE)
1347 : Instruction(Vec->getType(), InsertElement,
1348 OperandTraits<InsertElementInst>::op_begin(this),
1350 assert(isValidOperands(Vec, Elt, Index) &&
1351 "Invalid insertelement instruction operands!");
1359 bool InsertElementInst::isValidOperands(const Value *Vec, const Value *Elt,
1360 const Value *Index) {
1361 if (!isa<VectorType>(Vec->getType()))
1362 return false; // First operand of insertelement must be vector type.
1364 if (Elt->getType() != cast<VectorType>(Vec->getType())->getElementType())
1365 return false;// Second operand of insertelement must be vector element type.
1367 if (Index->getType() != Type::getInt32Ty(Vec->getContext()))
1368 return false; // Third operand of insertelement must be i32.
1373 //===----------------------------------------------------------------------===//
1374 // ShuffleVectorInst Implementation
1375 //===----------------------------------------------------------------------===//
1377 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1379 Instruction *InsertBefore)
1380 : Instruction(VectorType::get(cast<VectorType>(V1->getType())->getElementType(),
1381 cast<VectorType>(Mask->getType())->getNumElements()),
1383 OperandTraits<ShuffleVectorInst>::op_begin(this),
1384 OperandTraits<ShuffleVectorInst>::operands(this),
1386 assert(isValidOperands(V1, V2, Mask) &&
1387 "Invalid shuffle vector instruction operands!");
1394 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1396 BasicBlock *InsertAtEnd)
1397 : Instruction(VectorType::get(cast<VectorType>(V1->getType())->getElementType(),
1398 cast<VectorType>(Mask->getType())->getNumElements()),
1400 OperandTraits<ShuffleVectorInst>::op_begin(this),
1401 OperandTraits<ShuffleVectorInst>::operands(this),
1403 assert(isValidOperands(V1, V2, Mask) &&
1404 "Invalid shuffle vector instruction operands!");
1412 bool ShuffleVectorInst::isValidOperands(const Value *V1, const Value *V2,
1413 const Value *Mask) {
1414 if (!isa<VectorType>(V1->getType()) || V1->getType() != V2->getType())
1417 const VectorType *MaskTy = dyn_cast<VectorType>(Mask->getType());
1418 if (!isa<Constant>(Mask) || MaskTy == 0 ||
1419 MaskTy->getElementType() != Type::getInt32Ty(V1->getContext()))
1424 /// getMaskValue - Return the index from the shuffle mask for the specified
1425 /// output result. This is either -1 if the element is undef or a number less
1426 /// than 2*numelements.
1427 int ShuffleVectorInst::getMaskValue(unsigned i) const {
1428 const Constant *Mask = cast<Constant>(getOperand(2));
1429 if (isa<UndefValue>(Mask)) return -1;
1430 if (isa<ConstantAggregateZero>(Mask)) return 0;
1431 const ConstantVector *MaskCV = cast<ConstantVector>(Mask);
1432 assert(i < MaskCV->getNumOperands() && "Index out of range");
1434 if (isa<UndefValue>(MaskCV->getOperand(i)))
1436 return cast<ConstantInt>(MaskCV->getOperand(i))->getZExtValue();
1439 //===----------------------------------------------------------------------===//
1440 // InsertValueInst Class
1441 //===----------------------------------------------------------------------===//
1443 void InsertValueInst::init(Value *Agg, Value *Val, const unsigned *Idx,
1444 unsigned NumIdx, const Twine &Name) {
1445 assert(NumOperands == 2 && "NumOperands not initialized?");
1449 Indices.insert(Indices.end(), Idx, Idx + NumIdx);
1453 void InsertValueInst::init(Value *Agg, Value *Val, unsigned Idx,
1454 const Twine &Name) {
1455 assert(NumOperands == 2 && "NumOperands not initialized?");
1459 Indices.push_back(Idx);
1463 InsertValueInst::InsertValueInst(const InsertValueInst &IVI)
1464 : Instruction(IVI.getType(), InsertValue,
1465 OperandTraits<InsertValueInst>::op_begin(this), 2),
1466 Indices(IVI.Indices) {
1467 Op<0>() = IVI.getOperand(0);
1468 Op<1>() = IVI.getOperand(1);
1469 SubclassOptionalData = IVI.SubclassOptionalData;
1472 InsertValueInst::InsertValueInst(Value *Agg,
1476 Instruction *InsertBefore)
1477 : Instruction(Agg->getType(), InsertValue,
1478 OperandTraits<InsertValueInst>::op_begin(this),
1480 init(Agg, Val, Idx, Name);
1483 InsertValueInst::InsertValueInst(Value *Agg,
1487 BasicBlock *InsertAtEnd)
1488 : Instruction(Agg->getType(), InsertValue,
1489 OperandTraits<InsertValueInst>::op_begin(this),
1491 init(Agg, Val, Idx, Name);
1494 //===----------------------------------------------------------------------===//
1495 // ExtractValueInst Class
1496 //===----------------------------------------------------------------------===//
1498 void ExtractValueInst::init(const unsigned *Idx, unsigned NumIdx,
1499 const Twine &Name) {
1500 assert(NumOperands == 1 && "NumOperands not initialized?");
1502 Indices.insert(Indices.end(), Idx, Idx + NumIdx);
1506 void ExtractValueInst::init(unsigned Idx, const Twine &Name) {
1507 assert(NumOperands == 1 && "NumOperands not initialized?");
1509 Indices.push_back(Idx);
1513 ExtractValueInst::ExtractValueInst(const ExtractValueInst &EVI)
1514 : UnaryInstruction(EVI.getType(), ExtractValue, EVI.getOperand(0)),
1515 Indices(EVI.Indices) {
1516 SubclassOptionalData = EVI.SubclassOptionalData;
1519 // getIndexedType - Returns the type of the element that would be extracted
1520 // with an extractvalue instruction with the specified parameters.
1522 // A null type is returned if the indices are invalid for the specified
1525 const Type* ExtractValueInst::getIndexedType(const Type *Agg,
1526 const unsigned *Idxs,
1528 unsigned CurIdx = 0;
1529 for (; CurIdx != NumIdx; ++CurIdx) {
1530 const CompositeType *CT = dyn_cast<CompositeType>(Agg);
1531 if (!CT || isa<PointerType>(CT) || isa<VectorType>(CT)) return 0;
1532 unsigned Index = Idxs[CurIdx];
1533 if (!CT->indexValid(Index)) return 0;
1534 Agg = CT->getTypeAtIndex(Index);
1536 // If the new type forwards to another type, then it is in the middle
1537 // of being refined to another type (and hence, may have dropped all
1538 // references to what it was using before). So, use the new forwarded
1540 if (const Type *Ty = Agg->getForwardedType())
1543 return CurIdx == NumIdx ? Agg : 0;
1546 const Type* ExtractValueInst::getIndexedType(const Type *Agg,
1548 return getIndexedType(Agg, &Idx, 1);
1551 //===----------------------------------------------------------------------===//
1552 // BinaryOperator Class
1553 //===----------------------------------------------------------------------===//
1555 /// AdjustIType - Map Add, Sub, and Mul to FAdd, FSub, and FMul when the
1556 /// type is floating-point, to help provide compatibility with an older API.
1558 static BinaryOperator::BinaryOps AdjustIType(BinaryOperator::BinaryOps iType,
1560 // API compatibility: Adjust integer opcodes to floating-point opcodes.
1561 if (Ty->isFPOrFPVector()) {
1562 if (iType == BinaryOperator::Add) iType = BinaryOperator::FAdd;
1563 else if (iType == BinaryOperator::Sub) iType = BinaryOperator::FSub;
1564 else if (iType == BinaryOperator::Mul) iType = BinaryOperator::FMul;
1569 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
1570 const Type *Ty, const Twine &Name,
1571 Instruction *InsertBefore)
1572 : Instruction(Ty, AdjustIType(iType, Ty),
1573 OperandTraits<BinaryOperator>::op_begin(this),
1574 OperandTraits<BinaryOperator>::operands(this),
1578 init(AdjustIType(iType, Ty));
1582 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
1583 const Type *Ty, const Twine &Name,
1584 BasicBlock *InsertAtEnd)
1585 : Instruction(Ty, AdjustIType(iType, Ty),
1586 OperandTraits<BinaryOperator>::op_begin(this),
1587 OperandTraits<BinaryOperator>::operands(this),
1591 init(AdjustIType(iType, Ty));
1596 void BinaryOperator::init(BinaryOps iType) {
1597 Value *LHS = getOperand(0), *RHS = getOperand(1);
1598 LHS = LHS; RHS = RHS; // Silence warnings.
1599 assert(LHS->getType() == RHS->getType() &&
1600 "Binary operator operand types must match!");
1605 assert(getType() == LHS->getType() &&
1606 "Arithmetic operation should return same type as operands!");
1607 assert(getType()->isIntOrIntVector() &&
1608 "Tried to create an integer operation on a non-integer type!");
1610 case FAdd: case FSub:
1612 assert(getType() == LHS->getType() &&
1613 "Arithmetic operation should return same type as operands!");
1614 assert(getType()->isFPOrFPVector() &&
1615 "Tried to create a floating-point operation on a "
1616 "non-floating-point type!");
1620 assert(getType() == LHS->getType() &&
1621 "Arithmetic operation should return same type as operands!");
1622 assert((getType()->isInteger() || (isa<VectorType>(getType()) &&
1623 cast<VectorType>(getType())->getElementType()->isInteger())) &&
1624 "Incorrect operand type (not integer) for S/UDIV");
1627 assert(getType() == LHS->getType() &&
1628 "Arithmetic operation should return same type as operands!");
1629 assert(getType()->isFPOrFPVector() &&
1630 "Incorrect operand type (not floating point) for FDIV");
1634 assert(getType() == LHS->getType() &&
1635 "Arithmetic operation should return same type as operands!");
1636 assert((getType()->isInteger() || (isa<VectorType>(getType()) &&
1637 cast<VectorType>(getType())->getElementType()->isInteger())) &&
1638 "Incorrect operand type (not integer) for S/UREM");
1641 assert(getType() == LHS->getType() &&
1642 "Arithmetic operation should return same type as operands!");
1643 assert(getType()->isFPOrFPVector() &&
1644 "Incorrect operand type (not floating point) for FREM");
1649 assert(getType() == LHS->getType() &&
1650 "Shift operation should return same type as operands!");
1651 assert((getType()->isInteger() ||
1652 (isa<VectorType>(getType()) &&
1653 cast<VectorType>(getType())->getElementType()->isInteger())) &&
1654 "Tried to create a shift operation on a non-integral type!");
1658 assert(getType() == LHS->getType() &&
1659 "Logical operation should return same type as operands!");
1660 assert((getType()->isInteger() ||
1661 (isa<VectorType>(getType()) &&
1662 cast<VectorType>(getType())->getElementType()->isInteger())) &&
1663 "Tried to create a logical operation on a non-integral type!");
1671 BinaryOperator *BinaryOperator::Create(BinaryOps Op, Value *S1, Value *S2,
1673 Instruction *InsertBefore) {
1674 assert(S1->getType() == S2->getType() &&
1675 "Cannot create binary operator with two operands of differing type!");
1676 return new BinaryOperator(Op, S1, S2, S1->getType(), Name, InsertBefore);
1679 BinaryOperator *BinaryOperator::Create(BinaryOps Op, Value *S1, Value *S2,
1681 BasicBlock *InsertAtEnd) {
1682 BinaryOperator *Res = Create(Op, S1, S2, Name);
1683 InsertAtEnd->getInstList().push_back(Res);
1687 BinaryOperator *BinaryOperator::CreateNeg(Value *Op, const Twine &Name,
1688 Instruction *InsertBefore) {
1689 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1690 return new BinaryOperator(Instruction::Sub,
1692 Op->getType(), Name, InsertBefore);
1695 BinaryOperator *BinaryOperator::CreateNeg(Value *Op, const Twine &Name,
1696 BasicBlock *InsertAtEnd) {
1697 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1698 return new BinaryOperator(Instruction::Sub,
1700 Op->getType(), Name, InsertAtEnd);
1703 BinaryOperator *BinaryOperator::CreateFNeg(Value *Op, const Twine &Name,
1704 Instruction *InsertBefore) {
1705 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1706 return new BinaryOperator(Instruction::FSub,
1708 Op->getType(), Name, InsertBefore);
1711 BinaryOperator *BinaryOperator::CreateFNeg(Value *Op, const Twine &Name,
1712 BasicBlock *InsertAtEnd) {
1713 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1714 return new BinaryOperator(Instruction::FSub,
1716 Op->getType(), Name, InsertAtEnd);
1719 BinaryOperator *BinaryOperator::CreateNot(Value *Op, const Twine &Name,
1720 Instruction *InsertBefore) {
1722 if (const VectorType *PTy = dyn_cast<VectorType>(Op->getType())) {
1723 C = Constant::getAllOnesValue(PTy->getElementType());
1724 C = ConstantVector::get(
1725 std::vector<Constant*>(PTy->getNumElements(), C));
1727 C = Constant::getAllOnesValue(Op->getType());
1730 return new BinaryOperator(Instruction::Xor, Op, C,
1731 Op->getType(), Name, InsertBefore);
1734 BinaryOperator *BinaryOperator::CreateNot(Value *Op, const Twine &Name,
1735 BasicBlock *InsertAtEnd) {
1737 if (const VectorType *PTy = dyn_cast<VectorType>(Op->getType())) {
1738 // Create a vector of all ones values.
1739 Constant *Elt = Constant::getAllOnesValue(PTy->getElementType());
1740 AllOnes = ConstantVector::get(
1741 std::vector<Constant*>(PTy->getNumElements(), Elt));
1743 AllOnes = Constant::getAllOnesValue(Op->getType());
1746 return new BinaryOperator(Instruction::Xor, Op, AllOnes,
1747 Op->getType(), Name, InsertAtEnd);
1751 // isConstantAllOnes - Helper function for several functions below
1752 static inline bool isConstantAllOnes(const Value *V) {
1753 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V))
1754 return CI->isAllOnesValue();
1755 if (const ConstantVector *CV = dyn_cast<ConstantVector>(V))
1756 return CV->isAllOnesValue();
1760 bool BinaryOperator::isNeg(const Value *V) {
1761 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1762 if (Bop->getOpcode() == Instruction::Sub)
1763 if (Constant* C = dyn_cast<Constant>(Bop->getOperand(0)))
1764 return C->isNegativeZeroValue();
1768 bool BinaryOperator::isFNeg(const Value *V) {
1769 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1770 if (Bop->getOpcode() == Instruction::FSub)
1771 if (Constant* C = dyn_cast<Constant>(Bop->getOperand(0)))
1772 return C->isNegativeZeroValue();
1776 bool BinaryOperator::isNot(const Value *V) {
1777 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1778 return (Bop->getOpcode() == Instruction::Xor &&
1779 (isConstantAllOnes(Bop->getOperand(1)) ||
1780 isConstantAllOnes(Bop->getOperand(0))));
1784 Value *BinaryOperator::getNegArgument(Value *BinOp) {
1785 return cast<BinaryOperator>(BinOp)->getOperand(1);
1788 const Value *BinaryOperator::getNegArgument(const Value *BinOp) {
1789 return getNegArgument(const_cast<Value*>(BinOp));
1792 Value *BinaryOperator::getFNegArgument(Value *BinOp) {
1793 return cast<BinaryOperator>(BinOp)->getOperand(1);
1796 const Value *BinaryOperator::getFNegArgument(const Value *BinOp) {
1797 return getFNegArgument(const_cast<Value*>(BinOp));
1800 Value *BinaryOperator::getNotArgument(Value *BinOp) {
1801 assert(isNot(BinOp) && "getNotArgument on non-'not' instruction!");
1802 BinaryOperator *BO = cast<BinaryOperator>(BinOp);
1803 Value *Op0 = BO->getOperand(0);
1804 Value *Op1 = BO->getOperand(1);
1805 if (isConstantAllOnes(Op0)) return Op1;
1807 assert(isConstantAllOnes(Op1));
1811 const Value *BinaryOperator::getNotArgument(const Value *BinOp) {
1812 return getNotArgument(const_cast<Value*>(BinOp));
1816 // swapOperands - Exchange the two operands to this instruction. This
1817 // instruction is safe to use on any binary instruction and does not
1818 // modify the semantics of the instruction. If the instruction is
1819 // order dependent (SetLT f.e.) the opcode is changed.
1821 bool BinaryOperator::swapOperands() {
1822 if (!isCommutative())
1823 return true; // Can't commute operands
1824 Op<0>().swap(Op<1>());
1828 void BinaryOperator::setHasNoUnsignedWrap(bool b) {
1829 cast<OverflowingBinaryOperator>(this)->setHasNoUnsignedWrap(b);
1832 void BinaryOperator::setHasNoSignedWrap(bool b) {
1833 cast<OverflowingBinaryOperator>(this)->setHasNoSignedWrap(b);
1836 void BinaryOperator::setIsExact(bool b) {
1837 cast<SDivOperator>(this)->setIsExact(b);
1840 //===----------------------------------------------------------------------===//
1842 //===----------------------------------------------------------------------===//
1844 // Just determine if this cast only deals with integral->integral conversion.
1845 bool CastInst::isIntegerCast() const {
1846 switch (getOpcode()) {
1847 default: return false;
1848 case Instruction::ZExt:
1849 case Instruction::SExt:
1850 case Instruction::Trunc:
1852 case Instruction::BitCast:
1853 return getOperand(0)->getType()->isInteger() && getType()->isInteger();
1857 bool CastInst::isLosslessCast() const {
1858 // Only BitCast can be lossless, exit fast if we're not BitCast
1859 if (getOpcode() != Instruction::BitCast)
1862 // Identity cast is always lossless
1863 const Type* SrcTy = getOperand(0)->getType();
1864 const Type* DstTy = getType();
1868 // Pointer to pointer is always lossless.
1869 if (isa<PointerType>(SrcTy))
1870 return isa<PointerType>(DstTy);
1871 return false; // Other types have no identity values
1874 /// This function determines if the CastInst does not require any bits to be
1875 /// changed in order to effect the cast. Essentially, it identifies cases where
1876 /// no code gen is necessary for the cast, hence the name no-op cast. For
1877 /// example, the following are all no-op casts:
1878 /// # bitcast i32* %x to i8*
1879 /// # bitcast <2 x i32> %x to <4 x i16>
1880 /// # ptrtoint i32* %x to i32 ; on 32-bit plaforms only
1881 /// @brief Determine if a cast is a no-op.
1882 bool CastInst::isNoopCast(const Type *IntPtrTy) const {
1883 switch (getOpcode()) {
1885 assert(!"Invalid CastOp");
1886 case Instruction::Trunc:
1887 case Instruction::ZExt:
1888 case Instruction::SExt:
1889 case Instruction::FPTrunc:
1890 case Instruction::FPExt:
1891 case Instruction::UIToFP:
1892 case Instruction::SIToFP:
1893 case Instruction::FPToUI:
1894 case Instruction::FPToSI:
1895 return false; // These always modify bits
1896 case Instruction::BitCast:
1897 return true; // BitCast never modifies bits.
1898 case Instruction::PtrToInt:
1899 return IntPtrTy->getScalarSizeInBits() ==
1900 getType()->getScalarSizeInBits();
1901 case Instruction::IntToPtr:
1902 return IntPtrTy->getScalarSizeInBits() ==
1903 getOperand(0)->getType()->getScalarSizeInBits();
1907 /// This function determines if a pair of casts can be eliminated and what
1908 /// opcode should be used in the elimination. This assumes that there are two
1909 /// instructions like this:
1910 /// * %F = firstOpcode SrcTy %x to MidTy
1911 /// * %S = secondOpcode MidTy %F to DstTy
1912 /// The function returns a resultOpcode so these two casts can be replaced with:
1913 /// * %Replacement = resultOpcode %SrcTy %x to DstTy
1914 /// If no such cast is permited, the function returns 0.
1915 unsigned CastInst::isEliminableCastPair(
1916 Instruction::CastOps firstOp, Instruction::CastOps secondOp,
1917 const Type *SrcTy, const Type *MidTy, const Type *DstTy, const Type *IntPtrTy)
1919 // Define the 144 possibilities for these two cast instructions. The values
1920 // in this matrix determine what to do in a given situation and select the
1921 // case in the switch below. The rows correspond to firstOp, the columns
1922 // correspond to secondOp. In looking at the table below, keep in mind
1923 // the following cast properties:
1925 // Size Compare Source Destination
1926 // Operator Src ? Size Type Sign Type Sign
1927 // -------- ------------ ------------------- ---------------------
1928 // TRUNC > Integer Any Integral Any
1929 // ZEXT < Integral Unsigned Integer Any
1930 // SEXT < Integral Signed Integer Any
1931 // FPTOUI n/a FloatPt n/a Integral Unsigned
1932 // FPTOSI n/a FloatPt n/a Integral Signed
1933 // UITOFP n/a Integral Unsigned FloatPt n/a
1934 // SITOFP n/a Integral Signed FloatPt n/a
1935 // FPTRUNC > FloatPt n/a FloatPt n/a
1936 // FPEXT < FloatPt n/a FloatPt n/a
1937 // PTRTOINT n/a Pointer n/a Integral Unsigned
1938 // INTTOPTR n/a Integral Unsigned Pointer n/a
1939 // BITCONVERT = FirstClass n/a FirstClass n/a
1941 // NOTE: some transforms are safe, but we consider them to be non-profitable.
1942 // For example, we could merge "fptoui double to i32" + "zext i32 to i64",
1943 // into "fptoui double to i64", but this loses information about the range
1944 // of the produced value (we no longer know the top-part is all zeros).
1945 // Further this conversion is often much more expensive for typical hardware,
1946 // and causes issues when building libgcc. We disallow fptosi+sext for the
1948 const unsigned numCastOps =
1949 Instruction::CastOpsEnd - Instruction::CastOpsBegin;
1950 static const uint8_t CastResults[numCastOps][numCastOps] = {
1951 // T F F U S F F P I B -+
1952 // R Z S P P I I T P 2 N T |
1953 // U E E 2 2 2 2 R E I T C +- secondOp
1954 // N X X U S F F N X N 2 V |
1955 // C T T I I P P C T T P T -+
1956 { 1, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // Trunc -+
1957 { 8, 1, 9,99,99, 2, 0,99,99,99, 2, 3 }, // ZExt |
1958 { 8, 0, 1,99,99, 0, 2,99,99,99, 0, 3 }, // SExt |
1959 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // FPToUI |
1960 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // FPToSI |
1961 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4 }, // UIToFP +- firstOp
1962 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4 }, // SIToFP |
1963 { 99,99,99, 0, 0,99,99, 1, 0,99,99, 4 }, // FPTrunc |
1964 { 99,99,99, 2, 2,99,99,10, 2,99,99, 4 }, // FPExt |
1965 { 1, 0, 0,99,99, 0, 0,99,99,99, 7, 3 }, // PtrToInt |
1966 { 99,99,99,99,99,99,99,99,99,13,99,12 }, // IntToPtr |
1967 { 5, 5, 5, 6, 6, 5, 5, 6, 6,11, 5, 1 }, // BitCast -+
1970 int ElimCase = CastResults[firstOp-Instruction::CastOpsBegin]
1971 [secondOp-Instruction::CastOpsBegin];
1974 // categorically disallowed
1977 // allowed, use first cast's opcode
1980 // allowed, use second cast's opcode
1983 // no-op cast in second op implies firstOp as long as the DestTy
1985 if (DstTy->isInteger())
1989 // no-op cast in second op implies firstOp as long as the DestTy
1990 // is floating point
1991 if (DstTy->isFloatingPoint())
1995 // no-op cast in first op implies secondOp as long as the SrcTy
1997 if (SrcTy->isInteger())
2001 // no-op cast in first op implies secondOp as long as the SrcTy
2002 // is a floating point
2003 if (SrcTy->isFloatingPoint())
2007 // ptrtoint, inttoptr -> bitcast (ptr -> ptr) if int size is >= ptr size
2010 unsigned PtrSize = IntPtrTy->getScalarSizeInBits();
2011 unsigned MidSize = MidTy->getScalarSizeInBits();
2012 if (MidSize >= PtrSize)
2013 return Instruction::BitCast;
2017 // ext, trunc -> bitcast, if the SrcTy and DstTy are same size
2018 // ext, trunc -> ext, if sizeof(SrcTy) < sizeof(DstTy)
2019 // ext, trunc -> trunc, if sizeof(SrcTy) > sizeof(DstTy)
2020 unsigned SrcSize = SrcTy->getScalarSizeInBits();
2021 unsigned DstSize = DstTy->getScalarSizeInBits();
2022 if (SrcSize == DstSize)
2023 return Instruction::BitCast;
2024 else if (SrcSize < DstSize)
2028 case 9: // zext, sext -> zext, because sext can't sign extend after zext
2029 return Instruction::ZExt;
2031 // fpext followed by ftrunc is allowed if the bit size returned to is
2032 // the same as the original, in which case its just a bitcast
2034 return Instruction::BitCast;
2035 return 0; // If the types are not the same we can't eliminate it.
2037 // bitcast followed by ptrtoint is allowed as long as the bitcast
2038 // is a pointer to pointer cast.
2039 if (isa<PointerType>(SrcTy) && isa<PointerType>(MidTy))
2043 // inttoptr, bitcast -> intptr if bitcast is a ptr to ptr cast
2044 if (isa<PointerType>(MidTy) && isa<PointerType>(DstTy))
2048 // inttoptr, ptrtoint -> bitcast if SrcSize<=PtrSize and SrcSize==DstSize
2051 unsigned PtrSize = IntPtrTy->getScalarSizeInBits();
2052 unsigned SrcSize = SrcTy->getScalarSizeInBits();
2053 unsigned DstSize = DstTy->getScalarSizeInBits();
2054 if (SrcSize <= PtrSize && SrcSize == DstSize)
2055 return Instruction::BitCast;
2059 // cast combination can't happen (error in input). This is for all cases
2060 // where the MidTy is not the same for the two cast instructions.
2061 assert(!"Invalid Cast Combination");
2064 assert(!"Error in CastResults table!!!");
2070 CastInst *CastInst::Create(Instruction::CastOps op, Value *S, const Type *Ty,
2071 const Twine &Name, Instruction *InsertBefore) {
2072 // Construct and return the appropriate CastInst subclass
2074 case Trunc: return new TruncInst (S, Ty, Name, InsertBefore);
2075 case ZExt: return new ZExtInst (S, Ty, Name, InsertBefore);
2076 case SExt: return new SExtInst (S, Ty, Name, InsertBefore);
2077 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertBefore);
2078 case FPExt: return new FPExtInst (S, Ty, Name, InsertBefore);
2079 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertBefore);
2080 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertBefore);
2081 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertBefore);
2082 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertBefore);
2083 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertBefore);
2084 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertBefore);
2085 case BitCast: return new BitCastInst (S, Ty, Name, InsertBefore);
2087 assert(!"Invalid opcode provided");
2092 CastInst *CastInst::Create(Instruction::CastOps op, Value *S, const Type *Ty,
2093 const Twine &Name, BasicBlock *InsertAtEnd) {
2094 // Construct and return the appropriate CastInst subclass
2096 case Trunc: return new TruncInst (S, Ty, Name, InsertAtEnd);
2097 case ZExt: return new ZExtInst (S, Ty, Name, InsertAtEnd);
2098 case SExt: return new SExtInst (S, Ty, Name, InsertAtEnd);
2099 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertAtEnd);
2100 case FPExt: return new FPExtInst (S, Ty, Name, InsertAtEnd);
2101 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertAtEnd);
2102 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertAtEnd);
2103 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertAtEnd);
2104 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertAtEnd);
2105 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertAtEnd);
2106 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertAtEnd);
2107 case BitCast: return new BitCastInst (S, Ty, Name, InsertAtEnd);
2109 assert(!"Invalid opcode provided");
2114 CastInst *CastInst::CreateZExtOrBitCast(Value *S, const Type *Ty,
2116 Instruction *InsertBefore) {
2117 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2118 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2119 return Create(Instruction::ZExt, S, Ty, Name, InsertBefore);
2122 CastInst *CastInst::CreateZExtOrBitCast(Value *S, const Type *Ty,
2124 BasicBlock *InsertAtEnd) {
2125 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2126 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2127 return Create(Instruction::ZExt, S, Ty, Name, InsertAtEnd);
2130 CastInst *CastInst::CreateSExtOrBitCast(Value *S, const Type *Ty,
2132 Instruction *InsertBefore) {
2133 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2134 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2135 return Create(Instruction::SExt, S, Ty, Name, InsertBefore);
2138 CastInst *CastInst::CreateSExtOrBitCast(Value *S, const Type *Ty,
2140 BasicBlock *InsertAtEnd) {
2141 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2142 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2143 return Create(Instruction::SExt, S, Ty, Name, InsertAtEnd);
2146 CastInst *CastInst::CreateTruncOrBitCast(Value *S, const Type *Ty,
2148 Instruction *InsertBefore) {
2149 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2150 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2151 return Create(Instruction::Trunc, S, Ty, Name, InsertBefore);
2154 CastInst *CastInst::CreateTruncOrBitCast(Value *S, const Type *Ty,
2156 BasicBlock *InsertAtEnd) {
2157 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2158 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2159 return Create(Instruction::Trunc, S, Ty, Name, InsertAtEnd);
2162 CastInst *CastInst::CreatePointerCast(Value *S, const Type *Ty,
2164 BasicBlock *InsertAtEnd) {
2165 assert(isa<PointerType>(S->getType()) && "Invalid cast");
2166 assert((Ty->isInteger() || isa<PointerType>(Ty)) &&
2169 if (Ty->isInteger())
2170 return Create(Instruction::PtrToInt, S, Ty, Name, InsertAtEnd);
2171 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2174 /// @brief Create a BitCast or a PtrToInt cast instruction
2175 CastInst *CastInst::CreatePointerCast(Value *S, const Type *Ty,
2177 Instruction *InsertBefore) {
2178 assert(isa<PointerType>(S->getType()) && "Invalid cast");
2179 assert((Ty->isInteger() || isa<PointerType>(Ty)) &&
2182 if (Ty->isInteger())
2183 return Create(Instruction::PtrToInt, S, Ty, Name, InsertBefore);
2184 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2187 CastInst *CastInst::CreateIntegerCast(Value *C, const Type *Ty,
2188 bool isSigned, const Twine &Name,
2189 Instruction *InsertBefore) {
2190 assert(C->getType()->isInteger() && Ty->isInteger() && "Invalid cast");
2191 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2192 unsigned DstBits = Ty->getScalarSizeInBits();
2193 Instruction::CastOps opcode =
2194 (SrcBits == DstBits ? Instruction::BitCast :
2195 (SrcBits > DstBits ? Instruction::Trunc :
2196 (isSigned ? Instruction::SExt : Instruction::ZExt)));
2197 return Create(opcode, C, Ty, Name, InsertBefore);
2200 CastInst *CastInst::CreateIntegerCast(Value *C, const Type *Ty,
2201 bool isSigned, const Twine &Name,
2202 BasicBlock *InsertAtEnd) {
2203 assert(C->getType()->isIntOrIntVector() && Ty->isIntOrIntVector() &&
2205 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2206 unsigned DstBits = Ty->getScalarSizeInBits();
2207 Instruction::CastOps opcode =
2208 (SrcBits == DstBits ? Instruction::BitCast :
2209 (SrcBits > DstBits ? Instruction::Trunc :
2210 (isSigned ? Instruction::SExt : Instruction::ZExt)));
2211 return Create(opcode, C, Ty, Name, InsertAtEnd);
2214 CastInst *CastInst::CreateFPCast(Value *C, const Type *Ty,
2216 Instruction *InsertBefore) {
2217 assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
2219 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2220 unsigned DstBits = Ty->getScalarSizeInBits();
2221 Instruction::CastOps opcode =
2222 (SrcBits == DstBits ? Instruction::BitCast :
2223 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
2224 return Create(opcode, C, Ty, Name, InsertBefore);
2227 CastInst *CastInst::CreateFPCast(Value *C, const Type *Ty,
2229 BasicBlock *InsertAtEnd) {
2230 assert(C->getType()->isFPOrFPVector() && Ty->isFPOrFPVector() &&
2232 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2233 unsigned DstBits = Ty->getScalarSizeInBits();
2234 Instruction::CastOps opcode =
2235 (SrcBits == DstBits ? Instruction::BitCast :
2236 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
2237 return Create(opcode, C, Ty, Name, InsertAtEnd);
2240 // Check whether it is valid to call getCastOpcode for these types.
2241 // This routine must be kept in sync with getCastOpcode.
2242 bool CastInst::isCastable(const Type *SrcTy, const Type *DestTy) {
2243 if (!SrcTy->isFirstClassType() || !DestTy->isFirstClassType())
2246 if (SrcTy == DestTy)
2249 // Get the bit sizes, we'll need these
2250 unsigned SrcBits = SrcTy->getScalarSizeInBits(); // 0 for ptr
2251 unsigned DestBits = DestTy->getScalarSizeInBits(); // 0 for ptr
2253 // Run through the possibilities ...
2254 if (DestTy->isInteger()) { // Casting to integral
2255 if (SrcTy->isInteger()) { // Casting from integral
2257 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt
2259 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
2260 // Casting from vector
2261 return DestBits == PTy->getBitWidth();
2262 } else { // Casting from something else
2263 return isa<PointerType>(SrcTy);
2265 } else if (DestTy->isFloatingPoint()) { // Casting to floating pt
2266 if (SrcTy->isInteger()) { // Casting from integral
2268 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt
2270 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
2271 // Casting from vector
2272 return DestBits == PTy->getBitWidth();
2273 } else { // Casting from something else
2276 } else if (const VectorType *DestPTy = dyn_cast<VectorType>(DestTy)) {
2277 // Casting to vector
2278 if (const VectorType *SrcPTy = dyn_cast<VectorType>(SrcTy)) {
2279 // Casting from vector
2280 return DestPTy->getBitWidth() == SrcPTy->getBitWidth();
2281 } else { // Casting from something else
2282 return DestPTy->getBitWidth() == SrcBits;
2284 } else if (isa<PointerType>(DestTy)) { // Casting to pointer
2285 if (isa<PointerType>(SrcTy)) { // Casting from pointer
2287 } else if (SrcTy->isInteger()) { // Casting from integral
2289 } else { // Casting from something else
2292 } else { // Casting to something else
2297 // Provide a way to get a "cast" where the cast opcode is inferred from the
2298 // types and size of the operand. This, basically, is a parallel of the
2299 // logic in the castIsValid function below. This axiom should hold:
2300 // castIsValid( getCastOpcode(Val, Ty), Val, Ty)
2301 // should not assert in castIsValid. In other words, this produces a "correct"
2302 // casting opcode for the arguments passed to it.
2303 // This routine must be kept in sync with isCastable.
2304 Instruction::CastOps
2305 CastInst::getCastOpcode(
2306 const Value *Src, bool SrcIsSigned, const Type *DestTy, bool DestIsSigned) {
2307 // Get the bit sizes, we'll need these
2308 const Type *SrcTy = Src->getType();
2309 unsigned SrcBits = SrcTy->getScalarSizeInBits(); // 0 for ptr
2310 unsigned DestBits = DestTy->getScalarSizeInBits(); // 0 for ptr
2312 assert(SrcTy->isFirstClassType() && DestTy->isFirstClassType() &&
2313 "Only first class types are castable!");
2315 // Run through the possibilities ...
2316 if (DestTy->isInteger()) { // Casting to integral
2317 if (SrcTy->isInteger()) { // Casting from integral
2318 if (DestBits < SrcBits)
2319 return Trunc; // int -> smaller int
2320 else if (DestBits > SrcBits) { // its an extension
2322 return SExt; // signed -> SEXT
2324 return ZExt; // unsigned -> ZEXT
2326 return BitCast; // Same size, No-op cast
2328 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt
2330 return FPToSI; // FP -> sint
2332 return FPToUI; // FP -> uint
2333 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
2334 assert(DestBits == PTy->getBitWidth() &&
2335 "Casting vector to integer of different width");
2337 return BitCast; // Same size, no-op cast
2339 assert(isa<PointerType>(SrcTy) &&
2340 "Casting from a value that is not first-class type");
2341 return PtrToInt; // ptr -> int
2343 } else if (DestTy->isFloatingPoint()) { // Casting to floating pt
2344 if (SrcTy->isInteger()) { // Casting from integral
2346 return SIToFP; // sint -> FP
2348 return UIToFP; // uint -> FP
2349 } else if (SrcTy->isFloatingPoint()) { // Casting from floating pt
2350 if (DestBits < SrcBits) {
2351 return FPTrunc; // FP -> smaller FP
2352 } else if (DestBits > SrcBits) {
2353 return FPExt; // FP -> larger FP
2355 return BitCast; // same size, no-op cast
2357 } else if (const VectorType *PTy = dyn_cast<VectorType>(SrcTy)) {
2358 assert(DestBits == PTy->getBitWidth() &&
2359 "Casting vector to floating point of different width");
2361 return BitCast; // same size, no-op cast
2363 llvm_unreachable("Casting pointer or non-first class to float");
2365 } else if (const VectorType *DestPTy = dyn_cast<VectorType>(DestTy)) {
2366 if (const VectorType *SrcPTy = dyn_cast<VectorType>(SrcTy)) {
2367 assert(DestPTy->getBitWidth() == SrcPTy->getBitWidth() &&
2368 "Casting vector to vector of different widths");
2370 return BitCast; // vector -> vector
2371 } else if (DestPTy->getBitWidth() == SrcBits) {
2372 return BitCast; // float/int -> vector
2374 assert(!"Illegal cast to vector (wrong type or size)");
2376 } else if (isa<PointerType>(DestTy)) {
2377 if (isa<PointerType>(SrcTy)) {
2378 return BitCast; // ptr -> ptr
2379 } else if (SrcTy->isInteger()) {
2380 return IntToPtr; // int -> ptr
2382 assert(!"Casting pointer to other than pointer or int");
2385 assert(!"Casting to type that is not first-class");
2388 // If we fall through to here we probably hit an assertion cast above
2389 // and assertions are not turned on. Anything we return is an error, so
2390 // BitCast is as good a choice as any.
2394 //===----------------------------------------------------------------------===//
2395 // CastInst SubClass Constructors
2396 //===----------------------------------------------------------------------===//
2398 /// Check that the construction parameters for a CastInst are correct. This
2399 /// could be broken out into the separate constructors but it is useful to have
2400 /// it in one place and to eliminate the redundant code for getting the sizes
2401 /// of the types involved.
2403 CastInst::castIsValid(Instruction::CastOps op, Value *S, const Type *DstTy) {
2405 // Check for type sanity on the arguments
2406 const Type *SrcTy = S->getType();
2407 if (!SrcTy->isFirstClassType() || !DstTy->isFirstClassType())
2410 // Get the size of the types in bits, we'll need this later
2411 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
2412 unsigned DstBitSize = DstTy->getScalarSizeInBits();
2414 // Switch on the opcode provided
2416 default: return false; // This is an input error
2417 case Instruction::Trunc:
2418 return SrcTy->isIntOrIntVector() &&
2419 DstTy->isIntOrIntVector()&& SrcBitSize > DstBitSize;
2420 case Instruction::ZExt:
2421 return SrcTy->isIntOrIntVector() &&
2422 DstTy->isIntOrIntVector()&& SrcBitSize < DstBitSize;
2423 case Instruction::SExt:
2424 return SrcTy->isIntOrIntVector() &&
2425 DstTy->isIntOrIntVector()&& SrcBitSize < DstBitSize;
2426 case Instruction::FPTrunc:
2427 return SrcTy->isFPOrFPVector() &&
2428 DstTy->isFPOrFPVector() &&
2429 SrcBitSize > DstBitSize;
2430 case Instruction::FPExt:
2431 return SrcTy->isFPOrFPVector() &&
2432 DstTy->isFPOrFPVector() &&
2433 SrcBitSize < DstBitSize;
2434 case Instruction::UIToFP:
2435 case Instruction::SIToFP:
2436 if (const VectorType *SVTy = dyn_cast<VectorType>(SrcTy)) {
2437 if (const VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
2438 return SVTy->getElementType()->isIntOrIntVector() &&
2439 DVTy->getElementType()->isFPOrFPVector() &&
2440 SVTy->getNumElements() == DVTy->getNumElements();
2443 return SrcTy->isIntOrIntVector() && DstTy->isFPOrFPVector();
2444 case Instruction::FPToUI:
2445 case Instruction::FPToSI:
2446 if (const VectorType *SVTy = dyn_cast<VectorType>(SrcTy)) {
2447 if (const VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
2448 return SVTy->getElementType()->isFPOrFPVector() &&
2449 DVTy->getElementType()->isIntOrIntVector() &&
2450 SVTy->getNumElements() == DVTy->getNumElements();
2453 return SrcTy->isFPOrFPVector() && DstTy->isIntOrIntVector();
2454 case Instruction::PtrToInt:
2455 return isa<PointerType>(SrcTy) && DstTy->isInteger();
2456 case Instruction::IntToPtr:
2457 return SrcTy->isInteger() && isa<PointerType>(DstTy);
2458 case Instruction::BitCast:
2459 // BitCast implies a no-op cast of type only. No bits change.
2460 // However, you can't cast pointers to anything but pointers.
2461 if (isa<PointerType>(SrcTy) != isa<PointerType>(DstTy))
2464 // Now we know we're not dealing with a pointer/non-pointer mismatch. In all
2465 // these cases, the cast is okay if the source and destination bit widths
2467 return SrcTy->getPrimitiveSizeInBits() == DstTy->getPrimitiveSizeInBits();
2471 TruncInst::TruncInst(
2472 Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore
2473 ) : CastInst(Ty, Trunc, S, Name, InsertBefore) {
2474 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
2477 TruncInst::TruncInst(
2478 Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2479 ) : CastInst(Ty, Trunc, S, Name, InsertAtEnd) {
2480 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
2484 Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore
2485 ) : CastInst(Ty, ZExt, S, Name, InsertBefore) {
2486 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
2490 Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2491 ) : CastInst(Ty, ZExt, S, Name, InsertAtEnd) {
2492 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
2495 Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore
2496 ) : CastInst(Ty, SExt, S, Name, InsertBefore) {
2497 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
2501 Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2502 ) : CastInst(Ty, SExt, S, Name, InsertAtEnd) {
2503 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
2506 FPTruncInst::FPTruncInst(
2507 Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore
2508 ) : CastInst(Ty, FPTrunc, S, Name, InsertBefore) {
2509 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
2512 FPTruncInst::FPTruncInst(
2513 Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2514 ) : CastInst(Ty, FPTrunc, S, Name, InsertAtEnd) {
2515 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
2518 FPExtInst::FPExtInst(
2519 Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore
2520 ) : CastInst(Ty, FPExt, S, Name, InsertBefore) {
2521 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
2524 FPExtInst::FPExtInst(
2525 Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2526 ) : CastInst(Ty, FPExt, S, Name, InsertAtEnd) {
2527 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
2530 UIToFPInst::UIToFPInst(
2531 Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore
2532 ) : CastInst(Ty, UIToFP, S, Name, InsertBefore) {
2533 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
2536 UIToFPInst::UIToFPInst(
2537 Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2538 ) : CastInst(Ty, UIToFP, S, Name, InsertAtEnd) {
2539 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
2542 SIToFPInst::SIToFPInst(
2543 Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore
2544 ) : CastInst(Ty, SIToFP, S, Name, InsertBefore) {
2545 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
2548 SIToFPInst::SIToFPInst(
2549 Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2550 ) : CastInst(Ty, SIToFP, S, Name, InsertAtEnd) {
2551 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
2554 FPToUIInst::FPToUIInst(
2555 Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore
2556 ) : CastInst(Ty, FPToUI, S, Name, InsertBefore) {
2557 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
2560 FPToUIInst::FPToUIInst(
2561 Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2562 ) : CastInst(Ty, FPToUI, S, Name, InsertAtEnd) {
2563 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
2566 FPToSIInst::FPToSIInst(
2567 Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore
2568 ) : CastInst(Ty, FPToSI, S, Name, InsertBefore) {
2569 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
2572 FPToSIInst::FPToSIInst(
2573 Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2574 ) : CastInst(Ty, FPToSI, S, Name, InsertAtEnd) {
2575 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
2578 PtrToIntInst::PtrToIntInst(
2579 Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore
2580 ) : CastInst(Ty, PtrToInt, S, Name, InsertBefore) {
2581 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
2584 PtrToIntInst::PtrToIntInst(
2585 Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2586 ) : CastInst(Ty, PtrToInt, S, Name, InsertAtEnd) {
2587 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
2590 IntToPtrInst::IntToPtrInst(
2591 Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore
2592 ) : CastInst(Ty, IntToPtr, S, Name, InsertBefore) {
2593 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
2596 IntToPtrInst::IntToPtrInst(
2597 Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2598 ) : CastInst(Ty, IntToPtr, S, Name, InsertAtEnd) {
2599 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
2602 BitCastInst::BitCastInst(
2603 Value *S, const Type *Ty, const Twine &Name, Instruction *InsertBefore
2604 ) : CastInst(Ty, BitCast, S, Name, InsertBefore) {
2605 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
2608 BitCastInst::BitCastInst(
2609 Value *S, const Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2610 ) : CastInst(Ty, BitCast, S, Name, InsertAtEnd) {
2611 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
2614 //===----------------------------------------------------------------------===//
2616 //===----------------------------------------------------------------------===//
2618 CmpInst::CmpInst(const Type *ty, OtherOps op, unsigned short predicate,
2619 Value *LHS, Value *RHS, const Twine &Name,
2620 Instruction *InsertBefore)
2621 : Instruction(ty, op,
2622 OperandTraits<CmpInst>::op_begin(this),
2623 OperandTraits<CmpInst>::operands(this),
2627 SubclassData = predicate;
2631 CmpInst::CmpInst(const Type *ty, OtherOps op, unsigned short predicate,
2632 Value *LHS, Value *RHS, const Twine &Name,
2633 BasicBlock *InsertAtEnd)
2634 : Instruction(ty, op,
2635 OperandTraits<CmpInst>::op_begin(this),
2636 OperandTraits<CmpInst>::operands(this),
2640 SubclassData = predicate;
2645 CmpInst::Create(OtherOps Op, unsigned short predicate,
2646 Value *S1, Value *S2,
2647 const Twine &Name, Instruction *InsertBefore) {
2648 if (Op == Instruction::ICmp) {
2650 return new ICmpInst(InsertBefore, CmpInst::Predicate(predicate),
2653 return new ICmpInst(CmpInst::Predicate(predicate),
2658 return new FCmpInst(InsertBefore, CmpInst::Predicate(predicate),
2661 return new FCmpInst(CmpInst::Predicate(predicate),
2666 CmpInst::Create(OtherOps Op, unsigned short predicate, Value *S1, Value *S2,
2667 const Twine &Name, BasicBlock *InsertAtEnd) {
2668 if (Op == Instruction::ICmp) {
2669 return new ICmpInst(*InsertAtEnd, CmpInst::Predicate(predicate),
2672 return new FCmpInst(*InsertAtEnd, CmpInst::Predicate(predicate),
2676 void CmpInst::swapOperands() {
2677 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2680 cast<FCmpInst>(this)->swapOperands();
2683 bool CmpInst::isCommutative() {
2684 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2685 return IC->isCommutative();
2686 return cast<FCmpInst>(this)->isCommutative();
2689 bool CmpInst::isEquality() {
2690 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2691 return IC->isEquality();
2692 return cast<FCmpInst>(this)->isEquality();
2696 CmpInst::Predicate CmpInst::getInversePredicate(Predicate pred) {
2698 default: assert(!"Unknown cmp predicate!");
2699 case ICMP_EQ: return ICMP_NE;
2700 case ICMP_NE: return ICMP_EQ;
2701 case ICMP_UGT: return ICMP_ULE;
2702 case ICMP_ULT: return ICMP_UGE;
2703 case ICMP_UGE: return ICMP_ULT;
2704 case ICMP_ULE: return ICMP_UGT;
2705 case ICMP_SGT: return ICMP_SLE;
2706 case ICMP_SLT: return ICMP_SGE;
2707 case ICMP_SGE: return ICMP_SLT;
2708 case ICMP_SLE: return ICMP_SGT;
2710 case FCMP_OEQ: return FCMP_UNE;
2711 case FCMP_ONE: return FCMP_UEQ;
2712 case FCMP_OGT: return FCMP_ULE;
2713 case FCMP_OLT: return FCMP_UGE;
2714 case FCMP_OGE: return FCMP_ULT;
2715 case FCMP_OLE: return FCMP_UGT;
2716 case FCMP_UEQ: return FCMP_ONE;
2717 case FCMP_UNE: return FCMP_OEQ;
2718 case FCMP_UGT: return FCMP_OLE;
2719 case FCMP_ULT: return FCMP_OGE;
2720 case FCMP_UGE: return FCMP_OLT;
2721 case FCMP_ULE: return FCMP_OGT;
2722 case FCMP_ORD: return FCMP_UNO;
2723 case FCMP_UNO: return FCMP_ORD;
2724 case FCMP_TRUE: return FCMP_FALSE;
2725 case FCMP_FALSE: return FCMP_TRUE;
2729 ICmpInst::Predicate ICmpInst::getSignedPredicate(Predicate pred) {
2731 default: assert(! "Unknown icmp predicate!");
2732 case ICMP_EQ: case ICMP_NE:
2733 case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE:
2735 case ICMP_UGT: return ICMP_SGT;
2736 case ICMP_ULT: return ICMP_SLT;
2737 case ICMP_UGE: return ICMP_SGE;
2738 case ICMP_ULE: return ICMP_SLE;
2742 ICmpInst::Predicate ICmpInst::getUnsignedPredicate(Predicate pred) {
2744 default: assert(! "Unknown icmp predicate!");
2745 case ICMP_EQ: case ICMP_NE:
2746 case ICMP_UGT: case ICMP_ULT: case ICMP_UGE: case ICMP_ULE:
2748 case ICMP_SGT: return ICMP_UGT;
2749 case ICMP_SLT: return ICMP_ULT;
2750 case ICMP_SGE: return ICMP_UGE;
2751 case ICMP_SLE: return ICMP_ULE;
2755 bool ICmpInst::isSignedPredicate(Predicate pred) {
2757 default: assert(! "Unknown icmp predicate!");
2758 case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE:
2760 case ICMP_EQ: case ICMP_NE: case ICMP_UGT: case ICMP_ULT:
2761 case ICMP_UGE: case ICMP_ULE:
2766 /// Initialize a set of values that all satisfy the condition with C.
2769 ICmpInst::makeConstantRange(Predicate pred, const APInt &C) {
2772 uint32_t BitWidth = C.getBitWidth();
2774 default: llvm_unreachable("Invalid ICmp opcode to ConstantRange ctor!");
2775 case ICmpInst::ICMP_EQ: Upper++; break;
2776 case ICmpInst::ICMP_NE: Lower++; break;
2777 case ICmpInst::ICMP_ULT: Lower = APInt::getMinValue(BitWidth); break;
2778 case ICmpInst::ICMP_SLT: Lower = APInt::getSignedMinValue(BitWidth); break;
2779 case ICmpInst::ICMP_UGT:
2780 Lower++; Upper = APInt::getMinValue(BitWidth); // Min = Next(Max)
2782 case ICmpInst::ICMP_SGT:
2783 Lower++; Upper = APInt::getSignedMinValue(BitWidth); // Min = Next(Max)
2785 case ICmpInst::ICMP_ULE:
2786 Lower = APInt::getMinValue(BitWidth); Upper++;
2788 case ICmpInst::ICMP_SLE:
2789 Lower = APInt::getSignedMinValue(BitWidth); Upper++;
2791 case ICmpInst::ICMP_UGE:
2792 Upper = APInt::getMinValue(BitWidth); // Min = Next(Max)
2794 case ICmpInst::ICMP_SGE:
2795 Upper = APInt::getSignedMinValue(BitWidth); // Min = Next(Max)
2798 return ConstantRange(Lower, Upper);
2801 CmpInst::Predicate CmpInst::getSwappedPredicate(Predicate pred) {
2803 default: assert(!"Unknown cmp predicate!");
2804 case ICMP_EQ: case ICMP_NE:
2806 case ICMP_SGT: return ICMP_SLT;
2807 case ICMP_SLT: return ICMP_SGT;
2808 case ICMP_SGE: return ICMP_SLE;
2809 case ICMP_SLE: return ICMP_SGE;
2810 case ICMP_UGT: return ICMP_ULT;
2811 case ICMP_ULT: return ICMP_UGT;
2812 case ICMP_UGE: return ICMP_ULE;
2813 case ICMP_ULE: return ICMP_UGE;
2815 case FCMP_FALSE: case FCMP_TRUE:
2816 case FCMP_OEQ: case FCMP_ONE:
2817 case FCMP_UEQ: case FCMP_UNE:
2818 case FCMP_ORD: case FCMP_UNO:
2820 case FCMP_OGT: return FCMP_OLT;
2821 case FCMP_OLT: return FCMP_OGT;
2822 case FCMP_OGE: return FCMP_OLE;
2823 case FCMP_OLE: return FCMP_OGE;
2824 case FCMP_UGT: return FCMP_ULT;
2825 case FCMP_ULT: return FCMP_UGT;
2826 case FCMP_UGE: return FCMP_ULE;
2827 case FCMP_ULE: return FCMP_UGE;
2831 bool CmpInst::isUnsigned(unsigned short predicate) {
2832 switch (predicate) {
2833 default: return false;
2834 case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_ULE: case ICmpInst::ICMP_UGT:
2835 case ICmpInst::ICMP_UGE: return true;
2839 bool CmpInst::isSigned(unsigned short predicate){
2840 switch (predicate) {
2841 default: return false;
2842 case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_SLE: case ICmpInst::ICMP_SGT:
2843 case ICmpInst::ICMP_SGE: return true;
2847 bool CmpInst::isOrdered(unsigned short predicate) {
2848 switch (predicate) {
2849 default: return false;
2850 case FCmpInst::FCMP_OEQ: case FCmpInst::FCMP_ONE: case FCmpInst::FCMP_OGT:
2851 case FCmpInst::FCMP_OLT: case FCmpInst::FCMP_OGE: case FCmpInst::FCMP_OLE:
2852 case FCmpInst::FCMP_ORD: return true;
2856 bool CmpInst::isUnordered(unsigned short predicate) {
2857 switch (predicate) {
2858 default: return false;
2859 case FCmpInst::FCMP_UEQ: case FCmpInst::FCMP_UNE: case FCmpInst::FCMP_UGT:
2860 case FCmpInst::FCMP_ULT: case FCmpInst::FCMP_UGE: case FCmpInst::FCMP_ULE:
2861 case FCmpInst::FCMP_UNO: return true;
2865 //===----------------------------------------------------------------------===//
2866 // SwitchInst Implementation
2867 //===----------------------------------------------------------------------===//
2869 void SwitchInst::init(Value *Value, BasicBlock *Default, unsigned NumCases) {
2870 assert(Value && Default);
2871 ReservedSpace = 2+NumCases*2;
2873 OperandList = allocHungoffUses(ReservedSpace);
2875 OperandList[0] = Value;
2876 OperandList[1] = Default;
2879 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
2880 /// switch on and a default destination. The number of additional cases can
2881 /// be specified here to make memory allocation more efficient. This
2882 /// constructor can also autoinsert before another instruction.
2883 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
2884 Instruction *InsertBefore)
2885 : TerminatorInst(Type::getVoidTy(Value->getContext()), Instruction::Switch,
2886 0, 0, InsertBefore) {
2887 init(Value, Default, NumCases);
2890 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
2891 /// switch on and a default destination. The number of additional cases can
2892 /// be specified here to make memory allocation more efficient. This
2893 /// constructor also autoinserts at the end of the specified BasicBlock.
2894 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
2895 BasicBlock *InsertAtEnd)
2896 : TerminatorInst(Type::getVoidTy(Value->getContext()), Instruction::Switch,
2897 0, 0, InsertAtEnd) {
2898 init(Value, Default, NumCases);
2901 SwitchInst::SwitchInst(const SwitchInst &SI)
2902 : TerminatorInst(Type::getVoidTy(SI.getContext()), Instruction::Switch,
2903 allocHungoffUses(SI.getNumOperands()), SI.getNumOperands()) {
2904 Use *OL = OperandList, *InOL = SI.OperandList;
2905 for (unsigned i = 0, E = SI.getNumOperands(); i != E; i+=2) {
2907 OL[i+1] = InOL[i+1];
2909 SubclassOptionalData = SI.SubclassOptionalData;
2912 SwitchInst::~SwitchInst() {
2913 dropHungoffUses(OperandList);
2917 /// addCase - Add an entry to the switch instruction...
2919 void SwitchInst::addCase(ConstantInt *OnVal, BasicBlock *Dest) {
2920 unsigned OpNo = NumOperands;
2921 if (OpNo+2 > ReservedSpace)
2922 resizeOperands(0); // Get more space!
2923 // Initialize some new operands.
2924 assert(OpNo+1 < ReservedSpace && "Growing didn't work!");
2925 NumOperands = OpNo+2;
2926 OperandList[OpNo] = OnVal;
2927 OperandList[OpNo+1] = Dest;
2930 /// removeCase - This method removes the specified successor from the switch
2931 /// instruction. Note that this cannot be used to remove the default
2932 /// destination (successor #0).
2934 void SwitchInst::removeCase(unsigned idx) {
2935 assert(idx != 0 && "Cannot remove the default case!");
2936 assert(idx*2 < getNumOperands() && "Successor index out of range!!!");
2938 unsigned NumOps = getNumOperands();
2939 Use *OL = OperandList;
2941 // Move everything after this operand down.
2943 // FIXME: we could just swap with the end of the list, then erase. However,
2944 // client might not expect this to happen. The code as it is thrashes the
2945 // use/def lists, which is kinda lame.
2946 for (unsigned i = (idx+1)*2; i != NumOps; i += 2) {
2948 OL[i-2+1] = OL[i+1];
2951 // Nuke the last value.
2952 OL[NumOps-2].set(0);
2953 OL[NumOps-2+1].set(0);
2954 NumOperands = NumOps-2;
2957 /// resizeOperands - resize operands - This adjusts the length of the operands
2958 /// list according to the following behavior:
2959 /// 1. If NumOps == 0, grow the operand list in response to a push_back style
2960 /// of operation. This grows the number of ops by 3 times.
2961 /// 2. If NumOps > NumOperands, reserve space for NumOps operands.
2962 /// 3. If NumOps == NumOperands, trim the reserved space.
2964 void SwitchInst::resizeOperands(unsigned NumOps) {
2965 unsigned e = getNumOperands();
2968 } else if (NumOps*2 > NumOperands) {
2969 // No resize needed.
2970 if (ReservedSpace >= NumOps) return;
2971 } else if (NumOps == NumOperands) {
2972 if (ReservedSpace == NumOps) return;
2977 ReservedSpace = NumOps;
2978 Use *NewOps = allocHungoffUses(NumOps);
2979 Use *OldOps = OperandList;
2980 for (unsigned i = 0; i != e; ++i) {
2981 NewOps[i] = OldOps[i];
2983 OperandList = NewOps;
2984 if (OldOps) Use::zap(OldOps, OldOps + e, true);
2988 BasicBlock *SwitchInst::getSuccessorV(unsigned idx) const {
2989 return getSuccessor(idx);
2991 unsigned SwitchInst::getNumSuccessorsV() const {
2992 return getNumSuccessors();
2994 void SwitchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
2995 setSuccessor(idx, B);
2998 // Define these methods here so vtables don't get emitted into every translation
2999 // unit that uses these classes.
3001 GetElementPtrInst *GetElementPtrInst::clone(LLVMContext&) const {
3002 GetElementPtrInst *New = new(getNumOperands()) GetElementPtrInst(*this);
3003 New->SubclassOptionalData = SubclassOptionalData;
3007 BinaryOperator *BinaryOperator::clone(LLVMContext&) const {
3008 BinaryOperator *New = Create(getOpcode(), Op<0>(), Op<1>());
3009 New->SubclassOptionalData = SubclassOptionalData;
3013 FCmpInst* FCmpInst::clone(LLVMContext &Context) const {
3014 FCmpInst *New = new FCmpInst(getPredicate(), Op<0>(), Op<1>());
3015 New->SubclassOptionalData = SubclassOptionalData;
3018 ICmpInst* ICmpInst::clone(LLVMContext &Context) const {
3019 ICmpInst *New = new ICmpInst(getPredicate(), Op<0>(), Op<1>());
3020 New->SubclassOptionalData = SubclassOptionalData;
3024 ExtractValueInst *ExtractValueInst::clone(LLVMContext&) const {
3025 ExtractValueInst *New = new ExtractValueInst(*this);
3026 New->SubclassOptionalData = SubclassOptionalData;
3029 InsertValueInst *InsertValueInst::clone(LLVMContext&) const {
3030 InsertValueInst *New = new InsertValueInst(*this);
3031 New->SubclassOptionalData = SubclassOptionalData;
3035 MallocInst *MallocInst::clone(LLVMContext&) const {
3036 MallocInst *New = new MallocInst(getAllocatedType(),
3037 (Value*)getOperand(0),
3039 New->SubclassOptionalData = SubclassOptionalData;
3043 AllocaInst *AllocaInst::clone(LLVMContext&) const {
3044 AllocaInst *New = new AllocaInst(getAllocatedType(),
3045 (Value*)getOperand(0),
3047 New->SubclassOptionalData = SubclassOptionalData;
3051 FreeInst *FreeInst::clone(LLVMContext&) const {
3052 FreeInst *New = new FreeInst(getOperand(0));
3053 New->SubclassOptionalData = SubclassOptionalData;
3057 LoadInst *LoadInst::clone(LLVMContext&) const {
3058 LoadInst *New = new LoadInst(getOperand(0),
3059 Twine(), isVolatile(),
3061 New->SubclassOptionalData = SubclassOptionalData;
3065 StoreInst *StoreInst::clone(LLVMContext&) const {
3066 StoreInst *New = new StoreInst(getOperand(0), getOperand(1),
3067 isVolatile(), getAlignment());
3068 New->SubclassOptionalData = SubclassOptionalData;
3072 TruncInst *TruncInst::clone(LLVMContext&) const {
3073 TruncInst *New = new TruncInst(getOperand(0), getType());
3074 New->SubclassOptionalData = SubclassOptionalData;
3078 ZExtInst *ZExtInst::clone(LLVMContext&) const {
3079 ZExtInst *New = new ZExtInst(getOperand(0), getType());
3080 New->SubclassOptionalData = SubclassOptionalData;
3084 SExtInst *SExtInst::clone(LLVMContext&) const {
3085 SExtInst *New = new SExtInst(getOperand(0), getType());
3086 New->SubclassOptionalData = SubclassOptionalData;
3090 FPTruncInst *FPTruncInst::clone(LLVMContext&) const {
3091 FPTruncInst *New = new FPTruncInst(getOperand(0), getType());
3092 New->SubclassOptionalData = SubclassOptionalData;
3096 FPExtInst *FPExtInst::clone(LLVMContext&) const {
3097 FPExtInst *New = new FPExtInst(getOperand(0), getType());
3098 New->SubclassOptionalData = SubclassOptionalData;
3102 UIToFPInst *UIToFPInst::clone(LLVMContext&) const {
3103 UIToFPInst *New = new UIToFPInst(getOperand(0), getType());
3104 New->SubclassOptionalData = SubclassOptionalData;
3108 SIToFPInst *SIToFPInst::clone(LLVMContext&) const {
3109 SIToFPInst *New = new SIToFPInst(getOperand(0), getType());
3110 New->SubclassOptionalData = SubclassOptionalData;
3114 FPToUIInst *FPToUIInst::clone(LLVMContext&) const {
3115 FPToUIInst *New = new FPToUIInst(getOperand(0), getType());
3116 New->SubclassOptionalData = SubclassOptionalData;
3120 FPToSIInst *FPToSIInst::clone(LLVMContext&) const {
3121 FPToSIInst *New = new FPToSIInst(getOperand(0), getType());
3122 New->SubclassOptionalData = SubclassOptionalData;
3126 PtrToIntInst *PtrToIntInst::clone(LLVMContext&) const {
3127 PtrToIntInst *New = new PtrToIntInst(getOperand(0), getType());
3128 New->SubclassOptionalData = SubclassOptionalData;
3132 IntToPtrInst *IntToPtrInst::clone(LLVMContext&) const {
3133 IntToPtrInst *New = new IntToPtrInst(getOperand(0), getType());
3134 New->SubclassOptionalData = SubclassOptionalData;
3138 BitCastInst *BitCastInst::clone(LLVMContext&) const {
3139 BitCastInst *New = new BitCastInst(getOperand(0), getType());
3140 New->SubclassOptionalData = SubclassOptionalData;
3144 CallInst *CallInst::clone(LLVMContext&) const {
3145 CallInst *New = new(getNumOperands()) CallInst(*this);
3146 New->SubclassOptionalData = SubclassOptionalData;
3150 SelectInst *SelectInst::clone(LLVMContext&) const {
3151 SelectInst *New = SelectInst::Create(getOperand(0),
3154 New->SubclassOptionalData = SubclassOptionalData;
3158 VAArgInst *VAArgInst::clone(LLVMContext&) const {
3159 VAArgInst *New = new VAArgInst(getOperand(0), getType());
3160 New->SubclassOptionalData = SubclassOptionalData;
3164 ExtractElementInst *ExtractElementInst::clone(LLVMContext&) const {
3165 ExtractElementInst *New = ExtractElementInst::Create(getOperand(0),
3167 New->SubclassOptionalData = SubclassOptionalData;
3171 InsertElementInst *InsertElementInst::clone(LLVMContext&) const {
3172 InsertElementInst *New = InsertElementInst::Create(getOperand(0),
3175 New->SubclassOptionalData = SubclassOptionalData;
3179 ShuffleVectorInst *ShuffleVectorInst::clone(LLVMContext&) const {
3180 ShuffleVectorInst *New = new ShuffleVectorInst(getOperand(0),
3183 New->SubclassOptionalData = SubclassOptionalData;
3187 PHINode *PHINode::clone(LLVMContext&) const {
3188 PHINode *New = new PHINode(*this);
3189 New->SubclassOptionalData = SubclassOptionalData;
3193 ReturnInst *ReturnInst::clone(LLVMContext&) const {
3194 ReturnInst *New = new(getNumOperands()) ReturnInst(*this);
3195 New->SubclassOptionalData = SubclassOptionalData;
3199 BranchInst *BranchInst::clone(LLVMContext&) const {
3200 unsigned Ops(getNumOperands());
3201 BranchInst *New = new(Ops, Ops == 1) BranchInst(*this);
3202 New->SubclassOptionalData = SubclassOptionalData;
3206 SwitchInst *SwitchInst::clone(LLVMContext&) const {
3207 SwitchInst *New = new SwitchInst(*this);
3208 New->SubclassOptionalData = SubclassOptionalData;
3212 InvokeInst *InvokeInst::clone(LLVMContext&) const {
3213 InvokeInst *New = new(getNumOperands()) InvokeInst(*this);
3214 New->SubclassOptionalData = SubclassOptionalData;
3218 UnwindInst *UnwindInst::clone(LLVMContext &C) const {
3219 UnwindInst *New = new UnwindInst(C);
3220 New->SubclassOptionalData = SubclassOptionalData;
3224 UnreachableInst *UnreachableInst::clone(LLVMContext &C) const {
3225 UnreachableInst *New = new UnreachableInst(C);
3226 New->SubclassOptionalData = SubclassOptionalData;