1 //===-- Instructions.cpp - Implement the LLVM instructions ----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements all of the non-inline methods for the LLVM instruction
13 //===----------------------------------------------------------------------===//
15 #include "LLVMContextImpl.h"
16 #include "llvm/Constants.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/Function.h"
19 #include "llvm/Instructions.h"
20 #include "llvm/Module.h"
21 #include "llvm/Operator.h"
22 #include "llvm/Support/ErrorHandling.h"
23 #include "llvm/Support/CallSite.h"
24 #include "llvm/Support/ConstantRange.h"
25 #include "llvm/Support/MathExtras.h"
28 //===----------------------------------------------------------------------===//
30 //===----------------------------------------------------------------------===//
32 User::op_iterator CallSite::getCallee() const {
33 Instruction *II(getInstruction());
35 ? cast<CallInst>(II)->op_end() - 1 // Skip Callee
36 : cast<InvokeInst>(II)->op_end() - 3; // Skip BB, BB, Callee
39 //===----------------------------------------------------------------------===//
40 // TerminatorInst Class
41 //===----------------------------------------------------------------------===//
43 // Out of line virtual method, so the vtable, etc has a home.
44 TerminatorInst::~TerminatorInst() {
47 //===----------------------------------------------------------------------===//
48 // UnaryInstruction Class
49 //===----------------------------------------------------------------------===//
51 // Out of line virtual method, so the vtable, etc has a home.
52 UnaryInstruction::~UnaryInstruction() {
55 //===----------------------------------------------------------------------===//
57 //===----------------------------------------------------------------------===//
59 /// areInvalidOperands - Return a string if the specified operands are invalid
60 /// for a select operation, otherwise return null.
61 const char *SelectInst::areInvalidOperands(Value *Op0, Value *Op1, Value *Op2) {
62 if (Op1->getType() != Op2->getType())
63 return "both values to select must have same type";
65 if (VectorType *VT = dyn_cast<VectorType>(Op0->getType())) {
67 if (VT->getElementType() != Type::getInt1Ty(Op0->getContext()))
68 return "vector select condition element type must be i1";
69 VectorType *ET = dyn_cast<VectorType>(Op1->getType());
71 return "selected values for vector select must be vectors";
72 if (ET->getNumElements() != VT->getNumElements())
73 return "vector select requires selected vectors to have "
74 "the same vector length as select condition";
75 } else if (Op0->getType() != Type::getInt1Ty(Op0->getContext())) {
76 return "select condition must be i1 or <n x i1>";
82 //===----------------------------------------------------------------------===//
84 //===----------------------------------------------------------------------===//
86 PHINode::PHINode(const PHINode &PN)
87 : Instruction(PN.getType(), Instruction::PHI,
88 allocHungoffUses(PN.getNumOperands()), PN.getNumOperands()),
89 ReservedSpace(PN.getNumOperands()) {
90 std::copy(PN.op_begin(), PN.op_end(), op_begin());
91 std::copy(PN.block_begin(), PN.block_end(), block_begin());
92 SubclassOptionalData = PN.SubclassOptionalData;
99 Use *PHINode::allocHungoffUses(unsigned N) const {
100 // Allocate the array of Uses of the incoming values, followed by a pointer
101 // (with bottom bit set) to the User, followed by the array of pointers to
102 // the incoming basic blocks.
103 size_t size = N * sizeof(Use) + sizeof(Use::UserRef)
104 + N * sizeof(BasicBlock*);
105 Use *Begin = static_cast<Use*>(::operator new(size));
106 Use *End = Begin + N;
107 (void) new(End) Use::UserRef(const_cast<PHINode*>(this), 1);
108 return Use::initTags(Begin, End);
111 // removeIncomingValue - Remove an incoming value. This is useful if a
112 // predecessor basic block is deleted.
113 Value *PHINode::removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty) {
114 Value *Removed = getIncomingValue(Idx);
116 // Move everything after this operand down.
118 // FIXME: we could just swap with the end of the list, then erase. However,
119 // clients might not expect this to happen. The code as it is thrashes the
120 // use/def lists, which is kinda lame.
121 std::copy(op_begin() + Idx + 1, op_end(), op_begin() + Idx);
122 std::copy(block_begin() + Idx + 1, block_end(), block_begin() + Idx);
124 // Nuke the last value.
128 // If the PHI node is dead, because it has zero entries, nuke it now.
129 if (getNumOperands() == 0 && DeletePHIIfEmpty) {
130 // If anyone is using this PHI, make them use a dummy value instead...
131 replaceAllUsesWith(UndefValue::get(getType()));
137 /// growOperands - grow operands - This grows the operand list in response
138 /// to a push_back style of operation. This grows the number of ops by 1.5
141 void PHINode::growOperands() {
142 unsigned e = getNumOperands();
143 unsigned NumOps = e + e / 2;
144 if (NumOps < 2) NumOps = 2; // 2 op PHI nodes are VERY common.
146 Use *OldOps = op_begin();
147 BasicBlock **OldBlocks = block_begin();
149 ReservedSpace = NumOps;
150 OperandList = allocHungoffUses(ReservedSpace);
152 std::copy(OldOps, OldOps + e, op_begin());
153 std::copy(OldBlocks, OldBlocks + e, block_begin());
155 Use::zap(OldOps, OldOps + e, true);
158 /// hasConstantValue - If the specified PHI node always merges together the same
159 /// value, return the value, otherwise return null.
160 Value *PHINode::hasConstantValue() const {
161 // Exploit the fact that phi nodes always have at least one entry.
162 Value *ConstantValue = getIncomingValue(0);
163 for (unsigned i = 1, e = getNumIncomingValues(); i != e; ++i)
164 if (getIncomingValue(i) != ConstantValue && getIncomingValue(i) != this) {
165 if (ConstantValue != this)
166 return 0; // Incoming values not all the same.
167 // The case where the first value is this PHI.
168 ConstantValue = getIncomingValue(i);
170 if (ConstantValue == this)
171 return UndefValue::get(getType());
172 return ConstantValue;
175 //===----------------------------------------------------------------------===//
176 // LandingPadInst Implementation
177 //===----------------------------------------------------------------------===//
179 LandingPadInst::LandingPadInst(Type *RetTy, Value *PersonalityFn,
180 unsigned NumReservedValues, const Twine &NameStr,
181 Instruction *InsertBefore)
182 : Instruction(RetTy, Instruction::LandingPad, 0, 0, InsertBefore) {
183 init(PersonalityFn, 1 + NumReservedValues, NameStr);
186 LandingPadInst::LandingPadInst(Type *RetTy, Value *PersonalityFn,
187 unsigned NumReservedValues, const Twine &NameStr,
188 BasicBlock *InsertAtEnd)
189 : Instruction(RetTy, Instruction::LandingPad, 0, 0, InsertAtEnd) {
190 init(PersonalityFn, 1 + NumReservedValues, NameStr);
193 LandingPadInst::LandingPadInst(const LandingPadInst &LP)
194 : Instruction(LP.getType(), Instruction::LandingPad,
195 allocHungoffUses(LP.getNumOperands()), LP.getNumOperands()),
196 ReservedSpace(LP.getNumOperands()) {
197 Use *OL = OperandList, *InOL = LP.OperandList;
198 for (unsigned I = 0, E = ReservedSpace; I != E; ++I)
201 setCleanup(LP.isCleanup());
204 LandingPadInst::~LandingPadInst() {
208 LandingPadInst *LandingPadInst::Create(Type *RetTy, Value *PersonalityFn,
209 unsigned NumReservedClauses,
210 const Twine &NameStr,
211 Instruction *InsertBefore) {
212 return new LandingPadInst(RetTy, PersonalityFn, NumReservedClauses, NameStr,
216 LandingPadInst *LandingPadInst::Create(Type *RetTy, Value *PersonalityFn,
217 unsigned NumReservedClauses,
218 const Twine &NameStr,
219 BasicBlock *InsertAtEnd) {
220 return new LandingPadInst(RetTy, PersonalityFn, NumReservedClauses, NameStr,
224 void LandingPadInst::init(Value *PersFn, unsigned NumReservedValues,
225 const Twine &NameStr) {
226 ReservedSpace = NumReservedValues;
228 OperandList = allocHungoffUses(ReservedSpace);
229 OperandList[0] = PersFn;
234 /// growOperands - grow operands - This grows the operand list in response to a
235 /// push_back style of operation. This grows the number of ops by 2 times.
236 void LandingPadInst::growOperands(unsigned Size) {
237 unsigned e = getNumOperands();
238 if (ReservedSpace >= e + Size) return;
239 ReservedSpace = (e + Size / 2) * 2;
241 Use *NewOps = allocHungoffUses(ReservedSpace);
242 Use *OldOps = OperandList;
243 for (unsigned i = 0; i != e; ++i)
244 NewOps[i] = OldOps[i];
246 OperandList = NewOps;
247 Use::zap(OldOps, OldOps + e, true);
250 void LandingPadInst::addClause(Value *Val) {
251 unsigned OpNo = getNumOperands();
253 assert(OpNo < ReservedSpace && "Growing didn't work!");
255 OperandList[OpNo] = Val;
258 //===----------------------------------------------------------------------===//
259 // CallInst Implementation
260 //===----------------------------------------------------------------------===//
262 CallInst::~CallInst() {
265 void CallInst::init(Value *Func, ArrayRef<Value *> Args, const Twine &NameStr) {
266 assert(NumOperands == Args.size() + 1 && "NumOperands not set up?");
271 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
273 assert((Args.size() == FTy->getNumParams() ||
274 (FTy->isVarArg() && Args.size() > FTy->getNumParams())) &&
275 "Calling a function with bad signature!");
277 for (unsigned i = 0; i != Args.size(); ++i)
278 assert((i >= FTy->getNumParams() ||
279 FTy->getParamType(i) == Args[i]->getType()) &&
280 "Calling a function with a bad signature!");
283 std::copy(Args.begin(), Args.end(), op_begin());
287 void CallInst::init(Value *Func, const Twine &NameStr) {
288 assert(NumOperands == 1 && "NumOperands not set up?");
293 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
295 assert(FTy->getNumParams() == 0 && "Calling a function with bad signature");
301 CallInst::CallInst(Value *Func, const Twine &Name,
302 Instruction *InsertBefore)
303 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
304 ->getElementType())->getReturnType(),
306 OperandTraits<CallInst>::op_end(this) - 1,
311 CallInst::CallInst(Value *Func, const Twine &Name,
312 BasicBlock *InsertAtEnd)
313 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
314 ->getElementType())->getReturnType(),
316 OperandTraits<CallInst>::op_end(this) - 1,
321 CallInst::CallInst(const CallInst &CI)
322 : Instruction(CI.getType(), Instruction::Call,
323 OperandTraits<CallInst>::op_end(this) - CI.getNumOperands(),
324 CI.getNumOperands()) {
325 setAttributes(CI.getAttributes());
326 setTailCall(CI.isTailCall());
327 setCallingConv(CI.getCallingConv());
329 std::copy(CI.op_begin(), CI.op_end(), op_begin());
330 SubclassOptionalData = CI.SubclassOptionalData;
333 void CallInst::addAttribute(unsigned i, Attributes attr) {
334 AttrListPtr PAL = getAttributes();
335 PAL = PAL.addAttr(i, attr);
339 void CallInst::removeAttribute(unsigned i, Attributes attr) {
340 AttrListPtr PAL = getAttributes();
341 PAL = PAL.removeAttr(i, attr);
345 bool CallInst::paramHasSExtAttr(unsigned i) const {
346 if (AttributeList.getParamAttributes(i).hasSExtAttr())
348 if (const Function *F = getCalledFunction())
349 return F->getParamAttributes(i).hasSExtAttr();
353 bool CallInst::paramHasZExtAttr(unsigned i) const {
354 if (AttributeList.getParamAttributes(i).hasZExtAttr())
356 if (const Function *F = getCalledFunction())
357 return F->getParamAttributes(i).hasZExtAttr();
361 bool CallInst::paramHasInRegAttr(unsigned i) const {
362 if (AttributeList.getParamAttributes(i).hasInRegAttr())
364 if (const Function *F = getCalledFunction())
365 return F->getParamAttributes(i).hasInRegAttr();
369 bool CallInst::paramHasStructRetAttr(unsigned i) const {
370 if (AttributeList.getParamAttributes(i).hasStructRetAttr())
372 if (const Function *F = getCalledFunction())
373 return F->getParamAttributes(i).hasStructRetAttr();
377 bool CallInst::paramHasNestAttr(unsigned i) const {
378 if (AttributeList.getParamAttributes(i).hasNestAttr())
380 if (const Function *F = getCalledFunction())
381 return F->getParamAttributes(i).hasNestAttr();
385 bool CallInst::paramHasByValAttr(unsigned i) const {
386 if (AttributeList.getParamAttributes(i).hasByValAttr())
388 if (const Function *F = getCalledFunction())
389 return F->getParamAttributes(i).hasByValAttr();
393 bool CallInst::paramHasAttr(unsigned i, Attributes attr) const {
394 if (AttributeList.paramHasAttr(i, attr))
396 if (const Function *F = getCalledFunction())
397 return F->paramHasAttr(i, attr);
401 /// IsConstantOne - Return true only if val is constant int 1
402 static bool IsConstantOne(Value *val) {
403 assert(val && "IsConstantOne does not work with NULL val");
404 return isa<ConstantInt>(val) && cast<ConstantInt>(val)->isOne();
407 static Instruction *createMalloc(Instruction *InsertBefore,
408 BasicBlock *InsertAtEnd, Type *IntPtrTy,
409 Type *AllocTy, Value *AllocSize,
410 Value *ArraySize, Function *MallocF,
412 assert(((!InsertBefore && InsertAtEnd) || (InsertBefore && !InsertAtEnd)) &&
413 "createMalloc needs either InsertBefore or InsertAtEnd");
415 // malloc(type) becomes:
416 // bitcast (i8* malloc(typeSize)) to type*
417 // malloc(type, arraySize) becomes:
418 // bitcast (i8 *malloc(typeSize*arraySize)) to type*
420 ArraySize = ConstantInt::get(IntPtrTy, 1);
421 else if (ArraySize->getType() != IntPtrTy) {
423 ArraySize = CastInst::CreateIntegerCast(ArraySize, IntPtrTy, false,
426 ArraySize = CastInst::CreateIntegerCast(ArraySize, IntPtrTy, false,
430 if (!IsConstantOne(ArraySize)) {
431 if (IsConstantOne(AllocSize)) {
432 AllocSize = ArraySize; // Operand * 1 = Operand
433 } else if (Constant *CO = dyn_cast<Constant>(ArraySize)) {
434 Constant *Scale = ConstantExpr::getIntegerCast(CO, IntPtrTy,
436 // Malloc arg is constant product of type size and array size
437 AllocSize = ConstantExpr::getMul(Scale, cast<Constant>(AllocSize));
439 // Multiply type size by the array size...
441 AllocSize = BinaryOperator::CreateMul(ArraySize, AllocSize,
442 "mallocsize", InsertBefore);
444 AllocSize = BinaryOperator::CreateMul(ArraySize, AllocSize,
445 "mallocsize", InsertAtEnd);
449 assert(AllocSize->getType() == IntPtrTy && "malloc arg is wrong size");
450 // Create the call to Malloc.
451 BasicBlock* BB = InsertBefore ? InsertBefore->getParent() : InsertAtEnd;
452 Module* M = BB->getParent()->getParent();
453 Type *BPTy = Type::getInt8PtrTy(BB->getContext());
454 Value *MallocFunc = MallocF;
456 // prototype malloc as "void *malloc(size_t)"
457 MallocFunc = M->getOrInsertFunction("malloc", BPTy, IntPtrTy, NULL);
458 PointerType *AllocPtrType = PointerType::getUnqual(AllocTy);
459 CallInst *MCall = NULL;
460 Instruction *Result = NULL;
462 MCall = CallInst::Create(MallocFunc, AllocSize, "malloccall", InsertBefore);
464 if (Result->getType() != AllocPtrType)
465 // Create a cast instruction to convert to the right type...
466 Result = new BitCastInst(MCall, AllocPtrType, Name, InsertBefore);
468 MCall = CallInst::Create(MallocFunc, AllocSize, "malloccall");
470 if (Result->getType() != AllocPtrType) {
471 InsertAtEnd->getInstList().push_back(MCall);
472 // Create a cast instruction to convert to the right type...
473 Result = new BitCastInst(MCall, AllocPtrType, Name);
476 MCall->setTailCall();
477 if (Function *F = dyn_cast<Function>(MallocFunc)) {
478 MCall->setCallingConv(F->getCallingConv());
479 if (!F->doesNotAlias(0)) F->setDoesNotAlias(0);
481 assert(!MCall->getType()->isVoidTy() && "Malloc has void return type");
486 /// CreateMalloc - Generate the IR for a call to malloc:
487 /// 1. Compute the malloc call's argument as the specified type's size,
488 /// possibly multiplied by the array size if the array size is not
490 /// 2. Call malloc with that argument.
491 /// 3. Bitcast the result of the malloc call to the specified type.
492 Instruction *CallInst::CreateMalloc(Instruction *InsertBefore,
493 Type *IntPtrTy, Type *AllocTy,
494 Value *AllocSize, Value *ArraySize,
497 return createMalloc(InsertBefore, NULL, IntPtrTy, AllocTy, AllocSize,
498 ArraySize, MallocF, Name);
501 /// CreateMalloc - Generate the IR for a call to malloc:
502 /// 1. Compute the malloc call's argument as the specified type's size,
503 /// possibly multiplied by the array size if the array size is not
505 /// 2. Call malloc with that argument.
506 /// 3. Bitcast the result of the malloc call to the specified type.
507 /// Note: This function does not add the bitcast to the basic block, that is the
508 /// responsibility of the caller.
509 Instruction *CallInst::CreateMalloc(BasicBlock *InsertAtEnd,
510 Type *IntPtrTy, Type *AllocTy,
511 Value *AllocSize, Value *ArraySize,
512 Function *MallocF, const Twine &Name) {
513 return createMalloc(NULL, InsertAtEnd, IntPtrTy, AllocTy, AllocSize,
514 ArraySize, MallocF, Name);
517 static Instruction* createFree(Value* Source, Instruction *InsertBefore,
518 BasicBlock *InsertAtEnd) {
519 assert(((!InsertBefore && InsertAtEnd) || (InsertBefore && !InsertAtEnd)) &&
520 "createFree needs either InsertBefore or InsertAtEnd");
521 assert(Source->getType()->isPointerTy() &&
522 "Can not free something of nonpointer type!");
524 BasicBlock* BB = InsertBefore ? InsertBefore->getParent() : InsertAtEnd;
525 Module* M = BB->getParent()->getParent();
527 Type *VoidTy = Type::getVoidTy(M->getContext());
528 Type *IntPtrTy = Type::getInt8PtrTy(M->getContext());
529 // prototype free as "void free(void*)"
530 Value *FreeFunc = M->getOrInsertFunction("free", VoidTy, IntPtrTy, NULL);
531 CallInst* Result = NULL;
532 Value *PtrCast = Source;
534 if (Source->getType() != IntPtrTy)
535 PtrCast = new BitCastInst(Source, IntPtrTy, "", InsertBefore);
536 Result = CallInst::Create(FreeFunc, PtrCast, "", InsertBefore);
538 if (Source->getType() != IntPtrTy)
539 PtrCast = new BitCastInst(Source, IntPtrTy, "", InsertAtEnd);
540 Result = CallInst::Create(FreeFunc, PtrCast, "");
542 Result->setTailCall();
543 if (Function *F = dyn_cast<Function>(FreeFunc))
544 Result->setCallingConv(F->getCallingConv());
549 /// CreateFree - Generate the IR for a call to the builtin free function.
550 Instruction * CallInst::CreateFree(Value* Source, Instruction *InsertBefore) {
551 return createFree(Source, InsertBefore, NULL);
554 /// CreateFree - Generate the IR for a call to the builtin free function.
555 /// Note: This function does not add the call to the basic block, that is the
556 /// responsibility of the caller.
557 Instruction* CallInst::CreateFree(Value* Source, BasicBlock *InsertAtEnd) {
558 Instruction* FreeCall = createFree(Source, NULL, InsertAtEnd);
559 assert(FreeCall && "CreateFree did not create a CallInst");
563 //===----------------------------------------------------------------------===//
564 // InvokeInst Implementation
565 //===----------------------------------------------------------------------===//
567 void InvokeInst::init(Value *Fn, BasicBlock *IfNormal, BasicBlock *IfException,
568 ArrayRef<Value *> Args, const Twine &NameStr) {
569 assert(NumOperands == 3 + Args.size() && "NumOperands not set up?");
572 Op<-1>() = IfException;
576 cast<FunctionType>(cast<PointerType>(Fn->getType())->getElementType());
578 assert(((Args.size() == FTy->getNumParams()) ||
579 (FTy->isVarArg() && Args.size() > FTy->getNumParams())) &&
580 "Invoking a function with bad signature");
582 for (unsigned i = 0, e = Args.size(); i != e; i++)
583 assert((i >= FTy->getNumParams() ||
584 FTy->getParamType(i) == Args[i]->getType()) &&
585 "Invoking a function with a bad signature!");
588 std::copy(Args.begin(), Args.end(), op_begin());
592 InvokeInst::InvokeInst(const InvokeInst &II)
593 : TerminatorInst(II.getType(), Instruction::Invoke,
594 OperandTraits<InvokeInst>::op_end(this)
595 - II.getNumOperands(),
596 II.getNumOperands()) {
597 setAttributes(II.getAttributes());
598 setCallingConv(II.getCallingConv());
599 std::copy(II.op_begin(), II.op_end(), op_begin());
600 SubclassOptionalData = II.SubclassOptionalData;
603 BasicBlock *InvokeInst::getSuccessorV(unsigned idx) const {
604 return getSuccessor(idx);
606 unsigned InvokeInst::getNumSuccessorsV() const {
607 return getNumSuccessors();
609 void InvokeInst::setSuccessorV(unsigned idx, BasicBlock *B) {
610 return setSuccessor(idx, B);
613 bool InvokeInst::paramHasSExtAttr(unsigned i) const {
614 if (AttributeList.getParamAttributes(i).hasSExtAttr())
616 if (const Function *F = getCalledFunction())
617 return F->getParamAttributes(i).hasSExtAttr();
621 bool InvokeInst::paramHasZExtAttr(unsigned i) const {
622 if (AttributeList.getParamAttributes(i).hasZExtAttr())
624 if (const Function *F = getCalledFunction())
625 return F->getParamAttributes(i).hasZExtAttr();
629 bool InvokeInst::paramHasInRegAttr(unsigned i) const {
630 if (AttributeList.getParamAttributes(i).hasInRegAttr())
632 if (const Function *F = getCalledFunction())
633 return F->getParamAttributes(i).hasInRegAttr();
637 bool InvokeInst::paramHasStructRetAttr(unsigned i) const {
638 if (AttributeList.getParamAttributes(i).hasStructRetAttr())
640 if (const Function *F = getCalledFunction())
641 return F->getParamAttributes(i).hasStructRetAttr();
645 bool InvokeInst::paramHasNestAttr(unsigned i) const {
646 if (AttributeList.getParamAttributes(i).hasNestAttr())
648 if (const Function *F = getCalledFunction())
649 return F->getParamAttributes(i).hasNestAttr();
653 bool InvokeInst::paramHasByValAttr(unsigned i) const {
654 if (AttributeList.getParamAttributes(i).hasByValAttr())
656 if (const Function *F = getCalledFunction())
657 return F->getParamAttributes(i).hasByValAttr();
661 bool InvokeInst::paramHasAttr(unsigned i, Attributes attr) const {
662 if (AttributeList.paramHasAttr(i, attr))
664 if (const Function *F = getCalledFunction())
665 return F->paramHasAttr(i, attr);
669 void InvokeInst::addAttribute(unsigned i, Attributes attr) {
670 AttrListPtr PAL = getAttributes();
671 PAL = PAL.addAttr(i, attr);
675 void InvokeInst::removeAttribute(unsigned i, Attributes attr) {
676 AttrListPtr PAL = getAttributes();
677 PAL = PAL.removeAttr(i, attr);
681 LandingPadInst *InvokeInst::getLandingPadInst() const {
682 return cast<LandingPadInst>(getUnwindDest()->getFirstNonPHI());
685 //===----------------------------------------------------------------------===//
686 // ReturnInst Implementation
687 //===----------------------------------------------------------------------===//
689 ReturnInst::ReturnInst(const ReturnInst &RI)
690 : TerminatorInst(Type::getVoidTy(RI.getContext()), Instruction::Ret,
691 OperandTraits<ReturnInst>::op_end(this) -
693 RI.getNumOperands()) {
694 if (RI.getNumOperands())
695 Op<0>() = RI.Op<0>();
696 SubclassOptionalData = RI.SubclassOptionalData;
699 ReturnInst::ReturnInst(LLVMContext &C, Value *retVal, Instruction *InsertBefore)
700 : TerminatorInst(Type::getVoidTy(C), Instruction::Ret,
701 OperandTraits<ReturnInst>::op_end(this) - !!retVal, !!retVal,
706 ReturnInst::ReturnInst(LLVMContext &C, Value *retVal, BasicBlock *InsertAtEnd)
707 : TerminatorInst(Type::getVoidTy(C), Instruction::Ret,
708 OperandTraits<ReturnInst>::op_end(this) - !!retVal, !!retVal,
713 ReturnInst::ReturnInst(LLVMContext &Context, BasicBlock *InsertAtEnd)
714 : TerminatorInst(Type::getVoidTy(Context), Instruction::Ret,
715 OperandTraits<ReturnInst>::op_end(this), 0, InsertAtEnd) {
718 unsigned ReturnInst::getNumSuccessorsV() const {
719 return getNumSuccessors();
722 /// Out-of-line ReturnInst method, put here so the C++ compiler can choose to
723 /// emit the vtable for the class in this translation unit.
724 void ReturnInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
725 llvm_unreachable("ReturnInst has no successors!");
728 BasicBlock *ReturnInst::getSuccessorV(unsigned idx) const {
729 llvm_unreachable("ReturnInst has no successors!");
732 ReturnInst::~ReturnInst() {
735 //===----------------------------------------------------------------------===//
736 // ResumeInst Implementation
737 //===----------------------------------------------------------------------===//
739 ResumeInst::ResumeInst(const ResumeInst &RI)
740 : TerminatorInst(Type::getVoidTy(RI.getContext()), Instruction::Resume,
741 OperandTraits<ResumeInst>::op_begin(this), 1) {
742 Op<0>() = RI.Op<0>();
745 ResumeInst::ResumeInst(Value *Exn, Instruction *InsertBefore)
746 : TerminatorInst(Type::getVoidTy(Exn->getContext()), Instruction::Resume,
747 OperandTraits<ResumeInst>::op_begin(this), 1, InsertBefore) {
751 ResumeInst::ResumeInst(Value *Exn, BasicBlock *InsertAtEnd)
752 : TerminatorInst(Type::getVoidTy(Exn->getContext()), Instruction::Resume,
753 OperandTraits<ResumeInst>::op_begin(this), 1, InsertAtEnd) {
757 unsigned ResumeInst::getNumSuccessorsV() const {
758 return getNumSuccessors();
761 void ResumeInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
762 llvm_unreachable("ResumeInst has no successors!");
765 BasicBlock *ResumeInst::getSuccessorV(unsigned idx) const {
766 llvm_unreachable("ResumeInst has no successors!");
769 //===----------------------------------------------------------------------===//
770 // UnreachableInst Implementation
771 //===----------------------------------------------------------------------===//
773 UnreachableInst::UnreachableInst(LLVMContext &Context,
774 Instruction *InsertBefore)
775 : TerminatorInst(Type::getVoidTy(Context), Instruction::Unreachable,
776 0, 0, InsertBefore) {
778 UnreachableInst::UnreachableInst(LLVMContext &Context, BasicBlock *InsertAtEnd)
779 : TerminatorInst(Type::getVoidTy(Context), Instruction::Unreachable,
783 unsigned UnreachableInst::getNumSuccessorsV() const {
784 return getNumSuccessors();
787 void UnreachableInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
788 llvm_unreachable("UnreachableInst has no successors!");
791 BasicBlock *UnreachableInst::getSuccessorV(unsigned idx) const {
792 llvm_unreachable("UnreachableInst has no successors!");
795 //===----------------------------------------------------------------------===//
796 // BranchInst Implementation
797 //===----------------------------------------------------------------------===//
799 void BranchInst::AssertOK() {
801 assert(getCondition()->getType()->isIntegerTy(1) &&
802 "May only branch on boolean predicates!");
805 BranchInst::BranchInst(BasicBlock *IfTrue, Instruction *InsertBefore)
806 : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
807 OperandTraits<BranchInst>::op_end(this) - 1,
809 assert(IfTrue != 0 && "Branch destination may not be null!");
812 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
813 Instruction *InsertBefore)
814 : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
815 OperandTraits<BranchInst>::op_end(this) - 3,
825 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *InsertAtEnd)
826 : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
827 OperandTraits<BranchInst>::op_end(this) - 1,
829 assert(IfTrue != 0 && "Branch destination may not be null!");
833 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
834 BasicBlock *InsertAtEnd)
835 : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
836 OperandTraits<BranchInst>::op_end(this) - 3,
847 BranchInst::BranchInst(const BranchInst &BI) :
848 TerminatorInst(Type::getVoidTy(BI.getContext()), Instruction::Br,
849 OperandTraits<BranchInst>::op_end(this) - BI.getNumOperands(),
850 BI.getNumOperands()) {
851 Op<-1>() = BI.Op<-1>();
852 if (BI.getNumOperands() != 1) {
853 assert(BI.getNumOperands() == 3 && "BR can have 1 or 3 operands!");
854 Op<-3>() = BI.Op<-3>();
855 Op<-2>() = BI.Op<-2>();
857 SubclassOptionalData = BI.SubclassOptionalData;
860 void BranchInst::swapSuccessors() {
861 assert(isConditional() &&
862 "Cannot swap successors of an unconditional branch");
863 Op<-1>().swap(Op<-2>());
865 // Update profile metadata if present and it matches our structural
867 MDNode *ProfileData = getMetadata(LLVMContext::MD_prof);
868 if (!ProfileData || ProfileData->getNumOperands() != 3)
871 // The first operand is the name. Fetch them backwards and build a new one.
873 ProfileData->getOperand(0),
874 ProfileData->getOperand(2),
875 ProfileData->getOperand(1)
877 setMetadata(LLVMContext::MD_prof,
878 MDNode::get(ProfileData->getContext(), Ops));
881 BasicBlock *BranchInst::getSuccessorV(unsigned idx) const {
882 return getSuccessor(idx);
884 unsigned BranchInst::getNumSuccessorsV() const {
885 return getNumSuccessors();
887 void BranchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
888 setSuccessor(idx, B);
892 //===----------------------------------------------------------------------===//
893 // AllocaInst Implementation
894 //===----------------------------------------------------------------------===//
896 static Value *getAISize(LLVMContext &Context, Value *Amt) {
898 Amt = ConstantInt::get(Type::getInt32Ty(Context), 1);
900 assert(!isa<BasicBlock>(Amt) &&
901 "Passed basic block into allocation size parameter! Use other ctor");
902 assert(Amt->getType()->isIntegerTy() &&
903 "Allocation array size is not an integer!");
908 AllocaInst::AllocaInst(Type *Ty, Value *ArraySize,
909 const Twine &Name, Instruction *InsertBefore)
910 : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
911 getAISize(Ty->getContext(), ArraySize), InsertBefore) {
913 assert(!Ty->isVoidTy() && "Cannot allocate void!");
917 AllocaInst::AllocaInst(Type *Ty, Value *ArraySize,
918 const Twine &Name, BasicBlock *InsertAtEnd)
919 : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
920 getAISize(Ty->getContext(), ArraySize), InsertAtEnd) {
922 assert(!Ty->isVoidTy() && "Cannot allocate void!");
926 AllocaInst::AllocaInst(Type *Ty, const Twine &Name,
927 Instruction *InsertBefore)
928 : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
929 getAISize(Ty->getContext(), 0), InsertBefore) {
931 assert(!Ty->isVoidTy() && "Cannot allocate void!");
935 AllocaInst::AllocaInst(Type *Ty, const Twine &Name,
936 BasicBlock *InsertAtEnd)
937 : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
938 getAISize(Ty->getContext(), 0), InsertAtEnd) {
940 assert(!Ty->isVoidTy() && "Cannot allocate void!");
944 AllocaInst::AllocaInst(Type *Ty, Value *ArraySize, unsigned Align,
945 const Twine &Name, Instruction *InsertBefore)
946 : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
947 getAISize(Ty->getContext(), ArraySize), InsertBefore) {
949 assert(!Ty->isVoidTy() && "Cannot allocate void!");
953 AllocaInst::AllocaInst(Type *Ty, Value *ArraySize, unsigned Align,
954 const Twine &Name, BasicBlock *InsertAtEnd)
955 : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
956 getAISize(Ty->getContext(), ArraySize), InsertAtEnd) {
958 assert(!Ty->isVoidTy() && "Cannot allocate void!");
962 // Out of line virtual method, so the vtable, etc has a home.
963 AllocaInst::~AllocaInst() {
966 void AllocaInst::setAlignment(unsigned Align) {
967 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
968 assert(Align <= MaximumAlignment &&
969 "Alignment is greater than MaximumAlignment!");
970 setInstructionSubclassData(Log2_32(Align) + 1);
971 assert(getAlignment() == Align && "Alignment representation error!");
974 bool AllocaInst::isArrayAllocation() const {
975 if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(0)))
980 Type *AllocaInst::getAllocatedType() const {
981 return getType()->getElementType();
984 /// isStaticAlloca - Return true if this alloca is in the entry block of the
985 /// function and is a constant size. If so, the code generator will fold it
986 /// into the prolog/epilog code, so it is basically free.
987 bool AllocaInst::isStaticAlloca() const {
988 // Must be constant size.
989 if (!isa<ConstantInt>(getArraySize())) return false;
991 // Must be in the entry block.
992 const BasicBlock *Parent = getParent();
993 return Parent == &Parent->getParent()->front();
996 //===----------------------------------------------------------------------===//
997 // LoadInst Implementation
998 //===----------------------------------------------------------------------===//
1000 void LoadInst::AssertOK() {
1001 assert(getOperand(0)->getType()->isPointerTy() &&
1002 "Ptr must have pointer type.");
1003 assert(!(isAtomic() && getAlignment() == 0) &&
1004 "Alignment required for atomic load");
1007 LoadInst::LoadInst(Value *Ptr, const Twine &Name, Instruction *InsertBef)
1008 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1009 Load, Ptr, InsertBef) {
1012 setAtomic(NotAtomic);
1017 LoadInst::LoadInst(Value *Ptr, const Twine &Name, BasicBlock *InsertAE)
1018 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1019 Load, Ptr, InsertAE) {
1022 setAtomic(NotAtomic);
1027 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
1028 Instruction *InsertBef)
1029 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1030 Load, Ptr, InsertBef) {
1031 setVolatile(isVolatile);
1033 setAtomic(NotAtomic);
1038 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
1039 BasicBlock *InsertAE)
1040 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1041 Load, Ptr, InsertAE) {
1042 setVolatile(isVolatile);
1044 setAtomic(NotAtomic);
1049 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
1050 unsigned Align, Instruction *InsertBef)
1051 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1052 Load, Ptr, InsertBef) {
1053 setVolatile(isVolatile);
1054 setAlignment(Align);
1055 setAtomic(NotAtomic);
1060 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
1061 unsigned Align, BasicBlock *InsertAE)
1062 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1063 Load, Ptr, InsertAE) {
1064 setVolatile(isVolatile);
1065 setAlignment(Align);
1066 setAtomic(NotAtomic);
1071 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
1072 unsigned Align, AtomicOrdering Order,
1073 SynchronizationScope SynchScope,
1074 Instruction *InsertBef)
1075 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1076 Load, Ptr, InsertBef) {
1077 setVolatile(isVolatile);
1078 setAlignment(Align);
1079 setAtomic(Order, SynchScope);
1084 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
1085 unsigned Align, AtomicOrdering Order,
1086 SynchronizationScope SynchScope,
1087 BasicBlock *InsertAE)
1088 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1089 Load, Ptr, InsertAE) {
1090 setVolatile(isVolatile);
1091 setAlignment(Align);
1092 setAtomic(Order, SynchScope);
1097 LoadInst::LoadInst(Value *Ptr, const char *Name, Instruction *InsertBef)
1098 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1099 Load, Ptr, InsertBef) {
1102 setAtomic(NotAtomic);
1104 if (Name && Name[0]) setName(Name);
1107 LoadInst::LoadInst(Value *Ptr, const char *Name, BasicBlock *InsertAE)
1108 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1109 Load, Ptr, InsertAE) {
1112 setAtomic(NotAtomic);
1114 if (Name && Name[0]) setName(Name);
1117 LoadInst::LoadInst(Value *Ptr, const char *Name, bool isVolatile,
1118 Instruction *InsertBef)
1119 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1120 Load, Ptr, InsertBef) {
1121 setVolatile(isVolatile);
1123 setAtomic(NotAtomic);
1125 if (Name && Name[0]) setName(Name);
1128 LoadInst::LoadInst(Value *Ptr, const char *Name, bool isVolatile,
1129 BasicBlock *InsertAE)
1130 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1131 Load, Ptr, InsertAE) {
1132 setVolatile(isVolatile);
1134 setAtomic(NotAtomic);
1136 if (Name && Name[0]) setName(Name);
1139 void LoadInst::setAlignment(unsigned Align) {
1140 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
1141 assert(Align <= MaximumAlignment &&
1142 "Alignment is greater than MaximumAlignment!");
1143 setInstructionSubclassData((getSubclassDataFromInstruction() & ~(31 << 1)) |
1144 ((Log2_32(Align)+1)<<1));
1145 assert(getAlignment() == Align && "Alignment representation error!");
1148 //===----------------------------------------------------------------------===//
1149 // StoreInst Implementation
1150 //===----------------------------------------------------------------------===//
1152 void StoreInst::AssertOK() {
1153 assert(getOperand(0) && getOperand(1) && "Both operands must be non-null!");
1154 assert(getOperand(1)->getType()->isPointerTy() &&
1155 "Ptr must have pointer type!");
1156 assert(getOperand(0)->getType() ==
1157 cast<PointerType>(getOperand(1)->getType())->getElementType()
1158 && "Ptr must be a pointer to Val type!");
1159 assert(!(isAtomic() && getAlignment() == 0) &&
1160 "Alignment required for atomic load");
1164 StoreInst::StoreInst(Value *val, Value *addr, Instruction *InsertBefore)
1165 : Instruction(Type::getVoidTy(val->getContext()), Store,
1166 OperandTraits<StoreInst>::op_begin(this),
1167 OperandTraits<StoreInst>::operands(this),
1173 setAtomic(NotAtomic);
1177 StoreInst::StoreInst(Value *val, Value *addr, BasicBlock *InsertAtEnd)
1178 : Instruction(Type::getVoidTy(val->getContext()), Store,
1179 OperandTraits<StoreInst>::op_begin(this),
1180 OperandTraits<StoreInst>::operands(this),
1186 setAtomic(NotAtomic);
1190 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1191 Instruction *InsertBefore)
1192 : Instruction(Type::getVoidTy(val->getContext()), Store,
1193 OperandTraits<StoreInst>::op_begin(this),
1194 OperandTraits<StoreInst>::operands(this),
1198 setVolatile(isVolatile);
1200 setAtomic(NotAtomic);
1204 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1205 unsigned Align, Instruction *InsertBefore)
1206 : Instruction(Type::getVoidTy(val->getContext()), Store,
1207 OperandTraits<StoreInst>::op_begin(this),
1208 OperandTraits<StoreInst>::operands(this),
1212 setVolatile(isVolatile);
1213 setAlignment(Align);
1214 setAtomic(NotAtomic);
1218 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1219 unsigned Align, AtomicOrdering Order,
1220 SynchronizationScope SynchScope,
1221 Instruction *InsertBefore)
1222 : Instruction(Type::getVoidTy(val->getContext()), Store,
1223 OperandTraits<StoreInst>::op_begin(this),
1224 OperandTraits<StoreInst>::operands(this),
1228 setVolatile(isVolatile);
1229 setAlignment(Align);
1230 setAtomic(Order, SynchScope);
1234 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1235 BasicBlock *InsertAtEnd)
1236 : Instruction(Type::getVoidTy(val->getContext()), Store,
1237 OperandTraits<StoreInst>::op_begin(this),
1238 OperandTraits<StoreInst>::operands(this),
1242 setVolatile(isVolatile);
1244 setAtomic(NotAtomic);
1248 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1249 unsigned Align, BasicBlock *InsertAtEnd)
1250 : Instruction(Type::getVoidTy(val->getContext()), Store,
1251 OperandTraits<StoreInst>::op_begin(this),
1252 OperandTraits<StoreInst>::operands(this),
1256 setVolatile(isVolatile);
1257 setAlignment(Align);
1258 setAtomic(NotAtomic);
1262 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1263 unsigned Align, AtomicOrdering Order,
1264 SynchronizationScope SynchScope,
1265 BasicBlock *InsertAtEnd)
1266 : Instruction(Type::getVoidTy(val->getContext()), Store,
1267 OperandTraits<StoreInst>::op_begin(this),
1268 OperandTraits<StoreInst>::operands(this),
1272 setVolatile(isVolatile);
1273 setAlignment(Align);
1274 setAtomic(Order, SynchScope);
1278 void StoreInst::setAlignment(unsigned Align) {
1279 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
1280 assert(Align <= MaximumAlignment &&
1281 "Alignment is greater than MaximumAlignment!");
1282 setInstructionSubclassData((getSubclassDataFromInstruction() & ~(31 << 1)) |
1283 ((Log2_32(Align)+1) << 1));
1284 assert(getAlignment() == Align && "Alignment representation error!");
1287 //===----------------------------------------------------------------------===//
1288 // AtomicCmpXchgInst Implementation
1289 //===----------------------------------------------------------------------===//
1291 void AtomicCmpXchgInst::Init(Value *Ptr, Value *Cmp, Value *NewVal,
1292 AtomicOrdering Ordering,
1293 SynchronizationScope SynchScope) {
1297 setOrdering(Ordering);
1298 setSynchScope(SynchScope);
1300 assert(getOperand(0) && getOperand(1) && getOperand(2) &&
1301 "All operands must be non-null!");
1302 assert(getOperand(0)->getType()->isPointerTy() &&
1303 "Ptr must have pointer type!");
1304 assert(getOperand(1)->getType() ==
1305 cast<PointerType>(getOperand(0)->getType())->getElementType()
1306 && "Ptr must be a pointer to Cmp type!");
1307 assert(getOperand(2)->getType() ==
1308 cast<PointerType>(getOperand(0)->getType())->getElementType()
1309 && "Ptr must be a pointer to NewVal type!");
1310 assert(Ordering != NotAtomic &&
1311 "AtomicCmpXchg instructions must be atomic!");
1314 AtomicCmpXchgInst::AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal,
1315 AtomicOrdering Ordering,
1316 SynchronizationScope SynchScope,
1317 Instruction *InsertBefore)
1318 : Instruction(Cmp->getType(), AtomicCmpXchg,
1319 OperandTraits<AtomicCmpXchgInst>::op_begin(this),
1320 OperandTraits<AtomicCmpXchgInst>::operands(this),
1322 Init(Ptr, Cmp, NewVal, Ordering, SynchScope);
1325 AtomicCmpXchgInst::AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal,
1326 AtomicOrdering Ordering,
1327 SynchronizationScope SynchScope,
1328 BasicBlock *InsertAtEnd)
1329 : Instruction(Cmp->getType(), AtomicCmpXchg,
1330 OperandTraits<AtomicCmpXchgInst>::op_begin(this),
1331 OperandTraits<AtomicCmpXchgInst>::operands(this),
1333 Init(Ptr, Cmp, NewVal, Ordering, SynchScope);
1336 //===----------------------------------------------------------------------===//
1337 // AtomicRMWInst Implementation
1338 //===----------------------------------------------------------------------===//
1340 void AtomicRMWInst::Init(BinOp Operation, Value *Ptr, Value *Val,
1341 AtomicOrdering Ordering,
1342 SynchronizationScope SynchScope) {
1345 setOperation(Operation);
1346 setOrdering(Ordering);
1347 setSynchScope(SynchScope);
1349 assert(getOperand(0) && getOperand(1) &&
1350 "All operands must be non-null!");
1351 assert(getOperand(0)->getType()->isPointerTy() &&
1352 "Ptr must have pointer type!");
1353 assert(getOperand(1)->getType() ==
1354 cast<PointerType>(getOperand(0)->getType())->getElementType()
1355 && "Ptr must be a pointer to Val type!");
1356 assert(Ordering != NotAtomic &&
1357 "AtomicRMW instructions must be atomic!");
1360 AtomicRMWInst::AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val,
1361 AtomicOrdering Ordering,
1362 SynchronizationScope SynchScope,
1363 Instruction *InsertBefore)
1364 : Instruction(Val->getType(), AtomicRMW,
1365 OperandTraits<AtomicRMWInst>::op_begin(this),
1366 OperandTraits<AtomicRMWInst>::operands(this),
1368 Init(Operation, Ptr, Val, Ordering, SynchScope);
1371 AtomicRMWInst::AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val,
1372 AtomicOrdering Ordering,
1373 SynchronizationScope SynchScope,
1374 BasicBlock *InsertAtEnd)
1375 : Instruction(Val->getType(), AtomicRMW,
1376 OperandTraits<AtomicRMWInst>::op_begin(this),
1377 OperandTraits<AtomicRMWInst>::operands(this),
1379 Init(Operation, Ptr, Val, Ordering, SynchScope);
1382 //===----------------------------------------------------------------------===//
1383 // FenceInst Implementation
1384 //===----------------------------------------------------------------------===//
1386 FenceInst::FenceInst(LLVMContext &C, AtomicOrdering Ordering,
1387 SynchronizationScope SynchScope,
1388 Instruction *InsertBefore)
1389 : Instruction(Type::getVoidTy(C), Fence, 0, 0, InsertBefore) {
1390 setOrdering(Ordering);
1391 setSynchScope(SynchScope);
1394 FenceInst::FenceInst(LLVMContext &C, AtomicOrdering Ordering,
1395 SynchronizationScope SynchScope,
1396 BasicBlock *InsertAtEnd)
1397 : Instruction(Type::getVoidTy(C), Fence, 0, 0, InsertAtEnd) {
1398 setOrdering(Ordering);
1399 setSynchScope(SynchScope);
1402 //===----------------------------------------------------------------------===//
1403 // GetElementPtrInst Implementation
1404 //===----------------------------------------------------------------------===//
1406 void GetElementPtrInst::init(Value *Ptr, ArrayRef<Value *> IdxList,
1407 const Twine &Name) {
1408 assert(NumOperands == 1 + IdxList.size() && "NumOperands not initialized?");
1409 OperandList[0] = Ptr;
1410 std::copy(IdxList.begin(), IdxList.end(), op_begin() + 1);
1414 GetElementPtrInst::GetElementPtrInst(const GetElementPtrInst &GEPI)
1415 : Instruction(GEPI.getType(), GetElementPtr,
1416 OperandTraits<GetElementPtrInst>::op_end(this)
1417 - GEPI.getNumOperands(),
1418 GEPI.getNumOperands()) {
1419 std::copy(GEPI.op_begin(), GEPI.op_end(), op_begin());
1420 SubclassOptionalData = GEPI.SubclassOptionalData;
1423 /// getIndexedType - Returns the type of the element that would be accessed with
1424 /// a gep instruction with the specified parameters.
1426 /// The Idxs pointer should point to a continuous piece of memory containing the
1427 /// indices, either as Value* or uint64_t.
1429 /// A null type is returned if the indices are invalid for the specified
1432 template <typename IndexTy>
1433 static Type *getIndexedTypeInternal(Type *Ptr, ArrayRef<IndexTy> IdxList) {
1434 if (Ptr->isVectorTy()) {
1435 assert(IdxList.size() == 1 &&
1436 "GEP with vector pointers must have a single index");
1437 PointerType *PTy = dyn_cast<PointerType>(
1438 cast<VectorType>(Ptr)->getElementType());
1439 assert(PTy && "Gep with invalid vector pointer found");
1440 return PTy->getElementType();
1443 PointerType *PTy = dyn_cast<PointerType>(Ptr);
1444 if (!PTy) return 0; // Type isn't a pointer type!
1445 Type *Agg = PTy->getElementType();
1447 // Handle the special case of the empty set index set, which is always valid.
1448 if (IdxList.empty())
1451 // If there is at least one index, the top level type must be sized, otherwise
1452 // it cannot be 'stepped over'.
1453 if (!Agg->isSized())
1456 unsigned CurIdx = 1;
1457 for (; CurIdx != IdxList.size(); ++CurIdx) {
1458 CompositeType *CT = dyn_cast<CompositeType>(Agg);
1459 if (!CT || CT->isPointerTy()) return 0;
1460 IndexTy Index = IdxList[CurIdx];
1461 if (!CT->indexValid(Index)) return 0;
1462 Agg = CT->getTypeAtIndex(Index);
1464 return CurIdx == IdxList.size() ? Agg : 0;
1467 Type *GetElementPtrInst::getIndexedType(Type *Ptr, ArrayRef<Value *> IdxList) {
1468 return getIndexedTypeInternal(Ptr, IdxList);
1471 Type *GetElementPtrInst::getIndexedType(Type *Ptr,
1472 ArrayRef<Constant *> IdxList) {
1473 return getIndexedTypeInternal(Ptr, IdxList);
1476 Type *GetElementPtrInst::getIndexedType(Type *Ptr, ArrayRef<uint64_t> IdxList) {
1477 return getIndexedTypeInternal(Ptr, IdxList);
1480 unsigned GetElementPtrInst::getAddressSpace(Value *Ptr) {
1481 Type *Ty = Ptr->getType();
1483 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
1484 Ty = VTy->getElementType();
1486 if (PointerType *PTy = dyn_cast<PointerType>(Ty))
1487 return PTy->getAddressSpace();
1489 llvm_unreachable("Invalid GEP pointer type");
1492 /// hasAllZeroIndices - Return true if all of the indices of this GEP are
1493 /// zeros. If so, the result pointer and the first operand have the same
1494 /// value, just potentially different types.
1495 bool GetElementPtrInst::hasAllZeroIndices() const {
1496 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1497 if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(i))) {
1498 if (!CI->isZero()) return false;
1506 /// hasAllConstantIndices - Return true if all of the indices of this GEP are
1507 /// constant integers. If so, the result pointer and the first operand have
1508 /// a constant offset between them.
1509 bool GetElementPtrInst::hasAllConstantIndices() const {
1510 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1511 if (!isa<ConstantInt>(getOperand(i)))
1517 void GetElementPtrInst::setIsInBounds(bool B) {
1518 cast<GEPOperator>(this)->setIsInBounds(B);
1521 bool GetElementPtrInst::isInBounds() const {
1522 return cast<GEPOperator>(this)->isInBounds();
1525 //===----------------------------------------------------------------------===//
1526 // ExtractElementInst Implementation
1527 //===----------------------------------------------------------------------===//
1529 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
1531 Instruction *InsertBef)
1532 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1534 OperandTraits<ExtractElementInst>::op_begin(this),
1536 assert(isValidOperands(Val, Index) &&
1537 "Invalid extractelement instruction operands!");
1543 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
1545 BasicBlock *InsertAE)
1546 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1548 OperandTraits<ExtractElementInst>::op_begin(this),
1550 assert(isValidOperands(Val, Index) &&
1551 "Invalid extractelement instruction operands!");
1559 bool ExtractElementInst::isValidOperands(const Value *Val, const Value *Index) {
1560 if (!Val->getType()->isVectorTy() || !Index->getType()->isIntegerTy(32))
1566 //===----------------------------------------------------------------------===//
1567 // InsertElementInst Implementation
1568 //===----------------------------------------------------------------------===//
1570 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
1572 Instruction *InsertBef)
1573 : Instruction(Vec->getType(), InsertElement,
1574 OperandTraits<InsertElementInst>::op_begin(this),
1576 assert(isValidOperands(Vec, Elt, Index) &&
1577 "Invalid insertelement instruction operands!");
1584 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
1586 BasicBlock *InsertAE)
1587 : Instruction(Vec->getType(), InsertElement,
1588 OperandTraits<InsertElementInst>::op_begin(this),
1590 assert(isValidOperands(Vec, Elt, Index) &&
1591 "Invalid insertelement instruction operands!");
1599 bool InsertElementInst::isValidOperands(const Value *Vec, const Value *Elt,
1600 const Value *Index) {
1601 if (!Vec->getType()->isVectorTy())
1602 return false; // First operand of insertelement must be vector type.
1604 if (Elt->getType() != cast<VectorType>(Vec->getType())->getElementType())
1605 return false;// Second operand of insertelement must be vector element type.
1607 if (!Index->getType()->isIntegerTy(32))
1608 return false; // Third operand of insertelement must be i32.
1613 //===----------------------------------------------------------------------===//
1614 // ShuffleVectorInst Implementation
1615 //===----------------------------------------------------------------------===//
1617 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1619 Instruction *InsertBefore)
1620 : Instruction(VectorType::get(cast<VectorType>(V1->getType())->getElementType(),
1621 cast<VectorType>(Mask->getType())->getNumElements()),
1623 OperandTraits<ShuffleVectorInst>::op_begin(this),
1624 OperandTraits<ShuffleVectorInst>::operands(this),
1626 assert(isValidOperands(V1, V2, Mask) &&
1627 "Invalid shuffle vector instruction operands!");
1634 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1636 BasicBlock *InsertAtEnd)
1637 : Instruction(VectorType::get(cast<VectorType>(V1->getType())->getElementType(),
1638 cast<VectorType>(Mask->getType())->getNumElements()),
1640 OperandTraits<ShuffleVectorInst>::op_begin(this),
1641 OperandTraits<ShuffleVectorInst>::operands(this),
1643 assert(isValidOperands(V1, V2, Mask) &&
1644 "Invalid shuffle vector instruction operands!");
1652 bool ShuffleVectorInst::isValidOperands(const Value *V1, const Value *V2,
1653 const Value *Mask) {
1654 // V1 and V2 must be vectors of the same type.
1655 if (!V1->getType()->isVectorTy() || V1->getType() != V2->getType())
1658 // Mask must be vector of i32.
1659 VectorType *MaskTy = dyn_cast<VectorType>(Mask->getType());
1660 if (MaskTy == 0 || !MaskTy->getElementType()->isIntegerTy(32))
1663 // Check to see if Mask is valid.
1664 if (isa<UndefValue>(Mask) || isa<ConstantAggregateZero>(Mask))
1667 if (const ConstantVector *MV = dyn_cast<ConstantVector>(Mask)) {
1668 unsigned V1Size = cast<VectorType>(V1->getType())->getNumElements();
1669 for (unsigned i = 0, e = MV->getNumOperands(); i != e; ++i) {
1670 if (ConstantInt *CI = dyn_cast<ConstantInt>(MV->getOperand(i))) {
1671 if (CI->uge(V1Size*2))
1673 } else if (!isa<UndefValue>(MV->getOperand(i))) {
1680 if (const ConstantDataSequential *CDS =
1681 dyn_cast<ConstantDataSequential>(Mask)) {
1682 unsigned V1Size = cast<VectorType>(V1->getType())->getNumElements();
1683 for (unsigned i = 0, e = MaskTy->getNumElements(); i != e; ++i)
1684 if (CDS->getElementAsInteger(i) >= V1Size*2)
1689 // The bitcode reader can create a place holder for a forward reference
1690 // used as the shuffle mask. When this occurs, the shuffle mask will
1691 // fall into this case and fail. To avoid this error, do this bit of
1692 // ugliness to allow such a mask pass.
1693 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(Mask))
1694 if (CE->getOpcode() == Instruction::UserOp1)
1700 /// getMaskValue - Return the index from the shuffle mask for the specified
1701 /// output result. This is either -1 if the element is undef or a number less
1702 /// than 2*numelements.
1703 int ShuffleVectorInst::getMaskValue(Constant *Mask, unsigned i) {
1704 assert(i < Mask->getType()->getVectorNumElements() && "Index out of range");
1705 if (ConstantDataSequential *CDS =dyn_cast<ConstantDataSequential>(Mask))
1706 return CDS->getElementAsInteger(i);
1707 Constant *C = Mask->getAggregateElement(i);
1708 if (isa<UndefValue>(C))
1710 return cast<ConstantInt>(C)->getZExtValue();
1713 /// getShuffleMask - Return the full mask for this instruction, where each
1714 /// element is the element number and undef's are returned as -1.
1715 void ShuffleVectorInst::getShuffleMask(Constant *Mask,
1716 SmallVectorImpl<int> &Result) {
1717 unsigned NumElts = Mask->getType()->getVectorNumElements();
1719 if (ConstantDataSequential *CDS=dyn_cast<ConstantDataSequential>(Mask)) {
1720 for (unsigned i = 0; i != NumElts; ++i)
1721 Result.push_back(CDS->getElementAsInteger(i));
1724 for (unsigned i = 0; i != NumElts; ++i) {
1725 Constant *C = Mask->getAggregateElement(i);
1726 Result.push_back(isa<UndefValue>(C) ? -1 :
1727 cast<ConstantInt>(C)->getZExtValue());
1732 //===----------------------------------------------------------------------===//
1733 // InsertValueInst Class
1734 //===----------------------------------------------------------------------===//
1736 void InsertValueInst::init(Value *Agg, Value *Val, ArrayRef<unsigned> Idxs,
1737 const Twine &Name) {
1738 assert(NumOperands == 2 && "NumOperands not initialized?");
1740 // There's no fundamental reason why we require at least one index
1741 // (other than weirdness with &*IdxBegin being invalid; see
1742 // getelementptr's init routine for example). But there's no
1743 // present need to support it.
1744 assert(Idxs.size() > 0 && "InsertValueInst must have at least one index");
1746 assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs) ==
1747 Val->getType() && "Inserted value must match indexed type!");
1751 Indices.append(Idxs.begin(), Idxs.end());
1755 InsertValueInst::InsertValueInst(const InsertValueInst &IVI)
1756 : Instruction(IVI.getType(), InsertValue,
1757 OperandTraits<InsertValueInst>::op_begin(this), 2),
1758 Indices(IVI.Indices) {
1759 Op<0>() = IVI.getOperand(0);
1760 Op<1>() = IVI.getOperand(1);
1761 SubclassOptionalData = IVI.SubclassOptionalData;
1764 //===----------------------------------------------------------------------===//
1765 // ExtractValueInst Class
1766 //===----------------------------------------------------------------------===//
1768 void ExtractValueInst::init(ArrayRef<unsigned> Idxs, const Twine &Name) {
1769 assert(NumOperands == 1 && "NumOperands not initialized?");
1771 // There's no fundamental reason why we require at least one index.
1772 // But there's no present need to support it.
1773 assert(Idxs.size() > 0 && "ExtractValueInst must have at least one index");
1775 Indices.append(Idxs.begin(), Idxs.end());
1779 ExtractValueInst::ExtractValueInst(const ExtractValueInst &EVI)
1780 : UnaryInstruction(EVI.getType(), ExtractValue, EVI.getOperand(0)),
1781 Indices(EVI.Indices) {
1782 SubclassOptionalData = EVI.SubclassOptionalData;
1785 // getIndexedType - Returns the type of the element that would be extracted
1786 // with an extractvalue instruction with the specified parameters.
1788 // A null type is returned if the indices are invalid for the specified
1791 Type *ExtractValueInst::getIndexedType(Type *Agg,
1792 ArrayRef<unsigned> Idxs) {
1793 for (unsigned CurIdx = 0; CurIdx != Idxs.size(); ++CurIdx) {
1794 unsigned Index = Idxs[CurIdx];
1795 // We can't use CompositeType::indexValid(Index) here.
1796 // indexValid() always returns true for arrays because getelementptr allows
1797 // out-of-bounds indices. Since we don't allow those for extractvalue and
1798 // insertvalue we need to check array indexing manually.
1799 // Since the only other types we can index into are struct types it's just
1800 // as easy to check those manually as well.
1801 if (ArrayType *AT = dyn_cast<ArrayType>(Agg)) {
1802 if (Index >= AT->getNumElements())
1804 } else if (StructType *ST = dyn_cast<StructType>(Agg)) {
1805 if (Index >= ST->getNumElements())
1808 // Not a valid type to index into.
1812 Agg = cast<CompositeType>(Agg)->getTypeAtIndex(Index);
1814 return const_cast<Type*>(Agg);
1817 //===----------------------------------------------------------------------===//
1818 // BinaryOperator Class
1819 //===----------------------------------------------------------------------===//
1821 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
1822 Type *Ty, const Twine &Name,
1823 Instruction *InsertBefore)
1824 : Instruction(Ty, iType,
1825 OperandTraits<BinaryOperator>::op_begin(this),
1826 OperandTraits<BinaryOperator>::operands(this),
1834 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
1835 Type *Ty, const Twine &Name,
1836 BasicBlock *InsertAtEnd)
1837 : Instruction(Ty, iType,
1838 OperandTraits<BinaryOperator>::op_begin(this),
1839 OperandTraits<BinaryOperator>::operands(this),
1848 void BinaryOperator::init(BinaryOps iType) {
1849 Value *LHS = getOperand(0), *RHS = getOperand(1);
1850 (void)LHS; (void)RHS; // Silence warnings.
1851 assert(LHS->getType() == RHS->getType() &&
1852 "Binary operator operand types must match!");
1857 assert(getType() == LHS->getType() &&
1858 "Arithmetic operation should return same type as operands!");
1859 assert(getType()->isIntOrIntVectorTy() &&
1860 "Tried to create an integer operation on a non-integer type!");
1862 case FAdd: case FSub:
1864 assert(getType() == LHS->getType() &&
1865 "Arithmetic operation should return same type as operands!");
1866 assert(getType()->isFPOrFPVectorTy() &&
1867 "Tried to create a floating-point operation on a "
1868 "non-floating-point type!");
1872 assert(getType() == LHS->getType() &&
1873 "Arithmetic operation should return same type as operands!");
1874 assert((getType()->isIntegerTy() || (getType()->isVectorTy() &&
1875 cast<VectorType>(getType())->getElementType()->isIntegerTy())) &&
1876 "Incorrect operand type (not integer) for S/UDIV");
1879 assert(getType() == LHS->getType() &&
1880 "Arithmetic operation should return same type as operands!");
1881 assert(getType()->isFPOrFPVectorTy() &&
1882 "Incorrect operand type (not floating point) for FDIV");
1886 assert(getType() == LHS->getType() &&
1887 "Arithmetic operation should return same type as operands!");
1888 assert((getType()->isIntegerTy() || (getType()->isVectorTy() &&
1889 cast<VectorType>(getType())->getElementType()->isIntegerTy())) &&
1890 "Incorrect operand type (not integer) for S/UREM");
1893 assert(getType() == LHS->getType() &&
1894 "Arithmetic operation should return same type as operands!");
1895 assert(getType()->isFPOrFPVectorTy() &&
1896 "Incorrect operand type (not floating point) for FREM");
1901 assert(getType() == LHS->getType() &&
1902 "Shift operation should return same type as operands!");
1903 assert((getType()->isIntegerTy() ||
1904 (getType()->isVectorTy() &&
1905 cast<VectorType>(getType())->getElementType()->isIntegerTy())) &&
1906 "Tried to create a shift operation on a non-integral type!");
1910 assert(getType() == LHS->getType() &&
1911 "Logical operation should return same type as operands!");
1912 assert((getType()->isIntegerTy() ||
1913 (getType()->isVectorTy() &&
1914 cast<VectorType>(getType())->getElementType()->isIntegerTy())) &&
1915 "Tried to create a logical operation on a non-integral type!");
1923 BinaryOperator *BinaryOperator::Create(BinaryOps Op, Value *S1, Value *S2,
1925 Instruction *InsertBefore) {
1926 assert(S1->getType() == S2->getType() &&
1927 "Cannot create binary operator with two operands of differing type!");
1928 return new BinaryOperator(Op, S1, S2, S1->getType(), Name, InsertBefore);
1931 BinaryOperator *BinaryOperator::Create(BinaryOps Op, Value *S1, Value *S2,
1933 BasicBlock *InsertAtEnd) {
1934 BinaryOperator *Res = Create(Op, S1, S2, Name);
1935 InsertAtEnd->getInstList().push_back(Res);
1939 BinaryOperator *BinaryOperator::CreateNeg(Value *Op, const Twine &Name,
1940 Instruction *InsertBefore) {
1941 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1942 return new BinaryOperator(Instruction::Sub,
1944 Op->getType(), Name, InsertBefore);
1947 BinaryOperator *BinaryOperator::CreateNeg(Value *Op, const Twine &Name,
1948 BasicBlock *InsertAtEnd) {
1949 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1950 return new BinaryOperator(Instruction::Sub,
1952 Op->getType(), Name, InsertAtEnd);
1955 BinaryOperator *BinaryOperator::CreateNSWNeg(Value *Op, const Twine &Name,
1956 Instruction *InsertBefore) {
1957 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1958 return BinaryOperator::CreateNSWSub(zero, Op, Name, InsertBefore);
1961 BinaryOperator *BinaryOperator::CreateNSWNeg(Value *Op, const Twine &Name,
1962 BasicBlock *InsertAtEnd) {
1963 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1964 return BinaryOperator::CreateNSWSub(zero, Op, Name, InsertAtEnd);
1967 BinaryOperator *BinaryOperator::CreateNUWNeg(Value *Op, const Twine &Name,
1968 Instruction *InsertBefore) {
1969 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1970 return BinaryOperator::CreateNUWSub(zero, Op, Name, InsertBefore);
1973 BinaryOperator *BinaryOperator::CreateNUWNeg(Value *Op, const Twine &Name,
1974 BasicBlock *InsertAtEnd) {
1975 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1976 return BinaryOperator::CreateNUWSub(zero, Op, Name, InsertAtEnd);
1979 BinaryOperator *BinaryOperator::CreateFNeg(Value *Op, const Twine &Name,
1980 Instruction *InsertBefore) {
1981 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1982 return new BinaryOperator(Instruction::FSub, zero, Op,
1983 Op->getType(), Name, InsertBefore);
1986 BinaryOperator *BinaryOperator::CreateFNeg(Value *Op, const Twine &Name,
1987 BasicBlock *InsertAtEnd) {
1988 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1989 return new BinaryOperator(Instruction::FSub, zero, Op,
1990 Op->getType(), Name, InsertAtEnd);
1993 BinaryOperator *BinaryOperator::CreateNot(Value *Op, const Twine &Name,
1994 Instruction *InsertBefore) {
1995 Constant *C = Constant::getAllOnesValue(Op->getType());
1996 return new BinaryOperator(Instruction::Xor, Op, C,
1997 Op->getType(), Name, InsertBefore);
2000 BinaryOperator *BinaryOperator::CreateNot(Value *Op, const Twine &Name,
2001 BasicBlock *InsertAtEnd) {
2002 Constant *AllOnes = Constant::getAllOnesValue(Op->getType());
2003 return new BinaryOperator(Instruction::Xor, Op, AllOnes,
2004 Op->getType(), Name, InsertAtEnd);
2008 // isConstantAllOnes - Helper function for several functions below
2009 static inline bool isConstantAllOnes(const Value *V) {
2010 if (const Constant *C = dyn_cast<Constant>(V))
2011 return C->isAllOnesValue();
2015 bool BinaryOperator::isNeg(const Value *V) {
2016 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
2017 if (Bop->getOpcode() == Instruction::Sub)
2018 if (Constant* C = dyn_cast<Constant>(Bop->getOperand(0)))
2019 return C->isNegativeZeroValue();
2023 bool BinaryOperator::isFNeg(const Value *V) {
2024 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
2025 if (Bop->getOpcode() == Instruction::FSub)
2026 if (Constant* C = dyn_cast<Constant>(Bop->getOperand(0)))
2027 return C->isNegativeZeroValue();
2031 bool BinaryOperator::isNot(const Value *V) {
2032 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
2033 return (Bop->getOpcode() == Instruction::Xor &&
2034 (isConstantAllOnes(Bop->getOperand(1)) ||
2035 isConstantAllOnes(Bop->getOperand(0))));
2039 Value *BinaryOperator::getNegArgument(Value *BinOp) {
2040 return cast<BinaryOperator>(BinOp)->getOperand(1);
2043 const Value *BinaryOperator::getNegArgument(const Value *BinOp) {
2044 return getNegArgument(const_cast<Value*>(BinOp));
2047 Value *BinaryOperator::getFNegArgument(Value *BinOp) {
2048 return cast<BinaryOperator>(BinOp)->getOperand(1);
2051 const Value *BinaryOperator::getFNegArgument(const Value *BinOp) {
2052 return getFNegArgument(const_cast<Value*>(BinOp));
2055 Value *BinaryOperator::getNotArgument(Value *BinOp) {
2056 assert(isNot(BinOp) && "getNotArgument on non-'not' instruction!");
2057 BinaryOperator *BO = cast<BinaryOperator>(BinOp);
2058 Value *Op0 = BO->getOperand(0);
2059 Value *Op1 = BO->getOperand(1);
2060 if (isConstantAllOnes(Op0)) return Op1;
2062 assert(isConstantAllOnes(Op1));
2066 const Value *BinaryOperator::getNotArgument(const Value *BinOp) {
2067 return getNotArgument(const_cast<Value*>(BinOp));
2071 // swapOperands - Exchange the two operands to this instruction. This
2072 // instruction is safe to use on any binary instruction and does not
2073 // modify the semantics of the instruction. If the instruction is
2074 // order dependent (SetLT f.e.) the opcode is changed.
2076 bool BinaryOperator::swapOperands() {
2077 if (!isCommutative())
2078 return true; // Can't commute operands
2079 Op<0>().swap(Op<1>());
2083 void BinaryOperator::setHasNoUnsignedWrap(bool b) {
2084 cast<OverflowingBinaryOperator>(this)->setHasNoUnsignedWrap(b);
2087 void BinaryOperator::setHasNoSignedWrap(bool b) {
2088 cast<OverflowingBinaryOperator>(this)->setHasNoSignedWrap(b);
2091 void BinaryOperator::setIsExact(bool b) {
2092 cast<PossiblyExactOperator>(this)->setIsExact(b);
2095 bool BinaryOperator::hasNoUnsignedWrap() const {
2096 return cast<OverflowingBinaryOperator>(this)->hasNoUnsignedWrap();
2099 bool BinaryOperator::hasNoSignedWrap() const {
2100 return cast<OverflowingBinaryOperator>(this)->hasNoSignedWrap();
2103 bool BinaryOperator::isExact() const {
2104 return cast<PossiblyExactOperator>(this)->isExact();
2107 //===----------------------------------------------------------------------===//
2108 // FPMathOperator Class
2109 //===----------------------------------------------------------------------===//
2111 /// getFPAccuracy - Get the maximum error permitted by this operation in ULPs.
2112 /// An accuracy of 0.0 means that the operation should be performed with the
2113 /// default precision.
2114 float FPMathOperator::getFPAccuracy() const {
2116 cast<Instruction>(this)->getMetadata(LLVMContext::MD_fpmath);
2119 ConstantFP *Accuracy = cast<ConstantFP>(MD->getOperand(0));
2120 return Accuracy->getValueAPF().convertToFloat();
2124 //===----------------------------------------------------------------------===//
2126 //===----------------------------------------------------------------------===//
2128 void CastInst::anchor() {}
2130 // Just determine if this cast only deals with integral->integral conversion.
2131 bool CastInst::isIntegerCast() const {
2132 switch (getOpcode()) {
2133 default: return false;
2134 case Instruction::ZExt:
2135 case Instruction::SExt:
2136 case Instruction::Trunc:
2138 case Instruction::BitCast:
2139 return getOperand(0)->getType()->isIntegerTy() &&
2140 getType()->isIntegerTy();
2144 bool CastInst::isLosslessCast() const {
2145 // Only BitCast can be lossless, exit fast if we're not BitCast
2146 if (getOpcode() != Instruction::BitCast)
2149 // Identity cast is always lossless
2150 Type* SrcTy = getOperand(0)->getType();
2151 Type* DstTy = getType();
2155 // Pointer to pointer is always lossless.
2156 if (SrcTy->isPointerTy())
2157 return DstTy->isPointerTy();
2158 return false; // Other types have no identity values
2161 /// This function determines if the CastInst does not require any bits to be
2162 /// changed in order to effect the cast. Essentially, it identifies cases where
2163 /// no code gen is necessary for the cast, hence the name no-op cast. For
2164 /// example, the following are all no-op casts:
2165 /// # bitcast i32* %x to i8*
2166 /// # bitcast <2 x i32> %x to <4 x i16>
2167 /// # ptrtoint i32* %x to i32 ; on 32-bit plaforms only
2168 /// @brief Determine if the described cast is a no-op.
2169 bool CastInst::isNoopCast(Instruction::CastOps Opcode,
2174 default: llvm_unreachable("Invalid CastOp");
2175 case Instruction::Trunc:
2176 case Instruction::ZExt:
2177 case Instruction::SExt:
2178 case Instruction::FPTrunc:
2179 case Instruction::FPExt:
2180 case Instruction::UIToFP:
2181 case Instruction::SIToFP:
2182 case Instruction::FPToUI:
2183 case Instruction::FPToSI:
2184 return false; // These always modify bits
2185 case Instruction::BitCast:
2186 return true; // BitCast never modifies bits.
2187 case Instruction::PtrToInt:
2188 return IntPtrTy->getScalarSizeInBits() ==
2189 DestTy->getScalarSizeInBits();
2190 case Instruction::IntToPtr:
2191 return IntPtrTy->getScalarSizeInBits() ==
2192 SrcTy->getScalarSizeInBits();
2196 /// @brief Determine if a cast is a no-op.
2197 bool CastInst::isNoopCast(Type *IntPtrTy) const {
2198 return isNoopCast(getOpcode(), getOperand(0)->getType(), getType(), IntPtrTy);
2201 /// This function determines if a pair of casts can be eliminated and what
2202 /// opcode should be used in the elimination. This assumes that there are two
2203 /// instructions like this:
2204 /// * %F = firstOpcode SrcTy %x to MidTy
2205 /// * %S = secondOpcode MidTy %F to DstTy
2206 /// The function returns a resultOpcode so these two casts can be replaced with:
2207 /// * %Replacement = resultOpcode %SrcTy %x to DstTy
2208 /// If no such cast is permited, the function returns 0.
2209 unsigned CastInst::isEliminableCastPair(
2210 Instruction::CastOps firstOp, Instruction::CastOps secondOp,
2211 Type *SrcTy, Type *MidTy, Type *DstTy, Type *IntPtrTy) {
2212 // Define the 144 possibilities for these two cast instructions. The values
2213 // in this matrix determine what to do in a given situation and select the
2214 // case in the switch below. The rows correspond to firstOp, the columns
2215 // correspond to secondOp. In looking at the table below, keep in mind
2216 // the following cast properties:
2218 // Size Compare Source Destination
2219 // Operator Src ? Size Type Sign Type Sign
2220 // -------- ------------ ------------------- ---------------------
2221 // TRUNC > Integer Any Integral Any
2222 // ZEXT < Integral Unsigned Integer Any
2223 // SEXT < Integral Signed Integer Any
2224 // FPTOUI n/a FloatPt n/a Integral Unsigned
2225 // FPTOSI n/a FloatPt n/a Integral Signed
2226 // UITOFP n/a Integral Unsigned FloatPt n/a
2227 // SITOFP n/a Integral Signed FloatPt n/a
2228 // FPTRUNC > FloatPt n/a FloatPt n/a
2229 // FPEXT < FloatPt n/a FloatPt n/a
2230 // PTRTOINT n/a Pointer n/a Integral Unsigned
2231 // INTTOPTR n/a Integral Unsigned Pointer n/a
2232 // BITCAST = FirstClass n/a FirstClass n/a
2234 // NOTE: some transforms are safe, but we consider them to be non-profitable.
2235 // For example, we could merge "fptoui double to i32" + "zext i32 to i64",
2236 // into "fptoui double to i64", but this loses information about the range
2237 // of the produced value (we no longer know the top-part is all zeros).
2238 // Further this conversion is often much more expensive for typical hardware,
2239 // and causes issues when building libgcc. We disallow fptosi+sext for the
2241 const unsigned numCastOps =
2242 Instruction::CastOpsEnd - Instruction::CastOpsBegin;
2243 static const uint8_t CastResults[numCastOps][numCastOps] = {
2244 // T F F U S F F P I B -+
2245 // R Z S P P I I T P 2 N T |
2246 // U E E 2 2 2 2 R E I T C +- secondOp
2247 // N X X U S F F N X N 2 V |
2248 // C T T I I P P C T T P T -+
2249 { 1, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // Trunc -+
2250 { 8, 1, 9,99,99, 2, 0,99,99,99, 2, 3 }, // ZExt |
2251 { 8, 0, 1,99,99, 0, 2,99,99,99, 0, 3 }, // SExt |
2252 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // FPToUI |
2253 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // FPToSI |
2254 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4 }, // UIToFP +- firstOp
2255 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4 }, // SIToFP |
2256 { 99,99,99, 0, 0,99,99, 1, 0,99,99, 4 }, // FPTrunc |
2257 { 99,99,99, 2, 2,99,99,10, 2,99,99, 4 }, // FPExt |
2258 { 1, 0, 0,99,99, 0, 0,99,99,99, 7, 3 }, // PtrToInt |
2259 { 99,99,99,99,99,99,99,99,99,13,99,12 }, // IntToPtr |
2260 { 5, 5, 5, 6, 6, 5, 5, 6, 6,11, 5, 1 }, // BitCast -+
2263 // If either of the casts are a bitcast from scalar to vector, disallow the
2264 // merging. However, bitcast of A->B->A are allowed.
2265 bool isFirstBitcast = (firstOp == Instruction::BitCast);
2266 bool isSecondBitcast = (secondOp == Instruction::BitCast);
2267 bool chainedBitcast = (SrcTy == DstTy && isFirstBitcast && isSecondBitcast);
2269 // Check if any of the bitcasts convert scalars<->vectors.
2270 if ((isFirstBitcast && isa<VectorType>(SrcTy) != isa<VectorType>(MidTy)) ||
2271 (isSecondBitcast && isa<VectorType>(MidTy) != isa<VectorType>(DstTy)))
2272 // Unless we are bitcasing to the original type, disallow optimizations.
2273 if (!chainedBitcast) return 0;
2275 int ElimCase = CastResults[firstOp-Instruction::CastOpsBegin]
2276 [secondOp-Instruction::CastOpsBegin];
2279 // categorically disallowed
2282 // allowed, use first cast's opcode
2285 // allowed, use second cast's opcode
2288 // no-op cast in second op implies firstOp as long as the DestTy
2289 // is integer and we are not converting between a vector and a
2291 if (!SrcTy->isVectorTy() && DstTy->isIntegerTy())
2295 // no-op cast in second op implies firstOp as long as the DestTy
2296 // is floating point.
2297 if (DstTy->isFloatingPointTy())
2301 // no-op cast in first op implies secondOp as long as the SrcTy
2303 if (SrcTy->isIntegerTy())
2307 // no-op cast in first op implies secondOp as long as the SrcTy
2308 // is a floating point.
2309 if (SrcTy->isFloatingPointTy())
2313 // ptrtoint, inttoptr -> bitcast (ptr -> ptr) if int size is >= ptr size
2316 unsigned PtrSize = IntPtrTy->getScalarSizeInBits();
2317 unsigned MidSize = MidTy->getScalarSizeInBits();
2318 if (MidSize >= PtrSize)
2319 return Instruction::BitCast;
2323 // ext, trunc -> bitcast, if the SrcTy and DstTy are same size
2324 // ext, trunc -> ext, if sizeof(SrcTy) < sizeof(DstTy)
2325 // ext, trunc -> trunc, if sizeof(SrcTy) > sizeof(DstTy)
2326 unsigned SrcSize = SrcTy->getScalarSizeInBits();
2327 unsigned DstSize = DstTy->getScalarSizeInBits();
2328 if (SrcSize == DstSize)
2329 return Instruction::BitCast;
2330 else if (SrcSize < DstSize)
2334 case 9: // zext, sext -> zext, because sext can't sign extend after zext
2335 return Instruction::ZExt;
2337 // fpext followed by ftrunc is allowed if the bit size returned to is
2338 // the same as the original, in which case its just a bitcast
2340 return Instruction::BitCast;
2341 return 0; // If the types are not the same we can't eliminate it.
2343 // bitcast followed by ptrtoint is allowed as long as the bitcast
2344 // is a pointer to pointer cast.
2345 if (SrcTy->isPointerTy() && MidTy->isPointerTy())
2349 // inttoptr, bitcast -> intptr if bitcast is a ptr to ptr cast
2350 if (MidTy->isPointerTy() && DstTy->isPointerTy())
2354 // inttoptr, ptrtoint -> bitcast if SrcSize<=PtrSize and SrcSize==DstSize
2357 unsigned PtrSize = IntPtrTy->getScalarSizeInBits();
2358 unsigned SrcSize = SrcTy->getScalarSizeInBits();
2359 unsigned DstSize = DstTy->getScalarSizeInBits();
2360 if (SrcSize <= PtrSize && SrcSize == DstSize)
2361 return Instruction::BitCast;
2365 // cast combination can't happen (error in input). This is for all cases
2366 // where the MidTy is not the same for the two cast instructions.
2367 llvm_unreachable("Invalid Cast Combination");
2369 llvm_unreachable("Error in CastResults table!!!");
2373 CastInst *CastInst::Create(Instruction::CastOps op, Value *S, Type *Ty,
2374 const Twine &Name, Instruction *InsertBefore) {
2375 assert(castIsValid(op, S, Ty) && "Invalid cast!");
2376 // Construct and return the appropriate CastInst subclass
2378 case Trunc: return new TruncInst (S, Ty, Name, InsertBefore);
2379 case ZExt: return new ZExtInst (S, Ty, Name, InsertBefore);
2380 case SExt: return new SExtInst (S, Ty, Name, InsertBefore);
2381 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertBefore);
2382 case FPExt: return new FPExtInst (S, Ty, Name, InsertBefore);
2383 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertBefore);
2384 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertBefore);
2385 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertBefore);
2386 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertBefore);
2387 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertBefore);
2388 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertBefore);
2389 case BitCast: return new BitCastInst (S, Ty, Name, InsertBefore);
2390 default: llvm_unreachable("Invalid opcode provided");
2394 CastInst *CastInst::Create(Instruction::CastOps op, Value *S, Type *Ty,
2395 const Twine &Name, BasicBlock *InsertAtEnd) {
2396 assert(castIsValid(op, S, Ty) && "Invalid cast!");
2397 // Construct and return the appropriate CastInst subclass
2399 case Trunc: return new TruncInst (S, Ty, Name, InsertAtEnd);
2400 case ZExt: return new ZExtInst (S, Ty, Name, InsertAtEnd);
2401 case SExt: return new SExtInst (S, Ty, Name, InsertAtEnd);
2402 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertAtEnd);
2403 case FPExt: return new FPExtInst (S, Ty, Name, InsertAtEnd);
2404 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertAtEnd);
2405 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertAtEnd);
2406 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertAtEnd);
2407 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertAtEnd);
2408 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertAtEnd);
2409 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertAtEnd);
2410 case BitCast: return new BitCastInst (S, Ty, Name, InsertAtEnd);
2411 default: llvm_unreachable("Invalid opcode provided");
2415 CastInst *CastInst::CreateZExtOrBitCast(Value *S, Type *Ty,
2417 Instruction *InsertBefore) {
2418 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2419 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2420 return Create(Instruction::ZExt, S, Ty, Name, InsertBefore);
2423 CastInst *CastInst::CreateZExtOrBitCast(Value *S, Type *Ty,
2425 BasicBlock *InsertAtEnd) {
2426 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2427 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2428 return Create(Instruction::ZExt, S, Ty, Name, InsertAtEnd);
2431 CastInst *CastInst::CreateSExtOrBitCast(Value *S, Type *Ty,
2433 Instruction *InsertBefore) {
2434 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2435 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2436 return Create(Instruction::SExt, S, Ty, Name, InsertBefore);
2439 CastInst *CastInst::CreateSExtOrBitCast(Value *S, Type *Ty,
2441 BasicBlock *InsertAtEnd) {
2442 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2443 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2444 return Create(Instruction::SExt, S, Ty, Name, InsertAtEnd);
2447 CastInst *CastInst::CreateTruncOrBitCast(Value *S, Type *Ty,
2449 Instruction *InsertBefore) {
2450 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2451 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2452 return Create(Instruction::Trunc, S, Ty, Name, InsertBefore);
2455 CastInst *CastInst::CreateTruncOrBitCast(Value *S, Type *Ty,
2457 BasicBlock *InsertAtEnd) {
2458 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2459 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2460 return Create(Instruction::Trunc, S, Ty, Name, InsertAtEnd);
2463 CastInst *CastInst::CreatePointerCast(Value *S, Type *Ty,
2465 BasicBlock *InsertAtEnd) {
2466 assert(S->getType()->isPointerTy() && "Invalid cast");
2467 assert((Ty->isIntegerTy() || Ty->isPointerTy()) &&
2470 if (Ty->isIntegerTy())
2471 return Create(Instruction::PtrToInt, S, Ty, Name, InsertAtEnd);
2472 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2475 /// @brief Create a BitCast or a PtrToInt cast instruction
2476 CastInst *CastInst::CreatePointerCast(Value *S, Type *Ty,
2478 Instruction *InsertBefore) {
2479 assert(S->getType()->isPointerTy() && "Invalid cast");
2480 assert((Ty->isIntegerTy() || Ty->isPointerTy()) &&
2483 if (Ty->isIntegerTy())
2484 return Create(Instruction::PtrToInt, S, Ty, Name, InsertBefore);
2485 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2488 CastInst *CastInst::CreateIntegerCast(Value *C, Type *Ty,
2489 bool isSigned, const Twine &Name,
2490 Instruction *InsertBefore) {
2491 assert(C->getType()->isIntOrIntVectorTy() && Ty->isIntOrIntVectorTy() &&
2492 "Invalid integer cast");
2493 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2494 unsigned DstBits = Ty->getScalarSizeInBits();
2495 Instruction::CastOps opcode =
2496 (SrcBits == DstBits ? Instruction::BitCast :
2497 (SrcBits > DstBits ? Instruction::Trunc :
2498 (isSigned ? Instruction::SExt : Instruction::ZExt)));
2499 return Create(opcode, C, Ty, Name, InsertBefore);
2502 CastInst *CastInst::CreateIntegerCast(Value *C, Type *Ty,
2503 bool isSigned, const Twine &Name,
2504 BasicBlock *InsertAtEnd) {
2505 assert(C->getType()->isIntOrIntVectorTy() && Ty->isIntOrIntVectorTy() &&
2507 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2508 unsigned DstBits = Ty->getScalarSizeInBits();
2509 Instruction::CastOps opcode =
2510 (SrcBits == DstBits ? Instruction::BitCast :
2511 (SrcBits > DstBits ? Instruction::Trunc :
2512 (isSigned ? Instruction::SExt : Instruction::ZExt)));
2513 return Create(opcode, C, Ty, Name, InsertAtEnd);
2516 CastInst *CastInst::CreateFPCast(Value *C, Type *Ty,
2518 Instruction *InsertBefore) {
2519 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
2521 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2522 unsigned DstBits = Ty->getScalarSizeInBits();
2523 Instruction::CastOps opcode =
2524 (SrcBits == DstBits ? Instruction::BitCast :
2525 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
2526 return Create(opcode, C, Ty, Name, InsertBefore);
2529 CastInst *CastInst::CreateFPCast(Value *C, Type *Ty,
2531 BasicBlock *InsertAtEnd) {
2532 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
2534 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2535 unsigned DstBits = Ty->getScalarSizeInBits();
2536 Instruction::CastOps opcode =
2537 (SrcBits == DstBits ? Instruction::BitCast :
2538 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
2539 return Create(opcode, C, Ty, Name, InsertAtEnd);
2542 // Check whether it is valid to call getCastOpcode for these types.
2543 // This routine must be kept in sync with getCastOpcode.
2544 bool CastInst::isCastable(Type *SrcTy, Type *DestTy) {
2545 if (!SrcTy->isFirstClassType() || !DestTy->isFirstClassType())
2548 if (SrcTy == DestTy)
2551 if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy))
2552 if (VectorType *DestVecTy = dyn_cast<VectorType>(DestTy))
2553 if (SrcVecTy->getNumElements() == DestVecTy->getNumElements()) {
2554 // An element by element cast. Valid if casting the elements is valid.
2555 SrcTy = SrcVecTy->getElementType();
2556 DestTy = DestVecTy->getElementType();
2559 // Get the bit sizes, we'll need these
2560 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); // 0 for ptr
2561 unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr
2563 // Run through the possibilities ...
2564 if (DestTy->isIntegerTy()) { // Casting to integral
2565 if (SrcTy->isIntegerTy()) { // Casting from integral
2567 } else if (SrcTy->isFloatingPointTy()) { // Casting from floating pt
2569 } else if (SrcTy->isVectorTy()) { // Casting from vector
2570 return DestBits == SrcBits;
2571 } else { // Casting from something else
2572 return SrcTy->isPointerTy();
2574 } else if (DestTy->isFloatingPointTy()) { // Casting to floating pt
2575 if (SrcTy->isIntegerTy()) { // Casting from integral
2577 } else if (SrcTy->isFloatingPointTy()) { // Casting from floating pt
2579 } else if (SrcTy->isVectorTy()) { // Casting from vector
2580 return DestBits == SrcBits;
2581 } else { // Casting from something else
2584 } else if (DestTy->isVectorTy()) { // Casting to vector
2585 return DestBits == SrcBits;
2586 } else if (DestTy->isPointerTy()) { // Casting to pointer
2587 if (SrcTy->isPointerTy()) { // Casting from pointer
2589 } else if (SrcTy->isIntegerTy()) { // Casting from integral
2591 } else { // Casting from something else
2594 } else if (DestTy->isX86_MMXTy()) {
2595 if (SrcTy->isVectorTy()) {
2596 return DestBits == SrcBits; // 64-bit vector to MMX
2600 } else { // Casting to something else
2605 // Provide a way to get a "cast" where the cast opcode is inferred from the
2606 // types and size of the operand. This, basically, is a parallel of the
2607 // logic in the castIsValid function below. This axiom should hold:
2608 // castIsValid( getCastOpcode(Val, Ty), Val, Ty)
2609 // should not assert in castIsValid. In other words, this produces a "correct"
2610 // casting opcode for the arguments passed to it.
2611 // This routine must be kept in sync with isCastable.
2612 Instruction::CastOps
2613 CastInst::getCastOpcode(
2614 const Value *Src, bool SrcIsSigned, Type *DestTy, bool DestIsSigned) {
2615 Type *SrcTy = Src->getType();
2617 assert(SrcTy->isFirstClassType() && DestTy->isFirstClassType() &&
2618 "Only first class types are castable!");
2620 if (SrcTy == DestTy)
2623 if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy))
2624 if (VectorType *DestVecTy = dyn_cast<VectorType>(DestTy))
2625 if (SrcVecTy->getNumElements() == DestVecTy->getNumElements()) {
2626 // An element by element cast. Find the appropriate opcode based on the
2628 SrcTy = SrcVecTy->getElementType();
2629 DestTy = DestVecTy->getElementType();
2632 // Get the bit sizes, we'll need these
2633 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); // 0 for ptr
2634 unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr
2636 // Run through the possibilities ...
2637 if (DestTy->isIntegerTy()) { // Casting to integral
2638 if (SrcTy->isIntegerTy()) { // Casting from integral
2639 if (DestBits < SrcBits)
2640 return Trunc; // int -> smaller int
2641 else if (DestBits > SrcBits) { // its an extension
2643 return SExt; // signed -> SEXT
2645 return ZExt; // unsigned -> ZEXT
2647 return BitCast; // Same size, No-op cast
2649 } else if (SrcTy->isFloatingPointTy()) { // Casting from floating pt
2651 return FPToSI; // FP -> sint
2653 return FPToUI; // FP -> uint
2654 } else if (SrcTy->isVectorTy()) {
2655 assert(DestBits == SrcBits &&
2656 "Casting vector to integer of different width");
2657 return BitCast; // Same size, no-op cast
2659 assert(SrcTy->isPointerTy() &&
2660 "Casting from a value that is not first-class type");
2661 return PtrToInt; // ptr -> int
2663 } else if (DestTy->isFloatingPointTy()) { // Casting to floating pt
2664 if (SrcTy->isIntegerTy()) { // Casting from integral
2666 return SIToFP; // sint -> FP
2668 return UIToFP; // uint -> FP
2669 } else if (SrcTy->isFloatingPointTy()) { // Casting from floating pt
2670 if (DestBits < SrcBits) {
2671 return FPTrunc; // FP -> smaller FP
2672 } else if (DestBits > SrcBits) {
2673 return FPExt; // FP -> larger FP
2675 return BitCast; // same size, no-op cast
2677 } else if (SrcTy->isVectorTy()) {
2678 assert(DestBits == SrcBits &&
2679 "Casting vector to floating point of different width");
2680 return BitCast; // same size, no-op cast
2682 llvm_unreachable("Casting pointer or non-first class to float");
2683 } else if (DestTy->isVectorTy()) {
2684 assert(DestBits == SrcBits &&
2685 "Illegal cast to vector (wrong type or size)");
2687 } else if (DestTy->isPointerTy()) {
2688 if (SrcTy->isPointerTy()) {
2689 return BitCast; // ptr -> ptr
2690 } else if (SrcTy->isIntegerTy()) {
2691 return IntToPtr; // int -> ptr
2693 llvm_unreachable("Casting pointer to other than pointer or int");
2694 } else if (DestTy->isX86_MMXTy()) {
2695 if (SrcTy->isVectorTy()) {
2696 assert(DestBits == SrcBits && "Casting vector of wrong width to X86_MMX");
2697 return BitCast; // 64-bit vector to MMX
2699 llvm_unreachable("Illegal cast to X86_MMX");
2701 llvm_unreachable("Casting to type that is not first-class");
2704 //===----------------------------------------------------------------------===//
2705 // CastInst SubClass Constructors
2706 //===----------------------------------------------------------------------===//
2708 /// Check that the construction parameters for a CastInst are correct. This
2709 /// could be broken out into the separate constructors but it is useful to have
2710 /// it in one place and to eliminate the redundant code for getting the sizes
2711 /// of the types involved.
2713 CastInst::castIsValid(Instruction::CastOps op, Value *S, Type *DstTy) {
2715 // Check for type sanity on the arguments
2716 Type *SrcTy = S->getType();
2717 if (!SrcTy->isFirstClassType() || !DstTy->isFirstClassType() ||
2718 SrcTy->isAggregateType() || DstTy->isAggregateType())
2721 // Get the size of the types in bits, we'll need this later
2722 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
2723 unsigned DstBitSize = DstTy->getScalarSizeInBits();
2725 // If these are vector types, get the lengths of the vectors (using zero for
2726 // scalar types means that checking that vector lengths match also checks that
2727 // scalars are not being converted to vectors or vectors to scalars).
2728 unsigned SrcLength = SrcTy->isVectorTy() ?
2729 cast<VectorType>(SrcTy)->getNumElements() : 0;
2730 unsigned DstLength = DstTy->isVectorTy() ?
2731 cast<VectorType>(DstTy)->getNumElements() : 0;
2733 // Switch on the opcode provided
2735 default: return false; // This is an input error
2736 case Instruction::Trunc:
2737 return SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy() &&
2738 SrcLength == DstLength && SrcBitSize > DstBitSize;
2739 case Instruction::ZExt:
2740 return SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy() &&
2741 SrcLength == DstLength && SrcBitSize < DstBitSize;
2742 case Instruction::SExt:
2743 return SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy() &&
2744 SrcLength == DstLength && SrcBitSize < DstBitSize;
2745 case Instruction::FPTrunc:
2746 return SrcTy->isFPOrFPVectorTy() && DstTy->isFPOrFPVectorTy() &&
2747 SrcLength == DstLength && SrcBitSize > DstBitSize;
2748 case Instruction::FPExt:
2749 return SrcTy->isFPOrFPVectorTy() && DstTy->isFPOrFPVectorTy() &&
2750 SrcLength == DstLength && SrcBitSize < DstBitSize;
2751 case Instruction::UIToFP:
2752 case Instruction::SIToFP:
2753 return SrcTy->isIntOrIntVectorTy() && DstTy->isFPOrFPVectorTy() &&
2754 SrcLength == DstLength;
2755 case Instruction::FPToUI:
2756 case Instruction::FPToSI:
2757 return SrcTy->isFPOrFPVectorTy() && DstTy->isIntOrIntVectorTy() &&
2758 SrcLength == DstLength;
2759 case Instruction::PtrToInt:
2760 if (isa<VectorType>(SrcTy) != isa<VectorType>(DstTy))
2762 if (VectorType *VT = dyn_cast<VectorType>(SrcTy))
2763 if (VT->getNumElements() != cast<VectorType>(DstTy)->getNumElements())
2765 return SrcTy->getScalarType()->isPointerTy() &&
2766 DstTy->getScalarType()->isIntegerTy();
2767 case Instruction::IntToPtr:
2768 if (isa<VectorType>(SrcTy) != isa<VectorType>(DstTy))
2770 if (VectorType *VT = dyn_cast<VectorType>(SrcTy))
2771 if (VT->getNumElements() != cast<VectorType>(DstTy)->getNumElements())
2773 return SrcTy->getScalarType()->isIntegerTy() &&
2774 DstTy->getScalarType()->isPointerTy();
2775 case Instruction::BitCast:
2776 // BitCast implies a no-op cast of type only. No bits change.
2777 // However, you can't cast pointers to anything but pointers.
2778 if (SrcTy->isPointerTy() != DstTy->isPointerTy())
2781 // Now we know we're not dealing with a pointer/non-pointer mismatch. In all
2782 // these cases, the cast is okay if the source and destination bit widths
2784 return SrcTy->getPrimitiveSizeInBits() == DstTy->getPrimitiveSizeInBits();
2788 TruncInst::TruncInst(
2789 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2790 ) : CastInst(Ty, Trunc, S, Name, InsertBefore) {
2791 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
2794 TruncInst::TruncInst(
2795 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2796 ) : CastInst(Ty, Trunc, S, Name, InsertAtEnd) {
2797 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
2801 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2802 ) : CastInst(Ty, ZExt, S, Name, InsertBefore) {
2803 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
2807 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2808 ) : CastInst(Ty, ZExt, S, Name, InsertAtEnd) {
2809 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
2812 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2813 ) : CastInst(Ty, SExt, S, Name, InsertBefore) {
2814 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
2818 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2819 ) : CastInst(Ty, SExt, S, Name, InsertAtEnd) {
2820 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
2823 FPTruncInst::FPTruncInst(
2824 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2825 ) : CastInst(Ty, FPTrunc, S, Name, InsertBefore) {
2826 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
2829 FPTruncInst::FPTruncInst(
2830 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2831 ) : CastInst(Ty, FPTrunc, S, Name, InsertAtEnd) {
2832 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
2835 FPExtInst::FPExtInst(
2836 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2837 ) : CastInst(Ty, FPExt, S, Name, InsertBefore) {
2838 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
2841 FPExtInst::FPExtInst(
2842 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2843 ) : CastInst(Ty, FPExt, S, Name, InsertAtEnd) {
2844 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
2847 UIToFPInst::UIToFPInst(
2848 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2849 ) : CastInst(Ty, UIToFP, S, Name, InsertBefore) {
2850 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
2853 UIToFPInst::UIToFPInst(
2854 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2855 ) : CastInst(Ty, UIToFP, S, Name, InsertAtEnd) {
2856 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
2859 SIToFPInst::SIToFPInst(
2860 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2861 ) : CastInst(Ty, SIToFP, S, Name, InsertBefore) {
2862 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
2865 SIToFPInst::SIToFPInst(
2866 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2867 ) : CastInst(Ty, SIToFP, S, Name, InsertAtEnd) {
2868 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
2871 FPToUIInst::FPToUIInst(
2872 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2873 ) : CastInst(Ty, FPToUI, S, Name, InsertBefore) {
2874 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
2877 FPToUIInst::FPToUIInst(
2878 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2879 ) : CastInst(Ty, FPToUI, S, Name, InsertAtEnd) {
2880 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
2883 FPToSIInst::FPToSIInst(
2884 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2885 ) : CastInst(Ty, FPToSI, S, Name, InsertBefore) {
2886 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
2889 FPToSIInst::FPToSIInst(
2890 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2891 ) : CastInst(Ty, FPToSI, S, Name, InsertAtEnd) {
2892 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
2895 PtrToIntInst::PtrToIntInst(
2896 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2897 ) : CastInst(Ty, PtrToInt, S, Name, InsertBefore) {
2898 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
2901 PtrToIntInst::PtrToIntInst(
2902 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2903 ) : CastInst(Ty, PtrToInt, S, Name, InsertAtEnd) {
2904 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
2907 IntToPtrInst::IntToPtrInst(
2908 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2909 ) : CastInst(Ty, IntToPtr, S, Name, InsertBefore) {
2910 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
2913 IntToPtrInst::IntToPtrInst(
2914 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2915 ) : CastInst(Ty, IntToPtr, S, Name, InsertAtEnd) {
2916 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
2919 BitCastInst::BitCastInst(
2920 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2921 ) : CastInst(Ty, BitCast, S, Name, InsertBefore) {
2922 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
2925 BitCastInst::BitCastInst(
2926 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2927 ) : CastInst(Ty, BitCast, S, Name, InsertAtEnd) {
2928 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
2931 //===----------------------------------------------------------------------===//
2933 //===----------------------------------------------------------------------===//
2935 void CmpInst::anchor() {}
2937 CmpInst::CmpInst(Type *ty, OtherOps op, unsigned short predicate,
2938 Value *LHS, Value *RHS, const Twine &Name,
2939 Instruction *InsertBefore)
2940 : Instruction(ty, op,
2941 OperandTraits<CmpInst>::op_begin(this),
2942 OperandTraits<CmpInst>::operands(this),
2946 setPredicate((Predicate)predicate);
2950 CmpInst::CmpInst(Type *ty, OtherOps op, unsigned short predicate,
2951 Value *LHS, Value *RHS, const Twine &Name,
2952 BasicBlock *InsertAtEnd)
2953 : Instruction(ty, op,
2954 OperandTraits<CmpInst>::op_begin(this),
2955 OperandTraits<CmpInst>::operands(this),
2959 setPredicate((Predicate)predicate);
2964 CmpInst::Create(OtherOps Op, unsigned short predicate,
2965 Value *S1, Value *S2,
2966 const Twine &Name, Instruction *InsertBefore) {
2967 if (Op == Instruction::ICmp) {
2969 return new ICmpInst(InsertBefore, CmpInst::Predicate(predicate),
2972 return new ICmpInst(CmpInst::Predicate(predicate),
2977 return new FCmpInst(InsertBefore, CmpInst::Predicate(predicate),
2980 return new FCmpInst(CmpInst::Predicate(predicate),
2985 CmpInst::Create(OtherOps Op, unsigned short predicate, Value *S1, Value *S2,
2986 const Twine &Name, BasicBlock *InsertAtEnd) {
2987 if (Op == Instruction::ICmp) {
2988 return new ICmpInst(*InsertAtEnd, CmpInst::Predicate(predicate),
2991 return new FCmpInst(*InsertAtEnd, CmpInst::Predicate(predicate),
2995 void CmpInst::swapOperands() {
2996 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2999 cast<FCmpInst>(this)->swapOperands();
3002 bool CmpInst::isCommutative() const {
3003 if (const ICmpInst *IC = dyn_cast<ICmpInst>(this))
3004 return IC->isCommutative();
3005 return cast<FCmpInst>(this)->isCommutative();
3008 bool CmpInst::isEquality() const {
3009 if (const ICmpInst *IC = dyn_cast<ICmpInst>(this))
3010 return IC->isEquality();
3011 return cast<FCmpInst>(this)->isEquality();
3015 CmpInst::Predicate CmpInst::getInversePredicate(Predicate pred) {
3017 default: llvm_unreachable("Unknown cmp predicate!");
3018 case ICMP_EQ: return ICMP_NE;
3019 case ICMP_NE: return ICMP_EQ;
3020 case ICMP_UGT: return ICMP_ULE;
3021 case ICMP_ULT: return ICMP_UGE;
3022 case ICMP_UGE: return ICMP_ULT;
3023 case ICMP_ULE: return ICMP_UGT;
3024 case ICMP_SGT: return ICMP_SLE;
3025 case ICMP_SLT: return ICMP_SGE;
3026 case ICMP_SGE: return ICMP_SLT;
3027 case ICMP_SLE: return ICMP_SGT;
3029 case FCMP_OEQ: return FCMP_UNE;
3030 case FCMP_ONE: return FCMP_UEQ;
3031 case FCMP_OGT: return FCMP_ULE;
3032 case FCMP_OLT: return FCMP_UGE;
3033 case FCMP_OGE: return FCMP_ULT;
3034 case FCMP_OLE: return FCMP_UGT;
3035 case FCMP_UEQ: return FCMP_ONE;
3036 case FCMP_UNE: return FCMP_OEQ;
3037 case FCMP_UGT: return FCMP_OLE;
3038 case FCMP_ULT: return FCMP_OGE;
3039 case FCMP_UGE: return FCMP_OLT;
3040 case FCMP_ULE: return FCMP_OGT;
3041 case FCMP_ORD: return FCMP_UNO;
3042 case FCMP_UNO: return FCMP_ORD;
3043 case FCMP_TRUE: return FCMP_FALSE;
3044 case FCMP_FALSE: return FCMP_TRUE;
3048 ICmpInst::Predicate ICmpInst::getSignedPredicate(Predicate pred) {
3050 default: llvm_unreachable("Unknown icmp predicate!");
3051 case ICMP_EQ: case ICMP_NE:
3052 case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE:
3054 case ICMP_UGT: return ICMP_SGT;
3055 case ICMP_ULT: return ICMP_SLT;
3056 case ICMP_UGE: return ICMP_SGE;
3057 case ICMP_ULE: return ICMP_SLE;
3061 ICmpInst::Predicate ICmpInst::getUnsignedPredicate(Predicate pred) {
3063 default: llvm_unreachable("Unknown icmp predicate!");
3064 case ICMP_EQ: case ICMP_NE:
3065 case ICMP_UGT: case ICMP_ULT: case ICMP_UGE: case ICMP_ULE:
3067 case ICMP_SGT: return ICMP_UGT;
3068 case ICMP_SLT: return ICMP_ULT;
3069 case ICMP_SGE: return ICMP_UGE;
3070 case ICMP_SLE: return ICMP_ULE;
3074 /// Initialize a set of values that all satisfy the condition with C.
3077 ICmpInst::makeConstantRange(Predicate pred, const APInt &C) {
3080 uint32_t BitWidth = C.getBitWidth();
3082 default: llvm_unreachable("Invalid ICmp opcode to ConstantRange ctor!");
3083 case ICmpInst::ICMP_EQ: Upper++; break;
3084 case ICmpInst::ICMP_NE: Lower++; break;
3085 case ICmpInst::ICMP_ULT:
3086 Lower = APInt::getMinValue(BitWidth);
3087 // Check for an empty-set condition.
3089 return ConstantRange(BitWidth, /*isFullSet=*/false);
3091 case ICmpInst::ICMP_SLT:
3092 Lower = APInt::getSignedMinValue(BitWidth);
3093 // Check for an empty-set condition.
3095 return ConstantRange(BitWidth, /*isFullSet=*/false);
3097 case ICmpInst::ICMP_UGT:
3098 Lower++; Upper = APInt::getMinValue(BitWidth); // Min = Next(Max)
3099 // Check for an empty-set condition.
3101 return ConstantRange(BitWidth, /*isFullSet=*/false);
3103 case ICmpInst::ICMP_SGT:
3104 Lower++; Upper = APInt::getSignedMinValue(BitWidth); // Min = Next(Max)
3105 // Check for an empty-set condition.
3107 return ConstantRange(BitWidth, /*isFullSet=*/false);
3109 case ICmpInst::ICMP_ULE:
3110 Lower = APInt::getMinValue(BitWidth); Upper++;
3111 // Check for a full-set condition.
3113 return ConstantRange(BitWidth, /*isFullSet=*/true);
3115 case ICmpInst::ICMP_SLE:
3116 Lower = APInt::getSignedMinValue(BitWidth); Upper++;
3117 // Check for a full-set condition.
3119 return ConstantRange(BitWidth, /*isFullSet=*/true);
3121 case ICmpInst::ICMP_UGE:
3122 Upper = APInt::getMinValue(BitWidth); // Min = Next(Max)
3123 // Check for a full-set condition.
3125 return ConstantRange(BitWidth, /*isFullSet=*/true);
3127 case ICmpInst::ICMP_SGE:
3128 Upper = APInt::getSignedMinValue(BitWidth); // Min = Next(Max)
3129 // Check for a full-set condition.
3131 return ConstantRange(BitWidth, /*isFullSet=*/true);
3134 return ConstantRange(Lower, Upper);
3137 CmpInst::Predicate CmpInst::getSwappedPredicate(Predicate pred) {
3139 default: llvm_unreachable("Unknown cmp predicate!");
3140 case ICMP_EQ: case ICMP_NE:
3142 case ICMP_SGT: return ICMP_SLT;
3143 case ICMP_SLT: return ICMP_SGT;
3144 case ICMP_SGE: return ICMP_SLE;
3145 case ICMP_SLE: return ICMP_SGE;
3146 case ICMP_UGT: return ICMP_ULT;
3147 case ICMP_ULT: return ICMP_UGT;
3148 case ICMP_UGE: return ICMP_ULE;
3149 case ICMP_ULE: return ICMP_UGE;
3151 case FCMP_FALSE: case FCMP_TRUE:
3152 case FCMP_OEQ: case FCMP_ONE:
3153 case FCMP_UEQ: case FCMP_UNE:
3154 case FCMP_ORD: case FCMP_UNO:
3156 case FCMP_OGT: return FCMP_OLT;
3157 case FCMP_OLT: return FCMP_OGT;
3158 case FCMP_OGE: return FCMP_OLE;
3159 case FCMP_OLE: return FCMP_OGE;
3160 case FCMP_UGT: return FCMP_ULT;
3161 case FCMP_ULT: return FCMP_UGT;
3162 case FCMP_UGE: return FCMP_ULE;
3163 case FCMP_ULE: return FCMP_UGE;
3167 bool CmpInst::isUnsigned(unsigned short predicate) {
3168 switch (predicate) {
3169 default: return false;
3170 case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_ULE: case ICmpInst::ICMP_UGT:
3171 case ICmpInst::ICMP_UGE: return true;
3175 bool CmpInst::isSigned(unsigned short predicate) {
3176 switch (predicate) {
3177 default: return false;
3178 case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_SLE: case ICmpInst::ICMP_SGT:
3179 case ICmpInst::ICMP_SGE: return true;
3183 bool CmpInst::isOrdered(unsigned short predicate) {
3184 switch (predicate) {
3185 default: return false;
3186 case FCmpInst::FCMP_OEQ: case FCmpInst::FCMP_ONE: case FCmpInst::FCMP_OGT:
3187 case FCmpInst::FCMP_OLT: case FCmpInst::FCMP_OGE: case FCmpInst::FCMP_OLE:
3188 case FCmpInst::FCMP_ORD: return true;
3192 bool CmpInst::isUnordered(unsigned short predicate) {
3193 switch (predicate) {
3194 default: return false;
3195 case FCmpInst::FCMP_UEQ: case FCmpInst::FCMP_UNE: case FCmpInst::FCMP_UGT:
3196 case FCmpInst::FCMP_ULT: case FCmpInst::FCMP_UGE: case FCmpInst::FCMP_ULE:
3197 case FCmpInst::FCMP_UNO: return true;
3201 bool CmpInst::isTrueWhenEqual(unsigned short predicate) {
3203 default: return false;
3204 case ICMP_EQ: case ICMP_UGE: case ICMP_ULE: case ICMP_SGE: case ICMP_SLE:
3205 case FCMP_TRUE: case FCMP_UEQ: case FCMP_UGE: case FCMP_ULE: return true;
3209 bool CmpInst::isFalseWhenEqual(unsigned short predicate) {
3211 case ICMP_NE: case ICMP_UGT: case ICMP_ULT: case ICMP_SGT: case ICMP_SLT:
3212 case FCMP_FALSE: case FCMP_ONE: case FCMP_OGT: case FCMP_OLT: return true;
3213 default: return false;
3218 //===----------------------------------------------------------------------===//
3219 // SwitchInst Implementation
3220 //===----------------------------------------------------------------------===//
3222 void SwitchInst::init(Value *Value, BasicBlock *Default, unsigned NumReserved) {
3223 assert(Value && Default && NumReserved);
3224 ReservedSpace = NumReserved;
3226 OperandList = allocHungoffUses(ReservedSpace);
3228 OperandList[0] = Value;
3229 OperandList[1] = Default;
3232 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
3233 /// switch on and a default destination. The number of additional cases can
3234 /// be specified here to make memory allocation more efficient. This
3235 /// constructor can also autoinsert before another instruction.
3236 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
3237 Instruction *InsertBefore)
3238 : TerminatorInst(Type::getVoidTy(Value->getContext()), Instruction::Switch,
3239 0, 0, InsertBefore) {
3240 init(Value, Default, 2+NumCases*2);
3243 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
3244 /// switch on and a default destination. The number of additional cases can
3245 /// be specified here to make memory allocation more efficient. This
3246 /// constructor also autoinserts at the end of the specified BasicBlock.
3247 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
3248 BasicBlock *InsertAtEnd)
3249 : TerminatorInst(Type::getVoidTy(Value->getContext()), Instruction::Switch,
3250 0, 0, InsertAtEnd) {
3251 init(Value, Default, 2+NumCases*2);
3254 SwitchInst::SwitchInst(const SwitchInst &SI)
3255 : TerminatorInst(SI.getType(), Instruction::Switch, 0, 0) {
3256 init(SI.getCondition(), SI.getDefaultDest(), SI.getNumOperands());
3257 NumOperands = SI.getNumOperands();
3258 Use *OL = OperandList, *InOL = SI.OperandList;
3259 for (unsigned i = 2, E = SI.getNumOperands(); i != E; i += 2) {
3261 OL[i+1] = InOL[i+1];
3263 TheSubsets = SI.TheSubsets;
3264 SubclassOptionalData = SI.SubclassOptionalData;
3267 SwitchInst::~SwitchInst() {
3272 /// addCase - Add an entry to the switch instruction...
3274 void SwitchInst::addCase(ConstantInt *OnVal, BasicBlock *Dest) {
3275 IntegersSubsetToBB Mapping;
3277 // FIXME: Currently we work with ConstantInt based cases.
3278 // So inititalize IntItem container directly from ConstantInt.
3279 Mapping.add(IntItem::fromConstantInt(OnVal));
3280 IntegersSubset CaseRanges = Mapping.getCase();
3281 addCase(CaseRanges, Dest);
3284 void SwitchInst::addCase(IntegersSubset& OnVal, BasicBlock *Dest) {
3285 unsigned NewCaseIdx = getNumCases();
3286 unsigned OpNo = NumOperands;
3287 if (OpNo+2 > ReservedSpace)
3288 growOperands(); // Get more space!
3289 // Initialize some new operands.
3290 assert(OpNo+1 < ReservedSpace && "Growing didn't work!");
3291 NumOperands = OpNo+2;
3293 SubsetsIt TheSubsetsIt = TheSubsets.insert(TheSubsets.end(), OnVal);
3295 CaseIt Case(this, NewCaseIdx, TheSubsetsIt);
3296 Case.updateCaseValueOperand(OnVal);
3297 Case.setSuccessor(Dest);
3300 /// removeCase - This method removes the specified case and its successor
3301 /// from the switch instruction.
3302 void SwitchInst::removeCase(CaseIt& i) {
3303 unsigned idx = i.getCaseIndex();
3305 assert(2 + idx*2 < getNumOperands() && "Case index out of range!!!");
3307 unsigned NumOps = getNumOperands();
3308 Use *OL = OperandList;
3310 // Overwrite this case with the end of the list.
3311 if (2 + (idx + 1) * 2 != NumOps) {
3312 OL[2 + idx * 2] = OL[NumOps - 2];
3313 OL[2 + idx * 2 + 1] = OL[NumOps - 1];
3316 // Nuke the last value.
3317 OL[NumOps-2].set(0);
3318 OL[NumOps-2+1].set(0);
3320 // Do the same with TheCases collection:
3321 if (i.SubsetIt != --TheSubsets.end()) {
3322 *i.SubsetIt = TheSubsets.back();
3323 TheSubsets.pop_back();
3325 TheSubsets.pop_back();
3326 i.SubsetIt = TheSubsets.end();
3329 NumOperands = NumOps-2;
3332 /// growOperands - grow operands - This grows the operand list in response
3333 /// to a push_back style of operation. This grows the number of ops by 3 times.
3335 void SwitchInst::growOperands() {
3336 unsigned e = getNumOperands();
3337 unsigned NumOps = e*3;
3339 ReservedSpace = NumOps;
3340 Use *NewOps = allocHungoffUses(NumOps);
3341 Use *OldOps = OperandList;
3342 for (unsigned i = 0; i != e; ++i) {
3343 NewOps[i] = OldOps[i];
3345 OperandList = NewOps;
3346 Use::zap(OldOps, OldOps + e, true);
3350 BasicBlock *SwitchInst::getSuccessorV(unsigned idx) const {
3351 return getSuccessor(idx);
3353 unsigned SwitchInst::getNumSuccessorsV() const {
3354 return getNumSuccessors();
3356 void SwitchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
3357 setSuccessor(idx, B);
3360 //===----------------------------------------------------------------------===//
3361 // IndirectBrInst Implementation
3362 //===----------------------------------------------------------------------===//
3364 void IndirectBrInst::init(Value *Address, unsigned NumDests) {
3365 assert(Address && Address->getType()->isPointerTy() &&
3366 "Address of indirectbr must be a pointer");
3367 ReservedSpace = 1+NumDests;
3369 OperandList = allocHungoffUses(ReservedSpace);
3371 OperandList[0] = Address;
3375 /// growOperands - grow operands - This grows the operand list in response
3376 /// to a push_back style of operation. This grows the number of ops by 2 times.
3378 void IndirectBrInst::growOperands() {
3379 unsigned e = getNumOperands();
3380 unsigned NumOps = e*2;
3382 ReservedSpace = NumOps;
3383 Use *NewOps = allocHungoffUses(NumOps);
3384 Use *OldOps = OperandList;
3385 for (unsigned i = 0; i != e; ++i)
3386 NewOps[i] = OldOps[i];
3387 OperandList = NewOps;
3388 Use::zap(OldOps, OldOps + e, true);
3391 IndirectBrInst::IndirectBrInst(Value *Address, unsigned NumCases,
3392 Instruction *InsertBefore)
3393 : TerminatorInst(Type::getVoidTy(Address->getContext()),Instruction::IndirectBr,
3394 0, 0, InsertBefore) {
3395 init(Address, NumCases);
3398 IndirectBrInst::IndirectBrInst(Value *Address, unsigned NumCases,
3399 BasicBlock *InsertAtEnd)
3400 : TerminatorInst(Type::getVoidTy(Address->getContext()),Instruction::IndirectBr,
3401 0, 0, InsertAtEnd) {
3402 init(Address, NumCases);
3405 IndirectBrInst::IndirectBrInst(const IndirectBrInst &IBI)
3406 : TerminatorInst(Type::getVoidTy(IBI.getContext()), Instruction::IndirectBr,
3407 allocHungoffUses(IBI.getNumOperands()),
3408 IBI.getNumOperands()) {
3409 Use *OL = OperandList, *InOL = IBI.OperandList;
3410 for (unsigned i = 0, E = IBI.getNumOperands(); i != E; ++i)
3412 SubclassOptionalData = IBI.SubclassOptionalData;
3415 IndirectBrInst::~IndirectBrInst() {
3419 /// addDestination - Add a destination.
3421 void IndirectBrInst::addDestination(BasicBlock *DestBB) {
3422 unsigned OpNo = NumOperands;
3423 if (OpNo+1 > ReservedSpace)
3424 growOperands(); // Get more space!
3425 // Initialize some new operands.
3426 assert(OpNo < ReservedSpace && "Growing didn't work!");
3427 NumOperands = OpNo+1;
3428 OperandList[OpNo] = DestBB;
3431 /// removeDestination - This method removes the specified successor from the
3432 /// indirectbr instruction.
3433 void IndirectBrInst::removeDestination(unsigned idx) {
3434 assert(idx < getNumOperands()-1 && "Successor index out of range!");
3436 unsigned NumOps = getNumOperands();
3437 Use *OL = OperandList;
3439 // Replace this value with the last one.
3440 OL[idx+1] = OL[NumOps-1];
3442 // Nuke the last value.
3443 OL[NumOps-1].set(0);
3444 NumOperands = NumOps-1;
3447 BasicBlock *IndirectBrInst::getSuccessorV(unsigned idx) const {
3448 return getSuccessor(idx);
3450 unsigned IndirectBrInst::getNumSuccessorsV() const {
3451 return getNumSuccessors();
3453 void IndirectBrInst::setSuccessorV(unsigned idx, BasicBlock *B) {
3454 setSuccessor(idx, B);
3457 //===----------------------------------------------------------------------===//
3458 // clone_impl() implementations
3459 //===----------------------------------------------------------------------===//
3461 // Define these methods here so vtables don't get emitted into every translation
3462 // unit that uses these classes.
3464 GetElementPtrInst *GetElementPtrInst::clone_impl() const {
3465 return new (getNumOperands()) GetElementPtrInst(*this);
3468 BinaryOperator *BinaryOperator::clone_impl() const {
3469 return Create(getOpcode(), Op<0>(), Op<1>());
3472 FCmpInst* FCmpInst::clone_impl() const {
3473 return new FCmpInst(getPredicate(), Op<0>(), Op<1>());
3476 ICmpInst* ICmpInst::clone_impl() const {
3477 return new ICmpInst(getPredicate(), Op<0>(), Op<1>());
3480 ExtractValueInst *ExtractValueInst::clone_impl() const {
3481 return new ExtractValueInst(*this);
3484 InsertValueInst *InsertValueInst::clone_impl() const {
3485 return new InsertValueInst(*this);
3488 AllocaInst *AllocaInst::clone_impl() const {
3489 return new AllocaInst(getAllocatedType(),
3490 (Value*)getOperand(0),
3494 LoadInst *LoadInst::clone_impl() const {
3495 return new LoadInst(getOperand(0), Twine(), isVolatile(),
3496 getAlignment(), getOrdering(), getSynchScope());
3499 StoreInst *StoreInst::clone_impl() const {
3500 return new StoreInst(getOperand(0), getOperand(1), isVolatile(),
3501 getAlignment(), getOrdering(), getSynchScope());
3505 AtomicCmpXchgInst *AtomicCmpXchgInst::clone_impl() const {
3506 AtomicCmpXchgInst *Result =
3507 new AtomicCmpXchgInst(getOperand(0), getOperand(1), getOperand(2),
3508 getOrdering(), getSynchScope());
3509 Result->setVolatile(isVolatile());
3513 AtomicRMWInst *AtomicRMWInst::clone_impl() const {
3514 AtomicRMWInst *Result =
3515 new AtomicRMWInst(getOperation(),getOperand(0), getOperand(1),
3516 getOrdering(), getSynchScope());
3517 Result->setVolatile(isVolatile());
3521 FenceInst *FenceInst::clone_impl() const {
3522 return new FenceInst(getContext(), getOrdering(), getSynchScope());
3525 TruncInst *TruncInst::clone_impl() const {
3526 return new TruncInst(getOperand(0), getType());
3529 ZExtInst *ZExtInst::clone_impl() const {
3530 return new ZExtInst(getOperand(0), getType());
3533 SExtInst *SExtInst::clone_impl() const {
3534 return new SExtInst(getOperand(0), getType());
3537 FPTruncInst *FPTruncInst::clone_impl() const {
3538 return new FPTruncInst(getOperand(0), getType());
3541 FPExtInst *FPExtInst::clone_impl() const {
3542 return new FPExtInst(getOperand(0), getType());
3545 UIToFPInst *UIToFPInst::clone_impl() const {
3546 return new UIToFPInst(getOperand(0), getType());
3549 SIToFPInst *SIToFPInst::clone_impl() const {
3550 return new SIToFPInst(getOperand(0), getType());
3553 FPToUIInst *FPToUIInst::clone_impl() const {
3554 return new FPToUIInst(getOperand(0), getType());
3557 FPToSIInst *FPToSIInst::clone_impl() const {
3558 return new FPToSIInst(getOperand(0), getType());
3561 PtrToIntInst *PtrToIntInst::clone_impl() const {
3562 return new PtrToIntInst(getOperand(0), getType());
3565 IntToPtrInst *IntToPtrInst::clone_impl() const {
3566 return new IntToPtrInst(getOperand(0), getType());
3569 BitCastInst *BitCastInst::clone_impl() const {
3570 return new BitCastInst(getOperand(0), getType());
3573 CallInst *CallInst::clone_impl() const {
3574 return new(getNumOperands()) CallInst(*this);
3577 SelectInst *SelectInst::clone_impl() const {
3578 return SelectInst::Create(getOperand(0), getOperand(1), getOperand(2));
3581 VAArgInst *VAArgInst::clone_impl() const {
3582 return new VAArgInst(getOperand(0), getType());
3585 ExtractElementInst *ExtractElementInst::clone_impl() const {
3586 return ExtractElementInst::Create(getOperand(0), getOperand(1));
3589 InsertElementInst *InsertElementInst::clone_impl() const {
3590 return InsertElementInst::Create(getOperand(0), getOperand(1), getOperand(2));
3593 ShuffleVectorInst *ShuffleVectorInst::clone_impl() const {
3594 return new ShuffleVectorInst(getOperand(0), getOperand(1), getOperand(2));
3597 PHINode *PHINode::clone_impl() const {
3598 return new PHINode(*this);
3601 LandingPadInst *LandingPadInst::clone_impl() const {
3602 return new LandingPadInst(*this);
3605 ReturnInst *ReturnInst::clone_impl() const {
3606 return new(getNumOperands()) ReturnInst(*this);
3609 BranchInst *BranchInst::clone_impl() const {
3610 return new(getNumOperands()) BranchInst(*this);
3613 SwitchInst *SwitchInst::clone_impl() const {
3614 return new SwitchInst(*this);
3617 IndirectBrInst *IndirectBrInst::clone_impl() const {
3618 return new IndirectBrInst(*this);
3622 InvokeInst *InvokeInst::clone_impl() const {
3623 return new(getNumOperands()) InvokeInst(*this);
3626 ResumeInst *ResumeInst::clone_impl() const {
3627 return new(1) ResumeInst(*this);
3630 UnreachableInst *UnreachableInst::clone_impl() const {
3631 LLVMContext &Context = getContext();
3632 return new UnreachableInst(Context);