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 LandingPadInst::LandingPadInst(Type *RetTy, Value *PersonalityFn,
174 unsigned NumReservedValues, const Twine &NameStr,
175 Instruction *InsertBefore)
176 : Instruction(RetTy, Instruction::LandingPad, 0, 0, InsertBefore) {
177 init(PersonalityFn, 1 + NumReservedValues, NameStr);
180 LandingPadInst::LandingPadInst(Type *RetTy, Value *PersonalityFn,
181 unsigned NumReservedValues, const Twine &NameStr,
182 BasicBlock *InsertAtEnd)
183 : Instruction(RetTy, Instruction::LandingPad, 0, 0, InsertAtEnd) {
184 init(PersonalityFn, 1 + NumReservedValues, NameStr);
187 LandingPadInst::LandingPadInst(const LandingPadInst &LP)
188 : Instruction(LP.getType(), Instruction::LandingPad,
189 allocHungoffUses(LP.getNumOperands()), LP.getNumOperands()),
190 ReservedSpace(LP.getNumOperands()) {
191 Use *OL = OperandList, *InOL = LP.OperandList;
192 for (unsigned I = 0, E = ReservedSpace; I != E; ++I)
195 setCleanup(LP.isCleanup());
198 LandingPadInst::~LandingPadInst() {
202 LandingPadInst *LandingPadInst::Create(Type *RetTy, Value *PersonalityFn,
203 unsigned NumReservedClauses,
204 const Twine &NameStr,
205 Instruction *InsertBefore) {
206 return new LandingPadInst(RetTy, PersonalityFn, NumReservedClauses, NameStr,
210 LandingPadInst *LandingPadInst::Create(Type *RetTy, Value *PersonalityFn,
211 unsigned NumReservedClauses,
212 const Twine &NameStr,
213 BasicBlock *InsertAtEnd) {
214 return new LandingPadInst(RetTy, PersonalityFn, NumReservedClauses, NameStr,
218 void LandingPadInst::init(Value *PersFn, unsigned NumReservedValues,
219 const Twine &NameStr) {
220 ReservedSpace = NumReservedValues;
222 OperandList = allocHungoffUses(ReservedSpace);
223 OperandList[0] = PersFn;
228 /// growOperands - grow operands - This grows the operand list in response to a
229 /// push_back style of operation. This grows the number of ops by 2 times.
230 void LandingPadInst::growOperands(unsigned Size) {
231 unsigned e = getNumOperands();
232 if (ReservedSpace >= e + Size) return;
233 ReservedSpace = (e + Size / 2) * 2;
235 Use *NewOps = allocHungoffUses(ReservedSpace);
236 Use *OldOps = OperandList;
237 for (unsigned i = 0; i != e; ++i)
238 NewOps[i] = OldOps[i];
240 OperandList = NewOps;
241 Use::zap(OldOps, OldOps + e, true);
244 void LandingPadInst::addClause(Value *Val) {
245 unsigned OpNo = getNumOperands();
247 assert(OpNo < ReservedSpace && "Growing didn't work!");
249 OperandList[OpNo] = Val;
252 //===----------------------------------------------------------------------===//
253 // CallInst Implementation
254 //===----------------------------------------------------------------------===//
256 CallInst::~CallInst() {
259 void CallInst::init(Value *Func, ArrayRef<Value *> Args, const Twine &NameStr) {
260 assert(NumOperands == Args.size() + 1 && "NumOperands not set up?");
265 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
267 assert((Args.size() == FTy->getNumParams() ||
268 (FTy->isVarArg() && Args.size() > FTy->getNumParams())) &&
269 "Calling a function with bad signature!");
271 for (unsigned i = 0; i != Args.size(); ++i)
272 assert((i >= FTy->getNumParams() ||
273 FTy->getParamType(i) == Args[i]->getType()) &&
274 "Calling a function with a bad signature!");
277 std::copy(Args.begin(), Args.end(), op_begin());
281 void CallInst::init(Value *Func, const Twine &NameStr) {
282 assert(NumOperands == 1 && "NumOperands not set up?");
287 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
289 assert(FTy->getNumParams() == 0 && "Calling a function with bad signature");
295 CallInst::CallInst(Value *Func, const Twine &Name,
296 Instruction *InsertBefore)
297 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
298 ->getElementType())->getReturnType(),
300 OperandTraits<CallInst>::op_end(this) - 1,
305 CallInst::CallInst(Value *Func, const Twine &Name,
306 BasicBlock *InsertAtEnd)
307 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
308 ->getElementType())->getReturnType(),
310 OperandTraits<CallInst>::op_end(this) - 1,
315 CallInst::CallInst(const CallInst &CI)
316 : Instruction(CI.getType(), Instruction::Call,
317 OperandTraits<CallInst>::op_end(this) - CI.getNumOperands(),
318 CI.getNumOperands()) {
319 setAttributes(CI.getAttributes());
320 setTailCall(CI.isTailCall());
321 setCallingConv(CI.getCallingConv());
323 std::copy(CI.op_begin(), CI.op_end(), op_begin());
324 SubclassOptionalData = CI.SubclassOptionalData;
327 void CallInst::addAttribute(unsigned i, Attributes attr) {
328 AttrListPtr PAL = getAttributes();
329 PAL = PAL.addAttr(i, attr);
333 void CallInst::removeAttribute(unsigned i, Attributes attr) {
334 AttrListPtr PAL = getAttributes();
335 PAL = PAL.removeAttr(i, attr);
339 bool CallInst::paramHasAttr(unsigned i, Attributes attr) const {
340 if (AttributeList.paramHasAttr(i, attr))
342 if (const Function *F = getCalledFunction())
343 return F->paramHasAttr(i, attr);
347 /// IsConstantOne - Return true only if val is constant int 1
348 static bool IsConstantOne(Value *val) {
349 assert(val && "IsConstantOne does not work with NULL val");
350 return isa<ConstantInt>(val) && cast<ConstantInt>(val)->isOne();
353 static Instruction *createMalloc(Instruction *InsertBefore,
354 BasicBlock *InsertAtEnd, Type *IntPtrTy,
355 Type *AllocTy, Value *AllocSize,
356 Value *ArraySize, Function *MallocF,
358 assert(((!InsertBefore && InsertAtEnd) || (InsertBefore && !InsertAtEnd)) &&
359 "createMalloc needs either InsertBefore or InsertAtEnd");
361 // malloc(type) becomes:
362 // bitcast (i8* malloc(typeSize)) to type*
363 // malloc(type, arraySize) becomes:
364 // bitcast (i8 *malloc(typeSize*arraySize)) to type*
366 ArraySize = ConstantInt::get(IntPtrTy, 1);
367 else if (ArraySize->getType() != IntPtrTy) {
369 ArraySize = CastInst::CreateIntegerCast(ArraySize, IntPtrTy, false,
372 ArraySize = CastInst::CreateIntegerCast(ArraySize, IntPtrTy, false,
376 if (!IsConstantOne(ArraySize)) {
377 if (IsConstantOne(AllocSize)) {
378 AllocSize = ArraySize; // Operand * 1 = Operand
379 } else if (Constant *CO = dyn_cast<Constant>(ArraySize)) {
380 Constant *Scale = ConstantExpr::getIntegerCast(CO, IntPtrTy,
382 // Malloc arg is constant product of type size and array size
383 AllocSize = ConstantExpr::getMul(Scale, cast<Constant>(AllocSize));
385 // Multiply type size by the array size...
387 AllocSize = BinaryOperator::CreateMul(ArraySize, AllocSize,
388 "mallocsize", InsertBefore);
390 AllocSize = BinaryOperator::CreateMul(ArraySize, AllocSize,
391 "mallocsize", InsertAtEnd);
395 assert(AllocSize->getType() == IntPtrTy && "malloc arg is wrong size");
396 // Create the call to Malloc.
397 BasicBlock* BB = InsertBefore ? InsertBefore->getParent() : InsertAtEnd;
398 Module* M = BB->getParent()->getParent();
399 Type *BPTy = Type::getInt8PtrTy(BB->getContext());
400 Value *MallocFunc = MallocF;
402 // prototype malloc as "void *malloc(size_t)"
403 MallocFunc = M->getOrInsertFunction("malloc", BPTy, IntPtrTy, NULL);
404 PointerType *AllocPtrType = PointerType::getUnqual(AllocTy);
405 CallInst *MCall = NULL;
406 Instruction *Result = NULL;
408 MCall = CallInst::Create(MallocFunc, AllocSize, "malloccall", InsertBefore);
410 if (Result->getType() != AllocPtrType)
411 // Create a cast instruction to convert to the right type...
412 Result = new BitCastInst(MCall, AllocPtrType, Name, InsertBefore);
414 MCall = CallInst::Create(MallocFunc, AllocSize, "malloccall");
416 if (Result->getType() != AllocPtrType) {
417 InsertAtEnd->getInstList().push_back(MCall);
418 // Create a cast instruction to convert to the right type...
419 Result = new BitCastInst(MCall, AllocPtrType, Name);
422 MCall->setTailCall();
423 if (Function *F = dyn_cast<Function>(MallocFunc)) {
424 MCall->setCallingConv(F->getCallingConv());
425 if (!F->doesNotAlias(0)) F->setDoesNotAlias(0);
427 assert(!MCall->getType()->isVoidTy() && "Malloc has void return type");
432 /// CreateMalloc - Generate the IR for a call to malloc:
433 /// 1. Compute the malloc call's argument as the specified type's size,
434 /// possibly multiplied by the array size if the array size is not
436 /// 2. Call malloc with that argument.
437 /// 3. Bitcast the result of the malloc call to the specified type.
438 Instruction *CallInst::CreateMalloc(Instruction *InsertBefore,
439 Type *IntPtrTy, Type *AllocTy,
440 Value *AllocSize, Value *ArraySize,
443 return createMalloc(InsertBefore, NULL, IntPtrTy, AllocTy, AllocSize,
444 ArraySize, MallocF, Name);
447 /// CreateMalloc - Generate the IR for a call to malloc:
448 /// 1. Compute the malloc call's argument as the specified type's size,
449 /// possibly multiplied by the array size if the array size is not
451 /// 2. Call malloc with that argument.
452 /// 3. Bitcast the result of the malloc call to the specified type.
453 /// Note: This function does not add the bitcast to the basic block, that is the
454 /// responsibility of the caller.
455 Instruction *CallInst::CreateMalloc(BasicBlock *InsertAtEnd,
456 Type *IntPtrTy, Type *AllocTy,
457 Value *AllocSize, Value *ArraySize,
458 Function *MallocF, const Twine &Name) {
459 return createMalloc(NULL, InsertAtEnd, IntPtrTy, AllocTy, AllocSize,
460 ArraySize, MallocF, Name);
463 static Instruction* createFree(Value* Source, Instruction *InsertBefore,
464 BasicBlock *InsertAtEnd) {
465 assert(((!InsertBefore && InsertAtEnd) || (InsertBefore && !InsertAtEnd)) &&
466 "createFree needs either InsertBefore or InsertAtEnd");
467 assert(Source->getType()->isPointerTy() &&
468 "Can not free something of nonpointer type!");
470 BasicBlock* BB = InsertBefore ? InsertBefore->getParent() : InsertAtEnd;
471 Module* M = BB->getParent()->getParent();
473 Type *VoidTy = Type::getVoidTy(M->getContext());
474 Type *IntPtrTy = Type::getInt8PtrTy(M->getContext());
475 // prototype free as "void free(void*)"
476 Value *FreeFunc = M->getOrInsertFunction("free", VoidTy, IntPtrTy, NULL);
477 CallInst* Result = NULL;
478 Value *PtrCast = Source;
480 if (Source->getType() != IntPtrTy)
481 PtrCast = new BitCastInst(Source, IntPtrTy, "", InsertBefore);
482 Result = CallInst::Create(FreeFunc, PtrCast, "", InsertBefore);
484 if (Source->getType() != IntPtrTy)
485 PtrCast = new BitCastInst(Source, IntPtrTy, "", InsertAtEnd);
486 Result = CallInst::Create(FreeFunc, PtrCast, "");
488 Result->setTailCall();
489 if (Function *F = dyn_cast<Function>(FreeFunc))
490 Result->setCallingConv(F->getCallingConv());
495 /// CreateFree - Generate the IR for a call to the builtin free function.
496 Instruction * CallInst::CreateFree(Value* Source, Instruction *InsertBefore) {
497 return createFree(Source, InsertBefore, NULL);
500 /// CreateFree - Generate the IR for a call to the builtin free function.
501 /// Note: This function does not add the call to the basic block, that is the
502 /// responsibility of the caller.
503 Instruction* CallInst::CreateFree(Value* Source, BasicBlock *InsertAtEnd) {
504 Instruction* FreeCall = createFree(Source, NULL, InsertAtEnd);
505 assert(FreeCall && "CreateFree did not create a CallInst");
509 //===----------------------------------------------------------------------===//
510 // InvokeInst Implementation
511 //===----------------------------------------------------------------------===//
513 void InvokeInst::init(Value *Fn, BasicBlock *IfNormal, BasicBlock *IfException,
514 ArrayRef<Value *> Args, const Twine &NameStr) {
515 assert(NumOperands == 3 + Args.size() && "NumOperands not set up?");
518 Op<-1>() = IfException;
522 cast<FunctionType>(cast<PointerType>(Fn->getType())->getElementType());
524 assert(((Args.size() == FTy->getNumParams()) ||
525 (FTy->isVarArg() && Args.size() > FTy->getNumParams())) &&
526 "Invoking a function with bad signature");
528 for (unsigned i = 0, e = Args.size(); i != e; i++)
529 assert((i >= FTy->getNumParams() ||
530 FTy->getParamType(i) == Args[i]->getType()) &&
531 "Invoking a function with a bad signature!");
534 std::copy(Args.begin(), Args.end(), op_begin());
538 InvokeInst::InvokeInst(const InvokeInst &II)
539 : TerminatorInst(II.getType(), Instruction::Invoke,
540 OperandTraits<InvokeInst>::op_end(this)
541 - II.getNumOperands(),
542 II.getNumOperands()) {
543 setAttributes(II.getAttributes());
544 setCallingConv(II.getCallingConv());
545 std::copy(II.op_begin(), II.op_end(), op_begin());
546 SubclassOptionalData = II.SubclassOptionalData;
549 BasicBlock *InvokeInst::getSuccessorV(unsigned idx) const {
550 return getSuccessor(idx);
552 unsigned InvokeInst::getNumSuccessorsV() const {
553 return getNumSuccessors();
555 void InvokeInst::setSuccessorV(unsigned idx, BasicBlock *B) {
556 return setSuccessor(idx, B);
559 bool InvokeInst::paramHasAttr(unsigned i, Attributes attr) const {
560 if (AttributeList.paramHasAttr(i, attr))
562 if (const Function *F = getCalledFunction())
563 return F->paramHasAttr(i, attr);
567 void InvokeInst::addAttribute(unsigned i, Attributes attr) {
568 AttrListPtr PAL = getAttributes();
569 PAL = PAL.addAttr(i, attr);
573 void InvokeInst::removeAttribute(unsigned i, Attributes attr) {
574 AttrListPtr PAL = getAttributes();
575 PAL = PAL.removeAttr(i, attr);
579 LandingPadInst *InvokeInst::getLandingPadInst() const {
580 return cast<LandingPadInst>(getUnwindDest()->getFirstNonPHI());
583 //===----------------------------------------------------------------------===//
584 // ReturnInst Implementation
585 //===----------------------------------------------------------------------===//
587 ReturnInst::ReturnInst(const ReturnInst &RI)
588 : TerminatorInst(Type::getVoidTy(RI.getContext()), Instruction::Ret,
589 OperandTraits<ReturnInst>::op_end(this) -
591 RI.getNumOperands()) {
592 if (RI.getNumOperands())
593 Op<0>() = RI.Op<0>();
594 SubclassOptionalData = RI.SubclassOptionalData;
597 ReturnInst::ReturnInst(LLVMContext &C, Value *retVal, Instruction *InsertBefore)
598 : TerminatorInst(Type::getVoidTy(C), Instruction::Ret,
599 OperandTraits<ReturnInst>::op_end(this) - !!retVal, !!retVal,
604 ReturnInst::ReturnInst(LLVMContext &C, Value *retVal, BasicBlock *InsertAtEnd)
605 : TerminatorInst(Type::getVoidTy(C), Instruction::Ret,
606 OperandTraits<ReturnInst>::op_end(this) - !!retVal, !!retVal,
611 ReturnInst::ReturnInst(LLVMContext &Context, BasicBlock *InsertAtEnd)
612 : TerminatorInst(Type::getVoidTy(Context), Instruction::Ret,
613 OperandTraits<ReturnInst>::op_end(this), 0, InsertAtEnd) {
616 unsigned ReturnInst::getNumSuccessorsV() const {
617 return getNumSuccessors();
620 /// Out-of-line ReturnInst method, put here so the C++ compiler can choose to
621 /// emit the vtable for the class in this translation unit.
622 void ReturnInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
623 llvm_unreachable("ReturnInst has no successors!");
626 BasicBlock *ReturnInst::getSuccessorV(unsigned idx) const {
627 llvm_unreachable("ReturnInst has no successors!");
631 ReturnInst::~ReturnInst() {
634 //===----------------------------------------------------------------------===//
635 // UnwindInst Implementation
636 //===----------------------------------------------------------------------===//
638 UnwindInst::UnwindInst(LLVMContext &Context, Instruction *InsertBefore)
639 : TerminatorInst(Type::getVoidTy(Context), Instruction::Unwind,
640 0, 0, InsertBefore) {
642 UnwindInst::UnwindInst(LLVMContext &Context, BasicBlock *InsertAtEnd)
643 : TerminatorInst(Type::getVoidTy(Context), Instruction::Unwind,
648 unsigned UnwindInst::getNumSuccessorsV() const {
649 return getNumSuccessors();
652 void UnwindInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
653 llvm_unreachable("UnwindInst has no successors!");
656 BasicBlock *UnwindInst::getSuccessorV(unsigned idx) const {
657 llvm_unreachable("UnwindInst has no successors!");
661 //===----------------------------------------------------------------------===//
662 // ResumeInst Implementation
663 //===----------------------------------------------------------------------===//
665 ResumeInst::ResumeInst(const ResumeInst &RI)
666 : TerminatorInst(Type::getVoidTy(RI.getContext()), Instruction::Resume,
667 OperandTraits<ResumeInst>::op_begin(this), 1) {
668 Op<0>() = RI.Op<0>();
671 ResumeInst::ResumeInst(Value *Exn, Instruction *InsertBefore)
672 : TerminatorInst(Type::getVoidTy(Exn->getContext()), Instruction::Resume,
673 OperandTraits<ResumeInst>::op_begin(this), 1, InsertBefore) {
677 ResumeInst::ResumeInst(Value *Exn, BasicBlock *InsertAtEnd)
678 : TerminatorInst(Type::getVoidTy(Exn->getContext()), Instruction::Resume,
679 OperandTraits<ResumeInst>::op_begin(this), 1, InsertAtEnd) {
683 unsigned ResumeInst::getNumSuccessorsV() const {
684 return getNumSuccessors();
687 void ResumeInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
688 llvm_unreachable("ResumeInst has no successors!");
691 BasicBlock *ResumeInst::getSuccessorV(unsigned idx) const {
692 llvm_unreachable("ResumeInst has no successors!");
696 //===----------------------------------------------------------------------===//
697 // UnreachableInst Implementation
698 //===----------------------------------------------------------------------===//
700 UnreachableInst::UnreachableInst(LLVMContext &Context,
701 Instruction *InsertBefore)
702 : TerminatorInst(Type::getVoidTy(Context), Instruction::Unreachable,
703 0, 0, InsertBefore) {
705 UnreachableInst::UnreachableInst(LLVMContext &Context, BasicBlock *InsertAtEnd)
706 : TerminatorInst(Type::getVoidTy(Context), Instruction::Unreachable,
710 unsigned UnreachableInst::getNumSuccessorsV() const {
711 return getNumSuccessors();
714 void UnreachableInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
715 llvm_unreachable("UnwindInst has no successors!");
718 BasicBlock *UnreachableInst::getSuccessorV(unsigned idx) const {
719 llvm_unreachable("UnwindInst has no successors!");
723 //===----------------------------------------------------------------------===//
724 // BranchInst Implementation
725 //===----------------------------------------------------------------------===//
727 void BranchInst::AssertOK() {
729 assert(getCondition()->getType()->isIntegerTy(1) &&
730 "May only branch on boolean predicates!");
733 BranchInst::BranchInst(BasicBlock *IfTrue, Instruction *InsertBefore)
734 : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
735 OperandTraits<BranchInst>::op_end(this) - 1,
737 assert(IfTrue != 0 && "Branch destination may not be null!");
740 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
741 Instruction *InsertBefore)
742 : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
743 OperandTraits<BranchInst>::op_end(this) - 3,
753 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *InsertAtEnd)
754 : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
755 OperandTraits<BranchInst>::op_end(this) - 1,
757 assert(IfTrue != 0 && "Branch destination may not be null!");
761 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
762 BasicBlock *InsertAtEnd)
763 : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
764 OperandTraits<BranchInst>::op_end(this) - 3,
775 BranchInst::BranchInst(const BranchInst &BI) :
776 TerminatorInst(Type::getVoidTy(BI.getContext()), Instruction::Br,
777 OperandTraits<BranchInst>::op_end(this) - BI.getNumOperands(),
778 BI.getNumOperands()) {
779 Op<-1>() = BI.Op<-1>();
780 if (BI.getNumOperands() != 1) {
781 assert(BI.getNumOperands() == 3 && "BR can have 1 or 3 operands!");
782 Op<-3>() = BI.Op<-3>();
783 Op<-2>() = BI.Op<-2>();
785 SubclassOptionalData = BI.SubclassOptionalData;
788 void BranchInst::swapSuccessors() {
789 assert(isConditional() &&
790 "Cannot swap successors of an unconditional branch");
791 Op<-1>().swap(Op<-2>());
793 // Update profile metadata if present and it matches our structural
795 MDNode *ProfileData = getMetadata(LLVMContext::MD_prof);
796 if (!ProfileData || ProfileData->getNumOperands() != 3)
799 // The first operand is the name. Fetch them backwards and build a new one.
801 ProfileData->getOperand(0),
802 ProfileData->getOperand(2),
803 ProfileData->getOperand(1)
805 setMetadata(LLVMContext::MD_prof,
806 MDNode::get(ProfileData->getContext(), Ops));
809 BasicBlock *BranchInst::getSuccessorV(unsigned idx) const {
810 return getSuccessor(idx);
812 unsigned BranchInst::getNumSuccessorsV() const {
813 return getNumSuccessors();
815 void BranchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
816 setSuccessor(idx, B);
820 //===----------------------------------------------------------------------===//
821 // AllocaInst Implementation
822 //===----------------------------------------------------------------------===//
824 static Value *getAISize(LLVMContext &Context, Value *Amt) {
826 Amt = ConstantInt::get(Type::getInt32Ty(Context), 1);
828 assert(!isa<BasicBlock>(Amt) &&
829 "Passed basic block into allocation size parameter! Use other ctor");
830 assert(Amt->getType()->isIntegerTy() &&
831 "Allocation array size is not an integer!");
836 AllocaInst::AllocaInst(Type *Ty, Value *ArraySize,
837 const Twine &Name, Instruction *InsertBefore)
838 : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
839 getAISize(Ty->getContext(), ArraySize), InsertBefore) {
841 assert(!Ty->isVoidTy() && "Cannot allocate void!");
845 AllocaInst::AllocaInst(Type *Ty, Value *ArraySize,
846 const Twine &Name, BasicBlock *InsertAtEnd)
847 : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
848 getAISize(Ty->getContext(), ArraySize), InsertAtEnd) {
850 assert(!Ty->isVoidTy() && "Cannot allocate void!");
854 AllocaInst::AllocaInst(Type *Ty, const Twine &Name,
855 Instruction *InsertBefore)
856 : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
857 getAISize(Ty->getContext(), 0), InsertBefore) {
859 assert(!Ty->isVoidTy() && "Cannot allocate void!");
863 AllocaInst::AllocaInst(Type *Ty, const Twine &Name,
864 BasicBlock *InsertAtEnd)
865 : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
866 getAISize(Ty->getContext(), 0), InsertAtEnd) {
868 assert(!Ty->isVoidTy() && "Cannot allocate void!");
872 AllocaInst::AllocaInst(Type *Ty, Value *ArraySize, unsigned Align,
873 const Twine &Name, Instruction *InsertBefore)
874 : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
875 getAISize(Ty->getContext(), ArraySize), InsertBefore) {
877 assert(!Ty->isVoidTy() && "Cannot allocate void!");
881 AllocaInst::AllocaInst(Type *Ty, Value *ArraySize, unsigned Align,
882 const Twine &Name, BasicBlock *InsertAtEnd)
883 : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
884 getAISize(Ty->getContext(), ArraySize), InsertAtEnd) {
886 assert(!Ty->isVoidTy() && "Cannot allocate void!");
890 // Out of line virtual method, so the vtable, etc has a home.
891 AllocaInst::~AllocaInst() {
894 void AllocaInst::setAlignment(unsigned Align) {
895 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
896 assert(Align <= MaximumAlignment &&
897 "Alignment is greater than MaximumAlignment!");
898 setInstructionSubclassData(Log2_32(Align) + 1);
899 assert(getAlignment() == Align && "Alignment representation error!");
902 bool AllocaInst::isArrayAllocation() const {
903 if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(0)))
908 Type *AllocaInst::getAllocatedType() const {
909 return getType()->getElementType();
912 /// isStaticAlloca - Return true if this alloca is in the entry block of the
913 /// function and is a constant size. If so, the code generator will fold it
914 /// into the prolog/epilog code, so it is basically free.
915 bool AllocaInst::isStaticAlloca() const {
916 // Must be constant size.
917 if (!isa<ConstantInt>(getArraySize())) return false;
919 // Must be in the entry block.
920 const BasicBlock *Parent = getParent();
921 return Parent == &Parent->getParent()->front();
924 //===----------------------------------------------------------------------===//
925 // LoadInst Implementation
926 //===----------------------------------------------------------------------===//
928 void LoadInst::AssertOK() {
929 assert(getOperand(0)->getType()->isPointerTy() &&
930 "Ptr must have pointer type.");
931 assert(!(isAtomic() && getAlignment() == 0) &&
932 "Alignment required for atomic load");
935 LoadInst::LoadInst(Value *Ptr, const Twine &Name, Instruction *InsertBef)
936 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
937 Load, Ptr, InsertBef) {
940 setAtomic(NotAtomic);
945 LoadInst::LoadInst(Value *Ptr, const Twine &Name, BasicBlock *InsertAE)
946 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
947 Load, Ptr, InsertAE) {
950 setAtomic(NotAtomic);
955 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
956 Instruction *InsertBef)
957 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
958 Load, Ptr, InsertBef) {
959 setVolatile(isVolatile);
961 setAtomic(NotAtomic);
966 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
967 BasicBlock *InsertAE)
968 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
969 Load, Ptr, InsertAE) {
970 setVolatile(isVolatile);
972 setAtomic(NotAtomic);
977 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
978 unsigned Align, Instruction *InsertBef)
979 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
980 Load, Ptr, InsertBef) {
981 setVolatile(isVolatile);
983 setAtomic(NotAtomic);
988 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
989 unsigned Align, BasicBlock *InsertAE)
990 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
991 Load, Ptr, InsertAE) {
992 setVolatile(isVolatile);
994 setAtomic(NotAtomic);
999 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
1000 unsigned Align, AtomicOrdering Order,
1001 SynchronizationScope SynchScope,
1002 Instruction *InsertBef)
1003 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1004 Load, Ptr, InsertBef) {
1005 setVolatile(isVolatile);
1006 setAlignment(Align);
1007 setAtomic(Order, SynchScope);
1012 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
1013 unsigned Align, AtomicOrdering Order,
1014 SynchronizationScope SynchScope,
1015 BasicBlock *InsertAE)
1016 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1017 Load, Ptr, InsertAE) {
1018 setVolatile(isVolatile);
1019 setAlignment(Align);
1020 setAtomic(Order, SynchScope);
1025 LoadInst::LoadInst(Value *Ptr, const char *Name, Instruction *InsertBef)
1026 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1027 Load, Ptr, InsertBef) {
1030 setAtomic(NotAtomic);
1032 if (Name && Name[0]) setName(Name);
1035 LoadInst::LoadInst(Value *Ptr, const char *Name, BasicBlock *InsertAE)
1036 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1037 Load, Ptr, InsertAE) {
1040 setAtomic(NotAtomic);
1042 if (Name && Name[0]) setName(Name);
1045 LoadInst::LoadInst(Value *Ptr, const char *Name, bool isVolatile,
1046 Instruction *InsertBef)
1047 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1048 Load, Ptr, InsertBef) {
1049 setVolatile(isVolatile);
1051 setAtomic(NotAtomic);
1053 if (Name && Name[0]) setName(Name);
1056 LoadInst::LoadInst(Value *Ptr, const char *Name, bool isVolatile,
1057 BasicBlock *InsertAE)
1058 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1059 Load, Ptr, InsertAE) {
1060 setVolatile(isVolatile);
1062 setAtomic(NotAtomic);
1064 if (Name && Name[0]) setName(Name);
1067 void LoadInst::setAlignment(unsigned Align) {
1068 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
1069 assert(Align <= MaximumAlignment &&
1070 "Alignment is greater than MaximumAlignment!");
1071 setInstructionSubclassData((getSubclassDataFromInstruction() & ~(31 << 1)) |
1072 ((Log2_32(Align)+1)<<1));
1073 assert(getAlignment() == Align && "Alignment representation error!");
1076 //===----------------------------------------------------------------------===//
1077 // StoreInst Implementation
1078 //===----------------------------------------------------------------------===//
1080 void StoreInst::AssertOK() {
1081 assert(getOperand(0) && getOperand(1) && "Both operands must be non-null!");
1082 assert(getOperand(1)->getType()->isPointerTy() &&
1083 "Ptr must have pointer type!");
1084 assert(getOperand(0)->getType() ==
1085 cast<PointerType>(getOperand(1)->getType())->getElementType()
1086 && "Ptr must be a pointer to Val type!");
1087 assert(!(isAtomic() && getAlignment() == 0) &&
1088 "Alignment required for atomic load");
1092 StoreInst::StoreInst(Value *val, Value *addr, Instruction *InsertBefore)
1093 : Instruction(Type::getVoidTy(val->getContext()), Store,
1094 OperandTraits<StoreInst>::op_begin(this),
1095 OperandTraits<StoreInst>::operands(this),
1101 setAtomic(NotAtomic);
1105 StoreInst::StoreInst(Value *val, Value *addr, BasicBlock *InsertAtEnd)
1106 : Instruction(Type::getVoidTy(val->getContext()), Store,
1107 OperandTraits<StoreInst>::op_begin(this),
1108 OperandTraits<StoreInst>::operands(this),
1114 setAtomic(NotAtomic);
1118 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1119 Instruction *InsertBefore)
1120 : Instruction(Type::getVoidTy(val->getContext()), Store,
1121 OperandTraits<StoreInst>::op_begin(this),
1122 OperandTraits<StoreInst>::operands(this),
1126 setVolatile(isVolatile);
1128 setAtomic(NotAtomic);
1132 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1133 unsigned Align, Instruction *InsertBefore)
1134 : Instruction(Type::getVoidTy(val->getContext()), Store,
1135 OperandTraits<StoreInst>::op_begin(this),
1136 OperandTraits<StoreInst>::operands(this),
1140 setVolatile(isVolatile);
1141 setAlignment(Align);
1142 setAtomic(NotAtomic);
1146 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1147 unsigned Align, AtomicOrdering Order,
1148 SynchronizationScope SynchScope,
1149 Instruction *InsertBefore)
1150 : Instruction(Type::getVoidTy(val->getContext()), Store,
1151 OperandTraits<StoreInst>::op_begin(this),
1152 OperandTraits<StoreInst>::operands(this),
1156 setVolatile(isVolatile);
1157 setAlignment(Align);
1158 setAtomic(Order, SynchScope);
1162 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1163 BasicBlock *InsertAtEnd)
1164 : Instruction(Type::getVoidTy(val->getContext()), Store,
1165 OperandTraits<StoreInst>::op_begin(this),
1166 OperandTraits<StoreInst>::operands(this),
1170 setVolatile(isVolatile);
1172 setAtomic(NotAtomic);
1176 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1177 unsigned Align, BasicBlock *InsertAtEnd)
1178 : Instruction(Type::getVoidTy(val->getContext()), Store,
1179 OperandTraits<StoreInst>::op_begin(this),
1180 OperandTraits<StoreInst>::operands(this),
1184 setVolatile(isVolatile);
1185 setAlignment(Align);
1186 setAtomic(NotAtomic);
1190 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1191 unsigned Align, AtomicOrdering Order,
1192 SynchronizationScope SynchScope,
1193 BasicBlock *InsertAtEnd)
1194 : Instruction(Type::getVoidTy(val->getContext()), Store,
1195 OperandTraits<StoreInst>::op_begin(this),
1196 OperandTraits<StoreInst>::operands(this),
1200 setVolatile(isVolatile);
1201 setAlignment(Align);
1202 setAtomic(Order, SynchScope);
1206 void StoreInst::setAlignment(unsigned Align) {
1207 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
1208 assert(Align <= MaximumAlignment &&
1209 "Alignment is greater than MaximumAlignment!");
1210 setInstructionSubclassData((getSubclassDataFromInstruction() & ~(31 << 1)) |
1211 ((Log2_32(Align)+1) << 1));
1212 assert(getAlignment() == Align && "Alignment representation error!");
1215 //===----------------------------------------------------------------------===//
1216 // AtomicCmpXchgInst Implementation
1217 //===----------------------------------------------------------------------===//
1219 void AtomicCmpXchgInst::Init(Value *Ptr, Value *Cmp, Value *NewVal,
1220 AtomicOrdering Ordering,
1221 SynchronizationScope SynchScope) {
1225 setOrdering(Ordering);
1226 setSynchScope(SynchScope);
1228 assert(getOperand(0) && getOperand(1) && getOperand(2) &&
1229 "All operands must be non-null!");
1230 assert(getOperand(0)->getType()->isPointerTy() &&
1231 "Ptr must have pointer type!");
1232 assert(getOperand(1)->getType() ==
1233 cast<PointerType>(getOperand(0)->getType())->getElementType()
1234 && "Ptr must be a pointer to Cmp type!");
1235 assert(getOperand(2)->getType() ==
1236 cast<PointerType>(getOperand(0)->getType())->getElementType()
1237 && "Ptr must be a pointer to NewVal type!");
1238 assert(Ordering != NotAtomic &&
1239 "AtomicCmpXchg instructions must be atomic!");
1242 AtomicCmpXchgInst::AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal,
1243 AtomicOrdering Ordering,
1244 SynchronizationScope SynchScope,
1245 Instruction *InsertBefore)
1246 : Instruction(Cmp->getType(), AtomicCmpXchg,
1247 OperandTraits<AtomicCmpXchgInst>::op_begin(this),
1248 OperandTraits<AtomicCmpXchgInst>::operands(this),
1250 Init(Ptr, Cmp, NewVal, Ordering, SynchScope);
1253 AtomicCmpXchgInst::AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal,
1254 AtomicOrdering Ordering,
1255 SynchronizationScope SynchScope,
1256 BasicBlock *InsertAtEnd)
1257 : Instruction(Cmp->getType(), AtomicCmpXchg,
1258 OperandTraits<AtomicCmpXchgInst>::op_begin(this),
1259 OperandTraits<AtomicCmpXchgInst>::operands(this),
1261 Init(Ptr, Cmp, NewVal, Ordering, SynchScope);
1264 //===----------------------------------------------------------------------===//
1265 // AtomicRMWInst Implementation
1266 //===----------------------------------------------------------------------===//
1268 void AtomicRMWInst::Init(BinOp Operation, Value *Ptr, Value *Val,
1269 AtomicOrdering Ordering,
1270 SynchronizationScope SynchScope) {
1273 setOperation(Operation);
1274 setOrdering(Ordering);
1275 setSynchScope(SynchScope);
1277 assert(getOperand(0) && getOperand(1) &&
1278 "All operands must be non-null!");
1279 assert(getOperand(0)->getType()->isPointerTy() &&
1280 "Ptr must have pointer type!");
1281 assert(getOperand(1)->getType() ==
1282 cast<PointerType>(getOperand(0)->getType())->getElementType()
1283 && "Ptr must be a pointer to Val type!");
1284 assert(Ordering != NotAtomic &&
1285 "AtomicRMW instructions must be atomic!");
1288 AtomicRMWInst::AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val,
1289 AtomicOrdering Ordering,
1290 SynchronizationScope SynchScope,
1291 Instruction *InsertBefore)
1292 : Instruction(Val->getType(), AtomicRMW,
1293 OperandTraits<AtomicRMWInst>::op_begin(this),
1294 OperandTraits<AtomicRMWInst>::operands(this),
1296 Init(Operation, Ptr, Val, Ordering, SynchScope);
1299 AtomicRMWInst::AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val,
1300 AtomicOrdering Ordering,
1301 SynchronizationScope SynchScope,
1302 BasicBlock *InsertAtEnd)
1303 : Instruction(Val->getType(), AtomicRMW,
1304 OperandTraits<AtomicRMWInst>::op_begin(this),
1305 OperandTraits<AtomicRMWInst>::operands(this),
1307 Init(Operation, Ptr, Val, Ordering, SynchScope);
1310 //===----------------------------------------------------------------------===//
1311 // FenceInst Implementation
1312 //===----------------------------------------------------------------------===//
1314 FenceInst::FenceInst(LLVMContext &C, AtomicOrdering Ordering,
1315 SynchronizationScope SynchScope,
1316 Instruction *InsertBefore)
1317 : Instruction(Type::getVoidTy(C), Fence, 0, 0, InsertBefore) {
1318 setOrdering(Ordering);
1319 setSynchScope(SynchScope);
1322 FenceInst::FenceInst(LLVMContext &C, AtomicOrdering Ordering,
1323 SynchronizationScope SynchScope,
1324 BasicBlock *InsertAtEnd)
1325 : Instruction(Type::getVoidTy(C), Fence, 0, 0, InsertAtEnd) {
1326 setOrdering(Ordering);
1327 setSynchScope(SynchScope);
1330 //===----------------------------------------------------------------------===//
1331 // GetElementPtrInst Implementation
1332 //===----------------------------------------------------------------------===//
1334 void GetElementPtrInst::init(Value *Ptr, ArrayRef<Value *> IdxList,
1335 const Twine &Name) {
1336 assert(NumOperands == 1 + IdxList.size() && "NumOperands not initialized?");
1337 OperandList[0] = Ptr;
1338 std::copy(IdxList.begin(), IdxList.end(), op_begin() + 1);
1342 GetElementPtrInst::GetElementPtrInst(const GetElementPtrInst &GEPI)
1343 : Instruction(GEPI.getType(), GetElementPtr,
1344 OperandTraits<GetElementPtrInst>::op_end(this)
1345 - GEPI.getNumOperands(),
1346 GEPI.getNumOperands()) {
1347 std::copy(GEPI.op_begin(), GEPI.op_end(), op_begin());
1348 SubclassOptionalData = GEPI.SubclassOptionalData;
1351 /// getIndexedType - Returns the type of the element that would be accessed with
1352 /// a gep instruction with the specified parameters.
1354 /// The Idxs pointer should point to a continuous piece of memory containing the
1355 /// indices, either as Value* or uint64_t.
1357 /// A null type is returned if the indices are invalid for the specified
1360 template <typename IndexTy>
1361 static Type *getIndexedTypeInternal(Type *Ptr, ArrayRef<IndexTy> IdxList) {
1362 PointerType *PTy = dyn_cast<PointerType>(Ptr);
1363 if (!PTy) return 0; // Type isn't a pointer type!
1364 Type *Agg = PTy->getElementType();
1366 // Handle the special case of the empty set index set, which is always valid.
1367 if (IdxList.empty())
1370 // If there is at least one index, the top level type must be sized, otherwise
1371 // it cannot be 'stepped over'.
1372 if (!Agg->isSized())
1375 unsigned CurIdx = 1;
1376 for (; CurIdx != IdxList.size(); ++CurIdx) {
1377 CompositeType *CT = dyn_cast<CompositeType>(Agg);
1378 if (!CT || CT->isPointerTy()) return 0;
1379 IndexTy Index = IdxList[CurIdx];
1380 if (!CT->indexValid(Index)) return 0;
1381 Agg = CT->getTypeAtIndex(Index);
1383 return CurIdx == IdxList.size() ? Agg : 0;
1386 Type *GetElementPtrInst::getIndexedType(Type *Ptr, ArrayRef<Value *> IdxList) {
1387 return getIndexedTypeInternal(Ptr, IdxList);
1390 Type *GetElementPtrInst::getIndexedType(Type *Ptr,
1391 ArrayRef<Constant *> IdxList) {
1392 return getIndexedTypeInternal(Ptr, IdxList);
1395 Type *GetElementPtrInst::getIndexedType(Type *Ptr, ArrayRef<uint64_t> IdxList) {
1396 return getIndexedTypeInternal(Ptr, IdxList);
1399 /// hasAllZeroIndices - Return true if all of the indices of this GEP are
1400 /// zeros. If so, the result pointer and the first operand have the same
1401 /// value, just potentially different types.
1402 bool GetElementPtrInst::hasAllZeroIndices() const {
1403 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1404 if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(i))) {
1405 if (!CI->isZero()) return false;
1413 /// hasAllConstantIndices - Return true if all of the indices of this GEP are
1414 /// constant integers. If so, the result pointer and the first operand have
1415 /// a constant offset between them.
1416 bool GetElementPtrInst::hasAllConstantIndices() const {
1417 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1418 if (!isa<ConstantInt>(getOperand(i)))
1424 void GetElementPtrInst::setIsInBounds(bool B) {
1425 cast<GEPOperator>(this)->setIsInBounds(B);
1428 bool GetElementPtrInst::isInBounds() const {
1429 return cast<GEPOperator>(this)->isInBounds();
1432 //===----------------------------------------------------------------------===//
1433 // ExtractElementInst Implementation
1434 //===----------------------------------------------------------------------===//
1436 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
1438 Instruction *InsertBef)
1439 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1441 OperandTraits<ExtractElementInst>::op_begin(this),
1443 assert(isValidOperands(Val, Index) &&
1444 "Invalid extractelement instruction operands!");
1450 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
1452 BasicBlock *InsertAE)
1453 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1455 OperandTraits<ExtractElementInst>::op_begin(this),
1457 assert(isValidOperands(Val, Index) &&
1458 "Invalid extractelement instruction operands!");
1466 bool ExtractElementInst::isValidOperands(const Value *Val, const Value *Index) {
1467 if (!Val->getType()->isVectorTy() || !Index->getType()->isIntegerTy(32))
1473 //===----------------------------------------------------------------------===//
1474 // InsertElementInst Implementation
1475 //===----------------------------------------------------------------------===//
1477 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
1479 Instruction *InsertBef)
1480 : Instruction(Vec->getType(), InsertElement,
1481 OperandTraits<InsertElementInst>::op_begin(this),
1483 assert(isValidOperands(Vec, Elt, Index) &&
1484 "Invalid insertelement instruction operands!");
1491 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
1493 BasicBlock *InsertAE)
1494 : Instruction(Vec->getType(), InsertElement,
1495 OperandTraits<InsertElementInst>::op_begin(this),
1497 assert(isValidOperands(Vec, Elt, Index) &&
1498 "Invalid insertelement instruction operands!");
1506 bool InsertElementInst::isValidOperands(const Value *Vec, const Value *Elt,
1507 const Value *Index) {
1508 if (!Vec->getType()->isVectorTy())
1509 return false; // First operand of insertelement must be vector type.
1511 if (Elt->getType() != cast<VectorType>(Vec->getType())->getElementType())
1512 return false;// Second operand of insertelement must be vector element type.
1514 if (!Index->getType()->isIntegerTy(32))
1515 return false; // Third operand of insertelement must be i32.
1520 //===----------------------------------------------------------------------===//
1521 // ShuffleVectorInst Implementation
1522 //===----------------------------------------------------------------------===//
1524 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1526 Instruction *InsertBefore)
1527 : Instruction(VectorType::get(cast<VectorType>(V1->getType())->getElementType(),
1528 cast<VectorType>(Mask->getType())->getNumElements()),
1530 OperandTraits<ShuffleVectorInst>::op_begin(this),
1531 OperandTraits<ShuffleVectorInst>::operands(this),
1533 assert(isValidOperands(V1, V2, Mask) &&
1534 "Invalid shuffle vector instruction operands!");
1541 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1543 BasicBlock *InsertAtEnd)
1544 : Instruction(VectorType::get(cast<VectorType>(V1->getType())->getElementType(),
1545 cast<VectorType>(Mask->getType())->getNumElements()),
1547 OperandTraits<ShuffleVectorInst>::op_begin(this),
1548 OperandTraits<ShuffleVectorInst>::operands(this),
1550 assert(isValidOperands(V1, V2, Mask) &&
1551 "Invalid shuffle vector instruction operands!");
1559 bool ShuffleVectorInst::isValidOperands(const Value *V1, const Value *V2,
1560 const Value *Mask) {
1561 if (!V1->getType()->isVectorTy() || V1->getType() != V2->getType())
1564 VectorType *MaskTy = dyn_cast<VectorType>(Mask->getType());
1565 if (MaskTy == 0 || !MaskTy->getElementType()->isIntegerTy(32))
1568 // Check to see if Mask is valid.
1569 if (const ConstantVector *MV = dyn_cast<ConstantVector>(Mask)) {
1570 VectorType *VTy = cast<VectorType>(V1->getType());
1571 for (unsigned i = 0, e = MV->getNumOperands(); i != e; ++i) {
1572 if (ConstantInt* CI = dyn_cast<ConstantInt>(MV->getOperand(i))) {
1573 if (CI->uge(VTy->getNumElements()*2))
1575 } else if (!isa<UndefValue>(MV->getOperand(i))) {
1579 } else if (!isa<UndefValue>(Mask) && !isa<ConstantAggregateZero>(Mask)) {
1580 // The bitcode reader can create a place holder for a forward reference
1581 // used as the shuffle mask. When this occurs, the shuffle mask will
1582 // fall into this case and fail. To avoid this error, do this bit of
1583 // ugliness to allow such a mask pass.
1584 if (const ConstantExpr* CE = dyn_cast<ConstantExpr>(Mask)) {
1585 if (CE->getOpcode() == Instruction::UserOp1)
1593 /// getMaskValue - Return the index from the shuffle mask for the specified
1594 /// output result. This is either -1 if the element is undef or a number less
1595 /// than 2*numelements.
1596 int ShuffleVectorInst::getMaskValue(unsigned i) const {
1597 const Constant *Mask = cast<Constant>(getOperand(2));
1598 if (isa<UndefValue>(Mask)) return -1;
1599 if (isa<ConstantAggregateZero>(Mask)) return 0;
1600 const ConstantVector *MaskCV = cast<ConstantVector>(Mask);
1601 assert(i < MaskCV->getNumOperands() && "Index out of range");
1603 if (isa<UndefValue>(MaskCV->getOperand(i)))
1605 return cast<ConstantInt>(MaskCV->getOperand(i))->getZExtValue();
1608 //===----------------------------------------------------------------------===//
1609 // InsertValueInst Class
1610 //===----------------------------------------------------------------------===//
1612 void InsertValueInst::init(Value *Agg, Value *Val, ArrayRef<unsigned> Idxs,
1613 const Twine &Name) {
1614 assert(NumOperands == 2 && "NumOperands not initialized?");
1616 // There's no fundamental reason why we require at least one index
1617 // (other than weirdness with &*IdxBegin being invalid; see
1618 // getelementptr's init routine for example). But there's no
1619 // present need to support it.
1620 assert(Idxs.size() > 0 && "InsertValueInst must have at least one index");
1622 assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs) ==
1623 Val->getType() && "Inserted value must match indexed type!");
1627 Indices.append(Idxs.begin(), Idxs.end());
1631 InsertValueInst::InsertValueInst(const InsertValueInst &IVI)
1632 : Instruction(IVI.getType(), InsertValue,
1633 OperandTraits<InsertValueInst>::op_begin(this), 2),
1634 Indices(IVI.Indices) {
1635 Op<0>() = IVI.getOperand(0);
1636 Op<1>() = IVI.getOperand(1);
1637 SubclassOptionalData = IVI.SubclassOptionalData;
1640 //===----------------------------------------------------------------------===//
1641 // ExtractValueInst Class
1642 //===----------------------------------------------------------------------===//
1644 void ExtractValueInst::init(ArrayRef<unsigned> Idxs, const Twine &Name) {
1645 assert(NumOperands == 1 && "NumOperands not initialized?");
1647 // There's no fundamental reason why we require at least one index.
1648 // But there's no present need to support it.
1649 assert(Idxs.size() > 0 && "ExtractValueInst must have at least one index");
1651 Indices.append(Idxs.begin(), Idxs.end());
1655 ExtractValueInst::ExtractValueInst(const ExtractValueInst &EVI)
1656 : UnaryInstruction(EVI.getType(), ExtractValue, EVI.getOperand(0)),
1657 Indices(EVI.Indices) {
1658 SubclassOptionalData = EVI.SubclassOptionalData;
1661 // getIndexedType - Returns the type of the element that would be extracted
1662 // with an extractvalue instruction with the specified parameters.
1664 // A null type is returned if the indices are invalid for the specified
1667 Type *ExtractValueInst::getIndexedType(Type *Agg,
1668 ArrayRef<unsigned> Idxs) {
1669 for (unsigned CurIdx = 0; CurIdx != Idxs.size(); ++CurIdx) {
1670 unsigned Index = Idxs[CurIdx];
1671 // We can't use CompositeType::indexValid(Index) here.
1672 // indexValid() always returns true for arrays because getelementptr allows
1673 // out-of-bounds indices. Since we don't allow those for extractvalue and
1674 // insertvalue we need to check array indexing manually.
1675 // Since the only other types we can index into are struct types it's just
1676 // as easy to check those manually as well.
1677 if (ArrayType *AT = dyn_cast<ArrayType>(Agg)) {
1678 if (Index >= AT->getNumElements())
1680 } else if (StructType *ST = dyn_cast<StructType>(Agg)) {
1681 if (Index >= ST->getNumElements())
1684 // Not a valid type to index into.
1688 Agg = cast<CompositeType>(Agg)->getTypeAtIndex(Index);
1690 return const_cast<Type*>(Agg);
1693 //===----------------------------------------------------------------------===//
1694 // BinaryOperator Class
1695 //===----------------------------------------------------------------------===//
1697 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
1698 Type *Ty, const Twine &Name,
1699 Instruction *InsertBefore)
1700 : Instruction(Ty, iType,
1701 OperandTraits<BinaryOperator>::op_begin(this),
1702 OperandTraits<BinaryOperator>::operands(this),
1710 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
1711 Type *Ty, const Twine &Name,
1712 BasicBlock *InsertAtEnd)
1713 : Instruction(Ty, iType,
1714 OperandTraits<BinaryOperator>::op_begin(this),
1715 OperandTraits<BinaryOperator>::operands(this),
1724 void BinaryOperator::init(BinaryOps iType) {
1725 Value *LHS = getOperand(0), *RHS = getOperand(1);
1726 (void)LHS; (void)RHS; // Silence warnings.
1727 assert(LHS->getType() == RHS->getType() &&
1728 "Binary operator operand types must match!");
1733 assert(getType() == LHS->getType() &&
1734 "Arithmetic operation should return same type as operands!");
1735 assert(getType()->isIntOrIntVectorTy() &&
1736 "Tried to create an integer operation on a non-integer type!");
1738 case FAdd: case FSub:
1740 assert(getType() == LHS->getType() &&
1741 "Arithmetic operation should return same type as operands!");
1742 assert(getType()->isFPOrFPVectorTy() &&
1743 "Tried to create a floating-point operation on a "
1744 "non-floating-point type!");
1748 assert(getType() == LHS->getType() &&
1749 "Arithmetic operation should return same type as operands!");
1750 assert((getType()->isIntegerTy() || (getType()->isVectorTy() &&
1751 cast<VectorType>(getType())->getElementType()->isIntegerTy())) &&
1752 "Incorrect operand type (not integer) for S/UDIV");
1755 assert(getType() == LHS->getType() &&
1756 "Arithmetic operation should return same type as operands!");
1757 assert(getType()->isFPOrFPVectorTy() &&
1758 "Incorrect operand type (not floating point) for FDIV");
1762 assert(getType() == LHS->getType() &&
1763 "Arithmetic operation should return same type as operands!");
1764 assert((getType()->isIntegerTy() || (getType()->isVectorTy() &&
1765 cast<VectorType>(getType())->getElementType()->isIntegerTy())) &&
1766 "Incorrect operand type (not integer) for S/UREM");
1769 assert(getType() == LHS->getType() &&
1770 "Arithmetic operation should return same type as operands!");
1771 assert(getType()->isFPOrFPVectorTy() &&
1772 "Incorrect operand type (not floating point) for FREM");
1777 assert(getType() == LHS->getType() &&
1778 "Shift operation should return same type as operands!");
1779 assert((getType()->isIntegerTy() ||
1780 (getType()->isVectorTy() &&
1781 cast<VectorType>(getType())->getElementType()->isIntegerTy())) &&
1782 "Tried to create a shift operation on a non-integral type!");
1786 assert(getType() == LHS->getType() &&
1787 "Logical operation should return same type as operands!");
1788 assert((getType()->isIntegerTy() ||
1789 (getType()->isVectorTy() &&
1790 cast<VectorType>(getType())->getElementType()->isIntegerTy())) &&
1791 "Tried to create a logical operation on a non-integral type!");
1799 BinaryOperator *BinaryOperator::Create(BinaryOps Op, Value *S1, Value *S2,
1801 Instruction *InsertBefore) {
1802 assert(S1->getType() == S2->getType() &&
1803 "Cannot create binary operator with two operands of differing type!");
1804 return new BinaryOperator(Op, S1, S2, S1->getType(), Name, InsertBefore);
1807 BinaryOperator *BinaryOperator::Create(BinaryOps Op, Value *S1, Value *S2,
1809 BasicBlock *InsertAtEnd) {
1810 BinaryOperator *Res = Create(Op, S1, S2, Name);
1811 InsertAtEnd->getInstList().push_back(Res);
1815 BinaryOperator *BinaryOperator::CreateNeg(Value *Op, const Twine &Name,
1816 Instruction *InsertBefore) {
1817 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1818 return new BinaryOperator(Instruction::Sub,
1820 Op->getType(), Name, InsertBefore);
1823 BinaryOperator *BinaryOperator::CreateNeg(Value *Op, const Twine &Name,
1824 BasicBlock *InsertAtEnd) {
1825 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1826 return new BinaryOperator(Instruction::Sub,
1828 Op->getType(), Name, InsertAtEnd);
1831 BinaryOperator *BinaryOperator::CreateNSWNeg(Value *Op, const Twine &Name,
1832 Instruction *InsertBefore) {
1833 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1834 return BinaryOperator::CreateNSWSub(zero, Op, Name, InsertBefore);
1837 BinaryOperator *BinaryOperator::CreateNSWNeg(Value *Op, const Twine &Name,
1838 BasicBlock *InsertAtEnd) {
1839 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1840 return BinaryOperator::CreateNSWSub(zero, Op, Name, InsertAtEnd);
1843 BinaryOperator *BinaryOperator::CreateNUWNeg(Value *Op, const Twine &Name,
1844 Instruction *InsertBefore) {
1845 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1846 return BinaryOperator::CreateNUWSub(zero, Op, Name, InsertBefore);
1849 BinaryOperator *BinaryOperator::CreateNUWNeg(Value *Op, const Twine &Name,
1850 BasicBlock *InsertAtEnd) {
1851 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1852 return BinaryOperator::CreateNUWSub(zero, Op, Name, InsertAtEnd);
1855 BinaryOperator *BinaryOperator::CreateFNeg(Value *Op, const Twine &Name,
1856 Instruction *InsertBefore) {
1857 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1858 return new BinaryOperator(Instruction::FSub,
1860 Op->getType(), Name, InsertBefore);
1863 BinaryOperator *BinaryOperator::CreateFNeg(Value *Op, const Twine &Name,
1864 BasicBlock *InsertAtEnd) {
1865 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1866 return new BinaryOperator(Instruction::FSub,
1868 Op->getType(), Name, InsertAtEnd);
1871 BinaryOperator *BinaryOperator::CreateNot(Value *Op, const Twine &Name,
1872 Instruction *InsertBefore) {
1874 if (VectorType *PTy = dyn_cast<VectorType>(Op->getType())) {
1875 C = Constant::getAllOnesValue(PTy->getElementType());
1876 C = ConstantVector::get(
1877 std::vector<Constant*>(PTy->getNumElements(), C));
1879 C = Constant::getAllOnesValue(Op->getType());
1882 return new BinaryOperator(Instruction::Xor, Op, C,
1883 Op->getType(), Name, InsertBefore);
1886 BinaryOperator *BinaryOperator::CreateNot(Value *Op, const Twine &Name,
1887 BasicBlock *InsertAtEnd) {
1889 if (VectorType *PTy = dyn_cast<VectorType>(Op->getType())) {
1890 // Create a vector of all ones values.
1891 Constant *Elt = Constant::getAllOnesValue(PTy->getElementType());
1892 AllOnes = ConstantVector::get(
1893 std::vector<Constant*>(PTy->getNumElements(), Elt));
1895 AllOnes = Constant::getAllOnesValue(Op->getType());
1898 return new BinaryOperator(Instruction::Xor, Op, AllOnes,
1899 Op->getType(), Name, InsertAtEnd);
1903 // isConstantAllOnes - Helper function for several functions below
1904 static inline bool isConstantAllOnes(const Value *V) {
1905 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V))
1906 return CI->isAllOnesValue();
1907 if (const ConstantVector *CV = dyn_cast<ConstantVector>(V))
1908 return CV->isAllOnesValue();
1912 bool BinaryOperator::isNeg(const Value *V) {
1913 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1914 if (Bop->getOpcode() == Instruction::Sub)
1915 if (Constant* C = dyn_cast<Constant>(Bop->getOperand(0)))
1916 return C->isNegativeZeroValue();
1920 bool BinaryOperator::isFNeg(const Value *V) {
1921 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1922 if (Bop->getOpcode() == Instruction::FSub)
1923 if (Constant* C = dyn_cast<Constant>(Bop->getOperand(0)))
1924 return C->isNegativeZeroValue();
1928 bool BinaryOperator::isNot(const Value *V) {
1929 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1930 return (Bop->getOpcode() == Instruction::Xor &&
1931 (isConstantAllOnes(Bop->getOperand(1)) ||
1932 isConstantAllOnes(Bop->getOperand(0))));
1936 Value *BinaryOperator::getNegArgument(Value *BinOp) {
1937 return cast<BinaryOperator>(BinOp)->getOperand(1);
1940 const Value *BinaryOperator::getNegArgument(const Value *BinOp) {
1941 return getNegArgument(const_cast<Value*>(BinOp));
1944 Value *BinaryOperator::getFNegArgument(Value *BinOp) {
1945 return cast<BinaryOperator>(BinOp)->getOperand(1);
1948 const Value *BinaryOperator::getFNegArgument(const Value *BinOp) {
1949 return getFNegArgument(const_cast<Value*>(BinOp));
1952 Value *BinaryOperator::getNotArgument(Value *BinOp) {
1953 assert(isNot(BinOp) && "getNotArgument on non-'not' instruction!");
1954 BinaryOperator *BO = cast<BinaryOperator>(BinOp);
1955 Value *Op0 = BO->getOperand(0);
1956 Value *Op1 = BO->getOperand(1);
1957 if (isConstantAllOnes(Op0)) return Op1;
1959 assert(isConstantAllOnes(Op1));
1963 const Value *BinaryOperator::getNotArgument(const Value *BinOp) {
1964 return getNotArgument(const_cast<Value*>(BinOp));
1968 // swapOperands - Exchange the two operands to this instruction. This
1969 // instruction is safe to use on any binary instruction and does not
1970 // modify the semantics of the instruction. If the instruction is
1971 // order dependent (SetLT f.e.) the opcode is changed.
1973 bool BinaryOperator::swapOperands() {
1974 if (!isCommutative())
1975 return true; // Can't commute operands
1976 Op<0>().swap(Op<1>());
1980 void BinaryOperator::setHasNoUnsignedWrap(bool b) {
1981 cast<OverflowingBinaryOperator>(this)->setHasNoUnsignedWrap(b);
1984 void BinaryOperator::setHasNoSignedWrap(bool b) {
1985 cast<OverflowingBinaryOperator>(this)->setHasNoSignedWrap(b);
1988 void BinaryOperator::setIsExact(bool b) {
1989 cast<PossiblyExactOperator>(this)->setIsExact(b);
1992 bool BinaryOperator::hasNoUnsignedWrap() const {
1993 return cast<OverflowingBinaryOperator>(this)->hasNoUnsignedWrap();
1996 bool BinaryOperator::hasNoSignedWrap() const {
1997 return cast<OverflowingBinaryOperator>(this)->hasNoSignedWrap();
2000 bool BinaryOperator::isExact() const {
2001 return cast<PossiblyExactOperator>(this)->isExact();
2004 //===----------------------------------------------------------------------===//
2006 //===----------------------------------------------------------------------===//
2008 void CastInst::anchor() {}
2010 // Just determine if this cast only deals with integral->integral conversion.
2011 bool CastInst::isIntegerCast() const {
2012 switch (getOpcode()) {
2013 default: return false;
2014 case Instruction::ZExt:
2015 case Instruction::SExt:
2016 case Instruction::Trunc:
2018 case Instruction::BitCast:
2019 return getOperand(0)->getType()->isIntegerTy() &&
2020 getType()->isIntegerTy();
2024 bool CastInst::isLosslessCast() const {
2025 // Only BitCast can be lossless, exit fast if we're not BitCast
2026 if (getOpcode() != Instruction::BitCast)
2029 // Identity cast is always lossless
2030 Type* SrcTy = getOperand(0)->getType();
2031 Type* DstTy = getType();
2035 // Pointer to pointer is always lossless.
2036 if (SrcTy->isPointerTy())
2037 return DstTy->isPointerTy();
2038 return false; // Other types have no identity values
2041 /// This function determines if the CastInst does not require any bits to be
2042 /// changed in order to effect the cast. Essentially, it identifies cases where
2043 /// no code gen is necessary for the cast, hence the name no-op cast. For
2044 /// example, the following are all no-op casts:
2045 /// # bitcast i32* %x to i8*
2046 /// # bitcast <2 x i32> %x to <4 x i16>
2047 /// # ptrtoint i32* %x to i32 ; on 32-bit plaforms only
2048 /// @brief Determine if the described cast is a no-op.
2049 bool CastInst::isNoopCast(Instruction::CastOps Opcode,
2055 assert(0 && "Invalid CastOp");
2056 case Instruction::Trunc:
2057 case Instruction::ZExt:
2058 case Instruction::SExt:
2059 case Instruction::FPTrunc:
2060 case Instruction::FPExt:
2061 case Instruction::UIToFP:
2062 case Instruction::SIToFP:
2063 case Instruction::FPToUI:
2064 case Instruction::FPToSI:
2065 return false; // These always modify bits
2066 case Instruction::BitCast:
2067 return true; // BitCast never modifies bits.
2068 case Instruction::PtrToInt:
2069 return IntPtrTy->getScalarSizeInBits() ==
2070 DestTy->getScalarSizeInBits();
2071 case Instruction::IntToPtr:
2072 return IntPtrTy->getScalarSizeInBits() ==
2073 SrcTy->getScalarSizeInBits();
2077 /// @brief Determine if a cast is a no-op.
2078 bool CastInst::isNoopCast(Type *IntPtrTy) const {
2079 return isNoopCast(getOpcode(), getOperand(0)->getType(), getType(), IntPtrTy);
2082 /// This function determines if a pair of casts can be eliminated and what
2083 /// opcode should be used in the elimination. This assumes that there are two
2084 /// instructions like this:
2085 /// * %F = firstOpcode SrcTy %x to MidTy
2086 /// * %S = secondOpcode MidTy %F to DstTy
2087 /// The function returns a resultOpcode so these two casts can be replaced with:
2088 /// * %Replacement = resultOpcode %SrcTy %x to DstTy
2089 /// If no such cast is permited, the function returns 0.
2090 unsigned CastInst::isEliminableCastPair(
2091 Instruction::CastOps firstOp, Instruction::CastOps secondOp,
2092 Type *SrcTy, Type *MidTy, Type *DstTy, Type *IntPtrTy) {
2093 // Define the 144 possibilities for these two cast instructions. The values
2094 // in this matrix determine what to do in a given situation and select the
2095 // case in the switch below. The rows correspond to firstOp, the columns
2096 // correspond to secondOp. In looking at the table below, keep in mind
2097 // the following cast properties:
2099 // Size Compare Source Destination
2100 // Operator Src ? Size Type Sign Type Sign
2101 // -------- ------------ ------------------- ---------------------
2102 // TRUNC > Integer Any Integral Any
2103 // ZEXT < Integral Unsigned Integer Any
2104 // SEXT < Integral Signed Integer Any
2105 // FPTOUI n/a FloatPt n/a Integral Unsigned
2106 // FPTOSI n/a FloatPt n/a Integral Signed
2107 // UITOFP n/a Integral Unsigned FloatPt n/a
2108 // SITOFP n/a Integral Signed FloatPt n/a
2109 // FPTRUNC > FloatPt n/a FloatPt n/a
2110 // FPEXT < FloatPt n/a FloatPt n/a
2111 // PTRTOINT n/a Pointer n/a Integral Unsigned
2112 // INTTOPTR n/a Integral Unsigned Pointer n/a
2113 // BITCAST = FirstClass n/a FirstClass n/a
2115 // NOTE: some transforms are safe, but we consider them to be non-profitable.
2116 // For example, we could merge "fptoui double to i32" + "zext i32 to i64",
2117 // into "fptoui double to i64", but this loses information about the range
2118 // of the produced value (we no longer know the top-part is all zeros).
2119 // Further this conversion is often much more expensive for typical hardware,
2120 // and causes issues when building libgcc. We disallow fptosi+sext for the
2122 const unsigned numCastOps =
2123 Instruction::CastOpsEnd - Instruction::CastOpsBegin;
2124 static const uint8_t CastResults[numCastOps][numCastOps] = {
2125 // T F F U S F F P I B -+
2126 // R Z S P P I I T P 2 N T |
2127 // U E E 2 2 2 2 R E I T C +- secondOp
2128 // N X X U S F F N X N 2 V |
2129 // C T T I I P P C T T P T -+
2130 { 1, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // Trunc -+
2131 { 8, 1, 9,99,99, 2, 0,99,99,99, 2, 3 }, // ZExt |
2132 { 8, 0, 1,99,99, 0, 2,99,99,99, 0, 3 }, // SExt |
2133 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // FPToUI |
2134 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // FPToSI |
2135 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4 }, // UIToFP +- firstOp
2136 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4 }, // SIToFP |
2137 { 99,99,99, 0, 0,99,99, 1, 0,99,99, 4 }, // FPTrunc |
2138 { 99,99,99, 2, 2,99,99,10, 2,99,99, 4 }, // FPExt |
2139 { 1, 0, 0,99,99, 0, 0,99,99,99, 7, 3 }, // PtrToInt |
2140 { 99,99,99,99,99,99,99,99,99,13,99,12 }, // IntToPtr |
2141 { 5, 5, 5, 6, 6, 5, 5, 6, 6,11, 5, 1 }, // BitCast -+
2144 // If either of the casts are a bitcast from scalar to vector, disallow the
2145 // merging. However, bitcast of A->B->A are allowed.
2146 bool isFirstBitcast = (firstOp == Instruction::BitCast);
2147 bool isSecondBitcast = (secondOp == Instruction::BitCast);
2148 bool chainedBitcast = (SrcTy == DstTy && isFirstBitcast && isSecondBitcast);
2150 // Check if any of the bitcasts convert scalars<->vectors.
2151 if ((isFirstBitcast && isa<VectorType>(SrcTy) != isa<VectorType>(MidTy)) ||
2152 (isSecondBitcast && isa<VectorType>(MidTy) != isa<VectorType>(DstTy)))
2153 // Unless we are bitcasing to the original type, disallow optimizations.
2154 if (!chainedBitcast) return 0;
2156 int ElimCase = CastResults[firstOp-Instruction::CastOpsBegin]
2157 [secondOp-Instruction::CastOpsBegin];
2160 // categorically disallowed
2163 // allowed, use first cast's opcode
2166 // allowed, use second cast's opcode
2169 // no-op cast in second op implies firstOp as long as the DestTy
2170 // is integer and we are not converting between a vector and a
2172 if (!SrcTy->isVectorTy() && DstTy->isIntegerTy())
2176 // no-op cast in second op implies firstOp as long as the DestTy
2177 // is floating point.
2178 if (DstTy->isFloatingPointTy())
2182 // no-op cast in first op implies secondOp as long as the SrcTy
2184 if (SrcTy->isIntegerTy())
2188 // no-op cast in first op implies secondOp as long as the SrcTy
2189 // is a floating point.
2190 if (SrcTy->isFloatingPointTy())
2194 // ptrtoint, inttoptr -> bitcast (ptr -> ptr) if int size is >= ptr size
2197 unsigned PtrSize = IntPtrTy->getScalarSizeInBits();
2198 unsigned MidSize = MidTy->getScalarSizeInBits();
2199 if (MidSize >= PtrSize)
2200 return Instruction::BitCast;
2204 // ext, trunc -> bitcast, if the SrcTy and DstTy are same size
2205 // ext, trunc -> ext, if sizeof(SrcTy) < sizeof(DstTy)
2206 // ext, trunc -> trunc, if sizeof(SrcTy) > sizeof(DstTy)
2207 unsigned SrcSize = SrcTy->getScalarSizeInBits();
2208 unsigned DstSize = DstTy->getScalarSizeInBits();
2209 if (SrcSize == DstSize)
2210 return Instruction::BitCast;
2211 else if (SrcSize < DstSize)
2215 case 9: // zext, sext -> zext, because sext can't sign extend after zext
2216 return Instruction::ZExt;
2218 // fpext followed by ftrunc is allowed if the bit size returned to is
2219 // the same as the original, in which case its just a bitcast
2221 return Instruction::BitCast;
2222 return 0; // If the types are not the same we can't eliminate it.
2224 // bitcast followed by ptrtoint is allowed as long as the bitcast
2225 // is a pointer to pointer cast.
2226 if (SrcTy->isPointerTy() && MidTy->isPointerTy())
2230 // inttoptr, bitcast -> intptr if bitcast is a ptr to ptr cast
2231 if (MidTy->isPointerTy() && DstTy->isPointerTy())
2235 // inttoptr, ptrtoint -> bitcast if SrcSize<=PtrSize and SrcSize==DstSize
2238 unsigned PtrSize = IntPtrTy->getScalarSizeInBits();
2239 unsigned SrcSize = SrcTy->getScalarSizeInBits();
2240 unsigned DstSize = DstTy->getScalarSizeInBits();
2241 if (SrcSize <= PtrSize && SrcSize == DstSize)
2242 return Instruction::BitCast;
2246 // cast combination can't happen (error in input). This is for all cases
2247 // where the MidTy is not the same for the two cast instructions.
2248 assert(0 && "Invalid Cast Combination");
2251 assert(0 && "Error in CastResults table!!!");
2257 CastInst *CastInst::Create(Instruction::CastOps op, Value *S, Type *Ty,
2258 const Twine &Name, Instruction *InsertBefore) {
2259 assert(castIsValid(op, S, Ty) && "Invalid cast!");
2260 // Construct and return the appropriate CastInst subclass
2262 case Trunc: return new TruncInst (S, Ty, Name, InsertBefore);
2263 case ZExt: return new ZExtInst (S, Ty, Name, InsertBefore);
2264 case SExt: return new SExtInst (S, Ty, Name, InsertBefore);
2265 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertBefore);
2266 case FPExt: return new FPExtInst (S, Ty, Name, InsertBefore);
2267 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertBefore);
2268 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertBefore);
2269 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertBefore);
2270 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertBefore);
2271 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertBefore);
2272 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertBefore);
2273 case BitCast: return new BitCastInst (S, Ty, Name, InsertBefore);
2275 assert(0 && "Invalid opcode provided");
2280 CastInst *CastInst::Create(Instruction::CastOps op, Value *S, Type *Ty,
2281 const Twine &Name, BasicBlock *InsertAtEnd) {
2282 assert(castIsValid(op, S, Ty) && "Invalid cast!");
2283 // Construct and return the appropriate CastInst subclass
2285 case Trunc: return new TruncInst (S, Ty, Name, InsertAtEnd);
2286 case ZExt: return new ZExtInst (S, Ty, Name, InsertAtEnd);
2287 case SExt: return new SExtInst (S, Ty, Name, InsertAtEnd);
2288 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertAtEnd);
2289 case FPExt: return new FPExtInst (S, Ty, Name, InsertAtEnd);
2290 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertAtEnd);
2291 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertAtEnd);
2292 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertAtEnd);
2293 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertAtEnd);
2294 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertAtEnd);
2295 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertAtEnd);
2296 case BitCast: return new BitCastInst (S, Ty, Name, InsertAtEnd);
2298 assert(0 && "Invalid opcode provided");
2303 CastInst *CastInst::CreateZExtOrBitCast(Value *S, Type *Ty,
2305 Instruction *InsertBefore) {
2306 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2307 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2308 return Create(Instruction::ZExt, S, Ty, Name, InsertBefore);
2311 CastInst *CastInst::CreateZExtOrBitCast(Value *S, Type *Ty,
2313 BasicBlock *InsertAtEnd) {
2314 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2315 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2316 return Create(Instruction::ZExt, S, Ty, Name, InsertAtEnd);
2319 CastInst *CastInst::CreateSExtOrBitCast(Value *S, Type *Ty,
2321 Instruction *InsertBefore) {
2322 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2323 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2324 return Create(Instruction::SExt, S, Ty, Name, InsertBefore);
2327 CastInst *CastInst::CreateSExtOrBitCast(Value *S, Type *Ty,
2329 BasicBlock *InsertAtEnd) {
2330 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2331 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2332 return Create(Instruction::SExt, S, Ty, Name, InsertAtEnd);
2335 CastInst *CastInst::CreateTruncOrBitCast(Value *S, Type *Ty,
2337 Instruction *InsertBefore) {
2338 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2339 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2340 return Create(Instruction::Trunc, S, Ty, Name, InsertBefore);
2343 CastInst *CastInst::CreateTruncOrBitCast(Value *S, Type *Ty,
2345 BasicBlock *InsertAtEnd) {
2346 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2347 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2348 return Create(Instruction::Trunc, S, Ty, Name, InsertAtEnd);
2351 CastInst *CastInst::CreatePointerCast(Value *S, Type *Ty,
2353 BasicBlock *InsertAtEnd) {
2354 assert(S->getType()->isPointerTy() && "Invalid cast");
2355 assert((Ty->isIntegerTy() || Ty->isPointerTy()) &&
2358 if (Ty->isIntegerTy())
2359 return Create(Instruction::PtrToInt, S, Ty, Name, InsertAtEnd);
2360 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2363 /// @brief Create a BitCast or a PtrToInt cast instruction
2364 CastInst *CastInst::CreatePointerCast(Value *S, Type *Ty,
2366 Instruction *InsertBefore) {
2367 assert(S->getType()->isPointerTy() && "Invalid cast");
2368 assert((Ty->isIntegerTy() || Ty->isPointerTy()) &&
2371 if (Ty->isIntegerTy())
2372 return Create(Instruction::PtrToInt, S, Ty, Name, InsertBefore);
2373 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2376 CastInst *CastInst::CreateIntegerCast(Value *C, Type *Ty,
2377 bool isSigned, const Twine &Name,
2378 Instruction *InsertBefore) {
2379 assert(C->getType()->isIntOrIntVectorTy() && Ty->isIntOrIntVectorTy() &&
2380 "Invalid integer cast");
2381 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2382 unsigned DstBits = Ty->getScalarSizeInBits();
2383 Instruction::CastOps opcode =
2384 (SrcBits == DstBits ? Instruction::BitCast :
2385 (SrcBits > DstBits ? Instruction::Trunc :
2386 (isSigned ? Instruction::SExt : Instruction::ZExt)));
2387 return Create(opcode, C, Ty, Name, InsertBefore);
2390 CastInst *CastInst::CreateIntegerCast(Value *C, Type *Ty,
2391 bool isSigned, const Twine &Name,
2392 BasicBlock *InsertAtEnd) {
2393 assert(C->getType()->isIntOrIntVectorTy() && Ty->isIntOrIntVectorTy() &&
2395 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2396 unsigned DstBits = Ty->getScalarSizeInBits();
2397 Instruction::CastOps opcode =
2398 (SrcBits == DstBits ? Instruction::BitCast :
2399 (SrcBits > DstBits ? Instruction::Trunc :
2400 (isSigned ? Instruction::SExt : Instruction::ZExt)));
2401 return Create(opcode, C, Ty, Name, InsertAtEnd);
2404 CastInst *CastInst::CreateFPCast(Value *C, Type *Ty,
2406 Instruction *InsertBefore) {
2407 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
2409 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2410 unsigned DstBits = Ty->getScalarSizeInBits();
2411 Instruction::CastOps opcode =
2412 (SrcBits == DstBits ? Instruction::BitCast :
2413 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
2414 return Create(opcode, C, Ty, Name, InsertBefore);
2417 CastInst *CastInst::CreateFPCast(Value *C, Type *Ty,
2419 BasicBlock *InsertAtEnd) {
2420 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
2422 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2423 unsigned DstBits = Ty->getScalarSizeInBits();
2424 Instruction::CastOps opcode =
2425 (SrcBits == DstBits ? Instruction::BitCast :
2426 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
2427 return Create(opcode, C, Ty, Name, InsertAtEnd);
2430 // Check whether it is valid to call getCastOpcode for these types.
2431 // This routine must be kept in sync with getCastOpcode.
2432 bool CastInst::isCastable(Type *SrcTy, Type *DestTy) {
2433 if (!SrcTy->isFirstClassType() || !DestTy->isFirstClassType())
2436 if (SrcTy == DestTy)
2439 if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy))
2440 if (VectorType *DestVecTy = dyn_cast<VectorType>(DestTy))
2441 if (SrcVecTy->getNumElements() == DestVecTy->getNumElements()) {
2442 // An element by element cast. Valid if casting the elements is valid.
2443 SrcTy = SrcVecTy->getElementType();
2444 DestTy = DestVecTy->getElementType();
2447 // Get the bit sizes, we'll need these
2448 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); // 0 for ptr
2449 unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr
2451 // Run through the possibilities ...
2452 if (DestTy->isIntegerTy()) { // Casting to integral
2453 if (SrcTy->isIntegerTy()) { // Casting from integral
2455 } else if (SrcTy->isFloatingPointTy()) { // Casting from floating pt
2457 } else if (SrcTy->isVectorTy()) { // Casting from vector
2458 return DestBits == SrcBits;
2459 } else { // Casting from something else
2460 return SrcTy->isPointerTy();
2462 } else if (DestTy->isFloatingPointTy()) { // Casting to floating pt
2463 if (SrcTy->isIntegerTy()) { // Casting from integral
2465 } else if (SrcTy->isFloatingPointTy()) { // Casting from floating pt
2467 } else if (SrcTy->isVectorTy()) { // Casting from vector
2468 return DestBits == SrcBits;
2469 } else { // Casting from something else
2472 } else if (DestTy->isVectorTy()) { // Casting to vector
2473 return DestBits == SrcBits;
2474 } else if (DestTy->isPointerTy()) { // Casting to pointer
2475 if (SrcTy->isPointerTy()) { // Casting from pointer
2477 } else if (SrcTy->isIntegerTy()) { // Casting from integral
2479 } else { // Casting from something else
2482 } else if (DestTy->isX86_MMXTy()) {
2483 if (SrcTy->isVectorTy()) {
2484 return DestBits == SrcBits; // 64-bit vector to MMX
2488 } else { // Casting to something else
2493 // Provide a way to get a "cast" where the cast opcode is inferred from the
2494 // types and size of the operand. This, basically, is a parallel of the
2495 // logic in the castIsValid function below. This axiom should hold:
2496 // castIsValid( getCastOpcode(Val, Ty), Val, Ty)
2497 // should not assert in castIsValid. In other words, this produces a "correct"
2498 // casting opcode for the arguments passed to it.
2499 // This routine must be kept in sync with isCastable.
2500 Instruction::CastOps
2501 CastInst::getCastOpcode(
2502 const Value *Src, bool SrcIsSigned, Type *DestTy, bool DestIsSigned) {
2503 Type *SrcTy = Src->getType();
2505 assert(SrcTy->isFirstClassType() && DestTy->isFirstClassType() &&
2506 "Only first class types are castable!");
2508 if (SrcTy == DestTy)
2511 if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy))
2512 if (VectorType *DestVecTy = dyn_cast<VectorType>(DestTy))
2513 if (SrcVecTy->getNumElements() == DestVecTy->getNumElements()) {
2514 // An element by element cast. Find the appropriate opcode based on the
2516 SrcTy = SrcVecTy->getElementType();
2517 DestTy = DestVecTy->getElementType();
2520 // Get the bit sizes, we'll need these
2521 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); // 0 for ptr
2522 unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr
2524 // Run through the possibilities ...
2525 if (DestTy->isIntegerTy()) { // Casting to integral
2526 if (SrcTy->isIntegerTy()) { // Casting from integral
2527 if (DestBits < SrcBits)
2528 return Trunc; // int -> smaller int
2529 else if (DestBits > SrcBits) { // its an extension
2531 return SExt; // signed -> SEXT
2533 return ZExt; // unsigned -> ZEXT
2535 return BitCast; // Same size, No-op cast
2537 } else if (SrcTy->isFloatingPointTy()) { // Casting from floating pt
2539 return FPToSI; // FP -> sint
2541 return FPToUI; // FP -> uint
2542 } else if (SrcTy->isVectorTy()) {
2543 assert(DestBits == SrcBits &&
2544 "Casting vector to integer of different width");
2545 return BitCast; // Same size, no-op cast
2547 assert(SrcTy->isPointerTy() &&
2548 "Casting from a value that is not first-class type");
2549 return PtrToInt; // ptr -> int
2551 } else if (DestTy->isFloatingPointTy()) { // Casting to floating pt
2552 if (SrcTy->isIntegerTy()) { // Casting from integral
2554 return SIToFP; // sint -> FP
2556 return UIToFP; // uint -> FP
2557 } else if (SrcTy->isFloatingPointTy()) { // Casting from floating pt
2558 if (DestBits < SrcBits) {
2559 return FPTrunc; // FP -> smaller FP
2560 } else if (DestBits > SrcBits) {
2561 return FPExt; // FP -> larger FP
2563 return BitCast; // same size, no-op cast
2565 } else if (SrcTy->isVectorTy()) {
2566 assert(DestBits == SrcBits &&
2567 "Casting vector to floating point of different width");
2568 return BitCast; // same size, no-op cast
2570 llvm_unreachable("Casting pointer or non-first class to float");
2572 } else if (DestTy->isVectorTy()) {
2573 assert(DestBits == SrcBits &&
2574 "Illegal cast to vector (wrong type or size)");
2576 } else if (DestTy->isPointerTy()) {
2577 if (SrcTy->isPointerTy()) {
2578 return BitCast; // ptr -> ptr
2579 } else if (SrcTy->isIntegerTy()) {
2580 return IntToPtr; // int -> ptr
2582 assert(0 && "Casting pointer to other than pointer or int");
2584 } else if (DestTy->isX86_MMXTy()) {
2585 if (SrcTy->isVectorTy()) {
2586 assert(DestBits == SrcBits && "Casting vector of wrong width to X86_MMX");
2587 return BitCast; // 64-bit vector to MMX
2589 assert(0 && "Illegal cast to X86_MMX");
2592 assert(0 && "Casting to type that is not first-class");
2595 // If we fall through to here we probably hit an assertion cast above
2596 // and assertions are not turned on. Anything we return is an error, so
2597 // BitCast is as good a choice as any.
2601 //===----------------------------------------------------------------------===//
2602 // CastInst SubClass Constructors
2603 //===----------------------------------------------------------------------===//
2605 /// Check that the construction parameters for a CastInst are correct. This
2606 /// could be broken out into the separate constructors but it is useful to have
2607 /// it in one place and to eliminate the redundant code for getting the sizes
2608 /// of the types involved.
2610 CastInst::castIsValid(Instruction::CastOps op, Value *S, Type *DstTy) {
2612 // Check for type sanity on the arguments
2613 Type *SrcTy = S->getType();
2614 if (!SrcTy->isFirstClassType() || !DstTy->isFirstClassType() ||
2615 SrcTy->isAggregateType() || DstTy->isAggregateType())
2618 // Get the size of the types in bits, we'll need this later
2619 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
2620 unsigned DstBitSize = DstTy->getScalarSizeInBits();
2622 // If these are vector types, get the lengths of the vectors (using zero for
2623 // scalar types means that checking that vector lengths match also checks that
2624 // scalars are not being converted to vectors or vectors to scalars).
2625 unsigned SrcLength = SrcTy->isVectorTy() ?
2626 cast<VectorType>(SrcTy)->getNumElements() : 0;
2627 unsigned DstLength = DstTy->isVectorTy() ?
2628 cast<VectorType>(DstTy)->getNumElements() : 0;
2630 // Switch on the opcode provided
2632 default: return false; // This is an input error
2633 case Instruction::Trunc:
2634 return SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy() &&
2635 SrcLength == DstLength && SrcBitSize > DstBitSize;
2636 case Instruction::ZExt:
2637 return SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy() &&
2638 SrcLength == DstLength && SrcBitSize < DstBitSize;
2639 case Instruction::SExt:
2640 return SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy() &&
2641 SrcLength == DstLength && SrcBitSize < DstBitSize;
2642 case Instruction::FPTrunc:
2643 return SrcTy->isFPOrFPVectorTy() && DstTy->isFPOrFPVectorTy() &&
2644 SrcLength == DstLength && SrcBitSize > DstBitSize;
2645 case Instruction::FPExt:
2646 return SrcTy->isFPOrFPVectorTy() && DstTy->isFPOrFPVectorTy() &&
2647 SrcLength == DstLength && SrcBitSize < DstBitSize;
2648 case Instruction::UIToFP:
2649 case Instruction::SIToFP:
2650 return SrcTy->isIntOrIntVectorTy() && DstTy->isFPOrFPVectorTy() &&
2651 SrcLength == DstLength;
2652 case Instruction::FPToUI:
2653 case Instruction::FPToSI:
2654 return SrcTy->isFPOrFPVectorTy() && DstTy->isIntOrIntVectorTy() &&
2655 SrcLength == DstLength;
2656 case Instruction::PtrToInt:
2657 return SrcTy->isPointerTy() && DstTy->isIntegerTy();
2658 case Instruction::IntToPtr:
2659 return SrcTy->isIntegerTy() && DstTy->isPointerTy();
2660 case Instruction::BitCast:
2661 // BitCast implies a no-op cast of type only. No bits change.
2662 // However, you can't cast pointers to anything but pointers.
2663 if (SrcTy->isPointerTy() != DstTy->isPointerTy())
2666 // Now we know we're not dealing with a pointer/non-pointer mismatch. In all
2667 // these cases, the cast is okay if the source and destination bit widths
2669 return SrcTy->getPrimitiveSizeInBits() == DstTy->getPrimitiveSizeInBits();
2673 TruncInst::TruncInst(
2674 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2675 ) : CastInst(Ty, Trunc, S, Name, InsertBefore) {
2676 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
2679 TruncInst::TruncInst(
2680 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2681 ) : CastInst(Ty, Trunc, S, Name, InsertAtEnd) {
2682 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
2686 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2687 ) : CastInst(Ty, ZExt, S, Name, InsertBefore) {
2688 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
2692 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2693 ) : CastInst(Ty, ZExt, S, Name, InsertAtEnd) {
2694 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
2697 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2698 ) : CastInst(Ty, SExt, S, Name, InsertBefore) {
2699 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
2703 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2704 ) : CastInst(Ty, SExt, S, Name, InsertAtEnd) {
2705 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
2708 FPTruncInst::FPTruncInst(
2709 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2710 ) : CastInst(Ty, FPTrunc, S, Name, InsertBefore) {
2711 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
2714 FPTruncInst::FPTruncInst(
2715 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2716 ) : CastInst(Ty, FPTrunc, S, Name, InsertAtEnd) {
2717 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
2720 FPExtInst::FPExtInst(
2721 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2722 ) : CastInst(Ty, FPExt, S, Name, InsertBefore) {
2723 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
2726 FPExtInst::FPExtInst(
2727 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2728 ) : CastInst(Ty, FPExt, S, Name, InsertAtEnd) {
2729 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
2732 UIToFPInst::UIToFPInst(
2733 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2734 ) : CastInst(Ty, UIToFP, S, Name, InsertBefore) {
2735 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
2738 UIToFPInst::UIToFPInst(
2739 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2740 ) : CastInst(Ty, UIToFP, S, Name, InsertAtEnd) {
2741 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
2744 SIToFPInst::SIToFPInst(
2745 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2746 ) : CastInst(Ty, SIToFP, S, Name, InsertBefore) {
2747 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
2750 SIToFPInst::SIToFPInst(
2751 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2752 ) : CastInst(Ty, SIToFP, S, Name, InsertAtEnd) {
2753 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
2756 FPToUIInst::FPToUIInst(
2757 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2758 ) : CastInst(Ty, FPToUI, S, Name, InsertBefore) {
2759 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
2762 FPToUIInst::FPToUIInst(
2763 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2764 ) : CastInst(Ty, FPToUI, S, Name, InsertAtEnd) {
2765 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
2768 FPToSIInst::FPToSIInst(
2769 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2770 ) : CastInst(Ty, FPToSI, S, Name, InsertBefore) {
2771 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
2774 FPToSIInst::FPToSIInst(
2775 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2776 ) : CastInst(Ty, FPToSI, S, Name, InsertAtEnd) {
2777 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
2780 PtrToIntInst::PtrToIntInst(
2781 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2782 ) : CastInst(Ty, PtrToInt, S, Name, InsertBefore) {
2783 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
2786 PtrToIntInst::PtrToIntInst(
2787 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2788 ) : CastInst(Ty, PtrToInt, S, Name, InsertAtEnd) {
2789 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
2792 IntToPtrInst::IntToPtrInst(
2793 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2794 ) : CastInst(Ty, IntToPtr, S, Name, InsertBefore) {
2795 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
2798 IntToPtrInst::IntToPtrInst(
2799 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2800 ) : CastInst(Ty, IntToPtr, S, Name, InsertAtEnd) {
2801 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
2804 BitCastInst::BitCastInst(
2805 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2806 ) : CastInst(Ty, BitCast, S, Name, InsertBefore) {
2807 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
2810 BitCastInst::BitCastInst(
2811 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2812 ) : CastInst(Ty, BitCast, S, Name, InsertAtEnd) {
2813 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
2816 //===----------------------------------------------------------------------===//
2818 //===----------------------------------------------------------------------===//
2820 void CmpInst::Anchor() const {}
2822 CmpInst::CmpInst(Type *ty, OtherOps op, unsigned short predicate,
2823 Value *LHS, Value *RHS, const Twine &Name,
2824 Instruction *InsertBefore)
2825 : Instruction(ty, op,
2826 OperandTraits<CmpInst>::op_begin(this),
2827 OperandTraits<CmpInst>::operands(this),
2831 setPredicate((Predicate)predicate);
2835 CmpInst::CmpInst(Type *ty, OtherOps op, unsigned short predicate,
2836 Value *LHS, Value *RHS, const Twine &Name,
2837 BasicBlock *InsertAtEnd)
2838 : Instruction(ty, op,
2839 OperandTraits<CmpInst>::op_begin(this),
2840 OperandTraits<CmpInst>::operands(this),
2844 setPredicate((Predicate)predicate);
2849 CmpInst::Create(OtherOps Op, unsigned short predicate,
2850 Value *S1, Value *S2,
2851 const Twine &Name, Instruction *InsertBefore) {
2852 if (Op == Instruction::ICmp) {
2854 return new ICmpInst(InsertBefore, CmpInst::Predicate(predicate),
2857 return new ICmpInst(CmpInst::Predicate(predicate),
2862 return new FCmpInst(InsertBefore, CmpInst::Predicate(predicate),
2865 return new FCmpInst(CmpInst::Predicate(predicate),
2870 CmpInst::Create(OtherOps Op, unsigned short predicate, Value *S1, Value *S2,
2871 const Twine &Name, BasicBlock *InsertAtEnd) {
2872 if (Op == Instruction::ICmp) {
2873 return new ICmpInst(*InsertAtEnd, CmpInst::Predicate(predicate),
2876 return new FCmpInst(*InsertAtEnd, CmpInst::Predicate(predicate),
2880 void CmpInst::swapOperands() {
2881 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2884 cast<FCmpInst>(this)->swapOperands();
2887 bool CmpInst::isCommutative() const {
2888 if (const ICmpInst *IC = dyn_cast<ICmpInst>(this))
2889 return IC->isCommutative();
2890 return cast<FCmpInst>(this)->isCommutative();
2893 bool CmpInst::isEquality() const {
2894 if (const ICmpInst *IC = dyn_cast<ICmpInst>(this))
2895 return IC->isEquality();
2896 return cast<FCmpInst>(this)->isEquality();
2900 CmpInst::Predicate CmpInst::getInversePredicate(Predicate pred) {
2902 default: assert(0 && "Unknown cmp predicate!");
2903 case ICMP_EQ: return ICMP_NE;
2904 case ICMP_NE: return ICMP_EQ;
2905 case ICMP_UGT: return ICMP_ULE;
2906 case ICMP_ULT: return ICMP_UGE;
2907 case ICMP_UGE: return ICMP_ULT;
2908 case ICMP_ULE: return ICMP_UGT;
2909 case ICMP_SGT: return ICMP_SLE;
2910 case ICMP_SLT: return ICMP_SGE;
2911 case ICMP_SGE: return ICMP_SLT;
2912 case ICMP_SLE: return ICMP_SGT;
2914 case FCMP_OEQ: return FCMP_UNE;
2915 case FCMP_ONE: return FCMP_UEQ;
2916 case FCMP_OGT: return FCMP_ULE;
2917 case FCMP_OLT: return FCMP_UGE;
2918 case FCMP_OGE: return FCMP_ULT;
2919 case FCMP_OLE: return FCMP_UGT;
2920 case FCMP_UEQ: return FCMP_ONE;
2921 case FCMP_UNE: return FCMP_OEQ;
2922 case FCMP_UGT: return FCMP_OLE;
2923 case FCMP_ULT: return FCMP_OGE;
2924 case FCMP_UGE: return FCMP_OLT;
2925 case FCMP_ULE: return FCMP_OGT;
2926 case FCMP_ORD: return FCMP_UNO;
2927 case FCMP_UNO: return FCMP_ORD;
2928 case FCMP_TRUE: return FCMP_FALSE;
2929 case FCMP_FALSE: return FCMP_TRUE;
2933 ICmpInst::Predicate ICmpInst::getSignedPredicate(Predicate pred) {
2935 default: assert(0 && "Unknown icmp predicate!");
2936 case ICMP_EQ: case ICMP_NE:
2937 case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE:
2939 case ICMP_UGT: return ICMP_SGT;
2940 case ICMP_ULT: return ICMP_SLT;
2941 case ICMP_UGE: return ICMP_SGE;
2942 case ICMP_ULE: return ICMP_SLE;
2946 ICmpInst::Predicate ICmpInst::getUnsignedPredicate(Predicate pred) {
2948 default: assert(0 && "Unknown icmp predicate!");
2949 case ICMP_EQ: case ICMP_NE:
2950 case ICMP_UGT: case ICMP_ULT: case ICMP_UGE: case ICMP_ULE:
2952 case ICMP_SGT: return ICMP_UGT;
2953 case ICMP_SLT: return ICMP_ULT;
2954 case ICMP_SGE: return ICMP_UGE;
2955 case ICMP_SLE: return ICMP_ULE;
2959 /// Initialize a set of values that all satisfy the condition with C.
2962 ICmpInst::makeConstantRange(Predicate pred, const APInt &C) {
2965 uint32_t BitWidth = C.getBitWidth();
2967 default: llvm_unreachable("Invalid ICmp opcode to ConstantRange ctor!");
2968 case ICmpInst::ICMP_EQ: Upper++; break;
2969 case ICmpInst::ICMP_NE: Lower++; break;
2970 case ICmpInst::ICMP_ULT:
2971 Lower = APInt::getMinValue(BitWidth);
2972 // Check for an empty-set condition.
2974 return ConstantRange(BitWidth, /*isFullSet=*/false);
2976 case ICmpInst::ICMP_SLT:
2977 Lower = APInt::getSignedMinValue(BitWidth);
2978 // Check for an empty-set condition.
2980 return ConstantRange(BitWidth, /*isFullSet=*/false);
2982 case ICmpInst::ICMP_UGT:
2983 Lower++; Upper = APInt::getMinValue(BitWidth); // Min = Next(Max)
2984 // Check for an empty-set condition.
2986 return ConstantRange(BitWidth, /*isFullSet=*/false);
2988 case ICmpInst::ICMP_SGT:
2989 Lower++; Upper = APInt::getSignedMinValue(BitWidth); // Min = Next(Max)
2990 // Check for an empty-set condition.
2992 return ConstantRange(BitWidth, /*isFullSet=*/false);
2994 case ICmpInst::ICMP_ULE:
2995 Lower = APInt::getMinValue(BitWidth); Upper++;
2996 // Check for a full-set condition.
2998 return ConstantRange(BitWidth, /*isFullSet=*/true);
3000 case ICmpInst::ICMP_SLE:
3001 Lower = APInt::getSignedMinValue(BitWidth); Upper++;
3002 // Check for a full-set condition.
3004 return ConstantRange(BitWidth, /*isFullSet=*/true);
3006 case ICmpInst::ICMP_UGE:
3007 Upper = APInt::getMinValue(BitWidth); // Min = Next(Max)
3008 // Check for a full-set condition.
3010 return ConstantRange(BitWidth, /*isFullSet=*/true);
3012 case ICmpInst::ICMP_SGE:
3013 Upper = APInt::getSignedMinValue(BitWidth); // Min = Next(Max)
3014 // Check for a full-set condition.
3016 return ConstantRange(BitWidth, /*isFullSet=*/true);
3019 return ConstantRange(Lower, Upper);
3022 CmpInst::Predicate CmpInst::getSwappedPredicate(Predicate pred) {
3024 default: assert(0 && "Unknown cmp predicate!");
3025 case ICMP_EQ: case ICMP_NE:
3027 case ICMP_SGT: return ICMP_SLT;
3028 case ICMP_SLT: return ICMP_SGT;
3029 case ICMP_SGE: return ICMP_SLE;
3030 case ICMP_SLE: return ICMP_SGE;
3031 case ICMP_UGT: return ICMP_ULT;
3032 case ICMP_ULT: return ICMP_UGT;
3033 case ICMP_UGE: return ICMP_ULE;
3034 case ICMP_ULE: return ICMP_UGE;
3036 case FCMP_FALSE: case FCMP_TRUE:
3037 case FCMP_OEQ: case FCMP_ONE:
3038 case FCMP_UEQ: case FCMP_UNE:
3039 case FCMP_ORD: case FCMP_UNO:
3041 case FCMP_OGT: return FCMP_OLT;
3042 case FCMP_OLT: return FCMP_OGT;
3043 case FCMP_OGE: return FCMP_OLE;
3044 case FCMP_OLE: return FCMP_OGE;
3045 case FCMP_UGT: return FCMP_ULT;
3046 case FCMP_ULT: return FCMP_UGT;
3047 case FCMP_UGE: return FCMP_ULE;
3048 case FCMP_ULE: return FCMP_UGE;
3052 bool CmpInst::isUnsigned(unsigned short predicate) {
3053 switch (predicate) {
3054 default: return false;
3055 case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_ULE: case ICmpInst::ICMP_UGT:
3056 case ICmpInst::ICMP_UGE: return true;
3060 bool CmpInst::isSigned(unsigned short predicate) {
3061 switch (predicate) {
3062 default: return false;
3063 case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_SLE: case ICmpInst::ICMP_SGT:
3064 case ICmpInst::ICMP_SGE: return true;
3068 bool CmpInst::isOrdered(unsigned short predicate) {
3069 switch (predicate) {
3070 default: return false;
3071 case FCmpInst::FCMP_OEQ: case FCmpInst::FCMP_ONE: case FCmpInst::FCMP_OGT:
3072 case FCmpInst::FCMP_OLT: case FCmpInst::FCMP_OGE: case FCmpInst::FCMP_OLE:
3073 case FCmpInst::FCMP_ORD: return true;
3077 bool CmpInst::isUnordered(unsigned short predicate) {
3078 switch (predicate) {
3079 default: return false;
3080 case FCmpInst::FCMP_UEQ: case FCmpInst::FCMP_UNE: case FCmpInst::FCMP_UGT:
3081 case FCmpInst::FCMP_ULT: case FCmpInst::FCMP_UGE: case FCmpInst::FCMP_ULE:
3082 case FCmpInst::FCMP_UNO: return true;
3086 bool CmpInst::isTrueWhenEqual(unsigned short predicate) {
3088 default: return false;
3089 case ICMP_EQ: case ICMP_UGE: case ICMP_ULE: case ICMP_SGE: case ICMP_SLE:
3090 case FCMP_TRUE: case FCMP_UEQ: case FCMP_UGE: case FCMP_ULE: return true;
3094 bool CmpInst::isFalseWhenEqual(unsigned short predicate) {
3096 case ICMP_NE: case ICMP_UGT: case ICMP_ULT: case ICMP_SGT: case ICMP_SLT:
3097 case FCMP_FALSE: case FCMP_ONE: case FCMP_OGT: case FCMP_OLT: return true;
3098 default: return false;
3103 //===----------------------------------------------------------------------===//
3104 // SwitchInst Implementation
3105 //===----------------------------------------------------------------------===//
3107 void SwitchInst::init(Value *Value, BasicBlock *Default, unsigned NumReserved) {
3108 assert(Value && Default && NumReserved);
3109 ReservedSpace = NumReserved;
3111 OperandList = allocHungoffUses(ReservedSpace);
3113 OperandList[0] = Value;
3114 OperandList[1] = Default;
3117 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
3118 /// switch on and a default destination. The number of additional cases can
3119 /// be specified here to make memory allocation more efficient. This
3120 /// constructor can also autoinsert before another instruction.
3121 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
3122 Instruction *InsertBefore)
3123 : TerminatorInst(Type::getVoidTy(Value->getContext()), Instruction::Switch,
3124 0, 0, InsertBefore) {
3125 init(Value, Default, 2+NumCases*2);
3128 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
3129 /// switch on and a default destination. The number of additional cases can
3130 /// be specified here to make memory allocation more efficient. This
3131 /// constructor also autoinserts at the end of the specified BasicBlock.
3132 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
3133 BasicBlock *InsertAtEnd)
3134 : TerminatorInst(Type::getVoidTy(Value->getContext()), Instruction::Switch,
3135 0, 0, InsertAtEnd) {
3136 init(Value, Default, 2+NumCases*2);
3139 SwitchInst::SwitchInst(const SwitchInst &SI)
3140 : TerminatorInst(SI.getType(), Instruction::Switch, 0, 0) {
3141 init(SI.getCondition(), SI.getDefaultDest(), SI.getNumOperands());
3142 NumOperands = SI.getNumOperands();
3143 Use *OL = OperandList, *InOL = SI.OperandList;
3144 for (unsigned i = 2, E = SI.getNumOperands(); i != E; i += 2) {
3146 OL[i+1] = InOL[i+1];
3148 SubclassOptionalData = SI.SubclassOptionalData;
3151 SwitchInst::~SwitchInst() {
3156 /// addCase - Add an entry to the switch instruction...
3158 void SwitchInst::addCase(ConstantInt *OnVal, BasicBlock *Dest) {
3159 unsigned OpNo = NumOperands;
3160 if (OpNo+2 > ReservedSpace)
3161 growOperands(); // Get more space!
3162 // Initialize some new operands.
3163 assert(OpNo+1 < ReservedSpace && "Growing didn't work!");
3164 NumOperands = OpNo+2;
3165 OperandList[OpNo] = OnVal;
3166 OperandList[OpNo+1] = Dest;
3169 /// removeCase - This method removes the specified successor from the switch
3170 /// instruction. Note that this cannot be used to remove the default
3171 /// destination (successor #0).
3173 void SwitchInst::removeCase(unsigned idx) {
3174 assert(idx != 0 && "Cannot remove the default case!");
3175 assert(idx*2 < getNumOperands() && "Successor index out of range!!!");
3177 unsigned NumOps = getNumOperands();
3178 Use *OL = OperandList;
3180 // Overwrite this case with the end of the list.
3181 if ((idx + 1) * 2 != NumOps) {
3182 OL[idx * 2] = OL[NumOps - 2];
3183 OL[idx * 2 + 1] = OL[NumOps - 1];
3186 // Nuke the last value.
3187 OL[NumOps-2].set(0);
3188 OL[NumOps-2+1].set(0);
3189 NumOperands = NumOps-2;
3192 /// growOperands - grow operands - This grows the operand list in response
3193 /// to a push_back style of operation. This grows the number of ops by 3 times.
3195 void SwitchInst::growOperands() {
3196 unsigned e = getNumOperands();
3197 unsigned NumOps = e*3;
3199 ReservedSpace = NumOps;
3200 Use *NewOps = allocHungoffUses(NumOps);
3201 Use *OldOps = OperandList;
3202 for (unsigned i = 0; i != e; ++i) {
3203 NewOps[i] = OldOps[i];
3205 OperandList = NewOps;
3206 Use::zap(OldOps, OldOps + e, true);
3210 BasicBlock *SwitchInst::getSuccessorV(unsigned idx) const {
3211 return getSuccessor(idx);
3213 unsigned SwitchInst::getNumSuccessorsV() const {
3214 return getNumSuccessors();
3216 void SwitchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
3217 setSuccessor(idx, B);
3220 //===----------------------------------------------------------------------===//
3221 // IndirectBrInst Implementation
3222 //===----------------------------------------------------------------------===//
3224 void IndirectBrInst::init(Value *Address, unsigned NumDests) {
3225 assert(Address && Address->getType()->isPointerTy() &&
3226 "Address of indirectbr must be a pointer");
3227 ReservedSpace = 1+NumDests;
3229 OperandList = allocHungoffUses(ReservedSpace);
3231 OperandList[0] = Address;
3235 /// growOperands - grow operands - This grows the operand list in response
3236 /// to a push_back style of operation. This grows the number of ops by 2 times.
3238 void IndirectBrInst::growOperands() {
3239 unsigned e = getNumOperands();
3240 unsigned NumOps = e*2;
3242 ReservedSpace = NumOps;
3243 Use *NewOps = allocHungoffUses(NumOps);
3244 Use *OldOps = OperandList;
3245 for (unsigned i = 0; i != e; ++i)
3246 NewOps[i] = OldOps[i];
3247 OperandList = NewOps;
3248 Use::zap(OldOps, OldOps + e, true);
3251 IndirectBrInst::IndirectBrInst(Value *Address, unsigned NumCases,
3252 Instruction *InsertBefore)
3253 : TerminatorInst(Type::getVoidTy(Address->getContext()),Instruction::IndirectBr,
3254 0, 0, InsertBefore) {
3255 init(Address, NumCases);
3258 IndirectBrInst::IndirectBrInst(Value *Address, unsigned NumCases,
3259 BasicBlock *InsertAtEnd)
3260 : TerminatorInst(Type::getVoidTy(Address->getContext()),Instruction::IndirectBr,
3261 0, 0, InsertAtEnd) {
3262 init(Address, NumCases);
3265 IndirectBrInst::IndirectBrInst(const IndirectBrInst &IBI)
3266 : TerminatorInst(Type::getVoidTy(IBI.getContext()), Instruction::IndirectBr,
3267 allocHungoffUses(IBI.getNumOperands()),
3268 IBI.getNumOperands()) {
3269 Use *OL = OperandList, *InOL = IBI.OperandList;
3270 for (unsigned i = 0, E = IBI.getNumOperands(); i != E; ++i)
3272 SubclassOptionalData = IBI.SubclassOptionalData;
3275 IndirectBrInst::~IndirectBrInst() {
3279 /// addDestination - Add a destination.
3281 void IndirectBrInst::addDestination(BasicBlock *DestBB) {
3282 unsigned OpNo = NumOperands;
3283 if (OpNo+1 > ReservedSpace)
3284 growOperands(); // Get more space!
3285 // Initialize some new operands.
3286 assert(OpNo < ReservedSpace && "Growing didn't work!");
3287 NumOperands = OpNo+1;
3288 OperandList[OpNo] = DestBB;
3291 /// removeDestination - This method removes the specified successor from the
3292 /// indirectbr instruction.
3293 void IndirectBrInst::removeDestination(unsigned idx) {
3294 assert(idx < getNumOperands()-1 && "Successor index out of range!");
3296 unsigned NumOps = getNumOperands();
3297 Use *OL = OperandList;
3299 // Replace this value with the last one.
3300 OL[idx+1] = OL[NumOps-1];
3302 // Nuke the last value.
3303 OL[NumOps-1].set(0);
3304 NumOperands = NumOps-1;
3307 BasicBlock *IndirectBrInst::getSuccessorV(unsigned idx) const {
3308 return getSuccessor(idx);
3310 unsigned IndirectBrInst::getNumSuccessorsV() const {
3311 return getNumSuccessors();
3313 void IndirectBrInst::setSuccessorV(unsigned idx, BasicBlock *B) {
3314 setSuccessor(idx, B);
3317 //===----------------------------------------------------------------------===//
3318 // clone_impl() implementations
3319 //===----------------------------------------------------------------------===//
3321 // Define these methods here so vtables don't get emitted into every translation
3322 // unit that uses these classes.
3324 GetElementPtrInst *GetElementPtrInst::clone_impl() const {
3325 return new (getNumOperands()) GetElementPtrInst(*this);
3328 BinaryOperator *BinaryOperator::clone_impl() const {
3329 return Create(getOpcode(), Op<0>(), Op<1>());
3332 FCmpInst* FCmpInst::clone_impl() const {
3333 return new FCmpInst(getPredicate(), Op<0>(), Op<1>());
3336 ICmpInst* ICmpInst::clone_impl() const {
3337 return new ICmpInst(getPredicate(), Op<0>(), Op<1>());
3340 ExtractValueInst *ExtractValueInst::clone_impl() const {
3341 return new ExtractValueInst(*this);
3344 InsertValueInst *InsertValueInst::clone_impl() const {
3345 return new InsertValueInst(*this);
3348 AllocaInst *AllocaInst::clone_impl() const {
3349 return new AllocaInst(getAllocatedType(),
3350 (Value*)getOperand(0),
3354 LoadInst *LoadInst::clone_impl() const {
3355 return new LoadInst(getOperand(0), Twine(), isVolatile(),
3356 getAlignment(), getOrdering(), getSynchScope());
3359 StoreInst *StoreInst::clone_impl() const {
3360 return new StoreInst(getOperand(0), getOperand(1), isVolatile(),
3361 getAlignment(), getOrdering(), getSynchScope());
3365 AtomicCmpXchgInst *AtomicCmpXchgInst::clone_impl() const {
3366 AtomicCmpXchgInst *Result =
3367 new AtomicCmpXchgInst(getOperand(0), getOperand(1), getOperand(2),
3368 getOrdering(), getSynchScope());
3369 Result->setVolatile(isVolatile());
3373 AtomicRMWInst *AtomicRMWInst::clone_impl() const {
3374 AtomicRMWInst *Result =
3375 new AtomicRMWInst(getOperation(),getOperand(0), getOperand(1),
3376 getOrdering(), getSynchScope());
3377 Result->setVolatile(isVolatile());
3381 FenceInst *FenceInst::clone_impl() const {
3382 return new FenceInst(getContext(), getOrdering(), getSynchScope());
3385 TruncInst *TruncInst::clone_impl() const {
3386 return new TruncInst(getOperand(0), getType());
3389 ZExtInst *ZExtInst::clone_impl() const {
3390 return new ZExtInst(getOperand(0), getType());
3393 SExtInst *SExtInst::clone_impl() const {
3394 return new SExtInst(getOperand(0), getType());
3397 FPTruncInst *FPTruncInst::clone_impl() const {
3398 return new FPTruncInst(getOperand(0), getType());
3401 FPExtInst *FPExtInst::clone_impl() const {
3402 return new FPExtInst(getOperand(0), getType());
3405 UIToFPInst *UIToFPInst::clone_impl() const {
3406 return new UIToFPInst(getOperand(0), getType());
3409 SIToFPInst *SIToFPInst::clone_impl() const {
3410 return new SIToFPInst(getOperand(0), getType());
3413 FPToUIInst *FPToUIInst::clone_impl() const {
3414 return new FPToUIInst(getOperand(0), getType());
3417 FPToSIInst *FPToSIInst::clone_impl() const {
3418 return new FPToSIInst(getOperand(0), getType());
3421 PtrToIntInst *PtrToIntInst::clone_impl() const {
3422 return new PtrToIntInst(getOperand(0), getType());
3425 IntToPtrInst *IntToPtrInst::clone_impl() const {
3426 return new IntToPtrInst(getOperand(0), getType());
3429 BitCastInst *BitCastInst::clone_impl() const {
3430 return new BitCastInst(getOperand(0), getType());
3433 CallInst *CallInst::clone_impl() const {
3434 return new(getNumOperands()) CallInst(*this);
3437 SelectInst *SelectInst::clone_impl() const {
3438 return SelectInst::Create(getOperand(0), getOperand(1), getOperand(2));
3441 VAArgInst *VAArgInst::clone_impl() const {
3442 return new VAArgInst(getOperand(0), getType());
3445 ExtractElementInst *ExtractElementInst::clone_impl() const {
3446 return ExtractElementInst::Create(getOperand(0), getOperand(1));
3449 InsertElementInst *InsertElementInst::clone_impl() const {
3450 return InsertElementInst::Create(getOperand(0),
3455 ShuffleVectorInst *ShuffleVectorInst::clone_impl() const {
3456 return new ShuffleVectorInst(getOperand(0),
3461 PHINode *PHINode::clone_impl() const {
3462 return new PHINode(*this);
3465 LandingPadInst *LandingPadInst::clone_impl() const {
3466 return new LandingPadInst(*this);
3469 ReturnInst *ReturnInst::clone_impl() const {
3470 return new(getNumOperands()) ReturnInst(*this);
3473 BranchInst *BranchInst::clone_impl() const {
3474 return new(getNumOperands()) BranchInst(*this);
3477 SwitchInst *SwitchInst::clone_impl() const {
3478 return new SwitchInst(*this);
3481 IndirectBrInst *IndirectBrInst::clone_impl() const {
3482 return new IndirectBrInst(*this);
3486 InvokeInst *InvokeInst::clone_impl() const {
3487 return new(getNumOperands()) InvokeInst(*this);
3490 ResumeInst *ResumeInst::clone_impl() const {
3491 return new(1) ResumeInst(*this);
3494 UnwindInst *UnwindInst::clone_impl() const {
3495 LLVMContext &Context = getContext();
3496 return new UnwindInst(Context);
3499 UnreachableInst *UnreachableInst::clone_impl() const {
3500 LLVMContext &Context = getContext();
3501 return new UnreachableInst(Context);