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 "LLVMContextImpl.h"
16 #include "llvm/Constants.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/Function.h"
19 #include "llvm/Instructions.h"
20 #include "llvm/Module.h"
21 #include "llvm/Operator.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 User::op_iterator CallSite::getCallee() const {
33 Instruction *II(getInstruction());
35 ? cast<CallInst>(II)->op_end() - 1 // Skip Callee
36 : cast<InvokeInst>(II)->op_end() - 3; // Skip BB, BB, Callee
39 //===----------------------------------------------------------------------===//
40 // TerminatorInst Class
41 //===----------------------------------------------------------------------===//
43 // Out of line virtual method, so the vtable, etc has a home.
44 TerminatorInst::~TerminatorInst() {
47 //===----------------------------------------------------------------------===//
48 // UnaryInstruction Class
49 //===----------------------------------------------------------------------===//
51 // Out of line virtual method, so the vtable, etc has a home.
52 UnaryInstruction::~UnaryInstruction() {
55 //===----------------------------------------------------------------------===//
57 //===----------------------------------------------------------------------===//
59 /// areInvalidOperands - Return a string if the specified operands are invalid
60 /// for a select operation, otherwise return null.
61 const char *SelectInst::areInvalidOperands(Value *Op0, Value *Op1, Value *Op2) {
62 if (Op1->getType() != Op2->getType())
63 return "both values to select must have same type";
65 if (VectorType *VT = dyn_cast<VectorType>(Op0->getType())) {
67 if (VT->getElementType() != Type::getInt1Ty(Op0->getContext()))
68 return "vector select condition element type must be i1";
69 VectorType *ET = dyn_cast<VectorType>(Op1->getType());
71 return "selected values for vector select must be vectors";
72 if (ET->getNumElements() != VT->getNumElements())
73 return "vector select requires selected vectors to have "
74 "the same vector length as select condition";
75 } else if (Op0->getType() != Type::getInt1Ty(Op0->getContext())) {
76 return "select condition must be i1 or <n x i1>";
82 //===----------------------------------------------------------------------===//
84 //===----------------------------------------------------------------------===//
86 PHINode::PHINode(const PHINode &PN)
87 : Instruction(PN.getType(), Instruction::PHI,
88 allocHungoffUses(PN.getNumOperands()), PN.getNumOperands()),
89 ReservedSpace(PN.getNumOperands()) {
90 std::copy(PN.op_begin(), PN.op_end(), op_begin());
91 std::copy(PN.block_begin(), PN.block_end(), block_begin());
92 SubclassOptionalData = PN.SubclassOptionalData;
99 Use *PHINode::allocHungoffUses(unsigned N) const {
100 // Allocate the array of Uses of the incoming values, followed by a pointer
101 // (with bottom bit set) to the User, followed by the array of pointers to
102 // the incoming basic blocks.
103 size_t size = N * sizeof(Use) + sizeof(Use::UserRef)
104 + N * sizeof(BasicBlock*);
105 Use *Begin = static_cast<Use*>(::operator new(size));
106 Use *End = Begin + N;
107 (void) new(End) Use::UserRef(const_cast<PHINode*>(this), 1);
108 return Use::initTags(Begin, End);
111 // removeIncomingValue - Remove an incoming value. This is useful if a
112 // predecessor basic block is deleted.
113 Value *PHINode::removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty) {
114 Value *Removed = getIncomingValue(Idx);
116 // Move everything after this operand down.
118 // FIXME: we could just swap with the end of the list, then erase. However,
119 // clients might not expect this to happen. The code as it is thrashes the
120 // use/def lists, which is kinda lame.
121 std::copy(op_begin() + Idx + 1, op_end(), op_begin() + Idx);
122 std::copy(block_begin() + Idx + 1, block_end(), block_begin() + Idx);
124 // Nuke the last value.
128 // If the PHI node is dead, because it has zero entries, nuke it now.
129 if (getNumOperands() == 0 && DeletePHIIfEmpty) {
130 // If anyone is using this PHI, make them use a dummy value instead...
131 replaceAllUsesWith(UndefValue::get(getType()));
137 /// growOperands - grow operands - This grows the operand list in response
138 /// to a push_back style of operation. This grows the number of ops by 1.5
141 void PHINode::growOperands() {
142 unsigned e = getNumOperands();
143 unsigned NumOps = e + e / 2;
144 if (NumOps < 2) NumOps = 2; // 2 op PHI nodes are VERY common.
146 Use *OldOps = op_begin();
147 BasicBlock **OldBlocks = block_begin();
149 ReservedSpace = NumOps;
150 OperandList = allocHungoffUses(ReservedSpace);
152 std::copy(OldOps, OldOps + e, op_begin());
153 std::copy(OldBlocks, OldBlocks + e, block_begin());
155 Use::zap(OldOps, OldOps + e, true);
158 /// hasConstantValue - If the specified PHI node always merges together the same
159 /// value, return the value, otherwise return null.
160 Value *PHINode::hasConstantValue() const {
161 // Exploit the fact that phi nodes always have at least one entry.
162 Value *ConstantValue = getIncomingValue(0);
163 for (unsigned i = 1, e = getNumIncomingValues(); i != e; ++i)
164 if (getIncomingValue(i) != ConstantValue)
165 return 0; // Incoming values not all the same.
166 return ConstantValue;
169 //===----------------------------------------------------------------------===//
170 // LandingPadInst Implementation
171 //===----------------------------------------------------------------------===//
173 void LandingPadInst::init(Function *PersFn, unsigned NumReservedValues,
174 const Twine &NameStr) {
175 ReservedSpace = NumReservedValues;
177 OperandList = allocHungoffUses(ReservedSpace);
178 OperandList[0] = (Value*)PersFn;
182 LandingPadInst::LandingPadInst(const LandingPadInst &LP)
183 : Instruction(LP.getType(), Instruction::LandingPad,
184 allocHungoffUses(LP.getNumOperands()), LP.getNumOperands()),
185 ReservedSpace(LP.getNumOperands()) {
186 Use *OL = OperandList, *InOL = LP.OperandList;
187 for (unsigned I = 0, E = ReservedSpace; I != E; ++I)
190 for (SmallVectorImpl<ClauseType>::const_iterator
191 I = LP.ClauseIdxs.begin(), E = LP.ClauseIdxs.end(); I != E; ++I)
192 ClauseIdxs.push_back(*I);
194 IsCleanup = LP.IsCleanup;
195 SubclassOptionalData = LP.SubclassOptionalData;
198 LandingPadInst::~LandingPadInst() {
202 /// growOperands - grow operands - This grows the operand list in response to a
203 /// push_back style of operation. This grows the number of ops by 2 times.
204 void LandingPadInst::growOperands() {
205 unsigned e = getNumOperands();
206 ReservedSpace = e * 2;
208 Use *NewOps = allocHungoffUses(ReservedSpace);
209 Use *OldOps = OperandList;
210 for (unsigned i = 0; i != e; ++i)
211 NewOps[i] = OldOps[i];
213 OperandList = NewOps;
214 Use::zap(OldOps, OldOps + e, true);
217 void LandingPadInst::reserveClauses(unsigned Size) {
218 unsigned e = getNumOperands();
219 if (ReservedSpace >= e + Size) return;
220 ReservedSpace = e + Size;
222 Use *NewOps = allocHungoffUses(ReservedSpace);
223 Use *OldOps = OperandList;
224 for (unsigned i = 0; i != e; ++i)
225 NewOps[i] = OldOps[i];
227 OperandList = NewOps;
228 Use::zap(OldOps, OldOps + e, true);
231 void LandingPadInst::addClause(ClauseType CT, Constant *ClauseVal) {
232 unsigned OpNo = getNumOperands();
233 if (OpNo + 1 > ReservedSpace)
235 assert(OpNo < ReservedSpace && "Growing didn't work!");
236 ClauseIdxs.push_back(CT);
238 OperandList[OpNo] = (Value*)ClauseVal;
241 //===----------------------------------------------------------------------===//
242 // CallInst Implementation
243 //===----------------------------------------------------------------------===//
245 CallInst::~CallInst() {
248 void CallInst::init(Value *Func, ArrayRef<Value *> Args, const Twine &NameStr) {
249 assert(NumOperands == Args.size() + 1 && "NumOperands not set up?");
254 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
256 assert((Args.size() == FTy->getNumParams() ||
257 (FTy->isVarArg() && Args.size() > FTy->getNumParams())) &&
258 "Calling a function with bad signature!");
260 for (unsigned i = 0; i != Args.size(); ++i)
261 assert((i >= FTy->getNumParams() ||
262 FTy->getParamType(i) == Args[i]->getType()) &&
263 "Calling a function with a bad signature!");
266 std::copy(Args.begin(), Args.end(), op_begin());
270 void CallInst::init(Value *Func, const Twine &NameStr) {
271 assert(NumOperands == 1 && "NumOperands not set up?");
276 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
278 assert(FTy->getNumParams() == 0 && "Calling a function with bad signature");
284 CallInst::CallInst(Value *Func, const Twine &Name,
285 Instruction *InsertBefore)
286 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
287 ->getElementType())->getReturnType(),
289 OperandTraits<CallInst>::op_end(this) - 1,
294 CallInst::CallInst(Value *Func, const Twine &Name,
295 BasicBlock *InsertAtEnd)
296 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
297 ->getElementType())->getReturnType(),
299 OperandTraits<CallInst>::op_end(this) - 1,
304 CallInst::CallInst(const CallInst &CI)
305 : Instruction(CI.getType(), Instruction::Call,
306 OperandTraits<CallInst>::op_end(this) - CI.getNumOperands(),
307 CI.getNumOperands()) {
308 setAttributes(CI.getAttributes());
309 setTailCall(CI.isTailCall());
310 setCallingConv(CI.getCallingConv());
312 std::copy(CI.op_begin(), CI.op_end(), op_begin());
313 SubclassOptionalData = CI.SubclassOptionalData;
316 void CallInst::addAttribute(unsigned i, Attributes attr) {
317 AttrListPtr PAL = getAttributes();
318 PAL = PAL.addAttr(i, attr);
322 void CallInst::removeAttribute(unsigned i, Attributes attr) {
323 AttrListPtr PAL = getAttributes();
324 PAL = PAL.removeAttr(i, attr);
328 bool CallInst::paramHasAttr(unsigned i, Attributes attr) const {
329 if (AttributeList.paramHasAttr(i, attr))
331 if (const Function *F = getCalledFunction())
332 return F->paramHasAttr(i, attr);
336 /// IsConstantOne - Return true only if val is constant int 1
337 static bool IsConstantOne(Value *val) {
338 assert(val && "IsConstantOne does not work with NULL val");
339 return isa<ConstantInt>(val) && cast<ConstantInt>(val)->isOne();
342 static Instruction *createMalloc(Instruction *InsertBefore,
343 BasicBlock *InsertAtEnd, Type *IntPtrTy,
344 Type *AllocTy, Value *AllocSize,
345 Value *ArraySize, Function *MallocF,
347 assert(((!InsertBefore && InsertAtEnd) || (InsertBefore && !InsertAtEnd)) &&
348 "createMalloc needs either InsertBefore or InsertAtEnd");
350 // malloc(type) becomes:
351 // bitcast (i8* malloc(typeSize)) to type*
352 // malloc(type, arraySize) becomes:
353 // bitcast (i8 *malloc(typeSize*arraySize)) to type*
355 ArraySize = ConstantInt::get(IntPtrTy, 1);
356 else if (ArraySize->getType() != IntPtrTy) {
358 ArraySize = CastInst::CreateIntegerCast(ArraySize, IntPtrTy, false,
361 ArraySize = CastInst::CreateIntegerCast(ArraySize, IntPtrTy, false,
365 if (!IsConstantOne(ArraySize)) {
366 if (IsConstantOne(AllocSize)) {
367 AllocSize = ArraySize; // Operand * 1 = Operand
368 } else if (Constant *CO = dyn_cast<Constant>(ArraySize)) {
369 Constant *Scale = ConstantExpr::getIntegerCast(CO, IntPtrTy,
371 // Malloc arg is constant product of type size and array size
372 AllocSize = ConstantExpr::getMul(Scale, cast<Constant>(AllocSize));
374 // Multiply type size by the array size...
376 AllocSize = BinaryOperator::CreateMul(ArraySize, AllocSize,
377 "mallocsize", InsertBefore);
379 AllocSize = BinaryOperator::CreateMul(ArraySize, AllocSize,
380 "mallocsize", InsertAtEnd);
384 assert(AllocSize->getType() == IntPtrTy && "malloc arg is wrong size");
385 // Create the call to Malloc.
386 BasicBlock* BB = InsertBefore ? InsertBefore->getParent() : InsertAtEnd;
387 Module* M = BB->getParent()->getParent();
388 Type *BPTy = Type::getInt8PtrTy(BB->getContext());
389 Value *MallocFunc = MallocF;
391 // prototype malloc as "void *malloc(size_t)"
392 MallocFunc = M->getOrInsertFunction("malloc", BPTy, IntPtrTy, NULL);
393 PointerType *AllocPtrType = PointerType::getUnqual(AllocTy);
394 CallInst *MCall = NULL;
395 Instruction *Result = NULL;
397 MCall = CallInst::Create(MallocFunc, AllocSize, "malloccall", InsertBefore);
399 if (Result->getType() != AllocPtrType)
400 // Create a cast instruction to convert to the right type...
401 Result = new BitCastInst(MCall, AllocPtrType, Name, InsertBefore);
403 MCall = CallInst::Create(MallocFunc, AllocSize, "malloccall");
405 if (Result->getType() != AllocPtrType) {
406 InsertAtEnd->getInstList().push_back(MCall);
407 // Create a cast instruction to convert to the right type...
408 Result = new BitCastInst(MCall, AllocPtrType, Name);
411 MCall->setTailCall();
412 if (Function *F = dyn_cast<Function>(MallocFunc)) {
413 MCall->setCallingConv(F->getCallingConv());
414 if (!F->doesNotAlias(0)) F->setDoesNotAlias(0);
416 assert(!MCall->getType()->isVoidTy() && "Malloc has void return type");
421 /// CreateMalloc - Generate the IR for a call to malloc:
422 /// 1. Compute the malloc call's argument as the specified type's size,
423 /// possibly multiplied by the array size if the array size is not
425 /// 2. Call malloc with that argument.
426 /// 3. Bitcast the result of the malloc call to the specified type.
427 Instruction *CallInst::CreateMalloc(Instruction *InsertBefore,
428 Type *IntPtrTy, Type *AllocTy,
429 Value *AllocSize, Value *ArraySize,
432 return createMalloc(InsertBefore, NULL, IntPtrTy, AllocTy, AllocSize,
433 ArraySize, MallocF, Name);
436 /// CreateMalloc - Generate the IR for a call to malloc:
437 /// 1. Compute the malloc call's argument as the specified type's size,
438 /// possibly multiplied by the array size if the array size is not
440 /// 2. Call malloc with that argument.
441 /// 3. Bitcast the result of the malloc call to the specified type.
442 /// Note: This function does not add the bitcast to the basic block, that is the
443 /// responsibility of the caller.
444 Instruction *CallInst::CreateMalloc(BasicBlock *InsertAtEnd,
445 Type *IntPtrTy, Type *AllocTy,
446 Value *AllocSize, Value *ArraySize,
447 Function *MallocF, const Twine &Name) {
448 return createMalloc(NULL, InsertAtEnd, IntPtrTy, AllocTy, AllocSize,
449 ArraySize, MallocF, Name);
452 static Instruction* createFree(Value* Source, Instruction *InsertBefore,
453 BasicBlock *InsertAtEnd) {
454 assert(((!InsertBefore && InsertAtEnd) || (InsertBefore && !InsertAtEnd)) &&
455 "createFree needs either InsertBefore or InsertAtEnd");
456 assert(Source->getType()->isPointerTy() &&
457 "Can not free something of nonpointer type!");
459 BasicBlock* BB = InsertBefore ? InsertBefore->getParent() : InsertAtEnd;
460 Module* M = BB->getParent()->getParent();
462 Type *VoidTy = Type::getVoidTy(M->getContext());
463 Type *IntPtrTy = Type::getInt8PtrTy(M->getContext());
464 // prototype free as "void free(void*)"
465 Value *FreeFunc = M->getOrInsertFunction("free", VoidTy, IntPtrTy, NULL);
466 CallInst* Result = NULL;
467 Value *PtrCast = Source;
469 if (Source->getType() != IntPtrTy)
470 PtrCast = new BitCastInst(Source, IntPtrTy, "", InsertBefore);
471 Result = CallInst::Create(FreeFunc, PtrCast, "", InsertBefore);
473 if (Source->getType() != IntPtrTy)
474 PtrCast = new BitCastInst(Source, IntPtrTy, "", InsertAtEnd);
475 Result = CallInst::Create(FreeFunc, PtrCast, "");
477 Result->setTailCall();
478 if (Function *F = dyn_cast<Function>(FreeFunc))
479 Result->setCallingConv(F->getCallingConv());
484 /// CreateFree - Generate the IR for a call to the builtin free function.
485 Instruction * CallInst::CreateFree(Value* Source, Instruction *InsertBefore) {
486 return createFree(Source, InsertBefore, NULL);
489 /// CreateFree - Generate the IR for a call to the builtin free function.
490 /// Note: This function does not add the call to the basic block, that is the
491 /// responsibility of the caller.
492 Instruction* CallInst::CreateFree(Value* Source, BasicBlock *InsertAtEnd) {
493 Instruction* FreeCall = createFree(Source, NULL, InsertAtEnd);
494 assert(FreeCall && "CreateFree did not create a CallInst");
498 //===----------------------------------------------------------------------===//
499 // InvokeInst Implementation
500 //===----------------------------------------------------------------------===//
502 void InvokeInst::init(Value *Fn, BasicBlock *IfNormal, BasicBlock *IfException,
503 ArrayRef<Value *> Args, const Twine &NameStr) {
504 assert(NumOperands == 3 + Args.size() && "NumOperands not set up?");
507 Op<-1>() = IfException;
511 cast<FunctionType>(cast<PointerType>(Fn->getType())->getElementType());
513 assert(((Args.size() == FTy->getNumParams()) ||
514 (FTy->isVarArg() && Args.size() > FTy->getNumParams())) &&
515 "Invoking a function with bad signature");
517 for (unsigned i = 0, e = Args.size(); i != e; i++)
518 assert((i >= FTy->getNumParams() ||
519 FTy->getParamType(i) == Args[i]->getType()) &&
520 "Invoking a function with a bad signature!");
523 std::copy(Args.begin(), Args.end(), op_begin());
527 InvokeInst::InvokeInst(const InvokeInst &II)
528 : TerminatorInst(II.getType(), Instruction::Invoke,
529 OperandTraits<InvokeInst>::op_end(this)
530 - II.getNumOperands(),
531 II.getNumOperands()) {
532 setAttributes(II.getAttributes());
533 setCallingConv(II.getCallingConv());
534 std::copy(II.op_begin(), II.op_end(), op_begin());
535 SubclassOptionalData = II.SubclassOptionalData;
538 BasicBlock *InvokeInst::getSuccessorV(unsigned idx) const {
539 return getSuccessor(idx);
541 unsigned InvokeInst::getNumSuccessorsV() const {
542 return getNumSuccessors();
544 void InvokeInst::setSuccessorV(unsigned idx, BasicBlock *B) {
545 return setSuccessor(idx, B);
548 bool InvokeInst::paramHasAttr(unsigned i, Attributes attr) const {
549 if (AttributeList.paramHasAttr(i, attr))
551 if (const Function *F = getCalledFunction())
552 return F->paramHasAttr(i, attr);
556 void InvokeInst::addAttribute(unsigned i, Attributes attr) {
557 AttrListPtr PAL = getAttributes();
558 PAL = PAL.addAttr(i, attr);
562 void InvokeInst::removeAttribute(unsigned i, Attributes attr) {
563 AttrListPtr PAL = getAttributes();
564 PAL = PAL.removeAttr(i, attr);
568 LandingPadInst *InvokeInst::getLandingPad() const {
569 return cast<LandingPadInst>(getUnwindDest()->getFirstNonPHI());
572 //===----------------------------------------------------------------------===//
573 // ReturnInst Implementation
574 //===----------------------------------------------------------------------===//
576 ReturnInst::ReturnInst(const ReturnInst &RI)
577 : TerminatorInst(Type::getVoidTy(RI.getContext()), Instruction::Ret,
578 OperandTraits<ReturnInst>::op_end(this) -
580 RI.getNumOperands()) {
581 if (RI.getNumOperands())
582 Op<0>() = RI.Op<0>();
583 SubclassOptionalData = RI.SubclassOptionalData;
586 ReturnInst::ReturnInst(LLVMContext &C, Value *retVal, Instruction *InsertBefore)
587 : TerminatorInst(Type::getVoidTy(C), Instruction::Ret,
588 OperandTraits<ReturnInst>::op_end(this) - !!retVal, !!retVal,
593 ReturnInst::ReturnInst(LLVMContext &C, Value *retVal, BasicBlock *InsertAtEnd)
594 : TerminatorInst(Type::getVoidTy(C), Instruction::Ret,
595 OperandTraits<ReturnInst>::op_end(this) - !!retVal, !!retVal,
600 ReturnInst::ReturnInst(LLVMContext &Context, BasicBlock *InsertAtEnd)
601 : TerminatorInst(Type::getVoidTy(Context), Instruction::Ret,
602 OperandTraits<ReturnInst>::op_end(this), 0, InsertAtEnd) {
605 unsigned ReturnInst::getNumSuccessorsV() const {
606 return getNumSuccessors();
609 /// Out-of-line ReturnInst method, put here so the C++ compiler can choose to
610 /// emit the vtable for the class in this translation unit.
611 void ReturnInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
612 llvm_unreachable("ReturnInst has no successors!");
615 BasicBlock *ReturnInst::getSuccessorV(unsigned idx) const {
616 llvm_unreachable("ReturnInst has no successors!");
620 ReturnInst::~ReturnInst() {
623 //===----------------------------------------------------------------------===//
624 // UnwindInst Implementation
625 //===----------------------------------------------------------------------===//
627 UnwindInst::UnwindInst(LLVMContext &Context, Instruction *InsertBefore)
628 : TerminatorInst(Type::getVoidTy(Context), Instruction::Unwind,
629 0, 0, InsertBefore) {
631 UnwindInst::UnwindInst(LLVMContext &Context, BasicBlock *InsertAtEnd)
632 : TerminatorInst(Type::getVoidTy(Context), Instruction::Unwind,
637 unsigned UnwindInst::getNumSuccessorsV() const {
638 return getNumSuccessors();
641 void UnwindInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
642 llvm_unreachable("UnwindInst has no successors!");
645 BasicBlock *UnwindInst::getSuccessorV(unsigned idx) const {
646 llvm_unreachable("UnwindInst has no successors!");
650 //===----------------------------------------------------------------------===//
651 // ResumeInst Implementation
652 //===----------------------------------------------------------------------===//
654 ResumeInst::ResumeInst(const ResumeInst &RI)
655 : TerminatorInst(Type::getVoidTy(RI.getContext()), Instruction::Resume,
656 OperandTraits<ResumeInst>::op_begin(this), 1) {
657 Op<0>() = RI.Op<0>();
658 SubclassOptionalData = RI.SubclassOptionalData;
661 ResumeInst::ResumeInst(LLVMContext &C, Value *Exn, Instruction *InsertBefore)
662 : TerminatorInst(Type::getVoidTy(C), Instruction::Resume,
663 OperandTraits<ResumeInst>::op_begin(this), 1, InsertBefore) {
667 ResumeInst::ResumeInst(LLVMContext &C, Value *Exn, BasicBlock *InsertAtEnd)
668 : TerminatorInst(Type::getVoidTy(C), Instruction::Resume,
669 OperandTraits<ResumeInst>::op_begin(this), 1, InsertAtEnd) {
673 unsigned ResumeInst::getNumSuccessorsV() const {
674 return getNumSuccessors();
677 void ResumeInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
678 llvm_unreachable("ResumeInst has no successors!");
681 BasicBlock *ResumeInst::getSuccessorV(unsigned idx) const {
682 llvm_unreachable("ResumeInst has no successors!");
686 //===----------------------------------------------------------------------===//
687 // UnreachableInst Implementation
688 //===----------------------------------------------------------------------===//
690 UnreachableInst::UnreachableInst(LLVMContext &Context,
691 Instruction *InsertBefore)
692 : TerminatorInst(Type::getVoidTy(Context), Instruction::Unreachable,
693 0, 0, InsertBefore) {
695 UnreachableInst::UnreachableInst(LLVMContext &Context, BasicBlock *InsertAtEnd)
696 : TerminatorInst(Type::getVoidTy(Context), Instruction::Unreachable,
700 unsigned UnreachableInst::getNumSuccessorsV() const {
701 return getNumSuccessors();
704 void UnreachableInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
705 llvm_unreachable("UnreachableInst has no successors!");
708 BasicBlock *UnreachableInst::getSuccessorV(unsigned idx) const {
709 llvm_unreachable("UnreachableInst has no successors!");
713 //===----------------------------------------------------------------------===//
714 // BranchInst Implementation
715 //===----------------------------------------------------------------------===//
717 void BranchInst::AssertOK() {
719 assert(getCondition()->getType()->isIntegerTy(1) &&
720 "May only branch on boolean predicates!");
723 BranchInst::BranchInst(BasicBlock *IfTrue, Instruction *InsertBefore)
724 : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
725 OperandTraits<BranchInst>::op_end(this) - 1,
727 assert(IfTrue != 0 && "Branch destination may not be null!");
730 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
731 Instruction *InsertBefore)
732 : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
733 OperandTraits<BranchInst>::op_end(this) - 3,
743 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *InsertAtEnd)
744 : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
745 OperandTraits<BranchInst>::op_end(this) - 1,
747 assert(IfTrue != 0 && "Branch destination may not be null!");
751 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
752 BasicBlock *InsertAtEnd)
753 : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
754 OperandTraits<BranchInst>::op_end(this) - 3,
765 BranchInst::BranchInst(const BranchInst &BI) :
766 TerminatorInst(Type::getVoidTy(BI.getContext()), Instruction::Br,
767 OperandTraits<BranchInst>::op_end(this) - BI.getNumOperands(),
768 BI.getNumOperands()) {
769 Op<-1>() = BI.Op<-1>();
770 if (BI.getNumOperands() != 1) {
771 assert(BI.getNumOperands() == 3 && "BR can have 1 or 3 operands!");
772 Op<-3>() = BI.Op<-3>();
773 Op<-2>() = BI.Op<-2>();
775 SubclassOptionalData = BI.SubclassOptionalData;
778 BasicBlock *BranchInst::getSuccessorV(unsigned idx) const {
779 return getSuccessor(idx);
781 unsigned BranchInst::getNumSuccessorsV() const {
782 return getNumSuccessors();
784 void BranchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
785 setSuccessor(idx, B);
789 //===----------------------------------------------------------------------===//
790 // AllocaInst Implementation
791 //===----------------------------------------------------------------------===//
793 static Value *getAISize(LLVMContext &Context, Value *Amt) {
795 Amt = ConstantInt::get(Type::getInt32Ty(Context), 1);
797 assert(!isa<BasicBlock>(Amt) &&
798 "Passed basic block into allocation size parameter! Use other ctor");
799 assert(Amt->getType()->isIntegerTy() &&
800 "Allocation array size is not an integer!");
805 AllocaInst::AllocaInst(Type *Ty, Value *ArraySize,
806 const Twine &Name, Instruction *InsertBefore)
807 : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
808 getAISize(Ty->getContext(), ArraySize), InsertBefore) {
810 assert(!Ty->isVoidTy() && "Cannot allocate void!");
814 AllocaInst::AllocaInst(Type *Ty, Value *ArraySize,
815 const Twine &Name, BasicBlock *InsertAtEnd)
816 : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
817 getAISize(Ty->getContext(), ArraySize), InsertAtEnd) {
819 assert(!Ty->isVoidTy() && "Cannot allocate void!");
823 AllocaInst::AllocaInst(Type *Ty, const Twine &Name,
824 Instruction *InsertBefore)
825 : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
826 getAISize(Ty->getContext(), 0), InsertBefore) {
828 assert(!Ty->isVoidTy() && "Cannot allocate void!");
832 AllocaInst::AllocaInst(Type *Ty, const Twine &Name,
833 BasicBlock *InsertAtEnd)
834 : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
835 getAISize(Ty->getContext(), 0), InsertAtEnd) {
837 assert(!Ty->isVoidTy() && "Cannot allocate void!");
841 AllocaInst::AllocaInst(Type *Ty, Value *ArraySize, unsigned Align,
842 const Twine &Name, Instruction *InsertBefore)
843 : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
844 getAISize(Ty->getContext(), ArraySize), InsertBefore) {
846 assert(!Ty->isVoidTy() && "Cannot allocate void!");
850 AllocaInst::AllocaInst(Type *Ty, Value *ArraySize, unsigned Align,
851 const Twine &Name, BasicBlock *InsertAtEnd)
852 : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
853 getAISize(Ty->getContext(), ArraySize), InsertAtEnd) {
855 assert(!Ty->isVoidTy() && "Cannot allocate void!");
859 // Out of line virtual method, so the vtable, etc has a home.
860 AllocaInst::~AllocaInst() {
863 void AllocaInst::setAlignment(unsigned Align) {
864 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
865 assert(Align <= MaximumAlignment &&
866 "Alignment is greater than MaximumAlignment!");
867 setInstructionSubclassData(Log2_32(Align) + 1);
868 assert(getAlignment() == Align && "Alignment representation error!");
871 bool AllocaInst::isArrayAllocation() const {
872 if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(0)))
877 Type *AllocaInst::getAllocatedType() const {
878 return getType()->getElementType();
881 /// isStaticAlloca - Return true if this alloca is in the entry block of the
882 /// function and is a constant size. If so, the code generator will fold it
883 /// into the prolog/epilog code, so it is basically free.
884 bool AllocaInst::isStaticAlloca() const {
885 // Must be constant size.
886 if (!isa<ConstantInt>(getArraySize())) return false;
888 // Must be in the entry block.
889 const BasicBlock *Parent = getParent();
890 return Parent == &Parent->getParent()->front();
893 //===----------------------------------------------------------------------===//
894 // LoadInst Implementation
895 //===----------------------------------------------------------------------===//
897 void LoadInst::AssertOK() {
898 assert(getOperand(0)->getType()->isPointerTy() &&
899 "Ptr must have pointer type.");
902 LoadInst::LoadInst(Value *Ptr, const Twine &Name, Instruction *InsertBef)
903 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
904 Load, Ptr, InsertBef) {
911 LoadInst::LoadInst(Value *Ptr, const Twine &Name, BasicBlock *InsertAE)
912 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
913 Load, Ptr, InsertAE) {
920 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
921 Instruction *InsertBef)
922 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
923 Load, Ptr, InsertBef) {
924 setVolatile(isVolatile);
930 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
931 unsigned Align, Instruction *InsertBef)
932 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
933 Load, Ptr, InsertBef) {
934 setVolatile(isVolatile);
940 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
941 unsigned Align, BasicBlock *InsertAE)
942 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
943 Load, Ptr, InsertAE) {
944 setVolatile(isVolatile);
950 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
951 BasicBlock *InsertAE)
952 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
953 Load, Ptr, InsertAE) {
954 setVolatile(isVolatile);
962 LoadInst::LoadInst(Value *Ptr, const char *Name, Instruction *InsertBef)
963 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
964 Load, Ptr, InsertBef) {
968 if (Name && Name[0]) setName(Name);
971 LoadInst::LoadInst(Value *Ptr, const char *Name, BasicBlock *InsertAE)
972 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
973 Load, Ptr, InsertAE) {
977 if (Name && Name[0]) setName(Name);
980 LoadInst::LoadInst(Value *Ptr, const char *Name, bool isVolatile,
981 Instruction *InsertBef)
982 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
983 Load, Ptr, InsertBef) {
984 setVolatile(isVolatile);
987 if (Name && Name[0]) setName(Name);
990 LoadInst::LoadInst(Value *Ptr, const char *Name, bool isVolatile,
991 BasicBlock *InsertAE)
992 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
993 Load, Ptr, InsertAE) {
994 setVolatile(isVolatile);
997 if (Name && Name[0]) setName(Name);
1000 void LoadInst::setAlignment(unsigned Align) {
1001 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
1002 assert(Align <= MaximumAlignment &&
1003 "Alignment is greater than MaximumAlignment!");
1004 setInstructionSubclassData((getSubclassDataFromInstruction() & 1) |
1005 ((Log2_32(Align)+1)<<1));
1006 assert(getAlignment() == Align && "Alignment representation error!");
1009 //===----------------------------------------------------------------------===//
1010 // StoreInst Implementation
1011 //===----------------------------------------------------------------------===//
1013 void StoreInst::AssertOK() {
1014 assert(getOperand(0) && getOperand(1) && "Both operands must be non-null!");
1015 assert(getOperand(1)->getType()->isPointerTy() &&
1016 "Ptr must have pointer type!");
1017 assert(getOperand(0)->getType() ==
1018 cast<PointerType>(getOperand(1)->getType())->getElementType()
1019 && "Ptr must be a pointer to Val type!");
1023 StoreInst::StoreInst(Value *val, Value *addr, Instruction *InsertBefore)
1024 : Instruction(Type::getVoidTy(val->getContext()), Store,
1025 OperandTraits<StoreInst>::op_begin(this),
1026 OperandTraits<StoreInst>::operands(this),
1035 StoreInst::StoreInst(Value *val, Value *addr, BasicBlock *InsertAtEnd)
1036 : Instruction(Type::getVoidTy(val->getContext()), Store,
1037 OperandTraits<StoreInst>::op_begin(this),
1038 OperandTraits<StoreInst>::operands(this),
1047 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1048 Instruction *InsertBefore)
1049 : Instruction(Type::getVoidTy(val->getContext()), Store,
1050 OperandTraits<StoreInst>::op_begin(this),
1051 OperandTraits<StoreInst>::operands(this),
1055 setVolatile(isVolatile);
1060 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1061 unsigned Align, Instruction *InsertBefore)
1062 : Instruction(Type::getVoidTy(val->getContext()), Store,
1063 OperandTraits<StoreInst>::op_begin(this),
1064 OperandTraits<StoreInst>::operands(this),
1068 setVolatile(isVolatile);
1069 setAlignment(Align);
1073 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1074 unsigned Align, BasicBlock *InsertAtEnd)
1075 : Instruction(Type::getVoidTy(val->getContext()), Store,
1076 OperandTraits<StoreInst>::op_begin(this),
1077 OperandTraits<StoreInst>::operands(this),
1081 setVolatile(isVolatile);
1082 setAlignment(Align);
1086 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1087 BasicBlock *InsertAtEnd)
1088 : Instruction(Type::getVoidTy(val->getContext()), Store,
1089 OperandTraits<StoreInst>::op_begin(this),
1090 OperandTraits<StoreInst>::operands(this),
1094 setVolatile(isVolatile);
1099 void StoreInst::setAlignment(unsigned Align) {
1100 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
1101 assert(Align <= MaximumAlignment &&
1102 "Alignment is greater than MaximumAlignment!");
1103 setInstructionSubclassData((getSubclassDataFromInstruction() & 1) |
1104 ((Log2_32(Align)+1) << 1));
1105 assert(getAlignment() == Align && "Alignment representation error!");
1108 //===----------------------------------------------------------------------===//
1109 // AtomicCmpXchgInst Implementation
1110 //===----------------------------------------------------------------------===//
1112 void AtomicCmpXchgInst::Init(Value *Ptr, Value *Cmp, Value *NewVal,
1113 AtomicOrdering Ordering,
1114 SynchronizationScope SynchScope) {
1118 setOrdering(Ordering);
1119 setSynchScope(SynchScope);
1121 assert(getOperand(0) && getOperand(1) && getOperand(2) &&
1122 "All operands must be non-null!");
1123 assert(getOperand(0)->getType()->isPointerTy() &&
1124 "Ptr must have pointer type!");
1125 assert(getOperand(1)->getType() ==
1126 cast<PointerType>(getOperand(0)->getType())->getElementType()
1127 && "Ptr must be a pointer to Cmp type!");
1128 assert(getOperand(2)->getType() ==
1129 cast<PointerType>(getOperand(0)->getType())->getElementType()
1130 && "Ptr must be a pointer to NewVal type!");
1131 assert(Ordering != NotAtomic &&
1132 "AtomicCmpXchg instructions must be atomic!");
1135 AtomicCmpXchgInst::AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal,
1136 AtomicOrdering Ordering,
1137 SynchronizationScope SynchScope,
1138 Instruction *InsertBefore)
1139 : Instruction(Cmp->getType(), AtomicCmpXchg,
1140 OperandTraits<AtomicCmpXchgInst>::op_begin(this),
1141 OperandTraits<AtomicCmpXchgInst>::operands(this),
1143 Init(Ptr, Cmp, NewVal, Ordering, SynchScope);
1146 AtomicCmpXchgInst::AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal,
1147 AtomicOrdering Ordering,
1148 SynchronizationScope SynchScope,
1149 BasicBlock *InsertAtEnd)
1150 : Instruction(Cmp->getType(), AtomicCmpXchg,
1151 OperandTraits<AtomicCmpXchgInst>::op_begin(this),
1152 OperandTraits<AtomicCmpXchgInst>::operands(this),
1154 Init(Ptr, Cmp, NewVal, Ordering, SynchScope);
1157 //===----------------------------------------------------------------------===//
1158 // AtomicRMWInst Implementation
1159 //===----------------------------------------------------------------------===//
1161 void AtomicRMWInst::Init(BinOp Operation, Value *Ptr, Value *Val,
1162 AtomicOrdering Ordering,
1163 SynchronizationScope SynchScope) {
1166 setOperation(Operation);
1167 setOrdering(Ordering);
1168 setSynchScope(SynchScope);
1170 assert(getOperand(0) && getOperand(1) &&
1171 "All operands must be non-null!");
1172 assert(getOperand(0)->getType()->isPointerTy() &&
1173 "Ptr must have pointer type!");
1174 assert(getOperand(1)->getType() ==
1175 cast<PointerType>(getOperand(0)->getType())->getElementType()
1176 && "Ptr must be a pointer to Val type!");
1177 assert(Ordering != NotAtomic &&
1178 "AtomicRMW instructions must be atomic!");
1181 AtomicRMWInst::AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val,
1182 AtomicOrdering Ordering,
1183 SynchronizationScope SynchScope,
1184 Instruction *InsertBefore)
1185 : Instruction(Val->getType(), AtomicRMW,
1186 OperandTraits<AtomicRMWInst>::op_begin(this),
1187 OperandTraits<AtomicRMWInst>::operands(this),
1189 Init(Operation, Ptr, Val, Ordering, SynchScope);
1192 AtomicRMWInst::AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val,
1193 AtomicOrdering Ordering,
1194 SynchronizationScope SynchScope,
1195 BasicBlock *InsertAtEnd)
1196 : Instruction(Val->getType(), AtomicRMW,
1197 OperandTraits<AtomicRMWInst>::op_begin(this),
1198 OperandTraits<AtomicRMWInst>::operands(this),
1200 Init(Operation, Ptr, Val, Ordering, SynchScope);
1203 //===----------------------------------------------------------------------===//
1204 // FenceInst Implementation
1205 //===----------------------------------------------------------------------===//
1207 FenceInst::FenceInst(LLVMContext &C, AtomicOrdering Ordering,
1208 SynchronizationScope SynchScope,
1209 Instruction *InsertBefore)
1210 : Instruction(Type::getVoidTy(C), Fence, 0, 0, InsertBefore) {
1211 setOrdering(Ordering);
1212 setSynchScope(SynchScope);
1215 FenceInst::FenceInst(LLVMContext &C, AtomicOrdering Ordering,
1216 SynchronizationScope SynchScope,
1217 BasicBlock *InsertAtEnd)
1218 : Instruction(Type::getVoidTy(C), Fence, 0, 0, InsertAtEnd) {
1219 setOrdering(Ordering);
1220 setSynchScope(SynchScope);
1223 //===----------------------------------------------------------------------===//
1224 // GetElementPtrInst Implementation
1225 //===----------------------------------------------------------------------===//
1227 void GetElementPtrInst::init(Value *Ptr, ArrayRef<Value *> IdxList,
1228 const Twine &Name) {
1229 assert(NumOperands == 1 + IdxList.size() && "NumOperands not initialized?");
1230 OperandList[0] = Ptr;
1231 std::copy(IdxList.begin(), IdxList.end(), op_begin() + 1);
1235 GetElementPtrInst::GetElementPtrInst(const GetElementPtrInst &GEPI)
1236 : Instruction(GEPI.getType(), GetElementPtr,
1237 OperandTraits<GetElementPtrInst>::op_end(this)
1238 - GEPI.getNumOperands(),
1239 GEPI.getNumOperands()) {
1240 std::copy(GEPI.op_begin(), GEPI.op_end(), op_begin());
1241 SubclassOptionalData = GEPI.SubclassOptionalData;
1244 /// getIndexedType - Returns the type of the element that would be accessed with
1245 /// a gep instruction with the specified parameters.
1247 /// The Idxs pointer should point to a continuous piece of memory containing the
1248 /// indices, either as Value* or uint64_t.
1250 /// A null type is returned if the indices are invalid for the specified
1253 template <typename IndexTy>
1254 static Type *getIndexedTypeInternal(Type *Ptr, ArrayRef<IndexTy> IdxList) {
1255 PointerType *PTy = dyn_cast<PointerType>(Ptr);
1256 if (!PTy) return 0; // Type isn't a pointer type!
1257 Type *Agg = PTy->getElementType();
1259 // Handle the special case of the empty set index set, which is always valid.
1260 if (IdxList.empty())
1263 // If there is at least one index, the top level type must be sized, otherwise
1264 // it cannot be 'stepped over'.
1265 if (!Agg->isSized())
1268 unsigned CurIdx = 1;
1269 for (; CurIdx != IdxList.size(); ++CurIdx) {
1270 CompositeType *CT = dyn_cast<CompositeType>(Agg);
1271 if (!CT || CT->isPointerTy()) return 0;
1272 IndexTy Index = IdxList[CurIdx];
1273 if (!CT->indexValid(Index)) return 0;
1274 Agg = CT->getTypeAtIndex(Index);
1276 return CurIdx == IdxList.size() ? Agg : 0;
1279 Type *GetElementPtrInst::getIndexedType(Type *Ptr, ArrayRef<Value *> IdxList) {
1280 return getIndexedTypeInternal(Ptr, IdxList);
1283 Type *GetElementPtrInst::getIndexedType(Type *Ptr,
1284 ArrayRef<Constant *> IdxList) {
1285 return getIndexedTypeInternal(Ptr, IdxList);
1288 Type *GetElementPtrInst::getIndexedType(Type *Ptr, ArrayRef<uint64_t> IdxList) {
1289 return getIndexedTypeInternal(Ptr, IdxList);
1292 /// hasAllZeroIndices - Return true if all of the indices of this GEP are
1293 /// zeros. If so, the result pointer and the first operand have the same
1294 /// value, just potentially different types.
1295 bool GetElementPtrInst::hasAllZeroIndices() const {
1296 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1297 if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(i))) {
1298 if (!CI->isZero()) return false;
1306 /// hasAllConstantIndices - Return true if all of the indices of this GEP are
1307 /// constant integers. If so, the result pointer and the first operand have
1308 /// a constant offset between them.
1309 bool GetElementPtrInst::hasAllConstantIndices() const {
1310 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1311 if (!isa<ConstantInt>(getOperand(i)))
1317 void GetElementPtrInst::setIsInBounds(bool B) {
1318 cast<GEPOperator>(this)->setIsInBounds(B);
1321 bool GetElementPtrInst::isInBounds() const {
1322 return cast<GEPOperator>(this)->isInBounds();
1325 //===----------------------------------------------------------------------===//
1326 // ExtractElementInst Implementation
1327 //===----------------------------------------------------------------------===//
1329 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
1331 Instruction *InsertBef)
1332 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1334 OperandTraits<ExtractElementInst>::op_begin(this),
1336 assert(isValidOperands(Val, Index) &&
1337 "Invalid extractelement instruction operands!");
1343 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
1345 BasicBlock *InsertAE)
1346 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1348 OperandTraits<ExtractElementInst>::op_begin(this),
1350 assert(isValidOperands(Val, Index) &&
1351 "Invalid extractelement instruction operands!");
1359 bool ExtractElementInst::isValidOperands(const Value *Val, const Value *Index) {
1360 if (!Val->getType()->isVectorTy() || !Index->getType()->isIntegerTy(32))
1366 //===----------------------------------------------------------------------===//
1367 // InsertElementInst Implementation
1368 //===----------------------------------------------------------------------===//
1370 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
1372 Instruction *InsertBef)
1373 : Instruction(Vec->getType(), InsertElement,
1374 OperandTraits<InsertElementInst>::op_begin(this),
1376 assert(isValidOperands(Vec, Elt, Index) &&
1377 "Invalid insertelement instruction operands!");
1384 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
1386 BasicBlock *InsertAE)
1387 : Instruction(Vec->getType(), InsertElement,
1388 OperandTraits<InsertElementInst>::op_begin(this),
1390 assert(isValidOperands(Vec, Elt, Index) &&
1391 "Invalid insertelement instruction operands!");
1399 bool InsertElementInst::isValidOperands(const Value *Vec, const Value *Elt,
1400 const Value *Index) {
1401 if (!Vec->getType()->isVectorTy())
1402 return false; // First operand of insertelement must be vector type.
1404 if (Elt->getType() != cast<VectorType>(Vec->getType())->getElementType())
1405 return false;// Second operand of insertelement must be vector element type.
1407 if (!Index->getType()->isIntegerTy(32))
1408 return false; // Third operand of insertelement must be i32.
1413 //===----------------------------------------------------------------------===//
1414 // ShuffleVectorInst Implementation
1415 //===----------------------------------------------------------------------===//
1417 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1419 Instruction *InsertBefore)
1420 : Instruction(VectorType::get(cast<VectorType>(V1->getType())->getElementType(),
1421 cast<VectorType>(Mask->getType())->getNumElements()),
1423 OperandTraits<ShuffleVectorInst>::op_begin(this),
1424 OperandTraits<ShuffleVectorInst>::operands(this),
1426 assert(isValidOperands(V1, V2, Mask) &&
1427 "Invalid shuffle vector instruction operands!");
1434 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1436 BasicBlock *InsertAtEnd)
1437 : Instruction(VectorType::get(cast<VectorType>(V1->getType())->getElementType(),
1438 cast<VectorType>(Mask->getType())->getNumElements()),
1440 OperandTraits<ShuffleVectorInst>::op_begin(this),
1441 OperandTraits<ShuffleVectorInst>::operands(this),
1443 assert(isValidOperands(V1, V2, Mask) &&
1444 "Invalid shuffle vector instruction operands!");
1452 bool ShuffleVectorInst::isValidOperands(const Value *V1, const Value *V2,
1453 const Value *Mask) {
1454 if (!V1->getType()->isVectorTy() || V1->getType() != V2->getType())
1457 VectorType *MaskTy = dyn_cast<VectorType>(Mask->getType());
1458 if (MaskTy == 0 || !MaskTy->getElementType()->isIntegerTy(32))
1461 // Check to see if Mask is valid.
1462 if (const ConstantVector *MV = dyn_cast<ConstantVector>(Mask)) {
1463 VectorType *VTy = cast<VectorType>(V1->getType());
1464 for (unsigned i = 0, e = MV->getNumOperands(); i != e; ++i) {
1465 if (ConstantInt* CI = dyn_cast<ConstantInt>(MV->getOperand(i))) {
1466 if (CI->uge(VTy->getNumElements()*2))
1468 } else if (!isa<UndefValue>(MV->getOperand(i))) {
1473 else if (!isa<UndefValue>(Mask) && !isa<ConstantAggregateZero>(Mask))
1479 /// getMaskValue - Return the index from the shuffle mask for the specified
1480 /// output result. This is either -1 if the element is undef or a number less
1481 /// than 2*numelements.
1482 int ShuffleVectorInst::getMaskValue(unsigned i) const {
1483 const Constant *Mask = cast<Constant>(getOperand(2));
1484 if (isa<UndefValue>(Mask)) return -1;
1485 if (isa<ConstantAggregateZero>(Mask)) return 0;
1486 const ConstantVector *MaskCV = cast<ConstantVector>(Mask);
1487 assert(i < MaskCV->getNumOperands() && "Index out of range");
1489 if (isa<UndefValue>(MaskCV->getOperand(i)))
1491 return cast<ConstantInt>(MaskCV->getOperand(i))->getZExtValue();
1494 //===----------------------------------------------------------------------===//
1495 // InsertValueInst Class
1496 //===----------------------------------------------------------------------===//
1498 void InsertValueInst::init(Value *Agg, Value *Val, ArrayRef<unsigned> Idxs,
1499 const Twine &Name) {
1500 assert(NumOperands == 2 && "NumOperands not initialized?");
1502 // There's no fundamental reason why we require at least one index
1503 // (other than weirdness with &*IdxBegin being invalid; see
1504 // getelementptr's init routine for example). But there's no
1505 // present need to support it.
1506 assert(Idxs.size() > 0 && "InsertValueInst must have at least one index");
1508 assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs) ==
1509 Val->getType() && "Inserted value must match indexed type!");
1513 Indices.append(Idxs.begin(), Idxs.end());
1517 InsertValueInst::InsertValueInst(const InsertValueInst &IVI)
1518 : Instruction(IVI.getType(), InsertValue,
1519 OperandTraits<InsertValueInst>::op_begin(this), 2),
1520 Indices(IVI.Indices) {
1521 Op<0>() = IVI.getOperand(0);
1522 Op<1>() = IVI.getOperand(1);
1523 SubclassOptionalData = IVI.SubclassOptionalData;
1526 //===----------------------------------------------------------------------===//
1527 // ExtractValueInst Class
1528 //===----------------------------------------------------------------------===//
1530 void ExtractValueInst::init(ArrayRef<unsigned> Idxs, const Twine &Name) {
1531 assert(NumOperands == 1 && "NumOperands not initialized?");
1533 // There's no fundamental reason why we require at least one index.
1534 // But there's no present need to support it.
1535 assert(Idxs.size() > 0 && "ExtractValueInst must have at least one index");
1537 Indices.append(Idxs.begin(), Idxs.end());
1541 ExtractValueInst::ExtractValueInst(const ExtractValueInst &EVI)
1542 : UnaryInstruction(EVI.getType(), ExtractValue, EVI.getOperand(0)),
1543 Indices(EVI.Indices) {
1544 SubclassOptionalData = EVI.SubclassOptionalData;
1547 // getIndexedType - Returns the type of the element that would be extracted
1548 // with an extractvalue instruction with the specified parameters.
1550 // A null type is returned if the indices are invalid for the specified
1553 Type *ExtractValueInst::getIndexedType(Type *Agg,
1554 ArrayRef<unsigned> Idxs) {
1555 for (unsigned CurIdx = 0; CurIdx != Idxs.size(); ++CurIdx) {
1556 unsigned Index = Idxs[CurIdx];
1557 // We can't use CompositeType::indexValid(Index) here.
1558 // indexValid() always returns true for arrays because getelementptr allows
1559 // out-of-bounds indices. Since we don't allow those for extractvalue and
1560 // insertvalue we need to check array indexing manually.
1561 // Since the only other types we can index into are struct types it's just
1562 // as easy to check those manually as well.
1563 if (ArrayType *AT = dyn_cast<ArrayType>(Agg)) {
1564 if (Index >= AT->getNumElements())
1566 } else if (StructType *ST = dyn_cast<StructType>(Agg)) {
1567 if (Index >= ST->getNumElements())
1570 // Not a valid type to index into.
1574 Agg = cast<CompositeType>(Agg)->getTypeAtIndex(Index);
1576 return const_cast<Type*>(Agg);
1579 //===----------------------------------------------------------------------===//
1580 // BinaryOperator Class
1581 //===----------------------------------------------------------------------===//
1583 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
1584 Type *Ty, const Twine &Name,
1585 Instruction *InsertBefore)
1586 : Instruction(Ty, iType,
1587 OperandTraits<BinaryOperator>::op_begin(this),
1588 OperandTraits<BinaryOperator>::operands(this),
1596 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
1597 Type *Ty, const Twine &Name,
1598 BasicBlock *InsertAtEnd)
1599 : Instruction(Ty, iType,
1600 OperandTraits<BinaryOperator>::op_begin(this),
1601 OperandTraits<BinaryOperator>::operands(this),
1610 void BinaryOperator::init(BinaryOps iType) {
1611 Value *LHS = getOperand(0), *RHS = getOperand(1);
1612 (void)LHS; (void)RHS; // Silence warnings.
1613 assert(LHS->getType() == RHS->getType() &&
1614 "Binary operator operand types must match!");
1619 assert(getType() == LHS->getType() &&
1620 "Arithmetic operation should return same type as operands!");
1621 assert(getType()->isIntOrIntVectorTy() &&
1622 "Tried to create an integer operation on a non-integer type!");
1624 case FAdd: case FSub:
1626 assert(getType() == LHS->getType() &&
1627 "Arithmetic operation should return same type as operands!");
1628 assert(getType()->isFPOrFPVectorTy() &&
1629 "Tried to create a floating-point operation on a "
1630 "non-floating-point type!");
1634 assert(getType() == LHS->getType() &&
1635 "Arithmetic operation should return same type as operands!");
1636 assert((getType()->isIntegerTy() || (getType()->isVectorTy() &&
1637 cast<VectorType>(getType())->getElementType()->isIntegerTy())) &&
1638 "Incorrect operand type (not integer) for S/UDIV");
1641 assert(getType() == LHS->getType() &&
1642 "Arithmetic operation should return same type as operands!");
1643 assert(getType()->isFPOrFPVectorTy() &&
1644 "Incorrect operand type (not floating point) for FDIV");
1648 assert(getType() == LHS->getType() &&
1649 "Arithmetic operation should return same type as operands!");
1650 assert((getType()->isIntegerTy() || (getType()->isVectorTy() &&
1651 cast<VectorType>(getType())->getElementType()->isIntegerTy())) &&
1652 "Incorrect operand type (not integer) for S/UREM");
1655 assert(getType() == LHS->getType() &&
1656 "Arithmetic operation should return same type as operands!");
1657 assert(getType()->isFPOrFPVectorTy() &&
1658 "Incorrect operand type (not floating point) for FREM");
1663 assert(getType() == LHS->getType() &&
1664 "Shift operation should return same type as operands!");
1665 assert((getType()->isIntegerTy() ||
1666 (getType()->isVectorTy() &&
1667 cast<VectorType>(getType())->getElementType()->isIntegerTy())) &&
1668 "Tried to create a shift operation on a non-integral type!");
1672 assert(getType() == LHS->getType() &&
1673 "Logical operation should return same type as operands!");
1674 assert((getType()->isIntegerTy() ||
1675 (getType()->isVectorTy() &&
1676 cast<VectorType>(getType())->getElementType()->isIntegerTy())) &&
1677 "Tried to create a logical operation on a non-integral type!");
1685 BinaryOperator *BinaryOperator::Create(BinaryOps Op, Value *S1, Value *S2,
1687 Instruction *InsertBefore) {
1688 assert(S1->getType() == S2->getType() &&
1689 "Cannot create binary operator with two operands of differing type!");
1690 return new BinaryOperator(Op, S1, S2, S1->getType(), Name, InsertBefore);
1693 BinaryOperator *BinaryOperator::Create(BinaryOps Op, Value *S1, Value *S2,
1695 BasicBlock *InsertAtEnd) {
1696 BinaryOperator *Res = Create(Op, S1, S2, Name);
1697 InsertAtEnd->getInstList().push_back(Res);
1701 BinaryOperator *BinaryOperator::CreateNeg(Value *Op, const Twine &Name,
1702 Instruction *InsertBefore) {
1703 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1704 return new BinaryOperator(Instruction::Sub,
1706 Op->getType(), Name, InsertBefore);
1709 BinaryOperator *BinaryOperator::CreateNeg(Value *Op, const Twine &Name,
1710 BasicBlock *InsertAtEnd) {
1711 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1712 return new BinaryOperator(Instruction::Sub,
1714 Op->getType(), Name, InsertAtEnd);
1717 BinaryOperator *BinaryOperator::CreateNSWNeg(Value *Op, const Twine &Name,
1718 Instruction *InsertBefore) {
1719 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1720 return BinaryOperator::CreateNSWSub(zero, Op, Name, InsertBefore);
1723 BinaryOperator *BinaryOperator::CreateNSWNeg(Value *Op, const Twine &Name,
1724 BasicBlock *InsertAtEnd) {
1725 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1726 return BinaryOperator::CreateNSWSub(zero, Op, Name, InsertAtEnd);
1729 BinaryOperator *BinaryOperator::CreateNUWNeg(Value *Op, const Twine &Name,
1730 Instruction *InsertBefore) {
1731 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1732 return BinaryOperator::CreateNUWSub(zero, Op, Name, InsertBefore);
1735 BinaryOperator *BinaryOperator::CreateNUWNeg(Value *Op, const Twine &Name,
1736 BasicBlock *InsertAtEnd) {
1737 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1738 return BinaryOperator::CreateNUWSub(zero, Op, Name, InsertAtEnd);
1741 BinaryOperator *BinaryOperator::CreateFNeg(Value *Op, const Twine &Name,
1742 Instruction *InsertBefore) {
1743 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1744 return new BinaryOperator(Instruction::FSub,
1746 Op->getType(), Name, InsertBefore);
1749 BinaryOperator *BinaryOperator::CreateFNeg(Value *Op, const Twine &Name,
1750 BasicBlock *InsertAtEnd) {
1751 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1752 return new BinaryOperator(Instruction::FSub,
1754 Op->getType(), Name, InsertAtEnd);
1757 BinaryOperator *BinaryOperator::CreateNot(Value *Op, const Twine &Name,
1758 Instruction *InsertBefore) {
1760 if (VectorType *PTy = dyn_cast<VectorType>(Op->getType())) {
1761 C = Constant::getAllOnesValue(PTy->getElementType());
1762 C = ConstantVector::get(
1763 std::vector<Constant*>(PTy->getNumElements(), C));
1765 C = Constant::getAllOnesValue(Op->getType());
1768 return new BinaryOperator(Instruction::Xor, Op, C,
1769 Op->getType(), Name, InsertBefore);
1772 BinaryOperator *BinaryOperator::CreateNot(Value *Op, const Twine &Name,
1773 BasicBlock *InsertAtEnd) {
1775 if (VectorType *PTy = dyn_cast<VectorType>(Op->getType())) {
1776 // Create a vector of all ones values.
1777 Constant *Elt = Constant::getAllOnesValue(PTy->getElementType());
1778 AllOnes = ConstantVector::get(
1779 std::vector<Constant*>(PTy->getNumElements(), Elt));
1781 AllOnes = Constant::getAllOnesValue(Op->getType());
1784 return new BinaryOperator(Instruction::Xor, Op, AllOnes,
1785 Op->getType(), Name, InsertAtEnd);
1789 // isConstantAllOnes - Helper function for several functions below
1790 static inline bool isConstantAllOnes(const Value *V) {
1791 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V))
1792 return CI->isAllOnesValue();
1793 if (const ConstantVector *CV = dyn_cast<ConstantVector>(V))
1794 return CV->isAllOnesValue();
1798 bool BinaryOperator::isNeg(const Value *V) {
1799 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1800 if (Bop->getOpcode() == Instruction::Sub)
1801 if (Constant* C = dyn_cast<Constant>(Bop->getOperand(0)))
1802 return C->isNegativeZeroValue();
1806 bool BinaryOperator::isFNeg(const Value *V) {
1807 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1808 if (Bop->getOpcode() == Instruction::FSub)
1809 if (Constant* C = dyn_cast<Constant>(Bop->getOperand(0)))
1810 return C->isNegativeZeroValue();
1814 bool BinaryOperator::isNot(const Value *V) {
1815 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1816 return (Bop->getOpcode() == Instruction::Xor &&
1817 (isConstantAllOnes(Bop->getOperand(1)) ||
1818 isConstantAllOnes(Bop->getOperand(0))));
1822 Value *BinaryOperator::getNegArgument(Value *BinOp) {
1823 return cast<BinaryOperator>(BinOp)->getOperand(1);
1826 const Value *BinaryOperator::getNegArgument(const Value *BinOp) {
1827 return getNegArgument(const_cast<Value*>(BinOp));
1830 Value *BinaryOperator::getFNegArgument(Value *BinOp) {
1831 return cast<BinaryOperator>(BinOp)->getOperand(1);
1834 const Value *BinaryOperator::getFNegArgument(const Value *BinOp) {
1835 return getFNegArgument(const_cast<Value*>(BinOp));
1838 Value *BinaryOperator::getNotArgument(Value *BinOp) {
1839 assert(isNot(BinOp) && "getNotArgument on non-'not' instruction!");
1840 BinaryOperator *BO = cast<BinaryOperator>(BinOp);
1841 Value *Op0 = BO->getOperand(0);
1842 Value *Op1 = BO->getOperand(1);
1843 if (isConstantAllOnes(Op0)) return Op1;
1845 assert(isConstantAllOnes(Op1));
1849 const Value *BinaryOperator::getNotArgument(const Value *BinOp) {
1850 return getNotArgument(const_cast<Value*>(BinOp));
1854 // swapOperands - Exchange the two operands to this instruction. This
1855 // instruction is safe to use on any binary instruction and does not
1856 // modify the semantics of the instruction. If the instruction is
1857 // order dependent (SetLT f.e.) the opcode is changed.
1859 bool BinaryOperator::swapOperands() {
1860 if (!isCommutative())
1861 return true; // Can't commute operands
1862 Op<0>().swap(Op<1>());
1866 void BinaryOperator::setHasNoUnsignedWrap(bool b) {
1867 cast<OverflowingBinaryOperator>(this)->setHasNoUnsignedWrap(b);
1870 void BinaryOperator::setHasNoSignedWrap(bool b) {
1871 cast<OverflowingBinaryOperator>(this)->setHasNoSignedWrap(b);
1874 void BinaryOperator::setIsExact(bool b) {
1875 cast<PossiblyExactOperator>(this)->setIsExact(b);
1878 bool BinaryOperator::hasNoUnsignedWrap() const {
1879 return cast<OverflowingBinaryOperator>(this)->hasNoUnsignedWrap();
1882 bool BinaryOperator::hasNoSignedWrap() const {
1883 return cast<OverflowingBinaryOperator>(this)->hasNoSignedWrap();
1886 bool BinaryOperator::isExact() const {
1887 return cast<PossiblyExactOperator>(this)->isExact();
1890 //===----------------------------------------------------------------------===//
1892 //===----------------------------------------------------------------------===//
1894 // Just determine if this cast only deals with integral->integral conversion.
1895 bool CastInst::isIntegerCast() const {
1896 switch (getOpcode()) {
1897 default: return false;
1898 case Instruction::ZExt:
1899 case Instruction::SExt:
1900 case Instruction::Trunc:
1902 case Instruction::BitCast:
1903 return getOperand(0)->getType()->isIntegerTy() &&
1904 getType()->isIntegerTy();
1908 bool CastInst::isLosslessCast() const {
1909 // Only BitCast can be lossless, exit fast if we're not BitCast
1910 if (getOpcode() != Instruction::BitCast)
1913 // Identity cast is always lossless
1914 Type* SrcTy = getOperand(0)->getType();
1915 Type* DstTy = getType();
1919 // Pointer to pointer is always lossless.
1920 if (SrcTy->isPointerTy())
1921 return DstTy->isPointerTy();
1922 return false; // Other types have no identity values
1925 /// This function determines if the CastInst does not require any bits to be
1926 /// changed in order to effect the cast. Essentially, it identifies cases where
1927 /// no code gen is necessary for the cast, hence the name no-op cast. For
1928 /// example, the following are all no-op casts:
1929 /// # bitcast i32* %x to i8*
1930 /// # bitcast <2 x i32> %x to <4 x i16>
1931 /// # ptrtoint i32* %x to i32 ; on 32-bit plaforms only
1932 /// @brief Determine if the described cast is a no-op.
1933 bool CastInst::isNoopCast(Instruction::CastOps Opcode,
1939 assert(!"Invalid CastOp");
1940 case Instruction::Trunc:
1941 case Instruction::ZExt:
1942 case Instruction::SExt:
1943 case Instruction::FPTrunc:
1944 case Instruction::FPExt:
1945 case Instruction::UIToFP:
1946 case Instruction::SIToFP:
1947 case Instruction::FPToUI:
1948 case Instruction::FPToSI:
1949 return false; // These always modify bits
1950 case Instruction::BitCast:
1951 return true; // BitCast never modifies bits.
1952 case Instruction::PtrToInt:
1953 return IntPtrTy->getScalarSizeInBits() ==
1954 DestTy->getScalarSizeInBits();
1955 case Instruction::IntToPtr:
1956 return IntPtrTy->getScalarSizeInBits() ==
1957 SrcTy->getScalarSizeInBits();
1961 /// @brief Determine if a cast is a no-op.
1962 bool CastInst::isNoopCast(Type *IntPtrTy) const {
1963 return isNoopCast(getOpcode(), getOperand(0)->getType(), getType(), IntPtrTy);
1966 /// This function determines if a pair of casts can be eliminated and what
1967 /// opcode should be used in the elimination. This assumes that there are two
1968 /// instructions like this:
1969 /// * %F = firstOpcode SrcTy %x to MidTy
1970 /// * %S = secondOpcode MidTy %F to DstTy
1971 /// The function returns a resultOpcode so these two casts can be replaced with:
1972 /// * %Replacement = resultOpcode %SrcTy %x to DstTy
1973 /// If no such cast is permited, the function returns 0.
1974 unsigned CastInst::isEliminableCastPair(
1975 Instruction::CastOps firstOp, Instruction::CastOps secondOp,
1976 Type *SrcTy, Type *MidTy, Type *DstTy, Type *IntPtrTy)
1978 // Define the 144 possibilities for these two cast instructions. The values
1979 // in this matrix determine what to do in a given situation and select the
1980 // case in the switch below. The rows correspond to firstOp, the columns
1981 // correspond to secondOp. In looking at the table below, keep in mind
1982 // the following cast properties:
1984 // Size Compare Source Destination
1985 // Operator Src ? Size Type Sign Type Sign
1986 // -------- ------------ ------------------- ---------------------
1987 // TRUNC > Integer Any Integral Any
1988 // ZEXT < Integral Unsigned Integer Any
1989 // SEXT < Integral Signed Integer Any
1990 // FPTOUI n/a FloatPt n/a Integral Unsigned
1991 // FPTOSI n/a FloatPt n/a Integral Signed
1992 // UITOFP n/a Integral Unsigned FloatPt n/a
1993 // SITOFP n/a Integral Signed FloatPt n/a
1994 // FPTRUNC > FloatPt n/a FloatPt n/a
1995 // FPEXT < FloatPt n/a FloatPt n/a
1996 // PTRTOINT n/a Pointer n/a Integral Unsigned
1997 // INTTOPTR n/a Integral Unsigned Pointer n/a
1998 // BITCAST = FirstClass n/a FirstClass n/a
2000 // NOTE: some transforms are safe, but we consider them to be non-profitable.
2001 // For example, we could merge "fptoui double to i32" + "zext i32 to i64",
2002 // into "fptoui double to i64", but this loses information about the range
2003 // of the produced value (we no longer know the top-part is all zeros).
2004 // Further this conversion is often much more expensive for typical hardware,
2005 // and causes issues when building libgcc. We disallow fptosi+sext for the
2007 const unsigned numCastOps =
2008 Instruction::CastOpsEnd - Instruction::CastOpsBegin;
2009 static const uint8_t CastResults[numCastOps][numCastOps] = {
2010 // T F F U S F F P I B -+
2011 // R Z S P P I I T P 2 N T |
2012 // U E E 2 2 2 2 R E I T C +- secondOp
2013 // N X X U S F F N X N 2 V |
2014 // C T T I I P P C T T P T -+
2015 { 1, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // Trunc -+
2016 { 8, 1, 9,99,99, 2, 0,99,99,99, 2, 3 }, // ZExt |
2017 { 8, 0, 1,99,99, 0, 2,99,99,99, 0, 3 }, // SExt |
2018 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // FPToUI |
2019 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // FPToSI |
2020 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4 }, // UIToFP +- firstOp
2021 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4 }, // SIToFP |
2022 { 99,99,99, 0, 0,99,99, 1, 0,99,99, 4 }, // FPTrunc |
2023 { 99,99,99, 2, 2,99,99,10, 2,99,99, 4 }, // FPExt |
2024 { 1, 0, 0,99,99, 0, 0,99,99,99, 7, 3 }, // PtrToInt |
2025 { 99,99,99,99,99,99,99,99,99,13,99,12 }, // IntToPtr |
2026 { 5, 5, 5, 6, 6, 5, 5, 6, 6,11, 5, 1 }, // BitCast -+
2029 // If either of the casts are a bitcast from scalar to vector, disallow the
2031 if ((firstOp == Instruction::BitCast &&
2032 isa<VectorType>(SrcTy) != isa<VectorType>(MidTy)) ||
2033 (secondOp == Instruction::BitCast &&
2034 isa<VectorType>(MidTy) != isa<VectorType>(DstTy)))
2035 return 0; // Disallowed
2037 int ElimCase = CastResults[firstOp-Instruction::CastOpsBegin]
2038 [secondOp-Instruction::CastOpsBegin];
2041 // categorically disallowed
2044 // allowed, use first cast's opcode
2047 // allowed, use second cast's opcode
2050 // no-op cast in second op implies firstOp as long as the DestTy
2051 // is integer and we are not converting between a vector and a
2053 if (!SrcTy->isVectorTy() && DstTy->isIntegerTy())
2057 // no-op cast in second op implies firstOp as long as the DestTy
2058 // is floating point.
2059 if (DstTy->isFloatingPointTy())
2063 // no-op cast in first op implies secondOp as long as the SrcTy
2065 if (SrcTy->isIntegerTy())
2069 // no-op cast in first op implies secondOp as long as the SrcTy
2070 // is a floating point.
2071 if (SrcTy->isFloatingPointTy())
2075 // ptrtoint, inttoptr -> bitcast (ptr -> ptr) if int size is >= ptr size
2078 unsigned PtrSize = IntPtrTy->getScalarSizeInBits();
2079 unsigned MidSize = MidTy->getScalarSizeInBits();
2080 if (MidSize >= PtrSize)
2081 return Instruction::BitCast;
2085 // ext, trunc -> bitcast, if the SrcTy and DstTy are same size
2086 // ext, trunc -> ext, if sizeof(SrcTy) < sizeof(DstTy)
2087 // ext, trunc -> trunc, if sizeof(SrcTy) > sizeof(DstTy)
2088 unsigned SrcSize = SrcTy->getScalarSizeInBits();
2089 unsigned DstSize = DstTy->getScalarSizeInBits();
2090 if (SrcSize == DstSize)
2091 return Instruction::BitCast;
2092 else if (SrcSize < DstSize)
2096 case 9: // zext, sext -> zext, because sext can't sign extend after zext
2097 return Instruction::ZExt;
2099 // fpext followed by ftrunc is allowed if the bit size returned to is
2100 // the same as the original, in which case its just a bitcast
2102 return Instruction::BitCast;
2103 return 0; // If the types are not the same we can't eliminate it.
2105 // bitcast followed by ptrtoint is allowed as long as the bitcast
2106 // is a pointer to pointer cast.
2107 if (SrcTy->isPointerTy() && MidTy->isPointerTy())
2111 // inttoptr, bitcast -> intptr if bitcast is a ptr to ptr cast
2112 if (MidTy->isPointerTy() && DstTy->isPointerTy())
2116 // inttoptr, ptrtoint -> bitcast if SrcSize<=PtrSize and SrcSize==DstSize
2119 unsigned PtrSize = IntPtrTy->getScalarSizeInBits();
2120 unsigned SrcSize = SrcTy->getScalarSizeInBits();
2121 unsigned DstSize = DstTy->getScalarSizeInBits();
2122 if (SrcSize <= PtrSize && SrcSize == DstSize)
2123 return Instruction::BitCast;
2127 // cast combination can't happen (error in input). This is for all cases
2128 // where the MidTy is not the same for the two cast instructions.
2129 assert(!"Invalid Cast Combination");
2132 assert(!"Error in CastResults table!!!");
2138 CastInst *CastInst::Create(Instruction::CastOps op, Value *S, Type *Ty,
2139 const Twine &Name, Instruction *InsertBefore) {
2140 assert(castIsValid(op, S, Ty) && "Invalid cast!");
2141 // Construct and return the appropriate CastInst subclass
2143 case Trunc: return new TruncInst (S, Ty, Name, InsertBefore);
2144 case ZExt: return new ZExtInst (S, Ty, Name, InsertBefore);
2145 case SExt: return new SExtInst (S, Ty, Name, InsertBefore);
2146 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertBefore);
2147 case FPExt: return new FPExtInst (S, Ty, Name, InsertBefore);
2148 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertBefore);
2149 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertBefore);
2150 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertBefore);
2151 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertBefore);
2152 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertBefore);
2153 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertBefore);
2154 case BitCast: return new BitCastInst (S, Ty, Name, InsertBefore);
2156 assert(!"Invalid opcode provided");
2161 CastInst *CastInst::Create(Instruction::CastOps op, Value *S, Type *Ty,
2162 const Twine &Name, BasicBlock *InsertAtEnd) {
2163 assert(castIsValid(op, S, Ty) && "Invalid cast!");
2164 // Construct and return the appropriate CastInst subclass
2166 case Trunc: return new TruncInst (S, Ty, Name, InsertAtEnd);
2167 case ZExt: return new ZExtInst (S, Ty, Name, InsertAtEnd);
2168 case SExt: return new SExtInst (S, Ty, Name, InsertAtEnd);
2169 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertAtEnd);
2170 case FPExt: return new FPExtInst (S, Ty, Name, InsertAtEnd);
2171 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertAtEnd);
2172 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertAtEnd);
2173 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertAtEnd);
2174 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertAtEnd);
2175 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertAtEnd);
2176 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertAtEnd);
2177 case BitCast: return new BitCastInst (S, Ty, Name, InsertAtEnd);
2179 assert(!"Invalid opcode provided");
2184 CastInst *CastInst::CreateZExtOrBitCast(Value *S, Type *Ty,
2186 Instruction *InsertBefore) {
2187 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2188 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2189 return Create(Instruction::ZExt, S, Ty, Name, InsertBefore);
2192 CastInst *CastInst::CreateZExtOrBitCast(Value *S, Type *Ty,
2194 BasicBlock *InsertAtEnd) {
2195 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2196 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2197 return Create(Instruction::ZExt, S, Ty, Name, InsertAtEnd);
2200 CastInst *CastInst::CreateSExtOrBitCast(Value *S, Type *Ty,
2202 Instruction *InsertBefore) {
2203 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2204 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2205 return Create(Instruction::SExt, S, Ty, Name, InsertBefore);
2208 CastInst *CastInst::CreateSExtOrBitCast(Value *S, Type *Ty,
2210 BasicBlock *InsertAtEnd) {
2211 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2212 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2213 return Create(Instruction::SExt, S, Ty, Name, InsertAtEnd);
2216 CastInst *CastInst::CreateTruncOrBitCast(Value *S, Type *Ty,
2218 Instruction *InsertBefore) {
2219 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2220 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2221 return Create(Instruction::Trunc, S, Ty, Name, InsertBefore);
2224 CastInst *CastInst::CreateTruncOrBitCast(Value *S, Type *Ty,
2226 BasicBlock *InsertAtEnd) {
2227 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2228 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2229 return Create(Instruction::Trunc, S, Ty, Name, InsertAtEnd);
2232 CastInst *CastInst::CreatePointerCast(Value *S, Type *Ty,
2234 BasicBlock *InsertAtEnd) {
2235 assert(S->getType()->isPointerTy() && "Invalid cast");
2236 assert((Ty->isIntegerTy() || Ty->isPointerTy()) &&
2239 if (Ty->isIntegerTy())
2240 return Create(Instruction::PtrToInt, S, Ty, Name, InsertAtEnd);
2241 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2244 /// @brief Create a BitCast or a PtrToInt cast instruction
2245 CastInst *CastInst::CreatePointerCast(Value *S, Type *Ty,
2247 Instruction *InsertBefore) {
2248 assert(S->getType()->isPointerTy() && "Invalid cast");
2249 assert((Ty->isIntegerTy() || Ty->isPointerTy()) &&
2252 if (Ty->isIntegerTy())
2253 return Create(Instruction::PtrToInt, S, Ty, Name, InsertBefore);
2254 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2257 CastInst *CastInst::CreateIntegerCast(Value *C, Type *Ty,
2258 bool isSigned, const Twine &Name,
2259 Instruction *InsertBefore) {
2260 assert(C->getType()->isIntOrIntVectorTy() && Ty->isIntOrIntVectorTy() &&
2261 "Invalid integer cast");
2262 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2263 unsigned DstBits = Ty->getScalarSizeInBits();
2264 Instruction::CastOps opcode =
2265 (SrcBits == DstBits ? Instruction::BitCast :
2266 (SrcBits > DstBits ? Instruction::Trunc :
2267 (isSigned ? Instruction::SExt : Instruction::ZExt)));
2268 return Create(opcode, C, Ty, Name, InsertBefore);
2271 CastInst *CastInst::CreateIntegerCast(Value *C, Type *Ty,
2272 bool isSigned, const Twine &Name,
2273 BasicBlock *InsertAtEnd) {
2274 assert(C->getType()->isIntOrIntVectorTy() && Ty->isIntOrIntVectorTy() &&
2276 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2277 unsigned DstBits = Ty->getScalarSizeInBits();
2278 Instruction::CastOps opcode =
2279 (SrcBits == DstBits ? Instruction::BitCast :
2280 (SrcBits > DstBits ? Instruction::Trunc :
2281 (isSigned ? Instruction::SExt : Instruction::ZExt)));
2282 return Create(opcode, C, Ty, Name, InsertAtEnd);
2285 CastInst *CastInst::CreateFPCast(Value *C, Type *Ty,
2287 Instruction *InsertBefore) {
2288 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
2290 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2291 unsigned DstBits = Ty->getScalarSizeInBits();
2292 Instruction::CastOps opcode =
2293 (SrcBits == DstBits ? Instruction::BitCast :
2294 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
2295 return Create(opcode, C, Ty, Name, InsertBefore);
2298 CastInst *CastInst::CreateFPCast(Value *C, Type *Ty,
2300 BasicBlock *InsertAtEnd) {
2301 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
2303 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2304 unsigned DstBits = Ty->getScalarSizeInBits();
2305 Instruction::CastOps opcode =
2306 (SrcBits == DstBits ? Instruction::BitCast :
2307 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
2308 return Create(opcode, C, Ty, Name, InsertAtEnd);
2311 // Check whether it is valid to call getCastOpcode for these types.
2312 // This routine must be kept in sync with getCastOpcode.
2313 bool CastInst::isCastable(Type *SrcTy, Type *DestTy) {
2314 if (!SrcTy->isFirstClassType() || !DestTy->isFirstClassType())
2317 if (SrcTy == DestTy)
2320 if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy))
2321 if (VectorType *DestVecTy = dyn_cast<VectorType>(DestTy))
2322 if (SrcVecTy->getNumElements() == DestVecTy->getNumElements()) {
2323 // An element by element cast. Valid if casting the elements is valid.
2324 SrcTy = SrcVecTy->getElementType();
2325 DestTy = DestVecTy->getElementType();
2328 // Get the bit sizes, we'll need these
2329 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); // 0 for ptr
2330 unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr
2332 // Run through the possibilities ...
2333 if (DestTy->isIntegerTy()) { // Casting to integral
2334 if (SrcTy->isIntegerTy()) { // Casting from integral
2336 } else if (SrcTy->isFloatingPointTy()) { // Casting from floating pt
2338 } else if (SrcTy->isVectorTy()) { // Casting from vector
2339 return DestBits == SrcBits;
2340 } else { // Casting from something else
2341 return SrcTy->isPointerTy();
2343 } else if (DestTy->isFloatingPointTy()) { // Casting to floating pt
2344 if (SrcTy->isIntegerTy()) { // Casting from integral
2346 } else if (SrcTy->isFloatingPointTy()) { // Casting from floating pt
2348 } else if (SrcTy->isVectorTy()) { // Casting from vector
2349 return DestBits == SrcBits;
2350 } else { // Casting from something else
2353 } else if (DestTy->isVectorTy()) { // Casting to vector
2354 return DestBits == SrcBits;
2355 } else if (DestTy->isPointerTy()) { // Casting to pointer
2356 if (SrcTy->isPointerTy()) { // Casting from pointer
2358 } else if (SrcTy->isIntegerTy()) { // Casting from integral
2360 } else { // Casting from something else
2363 } else if (DestTy->isX86_MMXTy()) {
2364 if (SrcTy->isVectorTy()) {
2365 return DestBits == SrcBits; // 64-bit vector to MMX
2369 } else { // Casting to something else
2374 // Provide a way to get a "cast" where the cast opcode is inferred from the
2375 // types and size of the operand. This, basically, is a parallel of the
2376 // logic in the castIsValid function below. This axiom should hold:
2377 // castIsValid( getCastOpcode(Val, Ty), Val, Ty)
2378 // should not assert in castIsValid. In other words, this produces a "correct"
2379 // casting opcode for the arguments passed to it.
2380 // This routine must be kept in sync with isCastable.
2381 Instruction::CastOps
2382 CastInst::getCastOpcode(
2383 const Value *Src, bool SrcIsSigned, Type *DestTy, bool DestIsSigned) {
2384 Type *SrcTy = Src->getType();
2386 assert(SrcTy->isFirstClassType() && DestTy->isFirstClassType() &&
2387 "Only first class types are castable!");
2389 if (SrcTy == DestTy)
2392 if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy))
2393 if (VectorType *DestVecTy = dyn_cast<VectorType>(DestTy))
2394 if (SrcVecTy->getNumElements() == DestVecTy->getNumElements()) {
2395 // An element by element cast. Find the appropriate opcode based on the
2397 SrcTy = SrcVecTy->getElementType();
2398 DestTy = DestVecTy->getElementType();
2401 // Get the bit sizes, we'll need these
2402 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); // 0 for ptr
2403 unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr
2405 // Run through the possibilities ...
2406 if (DestTy->isIntegerTy()) { // Casting to integral
2407 if (SrcTy->isIntegerTy()) { // Casting from integral
2408 if (DestBits < SrcBits)
2409 return Trunc; // int -> smaller int
2410 else if (DestBits > SrcBits) { // its an extension
2412 return SExt; // signed -> SEXT
2414 return ZExt; // unsigned -> ZEXT
2416 return BitCast; // Same size, No-op cast
2418 } else if (SrcTy->isFloatingPointTy()) { // Casting from floating pt
2420 return FPToSI; // FP -> sint
2422 return FPToUI; // FP -> uint
2423 } else if (SrcTy->isVectorTy()) {
2424 assert(DestBits == SrcBits &&
2425 "Casting vector to integer of different width");
2426 return BitCast; // Same size, no-op cast
2428 assert(SrcTy->isPointerTy() &&
2429 "Casting from a value that is not first-class type");
2430 return PtrToInt; // ptr -> int
2432 } else if (DestTy->isFloatingPointTy()) { // Casting to floating pt
2433 if (SrcTy->isIntegerTy()) { // Casting from integral
2435 return SIToFP; // sint -> FP
2437 return UIToFP; // uint -> FP
2438 } else if (SrcTy->isFloatingPointTy()) { // Casting from floating pt
2439 if (DestBits < SrcBits) {
2440 return FPTrunc; // FP -> smaller FP
2441 } else if (DestBits > SrcBits) {
2442 return FPExt; // FP -> larger FP
2444 return BitCast; // same size, no-op cast
2446 } else if (SrcTy->isVectorTy()) {
2447 assert(DestBits == SrcBits &&
2448 "Casting vector to floating point of different width");
2449 return BitCast; // same size, no-op cast
2451 llvm_unreachable("Casting pointer or non-first class to float");
2453 } else if (DestTy->isVectorTy()) {
2454 assert(DestBits == SrcBits &&
2455 "Illegal cast to vector (wrong type or size)");
2457 } else if (DestTy->isPointerTy()) {
2458 if (SrcTy->isPointerTy()) {
2459 return BitCast; // ptr -> ptr
2460 } else if (SrcTy->isIntegerTy()) {
2461 return IntToPtr; // int -> ptr
2463 assert(!"Casting pointer to other than pointer or int");
2465 } else if (DestTy->isX86_MMXTy()) {
2466 if (SrcTy->isVectorTy()) {
2467 assert(DestBits == SrcBits && "Casting vector of wrong width to X86_MMX");
2468 return BitCast; // 64-bit vector to MMX
2470 assert(!"Illegal cast to X86_MMX");
2473 assert(!"Casting to type that is not first-class");
2476 // If we fall through to here we probably hit an assertion cast above
2477 // and assertions are not turned on. Anything we return is an error, so
2478 // BitCast is as good a choice as any.
2482 //===----------------------------------------------------------------------===//
2483 // CastInst SubClass Constructors
2484 //===----------------------------------------------------------------------===//
2486 /// Check that the construction parameters for a CastInst are correct. This
2487 /// could be broken out into the separate constructors but it is useful to have
2488 /// it in one place and to eliminate the redundant code for getting the sizes
2489 /// of the types involved.
2491 CastInst::castIsValid(Instruction::CastOps op, Value *S, Type *DstTy) {
2493 // Check for type sanity on the arguments
2494 Type *SrcTy = S->getType();
2495 if (!SrcTy->isFirstClassType() || !DstTy->isFirstClassType() ||
2496 SrcTy->isAggregateType() || DstTy->isAggregateType())
2499 // Get the size of the types in bits, we'll need this later
2500 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
2501 unsigned DstBitSize = DstTy->getScalarSizeInBits();
2503 // If these are vector types, get the lengths of the vectors (using zero for
2504 // scalar types means that checking that vector lengths match also checks that
2505 // scalars are not being converted to vectors or vectors to scalars).
2506 unsigned SrcLength = SrcTy->isVectorTy() ?
2507 cast<VectorType>(SrcTy)->getNumElements() : 0;
2508 unsigned DstLength = DstTy->isVectorTy() ?
2509 cast<VectorType>(DstTy)->getNumElements() : 0;
2511 // Switch on the opcode provided
2513 default: return false; // This is an input error
2514 case Instruction::Trunc:
2515 return SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy() &&
2516 SrcLength == DstLength && SrcBitSize > DstBitSize;
2517 case Instruction::ZExt:
2518 return SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy() &&
2519 SrcLength == DstLength && SrcBitSize < DstBitSize;
2520 case Instruction::SExt:
2521 return SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy() &&
2522 SrcLength == DstLength && SrcBitSize < DstBitSize;
2523 case Instruction::FPTrunc:
2524 return SrcTy->isFPOrFPVectorTy() && DstTy->isFPOrFPVectorTy() &&
2525 SrcLength == DstLength && SrcBitSize > DstBitSize;
2526 case Instruction::FPExt:
2527 return SrcTy->isFPOrFPVectorTy() && DstTy->isFPOrFPVectorTy() &&
2528 SrcLength == DstLength && SrcBitSize < DstBitSize;
2529 case Instruction::UIToFP:
2530 case Instruction::SIToFP:
2531 return SrcTy->isIntOrIntVectorTy() && DstTy->isFPOrFPVectorTy() &&
2532 SrcLength == DstLength;
2533 case Instruction::FPToUI:
2534 case Instruction::FPToSI:
2535 return SrcTy->isFPOrFPVectorTy() && DstTy->isIntOrIntVectorTy() &&
2536 SrcLength == DstLength;
2537 case Instruction::PtrToInt:
2538 return SrcTy->isPointerTy() && DstTy->isIntegerTy();
2539 case Instruction::IntToPtr:
2540 return SrcTy->isIntegerTy() && DstTy->isPointerTy();
2541 case Instruction::BitCast:
2542 // BitCast implies a no-op cast of type only. No bits change.
2543 // However, you can't cast pointers to anything but pointers.
2544 if (SrcTy->isPointerTy() != DstTy->isPointerTy())
2547 // Now we know we're not dealing with a pointer/non-pointer mismatch. In all
2548 // these cases, the cast is okay if the source and destination bit widths
2550 return SrcTy->getPrimitiveSizeInBits() == DstTy->getPrimitiveSizeInBits();
2554 TruncInst::TruncInst(
2555 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2556 ) : CastInst(Ty, Trunc, S, Name, InsertBefore) {
2557 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
2560 TruncInst::TruncInst(
2561 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2562 ) : CastInst(Ty, Trunc, S, Name, InsertAtEnd) {
2563 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
2567 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2568 ) : CastInst(Ty, ZExt, S, Name, InsertBefore) {
2569 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
2573 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2574 ) : CastInst(Ty, ZExt, S, Name, InsertAtEnd) {
2575 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
2578 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2579 ) : CastInst(Ty, SExt, S, Name, InsertBefore) {
2580 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
2584 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2585 ) : CastInst(Ty, SExt, S, Name, InsertAtEnd) {
2586 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
2589 FPTruncInst::FPTruncInst(
2590 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2591 ) : CastInst(Ty, FPTrunc, S, Name, InsertBefore) {
2592 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
2595 FPTruncInst::FPTruncInst(
2596 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2597 ) : CastInst(Ty, FPTrunc, S, Name, InsertAtEnd) {
2598 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
2601 FPExtInst::FPExtInst(
2602 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2603 ) : CastInst(Ty, FPExt, S, Name, InsertBefore) {
2604 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
2607 FPExtInst::FPExtInst(
2608 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2609 ) : CastInst(Ty, FPExt, S, Name, InsertAtEnd) {
2610 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
2613 UIToFPInst::UIToFPInst(
2614 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2615 ) : CastInst(Ty, UIToFP, S, Name, InsertBefore) {
2616 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
2619 UIToFPInst::UIToFPInst(
2620 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2621 ) : CastInst(Ty, UIToFP, S, Name, InsertAtEnd) {
2622 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
2625 SIToFPInst::SIToFPInst(
2626 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2627 ) : CastInst(Ty, SIToFP, S, Name, InsertBefore) {
2628 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
2631 SIToFPInst::SIToFPInst(
2632 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2633 ) : CastInst(Ty, SIToFP, S, Name, InsertAtEnd) {
2634 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
2637 FPToUIInst::FPToUIInst(
2638 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2639 ) : CastInst(Ty, FPToUI, S, Name, InsertBefore) {
2640 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
2643 FPToUIInst::FPToUIInst(
2644 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2645 ) : CastInst(Ty, FPToUI, S, Name, InsertAtEnd) {
2646 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
2649 FPToSIInst::FPToSIInst(
2650 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2651 ) : CastInst(Ty, FPToSI, S, Name, InsertBefore) {
2652 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
2655 FPToSIInst::FPToSIInst(
2656 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2657 ) : CastInst(Ty, FPToSI, S, Name, InsertAtEnd) {
2658 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
2661 PtrToIntInst::PtrToIntInst(
2662 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2663 ) : CastInst(Ty, PtrToInt, S, Name, InsertBefore) {
2664 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
2667 PtrToIntInst::PtrToIntInst(
2668 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2669 ) : CastInst(Ty, PtrToInt, S, Name, InsertAtEnd) {
2670 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
2673 IntToPtrInst::IntToPtrInst(
2674 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2675 ) : CastInst(Ty, IntToPtr, S, Name, InsertBefore) {
2676 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
2679 IntToPtrInst::IntToPtrInst(
2680 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2681 ) : CastInst(Ty, IntToPtr, S, Name, InsertAtEnd) {
2682 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
2685 BitCastInst::BitCastInst(
2686 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2687 ) : CastInst(Ty, BitCast, S, Name, InsertBefore) {
2688 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
2691 BitCastInst::BitCastInst(
2692 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2693 ) : CastInst(Ty, BitCast, S, Name, InsertAtEnd) {
2694 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
2697 //===----------------------------------------------------------------------===//
2699 //===----------------------------------------------------------------------===//
2701 void CmpInst::Anchor() const {}
2703 CmpInst::CmpInst(Type *ty, OtherOps op, unsigned short predicate,
2704 Value *LHS, Value *RHS, const Twine &Name,
2705 Instruction *InsertBefore)
2706 : Instruction(ty, op,
2707 OperandTraits<CmpInst>::op_begin(this),
2708 OperandTraits<CmpInst>::operands(this),
2712 setPredicate((Predicate)predicate);
2716 CmpInst::CmpInst(Type *ty, OtherOps op, unsigned short predicate,
2717 Value *LHS, Value *RHS, const Twine &Name,
2718 BasicBlock *InsertAtEnd)
2719 : Instruction(ty, op,
2720 OperandTraits<CmpInst>::op_begin(this),
2721 OperandTraits<CmpInst>::operands(this),
2725 setPredicate((Predicate)predicate);
2730 CmpInst::Create(OtherOps Op, unsigned short predicate,
2731 Value *S1, Value *S2,
2732 const Twine &Name, Instruction *InsertBefore) {
2733 if (Op == Instruction::ICmp) {
2735 return new ICmpInst(InsertBefore, CmpInst::Predicate(predicate),
2738 return new ICmpInst(CmpInst::Predicate(predicate),
2743 return new FCmpInst(InsertBefore, CmpInst::Predicate(predicate),
2746 return new FCmpInst(CmpInst::Predicate(predicate),
2751 CmpInst::Create(OtherOps Op, unsigned short predicate, Value *S1, Value *S2,
2752 const Twine &Name, BasicBlock *InsertAtEnd) {
2753 if (Op == Instruction::ICmp) {
2754 return new ICmpInst(*InsertAtEnd, CmpInst::Predicate(predicate),
2757 return new FCmpInst(*InsertAtEnd, CmpInst::Predicate(predicate),
2761 void CmpInst::swapOperands() {
2762 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2765 cast<FCmpInst>(this)->swapOperands();
2768 bool CmpInst::isCommutative() const {
2769 if (const ICmpInst *IC = dyn_cast<ICmpInst>(this))
2770 return IC->isCommutative();
2771 return cast<FCmpInst>(this)->isCommutative();
2774 bool CmpInst::isEquality() const {
2775 if (const ICmpInst *IC = dyn_cast<ICmpInst>(this))
2776 return IC->isEquality();
2777 return cast<FCmpInst>(this)->isEquality();
2781 CmpInst::Predicate CmpInst::getInversePredicate(Predicate pred) {
2783 default: assert(!"Unknown cmp predicate!");
2784 case ICMP_EQ: return ICMP_NE;
2785 case ICMP_NE: return ICMP_EQ;
2786 case ICMP_UGT: return ICMP_ULE;
2787 case ICMP_ULT: return ICMP_UGE;
2788 case ICMP_UGE: return ICMP_ULT;
2789 case ICMP_ULE: return ICMP_UGT;
2790 case ICMP_SGT: return ICMP_SLE;
2791 case ICMP_SLT: return ICMP_SGE;
2792 case ICMP_SGE: return ICMP_SLT;
2793 case ICMP_SLE: return ICMP_SGT;
2795 case FCMP_OEQ: return FCMP_UNE;
2796 case FCMP_ONE: return FCMP_UEQ;
2797 case FCMP_OGT: return FCMP_ULE;
2798 case FCMP_OLT: return FCMP_UGE;
2799 case FCMP_OGE: return FCMP_ULT;
2800 case FCMP_OLE: return FCMP_UGT;
2801 case FCMP_UEQ: return FCMP_ONE;
2802 case FCMP_UNE: return FCMP_OEQ;
2803 case FCMP_UGT: return FCMP_OLE;
2804 case FCMP_ULT: return FCMP_OGE;
2805 case FCMP_UGE: return FCMP_OLT;
2806 case FCMP_ULE: return FCMP_OGT;
2807 case FCMP_ORD: return FCMP_UNO;
2808 case FCMP_UNO: return FCMP_ORD;
2809 case FCMP_TRUE: return FCMP_FALSE;
2810 case FCMP_FALSE: return FCMP_TRUE;
2814 ICmpInst::Predicate ICmpInst::getSignedPredicate(Predicate pred) {
2816 default: assert(! "Unknown icmp predicate!");
2817 case ICMP_EQ: case ICMP_NE:
2818 case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE:
2820 case ICMP_UGT: return ICMP_SGT;
2821 case ICMP_ULT: return ICMP_SLT;
2822 case ICMP_UGE: return ICMP_SGE;
2823 case ICMP_ULE: return ICMP_SLE;
2827 ICmpInst::Predicate ICmpInst::getUnsignedPredicate(Predicate pred) {
2829 default: assert(! "Unknown icmp predicate!");
2830 case ICMP_EQ: case ICMP_NE:
2831 case ICMP_UGT: case ICMP_ULT: case ICMP_UGE: case ICMP_ULE:
2833 case ICMP_SGT: return ICMP_UGT;
2834 case ICMP_SLT: return ICMP_ULT;
2835 case ICMP_SGE: return ICMP_UGE;
2836 case ICMP_SLE: return ICMP_ULE;
2840 /// Initialize a set of values that all satisfy the condition with C.
2843 ICmpInst::makeConstantRange(Predicate pred, const APInt &C) {
2846 uint32_t BitWidth = C.getBitWidth();
2848 default: llvm_unreachable("Invalid ICmp opcode to ConstantRange ctor!");
2849 case ICmpInst::ICMP_EQ: Upper++; break;
2850 case ICmpInst::ICMP_NE: Lower++; break;
2851 case ICmpInst::ICMP_ULT:
2852 Lower = APInt::getMinValue(BitWidth);
2853 // Check for an empty-set condition.
2855 return ConstantRange(BitWidth, /*isFullSet=*/false);
2857 case ICmpInst::ICMP_SLT:
2858 Lower = APInt::getSignedMinValue(BitWidth);
2859 // Check for an empty-set condition.
2861 return ConstantRange(BitWidth, /*isFullSet=*/false);
2863 case ICmpInst::ICMP_UGT:
2864 Lower++; Upper = APInt::getMinValue(BitWidth); // Min = Next(Max)
2865 // Check for an empty-set condition.
2867 return ConstantRange(BitWidth, /*isFullSet=*/false);
2869 case ICmpInst::ICMP_SGT:
2870 Lower++; Upper = APInt::getSignedMinValue(BitWidth); // Min = Next(Max)
2871 // Check for an empty-set condition.
2873 return ConstantRange(BitWidth, /*isFullSet=*/false);
2875 case ICmpInst::ICMP_ULE:
2876 Lower = APInt::getMinValue(BitWidth); Upper++;
2877 // Check for a full-set condition.
2879 return ConstantRange(BitWidth, /*isFullSet=*/true);
2881 case ICmpInst::ICMP_SLE:
2882 Lower = APInt::getSignedMinValue(BitWidth); Upper++;
2883 // Check for a full-set condition.
2885 return ConstantRange(BitWidth, /*isFullSet=*/true);
2887 case ICmpInst::ICMP_UGE:
2888 Upper = APInt::getMinValue(BitWidth); // Min = Next(Max)
2889 // Check for a full-set condition.
2891 return ConstantRange(BitWidth, /*isFullSet=*/true);
2893 case ICmpInst::ICMP_SGE:
2894 Upper = APInt::getSignedMinValue(BitWidth); // Min = Next(Max)
2895 // Check for a full-set condition.
2897 return ConstantRange(BitWidth, /*isFullSet=*/true);
2900 return ConstantRange(Lower, Upper);
2903 CmpInst::Predicate CmpInst::getSwappedPredicate(Predicate pred) {
2905 default: assert(!"Unknown cmp predicate!");
2906 case ICMP_EQ: case ICMP_NE:
2908 case ICMP_SGT: return ICMP_SLT;
2909 case ICMP_SLT: return ICMP_SGT;
2910 case ICMP_SGE: return ICMP_SLE;
2911 case ICMP_SLE: return ICMP_SGE;
2912 case ICMP_UGT: return ICMP_ULT;
2913 case ICMP_ULT: return ICMP_UGT;
2914 case ICMP_UGE: return ICMP_ULE;
2915 case ICMP_ULE: return ICMP_UGE;
2917 case FCMP_FALSE: case FCMP_TRUE:
2918 case FCMP_OEQ: case FCMP_ONE:
2919 case FCMP_UEQ: case FCMP_UNE:
2920 case FCMP_ORD: case FCMP_UNO:
2922 case FCMP_OGT: return FCMP_OLT;
2923 case FCMP_OLT: return FCMP_OGT;
2924 case FCMP_OGE: return FCMP_OLE;
2925 case FCMP_OLE: return FCMP_OGE;
2926 case FCMP_UGT: return FCMP_ULT;
2927 case FCMP_ULT: return FCMP_UGT;
2928 case FCMP_UGE: return FCMP_ULE;
2929 case FCMP_ULE: return FCMP_UGE;
2933 bool CmpInst::isUnsigned(unsigned short predicate) {
2934 switch (predicate) {
2935 default: return false;
2936 case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_ULE: case ICmpInst::ICMP_UGT:
2937 case ICmpInst::ICMP_UGE: return true;
2941 bool CmpInst::isSigned(unsigned short predicate) {
2942 switch (predicate) {
2943 default: return false;
2944 case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_SLE: case ICmpInst::ICMP_SGT:
2945 case ICmpInst::ICMP_SGE: return true;
2949 bool CmpInst::isOrdered(unsigned short predicate) {
2950 switch (predicate) {
2951 default: return false;
2952 case FCmpInst::FCMP_OEQ: case FCmpInst::FCMP_ONE: case FCmpInst::FCMP_OGT:
2953 case FCmpInst::FCMP_OLT: case FCmpInst::FCMP_OGE: case FCmpInst::FCMP_OLE:
2954 case FCmpInst::FCMP_ORD: return true;
2958 bool CmpInst::isUnordered(unsigned short predicate) {
2959 switch (predicate) {
2960 default: return false;
2961 case FCmpInst::FCMP_UEQ: case FCmpInst::FCMP_UNE: case FCmpInst::FCMP_UGT:
2962 case FCmpInst::FCMP_ULT: case FCmpInst::FCMP_UGE: case FCmpInst::FCMP_ULE:
2963 case FCmpInst::FCMP_UNO: return true;
2967 bool CmpInst::isTrueWhenEqual(unsigned short predicate) {
2969 default: return false;
2970 case ICMP_EQ: case ICMP_UGE: case ICMP_ULE: case ICMP_SGE: case ICMP_SLE:
2971 case FCMP_TRUE: case FCMP_UEQ: case FCMP_UGE: case FCMP_ULE: return true;
2975 bool CmpInst::isFalseWhenEqual(unsigned short predicate) {
2977 case ICMP_NE: case ICMP_UGT: case ICMP_ULT: case ICMP_SGT: case ICMP_SLT:
2978 case FCMP_FALSE: case FCMP_ONE: case FCMP_OGT: case FCMP_OLT: return true;
2979 default: return false;
2984 //===----------------------------------------------------------------------===//
2985 // SwitchInst Implementation
2986 //===----------------------------------------------------------------------===//
2988 void SwitchInst::init(Value *Value, BasicBlock *Default, unsigned NumReserved) {
2989 assert(Value && Default && NumReserved);
2990 ReservedSpace = NumReserved;
2992 OperandList = allocHungoffUses(ReservedSpace);
2994 OperandList[0] = Value;
2995 OperandList[1] = Default;
2998 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
2999 /// switch on and a default destination. The number of additional cases can
3000 /// be specified here to make memory allocation more efficient. This
3001 /// constructor can also autoinsert before another instruction.
3002 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
3003 Instruction *InsertBefore)
3004 : TerminatorInst(Type::getVoidTy(Value->getContext()), Instruction::Switch,
3005 0, 0, InsertBefore) {
3006 init(Value, Default, 2+NumCases*2);
3009 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
3010 /// switch on and a default destination. The number of additional cases can
3011 /// be specified here to make memory allocation more efficient. This
3012 /// constructor also autoinserts at the end of the specified BasicBlock.
3013 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
3014 BasicBlock *InsertAtEnd)
3015 : TerminatorInst(Type::getVoidTy(Value->getContext()), Instruction::Switch,
3016 0, 0, InsertAtEnd) {
3017 init(Value, Default, 2+NumCases*2);
3020 SwitchInst::SwitchInst(const SwitchInst &SI)
3021 : TerminatorInst(SI.getType(), Instruction::Switch, 0, 0) {
3022 init(SI.getCondition(), SI.getDefaultDest(), SI.getNumOperands());
3023 NumOperands = SI.getNumOperands();
3024 Use *OL = OperandList, *InOL = SI.OperandList;
3025 for (unsigned i = 2, E = SI.getNumOperands(); i != E; i += 2) {
3027 OL[i+1] = InOL[i+1];
3029 SubclassOptionalData = SI.SubclassOptionalData;
3032 SwitchInst::~SwitchInst() {
3037 /// addCase - Add an entry to the switch instruction...
3039 void SwitchInst::addCase(ConstantInt *OnVal, BasicBlock *Dest) {
3040 unsigned OpNo = NumOperands;
3041 if (OpNo+2 > ReservedSpace)
3042 growOperands(); // Get more space!
3043 // Initialize some new operands.
3044 assert(OpNo+1 < ReservedSpace && "Growing didn't work!");
3045 NumOperands = OpNo+2;
3046 OperandList[OpNo] = OnVal;
3047 OperandList[OpNo+1] = Dest;
3050 /// removeCase - This method removes the specified successor from the switch
3051 /// instruction. Note that this cannot be used to remove the default
3052 /// destination (successor #0).
3054 void SwitchInst::removeCase(unsigned idx) {
3055 assert(idx != 0 && "Cannot remove the default case!");
3056 assert(idx*2 < getNumOperands() && "Successor index out of range!!!");
3058 unsigned NumOps = getNumOperands();
3059 Use *OL = OperandList;
3061 // Overwrite this case with the end of the list.
3062 if ((idx + 1) * 2 != NumOps) {
3063 OL[idx * 2] = OL[NumOps - 2];
3064 OL[idx * 2 + 1] = OL[NumOps - 1];
3067 // Nuke the last value.
3068 OL[NumOps-2].set(0);
3069 OL[NumOps-2+1].set(0);
3070 NumOperands = NumOps-2;
3073 /// growOperands - grow operands - This grows the operand list in response
3074 /// to a push_back style of operation. This grows the number of ops by 3 times.
3076 void SwitchInst::growOperands() {
3077 unsigned e = getNumOperands();
3078 unsigned NumOps = e*3;
3080 ReservedSpace = NumOps;
3081 Use *NewOps = allocHungoffUses(NumOps);
3082 Use *OldOps = OperandList;
3083 for (unsigned i = 0; i != e; ++i) {
3084 NewOps[i] = OldOps[i];
3086 OperandList = NewOps;
3087 Use::zap(OldOps, OldOps + e, true);
3091 BasicBlock *SwitchInst::getSuccessorV(unsigned idx) const {
3092 return getSuccessor(idx);
3094 unsigned SwitchInst::getNumSuccessorsV() const {
3095 return getNumSuccessors();
3097 void SwitchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
3098 setSuccessor(idx, B);
3101 //===----------------------------------------------------------------------===//
3102 // IndirectBrInst Implementation
3103 //===----------------------------------------------------------------------===//
3105 void IndirectBrInst::init(Value *Address, unsigned NumDests) {
3106 assert(Address && Address->getType()->isPointerTy() &&
3107 "Address of indirectbr must be a pointer");
3108 ReservedSpace = 1+NumDests;
3110 OperandList = allocHungoffUses(ReservedSpace);
3112 OperandList[0] = Address;
3116 /// growOperands - grow operands - This grows the operand list in response
3117 /// to a push_back style of operation. This grows the number of ops by 2 times.
3119 void IndirectBrInst::growOperands() {
3120 unsigned e = getNumOperands();
3121 unsigned NumOps = e*2;
3123 ReservedSpace = NumOps;
3124 Use *NewOps = allocHungoffUses(NumOps);
3125 Use *OldOps = OperandList;
3126 for (unsigned i = 0; i != e; ++i)
3127 NewOps[i] = OldOps[i];
3128 OperandList = NewOps;
3129 Use::zap(OldOps, OldOps + e, true);
3132 IndirectBrInst::IndirectBrInst(Value *Address, unsigned NumCases,
3133 Instruction *InsertBefore)
3134 : TerminatorInst(Type::getVoidTy(Address->getContext()),Instruction::IndirectBr,
3135 0, 0, InsertBefore) {
3136 init(Address, NumCases);
3139 IndirectBrInst::IndirectBrInst(Value *Address, unsigned NumCases,
3140 BasicBlock *InsertAtEnd)
3141 : TerminatorInst(Type::getVoidTy(Address->getContext()),Instruction::IndirectBr,
3142 0, 0, InsertAtEnd) {
3143 init(Address, NumCases);
3146 IndirectBrInst::IndirectBrInst(const IndirectBrInst &IBI)
3147 : TerminatorInst(Type::getVoidTy(IBI.getContext()), Instruction::IndirectBr,
3148 allocHungoffUses(IBI.getNumOperands()),
3149 IBI.getNumOperands()) {
3150 Use *OL = OperandList, *InOL = IBI.OperandList;
3151 for (unsigned i = 0, E = IBI.getNumOperands(); i != E; ++i)
3153 SubclassOptionalData = IBI.SubclassOptionalData;
3156 IndirectBrInst::~IndirectBrInst() {
3160 /// addDestination - Add a destination.
3162 void IndirectBrInst::addDestination(BasicBlock *DestBB) {
3163 unsigned OpNo = NumOperands;
3164 if (OpNo+1 > ReservedSpace)
3165 growOperands(); // Get more space!
3166 // Initialize some new operands.
3167 assert(OpNo < ReservedSpace && "Growing didn't work!");
3168 NumOperands = OpNo+1;
3169 OperandList[OpNo] = DestBB;
3172 /// removeDestination - This method removes the specified successor from the
3173 /// indirectbr instruction.
3174 void IndirectBrInst::removeDestination(unsigned idx) {
3175 assert(idx < getNumOperands()-1 && "Successor index out of range!");
3177 unsigned NumOps = getNumOperands();
3178 Use *OL = OperandList;
3180 // Replace this value with the last one.
3181 OL[idx+1] = OL[NumOps-1];
3183 // Nuke the last value.
3184 OL[NumOps-1].set(0);
3185 NumOperands = NumOps-1;
3188 BasicBlock *IndirectBrInst::getSuccessorV(unsigned idx) const {
3189 return getSuccessor(idx);
3191 unsigned IndirectBrInst::getNumSuccessorsV() const {
3192 return getNumSuccessors();
3194 void IndirectBrInst::setSuccessorV(unsigned idx, BasicBlock *B) {
3195 setSuccessor(idx, B);
3198 //===----------------------------------------------------------------------===//
3199 // clone_impl() implementations
3200 //===----------------------------------------------------------------------===//
3202 // Define these methods here so vtables don't get emitted into every translation
3203 // unit that uses these classes.
3205 GetElementPtrInst *GetElementPtrInst::clone_impl() const {
3206 return new (getNumOperands()) GetElementPtrInst(*this);
3209 BinaryOperator *BinaryOperator::clone_impl() const {
3210 return Create(getOpcode(), Op<0>(), Op<1>());
3213 FCmpInst* FCmpInst::clone_impl() const {
3214 return new FCmpInst(getPredicate(), Op<0>(), Op<1>());
3217 ICmpInst* ICmpInst::clone_impl() const {
3218 return new ICmpInst(getPredicate(), Op<0>(), Op<1>());
3221 ExtractValueInst *ExtractValueInst::clone_impl() const {
3222 return new ExtractValueInst(*this);
3225 InsertValueInst *InsertValueInst::clone_impl() const {
3226 return new InsertValueInst(*this);
3229 AllocaInst *AllocaInst::clone_impl() const {
3230 return new AllocaInst(getAllocatedType(),
3231 (Value*)getOperand(0),
3235 LoadInst *LoadInst::clone_impl() const {
3236 return new LoadInst(getOperand(0),
3237 Twine(), isVolatile(),
3241 StoreInst *StoreInst::clone_impl() const {
3242 return new StoreInst(getOperand(0), getOperand(1),
3243 isVolatile(), getAlignment());
3246 AtomicCmpXchgInst *AtomicCmpXchgInst::clone_impl() const {
3247 AtomicCmpXchgInst *Result =
3248 new AtomicCmpXchgInst(getOperand(0), getOperand(1), getOperand(2),
3249 getOrdering(), getSynchScope());
3250 Result->setVolatile(isVolatile());
3254 AtomicRMWInst *AtomicRMWInst::clone_impl() const {
3255 AtomicRMWInst *Result =
3256 new AtomicRMWInst(getOperation(),getOperand(0), getOperand(1),
3257 getOrdering(), getSynchScope());
3258 Result->setVolatile(isVolatile());
3262 FenceInst *FenceInst::clone_impl() const {
3263 return new FenceInst(getContext(), getOrdering(), getSynchScope());
3266 TruncInst *TruncInst::clone_impl() const {
3267 return new TruncInst(getOperand(0), getType());
3270 ZExtInst *ZExtInst::clone_impl() const {
3271 return new ZExtInst(getOperand(0), getType());
3274 SExtInst *SExtInst::clone_impl() const {
3275 return new SExtInst(getOperand(0), getType());
3278 FPTruncInst *FPTruncInst::clone_impl() const {
3279 return new FPTruncInst(getOperand(0), getType());
3282 FPExtInst *FPExtInst::clone_impl() const {
3283 return new FPExtInst(getOperand(0), getType());
3286 UIToFPInst *UIToFPInst::clone_impl() const {
3287 return new UIToFPInst(getOperand(0), getType());
3290 SIToFPInst *SIToFPInst::clone_impl() const {
3291 return new SIToFPInst(getOperand(0), getType());
3294 FPToUIInst *FPToUIInst::clone_impl() const {
3295 return new FPToUIInst(getOperand(0), getType());
3298 FPToSIInst *FPToSIInst::clone_impl() const {
3299 return new FPToSIInst(getOperand(0), getType());
3302 PtrToIntInst *PtrToIntInst::clone_impl() const {
3303 return new PtrToIntInst(getOperand(0), getType());
3306 IntToPtrInst *IntToPtrInst::clone_impl() const {
3307 return new IntToPtrInst(getOperand(0), getType());
3310 BitCastInst *BitCastInst::clone_impl() const {
3311 return new BitCastInst(getOperand(0), getType());
3314 CallInst *CallInst::clone_impl() const {
3315 return new(getNumOperands()) CallInst(*this);
3318 SelectInst *SelectInst::clone_impl() const {
3319 return SelectInst::Create(getOperand(0), getOperand(1), getOperand(2));
3322 VAArgInst *VAArgInst::clone_impl() const {
3323 return new VAArgInst(getOperand(0), getType());
3326 ExtractElementInst *ExtractElementInst::clone_impl() const {
3327 return ExtractElementInst::Create(getOperand(0), getOperand(1));
3330 InsertElementInst *InsertElementInst::clone_impl() const {
3331 return InsertElementInst::Create(getOperand(0),
3336 ShuffleVectorInst *ShuffleVectorInst::clone_impl() const {
3337 return new ShuffleVectorInst(getOperand(0),
3342 PHINode *PHINode::clone_impl() const {
3343 return new PHINode(*this);
3346 LandingPadInst *LandingPadInst::clone_impl() const {
3347 return new LandingPadInst(*this);
3350 ReturnInst *ReturnInst::clone_impl() const {
3351 return new(getNumOperands()) ReturnInst(*this);
3354 BranchInst *BranchInst::clone_impl() const {
3355 return new(getNumOperands()) BranchInst(*this);
3358 SwitchInst *SwitchInst::clone_impl() const {
3359 return new SwitchInst(*this);
3362 IndirectBrInst *IndirectBrInst::clone_impl() const {
3363 return new IndirectBrInst(*this);
3367 InvokeInst *InvokeInst::clone_impl() const {
3368 return new(getNumOperands()) InvokeInst(*this);
3371 ResumeInst *ResumeInst::clone_impl() const {
3372 return new(1) ResumeInst(*this);
3375 UnwindInst *UnwindInst::clone_impl() const {
3376 LLVMContext &Context = getContext();
3377 return new UnwindInst(Context);
3380 UnreachableInst *UnreachableInst::clone_impl() const {
3381 LLVMContext &Context = getContext();
3382 return new UnreachableInst(Context);