1 //===-- Instructions.cpp - Implement the LLVM instructions ----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements all of the non-inline methods for the LLVM instruction
13 //===----------------------------------------------------------------------===//
15 #include "llvm/Instructions.h"
16 #include "LLVMContextImpl.h"
17 #include "llvm/Constants.h"
18 #include "llvm/DataLayout.h"
19 #include "llvm/DerivedTypes.h"
20 #include "llvm/Function.h"
21 #include "llvm/Module.h"
22 #include "llvm/Operator.h"
23 #include "llvm/Support/CallSite.h"
24 #include "llvm/Support/ConstantRange.h"
25 #include "llvm/Support/ErrorHandling.h"
26 #include "llvm/Support/MathExtras.h"
29 //===----------------------------------------------------------------------===//
31 //===----------------------------------------------------------------------===//
33 User::op_iterator CallSite::getCallee() const {
34 Instruction *II(getInstruction());
36 ? cast<CallInst>(II)->op_end() - 1 // Skip Callee
37 : cast<InvokeInst>(II)->op_end() - 3; // Skip BB, BB, Callee
40 //===----------------------------------------------------------------------===//
41 // TerminatorInst Class
42 //===----------------------------------------------------------------------===//
44 // Out of line virtual method, so the vtable, etc has a home.
45 TerminatorInst::~TerminatorInst() {
48 //===----------------------------------------------------------------------===//
49 // UnaryInstruction Class
50 //===----------------------------------------------------------------------===//
52 // Out of line virtual method, so the vtable, etc has a home.
53 UnaryInstruction::~UnaryInstruction() {
56 //===----------------------------------------------------------------------===//
58 //===----------------------------------------------------------------------===//
60 /// areInvalidOperands - Return a string if the specified operands are invalid
61 /// for a select operation, otherwise return null.
62 const char *SelectInst::areInvalidOperands(Value *Op0, Value *Op1, Value *Op2) {
63 if (Op1->getType() != Op2->getType())
64 return "both values to select must have same type";
66 if (VectorType *VT = dyn_cast<VectorType>(Op0->getType())) {
68 if (VT->getElementType() != Type::getInt1Ty(Op0->getContext()))
69 return "vector select condition element type must be i1";
70 VectorType *ET = dyn_cast<VectorType>(Op1->getType());
72 return "selected values for vector select must be vectors";
73 if (ET->getNumElements() != VT->getNumElements())
74 return "vector select requires selected vectors to have "
75 "the same vector length as select condition";
76 } else if (Op0->getType() != Type::getInt1Ty(Op0->getContext())) {
77 return "select condition must be i1 or <n x i1>";
83 //===----------------------------------------------------------------------===//
85 //===----------------------------------------------------------------------===//
87 PHINode::PHINode(const PHINode &PN)
88 : Instruction(PN.getType(), Instruction::PHI,
89 allocHungoffUses(PN.getNumOperands()), PN.getNumOperands()),
90 ReservedSpace(PN.getNumOperands()) {
91 std::copy(PN.op_begin(), PN.op_end(), op_begin());
92 std::copy(PN.block_begin(), PN.block_end(), block_begin());
93 SubclassOptionalData = PN.SubclassOptionalData;
100 Use *PHINode::allocHungoffUses(unsigned N) const {
101 // Allocate the array of Uses of the incoming values, followed by a pointer
102 // (with bottom bit set) to the User, followed by the array of pointers to
103 // the incoming basic blocks.
104 size_t size = N * sizeof(Use) + sizeof(Use::UserRef)
105 + N * sizeof(BasicBlock*);
106 Use *Begin = static_cast<Use*>(::operator new(size));
107 Use *End = Begin + N;
108 (void) new(End) Use::UserRef(const_cast<PHINode*>(this), 1);
109 return Use::initTags(Begin, End);
112 // removeIncomingValue - Remove an incoming value. This is useful if a
113 // predecessor basic block is deleted.
114 Value *PHINode::removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty) {
115 Value *Removed = getIncomingValue(Idx);
117 // Move everything after this operand down.
119 // FIXME: we could just swap with the end of the list, then erase. However,
120 // clients might not expect this to happen. The code as it is thrashes the
121 // use/def lists, which is kinda lame.
122 std::copy(op_begin() + Idx + 1, op_end(), op_begin() + Idx);
123 std::copy(block_begin() + Idx + 1, block_end(), block_begin() + Idx);
125 // Nuke the last value.
129 // If the PHI node is dead, because it has zero entries, nuke it now.
130 if (getNumOperands() == 0 && DeletePHIIfEmpty) {
131 // If anyone is using this PHI, make them use a dummy value instead...
132 replaceAllUsesWith(UndefValue::get(getType()));
138 /// growOperands - grow operands - This grows the operand list in response
139 /// to a push_back style of operation. This grows the number of ops by 1.5
142 void PHINode::growOperands() {
143 unsigned e = getNumOperands();
144 unsigned NumOps = e + e / 2;
145 if (NumOps < 2) NumOps = 2; // 2 op PHI nodes are VERY common.
147 Use *OldOps = op_begin();
148 BasicBlock **OldBlocks = block_begin();
150 ReservedSpace = NumOps;
151 OperandList = allocHungoffUses(ReservedSpace);
153 std::copy(OldOps, OldOps + e, op_begin());
154 std::copy(OldBlocks, OldBlocks + e, block_begin());
156 Use::zap(OldOps, OldOps + e, true);
159 /// hasConstantValue - If the specified PHI node always merges together the same
160 /// value, return the value, otherwise return null.
161 Value *PHINode::hasConstantValue() const {
162 // Exploit the fact that phi nodes always have at least one entry.
163 Value *ConstantValue = getIncomingValue(0);
164 for (unsigned i = 1, e = getNumIncomingValues(); i != e; ++i)
165 if (getIncomingValue(i) != ConstantValue && getIncomingValue(i) != this) {
166 if (ConstantValue != this)
167 return 0; // Incoming values not all the same.
168 // The case where the first value is this PHI.
169 ConstantValue = getIncomingValue(i);
171 if (ConstantValue == this)
172 return UndefValue::get(getType());
173 return ConstantValue;
176 //===----------------------------------------------------------------------===//
177 // LandingPadInst Implementation
178 //===----------------------------------------------------------------------===//
180 LandingPadInst::LandingPadInst(Type *RetTy, Value *PersonalityFn,
181 unsigned NumReservedValues, const Twine &NameStr,
182 Instruction *InsertBefore)
183 : Instruction(RetTy, Instruction::LandingPad, 0, 0, InsertBefore) {
184 init(PersonalityFn, 1 + NumReservedValues, NameStr);
187 LandingPadInst::LandingPadInst(Type *RetTy, Value *PersonalityFn,
188 unsigned NumReservedValues, const Twine &NameStr,
189 BasicBlock *InsertAtEnd)
190 : Instruction(RetTy, Instruction::LandingPad, 0, 0, InsertAtEnd) {
191 init(PersonalityFn, 1 + NumReservedValues, NameStr);
194 LandingPadInst::LandingPadInst(const LandingPadInst &LP)
195 : Instruction(LP.getType(), Instruction::LandingPad,
196 allocHungoffUses(LP.getNumOperands()), LP.getNumOperands()),
197 ReservedSpace(LP.getNumOperands()) {
198 Use *OL = OperandList, *InOL = LP.OperandList;
199 for (unsigned I = 0, E = ReservedSpace; I != E; ++I)
202 setCleanup(LP.isCleanup());
205 LandingPadInst::~LandingPadInst() {
209 LandingPadInst *LandingPadInst::Create(Type *RetTy, Value *PersonalityFn,
210 unsigned NumReservedClauses,
211 const Twine &NameStr,
212 Instruction *InsertBefore) {
213 return new LandingPadInst(RetTy, PersonalityFn, NumReservedClauses, NameStr,
217 LandingPadInst *LandingPadInst::Create(Type *RetTy, Value *PersonalityFn,
218 unsigned NumReservedClauses,
219 const Twine &NameStr,
220 BasicBlock *InsertAtEnd) {
221 return new LandingPadInst(RetTy, PersonalityFn, NumReservedClauses, NameStr,
225 void LandingPadInst::init(Value *PersFn, unsigned NumReservedValues,
226 const Twine &NameStr) {
227 ReservedSpace = NumReservedValues;
229 OperandList = allocHungoffUses(ReservedSpace);
230 OperandList[0] = PersFn;
235 /// growOperands - grow operands - This grows the operand list in response to a
236 /// push_back style of operation. This grows the number of ops by 2 times.
237 void LandingPadInst::growOperands(unsigned Size) {
238 unsigned e = getNumOperands();
239 if (ReservedSpace >= e + Size) return;
240 ReservedSpace = (e + Size / 2) * 2;
242 Use *NewOps = allocHungoffUses(ReservedSpace);
243 Use *OldOps = OperandList;
244 for (unsigned i = 0; i != e; ++i)
245 NewOps[i] = OldOps[i];
247 OperandList = NewOps;
248 Use::zap(OldOps, OldOps + e, true);
251 void LandingPadInst::addClause(Value *Val) {
252 unsigned OpNo = getNumOperands();
254 assert(OpNo < ReservedSpace && "Growing didn't work!");
256 OperandList[OpNo] = Val;
259 //===----------------------------------------------------------------------===//
260 // CallInst Implementation
261 //===----------------------------------------------------------------------===//
263 CallInst::~CallInst() {
266 void CallInst::init(Value *Func, ArrayRef<Value *> Args, const Twine &NameStr) {
267 assert(NumOperands == Args.size() + 1 && "NumOperands not set up?");
272 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
274 assert((Args.size() == FTy->getNumParams() ||
275 (FTy->isVarArg() && Args.size() > FTy->getNumParams())) &&
276 "Calling a function with bad signature!");
278 for (unsigned i = 0; i != Args.size(); ++i)
279 assert((i >= FTy->getNumParams() ||
280 FTy->getParamType(i) == Args[i]->getType()) &&
281 "Calling a function with a bad signature!");
284 std::copy(Args.begin(), Args.end(), op_begin());
288 void CallInst::init(Value *Func, const Twine &NameStr) {
289 assert(NumOperands == 1 && "NumOperands not set up?");
294 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
296 assert(FTy->getNumParams() == 0 && "Calling a function with bad signature");
302 CallInst::CallInst(Value *Func, const Twine &Name,
303 Instruction *InsertBefore)
304 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
305 ->getElementType())->getReturnType(),
307 OperandTraits<CallInst>::op_end(this) - 1,
312 CallInst::CallInst(Value *Func, const Twine &Name,
313 BasicBlock *InsertAtEnd)
314 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
315 ->getElementType())->getReturnType(),
317 OperandTraits<CallInst>::op_end(this) - 1,
322 CallInst::CallInst(const CallInst &CI)
323 : Instruction(CI.getType(), Instruction::Call,
324 OperandTraits<CallInst>::op_end(this) - CI.getNumOperands(),
325 CI.getNumOperands()) {
326 setAttributes(CI.getAttributes());
327 setTailCall(CI.isTailCall());
328 setCallingConv(CI.getCallingConv());
330 std::copy(CI.op_begin(), CI.op_end(), op_begin());
331 SubclassOptionalData = CI.SubclassOptionalData;
334 void CallInst::addAttribute(unsigned i, Attribute attr) {
335 AttributeSet PAL = getAttributes();
336 PAL = PAL.addAttr(getContext(), i, attr);
340 void CallInst::removeAttribute(unsigned i, Attribute attr) {
341 AttributeSet PAL = getAttributes();
342 PAL = PAL.removeAttr(getContext(), i, attr);
346 bool CallInst::hasFnAttr(Attribute::AttrKind A) const {
347 if (AttributeList.getParamAttributes(AttributeSet::FunctionIndex)
350 if (const Function *F = getCalledFunction())
351 return F->getAttributes().hasAttribute(AttributeSet::FunctionIndex, A);
355 bool CallInst::paramHasAttr(unsigned i, Attribute::AttrKind A) const {
356 if (AttributeList.getParamAttributes(i).hasAttribute(A))
358 if (const Function *F = getCalledFunction())
359 return F->getAttributes().hasAttribute(i, A);
363 /// IsConstantOne - Return true only if val is constant int 1
364 static bool IsConstantOne(Value *val) {
365 assert(val && "IsConstantOne does not work with NULL val");
366 return isa<ConstantInt>(val) && cast<ConstantInt>(val)->isOne();
369 static Instruction *createMalloc(Instruction *InsertBefore,
370 BasicBlock *InsertAtEnd, Type *IntPtrTy,
371 Type *AllocTy, Value *AllocSize,
372 Value *ArraySize, Function *MallocF,
374 assert(((!InsertBefore && InsertAtEnd) || (InsertBefore && !InsertAtEnd)) &&
375 "createMalloc needs either InsertBefore or InsertAtEnd");
377 // malloc(type) becomes:
378 // bitcast (i8* malloc(typeSize)) to type*
379 // malloc(type, arraySize) becomes:
380 // bitcast (i8 *malloc(typeSize*arraySize)) to type*
382 ArraySize = ConstantInt::get(IntPtrTy, 1);
383 else if (ArraySize->getType() != IntPtrTy) {
385 ArraySize = CastInst::CreateIntegerCast(ArraySize, IntPtrTy, false,
388 ArraySize = CastInst::CreateIntegerCast(ArraySize, IntPtrTy, false,
392 if (!IsConstantOne(ArraySize)) {
393 if (IsConstantOne(AllocSize)) {
394 AllocSize = ArraySize; // Operand * 1 = Operand
395 } else if (Constant *CO = dyn_cast<Constant>(ArraySize)) {
396 Constant *Scale = ConstantExpr::getIntegerCast(CO, IntPtrTy,
398 // Malloc arg is constant product of type size and array size
399 AllocSize = ConstantExpr::getMul(Scale, cast<Constant>(AllocSize));
401 // Multiply type size by the array size...
403 AllocSize = BinaryOperator::CreateMul(ArraySize, AllocSize,
404 "mallocsize", InsertBefore);
406 AllocSize = BinaryOperator::CreateMul(ArraySize, AllocSize,
407 "mallocsize", InsertAtEnd);
411 assert(AllocSize->getType() == IntPtrTy && "malloc arg is wrong size");
412 // Create the call to Malloc.
413 BasicBlock* BB = InsertBefore ? InsertBefore->getParent() : InsertAtEnd;
414 Module* M = BB->getParent()->getParent();
415 Type *BPTy = Type::getInt8PtrTy(BB->getContext());
416 Value *MallocFunc = MallocF;
418 // prototype malloc as "void *malloc(size_t)"
419 MallocFunc = M->getOrInsertFunction("malloc", BPTy, IntPtrTy, NULL);
420 PointerType *AllocPtrType = PointerType::getUnqual(AllocTy);
421 CallInst *MCall = NULL;
422 Instruction *Result = NULL;
424 MCall = CallInst::Create(MallocFunc, AllocSize, "malloccall", InsertBefore);
426 if (Result->getType() != AllocPtrType)
427 // Create a cast instruction to convert to the right type...
428 Result = new BitCastInst(MCall, AllocPtrType, Name, InsertBefore);
430 MCall = CallInst::Create(MallocFunc, AllocSize, "malloccall");
432 if (Result->getType() != AllocPtrType) {
433 InsertAtEnd->getInstList().push_back(MCall);
434 // Create a cast instruction to convert to the right type...
435 Result = new BitCastInst(MCall, AllocPtrType, Name);
438 MCall->setTailCall();
439 if (Function *F = dyn_cast<Function>(MallocFunc)) {
440 MCall->setCallingConv(F->getCallingConv());
441 if (!F->doesNotAlias(0)) F->setDoesNotAlias(0);
443 assert(!MCall->getType()->isVoidTy() && "Malloc has void return type");
448 /// CreateMalloc - Generate the IR for a call to malloc:
449 /// 1. Compute the malloc call's argument as the specified type's size,
450 /// possibly multiplied by the array size if the array size is not
452 /// 2. Call malloc with that argument.
453 /// 3. Bitcast the result of the malloc call to the specified type.
454 Instruction *CallInst::CreateMalloc(Instruction *InsertBefore,
455 Type *IntPtrTy, Type *AllocTy,
456 Value *AllocSize, Value *ArraySize,
459 return createMalloc(InsertBefore, NULL, IntPtrTy, AllocTy, AllocSize,
460 ArraySize, MallocF, Name);
463 /// CreateMalloc - Generate the IR for a call to malloc:
464 /// 1. Compute the malloc call's argument as the specified type's size,
465 /// possibly multiplied by the array size if the array size is not
467 /// 2. Call malloc with that argument.
468 /// 3. Bitcast the result of the malloc call to the specified type.
469 /// Note: This function does not add the bitcast to the basic block, that is the
470 /// responsibility of the caller.
471 Instruction *CallInst::CreateMalloc(BasicBlock *InsertAtEnd,
472 Type *IntPtrTy, Type *AllocTy,
473 Value *AllocSize, Value *ArraySize,
474 Function *MallocF, const Twine &Name) {
475 return createMalloc(NULL, InsertAtEnd, IntPtrTy, AllocTy, AllocSize,
476 ArraySize, MallocF, Name);
479 static Instruction* createFree(Value* Source, Instruction *InsertBefore,
480 BasicBlock *InsertAtEnd) {
481 assert(((!InsertBefore && InsertAtEnd) || (InsertBefore && !InsertAtEnd)) &&
482 "createFree needs either InsertBefore or InsertAtEnd");
483 assert(Source->getType()->isPointerTy() &&
484 "Can not free something of nonpointer type!");
486 BasicBlock* BB = InsertBefore ? InsertBefore->getParent() : InsertAtEnd;
487 Module* M = BB->getParent()->getParent();
489 Type *VoidTy = Type::getVoidTy(M->getContext());
490 Type *IntPtrTy = Type::getInt8PtrTy(M->getContext());
491 // prototype free as "void free(void*)"
492 Value *FreeFunc = M->getOrInsertFunction("free", VoidTy, IntPtrTy, NULL);
493 CallInst* Result = NULL;
494 Value *PtrCast = Source;
496 if (Source->getType() != IntPtrTy)
497 PtrCast = new BitCastInst(Source, IntPtrTy, "", InsertBefore);
498 Result = CallInst::Create(FreeFunc, PtrCast, "", InsertBefore);
500 if (Source->getType() != IntPtrTy)
501 PtrCast = new BitCastInst(Source, IntPtrTy, "", InsertAtEnd);
502 Result = CallInst::Create(FreeFunc, PtrCast, "");
504 Result->setTailCall();
505 if (Function *F = dyn_cast<Function>(FreeFunc))
506 Result->setCallingConv(F->getCallingConv());
511 /// CreateFree - Generate the IR for a call to the builtin free function.
512 Instruction * CallInst::CreateFree(Value* Source, Instruction *InsertBefore) {
513 return createFree(Source, InsertBefore, NULL);
516 /// CreateFree - Generate the IR for a call to the builtin free function.
517 /// Note: This function does not add the call to the basic block, that is the
518 /// responsibility of the caller.
519 Instruction* CallInst::CreateFree(Value* Source, BasicBlock *InsertAtEnd) {
520 Instruction* FreeCall = createFree(Source, NULL, InsertAtEnd);
521 assert(FreeCall && "CreateFree did not create a CallInst");
525 //===----------------------------------------------------------------------===//
526 // InvokeInst Implementation
527 //===----------------------------------------------------------------------===//
529 void InvokeInst::init(Value *Fn, BasicBlock *IfNormal, BasicBlock *IfException,
530 ArrayRef<Value *> Args, const Twine &NameStr) {
531 assert(NumOperands == 3 + Args.size() && "NumOperands not set up?");
534 Op<-1>() = IfException;
538 cast<FunctionType>(cast<PointerType>(Fn->getType())->getElementType());
540 assert(((Args.size() == FTy->getNumParams()) ||
541 (FTy->isVarArg() && Args.size() > FTy->getNumParams())) &&
542 "Invoking a function with bad signature");
544 for (unsigned i = 0, e = Args.size(); i != e; i++)
545 assert((i >= FTy->getNumParams() ||
546 FTy->getParamType(i) == Args[i]->getType()) &&
547 "Invoking a function with a bad signature!");
550 std::copy(Args.begin(), Args.end(), op_begin());
554 InvokeInst::InvokeInst(const InvokeInst &II)
555 : TerminatorInst(II.getType(), Instruction::Invoke,
556 OperandTraits<InvokeInst>::op_end(this)
557 - II.getNumOperands(),
558 II.getNumOperands()) {
559 setAttributes(II.getAttributes());
560 setCallingConv(II.getCallingConv());
561 std::copy(II.op_begin(), II.op_end(), op_begin());
562 SubclassOptionalData = II.SubclassOptionalData;
565 BasicBlock *InvokeInst::getSuccessorV(unsigned idx) const {
566 return getSuccessor(idx);
568 unsigned InvokeInst::getNumSuccessorsV() const {
569 return getNumSuccessors();
571 void InvokeInst::setSuccessorV(unsigned idx, BasicBlock *B) {
572 return setSuccessor(idx, B);
575 bool InvokeInst::hasFnAttr(Attribute::AttrKind A) const {
576 if (AttributeList.getParamAttributes(AttributeSet::FunctionIndex).
579 if (const Function *F = getCalledFunction())
580 return F->getAttributes().hasAttribute(AttributeSet::FunctionIndex, A);
584 bool InvokeInst::paramHasAttr(unsigned i, Attribute::AttrKind A) const {
585 if (AttributeList.getParamAttributes(i).hasAttribute(A))
587 if (const Function *F = getCalledFunction())
588 return F->getAttributes().hasAttribute(i, A);
592 void InvokeInst::addAttribute(unsigned i, Attribute attr) {
593 AttributeSet PAL = getAttributes();
594 PAL = PAL.addAttr(getContext(), i, attr);
598 void InvokeInst::removeAttribute(unsigned i, Attribute attr) {
599 AttributeSet PAL = getAttributes();
600 PAL = PAL.removeAttr(getContext(), i, attr);
604 LandingPadInst *InvokeInst::getLandingPadInst() const {
605 return cast<LandingPadInst>(getUnwindDest()->getFirstNonPHI());
608 //===----------------------------------------------------------------------===//
609 // ReturnInst Implementation
610 //===----------------------------------------------------------------------===//
612 ReturnInst::ReturnInst(const ReturnInst &RI)
613 : TerminatorInst(Type::getVoidTy(RI.getContext()), Instruction::Ret,
614 OperandTraits<ReturnInst>::op_end(this) -
616 RI.getNumOperands()) {
617 if (RI.getNumOperands())
618 Op<0>() = RI.Op<0>();
619 SubclassOptionalData = RI.SubclassOptionalData;
622 ReturnInst::ReturnInst(LLVMContext &C, Value *retVal, Instruction *InsertBefore)
623 : TerminatorInst(Type::getVoidTy(C), Instruction::Ret,
624 OperandTraits<ReturnInst>::op_end(this) - !!retVal, !!retVal,
629 ReturnInst::ReturnInst(LLVMContext &C, Value *retVal, BasicBlock *InsertAtEnd)
630 : TerminatorInst(Type::getVoidTy(C), Instruction::Ret,
631 OperandTraits<ReturnInst>::op_end(this) - !!retVal, !!retVal,
636 ReturnInst::ReturnInst(LLVMContext &Context, BasicBlock *InsertAtEnd)
637 : TerminatorInst(Type::getVoidTy(Context), Instruction::Ret,
638 OperandTraits<ReturnInst>::op_end(this), 0, InsertAtEnd) {
641 unsigned ReturnInst::getNumSuccessorsV() const {
642 return getNumSuccessors();
645 /// Out-of-line ReturnInst method, put here so the C++ compiler can choose to
646 /// emit the vtable for the class in this translation unit.
647 void ReturnInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
648 llvm_unreachable("ReturnInst has no successors!");
651 BasicBlock *ReturnInst::getSuccessorV(unsigned idx) const {
652 llvm_unreachable("ReturnInst has no successors!");
655 ReturnInst::~ReturnInst() {
658 //===----------------------------------------------------------------------===//
659 // ResumeInst Implementation
660 //===----------------------------------------------------------------------===//
662 ResumeInst::ResumeInst(const ResumeInst &RI)
663 : TerminatorInst(Type::getVoidTy(RI.getContext()), Instruction::Resume,
664 OperandTraits<ResumeInst>::op_begin(this), 1) {
665 Op<0>() = RI.Op<0>();
668 ResumeInst::ResumeInst(Value *Exn, Instruction *InsertBefore)
669 : TerminatorInst(Type::getVoidTy(Exn->getContext()), Instruction::Resume,
670 OperandTraits<ResumeInst>::op_begin(this), 1, InsertBefore) {
674 ResumeInst::ResumeInst(Value *Exn, BasicBlock *InsertAtEnd)
675 : TerminatorInst(Type::getVoidTy(Exn->getContext()), Instruction::Resume,
676 OperandTraits<ResumeInst>::op_begin(this), 1, InsertAtEnd) {
680 unsigned ResumeInst::getNumSuccessorsV() const {
681 return getNumSuccessors();
684 void ResumeInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
685 llvm_unreachable("ResumeInst has no successors!");
688 BasicBlock *ResumeInst::getSuccessorV(unsigned idx) const {
689 llvm_unreachable("ResumeInst has no successors!");
692 //===----------------------------------------------------------------------===//
693 // UnreachableInst Implementation
694 //===----------------------------------------------------------------------===//
696 UnreachableInst::UnreachableInst(LLVMContext &Context,
697 Instruction *InsertBefore)
698 : TerminatorInst(Type::getVoidTy(Context), Instruction::Unreachable,
699 0, 0, InsertBefore) {
701 UnreachableInst::UnreachableInst(LLVMContext &Context, BasicBlock *InsertAtEnd)
702 : TerminatorInst(Type::getVoidTy(Context), Instruction::Unreachable,
706 unsigned UnreachableInst::getNumSuccessorsV() const {
707 return getNumSuccessors();
710 void UnreachableInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
711 llvm_unreachable("UnreachableInst has no successors!");
714 BasicBlock *UnreachableInst::getSuccessorV(unsigned idx) const {
715 llvm_unreachable("UnreachableInst has no successors!");
718 //===----------------------------------------------------------------------===//
719 // BranchInst Implementation
720 //===----------------------------------------------------------------------===//
722 void BranchInst::AssertOK() {
724 assert(getCondition()->getType()->isIntegerTy(1) &&
725 "May only branch on boolean predicates!");
728 BranchInst::BranchInst(BasicBlock *IfTrue, Instruction *InsertBefore)
729 : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
730 OperandTraits<BranchInst>::op_end(this) - 1,
732 assert(IfTrue != 0 && "Branch destination may not be null!");
735 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
736 Instruction *InsertBefore)
737 : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
738 OperandTraits<BranchInst>::op_end(this) - 3,
748 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *InsertAtEnd)
749 : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
750 OperandTraits<BranchInst>::op_end(this) - 1,
752 assert(IfTrue != 0 && "Branch destination may not be null!");
756 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
757 BasicBlock *InsertAtEnd)
758 : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
759 OperandTraits<BranchInst>::op_end(this) - 3,
770 BranchInst::BranchInst(const BranchInst &BI) :
771 TerminatorInst(Type::getVoidTy(BI.getContext()), Instruction::Br,
772 OperandTraits<BranchInst>::op_end(this) - BI.getNumOperands(),
773 BI.getNumOperands()) {
774 Op<-1>() = BI.Op<-1>();
775 if (BI.getNumOperands() != 1) {
776 assert(BI.getNumOperands() == 3 && "BR can have 1 or 3 operands!");
777 Op<-3>() = BI.Op<-3>();
778 Op<-2>() = BI.Op<-2>();
780 SubclassOptionalData = BI.SubclassOptionalData;
783 void BranchInst::swapSuccessors() {
784 assert(isConditional() &&
785 "Cannot swap successors of an unconditional branch");
786 Op<-1>().swap(Op<-2>());
788 // Update profile metadata if present and it matches our structural
790 MDNode *ProfileData = getMetadata(LLVMContext::MD_prof);
791 if (!ProfileData || ProfileData->getNumOperands() != 3)
794 // The first operand is the name. Fetch them backwards and build a new one.
796 ProfileData->getOperand(0),
797 ProfileData->getOperand(2),
798 ProfileData->getOperand(1)
800 setMetadata(LLVMContext::MD_prof,
801 MDNode::get(ProfileData->getContext(), Ops));
804 BasicBlock *BranchInst::getSuccessorV(unsigned idx) const {
805 return getSuccessor(idx);
807 unsigned BranchInst::getNumSuccessorsV() const {
808 return getNumSuccessors();
810 void BranchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
811 setSuccessor(idx, B);
815 //===----------------------------------------------------------------------===//
816 // AllocaInst Implementation
817 //===----------------------------------------------------------------------===//
819 static Value *getAISize(LLVMContext &Context, Value *Amt) {
821 Amt = ConstantInt::get(Type::getInt32Ty(Context), 1);
823 assert(!isa<BasicBlock>(Amt) &&
824 "Passed basic block into allocation size parameter! Use other ctor");
825 assert(Amt->getType()->isIntegerTy() &&
826 "Allocation array size is not an integer!");
831 AllocaInst::AllocaInst(Type *Ty, Value *ArraySize,
832 const Twine &Name, Instruction *InsertBefore)
833 : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
834 getAISize(Ty->getContext(), ArraySize), InsertBefore) {
836 assert(!Ty->isVoidTy() && "Cannot allocate void!");
840 AllocaInst::AllocaInst(Type *Ty, Value *ArraySize,
841 const Twine &Name, BasicBlock *InsertAtEnd)
842 : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
843 getAISize(Ty->getContext(), ArraySize), InsertAtEnd) {
845 assert(!Ty->isVoidTy() && "Cannot allocate void!");
849 AllocaInst::AllocaInst(Type *Ty, const Twine &Name,
850 Instruction *InsertBefore)
851 : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
852 getAISize(Ty->getContext(), 0), InsertBefore) {
854 assert(!Ty->isVoidTy() && "Cannot allocate void!");
858 AllocaInst::AllocaInst(Type *Ty, const Twine &Name,
859 BasicBlock *InsertAtEnd)
860 : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
861 getAISize(Ty->getContext(), 0), InsertAtEnd) {
863 assert(!Ty->isVoidTy() && "Cannot allocate void!");
867 AllocaInst::AllocaInst(Type *Ty, Value *ArraySize, unsigned Align,
868 const Twine &Name, Instruction *InsertBefore)
869 : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
870 getAISize(Ty->getContext(), ArraySize), InsertBefore) {
872 assert(!Ty->isVoidTy() && "Cannot allocate void!");
876 AllocaInst::AllocaInst(Type *Ty, Value *ArraySize, unsigned Align,
877 const Twine &Name, BasicBlock *InsertAtEnd)
878 : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
879 getAISize(Ty->getContext(), ArraySize), InsertAtEnd) {
881 assert(!Ty->isVoidTy() && "Cannot allocate void!");
885 // Out of line virtual method, so the vtable, etc has a home.
886 AllocaInst::~AllocaInst() {
889 void AllocaInst::setAlignment(unsigned Align) {
890 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
891 assert(Align <= MaximumAlignment &&
892 "Alignment is greater than MaximumAlignment!");
893 setInstructionSubclassData(Log2_32(Align) + 1);
894 assert(getAlignment() == Align && "Alignment representation error!");
897 bool AllocaInst::isArrayAllocation() const {
898 if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(0)))
903 Type *AllocaInst::getAllocatedType() const {
904 return getType()->getElementType();
907 /// isStaticAlloca - Return true if this alloca is in the entry block of the
908 /// function and is a constant size. If so, the code generator will fold it
909 /// into the prolog/epilog code, so it is basically free.
910 bool AllocaInst::isStaticAlloca() const {
911 // Must be constant size.
912 if (!isa<ConstantInt>(getArraySize())) return false;
914 // Must be in the entry block.
915 const BasicBlock *Parent = getParent();
916 return Parent == &Parent->getParent()->front();
919 //===----------------------------------------------------------------------===//
920 // LoadInst Implementation
921 //===----------------------------------------------------------------------===//
923 void LoadInst::AssertOK() {
924 assert(getOperand(0)->getType()->isPointerTy() &&
925 "Ptr must have pointer type.");
926 assert(!(isAtomic() && getAlignment() == 0) &&
927 "Alignment required for atomic load");
930 LoadInst::LoadInst(Value *Ptr, const Twine &Name, Instruction *InsertBef)
931 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
932 Load, Ptr, InsertBef) {
935 setAtomic(NotAtomic);
940 LoadInst::LoadInst(Value *Ptr, const Twine &Name, BasicBlock *InsertAE)
941 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
942 Load, Ptr, InsertAE) {
945 setAtomic(NotAtomic);
950 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
951 Instruction *InsertBef)
952 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
953 Load, Ptr, InsertBef) {
954 setVolatile(isVolatile);
956 setAtomic(NotAtomic);
961 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
962 BasicBlock *InsertAE)
963 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
964 Load, Ptr, InsertAE) {
965 setVolatile(isVolatile);
967 setAtomic(NotAtomic);
972 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
973 unsigned Align, Instruction *InsertBef)
974 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
975 Load, Ptr, InsertBef) {
976 setVolatile(isVolatile);
978 setAtomic(NotAtomic);
983 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
984 unsigned Align, BasicBlock *InsertAE)
985 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
986 Load, Ptr, InsertAE) {
987 setVolatile(isVolatile);
989 setAtomic(NotAtomic);
994 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
995 unsigned Align, AtomicOrdering Order,
996 SynchronizationScope SynchScope,
997 Instruction *InsertBef)
998 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
999 Load, Ptr, InsertBef) {
1000 setVolatile(isVolatile);
1001 setAlignment(Align);
1002 setAtomic(Order, SynchScope);
1007 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
1008 unsigned Align, AtomicOrdering Order,
1009 SynchronizationScope SynchScope,
1010 BasicBlock *InsertAE)
1011 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1012 Load, Ptr, InsertAE) {
1013 setVolatile(isVolatile);
1014 setAlignment(Align);
1015 setAtomic(Order, SynchScope);
1020 LoadInst::LoadInst(Value *Ptr, const char *Name, Instruction *InsertBef)
1021 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1022 Load, Ptr, InsertBef) {
1025 setAtomic(NotAtomic);
1027 if (Name && Name[0]) setName(Name);
1030 LoadInst::LoadInst(Value *Ptr, const char *Name, BasicBlock *InsertAE)
1031 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1032 Load, Ptr, InsertAE) {
1035 setAtomic(NotAtomic);
1037 if (Name && Name[0]) setName(Name);
1040 LoadInst::LoadInst(Value *Ptr, const char *Name, bool isVolatile,
1041 Instruction *InsertBef)
1042 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1043 Load, Ptr, InsertBef) {
1044 setVolatile(isVolatile);
1046 setAtomic(NotAtomic);
1048 if (Name && Name[0]) setName(Name);
1051 LoadInst::LoadInst(Value *Ptr, const char *Name, bool isVolatile,
1052 BasicBlock *InsertAE)
1053 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1054 Load, Ptr, InsertAE) {
1055 setVolatile(isVolatile);
1057 setAtomic(NotAtomic);
1059 if (Name && Name[0]) setName(Name);
1062 void LoadInst::setAlignment(unsigned Align) {
1063 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
1064 assert(Align <= MaximumAlignment &&
1065 "Alignment is greater than MaximumAlignment!");
1066 setInstructionSubclassData((getSubclassDataFromInstruction() & ~(31 << 1)) |
1067 ((Log2_32(Align)+1)<<1));
1068 assert(getAlignment() == Align && "Alignment representation error!");
1071 //===----------------------------------------------------------------------===//
1072 // StoreInst Implementation
1073 //===----------------------------------------------------------------------===//
1075 void StoreInst::AssertOK() {
1076 assert(getOperand(0) && getOperand(1) && "Both operands must be non-null!");
1077 assert(getOperand(1)->getType()->isPointerTy() &&
1078 "Ptr must have pointer type!");
1079 assert(getOperand(0)->getType() ==
1080 cast<PointerType>(getOperand(1)->getType())->getElementType()
1081 && "Ptr must be a pointer to Val type!");
1082 assert(!(isAtomic() && getAlignment() == 0) &&
1083 "Alignment required for atomic load");
1087 StoreInst::StoreInst(Value *val, Value *addr, Instruction *InsertBefore)
1088 : Instruction(Type::getVoidTy(val->getContext()), Store,
1089 OperandTraits<StoreInst>::op_begin(this),
1090 OperandTraits<StoreInst>::operands(this),
1096 setAtomic(NotAtomic);
1100 StoreInst::StoreInst(Value *val, Value *addr, BasicBlock *InsertAtEnd)
1101 : Instruction(Type::getVoidTy(val->getContext()), Store,
1102 OperandTraits<StoreInst>::op_begin(this),
1103 OperandTraits<StoreInst>::operands(this),
1109 setAtomic(NotAtomic);
1113 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1114 Instruction *InsertBefore)
1115 : Instruction(Type::getVoidTy(val->getContext()), Store,
1116 OperandTraits<StoreInst>::op_begin(this),
1117 OperandTraits<StoreInst>::operands(this),
1121 setVolatile(isVolatile);
1123 setAtomic(NotAtomic);
1127 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1128 unsigned Align, Instruction *InsertBefore)
1129 : Instruction(Type::getVoidTy(val->getContext()), Store,
1130 OperandTraits<StoreInst>::op_begin(this),
1131 OperandTraits<StoreInst>::operands(this),
1135 setVolatile(isVolatile);
1136 setAlignment(Align);
1137 setAtomic(NotAtomic);
1141 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1142 unsigned Align, AtomicOrdering Order,
1143 SynchronizationScope SynchScope,
1144 Instruction *InsertBefore)
1145 : Instruction(Type::getVoidTy(val->getContext()), Store,
1146 OperandTraits<StoreInst>::op_begin(this),
1147 OperandTraits<StoreInst>::operands(this),
1151 setVolatile(isVolatile);
1152 setAlignment(Align);
1153 setAtomic(Order, SynchScope);
1157 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1158 BasicBlock *InsertAtEnd)
1159 : Instruction(Type::getVoidTy(val->getContext()), Store,
1160 OperandTraits<StoreInst>::op_begin(this),
1161 OperandTraits<StoreInst>::operands(this),
1165 setVolatile(isVolatile);
1167 setAtomic(NotAtomic);
1171 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1172 unsigned Align, BasicBlock *InsertAtEnd)
1173 : Instruction(Type::getVoidTy(val->getContext()), Store,
1174 OperandTraits<StoreInst>::op_begin(this),
1175 OperandTraits<StoreInst>::operands(this),
1179 setVolatile(isVolatile);
1180 setAlignment(Align);
1181 setAtomic(NotAtomic);
1185 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1186 unsigned Align, AtomicOrdering Order,
1187 SynchronizationScope SynchScope,
1188 BasicBlock *InsertAtEnd)
1189 : Instruction(Type::getVoidTy(val->getContext()), Store,
1190 OperandTraits<StoreInst>::op_begin(this),
1191 OperandTraits<StoreInst>::operands(this),
1195 setVolatile(isVolatile);
1196 setAlignment(Align);
1197 setAtomic(Order, SynchScope);
1201 void StoreInst::setAlignment(unsigned Align) {
1202 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
1203 assert(Align <= MaximumAlignment &&
1204 "Alignment is greater than MaximumAlignment!");
1205 setInstructionSubclassData((getSubclassDataFromInstruction() & ~(31 << 1)) |
1206 ((Log2_32(Align)+1) << 1));
1207 assert(getAlignment() == Align && "Alignment representation error!");
1210 //===----------------------------------------------------------------------===//
1211 // AtomicCmpXchgInst Implementation
1212 //===----------------------------------------------------------------------===//
1214 void AtomicCmpXchgInst::Init(Value *Ptr, Value *Cmp, Value *NewVal,
1215 AtomicOrdering Ordering,
1216 SynchronizationScope SynchScope) {
1220 setOrdering(Ordering);
1221 setSynchScope(SynchScope);
1223 assert(getOperand(0) && getOperand(1) && getOperand(2) &&
1224 "All operands must be non-null!");
1225 assert(getOperand(0)->getType()->isPointerTy() &&
1226 "Ptr must have pointer type!");
1227 assert(getOperand(1)->getType() ==
1228 cast<PointerType>(getOperand(0)->getType())->getElementType()
1229 && "Ptr must be a pointer to Cmp type!");
1230 assert(getOperand(2)->getType() ==
1231 cast<PointerType>(getOperand(0)->getType())->getElementType()
1232 && "Ptr must be a pointer to NewVal type!");
1233 assert(Ordering != NotAtomic &&
1234 "AtomicCmpXchg instructions must be atomic!");
1237 AtomicCmpXchgInst::AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal,
1238 AtomicOrdering Ordering,
1239 SynchronizationScope SynchScope,
1240 Instruction *InsertBefore)
1241 : Instruction(Cmp->getType(), AtomicCmpXchg,
1242 OperandTraits<AtomicCmpXchgInst>::op_begin(this),
1243 OperandTraits<AtomicCmpXchgInst>::operands(this),
1245 Init(Ptr, Cmp, NewVal, Ordering, SynchScope);
1248 AtomicCmpXchgInst::AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal,
1249 AtomicOrdering Ordering,
1250 SynchronizationScope SynchScope,
1251 BasicBlock *InsertAtEnd)
1252 : Instruction(Cmp->getType(), AtomicCmpXchg,
1253 OperandTraits<AtomicCmpXchgInst>::op_begin(this),
1254 OperandTraits<AtomicCmpXchgInst>::operands(this),
1256 Init(Ptr, Cmp, NewVal, Ordering, SynchScope);
1259 //===----------------------------------------------------------------------===//
1260 // AtomicRMWInst Implementation
1261 //===----------------------------------------------------------------------===//
1263 void AtomicRMWInst::Init(BinOp Operation, Value *Ptr, Value *Val,
1264 AtomicOrdering Ordering,
1265 SynchronizationScope SynchScope) {
1268 setOperation(Operation);
1269 setOrdering(Ordering);
1270 setSynchScope(SynchScope);
1272 assert(getOperand(0) && getOperand(1) &&
1273 "All operands must be non-null!");
1274 assert(getOperand(0)->getType()->isPointerTy() &&
1275 "Ptr must have pointer type!");
1276 assert(getOperand(1)->getType() ==
1277 cast<PointerType>(getOperand(0)->getType())->getElementType()
1278 && "Ptr must be a pointer to Val type!");
1279 assert(Ordering != NotAtomic &&
1280 "AtomicRMW instructions must be atomic!");
1283 AtomicRMWInst::AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val,
1284 AtomicOrdering Ordering,
1285 SynchronizationScope SynchScope,
1286 Instruction *InsertBefore)
1287 : Instruction(Val->getType(), AtomicRMW,
1288 OperandTraits<AtomicRMWInst>::op_begin(this),
1289 OperandTraits<AtomicRMWInst>::operands(this),
1291 Init(Operation, Ptr, Val, Ordering, SynchScope);
1294 AtomicRMWInst::AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val,
1295 AtomicOrdering Ordering,
1296 SynchronizationScope SynchScope,
1297 BasicBlock *InsertAtEnd)
1298 : Instruction(Val->getType(), AtomicRMW,
1299 OperandTraits<AtomicRMWInst>::op_begin(this),
1300 OperandTraits<AtomicRMWInst>::operands(this),
1302 Init(Operation, Ptr, Val, Ordering, SynchScope);
1305 //===----------------------------------------------------------------------===//
1306 // FenceInst Implementation
1307 //===----------------------------------------------------------------------===//
1309 FenceInst::FenceInst(LLVMContext &C, AtomicOrdering Ordering,
1310 SynchronizationScope SynchScope,
1311 Instruction *InsertBefore)
1312 : Instruction(Type::getVoidTy(C), Fence, 0, 0, InsertBefore) {
1313 setOrdering(Ordering);
1314 setSynchScope(SynchScope);
1317 FenceInst::FenceInst(LLVMContext &C, AtomicOrdering Ordering,
1318 SynchronizationScope SynchScope,
1319 BasicBlock *InsertAtEnd)
1320 : Instruction(Type::getVoidTy(C), Fence, 0, 0, InsertAtEnd) {
1321 setOrdering(Ordering);
1322 setSynchScope(SynchScope);
1325 //===----------------------------------------------------------------------===//
1326 // GetElementPtrInst Implementation
1327 //===----------------------------------------------------------------------===//
1329 void GetElementPtrInst::init(Value *Ptr, ArrayRef<Value *> IdxList,
1330 const Twine &Name) {
1331 assert(NumOperands == 1 + IdxList.size() && "NumOperands not initialized?");
1332 OperandList[0] = Ptr;
1333 std::copy(IdxList.begin(), IdxList.end(), op_begin() + 1);
1337 GetElementPtrInst::GetElementPtrInst(const GetElementPtrInst &GEPI)
1338 : Instruction(GEPI.getType(), GetElementPtr,
1339 OperandTraits<GetElementPtrInst>::op_end(this)
1340 - GEPI.getNumOperands(),
1341 GEPI.getNumOperands()) {
1342 std::copy(GEPI.op_begin(), GEPI.op_end(), op_begin());
1343 SubclassOptionalData = GEPI.SubclassOptionalData;
1346 /// getIndexedType - Returns the type of the element that would be accessed with
1347 /// a gep instruction with the specified parameters.
1349 /// The Idxs pointer should point to a continuous piece of memory containing the
1350 /// indices, either as Value* or uint64_t.
1352 /// A null type is returned if the indices are invalid for the specified
1355 template <typename IndexTy>
1356 static Type *getIndexedTypeInternal(Type *Ptr, ArrayRef<IndexTy> IdxList) {
1357 PointerType *PTy = dyn_cast<PointerType>(Ptr->getScalarType());
1358 if (!PTy) return 0; // Type isn't a pointer type!
1359 Type *Agg = PTy->getElementType();
1361 // Handle the special case of the empty set index set, which is always valid.
1362 if (IdxList.empty())
1365 // If there is at least one index, the top level type must be sized, otherwise
1366 // it cannot be 'stepped over'.
1367 if (!Agg->isSized())
1370 unsigned CurIdx = 1;
1371 for (; CurIdx != IdxList.size(); ++CurIdx) {
1372 CompositeType *CT = dyn_cast<CompositeType>(Agg);
1373 if (!CT || CT->isPointerTy()) return 0;
1374 IndexTy Index = IdxList[CurIdx];
1375 if (!CT->indexValid(Index)) return 0;
1376 Agg = CT->getTypeAtIndex(Index);
1378 return CurIdx == IdxList.size() ? Agg : 0;
1381 Type *GetElementPtrInst::getIndexedType(Type *Ptr, ArrayRef<Value *> IdxList) {
1382 return getIndexedTypeInternal(Ptr, IdxList);
1385 Type *GetElementPtrInst::getIndexedType(Type *Ptr,
1386 ArrayRef<Constant *> IdxList) {
1387 return getIndexedTypeInternal(Ptr, IdxList);
1390 Type *GetElementPtrInst::getIndexedType(Type *Ptr, ArrayRef<uint64_t> IdxList) {
1391 return getIndexedTypeInternal(Ptr, IdxList);
1394 /// hasAllZeroIndices - Return true if all of the indices of this GEP are
1395 /// zeros. If so, the result pointer and the first operand have the same
1396 /// value, just potentially different types.
1397 bool GetElementPtrInst::hasAllZeroIndices() const {
1398 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1399 if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(i))) {
1400 if (!CI->isZero()) return false;
1408 /// hasAllConstantIndices - Return true if all of the indices of this GEP are
1409 /// constant integers. If so, the result pointer and the first operand have
1410 /// a constant offset between them.
1411 bool GetElementPtrInst::hasAllConstantIndices() const {
1412 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1413 if (!isa<ConstantInt>(getOperand(i)))
1419 void GetElementPtrInst::setIsInBounds(bool B) {
1420 cast<GEPOperator>(this)->setIsInBounds(B);
1423 bool GetElementPtrInst::isInBounds() const {
1424 return cast<GEPOperator>(this)->isInBounds();
1427 bool GetElementPtrInst::accumulateConstantOffset(const DataLayout &DL,
1428 APInt &Offset) const {
1429 // Delegate to the generic GEPOperator implementation.
1430 return cast<GEPOperator>(this)->accumulateConstantOffset(DL, Offset);
1433 //===----------------------------------------------------------------------===//
1434 // ExtractElementInst Implementation
1435 //===----------------------------------------------------------------------===//
1437 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
1439 Instruction *InsertBef)
1440 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1442 OperandTraits<ExtractElementInst>::op_begin(this),
1444 assert(isValidOperands(Val, Index) &&
1445 "Invalid extractelement instruction operands!");
1451 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
1453 BasicBlock *InsertAE)
1454 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1456 OperandTraits<ExtractElementInst>::op_begin(this),
1458 assert(isValidOperands(Val, Index) &&
1459 "Invalid extractelement instruction operands!");
1467 bool ExtractElementInst::isValidOperands(const Value *Val, const Value *Index) {
1468 if (!Val->getType()->isVectorTy() || !Index->getType()->isIntegerTy(32))
1474 //===----------------------------------------------------------------------===//
1475 // InsertElementInst Implementation
1476 //===----------------------------------------------------------------------===//
1478 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
1480 Instruction *InsertBef)
1481 : Instruction(Vec->getType(), InsertElement,
1482 OperandTraits<InsertElementInst>::op_begin(this),
1484 assert(isValidOperands(Vec, Elt, Index) &&
1485 "Invalid insertelement instruction operands!");
1492 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
1494 BasicBlock *InsertAE)
1495 : Instruction(Vec->getType(), InsertElement,
1496 OperandTraits<InsertElementInst>::op_begin(this),
1498 assert(isValidOperands(Vec, Elt, Index) &&
1499 "Invalid insertelement instruction operands!");
1507 bool InsertElementInst::isValidOperands(const Value *Vec, const Value *Elt,
1508 const Value *Index) {
1509 if (!Vec->getType()->isVectorTy())
1510 return false; // First operand of insertelement must be vector type.
1512 if (Elt->getType() != cast<VectorType>(Vec->getType())->getElementType())
1513 return false;// Second operand of insertelement must be vector element type.
1515 if (!Index->getType()->isIntegerTy(32))
1516 return false; // Third operand of insertelement must be i32.
1521 //===----------------------------------------------------------------------===//
1522 // ShuffleVectorInst Implementation
1523 //===----------------------------------------------------------------------===//
1525 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1527 Instruction *InsertBefore)
1528 : Instruction(VectorType::get(cast<VectorType>(V1->getType())->getElementType(),
1529 cast<VectorType>(Mask->getType())->getNumElements()),
1531 OperandTraits<ShuffleVectorInst>::op_begin(this),
1532 OperandTraits<ShuffleVectorInst>::operands(this),
1534 assert(isValidOperands(V1, V2, Mask) &&
1535 "Invalid shuffle vector instruction operands!");
1542 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1544 BasicBlock *InsertAtEnd)
1545 : Instruction(VectorType::get(cast<VectorType>(V1->getType())->getElementType(),
1546 cast<VectorType>(Mask->getType())->getNumElements()),
1548 OperandTraits<ShuffleVectorInst>::op_begin(this),
1549 OperandTraits<ShuffleVectorInst>::operands(this),
1551 assert(isValidOperands(V1, V2, Mask) &&
1552 "Invalid shuffle vector instruction operands!");
1560 bool ShuffleVectorInst::isValidOperands(const Value *V1, const Value *V2,
1561 const Value *Mask) {
1562 // V1 and V2 must be vectors of the same type.
1563 if (!V1->getType()->isVectorTy() || V1->getType() != V2->getType())
1566 // Mask must be vector of i32.
1567 VectorType *MaskTy = dyn_cast<VectorType>(Mask->getType());
1568 if (MaskTy == 0 || !MaskTy->getElementType()->isIntegerTy(32))
1571 // Check to see if Mask is valid.
1572 if (isa<UndefValue>(Mask) || isa<ConstantAggregateZero>(Mask))
1575 if (const ConstantVector *MV = dyn_cast<ConstantVector>(Mask)) {
1576 unsigned V1Size = cast<VectorType>(V1->getType())->getNumElements();
1577 for (unsigned i = 0, e = MV->getNumOperands(); i != e; ++i) {
1578 if (ConstantInt *CI = dyn_cast<ConstantInt>(MV->getOperand(i))) {
1579 if (CI->uge(V1Size*2))
1581 } else if (!isa<UndefValue>(MV->getOperand(i))) {
1588 if (const ConstantDataSequential *CDS =
1589 dyn_cast<ConstantDataSequential>(Mask)) {
1590 unsigned V1Size = cast<VectorType>(V1->getType())->getNumElements();
1591 for (unsigned i = 0, e = MaskTy->getNumElements(); i != e; ++i)
1592 if (CDS->getElementAsInteger(i) >= V1Size*2)
1597 // The bitcode reader can create a place holder for a forward reference
1598 // used as the shuffle mask. When this occurs, the shuffle mask will
1599 // fall into this case and fail. To avoid this error, do this bit of
1600 // ugliness to allow such a mask pass.
1601 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(Mask))
1602 if (CE->getOpcode() == Instruction::UserOp1)
1608 /// getMaskValue - Return the index from the shuffle mask for the specified
1609 /// output result. This is either -1 if the element is undef or a number less
1610 /// than 2*numelements.
1611 int ShuffleVectorInst::getMaskValue(Constant *Mask, unsigned i) {
1612 assert(i < Mask->getType()->getVectorNumElements() && "Index out of range");
1613 if (ConstantDataSequential *CDS =dyn_cast<ConstantDataSequential>(Mask))
1614 return CDS->getElementAsInteger(i);
1615 Constant *C = Mask->getAggregateElement(i);
1616 if (isa<UndefValue>(C))
1618 return cast<ConstantInt>(C)->getZExtValue();
1621 /// getShuffleMask - Return the full mask for this instruction, where each
1622 /// element is the element number and undef's are returned as -1.
1623 void ShuffleVectorInst::getShuffleMask(Constant *Mask,
1624 SmallVectorImpl<int> &Result) {
1625 unsigned NumElts = Mask->getType()->getVectorNumElements();
1627 if (ConstantDataSequential *CDS=dyn_cast<ConstantDataSequential>(Mask)) {
1628 for (unsigned i = 0; i != NumElts; ++i)
1629 Result.push_back(CDS->getElementAsInteger(i));
1632 for (unsigned i = 0; i != NumElts; ++i) {
1633 Constant *C = Mask->getAggregateElement(i);
1634 Result.push_back(isa<UndefValue>(C) ? -1 :
1635 cast<ConstantInt>(C)->getZExtValue());
1640 //===----------------------------------------------------------------------===//
1641 // InsertValueInst Class
1642 //===----------------------------------------------------------------------===//
1644 void InsertValueInst::init(Value *Agg, Value *Val, ArrayRef<unsigned> Idxs,
1645 const Twine &Name) {
1646 assert(NumOperands == 2 && "NumOperands not initialized?");
1648 // There's no fundamental reason why we require at least one index
1649 // (other than weirdness with &*IdxBegin being invalid; see
1650 // getelementptr's init routine for example). But there's no
1651 // present need to support it.
1652 assert(Idxs.size() > 0 && "InsertValueInst must have at least one index");
1654 assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs) ==
1655 Val->getType() && "Inserted value must match indexed type!");
1659 Indices.append(Idxs.begin(), Idxs.end());
1663 InsertValueInst::InsertValueInst(const InsertValueInst &IVI)
1664 : Instruction(IVI.getType(), InsertValue,
1665 OperandTraits<InsertValueInst>::op_begin(this), 2),
1666 Indices(IVI.Indices) {
1667 Op<0>() = IVI.getOperand(0);
1668 Op<1>() = IVI.getOperand(1);
1669 SubclassOptionalData = IVI.SubclassOptionalData;
1672 //===----------------------------------------------------------------------===//
1673 // ExtractValueInst Class
1674 //===----------------------------------------------------------------------===//
1676 void ExtractValueInst::init(ArrayRef<unsigned> Idxs, const Twine &Name) {
1677 assert(NumOperands == 1 && "NumOperands not initialized?");
1679 // There's no fundamental reason why we require at least one index.
1680 // But there's no present need to support it.
1681 assert(Idxs.size() > 0 && "ExtractValueInst must have at least one index");
1683 Indices.append(Idxs.begin(), Idxs.end());
1687 ExtractValueInst::ExtractValueInst(const ExtractValueInst &EVI)
1688 : UnaryInstruction(EVI.getType(), ExtractValue, EVI.getOperand(0)),
1689 Indices(EVI.Indices) {
1690 SubclassOptionalData = EVI.SubclassOptionalData;
1693 // getIndexedType - Returns the type of the element that would be extracted
1694 // with an extractvalue instruction with the specified parameters.
1696 // A null type is returned if the indices are invalid for the specified
1699 Type *ExtractValueInst::getIndexedType(Type *Agg,
1700 ArrayRef<unsigned> Idxs) {
1701 for (unsigned CurIdx = 0; CurIdx != Idxs.size(); ++CurIdx) {
1702 unsigned Index = Idxs[CurIdx];
1703 // We can't use CompositeType::indexValid(Index) here.
1704 // indexValid() always returns true for arrays because getelementptr allows
1705 // out-of-bounds indices. Since we don't allow those for extractvalue and
1706 // insertvalue we need to check array indexing manually.
1707 // Since the only other types we can index into are struct types it's just
1708 // as easy to check those manually as well.
1709 if (ArrayType *AT = dyn_cast<ArrayType>(Agg)) {
1710 if (Index >= AT->getNumElements())
1712 } else if (StructType *ST = dyn_cast<StructType>(Agg)) {
1713 if (Index >= ST->getNumElements())
1716 // Not a valid type to index into.
1720 Agg = cast<CompositeType>(Agg)->getTypeAtIndex(Index);
1722 return const_cast<Type*>(Agg);
1725 //===----------------------------------------------------------------------===//
1726 // BinaryOperator Class
1727 //===----------------------------------------------------------------------===//
1729 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
1730 Type *Ty, const Twine &Name,
1731 Instruction *InsertBefore)
1732 : Instruction(Ty, iType,
1733 OperandTraits<BinaryOperator>::op_begin(this),
1734 OperandTraits<BinaryOperator>::operands(this),
1742 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
1743 Type *Ty, const Twine &Name,
1744 BasicBlock *InsertAtEnd)
1745 : Instruction(Ty, iType,
1746 OperandTraits<BinaryOperator>::op_begin(this),
1747 OperandTraits<BinaryOperator>::operands(this),
1756 void BinaryOperator::init(BinaryOps iType) {
1757 Value *LHS = getOperand(0), *RHS = getOperand(1);
1758 (void)LHS; (void)RHS; // Silence warnings.
1759 assert(LHS->getType() == RHS->getType() &&
1760 "Binary operator operand types must match!");
1765 assert(getType() == LHS->getType() &&
1766 "Arithmetic operation should return same type as operands!");
1767 assert(getType()->isIntOrIntVectorTy() &&
1768 "Tried to create an integer operation on a non-integer type!");
1770 case FAdd: case FSub:
1772 assert(getType() == LHS->getType() &&
1773 "Arithmetic operation should return same type as operands!");
1774 assert(getType()->isFPOrFPVectorTy() &&
1775 "Tried to create a floating-point operation on a "
1776 "non-floating-point type!");
1780 assert(getType() == LHS->getType() &&
1781 "Arithmetic operation should return same type as operands!");
1782 assert((getType()->isIntegerTy() || (getType()->isVectorTy() &&
1783 cast<VectorType>(getType())->getElementType()->isIntegerTy())) &&
1784 "Incorrect operand type (not integer) for S/UDIV");
1787 assert(getType() == LHS->getType() &&
1788 "Arithmetic operation should return same type as operands!");
1789 assert(getType()->isFPOrFPVectorTy() &&
1790 "Incorrect operand type (not floating point) for FDIV");
1794 assert(getType() == LHS->getType() &&
1795 "Arithmetic operation should return same type as operands!");
1796 assert((getType()->isIntegerTy() || (getType()->isVectorTy() &&
1797 cast<VectorType>(getType())->getElementType()->isIntegerTy())) &&
1798 "Incorrect operand type (not integer) for S/UREM");
1801 assert(getType() == LHS->getType() &&
1802 "Arithmetic operation should return same type as operands!");
1803 assert(getType()->isFPOrFPVectorTy() &&
1804 "Incorrect operand type (not floating point) for FREM");
1809 assert(getType() == LHS->getType() &&
1810 "Shift operation should return same type as operands!");
1811 assert((getType()->isIntegerTy() ||
1812 (getType()->isVectorTy() &&
1813 cast<VectorType>(getType())->getElementType()->isIntegerTy())) &&
1814 "Tried to create a shift operation on a non-integral type!");
1818 assert(getType() == LHS->getType() &&
1819 "Logical operation should return same type as operands!");
1820 assert((getType()->isIntegerTy() ||
1821 (getType()->isVectorTy() &&
1822 cast<VectorType>(getType())->getElementType()->isIntegerTy())) &&
1823 "Tried to create a logical operation on a non-integral type!");
1831 BinaryOperator *BinaryOperator::Create(BinaryOps Op, Value *S1, Value *S2,
1833 Instruction *InsertBefore) {
1834 assert(S1->getType() == S2->getType() &&
1835 "Cannot create binary operator with two operands of differing type!");
1836 return new BinaryOperator(Op, S1, S2, S1->getType(), Name, InsertBefore);
1839 BinaryOperator *BinaryOperator::Create(BinaryOps Op, Value *S1, Value *S2,
1841 BasicBlock *InsertAtEnd) {
1842 BinaryOperator *Res = Create(Op, S1, S2, Name);
1843 InsertAtEnd->getInstList().push_back(Res);
1847 BinaryOperator *BinaryOperator::CreateNeg(Value *Op, const Twine &Name,
1848 Instruction *InsertBefore) {
1849 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1850 return new BinaryOperator(Instruction::Sub,
1852 Op->getType(), Name, InsertBefore);
1855 BinaryOperator *BinaryOperator::CreateNeg(Value *Op, const Twine &Name,
1856 BasicBlock *InsertAtEnd) {
1857 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1858 return new BinaryOperator(Instruction::Sub,
1860 Op->getType(), Name, InsertAtEnd);
1863 BinaryOperator *BinaryOperator::CreateNSWNeg(Value *Op, const Twine &Name,
1864 Instruction *InsertBefore) {
1865 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1866 return BinaryOperator::CreateNSWSub(zero, Op, Name, InsertBefore);
1869 BinaryOperator *BinaryOperator::CreateNSWNeg(Value *Op, const Twine &Name,
1870 BasicBlock *InsertAtEnd) {
1871 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1872 return BinaryOperator::CreateNSWSub(zero, Op, Name, InsertAtEnd);
1875 BinaryOperator *BinaryOperator::CreateNUWNeg(Value *Op, const Twine &Name,
1876 Instruction *InsertBefore) {
1877 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1878 return BinaryOperator::CreateNUWSub(zero, Op, Name, InsertBefore);
1881 BinaryOperator *BinaryOperator::CreateNUWNeg(Value *Op, const Twine &Name,
1882 BasicBlock *InsertAtEnd) {
1883 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1884 return BinaryOperator::CreateNUWSub(zero, Op, Name, InsertAtEnd);
1887 BinaryOperator *BinaryOperator::CreateFNeg(Value *Op, const Twine &Name,
1888 Instruction *InsertBefore) {
1889 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1890 return new BinaryOperator(Instruction::FSub, zero, Op,
1891 Op->getType(), Name, InsertBefore);
1894 BinaryOperator *BinaryOperator::CreateFNeg(Value *Op, const Twine &Name,
1895 BasicBlock *InsertAtEnd) {
1896 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1897 return new BinaryOperator(Instruction::FSub, zero, Op,
1898 Op->getType(), Name, InsertAtEnd);
1901 BinaryOperator *BinaryOperator::CreateNot(Value *Op, const Twine &Name,
1902 Instruction *InsertBefore) {
1903 Constant *C = Constant::getAllOnesValue(Op->getType());
1904 return new BinaryOperator(Instruction::Xor, Op, C,
1905 Op->getType(), Name, InsertBefore);
1908 BinaryOperator *BinaryOperator::CreateNot(Value *Op, const Twine &Name,
1909 BasicBlock *InsertAtEnd) {
1910 Constant *AllOnes = Constant::getAllOnesValue(Op->getType());
1911 return new BinaryOperator(Instruction::Xor, Op, AllOnes,
1912 Op->getType(), Name, InsertAtEnd);
1916 // isConstantAllOnes - Helper function for several functions below
1917 static inline bool isConstantAllOnes(const Value *V) {
1918 if (const Constant *C = dyn_cast<Constant>(V))
1919 return C->isAllOnesValue();
1923 bool BinaryOperator::isNeg(const Value *V) {
1924 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1925 if (Bop->getOpcode() == Instruction::Sub)
1926 if (Constant* C = dyn_cast<Constant>(Bop->getOperand(0)))
1927 return C->isNegativeZeroValue();
1931 bool BinaryOperator::isFNeg(const Value *V) {
1932 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1933 if (Bop->getOpcode() == Instruction::FSub)
1934 if (Constant* C = dyn_cast<Constant>(Bop->getOperand(0)))
1935 return C->isNegativeZeroValue();
1939 bool BinaryOperator::isNot(const Value *V) {
1940 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1941 return (Bop->getOpcode() == Instruction::Xor &&
1942 (isConstantAllOnes(Bop->getOperand(1)) ||
1943 isConstantAllOnes(Bop->getOperand(0))));
1947 Value *BinaryOperator::getNegArgument(Value *BinOp) {
1948 return cast<BinaryOperator>(BinOp)->getOperand(1);
1951 const Value *BinaryOperator::getNegArgument(const Value *BinOp) {
1952 return getNegArgument(const_cast<Value*>(BinOp));
1955 Value *BinaryOperator::getFNegArgument(Value *BinOp) {
1956 return cast<BinaryOperator>(BinOp)->getOperand(1);
1959 const Value *BinaryOperator::getFNegArgument(const Value *BinOp) {
1960 return getFNegArgument(const_cast<Value*>(BinOp));
1963 Value *BinaryOperator::getNotArgument(Value *BinOp) {
1964 assert(isNot(BinOp) && "getNotArgument on non-'not' instruction!");
1965 BinaryOperator *BO = cast<BinaryOperator>(BinOp);
1966 Value *Op0 = BO->getOperand(0);
1967 Value *Op1 = BO->getOperand(1);
1968 if (isConstantAllOnes(Op0)) return Op1;
1970 assert(isConstantAllOnes(Op1));
1974 const Value *BinaryOperator::getNotArgument(const Value *BinOp) {
1975 return getNotArgument(const_cast<Value*>(BinOp));
1979 // swapOperands - Exchange the two operands to this instruction. This
1980 // instruction is safe to use on any binary instruction and does not
1981 // modify the semantics of the instruction. If the instruction is
1982 // order dependent (SetLT f.e.) the opcode is changed.
1984 bool BinaryOperator::swapOperands() {
1985 if (!isCommutative())
1986 return true; // Can't commute operands
1987 Op<0>().swap(Op<1>());
1991 void BinaryOperator::setHasNoUnsignedWrap(bool b) {
1992 cast<OverflowingBinaryOperator>(this)->setHasNoUnsignedWrap(b);
1995 void BinaryOperator::setHasNoSignedWrap(bool b) {
1996 cast<OverflowingBinaryOperator>(this)->setHasNoSignedWrap(b);
1999 void BinaryOperator::setIsExact(bool b) {
2000 cast<PossiblyExactOperator>(this)->setIsExact(b);
2003 bool BinaryOperator::hasNoUnsignedWrap() const {
2004 return cast<OverflowingBinaryOperator>(this)->hasNoUnsignedWrap();
2007 bool BinaryOperator::hasNoSignedWrap() const {
2008 return cast<OverflowingBinaryOperator>(this)->hasNoSignedWrap();
2011 bool BinaryOperator::isExact() const {
2012 return cast<PossiblyExactOperator>(this)->isExact();
2015 //===----------------------------------------------------------------------===//
2016 // FPMathOperator Class
2017 //===----------------------------------------------------------------------===//
2019 /// getFPAccuracy - Get the maximum error permitted by this operation in ULPs.
2020 /// An accuracy of 0.0 means that the operation should be performed with the
2021 /// default precision.
2022 float FPMathOperator::getFPAccuracy() const {
2024 cast<Instruction>(this)->getMetadata(LLVMContext::MD_fpmath);
2027 ConstantFP *Accuracy = cast<ConstantFP>(MD->getOperand(0));
2028 return Accuracy->getValueAPF().convertToFloat();
2032 //===----------------------------------------------------------------------===//
2034 //===----------------------------------------------------------------------===//
2036 void CastInst::anchor() {}
2038 // Just determine if this cast only deals with integral->integral conversion.
2039 bool CastInst::isIntegerCast() const {
2040 switch (getOpcode()) {
2041 default: return false;
2042 case Instruction::ZExt:
2043 case Instruction::SExt:
2044 case Instruction::Trunc:
2046 case Instruction::BitCast:
2047 return getOperand(0)->getType()->isIntegerTy() &&
2048 getType()->isIntegerTy();
2052 bool CastInst::isLosslessCast() const {
2053 // Only BitCast can be lossless, exit fast if we're not BitCast
2054 if (getOpcode() != Instruction::BitCast)
2057 // Identity cast is always lossless
2058 Type* SrcTy = getOperand(0)->getType();
2059 Type* DstTy = getType();
2063 // Pointer to pointer is always lossless.
2064 if (SrcTy->isPointerTy())
2065 return DstTy->isPointerTy();
2066 return false; // Other types have no identity values
2069 /// This function determines if the CastInst does not require any bits to be
2070 /// changed in order to effect the cast. Essentially, it identifies cases where
2071 /// no code gen is necessary for the cast, hence the name no-op cast. For
2072 /// example, the following are all no-op casts:
2073 /// # bitcast i32* %x to i8*
2074 /// # bitcast <2 x i32> %x to <4 x i16>
2075 /// # ptrtoint i32* %x to i32 ; on 32-bit plaforms only
2076 /// @brief Determine if the described cast is a no-op.
2077 bool CastInst::isNoopCast(Instruction::CastOps Opcode,
2082 default: llvm_unreachable("Invalid CastOp");
2083 case Instruction::Trunc:
2084 case Instruction::ZExt:
2085 case Instruction::SExt:
2086 case Instruction::FPTrunc:
2087 case Instruction::FPExt:
2088 case Instruction::UIToFP:
2089 case Instruction::SIToFP:
2090 case Instruction::FPToUI:
2091 case Instruction::FPToSI:
2092 return false; // These always modify bits
2093 case Instruction::BitCast:
2094 return true; // BitCast never modifies bits.
2095 case Instruction::PtrToInt:
2096 return IntPtrTy->getScalarSizeInBits() ==
2097 DestTy->getScalarSizeInBits();
2098 case Instruction::IntToPtr:
2099 return IntPtrTy->getScalarSizeInBits() ==
2100 SrcTy->getScalarSizeInBits();
2104 /// @brief Determine if a cast is a no-op.
2105 bool CastInst::isNoopCast(Type *IntPtrTy) const {
2106 return isNoopCast(getOpcode(), getOperand(0)->getType(), getType(), IntPtrTy);
2109 /// This function determines if a pair of casts can be eliminated and what
2110 /// opcode should be used in the elimination. This assumes that there are two
2111 /// instructions like this:
2112 /// * %F = firstOpcode SrcTy %x to MidTy
2113 /// * %S = secondOpcode MidTy %F to DstTy
2114 /// The function returns a resultOpcode so these two casts can be replaced with:
2115 /// * %Replacement = resultOpcode %SrcTy %x to DstTy
2116 /// If no such cast is permited, the function returns 0.
2117 unsigned CastInst::isEliminableCastPair(
2118 Instruction::CastOps firstOp, Instruction::CastOps secondOp,
2119 Type *SrcTy, Type *MidTy, Type *DstTy, Type *SrcIntPtrTy, Type *MidIntPtrTy,
2120 Type *DstIntPtrTy) {
2121 // Define the 144 possibilities for these two cast instructions. The values
2122 // in this matrix determine what to do in a given situation and select the
2123 // case in the switch below. The rows correspond to firstOp, the columns
2124 // correspond to secondOp. In looking at the table below, keep in mind
2125 // the following cast properties:
2127 // Size Compare Source Destination
2128 // Operator Src ? Size Type Sign Type Sign
2129 // -------- ------------ ------------------- ---------------------
2130 // TRUNC > Integer Any Integral Any
2131 // ZEXT < Integral Unsigned Integer Any
2132 // SEXT < Integral Signed Integer Any
2133 // FPTOUI n/a FloatPt n/a Integral Unsigned
2134 // FPTOSI n/a FloatPt n/a Integral Signed
2135 // UITOFP n/a Integral Unsigned FloatPt n/a
2136 // SITOFP n/a Integral Signed FloatPt n/a
2137 // FPTRUNC > FloatPt n/a FloatPt n/a
2138 // FPEXT < FloatPt n/a FloatPt n/a
2139 // PTRTOINT n/a Pointer n/a Integral Unsigned
2140 // INTTOPTR n/a Integral Unsigned Pointer n/a
2141 // BITCAST = FirstClass n/a FirstClass n/a
2143 // NOTE: some transforms are safe, but we consider them to be non-profitable.
2144 // For example, we could merge "fptoui double to i32" + "zext i32 to i64",
2145 // into "fptoui double to i64", but this loses information about the range
2146 // of the produced value (we no longer know the top-part is all zeros).
2147 // Further this conversion is often much more expensive for typical hardware,
2148 // and causes issues when building libgcc. We disallow fptosi+sext for the
2150 const unsigned numCastOps =
2151 Instruction::CastOpsEnd - Instruction::CastOpsBegin;
2152 static const uint8_t CastResults[numCastOps][numCastOps] = {
2153 // T F F U S F F P I B -+
2154 // R Z S P P I I T P 2 N T |
2155 // U E E 2 2 2 2 R E I T C +- secondOp
2156 // N X X U S F F N X N 2 V |
2157 // C T T I I P P C T T P T -+
2158 { 1, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // Trunc -+
2159 { 8, 1, 9,99,99, 2, 0,99,99,99, 2, 3 }, // ZExt |
2160 { 8, 0, 1,99,99, 0, 2,99,99,99, 0, 3 }, // SExt |
2161 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // FPToUI |
2162 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // FPToSI |
2163 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4 }, // UIToFP +- firstOp
2164 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4 }, // SIToFP |
2165 { 99,99,99, 0, 0,99,99, 1, 0,99,99, 4 }, // FPTrunc |
2166 { 99,99,99, 2, 2,99,99,10, 2,99,99, 4 }, // FPExt |
2167 { 1, 0, 0,99,99, 0, 0,99,99,99, 7, 3 }, // PtrToInt |
2168 { 99,99,99,99,99,99,99,99,99,13,99,12 }, // IntToPtr |
2169 { 5, 5, 5, 6, 6, 5, 5, 6, 6,11, 5, 1 }, // BitCast -+
2172 // If either of the casts are a bitcast from scalar to vector, disallow the
2173 // merging. However, bitcast of A->B->A are allowed.
2174 bool isFirstBitcast = (firstOp == Instruction::BitCast);
2175 bool isSecondBitcast = (secondOp == Instruction::BitCast);
2176 bool chainedBitcast = (SrcTy == DstTy && isFirstBitcast && isSecondBitcast);
2178 // Check if any of the bitcasts convert scalars<->vectors.
2179 if ((isFirstBitcast && isa<VectorType>(SrcTy) != isa<VectorType>(MidTy)) ||
2180 (isSecondBitcast && isa<VectorType>(MidTy) != isa<VectorType>(DstTy)))
2181 // Unless we are bitcasing to the original type, disallow optimizations.
2182 if (!chainedBitcast) return 0;
2184 int ElimCase = CastResults[firstOp-Instruction::CastOpsBegin]
2185 [secondOp-Instruction::CastOpsBegin];
2188 // categorically disallowed
2191 // allowed, use first cast's opcode
2194 // allowed, use second cast's opcode
2197 // no-op cast in second op implies firstOp as long as the DestTy
2198 // is integer and we are not converting between a vector and a
2200 if (!SrcTy->isVectorTy() && DstTy->isIntegerTy())
2204 // no-op cast in second op implies firstOp as long as the DestTy
2205 // is floating point.
2206 if (DstTy->isFloatingPointTy())
2210 // no-op cast in first op implies secondOp as long as the SrcTy
2212 if (SrcTy->isIntegerTy())
2216 // no-op cast in first op implies secondOp as long as the SrcTy
2217 // is a floating point.
2218 if (SrcTy->isFloatingPointTy())
2222 // ptrtoint, inttoptr -> bitcast (ptr -> ptr) if int size is >= ptr size
2223 if (!SrcIntPtrTy || DstIntPtrTy != SrcIntPtrTy)
2225 unsigned PtrSize = SrcIntPtrTy->getScalarSizeInBits();
2226 unsigned MidSize = MidTy->getScalarSizeInBits();
2227 if (MidSize >= PtrSize)
2228 return Instruction::BitCast;
2232 // ext, trunc -> bitcast, if the SrcTy and DstTy are same size
2233 // ext, trunc -> ext, if sizeof(SrcTy) < sizeof(DstTy)
2234 // ext, trunc -> trunc, if sizeof(SrcTy) > sizeof(DstTy)
2235 unsigned SrcSize = SrcTy->getScalarSizeInBits();
2236 unsigned DstSize = DstTy->getScalarSizeInBits();
2237 if (SrcSize == DstSize)
2238 return Instruction::BitCast;
2239 else if (SrcSize < DstSize)
2243 case 9: // zext, sext -> zext, because sext can't sign extend after zext
2244 return Instruction::ZExt;
2246 // fpext followed by ftrunc is allowed if the bit size returned to is
2247 // the same as the original, in which case its just a bitcast
2249 return Instruction::BitCast;
2250 return 0; // If the types are not the same we can't eliminate it.
2252 // bitcast followed by ptrtoint is allowed as long as the bitcast
2253 // is a pointer to pointer cast.
2254 if (SrcTy->isPointerTy() && MidTy->isPointerTy())
2258 // inttoptr, bitcast -> intptr if bitcast is a ptr to ptr cast
2259 if (MidTy->isPointerTy() && DstTy->isPointerTy())
2263 // inttoptr, ptrtoint -> bitcast if SrcSize<=PtrSize and SrcSize==DstSize
2266 unsigned PtrSize = MidIntPtrTy->getScalarSizeInBits();
2267 unsigned SrcSize = SrcTy->getScalarSizeInBits();
2268 unsigned DstSize = DstTy->getScalarSizeInBits();
2269 if (SrcSize <= PtrSize && SrcSize == DstSize)
2270 return Instruction::BitCast;
2274 // cast combination can't happen (error in input). This is for all cases
2275 // where the MidTy is not the same for the two cast instructions.
2276 llvm_unreachable("Invalid Cast Combination");
2278 llvm_unreachable("Error in CastResults table!!!");
2282 CastInst *CastInst::Create(Instruction::CastOps op, Value *S, Type *Ty,
2283 const Twine &Name, Instruction *InsertBefore) {
2284 assert(castIsValid(op, S, Ty) && "Invalid cast!");
2285 // Construct and return the appropriate CastInst subclass
2287 case Trunc: return new TruncInst (S, Ty, Name, InsertBefore);
2288 case ZExt: return new ZExtInst (S, Ty, Name, InsertBefore);
2289 case SExt: return new SExtInst (S, Ty, Name, InsertBefore);
2290 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertBefore);
2291 case FPExt: return new FPExtInst (S, Ty, Name, InsertBefore);
2292 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertBefore);
2293 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertBefore);
2294 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertBefore);
2295 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertBefore);
2296 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertBefore);
2297 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertBefore);
2298 case BitCast: return new BitCastInst (S, Ty, Name, InsertBefore);
2299 default: llvm_unreachable("Invalid opcode provided");
2303 CastInst *CastInst::Create(Instruction::CastOps op, Value *S, Type *Ty,
2304 const Twine &Name, BasicBlock *InsertAtEnd) {
2305 assert(castIsValid(op, S, Ty) && "Invalid cast!");
2306 // Construct and return the appropriate CastInst subclass
2308 case Trunc: return new TruncInst (S, Ty, Name, InsertAtEnd);
2309 case ZExt: return new ZExtInst (S, Ty, Name, InsertAtEnd);
2310 case SExt: return new SExtInst (S, Ty, Name, InsertAtEnd);
2311 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertAtEnd);
2312 case FPExt: return new FPExtInst (S, Ty, Name, InsertAtEnd);
2313 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertAtEnd);
2314 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertAtEnd);
2315 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertAtEnd);
2316 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertAtEnd);
2317 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertAtEnd);
2318 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertAtEnd);
2319 case BitCast: return new BitCastInst (S, Ty, Name, InsertAtEnd);
2320 default: llvm_unreachable("Invalid opcode provided");
2324 CastInst *CastInst::CreateZExtOrBitCast(Value *S, Type *Ty,
2326 Instruction *InsertBefore) {
2327 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2328 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2329 return Create(Instruction::ZExt, S, Ty, Name, InsertBefore);
2332 CastInst *CastInst::CreateZExtOrBitCast(Value *S, Type *Ty,
2334 BasicBlock *InsertAtEnd) {
2335 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2336 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2337 return Create(Instruction::ZExt, S, Ty, Name, InsertAtEnd);
2340 CastInst *CastInst::CreateSExtOrBitCast(Value *S, Type *Ty,
2342 Instruction *InsertBefore) {
2343 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2344 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2345 return Create(Instruction::SExt, S, Ty, Name, InsertBefore);
2348 CastInst *CastInst::CreateSExtOrBitCast(Value *S, Type *Ty,
2350 BasicBlock *InsertAtEnd) {
2351 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2352 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2353 return Create(Instruction::SExt, S, Ty, Name, InsertAtEnd);
2356 CastInst *CastInst::CreateTruncOrBitCast(Value *S, Type *Ty,
2358 Instruction *InsertBefore) {
2359 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2360 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2361 return Create(Instruction::Trunc, S, Ty, Name, InsertBefore);
2364 CastInst *CastInst::CreateTruncOrBitCast(Value *S, Type *Ty,
2366 BasicBlock *InsertAtEnd) {
2367 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2368 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2369 return Create(Instruction::Trunc, S, Ty, Name, InsertAtEnd);
2372 CastInst *CastInst::CreatePointerCast(Value *S, Type *Ty,
2374 BasicBlock *InsertAtEnd) {
2375 assert(S->getType()->isPointerTy() && "Invalid cast");
2376 assert((Ty->isIntegerTy() || Ty->isPointerTy()) &&
2379 if (Ty->isIntegerTy())
2380 return Create(Instruction::PtrToInt, S, Ty, Name, InsertAtEnd);
2381 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2384 /// @brief Create a BitCast or a PtrToInt cast instruction
2385 CastInst *CastInst::CreatePointerCast(Value *S, Type *Ty,
2387 Instruction *InsertBefore) {
2388 assert(S->getType()->isPointerTy() && "Invalid cast");
2389 assert((Ty->isIntegerTy() || Ty->isPointerTy()) &&
2392 if (Ty->isIntegerTy())
2393 return Create(Instruction::PtrToInt, S, Ty, Name, InsertBefore);
2394 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2397 CastInst *CastInst::CreateIntegerCast(Value *C, Type *Ty,
2398 bool isSigned, const Twine &Name,
2399 Instruction *InsertBefore) {
2400 assert(C->getType()->isIntOrIntVectorTy() && Ty->isIntOrIntVectorTy() &&
2401 "Invalid integer cast");
2402 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2403 unsigned DstBits = Ty->getScalarSizeInBits();
2404 Instruction::CastOps opcode =
2405 (SrcBits == DstBits ? Instruction::BitCast :
2406 (SrcBits > DstBits ? Instruction::Trunc :
2407 (isSigned ? Instruction::SExt : Instruction::ZExt)));
2408 return Create(opcode, C, Ty, Name, InsertBefore);
2411 CastInst *CastInst::CreateIntegerCast(Value *C, Type *Ty,
2412 bool isSigned, const Twine &Name,
2413 BasicBlock *InsertAtEnd) {
2414 assert(C->getType()->isIntOrIntVectorTy() && Ty->isIntOrIntVectorTy() &&
2416 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2417 unsigned DstBits = Ty->getScalarSizeInBits();
2418 Instruction::CastOps opcode =
2419 (SrcBits == DstBits ? Instruction::BitCast :
2420 (SrcBits > DstBits ? Instruction::Trunc :
2421 (isSigned ? Instruction::SExt : Instruction::ZExt)));
2422 return Create(opcode, C, Ty, Name, InsertAtEnd);
2425 CastInst *CastInst::CreateFPCast(Value *C, Type *Ty,
2427 Instruction *InsertBefore) {
2428 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
2430 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2431 unsigned DstBits = Ty->getScalarSizeInBits();
2432 Instruction::CastOps opcode =
2433 (SrcBits == DstBits ? Instruction::BitCast :
2434 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
2435 return Create(opcode, C, Ty, Name, InsertBefore);
2438 CastInst *CastInst::CreateFPCast(Value *C, Type *Ty,
2440 BasicBlock *InsertAtEnd) {
2441 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
2443 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2444 unsigned DstBits = Ty->getScalarSizeInBits();
2445 Instruction::CastOps opcode =
2446 (SrcBits == DstBits ? Instruction::BitCast :
2447 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
2448 return Create(opcode, C, Ty, Name, InsertAtEnd);
2451 // Check whether it is valid to call getCastOpcode for these types.
2452 // This routine must be kept in sync with getCastOpcode.
2453 bool CastInst::isCastable(Type *SrcTy, Type *DestTy) {
2454 if (!SrcTy->isFirstClassType() || !DestTy->isFirstClassType())
2457 if (SrcTy == DestTy)
2460 if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy))
2461 if (VectorType *DestVecTy = dyn_cast<VectorType>(DestTy))
2462 if (SrcVecTy->getNumElements() == DestVecTy->getNumElements()) {
2463 // An element by element cast. Valid if casting the elements is valid.
2464 SrcTy = SrcVecTy->getElementType();
2465 DestTy = DestVecTy->getElementType();
2468 // Get the bit sizes, we'll need these
2469 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); // 0 for ptr
2470 unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr
2472 // Run through the possibilities ...
2473 if (DestTy->isIntegerTy()) { // Casting to integral
2474 if (SrcTy->isIntegerTy()) { // Casting from integral
2476 } else if (SrcTy->isFloatingPointTy()) { // Casting from floating pt
2478 } else if (SrcTy->isVectorTy()) { // Casting from vector
2479 return DestBits == SrcBits;
2480 } else { // Casting from something else
2481 return SrcTy->isPointerTy();
2483 } else if (DestTy->isFloatingPointTy()) { // Casting to floating pt
2484 if (SrcTy->isIntegerTy()) { // Casting from integral
2486 } else if (SrcTy->isFloatingPointTy()) { // Casting from floating pt
2488 } else if (SrcTy->isVectorTy()) { // Casting from vector
2489 return DestBits == SrcBits;
2490 } else { // Casting from something else
2493 } else if (DestTy->isVectorTy()) { // Casting to vector
2494 return DestBits == SrcBits;
2495 } else if (DestTy->isPointerTy()) { // Casting to pointer
2496 if (SrcTy->isPointerTy()) { // Casting from pointer
2498 } else if (SrcTy->isIntegerTy()) { // Casting from integral
2500 } else { // Casting from something else
2503 } else if (DestTy->isX86_MMXTy()) {
2504 if (SrcTy->isVectorTy()) {
2505 return DestBits == SrcBits; // 64-bit vector to MMX
2509 } else { // Casting to something else
2514 // Provide a way to get a "cast" where the cast opcode is inferred from the
2515 // types and size of the operand. This, basically, is a parallel of the
2516 // logic in the castIsValid function below. This axiom should hold:
2517 // castIsValid( getCastOpcode(Val, Ty), Val, Ty)
2518 // should not assert in castIsValid. In other words, this produces a "correct"
2519 // casting opcode for the arguments passed to it.
2520 // This routine must be kept in sync with isCastable.
2521 Instruction::CastOps
2522 CastInst::getCastOpcode(
2523 const Value *Src, bool SrcIsSigned, Type *DestTy, bool DestIsSigned) {
2524 Type *SrcTy = Src->getType();
2526 assert(SrcTy->isFirstClassType() && DestTy->isFirstClassType() &&
2527 "Only first class types are castable!");
2529 if (SrcTy == DestTy)
2532 if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy))
2533 if (VectorType *DestVecTy = dyn_cast<VectorType>(DestTy))
2534 if (SrcVecTy->getNumElements() == DestVecTy->getNumElements()) {
2535 // An element by element cast. Find the appropriate opcode based on the
2537 SrcTy = SrcVecTy->getElementType();
2538 DestTy = DestVecTy->getElementType();
2541 // Get the bit sizes, we'll need these
2542 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); // 0 for ptr
2543 unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr
2545 // Run through the possibilities ...
2546 if (DestTy->isIntegerTy()) { // Casting to integral
2547 if (SrcTy->isIntegerTy()) { // Casting from integral
2548 if (DestBits < SrcBits)
2549 return Trunc; // int -> smaller int
2550 else if (DestBits > SrcBits) { // its an extension
2552 return SExt; // signed -> SEXT
2554 return ZExt; // unsigned -> ZEXT
2556 return BitCast; // Same size, No-op cast
2558 } else if (SrcTy->isFloatingPointTy()) { // Casting from floating pt
2560 return FPToSI; // FP -> sint
2562 return FPToUI; // FP -> uint
2563 } else if (SrcTy->isVectorTy()) {
2564 assert(DestBits == SrcBits &&
2565 "Casting vector to integer of different width");
2566 return BitCast; // Same size, no-op cast
2568 assert(SrcTy->isPointerTy() &&
2569 "Casting from a value that is not first-class type");
2570 return PtrToInt; // ptr -> int
2572 } else if (DestTy->isFloatingPointTy()) { // Casting to floating pt
2573 if (SrcTy->isIntegerTy()) { // Casting from integral
2575 return SIToFP; // sint -> FP
2577 return UIToFP; // uint -> FP
2578 } else if (SrcTy->isFloatingPointTy()) { // Casting from floating pt
2579 if (DestBits < SrcBits) {
2580 return FPTrunc; // FP -> smaller FP
2581 } else if (DestBits > SrcBits) {
2582 return FPExt; // FP -> larger FP
2584 return BitCast; // same size, no-op cast
2586 } else if (SrcTy->isVectorTy()) {
2587 assert(DestBits == SrcBits &&
2588 "Casting vector to floating point of different width");
2589 return BitCast; // same size, no-op cast
2591 llvm_unreachable("Casting pointer or non-first class to float");
2592 } else if (DestTy->isVectorTy()) {
2593 assert(DestBits == SrcBits &&
2594 "Illegal cast to vector (wrong type or size)");
2596 } else if (DestTy->isPointerTy()) {
2597 if (SrcTy->isPointerTy()) {
2598 return BitCast; // ptr -> ptr
2599 } else if (SrcTy->isIntegerTy()) {
2600 return IntToPtr; // int -> ptr
2602 llvm_unreachable("Casting pointer to other than pointer or int");
2603 } else if (DestTy->isX86_MMXTy()) {
2604 if (SrcTy->isVectorTy()) {
2605 assert(DestBits == SrcBits && "Casting vector of wrong width to X86_MMX");
2606 return BitCast; // 64-bit vector to MMX
2608 llvm_unreachable("Illegal cast to X86_MMX");
2610 llvm_unreachable("Casting to type that is not first-class");
2613 //===----------------------------------------------------------------------===//
2614 // CastInst SubClass Constructors
2615 //===----------------------------------------------------------------------===//
2617 /// Check that the construction parameters for a CastInst are correct. This
2618 /// could be broken out into the separate constructors but it is useful to have
2619 /// it in one place and to eliminate the redundant code for getting the sizes
2620 /// of the types involved.
2622 CastInst::castIsValid(Instruction::CastOps op, Value *S, Type *DstTy) {
2624 // Check for type sanity on the arguments
2625 Type *SrcTy = S->getType();
2626 if (!SrcTy->isFirstClassType() || !DstTy->isFirstClassType() ||
2627 SrcTy->isAggregateType() || DstTy->isAggregateType())
2630 // Get the size of the types in bits, we'll need this later
2631 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
2632 unsigned DstBitSize = DstTy->getScalarSizeInBits();
2634 // If these are vector types, get the lengths of the vectors (using zero for
2635 // scalar types means that checking that vector lengths match also checks that
2636 // scalars are not being converted to vectors or vectors to scalars).
2637 unsigned SrcLength = SrcTy->isVectorTy() ?
2638 cast<VectorType>(SrcTy)->getNumElements() : 0;
2639 unsigned DstLength = DstTy->isVectorTy() ?
2640 cast<VectorType>(DstTy)->getNumElements() : 0;
2642 // Switch on the opcode provided
2644 default: return false; // This is an input error
2645 case Instruction::Trunc:
2646 return SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy() &&
2647 SrcLength == DstLength && SrcBitSize > DstBitSize;
2648 case Instruction::ZExt:
2649 return SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy() &&
2650 SrcLength == DstLength && SrcBitSize < DstBitSize;
2651 case Instruction::SExt:
2652 return SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy() &&
2653 SrcLength == DstLength && SrcBitSize < DstBitSize;
2654 case Instruction::FPTrunc:
2655 return SrcTy->isFPOrFPVectorTy() && DstTy->isFPOrFPVectorTy() &&
2656 SrcLength == DstLength && SrcBitSize > DstBitSize;
2657 case Instruction::FPExt:
2658 return SrcTy->isFPOrFPVectorTy() && DstTy->isFPOrFPVectorTy() &&
2659 SrcLength == DstLength && SrcBitSize < DstBitSize;
2660 case Instruction::UIToFP:
2661 case Instruction::SIToFP:
2662 return SrcTy->isIntOrIntVectorTy() && DstTy->isFPOrFPVectorTy() &&
2663 SrcLength == DstLength;
2664 case Instruction::FPToUI:
2665 case Instruction::FPToSI:
2666 return SrcTy->isFPOrFPVectorTy() && DstTy->isIntOrIntVectorTy() &&
2667 SrcLength == DstLength;
2668 case Instruction::PtrToInt:
2669 if (isa<VectorType>(SrcTy) != isa<VectorType>(DstTy))
2671 if (VectorType *VT = dyn_cast<VectorType>(SrcTy))
2672 if (VT->getNumElements() != cast<VectorType>(DstTy)->getNumElements())
2674 return SrcTy->getScalarType()->isPointerTy() &&
2675 DstTy->getScalarType()->isIntegerTy();
2676 case Instruction::IntToPtr:
2677 if (isa<VectorType>(SrcTy) != isa<VectorType>(DstTy))
2679 if (VectorType *VT = dyn_cast<VectorType>(SrcTy))
2680 if (VT->getNumElements() != cast<VectorType>(DstTy)->getNumElements())
2682 return SrcTy->getScalarType()->isIntegerTy() &&
2683 DstTy->getScalarType()->isPointerTy();
2684 case Instruction::BitCast:
2685 // BitCast implies a no-op cast of type only. No bits change.
2686 // However, you can't cast pointers to anything but pointers.
2687 if (SrcTy->isPointerTy() != DstTy->isPointerTy())
2690 // Now we know we're not dealing with a pointer/non-pointer mismatch. In all
2691 // these cases, the cast is okay if the source and destination bit widths
2693 return SrcTy->getPrimitiveSizeInBits() == DstTy->getPrimitiveSizeInBits();
2697 TruncInst::TruncInst(
2698 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2699 ) : CastInst(Ty, Trunc, S, Name, InsertBefore) {
2700 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
2703 TruncInst::TruncInst(
2704 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2705 ) : CastInst(Ty, Trunc, S, Name, InsertAtEnd) {
2706 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
2710 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2711 ) : CastInst(Ty, ZExt, S, Name, InsertBefore) {
2712 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
2716 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2717 ) : CastInst(Ty, ZExt, S, Name, InsertAtEnd) {
2718 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
2721 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2722 ) : CastInst(Ty, SExt, S, Name, InsertBefore) {
2723 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
2727 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2728 ) : CastInst(Ty, SExt, S, Name, InsertAtEnd) {
2729 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
2732 FPTruncInst::FPTruncInst(
2733 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2734 ) : CastInst(Ty, FPTrunc, S, Name, InsertBefore) {
2735 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
2738 FPTruncInst::FPTruncInst(
2739 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2740 ) : CastInst(Ty, FPTrunc, S, Name, InsertAtEnd) {
2741 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
2744 FPExtInst::FPExtInst(
2745 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2746 ) : CastInst(Ty, FPExt, S, Name, InsertBefore) {
2747 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
2750 FPExtInst::FPExtInst(
2751 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2752 ) : CastInst(Ty, FPExt, S, Name, InsertAtEnd) {
2753 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
2756 UIToFPInst::UIToFPInst(
2757 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2758 ) : CastInst(Ty, UIToFP, S, Name, InsertBefore) {
2759 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
2762 UIToFPInst::UIToFPInst(
2763 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2764 ) : CastInst(Ty, UIToFP, S, Name, InsertAtEnd) {
2765 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
2768 SIToFPInst::SIToFPInst(
2769 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2770 ) : CastInst(Ty, SIToFP, S, Name, InsertBefore) {
2771 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
2774 SIToFPInst::SIToFPInst(
2775 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2776 ) : CastInst(Ty, SIToFP, S, Name, InsertAtEnd) {
2777 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
2780 FPToUIInst::FPToUIInst(
2781 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2782 ) : CastInst(Ty, FPToUI, S, Name, InsertBefore) {
2783 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
2786 FPToUIInst::FPToUIInst(
2787 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2788 ) : CastInst(Ty, FPToUI, S, Name, InsertAtEnd) {
2789 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
2792 FPToSIInst::FPToSIInst(
2793 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2794 ) : CastInst(Ty, FPToSI, S, Name, InsertBefore) {
2795 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
2798 FPToSIInst::FPToSIInst(
2799 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2800 ) : CastInst(Ty, FPToSI, S, Name, InsertAtEnd) {
2801 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
2804 PtrToIntInst::PtrToIntInst(
2805 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2806 ) : CastInst(Ty, PtrToInt, S, Name, InsertBefore) {
2807 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
2810 PtrToIntInst::PtrToIntInst(
2811 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2812 ) : CastInst(Ty, PtrToInt, S, Name, InsertAtEnd) {
2813 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
2816 IntToPtrInst::IntToPtrInst(
2817 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2818 ) : CastInst(Ty, IntToPtr, S, Name, InsertBefore) {
2819 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
2822 IntToPtrInst::IntToPtrInst(
2823 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2824 ) : CastInst(Ty, IntToPtr, S, Name, InsertAtEnd) {
2825 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
2828 BitCastInst::BitCastInst(
2829 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2830 ) : CastInst(Ty, BitCast, S, Name, InsertBefore) {
2831 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
2834 BitCastInst::BitCastInst(
2835 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2836 ) : CastInst(Ty, BitCast, S, Name, InsertAtEnd) {
2837 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
2840 //===----------------------------------------------------------------------===//
2842 //===----------------------------------------------------------------------===//
2844 void CmpInst::anchor() {}
2846 CmpInst::CmpInst(Type *ty, OtherOps op, unsigned short predicate,
2847 Value *LHS, Value *RHS, const Twine &Name,
2848 Instruction *InsertBefore)
2849 : Instruction(ty, op,
2850 OperandTraits<CmpInst>::op_begin(this),
2851 OperandTraits<CmpInst>::operands(this),
2855 setPredicate((Predicate)predicate);
2859 CmpInst::CmpInst(Type *ty, OtherOps op, unsigned short predicate,
2860 Value *LHS, Value *RHS, const Twine &Name,
2861 BasicBlock *InsertAtEnd)
2862 : Instruction(ty, op,
2863 OperandTraits<CmpInst>::op_begin(this),
2864 OperandTraits<CmpInst>::operands(this),
2868 setPredicate((Predicate)predicate);
2873 CmpInst::Create(OtherOps Op, unsigned short predicate,
2874 Value *S1, Value *S2,
2875 const Twine &Name, Instruction *InsertBefore) {
2876 if (Op == Instruction::ICmp) {
2878 return new ICmpInst(InsertBefore, CmpInst::Predicate(predicate),
2881 return new ICmpInst(CmpInst::Predicate(predicate),
2886 return new FCmpInst(InsertBefore, CmpInst::Predicate(predicate),
2889 return new FCmpInst(CmpInst::Predicate(predicate),
2894 CmpInst::Create(OtherOps Op, unsigned short predicate, Value *S1, Value *S2,
2895 const Twine &Name, BasicBlock *InsertAtEnd) {
2896 if (Op == Instruction::ICmp) {
2897 return new ICmpInst(*InsertAtEnd, CmpInst::Predicate(predicate),
2900 return new FCmpInst(*InsertAtEnd, CmpInst::Predicate(predicate),
2904 void CmpInst::swapOperands() {
2905 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2908 cast<FCmpInst>(this)->swapOperands();
2911 bool CmpInst::isCommutative() const {
2912 if (const ICmpInst *IC = dyn_cast<ICmpInst>(this))
2913 return IC->isCommutative();
2914 return cast<FCmpInst>(this)->isCommutative();
2917 bool CmpInst::isEquality() const {
2918 if (const ICmpInst *IC = dyn_cast<ICmpInst>(this))
2919 return IC->isEquality();
2920 return cast<FCmpInst>(this)->isEquality();
2924 CmpInst::Predicate CmpInst::getInversePredicate(Predicate pred) {
2926 default: llvm_unreachable("Unknown cmp predicate!");
2927 case ICMP_EQ: return ICMP_NE;
2928 case ICMP_NE: return ICMP_EQ;
2929 case ICMP_UGT: return ICMP_ULE;
2930 case ICMP_ULT: return ICMP_UGE;
2931 case ICMP_UGE: return ICMP_ULT;
2932 case ICMP_ULE: return ICMP_UGT;
2933 case ICMP_SGT: return ICMP_SLE;
2934 case ICMP_SLT: return ICMP_SGE;
2935 case ICMP_SGE: return ICMP_SLT;
2936 case ICMP_SLE: return ICMP_SGT;
2938 case FCMP_OEQ: return FCMP_UNE;
2939 case FCMP_ONE: return FCMP_UEQ;
2940 case FCMP_OGT: return FCMP_ULE;
2941 case FCMP_OLT: return FCMP_UGE;
2942 case FCMP_OGE: return FCMP_ULT;
2943 case FCMP_OLE: return FCMP_UGT;
2944 case FCMP_UEQ: return FCMP_ONE;
2945 case FCMP_UNE: return FCMP_OEQ;
2946 case FCMP_UGT: return FCMP_OLE;
2947 case FCMP_ULT: return FCMP_OGE;
2948 case FCMP_UGE: return FCMP_OLT;
2949 case FCMP_ULE: return FCMP_OGT;
2950 case FCMP_ORD: return FCMP_UNO;
2951 case FCMP_UNO: return FCMP_ORD;
2952 case FCMP_TRUE: return FCMP_FALSE;
2953 case FCMP_FALSE: return FCMP_TRUE;
2957 ICmpInst::Predicate ICmpInst::getSignedPredicate(Predicate pred) {
2959 default: llvm_unreachable("Unknown icmp predicate!");
2960 case ICMP_EQ: case ICMP_NE:
2961 case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE:
2963 case ICMP_UGT: return ICMP_SGT;
2964 case ICMP_ULT: return ICMP_SLT;
2965 case ICMP_UGE: return ICMP_SGE;
2966 case ICMP_ULE: return ICMP_SLE;
2970 ICmpInst::Predicate ICmpInst::getUnsignedPredicate(Predicate pred) {
2972 default: llvm_unreachable("Unknown icmp predicate!");
2973 case ICMP_EQ: case ICMP_NE:
2974 case ICMP_UGT: case ICMP_ULT: case ICMP_UGE: case ICMP_ULE:
2976 case ICMP_SGT: return ICMP_UGT;
2977 case ICMP_SLT: return ICMP_ULT;
2978 case ICMP_SGE: return ICMP_UGE;
2979 case ICMP_SLE: return ICMP_ULE;
2983 /// Initialize a set of values that all satisfy the condition with C.
2986 ICmpInst::makeConstantRange(Predicate pred, const APInt &C) {
2989 uint32_t BitWidth = C.getBitWidth();
2991 default: llvm_unreachable("Invalid ICmp opcode to ConstantRange ctor!");
2992 case ICmpInst::ICMP_EQ: Upper++; break;
2993 case ICmpInst::ICMP_NE: Lower++; break;
2994 case ICmpInst::ICMP_ULT:
2995 Lower = APInt::getMinValue(BitWidth);
2996 // Check for an empty-set condition.
2998 return ConstantRange(BitWidth, /*isFullSet=*/false);
3000 case ICmpInst::ICMP_SLT:
3001 Lower = APInt::getSignedMinValue(BitWidth);
3002 // Check for an empty-set condition.
3004 return ConstantRange(BitWidth, /*isFullSet=*/false);
3006 case ICmpInst::ICMP_UGT:
3007 Lower++; Upper = APInt::getMinValue(BitWidth); // Min = Next(Max)
3008 // Check for an empty-set condition.
3010 return ConstantRange(BitWidth, /*isFullSet=*/false);
3012 case ICmpInst::ICMP_SGT:
3013 Lower++; Upper = APInt::getSignedMinValue(BitWidth); // Min = Next(Max)
3014 // Check for an empty-set condition.
3016 return ConstantRange(BitWidth, /*isFullSet=*/false);
3018 case ICmpInst::ICMP_ULE:
3019 Lower = APInt::getMinValue(BitWidth); Upper++;
3020 // Check for a full-set condition.
3022 return ConstantRange(BitWidth, /*isFullSet=*/true);
3024 case ICmpInst::ICMP_SLE:
3025 Lower = APInt::getSignedMinValue(BitWidth); Upper++;
3026 // Check for a full-set condition.
3028 return ConstantRange(BitWidth, /*isFullSet=*/true);
3030 case ICmpInst::ICMP_UGE:
3031 Upper = APInt::getMinValue(BitWidth); // Min = Next(Max)
3032 // Check for a full-set condition.
3034 return ConstantRange(BitWidth, /*isFullSet=*/true);
3036 case ICmpInst::ICMP_SGE:
3037 Upper = APInt::getSignedMinValue(BitWidth); // Min = Next(Max)
3038 // Check for a full-set condition.
3040 return ConstantRange(BitWidth, /*isFullSet=*/true);
3043 return ConstantRange(Lower, Upper);
3046 CmpInst::Predicate CmpInst::getSwappedPredicate(Predicate pred) {
3048 default: llvm_unreachable("Unknown cmp predicate!");
3049 case ICMP_EQ: case ICMP_NE:
3051 case ICMP_SGT: return ICMP_SLT;
3052 case ICMP_SLT: return ICMP_SGT;
3053 case ICMP_SGE: return ICMP_SLE;
3054 case ICMP_SLE: return ICMP_SGE;
3055 case ICMP_UGT: return ICMP_ULT;
3056 case ICMP_ULT: return ICMP_UGT;
3057 case ICMP_UGE: return ICMP_ULE;
3058 case ICMP_ULE: return ICMP_UGE;
3060 case FCMP_FALSE: case FCMP_TRUE:
3061 case FCMP_OEQ: case FCMP_ONE:
3062 case FCMP_UEQ: case FCMP_UNE:
3063 case FCMP_ORD: case FCMP_UNO:
3065 case FCMP_OGT: return FCMP_OLT;
3066 case FCMP_OLT: return FCMP_OGT;
3067 case FCMP_OGE: return FCMP_OLE;
3068 case FCMP_OLE: return FCMP_OGE;
3069 case FCMP_UGT: return FCMP_ULT;
3070 case FCMP_ULT: return FCMP_UGT;
3071 case FCMP_UGE: return FCMP_ULE;
3072 case FCMP_ULE: return FCMP_UGE;
3076 bool CmpInst::isUnsigned(unsigned short predicate) {
3077 switch (predicate) {
3078 default: return false;
3079 case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_ULE: case ICmpInst::ICMP_UGT:
3080 case ICmpInst::ICMP_UGE: return true;
3084 bool CmpInst::isSigned(unsigned short predicate) {
3085 switch (predicate) {
3086 default: return false;
3087 case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_SLE: case ICmpInst::ICMP_SGT:
3088 case ICmpInst::ICMP_SGE: return true;
3092 bool CmpInst::isOrdered(unsigned short predicate) {
3093 switch (predicate) {
3094 default: return false;
3095 case FCmpInst::FCMP_OEQ: case FCmpInst::FCMP_ONE: case FCmpInst::FCMP_OGT:
3096 case FCmpInst::FCMP_OLT: case FCmpInst::FCMP_OGE: case FCmpInst::FCMP_OLE:
3097 case FCmpInst::FCMP_ORD: return true;
3101 bool CmpInst::isUnordered(unsigned short predicate) {
3102 switch (predicate) {
3103 default: return false;
3104 case FCmpInst::FCMP_UEQ: case FCmpInst::FCMP_UNE: case FCmpInst::FCMP_UGT:
3105 case FCmpInst::FCMP_ULT: case FCmpInst::FCMP_UGE: case FCmpInst::FCMP_ULE:
3106 case FCmpInst::FCMP_UNO: return true;
3110 bool CmpInst::isTrueWhenEqual(unsigned short predicate) {
3112 default: return false;
3113 case ICMP_EQ: case ICMP_UGE: case ICMP_ULE: case ICMP_SGE: case ICMP_SLE:
3114 case FCMP_TRUE: case FCMP_UEQ: case FCMP_UGE: case FCMP_ULE: return true;
3118 bool CmpInst::isFalseWhenEqual(unsigned short predicate) {
3120 case ICMP_NE: case ICMP_UGT: case ICMP_ULT: case ICMP_SGT: case ICMP_SLT:
3121 case FCMP_FALSE: case FCMP_ONE: case FCMP_OGT: case FCMP_OLT: return true;
3122 default: return false;
3127 //===----------------------------------------------------------------------===//
3128 // SwitchInst Implementation
3129 //===----------------------------------------------------------------------===//
3131 void SwitchInst::init(Value *Value, BasicBlock *Default, unsigned NumReserved) {
3132 assert(Value && Default && NumReserved);
3133 ReservedSpace = NumReserved;
3135 OperandList = allocHungoffUses(ReservedSpace);
3137 OperandList[0] = Value;
3138 OperandList[1] = Default;
3141 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
3142 /// switch on and a default destination. The number of additional cases can
3143 /// be specified here to make memory allocation more efficient. This
3144 /// constructor can also autoinsert before another instruction.
3145 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
3146 Instruction *InsertBefore)
3147 : TerminatorInst(Type::getVoidTy(Value->getContext()), Instruction::Switch,
3148 0, 0, InsertBefore) {
3149 init(Value, Default, 2+NumCases*2);
3152 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
3153 /// switch on and a default destination. The number of additional cases can
3154 /// be specified here to make memory allocation more efficient. This
3155 /// constructor also autoinserts at the end of the specified BasicBlock.
3156 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
3157 BasicBlock *InsertAtEnd)
3158 : TerminatorInst(Type::getVoidTy(Value->getContext()), Instruction::Switch,
3159 0, 0, InsertAtEnd) {
3160 init(Value, Default, 2+NumCases*2);
3163 SwitchInst::SwitchInst(const SwitchInst &SI)
3164 : TerminatorInst(SI.getType(), Instruction::Switch, 0, 0) {
3165 init(SI.getCondition(), SI.getDefaultDest(), SI.getNumOperands());
3166 NumOperands = SI.getNumOperands();
3167 Use *OL = OperandList, *InOL = SI.OperandList;
3168 for (unsigned i = 2, E = SI.getNumOperands(); i != E; i += 2) {
3170 OL[i+1] = InOL[i+1];
3172 TheSubsets = SI.TheSubsets;
3173 SubclassOptionalData = SI.SubclassOptionalData;
3176 SwitchInst::~SwitchInst() {
3181 /// addCase - Add an entry to the switch instruction...
3183 void SwitchInst::addCase(ConstantInt *OnVal, BasicBlock *Dest) {
3184 IntegersSubsetToBB Mapping;
3186 // FIXME: Currently we work with ConstantInt based cases.
3187 // So inititalize IntItem container directly from ConstantInt.
3188 Mapping.add(IntItem::fromConstantInt(OnVal));
3189 IntegersSubset CaseRanges = Mapping.getCase();
3190 addCase(CaseRanges, Dest);
3193 void SwitchInst::addCase(IntegersSubset& OnVal, BasicBlock *Dest) {
3194 unsigned NewCaseIdx = getNumCases();
3195 unsigned OpNo = NumOperands;
3196 if (OpNo+2 > ReservedSpace)
3197 growOperands(); // Get more space!
3198 // Initialize some new operands.
3199 assert(OpNo+1 < ReservedSpace && "Growing didn't work!");
3200 NumOperands = OpNo+2;
3202 SubsetsIt TheSubsetsIt = TheSubsets.insert(TheSubsets.end(), OnVal);
3204 CaseIt Case(this, NewCaseIdx, TheSubsetsIt);
3205 Case.updateCaseValueOperand(OnVal);
3206 Case.setSuccessor(Dest);
3209 /// removeCase - This method removes the specified case and its successor
3210 /// from the switch instruction.
3211 void SwitchInst::removeCase(CaseIt& i) {
3212 unsigned idx = i.getCaseIndex();
3214 assert(2 + idx*2 < getNumOperands() && "Case index out of range!!!");
3216 unsigned NumOps = getNumOperands();
3217 Use *OL = OperandList;
3219 // Overwrite this case with the end of the list.
3220 if (2 + (idx + 1) * 2 != NumOps) {
3221 OL[2 + idx * 2] = OL[NumOps - 2];
3222 OL[2 + idx * 2 + 1] = OL[NumOps - 1];
3225 // Nuke the last value.
3226 OL[NumOps-2].set(0);
3227 OL[NumOps-2+1].set(0);
3229 // Do the same with TheCases collection:
3230 if (i.SubsetIt != --TheSubsets.end()) {
3231 *i.SubsetIt = TheSubsets.back();
3232 TheSubsets.pop_back();
3234 TheSubsets.pop_back();
3235 i.SubsetIt = TheSubsets.end();
3238 NumOperands = NumOps-2;
3241 /// growOperands - grow operands - This grows the operand list in response
3242 /// to a push_back style of operation. This grows the number of ops by 3 times.
3244 void SwitchInst::growOperands() {
3245 unsigned e = getNumOperands();
3246 unsigned NumOps = e*3;
3248 ReservedSpace = NumOps;
3249 Use *NewOps = allocHungoffUses(NumOps);
3250 Use *OldOps = OperandList;
3251 for (unsigned i = 0; i != e; ++i) {
3252 NewOps[i] = OldOps[i];
3254 OperandList = NewOps;
3255 Use::zap(OldOps, OldOps + e, true);
3259 BasicBlock *SwitchInst::getSuccessorV(unsigned idx) const {
3260 return getSuccessor(idx);
3262 unsigned SwitchInst::getNumSuccessorsV() const {
3263 return getNumSuccessors();
3265 void SwitchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
3266 setSuccessor(idx, B);
3269 //===----------------------------------------------------------------------===//
3270 // IndirectBrInst Implementation
3271 //===----------------------------------------------------------------------===//
3273 void IndirectBrInst::init(Value *Address, unsigned NumDests) {
3274 assert(Address && Address->getType()->isPointerTy() &&
3275 "Address of indirectbr must be a pointer");
3276 ReservedSpace = 1+NumDests;
3278 OperandList = allocHungoffUses(ReservedSpace);
3280 OperandList[0] = Address;
3284 /// growOperands - grow operands - This grows the operand list in response
3285 /// to a push_back style of operation. This grows the number of ops by 2 times.
3287 void IndirectBrInst::growOperands() {
3288 unsigned e = getNumOperands();
3289 unsigned NumOps = e*2;
3291 ReservedSpace = NumOps;
3292 Use *NewOps = allocHungoffUses(NumOps);
3293 Use *OldOps = OperandList;
3294 for (unsigned i = 0; i != e; ++i)
3295 NewOps[i] = OldOps[i];
3296 OperandList = NewOps;
3297 Use::zap(OldOps, OldOps + e, true);
3300 IndirectBrInst::IndirectBrInst(Value *Address, unsigned NumCases,
3301 Instruction *InsertBefore)
3302 : TerminatorInst(Type::getVoidTy(Address->getContext()),Instruction::IndirectBr,
3303 0, 0, InsertBefore) {
3304 init(Address, NumCases);
3307 IndirectBrInst::IndirectBrInst(Value *Address, unsigned NumCases,
3308 BasicBlock *InsertAtEnd)
3309 : TerminatorInst(Type::getVoidTy(Address->getContext()),Instruction::IndirectBr,
3310 0, 0, InsertAtEnd) {
3311 init(Address, NumCases);
3314 IndirectBrInst::IndirectBrInst(const IndirectBrInst &IBI)
3315 : TerminatorInst(Type::getVoidTy(IBI.getContext()), Instruction::IndirectBr,
3316 allocHungoffUses(IBI.getNumOperands()),
3317 IBI.getNumOperands()) {
3318 Use *OL = OperandList, *InOL = IBI.OperandList;
3319 for (unsigned i = 0, E = IBI.getNumOperands(); i != E; ++i)
3321 SubclassOptionalData = IBI.SubclassOptionalData;
3324 IndirectBrInst::~IndirectBrInst() {
3328 /// addDestination - Add a destination.
3330 void IndirectBrInst::addDestination(BasicBlock *DestBB) {
3331 unsigned OpNo = NumOperands;
3332 if (OpNo+1 > ReservedSpace)
3333 growOperands(); // Get more space!
3334 // Initialize some new operands.
3335 assert(OpNo < ReservedSpace && "Growing didn't work!");
3336 NumOperands = OpNo+1;
3337 OperandList[OpNo] = DestBB;
3340 /// removeDestination - This method removes the specified successor from the
3341 /// indirectbr instruction.
3342 void IndirectBrInst::removeDestination(unsigned idx) {
3343 assert(idx < getNumOperands()-1 && "Successor index out of range!");
3345 unsigned NumOps = getNumOperands();
3346 Use *OL = OperandList;
3348 // Replace this value with the last one.
3349 OL[idx+1] = OL[NumOps-1];
3351 // Nuke the last value.
3352 OL[NumOps-1].set(0);
3353 NumOperands = NumOps-1;
3356 BasicBlock *IndirectBrInst::getSuccessorV(unsigned idx) const {
3357 return getSuccessor(idx);
3359 unsigned IndirectBrInst::getNumSuccessorsV() const {
3360 return getNumSuccessors();
3362 void IndirectBrInst::setSuccessorV(unsigned idx, BasicBlock *B) {
3363 setSuccessor(idx, B);
3366 //===----------------------------------------------------------------------===//
3367 // clone_impl() implementations
3368 //===----------------------------------------------------------------------===//
3370 // Define these methods here so vtables don't get emitted into every translation
3371 // unit that uses these classes.
3373 GetElementPtrInst *GetElementPtrInst::clone_impl() const {
3374 return new (getNumOperands()) GetElementPtrInst(*this);
3377 BinaryOperator *BinaryOperator::clone_impl() const {
3378 return Create(getOpcode(), Op<0>(), Op<1>());
3381 FCmpInst* FCmpInst::clone_impl() const {
3382 return new FCmpInst(getPredicate(), Op<0>(), Op<1>());
3385 ICmpInst* ICmpInst::clone_impl() const {
3386 return new ICmpInst(getPredicate(), Op<0>(), Op<1>());
3389 ExtractValueInst *ExtractValueInst::clone_impl() const {
3390 return new ExtractValueInst(*this);
3393 InsertValueInst *InsertValueInst::clone_impl() const {
3394 return new InsertValueInst(*this);
3397 AllocaInst *AllocaInst::clone_impl() const {
3398 return new AllocaInst(getAllocatedType(),
3399 (Value*)getOperand(0),
3403 LoadInst *LoadInst::clone_impl() const {
3404 return new LoadInst(getOperand(0), Twine(), isVolatile(),
3405 getAlignment(), getOrdering(), getSynchScope());
3408 StoreInst *StoreInst::clone_impl() const {
3409 return new StoreInst(getOperand(0), getOperand(1), isVolatile(),
3410 getAlignment(), getOrdering(), getSynchScope());
3414 AtomicCmpXchgInst *AtomicCmpXchgInst::clone_impl() const {
3415 AtomicCmpXchgInst *Result =
3416 new AtomicCmpXchgInst(getOperand(0), getOperand(1), getOperand(2),
3417 getOrdering(), getSynchScope());
3418 Result->setVolatile(isVolatile());
3422 AtomicRMWInst *AtomicRMWInst::clone_impl() const {
3423 AtomicRMWInst *Result =
3424 new AtomicRMWInst(getOperation(),getOperand(0), getOperand(1),
3425 getOrdering(), getSynchScope());
3426 Result->setVolatile(isVolatile());
3430 FenceInst *FenceInst::clone_impl() const {
3431 return new FenceInst(getContext(), getOrdering(), getSynchScope());
3434 TruncInst *TruncInst::clone_impl() const {
3435 return new TruncInst(getOperand(0), getType());
3438 ZExtInst *ZExtInst::clone_impl() const {
3439 return new ZExtInst(getOperand(0), getType());
3442 SExtInst *SExtInst::clone_impl() const {
3443 return new SExtInst(getOperand(0), getType());
3446 FPTruncInst *FPTruncInst::clone_impl() const {
3447 return new FPTruncInst(getOperand(0), getType());
3450 FPExtInst *FPExtInst::clone_impl() const {
3451 return new FPExtInst(getOperand(0), getType());
3454 UIToFPInst *UIToFPInst::clone_impl() const {
3455 return new UIToFPInst(getOperand(0), getType());
3458 SIToFPInst *SIToFPInst::clone_impl() const {
3459 return new SIToFPInst(getOperand(0), getType());
3462 FPToUIInst *FPToUIInst::clone_impl() const {
3463 return new FPToUIInst(getOperand(0), getType());
3466 FPToSIInst *FPToSIInst::clone_impl() const {
3467 return new FPToSIInst(getOperand(0), getType());
3470 PtrToIntInst *PtrToIntInst::clone_impl() const {
3471 return new PtrToIntInst(getOperand(0), getType());
3474 IntToPtrInst *IntToPtrInst::clone_impl() const {
3475 return new IntToPtrInst(getOperand(0), getType());
3478 BitCastInst *BitCastInst::clone_impl() const {
3479 return new BitCastInst(getOperand(0), getType());
3482 CallInst *CallInst::clone_impl() const {
3483 return new(getNumOperands()) CallInst(*this);
3486 SelectInst *SelectInst::clone_impl() const {
3487 return SelectInst::Create(getOperand(0), getOperand(1), getOperand(2));
3490 VAArgInst *VAArgInst::clone_impl() const {
3491 return new VAArgInst(getOperand(0), getType());
3494 ExtractElementInst *ExtractElementInst::clone_impl() const {
3495 return ExtractElementInst::Create(getOperand(0), getOperand(1));
3498 InsertElementInst *InsertElementInst::clone_impl() const {
3499 return InsertElementInst::Create(getOperand(0), getOperand(1), getOperand(2));
3502 ShuffleVectorInst *ShuffleVectorInst::clone_impl() const {
3503 return new ShuffleVectorInst(getOperand(0), getOperand(1), getOperand(2));
3506 PHINode *PHINode::clone_impl() const {
3507 return new PHINode(*this);
3510 LandingPadInst *LandingPadInst::clone_impl() const {
3511 return new LandingPadInst(*this);
3514 ReturnInst *ReturnInst::clone_impl() const {
3515 return new(getNumOperands()) ReturnInst(*this);
3518 BranchInst *BranchInst::clone_impl() const {
3519 return new(getNumOperands()) BranchInst(*this);
3522 SwitchInst *SwitchInst::clone_impl() const {
3523 return new SwitchInst(*this);
3526 IndirectBrInst *IndirectBrInst::clone_impl() const {
3527 return new IndirectBrInst(*this);
3531 InvokeInst *InvokeInst::clone_impl() const {
3532 return new(getNumOperands()) InvokeInst(*this);
3535 ResumeInst *ResumeInst::clone_impl() const {
3536 return new(1) ResumeInst(*this);
3539 UnreachableInst *UnreachableInst::clone_impl() const {
3540 LLVMContext &Context = getContext();
3541 return new UnreachableInst(Context);