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::fnHasNoAliasAttr() const {
346 if (AttributeList.getParamAttributes(~0U).hasNoAliasAttr())
348 if (const Function *F = getCalledFunction())
349 return F->getParamAttributes(~0U).hasNoAliasAttr();
352 bool CallInst::fnHasNoInlineAttr() const {
353 if (AttributeList.getParamAttributes(~0U).hasNoInlineAttr())
355 if (const Function *F = getCalledFunction())
356 return F->getParamAttributes(~0U).hasNoInlineAttr();
359 bool CallInst::fnHasNoReturnAttr() const {
360 if (AttributeList.getParamAttributes(~0U).hasNoReturnAttr())
362 if (const Function *F = getCalledFunction())
363 return F->getParamAttributes(~0U).hasNoReturnAttr();
366 bool CallInst::fnHasNoUnwindAttr() const {
367 if (AttributeList.getParamAttributes(~0U).hasNoUnwindAttr())
369 if (const Function *F = getCalledFunction())
370 return F->getParamAttributes(~0U).hasNoUnwindAttr();
373 bool CallInst::fnHasReadNoneAttr() const {
374 if (AttributeList.getParamAttributes(~0U).hasReadNoneAttr())
376 if (const Function *F = getCalledFunction())
377 return F->getParamAttributes(~0U).hasReadNoneAttr();
380 bool CallInst::fnHasReadOnlyAttr() const {
381 if (AttributeList.getParamAttributes(~0U).hasReadOnlyAttr())
383 if (const Function *F = getCalledFunction())
384 return F->getParamAttributes(~0U).hasReadOnlyAttr();
387 bool CallInst::fnHasReturnsTwiceAttr() const {
388 if (AttributeList.getParamAttributes(~0U).hasReturnsTwiceAttr())
390 if (const Function *F = getCalledFunction())
391 return F->getParamAttributes(~0U).hasReturnsTwiceAttr();
395 bool CallInst::paramHasSExtAttr(unsigned i) const {
396 if (AttributeList.getParamAttributes(i).hasSExtAttr())
398 if (const Function *F = getCalledFunction())
399 return F->getParamAttributes(i).hasSExtAttr();
403 bool CallInst::paramHasZExtAttr(unsigned i) const {
404 if (AttributeList.getParamAttributes(i).hasZExtAttr())
406 if (const Function *F = getCalledFunction())
407 return F->getParamAttributes(i).hasZExtAttr();
411 bool CallInst::paramHasInRegAttr(unsigned i) const {
412 if (AttributeList.getParamAttributes(i).hasInRegAttr())
414 if (const Function *F = getCalledFunction())
415 return F->getParamAttributes(i).hasInRegAttr();
419 bool CallInst::paramHasStructRetAttr(unsigned i) const {
420 if (AttributeList.getParamAttributes(i).hasStructRetAttr())
422 if (const Function *F = getCalledFunction())
423 return F->getParamAttributes(i).hasStructRetAttr();
427 bool CallInst::paramHasNestAttr(unsigned i) const {
428 if (AttributeList.getParamAttributes(i).hasNestAttr())
430 if (const Function *F = getCalledFunction())
431 return F->getParamAttributes(i).hasNestAttr();
435 bool CallInst::paramHasByValAttr(unsigned i) const {
436 if (AttributeList.getParamAttributes(i).hasByValAttr())
438 if (const Function *F = getCalledFunction())
439 return F->getParamAttributes(i).hasByValAttr();
443 bool CallInst::paramHasNoAliasAttr(unsigned i) const {
444 if (AttributeList.getParamAttributes(i).hasNoAliasAttr())
446 if (const Function *F = getCalledFunction())
447 return F->getParamAttributes(i).hasNoAliasAttr();
451 bool CallInst::paramHasNoCaptureAttr(unsigned i) const {
452 if (AttributeList.getParamAttributes(i).hasNoCaptureAttr())
454 if (const Function *F = getCalledFunction())
455 return F->getParamAttributes(i).hasNoCaptureAttr();
459 bool CallInst::paramHasAttr(unsigned i, Attributes attr) const {
460 if (AttributeList.paramHasAttr(i, attr))
462 if (const Function *F = getCalledFunction())
463 return F->paramHasAttr(i, attr);
467 /// IsConstantOne - Return true only if val is constant int 1
468 static bool IsConstantOne(Value *val) {
469 assert(val && "IsConstantOne does not work with NULL val");
470 return isa<ConstantInt>(val) && cast<ConstantInt>(val)->isOne();
473 static Instruction *createMalloc(Instruction *InsertBefore,
474 BasicBlock *InsertAtEnd, Type *IntPtrTy,
475 Type *AllocTy, Value *AllocSize,
476 Value *ArraySize, Function *MallocF,
478 assert(((!InsertBefore && InsertAtEnd) || (InsertBefore && !InsertAtEnd)) &&
479 "createMalloc needs either InsertBefore or InsertAtEnd");
481 // malloc(type) becomes:
482 // bitcast (i8* malloc(typeSize)) to type*
483 // malloc(type, arraySize) becomes:
484 // bitcast (i8 *malloc(typeSize*arraySize)) to type*
486 ArraySize = ConstantInt::get(IntPtrTy, 1);
487 else if (ArraySize->getType() != IntPtrTy) {
489 ArraySize = CastInst::CreateIntegerCast(ArraySize, IntPtrTy, false,
492 ArraySize = CastInst::CreateIntegerCast(ArraySize, IntPtrTy, false,
496 if (!IsConstantOne(ArraySize)) {
497 if (IsConstantOne(AllocSize)) {
498 AllocSize = ArraySize; // Operand * 1 = Operand
499 } else if (Constant *CO = dyn_cast<Constant>(ArraySize)) {
500 Constant *Scale = ConstantExpr::getIntegerCast(CO, IntPtrTy,
502 // Malloc arg is constant product of type size and array size
503 AllocSize = ConstantExpr::getMul(Scale, cast<Constant>(AllocSize));
505 // Multiply type size by the array size...
507 AllocSize = BinaryOperator::CreateMul(ArraySize, AllocSize,
508 "mallocsize", InsertBefore);
510 AllocSize = BinaryOperator::CreateMul(ArraySize, AllocSize,
511 "mallocsize", InsertAtEnd);
515 assert(AllocSize->getType() == IntPtrTy && "malloc arg is wrong size");
516 // Create the call to Malloc.
517 BasicBlock* BB = InsertBefore ? InsertBefore->getParent() : InsertAtEnd;
518 Module* M = BB->getParent()->getParent();
519 Type *BPTy = Type::getInt8PtrTy(BB->getContext());
520 Value *MallocFunc = MallocF;
522 // prototype malloc as "void *malloc(size_t)"
523 MallocFunc = M->getOrInsertFunction("malloc", BPTy, IntPtrTy, NULL);
524 PointerType *AllocPtrType = PointerType::getUnqual(AllocTy);
525 CallInst *MCall = NULL;
526 Instruction *Result = NULL;
528 MCall = CallInst::Create(MallocFunc, AllocSize, "malloccall", InsertBefore);
530 if (Result->getType() != AllocPtrType)
531 // Create a cast instruction to convert to the right type...
532 Result = new BitCastInst(MCall, AllocPtrType, Name, InsertBefore);
534 MCall = CallInst::Create(MallocFunc, AllocSize, "malloccall");
536 if (Result->getType() != AllocPtrType) {
537 InsertAtEnd->getInstList().push_back(MCall);
538 // Create a cast instruction to convert to the right type...
539 Result = new BitCastInst(MCall, AllocPtrType, Name);
542 MCall->setTailCall();
543 if (Function *F = dyn_cast<Function>(MallocFunc)) {
544 MCall->setCallingConv(F->getCallingConv());
545 if (!F->doesNotAlias(0)) F->setDoesNotAlias(0);
547 assert(!MCall->getType()->isVoidTy() && "Malloc has void return type");
552 /// CreateMalloc - Generate the IR for a call to malloc:
553 /// 1. Compute the malloc call's argument as the specified type's size,
554 /// possibly multiplied by the array size if the array size is not
556 /// 2. Call malloc with that argument.
557 /// 3. Bitcast the result of the malloc call to the specified type.
558 Instruction *CallInst::CreateMalloc(Instruction *InsertBefore,
559 Type *IntPtrTy, Type *AllocTy,
560 Value *AllocSize, Value *ArraySize,
563 return createMalloc(InsertBefore, NULL, IntPtrTy, AllocTy, AllocSize,
564 ArraySize, MallocF, Name);
567 /// CreateMalloc - Generate the IR for a call to malloc:
568 /// 1. Compute the malloc call's argument as the specified type's size,
569 /// possibly multiplied by the array size if the array size is not
571 /// 2. Call malloc with that argument.
572 /// 3. Bitcast the result of the malloc call to the specified type.
573 /// Note: This function does not add the bitcast to the basic block, that is the
574 /// responsibility of the caller.
575 Instruction *CallInst::CreateMalloc(BasicBlock *InsertAtEnd,
576 Type *IntPtrTy, Type *AllocTy,
577 Value *AllocSize, Value *ArraySize,
578 Function *MallocF, const Twine &Name) {
579 return createMalloc(NULL, InsertAtEnd, IntPtrTy, AllocTy, AllocSize,
580 ArraySize, MallocF, Name);
583 static Instruction* createFree(Value* Source, Instruction *InsertBefore,
584 BasicBlock *InsertAtEnd) {
585 assert(((!InsertBefore && InsertAtEnd) || (InsertBefore && !InsertAtEnd)) &&
586 "createFree needs either InsertBefore or InsertAtEnd");
587 assert(Source->getType()->isPointerTy() &&
588 "Can not free something of nonpointer type!");
590 BasicBlock* BB = InsertBefore ? InsertBefore->getParent() : InsertAtEnd;
591 Module* M = BB->getParent()->getParent();
593 Type *VoidTy = Type::getVoidTy(M->getContext());
594 Type *IntPtrTy = Type::getInt8PtrTy(M->getContext());
595 // prototype free as "void free(void*)"
596 Value *FreeFunc = M->getOrInsertFunction("free", VoidTy, IntPtrTy, NULL);
597 CallInst* Result = NULL;
598 Value *PtrCast = Source;
600 if (Source->getType() != IntPtrTy)
601 PtrCast = new BitCastInst(Source, IntPtrTy, "", InsertBefore);
602 Result = CallInst::Create(FreeFunc, PtrCast, "", InsertBefore);
604 if (Source->getType() != IntPtrTy)
605 PtrCast = new BitCastInst(Source, IntPtrTy, "", InsertAtEnd);
606 Result = CallInst::Create(FreeFunc, PtrCast, "");
608 Result->setTailCall();
609 if (Function *F = dyn_cast<Function>(FreeFunc))
610 Result->setCallingConv(F->getCallingConv());
615 /// CreateFree - Generate the IR for a call to the builtin free function.
616 Instruction * CallInst::CreateFree(Value* Source, Instruction *InsertBefore) {
617 return createFree(Source, InsertBefore, NULL);
620 /// CreateFree - Generate the IR for a call to the builtin free function.
621 /// Note: This function does not add the call to the basic block, that is the
622 /// responsibility of the caller.
623 Instruction* CallInst::CreateFree(Value* Source, BasicBlock *InsertAtEnd) {
624 Instruction* FreeCall = createFree(Source, NULL, InsertAtEnd);
625 assert(FreeCall && "CreateFree did not create a CallInst");
629 //===----------------------------------------------------------------------===//
630 // InvokeInst Implementation
631 //===----------------------------------------------------------------------===//
633 void InvokeInst::init(Value *Fn, BasicBlock *IfNormal, BasicBlock *IfException,
634 ArrayRef<Value *> Args, const Twine &NameStr) {
635 assert(NumOperands == 3 + Args.size() && "NumOperands not set up?");
638 Op<-1>() = IfException;
642 cast<FunctionType>(cast<PointerType>(Fn->getType())->getElementType());
644 assert(((Args.size() == FTy->getNumParams()) ||
645 (FTy->isVarArg() && Args.size() > FTy->getNumParams())) &&
646 "Invoking a function with bad signature");
648 for (unsigned i = 0, e = Args.size(); i != e; i++)
649 assert((i >= FTy->getNumParams() ||
650 FTy->getParamType(i) == Args[i]->getType()) &&
651 "Invoking a function with a bad signature!");
654 std::copy(Args.begin(), Args.end(), op_begin());
658 InvokeInst::InvokeInst(const InvokeInst &II)
659 : TerminatorInst(II.getType(), Instruction::Invoke,
660 OperandTraits<InvokeInst>::op_end(this)
661 - II.getNumOperands(),
662 II.getNumOperands()) {
663 setAttributes(II.getAttributes());
664 setCallingConv(II.getCallingConv());
665 std::copy(II.op_begin(), II.op_end(), op_begin());
666 SubclassOptionalData = II.SubclassOptionalData;
669 BasicBlock *InvokeInst::getSuccessorV(unsigned idx) const {
670 return getSuccessor(idx);
672 unsigned InvokeInst::getNumSuccessorsV() const {
673 return getNumSuccessors();
675 void InvokeInst::setSuccessorV(unsigned idx, BasicBlock *B) {
676 return setSuccessor(idx, B);
679 bool InvokeInst::fnHasNoAliasAttr() const {
680 if (AttributeList.getParamAttributes(~0U).hasNoAliasAttr())
682 if (const Function *F = getCalledFunction())
683 return F->getParamAttributes(~0U).hasNoAliasAttr();
686 bool InvokeInst::fnHasNoInlineAttr() const {
687 if (AttributeList.getParamAttributes(~0U).hasNoInlineAttr())
689 if (const Function *F = getCalledFunction())
690 return F->getParamAttributes(~0U).hasNoInlineAttr();
693 bool InvokeInst::fnHasNoReturnAttr() const {
694 if (AttributeList.getParamAttributes(~0U).hasNoReturnAttr())
696 if (const Function *F = getCalledFunction())
697 return F->getParamAttributes(~0U).hasNoReturnAttr();
700 bool InvokeInst::fnHasNoUnwindAttr() const {
701 if (AttributeList.getParamAttributes(~0U).hasNoUnwindAttr())
703 if (const Function *F = getCalledFunction())
704 return F->getParamAttributes(~0U).hasNoUnwindAttr();
707 bool InvokeInst::fnHasReadNoneAttr() const {
708 if (AttributeList.getParamAttributes(~0U).hasReadNoneAttr())
710 if (const Function *F = getCalledFunction())
711 return F->getParamAttributes(~0U).hasReadNoneAttr();
714 bool InvokeInst::fnHasReadOnlyAttr() const {
715 if (AttributeList.getParamAttributes(~0U).hasReadOnlyAttr())
717 if (const Function *F = getCalledFunction())
718 return F->getParamAttributes(~0U).hasReadOnlyAttr();
721 bool InvokeInst::fnHasReturnsTwiceAttr() const {
722 if (AttributeList.getParamAttributes(~0U).hasReturnsTwiceAttr())
724 if (const Function *F = getCalledFunction())
725 return F->getParamAttributes(~0U).hasReturnsTwiceAttr();
729 bool InvokeInst::paramHasSExtAttr(unsigned i) const {
730 if (AttributeList.getParamAttributes(i).hasSExtAttr())
732 if (const Function *F = getCalledFunction())
733 return F->getParamAttributes(i).hasSExtAttr();
737 bool InvokeInst::paramHasZExtAttr(unsigned i) const {
738 if (AttributeList.getParamAttributes(i).hasZExtAttr())
740 if (const Function *F = getCalledFunction())
741 return F->getParamAttributes(i).hasZExtAttr();
745 bool InvokeInst::paramHasInRegAttr(unsigned i) const {
746 if (AttributeList.getParamAttributes(i).hasInRegAttr())
748 if (const Function *F = getCalledFunction())
749 return F->getParamAttributes(i).hasInRegAttr();
753 bool InvokeInst::paramHasStructRetAttr(unsigned i) const {
754 if (AttributeList.getParamAttributes(i).hasStructRetAttr())
756 if (const Function *F = getCalledFunction())
757 return F->getParamAttributes(i).hasStructRetAttr();
761 bool InvokeInst::paramHasNestAttr(unsigned i) const {
762 if (AttributeList.getParamAttributes(i).hasNestAttr())
764 if (const Function *F = getCalledFunction())
765 return F->getParamAttributes(i).hasNestAttr();
769 bool InvokeInst::paramHasByValAttr(unsigned i) const {
770 if (AttributeList.getParamAttributes(i).hasByValAttr())
772 if (const Function *F = getCalledFunction())
773 return F->getParamAttributes(i).hasByValAttr();
777 bool InvokeInst::paramHasNoAliasAttr(unsigned i) const {
778 if (AttributeList.getParamAttributes(i).hasNoAliasAttr())
780 if (const Function *F = getCalledFunction())
781 return F->getParamAttributes(i).hasNoAliasAttr();
785 bool InvokeInst::paramHasNoCaptureAttr(unsigned i) const {
786 if (AttributeList.getParamAttributes(i).hasNoCaptureAttr())
788 if (const Function *F = getCalledFunction())
789 return F->getParamAttributes(i).hasNoCaptureAttr();
793 bool InvokeInst::paramHasAttr(unsigned i, Attributes attr) const {
794 if (AttributeList.paramHasAttr(i, attr))
796 if (const Function *F = getCalledFunction())
797 return F->paramHasAttr(i, attr);
801 void InvokeInst::addAttribute(unsigned i, Attributes attr) {
802 AttrListPtr PAL = getAttributes();
803 PAL = PAL.addAttr(i, attr);
807 void InvokeInst::removeAttribute(unsigned i, Attributes attr) {
808 AttrListPtr PAL = getAttributes();
809 PAL = PAL.removeAttr(i, attr);
813 LandingPadInst *InvokeInst::getLandingPadInst() const {
814 return cast<LandingPadInst>(getUnwindDest()->getFirstNonPHI());
817 //===----------------------------------------------------------------------===//
818 // ReturnInst Implementation
819 //===----------------------------------------------------------------------===//
821 ReturnInst::ReturnInst(const ReturnInst &RI)
822 : TerminatorInst(Type::getVoidTy(RI.getContext()), Instruction::Ret,
823 OperandTraits<ReturnInst>::op_end(this) -
825 RI.getNumOperands()) {
826 if (RI.getNumOperands())
827 Op<0>() = RI.Op<0>();
828 SubclassOptionalData = RI.SubclassOptionalData;
831 ReturnInst::ReturnInst(LLVMContext &C, Value *retVal, Instruction *InsertBefore)
832 : TerminatorInst(Type::getVoidTy(C), Instruction::Ret,
833 OperandTraits<ReturnInst>::op_end(this) - !!retVal, !!retVal,
838 ReturnInst::ReturnInst(LLVMContext &C, Value *retVal, BasicBlock *InsertAtEnd)
839 : TerminatorInst(Type::getVoidTy(C), Instruction::Ret,
840 OperandTraits<ReturnInst>::op_end(this) - !!retVal, !!retVal,
845 ReturnInst::ReturnInst(LLVMContext &Context, BasicBlock *InsertAtEnd)
846 : TerminatorInst(Type::getVoidTy(Context), Instruction::Ret,
847 OperandTraits<ReturnInst>::op_end(this), 0, InsertAtEnd) {
850 unsigned ReturnInst::getNumSuccessorsV() const {
851 return getNumSuccessors();
854 /// Out-of-line ReturnInst method, put here so the C++ compiler can choose to
855 /// emit the vtable for the class in this translation unit.
856 void ReturnInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
857 llvm_unreachable("ReturnInst has no successors!");
860 BasicBlock *ReturnInst::getSuccessorV(unsigned idx) const {
861 llvm_unreachable("ReturnInst has no successors!");
864 ReturnInst::~ReturnInst() {
867 //===----------------------------------------------------------------------===//
868 // ResumeInst Implementation
869 //===----------------------------------------------------------------------===//
871 ResumeInst::ResumeInst(const ResumeInst &RI)
872 : TerminatorInst(Type::getVoidTy(RI.getContext()), Instruction::Resume,
873 OperandTraits<ResumeInst>::op_begin(this), 1) {
874 Op<0>() = RI.Op<0>();
877 ResumeInst::ResumeInst(Value *Exn, Instruction *InsertBefore)
878 : TerminatorInst(Type::getVoidTy(Exn->getContext()), Instruction::Resume,
879 OperandTraits<ResumeInst>::op_begin(this), 1, InsertBefore) {
883 ResumeInst::ResumeInst(Value *Exn, BasicBlock *InsertAtEnd)
884 : TerminatorInst(Type::getVoidTy(Exn->getContext()), Instruction::Resume,
885 OperandTraits<ResumeInst>::op_begin(this), 1, InsertAtEnd) {
889 unsigned ResumeInst::getNumSuccessorsV() const {
890 return getNumSuccessors();
893 void ResumeInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
894 llvm_unreachable("ResumeInst has no successors!");
897 BasicBlock *ResumeInst::getSuccessorV(unsigned idx) const {
898 llvm_unreachable("ResumeInst has no successors!");
901 //===----------------------------------------------------------------------===//
902 // UnreachableInst Implementation
903 //===----------------------------------------------------------------------===//
905 UnreachableInst::UnreachableInst(LLVMContext &Context,
906 Instruction *InsertBefore)
907 : TerminatorInst(Type::getVoidTy(Context), Instruction::Unreachable,
908 0, 0, InsertBefore) {
910 UnreachableInst::UnreachableInst(LLVMContext &Context, BasicBlock *InsertAtEnd)
911 : TerminatorInst(Type::getVoidTy(Context), Instruction::Unreachable,
915 unsigned UnreachableInst::getNumSuccessorsV() const {
916 return getNumSuccessors();
919 void UnreachableInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
920 llvm_unreachable("UnreachableInst has no successors!");
923 BasicBlock *UnreachableInst::getSuccessorV(unsigned idx) const {
924 llvm_unreachable("UnreachableInst has no successors!");
927 //===----------------------------------------------------------------------===//
928 // BranchInst Implementation
929 //===----------------------------------------------------------------------===//
931 void BranchInst::AssertOK() {
933 assert(getCondition()->getType()->isIntegerTy(1) &&
934 "May only branch on boolean predicates!");
937 BranchInst::BranchInst(BasicBlock *IfTrue, Instruction *InsertBefore)
938 : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
939 OperandTraits<BranchInst>::op_end(this) - 1,
941 assert(IfTrue != 0 && "Branch destination may not be null!");
944 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
945 Instruction *InsertBefore)
946 : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
947 OperandTraits<BranchInst>::op_end(this) - 3,
957 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *InsertAtEnd)
958 : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
959 OperandTraits<BranchInst>::op_end(this) - 1,
961 assert(IfTrue != 0 && "Branch destination may not be null!");
965 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
966 BasicBlock *InsertAtEnd)
967 : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
968 OperandTraits<BranchInst>::op_end(this) - 3,
979 BranchInst::BranchInst(const BranchInst &BI) :
980 TerminatorInst(Type::getVoidTy(BI.getContext()), Instruction::Br,
981 OperandTraits<BranchInst>::op_end(this) - BI.getNumOperands(),
982 BI.getNumOperands()) {
983 Op<-1>() = BI.Op<-1>();
984 if (BI.getNumOperands() != 1) {
985 assert(BI.getNumOperands() == 3 && "BR can have 1 or 3 operands!");
986 Op<-3>() = BI.Op<-3>();
987 Op<-2>() = BI.Op<-2>();
989 SubclassOptionalData = BI.SubclassOptionalData;
992 void BranchInst::swapSuccessors() {
993 assert(isConditional() &&
994 "Cannot swap successors of an unconditional branch");
995 Op<-1>().swap(Op<-2>());
997 // Update profile metadata if present and it matches our structural
999 MDNode *ProfileData = getMetadata(LLVMContext::MD_prof);
1000 if (!ProfileData || ProfileData->getNumOperands() != 3)
1003 // The first operand is the name. Fetch them backwards and build a new one.
1005 ProfileData->getOperand(0),
1006 ProfileData->getOperand(2),
1007 ProfileData->getOperand(1)
1009 setMetadata(LLVMContext::MD_prof,
1010 MDNode::get(ProfileData->getContext(), Ops));
1013 BasicBlock *BranchInst::getSuccessorV(unsigned idx) const {
1014 return getSuccessor(idx);
1016 unsigned BranchInst::getNumSuccessorsV() const {
1017 return getNumSuccessors();
1019 void BranchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
1020 setSuccessor(idx, B);
1024 //===----------------------------------------------------------------------===//
1025 // AllocaInst Implementation
1026 //===----------------------------------------------------------------------===//
1028 static Value *getAISize(LLVMContext &Context, Value *Amt) {
1030 Amt = ConstantInt::get(Type::getInt32Ty(Context), 1);
1032 assert(!isa<BasicBlock>(Amt) &&
1033 "Passed basic block into allocation size parameter! Use other ctor");
1034 assert(Amt->getType()->isIntegerTy() &&
1035 "Allocation array size is not an integer!");
1040 AllocaInst::AllocaInst(Type *Ty, Value *ArraySize,
1041 const Twine &Name, Instruction *InsertBefore)
1042 : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
1043 getAISize(Ty->getContext(), ArraySize), InsertBefore) {
1045 assert(!Ty->isVoidTy() && "Cannot allocate void!");
1049 AllocaInst::AllocaInst(Type *Ty, Value *ArraySize,
1050 const Twine &Name, BasicBlock *InsertAtEnd)
1051 : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
1052 getAISize(Ty->getContext(), ArraySize), InsertAtEnd) {
1054 assert(!Ty->isVoidTy() && "Cannot allocate void!");
1058 AllocaInst::AllocaInst(Type *Ty, const Twine &Name,
1059 Instruction *InsertBefore)
1060 : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
1061 getAISize(Ty->getContext(), 0), InsertBefore) {
1063 assert(!Ty->isVoidTy() && "Cannot allocate void!");
1067 AllocaInst::AllocaInst(Type *Ty, const Twine &Name,
1068 BasicBlock *InsertAtEnd)
1069 : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
1070 getAISize(Ty->getContext(), 0), InsertAtEnd) {
1072 assert(!Ty->isVoidTy() && "Cannot allocate void!");
1076 AllocaInst::AllocaInst(Type *Ty, Value *ArraySize, unsigned Align,
1077 const Twine &Name, Instruction *InsertBefore)
1078 : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
1079 getAISize(Ty->getContext(), ArraySize), InsertBefore) {
1080 setAlignment(Align);
1081 assert(!Ty->isVoidTy() && "Cannot allocate void!");
1085 AllocaInst::AllocaInst(Type *Ty, Value *ArraySize, unsigned Align,
1086 const Twine &Name, BasicBlock *InsertAtEnd)
1087 : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
1088 getAISize(Ty->getContext(), ArraySize), InsertAtEnd) {
1089 setAlignment(Align);
1090 assert(!Ty->isVoidTy() && "Cannot allocate void!");
1094 // Out of line virtual method, so the vtable, etc has a home.
1095 AllocaInst::~AllocaInst() {
1098 void AllocaInst::setAlignment(unsigned Align) {
1099 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
1100 assert(Align <= MaximumAlignment &&
1101 "Alignment is greater than MaximumAlignment!");
1102 setInstructionSubclassData(Log2_32(Align) + 1);
1103 assert(getAlignment() == Align && "Alignment representation error!");
1106 bool AllocaInst::isArrayAllocation() const {
1107 if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(0)))
1108 return !CI->isOne();
1112 Type *AllocaInst::getAllocatedType() const {
1113 return getType()->getElementType();
1116 /// isStaticAlloca - Return true if this alloca is in the entry block of the
1117 /// function and is a constant size. If so, the code generator will fold it
1118 /// into the prolog/epilog code, so it is basically free.
1119 bool AllocaInst::isStaticAlloca() const {
1120 // Must be constant size.
1121 if (!isa<ConstantInt>(getArraySize())) return false;
1123 // Must be in the entry block.
1124 const BasicBlock *Parent = getParent();
1125 return Parent == &Parent->getParent()->front();
1128 //===----------------------------------------------------------------------===//
1129 // LoadInst Implementation
1130 //===----------------------------------------------------------------------===//
1132 void LoadInst::AssertOK() {
1133 assert(getOperand(0)->getType()->isPointerTy() &&
1134 "Ptr must have pointer type.");
1135 assert(!(isAtomic() && getAlignment() == 0) &&
1136 "Alignment required for atomic load");
1139 LoadInst::LoadInst(Value *Ptr, const Twine &Name, Instruction *InsertBef)
1140 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1141 Load, Ptr, InsertBef) {
1144 setAtomic(NotAtomic);
1149 LoadInst::LoadInst(Value *Ptr, const Twine &Name, BasicBlock *InsertAE)
1150 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1151 Load, Ptr, InsertAE) {
1154 setAtomic(NotAtomic);
1159 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
1160 Instruction *InsertBef)
1161 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1162 Load, Ptr, InsertBef) {
1163 setVolatile(isVolatile);
1165 setAtomic(NotAtomic);
1170 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
1171 BasicBlock *InsertAE)
1172 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1173 Load, Ptr, InsertAE) {
1174 setVolatile(isVolatile);
1176 setAtomic(NotAtomic);
1181 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
1182 unsigned Align, Instruction *InsertBef)
1183 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1184 Load, Ptr, InsertBef) {
1185 setVolatile(isVolatile);
1186 setAlignment(Align);
1187 setAtomic(NotAtomic);
1192 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
1193 unsigned Align, BasicBlock *InsertAE)
1194 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1195 Load, Ptr, InsertAE) {
1196 setVolatile(isVolatile);
1197 setAlignment(Align);
1198 setAtomic(NotAtomic);
1203 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
1204 unsigned Align, AtomicOrdering Order,
1205 SynchronizationScope SynchScope,
1206 Instruction *InsertBef)
1207 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1208 Load, Ptr, InsertBef) {
1209 setVolatile(isVolatile);
1210 setAlignment(Align);
1211 setAtomic(Order, SynchScope);
1216 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
1217 unsigned Align, AtomicOrdering Order,
1218 SynchronizationScope SynchScope,
1219 BasicBlock *InsertAE)
1220 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1221 Load, Ptr, InsertAE) {
1222 setVolatile(isVolatile);
1223 setAlignment(Align);
1224 setAtomic(Order, SynchScope);
1229 LoadInst::LoadInst(Value *Ptr, const char *Name, Instruction *InsertBef)
1230 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1231 Load, Ptr, InsertBef) {
1234 setAtomic(NotAtomic);
1236 if (Name && Name[0]) setName(Name);
1239 LoadInst::LoadInst(Value *Ptr, const char *Name, BasicBlock *InsertAE)
1240 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1241 Load, Ptr, InsertAE) {
1244 setAtomic(NotAtomic);
1246 if (Name && Name[0]) setName(Name);
1249 LoadInst::LoadInst(Value *Ptr, const char *Name, bool isVolatile,
1250 Instruction *InsertBef)
1251 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1252 Load, Ptr, InsertBef) {
1253 setVolatile(isVolatile);
1255 setAtomic(NotAtomic);
1257 if (Name && Name[0]) setName(Name);
1260 LoadInst::LoadInst(Value *Ptr, const char *Name, bool isVolatile,
1261 BasicBlock *InsertAE)
1262 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1263 Load, Ptr, InsertAE) {
1264 setVolatile(isVolatile);
1266 setAtomic(NotAtomic);
1268 if (Name && Name[0]) setName(Name);
1271 void LoadInst::setAlignment(unsigned Align) {
1272 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
1273 assert(Align <= MaximumAlignment &&
1274 "Alignment is greater than MaximumAlignment!");
1275 setInstructionSubclassData((getSubclassDataFromInstruction() & ~(31 << 1)) |
1276 ((Log2_32(Align)+1)<<1));
1277 assert(getAlignment() == Align && "Alignment representation error!");
1280 //===----------------------------------------------------------------------===//
1281 // StoreInst Implementation
1282 //===----------------------------------------------------------------------===//
1284 void StoreInst::AssertOK() {
1285 assert(getOperand(0) && getOperand(1) && "Both operands must be non-null!");
1286 assert(getOperand(1)->getType()->isPointerTy() &&
1287 "Ptr must have pointer type!");
1288 assert(getOperand(0)->getType() ==
1289 cast<PointerType>(getOperand(1)->getType())->getElementType()
1290 && "Ptr must be a pointer to Val type!");
1291 assert(!(isAtomic() && getAlignment() == 0) &&
1292 "Alignment required for atomic load");
1296 StoreInst::StoreInst(Value *val, Value *addr, Instruction *InsertBefore)
1297 : Instruction(Type::getVoidTy(val->getContext()), Store,
1298 OperandTraits<StoreInst>::op_begin(this),
1299 OperandTraits<StoreInst>::operands(this),
1305 setAtomic(NotAtomic);
1309 StoreInst::StoreInst(Value *val, Value *addr, BasicBlock *InsertAtEnd)
1310 : Instruction(Type::getVoidTy(val->getContext()), Store,
1311 OperandTraits<StoreInst>::op_begin(this),
1312 OperandTraits<StoreInst>::operands(this),
1318 setAtomic(NotAtomic);
1322 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1323 Instruction *InsertBefore)
1324 : Instruction(Type::getVoidTy(val->getContext()), Store,
1325 OperandTraits<StoreInst>::op_begin(this),
1326 OperandTraits<StoreInst>::operands(this),
1330 setVolatile(isVolatile);
1332 setAtomic(NotAtomic);
1336 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1337 unsigned Align, Instruction *InsertBefore)
1338 : Instruction(Type::getVoidTy(val->getContext()), Store,
1339 OperandTraits<StoreInst>::op_begin(this),
1340 OperandTraits<StoreInst>::operands(this),
1344 setVolatile(isVolatile);
1345 setAlignment(Align);
1346 setAtomic(NotAtomic);
1350 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1351 unsigned Align, AtomicOrdering Order,
1352 SynchronizationScope SynchScope,
1353 Instruction *InsertBefore)
1354 : Instruction(Type::getVoidTy(val->getContext()), Store,
1355 OperandTraits<StoreInst>::op_begin(this),
1356 OperandTraits<StoreInst>::operands(this),
1360 setVolatile(isVolatile);
1361 setAlignment(Align);
1362 setAtomic(Order, SynchScope);
1366 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1367 BasicBlock *InsertAtEnd)
1368 : Instruction(Type::getVoidTy(val->getContext()), Store,
1369 OperandTraits<StoreInst>::op_begin(this),
1370 OperandTraits<StoreInst>::operands(this),
1374 setVolatile(isVolatile);
1376 setAtomic(NotAtomic);
1380 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1381 unsigned Align, BasicBlock *InsertAtEnd)
1382 : Instruction(Type::getVoidTy(val->getContext()), Store,
1383 OperandTraits<StoreInst>::op_begin(this),
1384 OperandTraits<StoreInst>::operands(this),
1388 setVolatile(isVolatile);
1389 setAlignment(Align);
1390 setAtomic(NotAtomic);
1394 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1395 unsigned Align, AtomicOrdering Order,
1396 SynchronizationScope SynchScope,
1397 BasicBlock *InsertAtEnd)
1398 : Instruction(Type::getVoidTy(val->getContext()), Store,
1399 OperandTraits<StoreInst>::op_begin(this),
1400 OperandTraits<StoreInst>::operands(this),
1404 setVolatile(isVolatile);
1405 setAlignment(Align);
1406 setAtomic(Order, SynchScope);
1410 void StoreInst::setAlignment(unsigned Align) {
1411 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
1412 assert(Align <= MaximumAlignment &&
1413 "Alignment is greater than MaximumAlignment!");
1414 setInstructionSubclassData((getSubclassDataFromInstruction() & ~(31 << 1)) |
1415 ((Log2_32(Align)+1) << 1));
1416 assert(getAlignment() == Align && "Alignment representation error!");
1419 //===----------------------------------------------------------------------===//
1420 // AtomicCmpXchgInst Implementation
1421 //===----------------------------------------------------------------------===//
1423 void AtomicCmpXchgInst::Init(Value *Ptr, Value *Cmp, Value *NewVal,
1424 AtomicOrdering Ordering,
1425 SynchronizationScope SynchScope) {
1429 setOrdering(Ordering);
1430 setSynchScope(SynchScope);
1432 assert(getOperand(0) && getOperand(1) && getOperand(2) &&
1433 "All operands must be non-null!");
1434 assert(getOperand(0)->getType()->isPointerTy() &&
1435 "Ptr must have pointer type!");
1436 assert(getOperand(1)->getType() ==
1437 cast<PointerType>(getOperand(0)->getType())->getElementType()
1438 && "Ptr must be a pointer to Cmp type!");
1439 assert(getOperand(2)->getType() ==
1440 cast<PointerType>(getOperand(0)->getType())->getElementType()
1441 && "Ptr must be a pointer to NewVal type!");
1442 assert(Ordering != NotAtomic &&
1443 "AtomicCmpXchg instructions must be atomic!");
1446 AtomicCmpXchgInst::AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal,
1447 AtomicOrdering Ordering,
1448 SynchronizationScope SynchScope,
1449 Instruction *InsertBefore)
1450 : Instruction(Cmp->getType(), AtomicCmpXchg,
1451 OperandTraits<AtomicCmpXchgInst>::op_begin(this),
1452 OperandTraits<AtomicCmpXchgInst>::operands(this),
1454 Init(Ptr, Cmp, NewVal, Ordering, SynchScope);
1457 AtomicCmpXchgInst::AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal,
1458 AtomicOrdering Ordering,
1459 SynchronizationScope SynchScope,
1460 BasicBlock *InsertAtEnd)
1461 : Instruction(Cmp->getType(), AtomicCmpXchg,
1462 OperandTraits<AtomicCmpXchgInst>::op_begin(this),
1463 OperandTraits<AtomicCmpXchgInst>::operands(this),
1465 Init(Ptr, Cmp, NewVal, Ordering, SynchScope);
1468 //===----------------------------------------------------------------------===//
1469 // AtomicRMWInst Implementation
1470 //===----------------------------------------------------------------------===//
1472 void AtomicRMWInst::Init(BinOp Operation, Value *Ptr, Value *Val,
1473 AtomicOrdering Ordering,
1474 SynchronizationScope SynchScope) {
1477 setOperation(Operation);
1478 setOrdering(Ordering);
1479 setSynchScope(SynchScope);
1481 assert(getOperand(0) && getOperand(1) &&
1482 "All operands must be non-null!");
1483 assert(getOperand(0)->getType()->isPointerTy() &&
1484 "Ptr must have pointer type!");
1485 assert(getOperand(1)->getType() ==
1486 cast<PointerType>(getOperand(0)->getType())->getElementType()
1487 && "Ptr must be a pointer to Val type!");
1488 assert(Ordering != NotAtomic &&
1489 "AtomicRMW instructions must be atomic!");
1492 AtomicRMWInst::AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val,
1493 AtomicOrdering Ordering,
1494 SynchronizationScope SynchScope,
1495 Instruction *InsertBefore)
1496 : Instruction(Val->getType(), AtomicRMW,
1497 OperandTraits<AtomicRMWInst>::op_begin(this),
1498 OperandTraits<AtomicRMWInst>::operands(this),
1500 Init(Operation, Ptr, Val, Ordering, SynchScope);
1503 AtomicRMWInst::AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val,
1504 AtomicOrdering Ordering,
1505 SynchronizationScope SynchScope,
1506 BasicBlock *InsertAtEnd)
1507 : Instruction(Val->getType(), AtomicRMW,
1508 OperandTraits<AtomicRMWInst>::op_begin(this),
1509 OperandTraits<AtomicRMWInst>::operands(this),
1511 Init(Operation, Ptr, Val, Ordering, SynchScope);
1514 //===----------------------------------------------------------------------===//
1515 // FenceInst Implementation
1516 //===----------------------------------------------------------------------===//
1518 FenceInst::FenceInst(LLVMContext &C, AtomicOrdering Ordering,
1519 SynchronizationScope SynchScope,
1520 Instruction *InsertBefore)
1521 : Instruction(Type::getVoidTy(C), Fence, 0, 0, InsertBefore) {
1522 setOrdering(Ordering);
1523 setSynchScope(SynchScope);
1526 FenceInst::FenceInst(LLVMContext &C, AtomicOrdering Ordering,
1527 SynchronizationScope SynchScope,
1528 BasicBlock *InsertAtEnd)
1529 : Instruction(Type::getVoidTy(C), Fence, 0, 0, InsertAtEnd) {
1530 setOrdering(Ordering);
1531 setSynchScope(SynchScope);
1534 //===----------------------------------------------------------------------===//
1535 // GetElementPtrInst Implementation
1536 //===----------------------------------------------------------------------===//
1538 void GetElementPtrInst::init(Value *Ptr, ArrayRef<Value *> IdxList,
1539 const Twine &Name) {
1540 assert(NumOperands == 1 + IdxList.size() && "NumOperands not initialized?");
1541 OperandList[0] = Ptr;
1542 std::copy(IdxList.begin(), IdxList.end(), op_begin() + 1);
1546 GetElementPtrInst::GetElementPtrInst(const GetElementPtrInst &GEPI)
1547 : Instruction(GEPI.getType(), GetElementPtr,
1548 OperandTraits<GetElementPtrInst>::op_end(this)
1549 - GEPI.getNumOperands(),
1550 GEPI.getNumOperands()) {
1551 std::copy(GEPI.op_begin(), GEPI.op_end(), op_begin());
1552 SubclassOptionalData = GEPI.SubclassOptionalData;
1555 /// getIndexedType - Returns the type of the element that would be accessed with
1556 /// a gep instruction with the specified parameters.
1558 /// The Idxs pointer should point to a continuous piece of memory containing the
1559 /// indices, either as Value* or uint64_t.
1561 /// A null type is returned if the indices are invalid for the specified
1564 template <typename IndexTy>
1565 static Type *getIndexedTypeInternal(Type *Ptr, ArrayRef<IndexTy> IdxList) {
1566 if (Ptr->isVectorTy()) {
1567 assert(IdxList.size() == 1 &&
1568 "GEP with vector pointers must have a single index");
1569 PointerType *PTy = dyn_cast<PointerType>(
1570 cast<VectorType>(Ptr)->getElementType());
1571 assert(PTy && "Gep with invalid vector pointer found");
1572 return PTy->getElementType();
1575 PointerType *PTy = dyn_cast<PointerType>(Ptr);
1576 if (!PTy) return 0; // Type isn't a pointer type!
1577 Type *Agg = PTy->getElementType();
1579 // Handle the special case of the empty set index set, which is always valid.
1580 if (IdxList.empty())
1583 // If there is at least one index, the top level type must be sized, otherwise
1584 // it cannot be 'stepped over'.
1585 if (!Agg->isSized())
1588 unsigned CurIdx = 1;
1589 for (; CurIdx != IdxList.size(); ++CurIdx) {
1590 CompositeType *CT = dyn_cast<CompositeType>(Agg);
1591 if (!CT || CT->isPointerTy()) return 0;
1592 IndexTy Index = IdxList[CurIdx];
1593 if (!CT->indexValid(Index)) return 0;
1594 Agg = CT->getTypeAtIndex(Index);
1596 return CurIdx == IdxList.size() ? Agg : 0;
1599 Type *GetElementPtrInst::getIndexedType(Type *Ptr, ArrayRef<Value *> IdxList) {
1600 return getIndexedTypeInternal(Ptr, IdxList);
1603 Type *GetElementPtrInst::getIndexedType(Type *Ptr,
1604 ArrayRef<Constant *> IdxList) {
1605 return getIndexedTypeInternal(Ptr, IdxList);
1608 Type *GetElementPtrInst::getIndexedType(Type *Ptr, ArrayRef<uint64_t> IdxList) {
1609 return getIndexedTypeInternal(Ptr, IdxList);
1612 unsigned GetElementPtrInst::getAddressSpace(Value *Ptr) {
1613 Type *Ty = Ptr->getType();
1615 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
1616 Ty = VTy->getElementType();
1618 if (PointerType *PTy = dyn_cast<PointerType>(Ty))
1619 return PTy->getAddressSpace();
1621 llvm_unreachable("Invalid GEP pointer type");
1624 /// hasAllZeroIndices - Return true if all of the indices of this GEP are
1625 /// zeros. If so, the result pointer and the first operand have the same
1626 /// value, just potentially different types.
1627 bool GetElementPtrInst::hasAllZeroIndices() const {
1628 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1629 if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(i))) {
1630 if (!CI->isZero()) return false;
1638 /// hasAllConstantIndices - Return true if all of the indices of this GEP are
1639 /// constant integers. If so, the result pointer and the first operand have
1640 /// a constant offset between them.
1641 bool GetElementPtrInst::hasAllConstantIndices() const {
1642 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1643 if (!isa<ConstantInt>(getOperand(i)))
1649 void GetElementPtrInst::setIsInBounds(bool B) {
1650 cast<GEPOperator>(this)->setIsInBounds(B);
1653 bool GetElementPtrInst::isInBounds() const {
1654 return cast<GEPOperator>(this)->isInBounds();
1657 //===----------------------------------------------------------------------===//
1658 // ExtractElementInst Implementation
1659 //===----------------------------------------------------------------------===//
1661 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
1663 Instruction *InsertBef)
1664 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1666 OperandTraits<ExtractElementInst>::op_begin(this),
1668 assert(isValidOperands(Val, Index) &&
1669 "Invalid extractelement instruction operands!");
1675 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
1677 BasicBlock *InsertAE)
1678 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1680 OperandTraits<ExtractElementInst>::op_begin(this),
1682 assert(isValidOperands(Val, Index) &&
1683 "Invalid extractelement instruction operands!");
1691 bool ExtractElementInst::isValidOperands(const Value *Val, const Value *Index) {
1692 if (!Val->getType()->isVectorTy() || !Index->getType()->isIntegerTy(32))
1698 //===----------------------------------------------------------------------===//
1699 // InsertElementInst Implementation
1700 //===----------------------------------------------------------------------===//
1702 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
1704 Instruction *InsertBef)
1705 : Instruction(Vec->getType(), InsertElement,
1706 OperandTraits<InsertElementInst>::op_begin(this),
1708 assert(isValidOperands(Vec, Elt, Index) &&
1709 "Invalid insertelement instruction operands!");
1716 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
1718 BasicBlock *InsertAE)
1719 : Instruction(Vec->getType(), InsertElement,
1720 OperandTraits<InsertElementInst>::op_begin(this),
1722 assert(isValidOperands(Vec, Elt, Index) &&
1723 "Invalid insertelement instruction operands!");
1731 bool InsertElementInst::isValidOperands(const Value *Vec, const Value *Elt,
1732 const Value *Index) {
1733 if (!Vec->getType()->isVectorTy())
1734 return false; // First operand of insertelement must be vector type.
1736 if (Elt->getType() != cast<VectorType>(Vec->getType())->getElementType())
1737 return false;// Second operand of insertelement must be vector element type.
1739 if (!Index->getType()->isIntegerTy(32))
1740 return false; // Third operand of insertelement must be i32.
1745 //===----------------------------------------------------------------------===//
1746 // ShuffleVectorInst Implementation
1747 //===----------------------------------------------------------------------===//
1749 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1751 Instruction *InsertBefore)
1752 : Instruction(VectorType::get(cast<VectorType>(V1->getType())->getElementType(),
1753 cast<VectorType>(Mask->getType())->getNumElements()),
1755 OperandTraits<ShuffleVectorInst>::op_begin(this),
1756 OperandTraits<ShuffleVectorInst>::operands(this),
1758 assert(isValidOperands(V1, V2, Mask) &&
1759 "Invalid shuffle vector instruction operands!");
1766 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1768 BasicBlock *InsertAtEnd)
1769 : Instruction(VectorType::get(cast<VectorType>(V1->getType())->getElementType(),
1770 cast<VectorType>(Mask->getType())->getNumElements()),
1772 OperandTraits<ShuffleVectorInst>::op_begin(this),
1773 OperandTraits<ShuffleVectorInst>::operands(this),
1775 assert(isValidOperands(V1, V2, Mask) &&
1776 "Invalid shuffle vector instruction operands!");
1784 bool ShuffleVectorInst::isValidOperands(const Value *V1, const Value *V2,
1785 const Value *Mask) {
1786 // V1 and V2 must be vectors of the same type.
1787 if (!V1->getType()->isVectorTy() || V1->getType() != V2->getType())
1790 // Mask must be vector of i32.
1791 VectorType *MaskTy = dyn_cast<VectorType>(Mask->getType());
1792 if (MaskTy == 0 || !MaskTy->getElementType()->isIntegerTy(32))
1795 // Check to see if Mask is valid.
1796 if (isa<UndefValue>(Mask) || isa<ConstantAggregateZero>(Mask))
1799 if (const ConstantVector *MV = dyn_cast<ConstantVector>(Mask)) {
1800 unsigned V1Size = cast<VectorType>(V1->getType())->getNumElements();
1801 for (unsigned i = 0, e = MV->getNumOperands(); i != e; ++i) {
1802 if (ConstantInt *CI = dyn_cast<ConstantInt>(MV->getOperand(i))) {
1803 if (CI->uge(V1Size*2))
1805 } else if (!isa<UndefValue>(MV->getOperand(i))) {
1812 if (const ConstantDataSequential *CDS =
1813 dyn_cast<ConstantDataSequential>(Mask)) {
1814 unsigned V1Size = cast<VectorType>(V1->getType())->getNumElements();
1815 for (unsigned i = 0, e = MaskTy->getNumElements(); i != e; ++i)
1816 if (CDS->getElementAsInteger(i) >= V1Size*2)
1821 // The bitcode reader can create a place holder for a forward reference
1822 // used as the shuffle mask. When this occurs, the shuffle mask will
1823 // fall into this case and fail. To avoid this error, do this bit of
1824 // ugliness to allow such a mask pass.
1825 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(Mask))
1826 if (CE->getOpcode() == Instruction::UserOp1)
1832 /// getMaskValue - Return the index from the shuffle mask for the specified
1833 /// output result. This is either -1 if the element is undef or a number less
1834 /// than 2*numelements.
1835 int ShuffleVectorInst::getMaskValue(Constant *Mask, unsigned i) {
1836 assert(i < Mask->getType()->getVectorNumElements() && "Index out of range");
1837 if (ConstantDataSequential *CDS =dyn_cast<ConstantDataSequential>(Mask))
1838 return CDS->getElementAsInteger(i);
1839 Constant *C = Mask->getAggregateElement(i);
1840 if (isa<UndefValue>(C))
1842 return cast<ConstantInt>(C)->getZExtValue();
1845 /// getShuffleMask - Return the full mask for this instruction, where each
1846 /// element is the element number and undef's are returned as -1.
1847 void ShuffleVectorInst::getShuffleMask(Constant *Mask,
1848 SmallVectorImpl<int> &Result) {
1849 unsigned NumElts = Mask->getType()->getVectorNumElements();
1851 if (ConstantDataSequential *CDS=dyn_cast<ConstantDataSequential>(Mask)) {
1852 for (unsigned i = 0; i != NumElts; ++i)
1853 Result.push_back(CDS->getElementAsInteger(i));
1856 for (unsigned i = 0; i != NumElts; ++i) {
1857 Constant *C = Mask->getAggregateElement(i);
1858 Result.push_back(isa<UndefValue>(C) ? -1 :
1859 cast<ConstantInt>(C)->getZExtValue());
1864 //===----------------------------------------------------------------------===//
1865 // InsertValueInst Class
1866 //===----------------------------------------------------------------------===//
1868 void InsertValueInst::init(Value *Agg, Value *Val, ArrayRef<unsigned> Idxs,
1869 const Twine &Name) {
1870 assert(NumOperands == 2 && "NumOperands not initialized?");
1872 // There's no fundamental reason why we require at least one index
1873 // (other than weirdness with &*IdxBegin being invalid; see
1874 // getelementptr's init routine for example). But there's no
1875 // present need to support it.
1876 assert(Idxs.size() > 0 && "InsertValueInst must have at least one index");
1878 assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs) ==
1879 Val->getType() && "Inserted value must match indexed type!");
1883 Indices.append(Idxs.begin(), Idxs.end());
1887 InsertValueInst::InsertValueInst(const InsertValueInst &IVI)
1888 : Instruction(IVI.getType(), InsertValue,
1889 OperandTraits<InsertValueInst>::op_begin(this), 2),
1890 Indices(IVI.Indices) {
1891 Op<0>() = IVI.getOperand(0);
1892 Op<1>() = IVI.getOperand(1);
1893 SubclassOptionalData = IVI.SubclassOptionalData;
1896 //===----------------------------------------------------------------------===//
1897 // ExtractValueInst Class
1898 //===----------------------------------------------------------------------===//
1900 void ExtractValueInst::init(ArrayRef<unsigned> Idxs, const Twine &Name) {
1901 assert(NumOperands == 1 && "NumOperands not initialized?");
1903 // There's no fundamental reason why we require at least one index.
1904 // But there's no present need to support it.
1905 assert(Idxs.size() > 0 && "ExtractValueInst must have at least one index");
1907 Indices.append(Idxs.begin(), Idxs.end());
1911 ExtractValueInst::ExtractValueInst(const ExtractValueInst &EVI)
1912 : UnaryInstruction(EVI.getType(), ExtractValue, EVI.getOperand(0)),
1913 Indices(EVI.Indices) {
1914 SubclassOptionalData = EVI.SubclassOptionalData;
1917 // getIndexedType - Returns the type of the element that would be extracted
1918 // with an extractvalue instruction with the specified parameters.
1920 // A null type is returned if the indices are invalid for the specified
1923 Type *ExtractValueInst::getIndexedType(Type *Agg,
1924 ArrayRef<unsigned> Idxs) {
1925 for (unsigned CurIdx = 0; CurIdx != Idxs.size(); ++CurIdx) {
1926 unsigned Index = Idxs[CurIdx];
1927 // We can't use CompositeType::indexValid(Index) here.
1928 // indexValid() always returns true for arrays because getelementptr allows
1929 // out-of-bounds indices. Since we don't allow those for extractvalue and
1930 // insertvalue we need to check array indexing manually.
1931 // Since the only other types we can index into are struct types it's just
1932 // as easy to check those manually as well.
1933 if (ArrayType *AT = dyn_cast<ArrayType>(Agg)) {
1934 if (Index >= AT->getNumElements())
1936 } else if (StructType *ST = dyn_cast<StructType>(Agg)) {
1937 if (Index >= ST->getNumElements())
1940 // Not a valid type to index into.
1944 Agg = cast<CompositeType>(Agg)->getTypeAtIndex(Index);
1946 return const_cast<Type*>(Agg);
1949 //===----------------------------------------------------------------------===//
1950 // BinaryOperator Class
1951 //===----------------------------------------------------------------------===//
1953 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
1954 Type *Ty, const Twine &Name,
1955 Instruction *InsertBefore)
1956 : Instruction(Ty, iType,
1957 OperandTraits<BinaryOperator>::op_begin(this),
1958 OperandTraits<BinaryOperator>::operands(this),
1966 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
1967 Type *Ty, const Twine &Name,
1968 BasicBlock *InsertAtEnd)
1969 : Instruction(Ty, iType,
1970 OperandTraits<BinaryOperator>::op_begin(this),
1971 OperandTraits<BinaryOperator>::operands(this),
1980 void BinaryOperator::init(BinaryOps iType) {
1981 Value *LHS = getOperand(0), *RHS = getOperand(1);
1982 (void)LHS; (void)RHS; // Silence warnings.
1983 assert(LHS->getType() == RHS->getType() &&
1984 "Binary operator operand types must match!");
1989 assert(getType() == LHS->getType() &&
1990 "Arithmetic operation should return same type as operands!");
1991 assert(getType()->isIntOrIntVectorTy() &&
1992 "Tried to create an integer operation on a non-integer type!");
1994 case FAdd: case FSub:
1996 assert(getType() == LHS->getType() &&
1997 "Arithmetic operation should return same type as operands!");
1998 assert(getType()->isFPOrFPVectorTy() &&
1999 "Tried to create a floating-point operation on a "
2000 "non-floating-point type!");
2004 assert(getType() == LHS->getType() &&
2005 "Arithmetic operation should return same type as operands!");
2006 assert((getType()->isIntegerTy() || (getType()->isVectorTy() &&
2007 cast<VectorType>(getType())->getElementType()->isIntegerTy())) &&
2008 "Incorrect operand type (not integer) for S/UDIV");
2011 assert(getType() == LHS->getType() &&
2012 "Arithmetic operation should return same type as operands!");
2013 assert(getType()->isFPOrFPVectorTy() &&
2014 "Incorrect operand type (not floating point) for FDIV");
2018 assert(getType() == LHS->getType() &&
2019 "Arithmetic operation should return same type as operands!");
2020 assert((getType()->isIntegerTy() || (getType()->isVectorTy() &&
2021 cast<VectorType>(getType())->getElementType()->isIntegerTy())) &&
2022 "Incorrect operand type (not integer) for S/UREM");
2025 assert(getType() == LHS->getType() &&
2026 "Arithmetic operation should return same type as operands!");
2027 assert(getType()->isFPOrFPVectorTy() &&
2028 "Incorrect operand type (not floating point) for FREM");
2033 assert(getType() == LHS->getType() &&
2034 "Shift operation should return same type as operands!");
2035 assert((getType()->isIntegerTy() ||
2036 (getType()->isVectorTy() &&
2037 cast<VectorType>(getType())->getElementType()->isIntegerTy())) &&
2038 "Tried to create a shift operation on a non-integral type!");
2042 assert(getType() == LHS->getType() &&
2043 "Logical operation should return same type as operands!");
2044 assert((getType()->isIntegerTy() ||
2045 (getType()->isVectorTy() &&
2046 cast<VectorType>(getType())->getElementType()->isIntegerTy())) &&
2047 "Tried to create a logical operation on a non-integral type!");
2055 BinaryOperator *BinaryOperator::Create(BinaryOps Op, Value *S1, Value *S2,
2057 Instruction *InsertBefore) {
2058 assert(S1->getType() == S2->getType() &&
2059 "Cannot create binary operator with two operands of differing type!");
2060 return new BinaryOperator(Op, S1, S2, S1->getType(), Name, InsertBefore);
2063 BinaryOperator *BinaryOperator::Create(BinaryOps Op, Value *S1, Value *S2,
2065 BasicBlock *InsertAtEnd) {
2066 BinaryOperator *Res = Create(Op, S1, S2, Name);
2067 InsertAtEnd->getInstList().push_back(Res);
2071 BinaryOperator *BinaryOperator::CreateNeg(Value *Op, const Twine &Name,
2072 Instruction *InsertBefore) {
2073 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
2074 return new BinaryOperator(Instruction::Sub,
2076 Op->getType(), Name, InsertBefore);
2079 BinaryOperator *BinaryOperator::CreateNeg(Value *Op, const Twine &Name,
2080 BasicBlock *InsertAtEnd) {
2081 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
2082 return new BinaryOperator(Instruction::Sub,
2084 Op->getType(), Name, InsertAtEnd);
2087 BinaryOperator *BinaryOperator::CreateNSWNeg(Value *Op, const Twine &Name,
2088 Instruction *InsertBefore) {
2089 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
2090 return BinaryOperator::CreateNSWSub(zero, Op, Name, InsertBefore);
2093 BinaryOperator *BinaryOperator::CreateNSWNeg(Value *Op, const Twine &Name,
2094 BasicBlock *InsertAtEnd) {
2095 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
2096 return BinaryOperator::CreateNSWSub(zero, Op, Name, InsertAtEnd);
2099 BinaryOperator *BinaryOperator::CreateNUWNeg(Value *Op, const Twine &Name,
2100 Instruction *InsertBefore) {
2101 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
2102 return BinaryOperator::CreateNUWSub(zero, Op, Name, InsertBefore);
2105 BinaryOperator *BinaryOperator::CreateNUWNeg(Value *Op, const Twine &Name,
2106 BasicBlock *InsertAtEnd) {
2107 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
2108 return BinaryOperator::CreateNUWSub(zero, Op, Name, InsertAtEnd);
2111 BinaryOperator *BinaryOperator::CreateFNeg(Value *Op, const Twine &Name,
2112 Instruction *InsertBefore) {
2113 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
2114 return new BinaryOperator(Instruction::FSub, zero, Op,
2115 Op->getType(), Name, InsertBefore);
2118 BinaryOperator *BinaryOperator::CreateFNeg(Value *Op, const Twine &Name,
2119 BasicBlock *InsertAtEnd) {
2120 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
2121 return new BinaryOperator(Instruction::FSub, zero, Op,
2122 Op->getType(), Name, InsertAtEnd);
2125 BinaryOperator *BinaryOperator::CreateNot(Value *Op, const Twine &Name,
2126 Instruction *InsertBefore) {
2127 Constant *C = Constant::getAllOnesValue(Op->getType());
2128 return new BinaryOperator(Instruction::Xor, Op, C,
2129 Op->getType(), Name, InsertBefore);
2132 BinaryOperator *BinaryOperator::CreateNot(Value *Op, const Twine &Name,
2133 BasicBlock *InsertAtEnd) {
2134 Constant *AllOnes = Constant::getAllOnesValue(Op->getType());
2135 return new BinaryOperator(Instruction::Xor, Op, AllOnes,
2136 Op->getType(), Name, InsertAtEnd);
2140 // isConstantAllOnes - Helper function for several functions below
2141 static inline bool isConstantAllOnes(const Value *V) {
2142 if (const Constant *C = dyn_cast<Constant>(V))
2143 return C->isAllOnesValue();
2147 bool BinaryOperator::isNeg(const Value *V) {
2148 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
2149 if (Bop->getOpcode() == Instruction::Sub)
2150 if (Constant* C = dyn_cast<Constant>(Bop->getOperand(0)))
2151 return C->isNegativeZeroValue();
2155 bool BinaryOperator::isFNeg(const Value *V) {
2156 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
2157 if (Bop->getOpcode() == Instruction::FSub)
2158 if (Constant* C = dyn_cast<Constant>(Bop->getOperand(0)))
2159 return C->isNegativeZeroValue();
2163 bool BinaryOperator::isNot(const Value *V) {
2164 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
2165 return (Bop->getOpcode() == Instruction::Xor &&
2166 (isConstantAllOnes(Bop->getOperand(1)) ||
2167 isConstantAllOnes(Bop->getOperand(0))));
2171 Value *BinaryOperator::getNegArgument(Value *BinOp) {
2172 return cast<BinaryOperator>(BinOp)->getOperand(1);
2175 const Value *BinaryOperator::getNegArgument(const Value *BinOp) {
2176 return getNegArgument(const_cast<Value*>(BinOp));
2179 Value *BinaryOperator::getFNegArgument(Value *BinOp) {
2180 return cast<BinaryOperator>(BinOp)->getOperand(1);
2183 const Value *BinaryOperator::getFNegArgument(const Value *BinOp) {
2184 return getFNegArgument(const_cast<Value*>(BinOp));
2187 Value *BinaryOperator::getNotArgument(Value *BinOp) {
2188 assert(isNot(BinOp) && "getNotArgument on non-'not' instruction!");
2189 BinaryOperator *BO = cast<BinaryOperator>(BinOp);
2190 Value *Op0 = BO->getOperand(0);
2191 Value *Op1 = BO->getOperand(1);
2192 if (isConstantAllOnes(Op0)) return Op1;
2194 assert(isConstantAllOnes(Op1));
2198 const Value *BinaryOperator::getNotArgument(const Value *BinOp) {
2199 return getNotArgument(const_cast<Value*>(BinOp));
2203 // swapOperands - Exchange the two operands to this instruction. This
2204 // instruction is safe to use on any binary instruction and does not
2205 // modify the semantics of the instruction. If the instruction is
2206 // order dependent (SetLT f.e.) the opcode is changed.
2208 bool BinaryOperator::swapOperands() {
2209 if (!isCommutative())
2210 return true; // Can't commute operands
2211 Op<0>().swap(Op<1>());
2215 void BinaryOperator::setHasNoUnsignedWrap(bool b) {
2216 cast<OverflowingBinaryOperator>(this)->setHasNoUnsignedWrap(b);
2219 void BinaryOperator::setHasNoSignedWrap(bool b) {
2220 cast<OverflowingBinaryOperator>(this)->setHasNoSignedWrap(b);
2223 void BinaryOperator::setIsExact(bool b) {
2224 cast<PossiblyExactOperator>(this)->setIsExact(b);
2227 bool BinaryOperator::hasNoUnsignedWrap() const {
2228 return cast<OverflowingBinaryOperator>(this)->hasNoUnsignedWrap();
2231 bool BinaryOperator::hasNoSignedWrap() const {
2232 return cast<OverflowingBinaryOperator>(this)->hasNoSignedWrap();
2235 bool BinaryOperator::isExact() const {
2236 return cast<PossiblyExactOperator>(this)->isExact();
2239 //===----------------------------------------------------------------------===//
2240 // FPMathOperator Class
2241 //===----------------------------------------------------------------------===//
2243 /// getFPAccuracy - Get the maximum error permitted by this operation in ULPs.
2244 /// An accuracy of 0.0 means that the operation should be performed with the
2245 /// default precision.
2246 float FPMathOperator::getFPAccuracy() const {
2248 cast<Instruction>(this)->getMetadata(LLVMContext::MD_fpmath);
2251 ConstantFP *Accuracy = cast<ConstantFP>(MD->getOperand(0));
2252 return Accuracy->getValueAPF().convertToFloat();
2256 //===----------------------------------------------------------------------===//
2258 //===----------------------------------------------------------------------===//
2260 void CastInst::anchor() {}
2262 // Just determine if this cast only deals with integral->integral conversion.
2263 bool CastInst::isIntegerCast() const {
2264 switch (getOpcode()) {
2265 default: return false;
2266 case Instruction::ZExt:
2267 case Instruction::SExt:
2268 case Instruction::Trunc:
2270 case Instruction::BitCast:
2271 return getOperand(0)->getType()->isIntegerTy() &&
2272 getType()->isIntegerTy();
2276 bool CastInst::isLosslessCast() const {
2277 // Only BitCast can be lossless, exit fast if we're not BitCast
2278 if (getOpcode() != Instruction::BitCast)
2281 // Identity cast is always lossless
2282 Type* SrcTy = getOperand(0)->getType();
2283 Type* DstTy = getType();
2287 // Pointer to pointer is always lossless.
2288 if (SrcTy->isPointerTy())
2289 return DstTy->isPointerTy();
2290 return false; // Other types have no identity values
2293 /// This function determines if the CastInst does not require any bits to be
2294 /// changed in order to effect the cast. Essentially, it identifies cases where
2295 /// no code gen is necessary for the cast, hence the name no-op cast. For
2296 /// example, the following are all no-op casts:
2297 /// # bitcast i32* %x to i8*
2298 /// # bitcast <2 x i32> %x to <4 x i16>
2299 /// # ptrtoint i32* %x to i32 ; on 32-bit plaforms only
2300 /// @brief Determine if the described cast is a no-op.
2301 bool CastInst::isNoopCast(Instruction::CastOps Opcode,
2306 default: llvm_unreachable("Invalid CastOp");
2307 case Instruction::Trunc:
2308 case Instruction::ZExt:
2309 case Instruction::SExt:
2310 case Instruction::FPTrunc:
2311 case Instruction::FPExt:
2312 case Instruction::UIToFP:
2313 case Instruction::SIToFP:
2314 case Instruction::FPToUI:
2315 case Instruction::FPToSI:
2316 return false; // These always modify bits
2317 case Instruction::BitCast:
2318 return true; // BitCast never modifies bits.
2319 case Instruction::PtrToInt:
2320 return IntPtrTy->getScalarSizeInBits() ==
2321 DestTy->getScalarSizeInBits();
2322 case Instruction::IntToPtr:
2323 return IntPtrTy->getScalarSizeInBits() ==
2324 SrcTy->getScalarSizeInBits();
2328 /// @brief Determine if a cast is a no-op.
2329 bool CastInst::isNoopCast(Type *IntPtrTy) const {
2330 return isNoopCast(getOpcode(), getOperand(0)->getType(), getType(), IntPtrTy);
2333 /// This function determines if a pair of casts can be eliminated and what
2334 /// opcode should be used in the elimination. This assumes that there are two
2335 /// instructions like this:
2336 /// * %F = firstOpcode SrcTy %x to MidTy
2337 /// * %S = secondOpcode MidTy %F to DstTy
2338 /// The function returns a resultOpcode so these two casts can be replaced with:
2339 /// * %Replacement = resultOpcode %SrcTy %x to DstTy
2340 /// If no such cast is permited, the function returns 0.
2341 unsigned CastInst::isEliminableCastPair(
2342 Instruction::CastOps firstOp, Instruction::CastOps secondOp,
2343 Type *SrcTy, Type *MidTy, Type *DstTy, Type *IntPtrTy) {
2344 // Define the 144 possibilities for these two cast instructions. The values
2345 // in this matrix determine what to do in a given situation and select the
2346 // case in the switch below. The rows correspond to firstOp, the columns
2347 // correspond to secondOp. In looking at the table below, keep in mind
2348 // the following cast properties:
2350 // Size Compare Source Destination
2351 // Operator Src ? Size Type Sign Type Sign
2352 // -------- ------------ ------------------- ---------------------
2353 // TRUNC > Integer Any Integral Any
2354 // ZEXT < Integral Unsigned Integer Any
2355 // SEXT < Integral Signed Integer Any
2356 // FPTOUI n/a FloatPt n/a Integral Unsigned
2357 // FPTOSI n/a FloatPt n/a Integral Signed
2358 // UITOFP n/a Integral Unsigned FloatPt n/a
2359 // SITOFP n/a Integral Signed FloatPt n/a
2360 // FPTRUNC > FloatPt n/a FloatPt n/a
2361 // FPEXT < FloatPt n/a FloatPt n/a
2362 // PTRTOINT n/a Pointer n/a Integral Unsigned
2363 // INTTOPTR n/a Integral Unsigned Pointer n/a
2364 // BITCAST = FirstClass n/a FirstClass n/a
2366 // NOTE: some transforms are safe, but we consider them to be non-profitable.
2367 // For example, we could merge "fptoui double to i32" + "zext i32 to i64",
2368 // into "fptoui double to i64", but this loses information about the range
2369 // of the produced value (we no longer know the top-part is all zeros).
2370 // Further this conversion is often much more expensive for typical hardware,
2371 // and causes issues when building libgcc. We disallow fptosi+sext for the
2373 const unsigned numCastOps =
2374 Instruction::CastOpsEnd - Instruction::CastOpsBegin;
2375 static const uint8_t CastResults[numCastOps][numCastOps] = {
2376 // T F F U S F F P I B -+
2377 // R Z S P P I I T P 2 N T |
2378 // U E E 2 2 2 2 R E I T C +- secondOp
2379 // N X X U S F F N X N 2 V |
2380 // C T T I I P P C T T P T -+
2381 { 1, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // Trunc -+
2382 { 8, 1, 9,99,99, 2, 0,99,99,99, 2, 3 }, // ZExt |
2383 { 8, 0, 1,99,99, 0, 2,99,99,99, 0, 3 }, // SExt |
2384 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // FPToUI |
2385 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // FPToSI |
2386 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4 }, // UIToFP +- firstOp
2387 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4 }, // SIToFP |
2388 { 99,99,99, 0, 0,99,99, 1, 0,99,99, 4 }, // FPTrunc |
2389 { 99,99,99, 2, 2,99,99,10, 2,99,99, 4 }, // FPExt |
2390 { 1, 0, 0,99,99, 0, 0,99,99,99, 7, 3 }, // PtrToInt |
2391 { 99,99,99,99,99,99,99,99,99,13,99,12 }, // IntToPtr |
2392 { 5, 5, 5, 6, 6, 5, 5, 6, 6,11, 5, 1 }, // BitCast -+
2395 // If either of the casts are a bitcast from scalar to vector, disallow the
2396 // merging. However, bitcast of A->B->A are allowed.
2397 bool isFirstBitcast = (firstOp == Instruction::BitCast);
2398 bool isSecondBitcast = (secondOp == Instruction::BitCast);
2399 bool chainedBitcast = (SrcTy == DstTy && isFirstBitcast && isSecondBitcast);
2401 // Check if any of the bitcasts convert scalars<->vectors.
2402 if ((isFirstBitcast && isa<VectorType>(SrcTy) != isa<VectorType>(MidTy)) ||
2403 (isSecondBitcast && isa<VectorType>(MidTy) != isa<VectorType>(DstTy)))
2404 // Unless we are bitcasing to the original type, disallow optimizations.
2405 if (!chainedBitcast) return 0;
2407 int ElimCase = CastResults[firstOp-Instruction::CastOpsBegin]
2408 [secondOp-Instruction::CastOpsBegin];
2411 // categorically disallowed
2414 // allowed, use first cast's opcode
2417 // allowed, use second cast's opcode
2420 // no-op cast in second op implies firstOp as long as the DestTy
2421 // is integer and we are not converting between a vector and a
2423 if (!SrcTy->isVectorTy() && DstTy->isIntegerTy())
2427 // no-op cast in second op implies firstOp as long as the DestTy
2428 // is floating point.
2429 if (DstTy->isFloatingPointTy())
2433 // no-op cast in first op implies secondOp as long as the SrcTy
2435 if (SrcTy->isIntegerTy())
2439 // no-op cast in first op implies secondOp as long as the SrcTy
2440 // is a floating point.
2441 if (SrcTy->isFloatingPointTy())
2445 // ptrtoint, inttoptr -> bitcast (ptr -> ptr) if int size is >= ptr size
2448 unsigned PtrSize = IntPtrTy->getScalarSizeInBits();
2449 unsigned MidSize = MidTy->getScalarSizeInBits();
2450 if (MidSize >= PtrSize)
2451 return Instruction::BitCast;
2455 // ext, trunc -> bitcast, if the SrcTy and DstTy are same size
2456 // ext, trunc -> ext, if sizeof(SrcTy) < sizeof(DstTy)
2457 // ext, trunc -> trunc, if sizeof(SrcTy) > sizeof(DstTy)
2458 unsigned SrcSize = SrcTy->getScalarSizeInBits();
2459 unsigned DstSize = DstTy->getScalarSizeInBits();
2460 if (SrcSize == DstSize)
2461 return Instruction::BitCast;
2462 else if (SrcSize < DstSize)
2466 case 9: // zext, sext -> zext, because sext can't sign extend after zext
2467 return Instruction::ZExt;
2469 // fpext followed by ftrunc is allowed if the bit size returned to is
2470 // the same as the original, in which case its just a bitcast
2472 return Instruction::BitCast;
2473 return 0; // If the types are not the same we can't eliminate it.
2475 // bitcast followed by ptrtoint is allowed as long as the bitcast
2476 // is a pointer to pointer cast.
2477 if (SrcTy->isPointerTy() && MidTy->isPointerTy())
2481 // inttoptr, bitcast -> intptr if bitcast is a ptr to ptr cast
2482 if (MidTy->isPointerTy() && DstTy->isPointerTy())
2486 // inttoptr, ptrtoint -> bitcast if SrcSize<=PtrSize and SrcSize==DstSize
2489 unsigned PtrSize = IntPtrTy->getScalarSizeInBits();
2490 unsigned SrcSize = SrcTy->getScalarSizeInBits();
2491 unsigned DstSize = DstTy->getScalarSizeInBits();
2492 if (SrcSize <= PtrSize && SrcSize == DstSize)
2493 return Instruction::BitCast;
2497 // cast combination can't happen (error in input). This is for all cases
2498 // where the MidTy is not the same for the two cast instructions.
2499 llvm_unreachable("Invalid Cast Combination");
2501 llvm_unreachable("Error in CastResults table!!!");
2505 CastInst *CastInst::Create(Instruction::CastOps op, Value *S, Type *Ty,
2506 const Twine &Name, Instruction *InsertBefore) {
2507 assert(castIsValid(op, S, Ty) && "Invalid cast!");
2508 // Construct and return the appropriate CastInst subclass
2510 case Trunc: return new TruncInst (S, Ty, Name, InsertBefore);
2511 case ZExt: return new ZExtInst (S, Ty, Name, InsertBefore);
2512 case SExt: return new SExtInst (S, Ty, Name, InsertBefore);
2513 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertBefore);
2514 case FPExt: return new FPExtInst (S, Ty, Name, InsertBefore);
2515 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertBefore);
2516 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertBefore);
2517 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertBefore);
2518 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertBefore);
2519 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertBefore);
2520 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertBefore);
2521 case BitCast: return new BitCastInst (S, Ty, Name, InsertBefore);
2522 default: llvm_unreachable("Invalid opcode provided");
2526 CastInst *CastInst::Create(Instruction::CastOps op, Value *S, Type *Ty,
2527 const Twine &Name, BasicBlock *InsertAtEnd) {
2528 assert(castIsValid(op, S, Ty) && "Invalid cast!");
2529 // Construct and return the appropriate CastInst subclass
2531 case Trunc: return new TruncInst (S, Ty, Name, InsertAtEnd);
2532 case ZExt: return new ZExtInst (S, Ty, Name, InsertAtEnd);
2533 case SExt: return new SExtInst (S, Ty, Name, InsertAtEnd);
2534 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertAtEnd);
2535 case FPExt: return new FPExtInst (S, Ty, Name, InsertAtEnd);
2536 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertAtEnd);
2537 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertAtEnd);
2538 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertAtEnd);
2539 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertAtEnd);
2540 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertAtEnd);
2541 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertAtEnd);
2542 case BitCast: return new BitCastInst (S, Ty, Name, InsertAtEnd);
2543 default: llvm_unreachable("Invalid opcode provided");
2547 CastInst *CastInst::CreateZExtOrBitCast(Value *S, Type *Ty,
2549 Instruction *InsertBefore) {
2550 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2551 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2552 return Create(Instruction::ZExt, S, Ty, Name, InsertBefore);
2555 CastInst *CastInst::CreateZExtOrBitCast(Value *S, Type *Ty,
2557 BasicBlock *InsertAtEnd) {
2558 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2559 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2560 return Create(Instruction::ZExt, S, Ty, Name, InsertAtEnd);
2563 CastInst *CastInst::CreateSExtOrBitCast(Value *S, Type *Ty,
2565 Instruction *InsertBefore) {
2566 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2567 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2568 return Create(Instruction::SExt, S, Ty, Name, InsertBefore);
2571 CastInst *CastInst::CreateSExtOrBitCast(Value *S, Type *Ty,
2573 BasicBlock *InsertAtEnd) {
2574 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2575 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2576 return Create(Instruction::SExt, S, Ty, Name, InsertAtEnd);
2579 CastInst *CastInst::CreateTruncOrBitCast(Value *S, Type *Ty,
2581 Instruction *InsertBefore) {
2582 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2583 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2584 return Create(Instruction::Trunc, S, Ty, Name, InsertBefore);
2587 CastInst *CastInst::CreateTruncOrBitCast(Value *S, Type *Ty,
2589 BasicBlock *InsertAtEnd) {
2590 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2591 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2592 return Create(Instruction::Trunc, S, Ty, Name, InsertAtEnd);
2595 CastInst *CastInst::CreatePointerCast(Value *S, Type *Ty,
2597 BasicBlock *InsertAtEnd) {
2598 assert(S->getType()->isPointerTy() && "Invalid cast");
2599 assert((Ty->isIntegerTy() || Ty->isPointerTy()) &&
2602 if (Ty->isIntegerTy())
2603 return Create(Instruction::PtrToInt, S, Ty, Name, InsertAtEnd);
2604 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2607 /// @brief Create a BitCast or a PtrToInt cast instruction
2608 CastInst *CastInst::CreatePointerCast(Value *S, Type *Ty,
2610 Instruction *InsertBefore) {
2611 assert(S->getType()->isPointerTy() && "Invalid cast");
2612 assert((Ty->isIntegerTy() || Ty->isPointerTy()) &&
2615 if (Ty->isIntegerTy())
2616 return Create(Instruction::PtrToInt, S, Ty, Name, InsertBefore);
2617 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2620 CastInst *CastInst::CreateIntegerCast(Value *C, Type *Ty,
2621 bool isSigned, const Twine &Name,
2622 Instruction *InsertBefore) {
2623 assert(C->getType()->isIntOrIntVectorTy() && Ty->isIntOrIntVectorTy() &&
2624 "Invalid integer cast");
2625 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2626 unsigned DstBits = Ty->getScalarSizeInBits();
2627 Instruction::CastOps opcode =
2628 (SrcBits == DstBits ? Instruction::BitCast :
2629 (SrcBits > DstBits ? Instruction::Trunc :
2630 (isSigned ? Instruction::SExt : Instruction::ZExt)));
2631 return Create(opcode, C, Ty, Name, InsertBefore);
2634 CastInst *CastInst::CreateIntegerCast(Value *C, Type *Ty,
2635 bool isSigned, const Twine &Name,
2636 BasicBlock *InsertAtEnd) {
2637 assert(C->getType()->isIntOrIntVectorTy() && Ty->isIntOrIntVectorTy() &&
2639 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2640 unsigned DstBits = Ty->getScalarSizeInBits();
2641 Instruction::CastOps opcode =
2642 (SrcBits == DstBits ? Instruction::BitCast :
2643 (SrcBits > DstBits ? Instruction::Trunc :
2644 (isSigned ? Instruction::SExt : Instruction::ZExt)));
2645 return Create(opcode, C, Ty, Name, InsertAtEnd);
2648 CastInst *CastInst::CreateFPCast(Value *C, Type *Ty,
2650 Instruction *InsertBefore) {
2651 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
2653 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2654 unsigned DstBits = Ty->getScalarSizeInBits();
2655 Instruction::CastOps opcode =
2656 (SrcBits == DstBits ? Instruction::BitCast :
2657 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
2658 return Create(opcode, C, Ty, Name, InsertBefore);
2661 CastInst *CastInst::CreateFPCast(Value *C, Type *Ty,
2663 BasicBlock *InsertAtEnd) {
2664 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
2666 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2667 unsigned DstBits = Ty->getScalarSizeInBits();
2668 Instruction::CastOps opcode =
2669 (SrcBits == DstBits ? Instruction::BitCast :
2670 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
2671 return Create(opcode, C, Ty, Name, InsertAtEnd);
2674 // Check whether it is valid to call getCastOpcode for these types.
2675 // This routine must be kept in sync with getCastOpcode.
2676 bool CastInst::isCastable(Type *SrcTy, Type *DestTy) {
2677 if (!SrcTy->isFirstClassType() || !DestTy->isFirstClassType())
2680 if (SrcTy == DestTy)
2683 if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy))
2684 if (VectorType *DestVecTy = dyn_cast<VectorType>(DestTy))
2685 if (SrcVecTy->getNumElements() == DestVecTy->getNumElements()) {
2686 // An element by element cast. Valid if casting the elements is valid.
2687 SrcTy = SrcVecTy->getElementType();
2688 DestTy = DestVecTy->getElementType();
2691 // Get the bit sizes, we'll need these
2692 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); // 0 for ptr
2693 unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr
2695 // Run through the possibilities ...
2696 if (DestTy->isIntegerTy()) { // Casting to integral
2697 if (SrcTy->isIntegerTy()) { // Casting from integral
2699 } else if (SrcTy->isFloatingPointTy()) { // Casting from floating pt
2701 } else if (SrcTy->isVectorTy()) { // Casting from vector
2702 return DestBits == SrcBits;
2703 } else { // Casting from something else
2704 return SrcTy->isPointerTy();
2706 } else if (DestTy->isFloatingPointTy()) { // Casting to floating pt
2707 if (SrcTy->isIntegerTy()) { // Casting from integral
2709 } else if (SrcTy->isFloatingPointTy()) { // Casting from floating pt
2711 } else if (SrcTy->isVectorTy()) { // Casting from vector
2712 return DestBits == SrcBits;
2713 } else { // Casting from something else
2716 } else if (DestTy->isVectorTy()) { // Casting to vector
2717 return DestBits == SrcBits;
2718 } else if (DestTy->isPointerTy()) { // Casting to pointer
2719 if (SrcTy->isPointerTy()) { // Casting from pointer
2721 } else if (SrcTy->isIntegerTy()) { // Casting from integral
2723 } else { // Casting from something else
2726 } else if (DestTy->isX86_MMXTy()) {
2727 if (SrcTy->isVectorTy()) {
2728 return DestBits == SrcBits; // 64-bit vector to MMX
2732 } else { // Casting to something else
2737 // Provide a way to get a "cast" where the cast opcode is inferred from the
2738 // types and size of the operand. This, basically, is a parallel of the
2739 // logic in the castIsValid function below. This axiom should hold:
2740 // castIsValid( getCastOpcode(Val, Ty), Val, Ty)
2741 // should not assert in castIsValid. In other words, this produces a "correct"
2742 // casting opcode for the arguments passed to it.
2743 // This routine must be kept in sync with isCastable.
2744 Instruction::CastOps
2745 CastInst::getCastOpcode(
2746 const Value *Src, bool SrcIsSigned, Type *DestTy, bool DestIsSigned) {
2747 Type *SrcTy = Src->getType();
2749 assert(SrcTy->isFirstClassType() && DestTy->isFirstClassType() &&
2750 "Only first class types are castable!");
2752 if (SrcTy == DestTy)
2755 if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy))
2756 if (VectorType *DestVecTy = dyn_cast<VectorType>(DestTy))
2757 if (SrcVecTy->getNumElements() == DestVecTy->getNumElements()) {
2758 // An element by element cast. Find the appropriate opcode based on the
2760 SrcTy = SrcVecTy->getElementType();
2761 DestTy = DestVecTy->getElementType();
2764 // Get the bit sizes, we'll need these
2765 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); // 0 for ptr
2766 unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr
2768 // Run through the possibilities ...
2769 if (DestTy->isIntegerTy()) { // Casting to integral
2770 if (SrcTy->isIntegerTy()) { // Casting from integral
2771 if (DestBits < SrcBits)
2772 return Trunc; // int -> smaller int
2773 else if (DestBits > SrcBits) { // its an extension
2775 return SExt; // signed -> SEXT
2777 return ZExt; // unsigned -> ZEXT
2779 return BitCast; // Same size, No-op cast
2781 } else if (SrcTy->isFloatingPointTy()) { // Casting from floating pt
2783 return FPToSI; // FP -> sint
2785 return FPToUI; // FP -> uint
2786 } else if (SrcTy->isVectorTy()) {
2787 assert(DestBits == SrcBits &&
2788 "Casting vector to integer of different width");
2789 return BitCast; // Same size, no-op cast
2791 assert(SrcTy->isPointerTy() &&
2792 "Casting from a value that is not first-class type");
2793 return PtrToInt; // ptr -> int
2795 } else if (DestTy->isFloatingPointTy()) { // Casting to floating pt
2796 if (SrcTy->isIntegerTy()) { // Casting from integral
2798 return SIToFP; // sint -> FP
2800 return UIToFP; // uint -> FP
2801 } else if (SrcTy->isFloatingPointTy()) { // Casting from floating pt
2802 if (DestBits < SrcBits) {
2803 return FPTrunc; // FP -> smaller FP
2804 } else if (DestBits > SrcBits) {
2805 return FPExt; // FP -> larger FP
2807 return BitCast; // same size, no-op cast
2809 } else if (SrcTy->isVectorTy()) {
2810 assert(DestBits == SrcBits &&
2811 "Casting vector to floating point of different width");
2812 return BitCast; // same size, no-op cast
2814 llvm_unreachable("Casting pointer or non-first class to float");
2815 } else if (DestTy->isVectorTy()) {
2816 assert(DestBits == SrcBits &&
2817 "Illegal cast to vector (wrong type or size)");
2819 } else if (DestTy->isPointerTy()) {
2820 if (SrcTy->isPointerTy()) {
2821 return BitCast; // ptr -> ptr
2822 } else if (SrcTy->isIntegerTy()) {
2823 return IntToPtr; // int -> ptr
2825 llvm_unreachable("Casting pointer to other than pointer or int");
2826 } else if (DestTy->isX86_MMXTy()) {
2827 if (SrcTy->isVectorTy()) {
2828 assert(DestBits == SrcBits && "Casting vector of wrong width to X86_MMX");
2829 return BitCast; // 64-bit vector to MMX
2831 llvm_unreachable("Illegal cast to X86_MMX");
2833 llvm_unreachable("Casting to type that is not first-class");
2836 //===----------------------------------------------------------------------===//
2837 // CastInst SubClass Constructors
2838 //===----------------------------------------------------------------------===//
2840 /// Check that the construction parameters for a CastInst are correct. This
2841 /// could be broken out into the separate constructors but it is useful to have
2842 /// it in one place and to eliminate the redundant code for getting the sizes
2843 /// of the types involved.
2845 CastInst::castIsValid(Instruction::CastOps op, Value *S, Type *DstTy) {
2847 // Check for type sanity on the arguments
2848 Type *SrcTy = S->getType();
2849 if (!SrcTy->isFirstClassType() || !DstTy->isFirstClassType() ||
2850 SrcTy->isAggregateType() || DstTy->isAggregateType())
2853 // Get the size of the types in bits, we'll need this later
2854 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
2855 unsigned DstBitSize = DstTy->getScalarSizeInBits();
2857 // If these are vector types, get the lengths of the vectors (using zero for
2858 // scalar types means that checking that vector lengths match also checks that
2859 // scalars are not being converted to vectors or vectors to scalars).
2860 unsigned SrcLength = SrcTy->isVectorTy() ?
2861 cast<VectorType>(SrcTy)->getNumElements() : 0;
2862 unsigned DstLength = DstTy->isVectorTy() ?
2863 cast<VectorType>(DstTy)->getNumElements() : 0;
2865 // Switch on the opcode provided
2867 default: return false; // This is an input error
2868 case Instruction::Trunc:
2869 return SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy() &&
2870 SrcLength == DstLength && SrcBitSize > DstBitSize;
2871 case Instruction::ZExt:
2872 return SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy() &&
2873 SrcLength == DstLength && SrcBitSize < DstBitSize;
2874 case Instruction::SExt:
2875 return SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy() &&
2876 SrcLength == DstLength && SrcBitSize < DstBitSize;
2877 case Instruction::FPTrunc:
2878 return SrcTy->isFPOrFPVectorTy() && DstTy->isFPOrFPVectorTy() &&
2879 SrcLength == DstLength && SrcBitSize > DstBitSize;
2880 case Instruction::FPExt:
2881 return SrcTy->isFPOrFPVectorTy() && DstTy->isFPOrFPVectorTy() &&
2882 SrcLength == DstLength && SrcBitSize < DstBitSize;
2883 case Instruction::UIToFP:
2884 case Instruction::SIToFP:
2885 return SrcTy->isIntOrIntVectorTy() && DstTy->isFPOrFPVectorTy() &&
2886 SrcLength == DstLength;
2887 case Instruction::FPToUI:
2888 case Instruction::FPToSI:
2889 return SrcTy->isFPOrFPVectorTy() && DstTy->isIntOrIntVectorTy() &&
2890 SrcLength == DstLength;
2891 case Instruction::PtrToInt:
2892 if (isa<VectorType>(SrcTy) != isa<VectorType>(DstTy))
2894 if (VectorType *VT = dyn_cast<VectorType>(SrcTy))
2895 if (VT->getNumElements() != cast<VectorType>(DstTy)->getNumElements())
2897 return SrcTy->getScalarType()->isPointerTy() &&
2898 DstTy->getScalarType()->isIntegerTy();
2899 case Instruction::IntToPtr:
2900 if (isa<VectorType>(SrcTy) != isa<VectorType>(DstTy))
2902 if (VectorType *VT = dyn_cast<VectorType>(SrcTy))
2903 if (VT->getNumElements() != cast<VectorType>(DstTy)->getNumElements())
2905 return SrcTy->getScalarType()->isIntegerTy() &&
2906 DstTy->getScalarType()->isPointerTy();
2907 case Instruction::BitCast:
2908 // BitCast implies a no-op cast of type only. No bits change.
2909 // However, you can't cast pointers to anything but pointers.
2910 if (SrcTy->isPointerTy() != DstTy->isPointerTy())
2913 // Now we know we're not dealing with a pointer/non-pointer mismatch. In all
2914 // these cases, the cast is okay if the source and destination bit widths
2916 return SrcTy->getPrimitiveSizeInBits() == DstTy->getPrimitiveSizeInBits();
2920 TruncInst::TruncInst(
2921 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2922 ) : CastInst(Ty, Trunc, S, Name, InsertBefore) {
2923 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
2926 TruncInst::TruncInst(
2927 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2928 ) : CastInst(Ty, Trunc, S, Name, InsertAtEnd) {
2929 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
2933 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2934 ) : CastInst(Ty, ZExt, S, Name, InsertBefore) {
2935 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
2939 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2940 ) : CastInst(Ty, ZExt, S, Name, InsertAtEnd) {
2941 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
2944 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2945 ) : CastInst(Ty, SExt, S, Name, InsertBefore) {
2946 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
2950 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2951 ) : CastInst(Ty, SExt, S, Name, InsertAtEnd) {
2952 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
2955 FPTruncInst::FPTruncInst(
2956 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2957 ) : CastInst(Ty, FPTrunc, S, Name, InsertBefore) {
2958 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
2961 FPTruncInst::FPTruncInst(
2962 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2963 ) : CastInst(Ty, FPTrunc, S, Name, InsertAtEnd) {
2964 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
2967 FPExtInst::FPExtInst(
2968 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2969 ) : CastInst(Ty, FPExt, S, Name, InsertBefore) {
2970 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
2973 FPExtInst::FPExtInst(
2974 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2975 ) : CastInst(Ty, FPExt, S, Name, InsertAtEnd) {
2976 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
2979 UIToFPInst::UIToFPInst(
2980 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2981 ) : CastInst(Ty, UIToFP, S, Name, InsertBefore) {
2982 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
2985 UIToFPInst::UIToFPInst(
2986 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2987 ) : CastInst(Ty, UIToFP, S, Name, InsertAtEnd) {
2988 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
2991 SIToFPInst::SIToFPInst(
2992 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2993 ) : CastInst(Ty, SIToFP, S, Name, InsertBefore) {
2994 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
2997 SIToFPInst::SIToFPInst(
2998 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2999 ) : CastInst(Ty, SIToFP, S, Name, InsertAtEnd) {
3000 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
3003 FPToUIInst::FPToUIInst(
3004 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3005 ) : CastInst(Ty, FPToUI, S, Name, InsertBefore) {
3006 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
3009 FPToUIInst::FPToUIInst(
3010 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3011 ) : CastInst(Ty, FPToUI, S, Name, InsertAtEnd) {
3012 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
3015 FPToSIInst::FPToSIInst(
3016 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3017 ) : CastInst(Ty, FPToSI, S, Name, InsertBefore) {
3018 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
3021 FPToSIInst::FPToSIInst(
3022 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3023 ) : CastInst(Ty, FPToSI, S, Name, InsertAtEnd) {
3024 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
3027 PtrToIntInst::PtrToIntInst(
3028 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3029 ) : CastInst(Ty, PtrToInt, S, Name, InsertBefore) {
3030 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
3033 PtrToIntInst::PtrToIntInst(
3034 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3035 ) : CastInst(Ty, PtrToInt, S, Name, InsertAtEnd) {
3036 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
3039 IntToPtrInst::IntToPtrInst(
3040 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3041 ) : CastInst(Ty, IntToPtr, S, Name, InsertBefore) {
3042 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
3045 IntToPtrInst::IntToPtrInst(
3046 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3047 ) : CastInst(Ty, IntToPtr, S, Name, InsertAtEnd) {
3048 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
3051 BitCastInst::BitCastInst(
3052 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3053 ) : CastInst(Ty, BitCast, S, Name, InsertBefore) {
3054 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
3057 BitCastInst::BitCastInst(
3058 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3059 ) : CastInst(Ty, BitCast, S, Name, InsertAtEnd) {
3060 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
3063 //===----------------------------------------------------------------------===//
3065 //===----------------------------------------------------------------------===//
3067 void CmpInst::anchor() {}
3069 CmpInst::CmpInst(Type *ty, OtherOps op, unsigned short predicate,
3070 Value *LHS, Value *RHS, const Twine &Name,
3071 Instruction *InsertBefore)
3072 : Instruction(ty, op,
3073 OperandTraits<CmpInst>::op_begin(this),
3074 OperandTraits<CmpInst>::operands(this),
3078 setPredicate((Predicate)predicate);
3082 CmpInst::CmpInst(Type *ty, OtherOps op, unsigned short predicate,
3083 Value *LHS, Value *RHS, const Twine &Name,
3084 BasicBlock *InsertAtEnd)
3085 : Instruction(ty, op,
3086 OperandTraits<CmpInst>::op_begin(this),
3087 OperandTraits<CmpInst>::operands(this),
3091 setPredicate((Predicate)predicate);
3096 CmpInst::Create(OtherOps Op, unsigned short predicate,
3097 Value *S1, Value *S2,
3098 const Twine &Name, Instruction *InsertBefore) {
3099 if (Op == Instruction::ICmp) {
3101 return new ICmpInst(InsertBefore, CmpInst::Predicate(predicate),
3104 return new ICmpInst(CmpInst::Predicate(predicate),
3109 return new FCmpInst(InsertBefore, CmpInst::Predicate(predicate),
3112 return new FCmpInst(CmpInst::Predicate(predicate),
3117 CmpInst::Create(OtherOps Op, unsigned short predicate, Value *S1, Value *S2,
3118 const Twine &Name, BasicBlock *InsertAtEnd) {
3119 if (Op == Instruction::ICmp) {
3120 return new ICmpInst(*InsertAtEnd, CmpInst::Predicate(predicate),
3123 return new FCmpInst(*InsertAtEnd, CmpInst::Predicate(predicate),
3127 void CmpInst::swapOperands() {
3128 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
3131 cast<FCmpInst>(this)->swapOperands();
3134 bool CmpInst::isCommutative() const {
3135 if (const ICmpInst *IC = dyn_cast<ICmpInst>(this))
3136 return IC->isCommutative();
3137 return cast<FCmpInst>(this)->isCommutative();
3140 bool CmpInst::isEquality() const {
3141 if (const ICmpInst *IC = dyn_cast<ICmpInst>(this))
3142 return IC->isEquality();
3143 return cast<FCmpInst>(this)->isEquality();
3147 CmpInst::Predicate CmpInst::getInversePredicate(Predicate pred) {
3149 default: llvm_unreachable("Unknown cmp predicate!");
3150 case ICMP_EQ: return ICMP_NE;
3151 case ICMP_NE: return ICMP_EQ;
3152 case ICMP_UGT: return ICMP_ULE;
3153 case ICMP_ULT: return ICMP_UGE;
3154 case ICMP_UGE: return ICMP_ULT;
3155 case ICMP_ULE: return ICMP_UGT;
3156 case ICMP_SGT: return ICMP_SLE;
3157 case ICMP_SLT: return ICMP_SGE;
3158 case ICMP_SGE: return ICMP_SLT;
3159 case ICMP_SLE: return ICMP_SGT;
3161 case FCMP_OEQ: return FCMP_UNE;
3162 case FCMP_ONE: return FCMP_UEQ;
3163 case FCMP_OGT: return FCMP_ULE;
3164 case FCMP_OLT: return FCMP_UGE;
3165 case FCMP_OGE: return FCMP_ULT;
3166 case FCMP_OLE: return FCMP_UGT;
3167 case FCMP_UEQ: return FCMP_ONE;
3168 case FCMP_UNE: return FCMP_OEQ;
3169 case FCMP_UGT: return FCMP_OLE;
3170 case FCMP_ULT: return FCMP_OGE;
3171 case FCMP_UGE: return FCMP_OLT;
3172 case FCMP_ULE: return FCMP_OGT;
3173 case FCMP_ORD: return FCMP_UNO;
3174 case FCMP_UNO: return FCMP_ORD;
3175 case FCMP_TRUE: return FCMP_FALSE;
3176 case FCMP_FALSE: return FCMP_TRUE;
3180 ICmpInst::Predicate ICmpInst::getSignedPredicate(Predicate pred) {
3182 default: llvm_unreachable("Unknown icmp predicate!");
3183 case ICMP_EQ: case ICMP_NE:
3184 case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE:
3186 case ICMP_UGT: return ICMP_SGT;
3187 case ICMP_ULT: return ICMP_SLT;
3188 case ICMP_UGE: return ICMP_SGE;
3189 case ICMP_ULE: return ICMP_SLE;
3193 ICmpInst::Predicate ICmpInst::getUnsignedPredicate(Predicate pred) {
3195 default: llvm_unreachable("Unknown icmp predicate!");
3196 case ICMP_EQ: case ICMP_NE:
3197 case ICMP_UGT: case ICMP_ULT: case ICMP_UGE: case ICMP_ULE:
3199 case ICMP_SGT: return ICMP_UGT;
3200 case ICMP_SLT: return ICMP_ULT;
3201 case ICMP_SGE: return ICMP_UGE;
3202 case ICMP_SLE: return ICMP_ULE;
3206 /// Initialize a set of values that all satisfy the condition with C.
3209 ICmpInst::makeConstantRange(Predicate pred, const APInt &C) {
3212 uint32_t BitWidth = C.getBitWidth();
3214 default: llvm_unreachable("Invalid ICmp opcode to ConstantRange ctor!");
3215 case ICmpInst::ICMP_EQ: Upper++; break;
3216 case ICmpInst::ICMP_NE: Lower++; break;
3217 case ICmpInst::ICMP_ULT:
3218 Lower = APInt::getMinValue(BitWidth);
3219 // Check for an empty-set condition.
3221 return ConstantRange(BitWidth, /*isFullSet=*/false);
3223 case ICmpInst::ICMP_SLT:
3224 Lower = APInt::getSignedMinValue(BitWidth);
3225 // Check for an empty-set condition.
3227 return ConstantRange(BitWidth, /*isFullSet=*/false);
3229 case ICmpInst::ICMP_UGT:
3230 Lower++; Upper = APInt::getMinValue(BitWidth); // Min = Next(Max)
3231 // Check for an empty-set condition.
3233 return ConstantRange(BitWidth, /*isFullSet=*/false);
3235 case ICmpInst::ICMP_SGT:
3236 Lower++; Upper = APInt::getSignedMinValue(BitWidth); // Min = Next(Max)
3237 // Check for an empty-set condition.
3239 return ConstantRange(BitWidth, /*isFullSet=*/false);
3241 case ICmpInst::ICMP_ULE:
3242 Lower = APInt::getMinValue(BitWidth); Upper++;
3243 // Check for a full-set condition.
3245 return ConstantRange(BitWidth, /*isFullSet=*/true);
3247 case ICmpInst::ICMP_SLE:
3248 Lower = APInt::getSignedMinValue(BitWidth); Upper++;
3249 // Check for a full-set condition.
3251 return ConstantRange(BitWidth, /*isFullSet=*/true);
3253 case ICmpInst::ICMP_UGE:
3254 Upper = APInt::getMinValue(BitWidth); // Min = Next(Max)
3255 // Check for a full-set condition.
3257 return ConstantRange(BitWidth, /*isFullSet=*/true);
3259 case ICmpInst::ICMP_SGE:
3260 Upper = APInt::getSignedMinValue(BitWidth); // Min = Next(Max)
3261 // Check for a full-set condition.
3263 return ConstantRange(BitWidth, /*isFullSet=*/true);
3266 return ConstantRange(Lower, Upper);
3269 CmpInst::Predicate CmpInst::getSwappedPredicate(Predicate pred) {
3271 default: llvm_unreachable("Unknown cmp predicate!");
3272 case ICMP_EQ: case ICMP_NE:
3274 case ICMP_SGT: return ICMP_SLT;
3275 case ICMP_SLT: return ICMP_SGT;
3276 case ICMP_SGE: return ICMP_SLE;
3277 case ICMP_SLE: return ICMP_SGE;
3278 case ICMP_UGT: return ICMP_ULT;
3279 case ICMP_ULT: return ICMP_UGT;
3280 case ICMP_UGE: return ICMP_ULE;
3281 case ICMP_ULE: return ICMP_UGE;
3283 case FCMP_FALSE: case FCMP_TRUE:
3284 case FCMP_OEQ: case FCMP_ONE:
3285 case FCMP_UEQ: case FCMP_UNE:
3286 case FCMP_ORD: case FCMP_UNO:
3288 case FCMP_OGT: return FCMP_OLT;
3289 case FCMP_OLT: return FCMP_OGT;
3290 case FCMP_OGE: return FCMP_OLE;
3291 case FCMP_OLE: return FCMP_OGE;
3292 case FCMP_UGT: return FCMP_ULT;
3293 case FCMP_ULT: return FCMP_UGT;
3294 case FCMP_UGE: return FCMP_ULE;
3295 case FCMP_ULE: return FCMP_UGE;
3299 bool CmpInst::isUnsigned(unsigned short predicate) {
3300 switch (predicate) {
3301 default: return false;
3302 case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_ULE: case ICmpInst::ICMP_UGT:
3303 case ICmpInst::ICMP_UGE: return true;
3307 bool CmpInst::isSigned(unsigned short predicate) {
3308 switch (predicate) {
3309 default: return false;
3310 case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_SLE: case ICmpInst::ICMP_SGT:
3311 case ICmpInst::ICMP_SGE: return true;
3315 bool CmpInst::isOrdered(unsigned short predicate) {
3316 switch (predicate) {
3317 default: return false;
3318 case FCmpInst::FCMP_OEQ: case FCmpInst::FCMP_ONE: case FCmpInst::FCMP_OGT:
3319 case FCmpInst::FCMP_OLT: case FCmpInst::FCMP_OGE: case FCmpInst::FCMP_OLE:
3320 case FCmpInst::FCMP_ORD: return true;
3324 bool CmpInst::isUnordered(unsigned short predicate) {
3325 switch (predicate) {
3326 default: return false;
3327 case FCmpInst::FCMP_UEQ: case FCmpInst::FCMP_UNE: case FCmpInst::FCMP_UGT:
3328 case FCmpInst::FCMP_ULT: case FCmpInst::FCMP_UGE: case FCmpInst::FCMP_ULE:
3329 case FCmpInst::FCMP_UNO: return true;
3333 bool CmpInst::isTrueWhenEqual(unsigned short predicate) {
3335 default: return false;
3336 case ICMP_EQ: case ICMP_UGE: case ICMP_ULE: case ICMP_SGE: case ICMP_SLE:
3337 case FCMP_TRUE: case FCMP_UEQ: case FCMP_UGE: case FCMP_ULE: return true;
3341 bool CmpInst::isFalseWhenEqual(unsigned short predicate) {
3343 case ICMP_NE: case ICMP_UGT: case ICMP_ULT: case ICMP_SGT: case ICMP_SLT:
3344 case FCMP_FALSE: case FCMP_ONE: case FCMP_OGT: case FCMP_OLT: return true;
3345 default: return false;
3350 //===----------------------------------------------------------------------===//
3351 // SwitchInst Implementation
3352 //===----------------------------------------------------------------------===//
3354 void SwitchInst::init(Value *Value, BasicBlock *Default, unsigned NumReserved) {
3355 assert(Value && Default && NumReserved);
3356 ReservedSpace = NumReserved;
3358 OperandList = allocHungoffUses(ReservedSpace);
3360 OperandList[0] = Value;
3361 OperandList[1] = Default;
3364 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
3365 /// switch on and a default destination. The number of additional cases can
3366 /// be specified here to make memory allocation more efficient. This
3367 /// constructor can also autoinsert before another instruction.
3368 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
3369 Instruction *InsertBefore)
3370 : TerminatorInst(Type::getVoidTy(Value->getContext()), Instruction::Switch,
3371 0, 0, InsertBefore) {
3372 init(Value, Default, 2+NumCases*2);
3375 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
3376 /// switch on and a default destination. The number of additional cases can
3377 /// be specified here to make memory allocation more efficient. This
3378 /// constructor also autoinserts at the end of the specified BasicBlock.
3379 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
3380 BasicBlock *InsertAtEnd)
3381 : TerminatorInst(Type::getVoidTy(Value->getContext()), Instruction::Switch,
3382 0, 0, InsertAtEnd) {
3383 init(Value, Default, 2+NumCases*2);
3386 SwitchInst::SwitchInst(const SwitchInst &SI)
3387 : TerminatorInst(SI.getType(), Instruction::Switch, 0, 0) {
3388 init(SI.getCondition(), SI.getDefaultDest(), SI.getNumOperands());
3389 NumOperands = SI.getNumOperands();
3390 Use *OL = OperandList, *InOL = SI.OperandList;
3391 for (unsigned i = 2, E = SI.getNumOperands(); i != E; i += 2) {
3393 OL[i+1] = InOL[i+1];
3395 TheSubsets = SI.TheSubsets;
3396 SubclassOptionalData = SI.SubclassOptionalData;
3399 SwitchInst::~SwitchInst() {
3404 /// addCase - Add an entry to the switch instruction...
3406 void SwitchInst::addCase(ConstantInt *OnVal, BasicBlock *Dest) {
3407 IntegersSubsetToBB Mapping;
3409 // FIXME: Currently we work with ConstantInt based cases.
3410 // So inititalize IntItem container directly from ConstantInt.
3411 Mapping.add(IntItem::fromConstantInt(OnVal));
3412 IntegersSubset CaseRanges = Mapping.getCase();
3413 addCase(CaseRanges, Dest);
3416 void SwitchInst::addCase(IntegersSubset& OnVal, BasicBlock *Dest) {
3417 unsigned NewCaseIdx = getNumCases();
3418 unsigned OpNo = NumOperands;
3419 if (OpNo+2 > ReservedSpace)
3420 growOperands(); // Get more space!
3421 // Initialize some new operands.
3422 assert(OpNo+1 < ReservedSpace && "Growing didn't work!");
3423 NumOperands = OpNo+2;
3425 SubsetsIt TheSubsetsIt = TheSubsets.insert(TheSubsets.end(), OnVal);
3427 CaseIt Case(this, NewCaseIdx, TheSubsetsIt);
3428 Case.updateCaseValueOperand(OnVal);
3429 Case.setSuccessor(Dest);
3432 /// removeCase - This method removes the specified case and its successor
3433 /// from the switch instruction.
3434 void SwitchInst::removeCase(CaseIt& i) {
3435 unsigned idx = i.getCaseIndex();
3437 assert(2 + idx*2 < getNumOperands() && "Case index out of range!!!");
3439 unsigned NumOps = getNumOperands();
3440 Use *OL = OperandList;
3442 // Overwrite this case with the end of the list.
3443 if (2 + (idx + 1) * 2 != NumOps) {
3444 OL[2 + idx * 2] = OL[NumOps - 2];
3445 OL[2 + idx * 2 + 1] = OL[NumOps - 1];
3448 // Nuke the last value.
3449 OL[NumOps-2].set(0);
3450 OL[NumOps-2+1].set(0);
3452 // Do the same with TheCases collection:
3453 if (i.SubsetIt != --TheSubsets.end()) {
3454 *i.SubsetIt = TheSubsets.back();
3455 TheSubsets.pop_back();
3457 TheSubsets.pop_back();
3458 i.SubsetIt = TheSubsets.end();
3461 NumOperands = NumOps-2;
3464 /// growOperands - grow operands - This grows the operand list in response
3465 /// to a push_back style of operation. This grows the number of ops by 3 times.
3467 void SwitchInst::growOperands() {
3468 unsigned e = getNumOperands();
3469 unsigned NumOps = e*3;
3471 ReservedSpace = NumOps;
3472 Use *NewOps = allocHungoffUses(NumOps);
3473 Use *OldOps = OperandList;
3474 for (unsigned i = 0; i != e; ++i) {
3475 NewOps[i] = OldOps[i];
3477 OperandList = NewOps;
3478 Use::zap(OldOps, OldOps + e, true);
3482 BasicBlock *SwitchInst::getSuccessorV(unsigned idx) const {
3483 return getSuccessor(idx);
3485 unsigned SwitchInst::getNumSuccessorsV() const {
3486 return getNumSuccessors();
3488 void SwitchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
3489 setSuccessor(idx, B);
3492 //===----------------------------------------------------------------------===//
3493 // IndirectBrInst Implementation
3494 //===----------------------------------------------------------------------===//
3496 void IndirectBrInst::init(Value *Address, unsigned NumDests) {
3497 assert(Address && Address->getType()->isPointerTy() &&
3498 "Address of indirectbr must be a pointer");
3499 ReservedSpace = 1+NumDests;
3501 OperandList = allocHungoffUses(ReservedSpace);
3503 OperandList[0] = Address;
3507 /// growOperands - grow operands - This grows the operand list in response
3508 /// to a push_back style of operation. This grows the number of ops by 2 times.
3510 void IndirectBrInst::growOperands() {
3511 unsigned e = getNumOperands();
3512 unsigned NumOps = e*2;
3514 ReservedSpace = NumOps;
3515 Use *NewOps = allocHungoffUses(NumOps);
3516 Use *OldOps = OperandList;
3517 for (unsigned i = 0; i != e; ++i)
3518 NewOps[i] = OldOps[i];
3519 OperandList = NewOps;
3520 Use::zap(OldOps, OldOps + e, true);
3523 IndirectBrInst::IndirectBrInst(Value *Address, unsigned NumCases,
3524 Instruction *InsertBefore)
3525 : TerminatorInst(Type::getVoidTy(Address->getContext()),Instruction::IndirectBr,
3526 0, 0, InsertBefore) {
3527 init(Address, NumCases);
3530 IndirectBrInst::IndirectBrInst(Value *Address, unsigned NumCases,
3531 BasicBlock *InsertAtEnd)
3532 : TerminatorInst(Type::getVoidTy(Address->getContext()),Instruction::IndirectBr,
3533 0, 0, InsertAtEnd) {
3534 init(Address, NumCases);
3537 IndirectBrInst::IndirectBrInst(const IndirectBrInst &IBI)
3538 : TerminatorInst(Type::getVoidTy(IBI.getContext()), Instruction::IndirectBr,
3539 allocHungoffUses(IBI.getNumOperands()),
3540 IBI.getNumOperands()) {
3541 Use *OL = OperandList, *InOL = IBI.OperandList;
3542 for (unsigned i = 0, E = IBI.getNumOperands(); i != E; ++i)
3544 SubclassOptionalData = IBI.SubclassOptionalData;
3547 IndirectBrInst::~IndirectBrInst() {
3551 /// addDestination - Add a destination.
3553 void IndirectBrInst::addDestination(BasicBlock *DestBB) {
3554 unsigned OpNo = NumOperands;
3555 if (OpNo+1 > ReservedSpace)
3556 growOperands(); // Get more space!
3557 // Initialize some new operands.
3558 assert(OpNo < ReservedSpace && "Growing didn't work!");
3559 NumOperands = OpNo+1;
3560 OperandList[OpNo] = DestBB;
3563 /// removeDestination - This method removes the specified successor from the
3564 /// indirectbr instruction.
3565 void IndirectBrInst::removeDestination(unsigned idx) {
3566 assert(idx < getNumOperands()-1 && "Successor index out of range!");
3568 unsigned NumOps = getNumOperands();
3569 Use *OL = OperandList;
3571 // Replace this value with the last one.
3572 OL[idx+1] = OL[NumOps-1];
3574 // Nuke the last value.
3575 OL[NumOps-1].set(0);
3576 NumOperands = NumOps-1;
3579 BasicBlock *IndirectBrInst::getSuccessorV(unsigned idx) const {
3580 return getSuccessor(idx);
3582 unsigned IndirectBrInst::getNumSuccessorsV() const {
3583 return getNumSuccessors();
3585 void IndirectBrInst::setSuccessorV(unsigned idx, BasicBlock *B) {
3586 setSuccessor(idx, B);
3589 //===----------------------------------------------------------------------===//
3590 // clone_impl() implementations
3591 //===----------------------------------------------------------------------===//
3593 // Define these methods here so vtables don't get emitted into every translation
3594 // unit that uses these classes.
3596 GetElementPtrInst *GetElementPtrInst::clone_impl() const {
3597 return new (getNumOperands()) GetElementPtrInst(*this);
3600 BinaryOperator *BinaryOperator::clone_impl() const {
3601 return Create(getOpcode(), Op<0>(), Op<1>());
3604 FCmpInst* FCmpInst::clone_impl() const {
3605 return new FCmpInst(getPredicate(), Op<0>(), Op<1>());
3608 ICmpInst* ICmpInst::clone_impl() const {
3609 return new ICmpInst(getPredicate(), Op<0>(), Op<1>());
3612 ExtractValueInst *ExtractValueInst::clone_impl() const {
3613 return new ExtractValueInst(*this);
3616 InsertValueInst *InsertValueInst::clone_impl() const {
3617 return new InsertValueInst(*this);
3620 AllocaInst *AllocaInst::clone_impl() const {
3621 return new AllocaInst(getAllocatedType(),
3622 (Value*)getOperand(0),
3626 LoadInst *LoadInst::clone_impl() const {
3627 return new LoadInst(getOperand(0), Twine(), isVolatile(),
3628 getAlignment(), getOrdering(), getSynchScope());
3631 StoreInst *StoreInst::clone_impl() const {
3632 return new StoreInst(getOperand(0), getOperand(1), isVolatile(),
3633 getAlignment(), getOrdering(), getSynchScope());
3637 AtomicCmpXchgInst *AtomicCmpXchgInst::clone_impl() const {
3638 AtomicCmpXchgInst *Result =
3639 new AtomicCmpXchgInst(getOperand(0), getOperand(1), getOperand(2),
3640 getOrdering(), getSynchScope());
3641 Result->setVolatile(isVolatile());
3645 AtomicRMWInst *AtomicRMWInst::clone_impl() const {
3646 AtomicRMWInst *Result =
3647 new AtomicRMWInst(getOperation(),getOperand(0), getOperand(1),
3648 getOrdering(), getSynchScope());
3649 Result->setVolatile(isVolatile());
3653 FenceInst *FenceInst::clone_impl() const {
3654 return new FenceInst(getContext(), getOrdering(), getSynchScope());
3657 TruncInst *TruncInst::clone_impl() const {
3658 return new TruncInst(getOperand(0), getType());
3661 ZExtInst *ZExtInst::clone_impl() const {
3662 return new ZExtInst(getOperand(0), getType());
3665 SExtInst *SExtInst::clone_impl() const {
3666 return new SExtInst(getOperand(0), getType());
3669 FPTruncInst *FPTruncInst::clone_impl() const {
3670 return new FPTruncInst(getOperand(0), getType());
3673 FPExtInst *FPExtInst::clone_impl() const {
3674 return new FPExtInst(getOperand(0), getType());
3677 UIToFPInst *UIToFPInst::clone_impl() const {
3678 return new UIToFPInst(getOperand(0), getType());
3681 SIToFPInst *SIToFPInst::clone_impl() const {
3682 return new SIToFPInst(getOperand(0), getType());
3685 FPToUIInst *FPToUIInst::clone_impl() const {
3686 return new FPToUIInst(getOperand(0), getType());
3689 FPToSIInst *FPToSIInst::clone_impl() const {
3690 return new FPToSIInst(getOperand(0), getType());
3693 PtrToIntInst *PtrToIntInst::clone_impl() const {
3694 return new PtrToIntInst(getOperand(0), getType());
3697 IntToPtrInst *IntToPtrInst::clone_impl() const {
3698 return new IntToPtrInst(getOperand(0), getType());
3701 BitCastInst *BitCastInst::clone_impl() const {
3702 return new BitCastInst(getOperand(0), getType());
3705 CallInst *CallInst::clone_impl() const {
3706 return new(getNumOperands()) CallInst(*this);
3709 SelectInst *SelectInst::clone_impl() const {
3710 return SelectInst::Create(getOperand(0), getOperand(1), getOperand(2));
3713 VAArgInst *VAArgInst::clone_impl() const {
3714 return new VAArgInst(getOperand(0), getType());
3717 ExtractElementInst *ExtractElementInst::clone_impl() const {
3718 return ExtractElementInst::Create(getOperand(0), getOperand(1));
3721 InsertElementInst *InsertElementInst::clone_impl() const {
3722 return InsertElementInst::Create(getOperand(0), getOperand(1), getOperand(2));
3725 ShuffleVectorInst *ShuffleVectorInst::clone_impl() const {
3726 return new ShuffleVectorInst(getOperand(0), getOperand(1), getOperand(2));
3729 PHINode *PHINode::clone_impl() const {
3730 return new PHINode(*this);
3733 LandingPadInst *LandingPadInst::clone_impl() const {
3734 return new LandingPadInst(*this);
3737 ReturnInst *ReturnInst::clone_impl() const {
3738 return new(getNumOperands()) ReturnInst(*this);
3741 BranchInst *BranchInst::clone_impl() const {
3742 return new(getNumOperands()) BranchInst(*this);
3745 SwitchInst *SwitchInst::clone_impl() const {
3746 return new SwitchInst(*this);
3749 IndirectBrInst *IndirectBrInst::clone_impl() const {
3750 return new IndirectBrInst(*this);
3754 InvokeInst *InvokeInst::clone_impl() const {
3755 return new(getNumOperands()) InvokeInst(*this);
3758 ResumeInst *ResumeInst::clone_impl() const {
3759 return new(1) ResumeInst(*this);
3762 UnreachableInst *UnreachableInst::clone_impl() const {
3763 LLVMContext &Context = getContext();
3764 return new UnreachableInst(Context);