1 //===-- Instructions.cpp - Implement the LLVM instructions ----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements all of the non-inline methods for the LLVM instruction
13 //===----------------------------------------------------------------------===//
15 #include "LLVMContextImpl.h"
16 #include "llvm/Constants.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/Function.h"
19 #include "llvm/Instructions.h"
20 #include "llvm/Module.h"
21 #include "llvm/Operator.h"
22 #include "llvm/Support/ErrorHandling.h"
23 #include "llvm/Support/CallSite.h"
24 #include "llvm/Support/ConstantRange.h"
25 #include "llvm/Support/MathExtras.h"
28 //===----------------------------------------------------------------------===//
30 //===----------------------------------------------------------------------===//
32 User::op_iterator CallSite::getCallee() const {
33 Instruction *II(getInstruction());
35 ? cast<CallInst>(II)->op_end() - 1 // Skip Callee
36 : cast<InvokeInst>(II)->op_end() - 3; // Skip BB, BB, Callee
39 //===----------------------------------------------------------------------===//
40 // TerminatorInst Class
41 //===----------------------------------------------------------------------===//
43 // Out of line virtual method, so the vtable, etc has a home.
44 TerminatorInst::~TerminatorInst() {
47 //===----------------------------------------------------------------------===//
48 // UnaryInstruction Class
49 //===----------------------------------------------------------------------===//
51 // Out of line virtual method, so the vtable, etc has a home.
52 UnaryInstruction::~UnaryInstruction() {
55 //===----------------------------------------------------------------------===//
57 //===----------------------------------------------------------------------===//
59 /// areInvalidOperands - Return a string if the specified operands are invalid
60 /// for a select operation, otherwise return null.
61 const char *SelectInst::areInvalidOperands(Value *Op0, Value *Op1, Value *Op2) {
62 if (Op1->getType() != Op2->getType())
63 return "both values to select must have same type";
65 if (VectorType *VT = dyn_cast<VectorType>(Op0->getType())) {
67 if (VT->getElementType() != Type::getInt1Ty(Op0->getContext()))
68 return "vector select condition element type must be i1";
69 VectorType *ET = dyn_cast<VectorType>(Op1->getType());
71 return "selected values for vector select must be vectors";
72 if (ET->getNumElements() != VT->getNumElements())
73 return "vector select requires selected vectors to have "
74 "the same vector length as select condition";
75 } else if (Op0->getType() != Type::getInt1Ty(Op0->getContext())) {
76 return "select condition must be i1 or <n x i1>";
82 //===----------------------------------------------------------------------===//
84 //===----------------------------------------------------------------------===//
86 PHINode::PHINode(const PHINode &PN)
87 : Instruction(PN.getType(), Instruction::PHI,
88 allocHungoffUses(PN.getNumOperands()), PN.getNumOperands()),
89 ReservedSpace(PN.getNumOperands()) {
90 std::copy(PN.op_begin(), PN.op_end(), op_begin());
91 std::copy(PN.block_begin(), PN.block_end(), block_begin());
92 SubclassOptionalData = PN.SubclassOptionalData;
99 Use *PHINode::allocHungoffUses(unsigned N) const {
100 // Allocate the array of Uses of the incoming values, followed by a pointer
101 // (with bottom bit set) to the User, followed by the array of pointers to
102 // the incoming basic blocks.
103 size_t size = N * sizeof(Use) + sizeof(Use::UserRef)
104 + N * sizeof(BasicBlock*);
105 Use *Begin = static_cast<Use*>(::operator new(size));
106 Use *End = Begin + N;
107 (void) new(End) Use::UserRef(const_cast<PHINode*>(this), 1);
108 return Use::initTags(Begin, End);
111 // removeIncomingValue - Remove an incoming value. This is useful if a
112 // predecessor basic block is deleted.
113 Value *PHINode::removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty) {
114 Value *Removed = getIncomingValue(Idx);
116 // Move everything after this operand down.
118 // FIXME: we could just swap with the end of the list, then erase. However,
119 // clients might not expect this to happen. The code as it is thrashes the
120 // use/def lists, which is kinda lame.
121 std::copy(op_begin() + Idx + 1, op_end(), op_begin() + Idx);
122 std::copy(block_begin() + Idx + 1, block_end(), block_begin() + Idx);
124 // Nuke the last value.
128 // If the PHI node is dead, because it has zero entries, nuke it now.
129 if (getNumOperands() == 0 && DeletePHIIfEmpty) {
130 // If anyone is using this PHI, make them use a dummy value instead...
131 replaceAllUsesWith(UndefValue::get(getType()));
137 /// growOperands - grow operands - This grows the operand list in response
138 /// to a push_back style of operation. This grows the number of ops by 1.5
141 void PHINode::growOperands() {
142 unsigned e = getNumOperands();
143 unsigned NumOps = e + e / 2;
144 if (NumOps < 2) NumOps = 2; // 2 op PHI nodes are VERY common.
146 Use *OldOps = op_begin();
147 BasicBlock **OldBlocks = block_begin();
149 ReservedSpace = NumOps;
150 OperandList = allocHungoffUses(ReservedSpace);
152 std::copy(OldOps, OldOps + e, op_begin());
153 std::copy(OldBlocks, OldBlocks + e, block_begin());
155 Use::zap(OldOps, OldOps + e, true);
158 /// hasConstantValue - If the specified PHI node always merges together the same
159 /// value, return the value, otherwise return null.
160 Value *PHINode::hasConstantValue() const {
161 // Exploit the fact that phi nodes always have at least one entry.
162 Value *ConstantValue = getIncomingValue(0);
163 for (unsigned i = 1, e = getNumIncomingValues(); i != e; ++i)
164 if (getIncomingValue(i) != ConstantValue && getIncomingValue(i) != this) {
165 if (ConstantValue != this)
166 return 0; // Incoming values not all the same.
167 // The case where the first value is this PHI.
168 ConstantValue = getIncomingValue(i);
170 if (ConstantValue == this)
171 return UndefValue::get(getType());
172 return ConstantValue;
175 //===----------------------------------------------------------------------===//
176 // LandingPadInst Implementation
177 //===----------------------------------------------------------------------===//
179 LandingPadInst::LandingPadInst(Type *RetTy, Value *PersonalityFn,
180 unsigned NumReservedValues, const Twine &NameStr,
181 Instruction *InsertBefore)
182 : Instruction(RetTy, Instruction::LandingPad, 0, 0, InsertBefore) {
183 init(PersonalityFn, 1 + NumReservedValues, NameStr);
186 LandingPadInst::LandingPadInst(Type *RetTy, Value *PersonalityFn,
187 unsigned NumReservedValues, const Twine &NameStr,
188 BasicBlock *InsertAtEnd)
189 : Instruction(RetTy, Instruction::LandingPad, 0, 0, InsertAtEnd) {
190 init(PersonalityFn, 1 + NumReservedValues, NameStr);
193 LandingPadInst::LandingPadInst(const LandingPadInst &LP)
194 : Instruction(LP.getType(), Instruction::LandingPad,
195 allocHungoffUses(LP.getNumOperands()), LP.getNumOperands()),
196 ReservedSpace(LP.getNumOperands()) {
197 Use *OL = OperandList, *InOL = LP.OperandList;
198 for (unsigned I = 0, E = ReservedSpace; I != E; ++I)
201 setCleanup(LP.isCleanup());
204 LandingPadInst::~LandingPadInst() {
208 LandingPadInst *LandingPadInst::Create(Type *RetTy, Value *PersonalityFn,
209 unsigned NumReservedClauses,
210 const Twine &NameStr,
211 Instruction *InsertBefore) {
212 return new LandingPadInst(RetTy, PersonalityFn, NumReservedClauses, NameStr,
216 LandingPadInst *LandingPadInst::Create(Type *RetTy, Value *PersonalityFn,
217 unsigned NumReservedClauses,
218 const Twine &NameStr,
219 BasicBlock *InsertAtEnd) {
220 return new LandingPadInst(RetTy, PersonalityFn, NumReservedClauses, NameStr,
224 void LandingPadInst::init(Value *PersFn, unsigned NumReservedValues,
225 const Twine &NameStr) {
226 ReservedSpace = NumReservedValues;
228 OperandList = allocHungoffUses(ReservedSpace);
229 OperandList[0] = PersFn;
234 /// growOperands - grow operands - This grows the operand list in response to a
235 /// push_back style of operation. This grows the number of ops by 2 times.
236 void LandingPadInst::growOperands(unsigned Size) {
237 unsigned e = getNumOperands();
238 if (ReservedSpace >= e + Size) return;
239 ReservedSpace = (e + Size / 2) * 2;
241 Use *NewOps = allocHungoffUses(ReservedSpace);
242 Use *OldOps = OperandList;
243 for (unsigned i = 0; i != e; ++i)
244 NewOps[i] = OldOps[i];
246 OperandList = NewOps;
247 Use::zap(OldOps, OldOps + e, true);
250 void LandingPadInst::addClause(Value *Val) {
251 unsigned OpNo = getNumOperands();
253 assert(OpNo < ReservedSpace && "Growing didn't work!");
255 OperandList[OpNo] = Val;
258 //===----------------------------------------------------------------------===//
259 // CallInst Implementation
260 //===----------------------------------------------------------------------===//
262 CallInst::~CallInst() {
265 void CallInst::init(Value *Func, ArrayRef<Value *> Args, const Twine &NameStr) {
266 assert(NumOperands == Args.size() + 1 && "NumOperands not set up?");
271 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
273 assert((Args.size() == FTy->getNumParams() ||
274 (FTy->isVarArg() && Args.size() > FTy->getNumParams())) &&
275 "Calling a function with bad signature!");
277 for (unsigned i = 0; i != Args.size(); ++i)
278 assert((i >= FTy->getNumParams() ||
279 FTy->getParamType(i) == Args[i]->getType()) &&
280 "Calling a function with a bad signature!");
283 std::copy(Args.begin(), Args.end(), op_begin());
287 void CallInst::init(Value *Func, const Twine &NameStr) {
288 assert(NumOperands == 1 && "NumOperands not set up?");
293 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
295 assert(FTy->getNumParams() == 0 && "Calling a function with bad signature");
301 CallInst::CallInst(Value *Func, const Twine &Name,
302 Instruction *InsertBefore)
303 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
304 ->getElementType())->getReturnType(),
306 OperandTraits<CallInst>::op_end(this) - 1,
311 CallInst::CallInst(Value *Func, const Twine &Name,
312 BasicBlock *InsertAtEnd)
313 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
314 ->getElementType())->getReturnType(),
316 OperandTraits<CallInst>::op_end(this) - 1,
321 CallInst::CallInst(const CallInst &CI)
322 : Instruction(CI.getType(), Instruction::Call,
323 OperandTraits<CallInst>::op_end(this) - CI.getNumOperands(),
324 CI.getNumOperands()) {
325 setAttributes(CI.getAttributes());
326 setTailCall(CI.isTailCall());
327 setCallingConv(CI.getCallingConv());
329 std::copy(CI.op_begin(), CI.op_end(), op_begin());
330 SubclassOptionalData = CI.SubclassOptionalData;
333 void CallInst::addAttribute(unsigned i, Attributes attr) {
334 AttrListPtr PAL = getAttributes();
335 PAL = PAL.addAttr(i, attr);
339 void CallInst::removeAttribute(unsigned i, Attributes attr) {
340 AttrListPtr PAL = getAttributes();
341 PAL = PAL.removeAttr(i, attr);
345 bool CallInst::paramHasSExtAttr(unsigned i) const {
346 if (AttributeList.getParamAttributes(i).hasSExtAttr())
348 if (const Function *F = getCalledFunction())
349 return F->getParamAttributes(i).hasSExtAttr();
353 bool CallInst::paramHasZExtAttr(unsigned i) const {
354 if (AttributeList.getParamAttributes(i).hasZExtAttr())
356 if (const Function *F = getCalledFunction())
357 return F->getParamAttributes(i).hasZExtAttr();
361 bool CallInst::paramHasInRegAttr(unsigned i) const {
362 if (AttributeList.getParamAttributes(i).hasInRegAttr())
364 if (const Function *F = getCalledFunction())
365 return F->getParamAttributes(i).hasInRegAttr();
369 bool CallInst::paramHasStructRetAttr(unsigned i) const {
370 if (AttributeList.getParamAttributes(i).hasStructRetAttr())
372 if (const Function *F = getCalledFunction())
373 return F->getParamAttributes(i).hasStructRetAttr();
377 bool CallInst::paramHasNestAttr(unsigned i) const {
378 if (AttributeList.getParamAttributes(i).hasNestAttr())
380 if (const Function *F = getCalledFunction())
381 return F->getParamAttributes(i).hasNestAttr();
385 bool CallInst::paramHasByValAttr(unsigned i) const {
386 if (AttributeList.getParamAttributes(i).hasByValAttr())
388 if (const Function *F = getCalledFunction())
389 return F->getParamAttributes(i).hasByValAttr();
393 bool CallInst::paramHasNoAliasAttr(unsigned i) const {
394 if (AttributeList.getParamAttributes(i).hasNoAliasAttr())
396 if (const Function *F = getCalledFunction())
397 return F->getParamAttributes(i).hasNoAliasAttr();
401 bool CallInst::paramHasNoCaptureAttr(unsigned i) const {
402 if (AttributeList.getParamAttributes(i).hasNoCaptureAttr())
404 if (const Function *F = getCalledFunction())
405 return F->getParamAttributes(i).hasNoCaptureAttr();
409 bool CallInst::paramHasAttr(unsigned i, Attributes attr) const {
410 if (AttributeList.paramHasAttr(i, attr))
412 if (const Function *F = getCalledFunction())
413 return F->paramHasAttr(i, attr);
417 /// IsConstantOne - Return true only if val is constant int 1
418 static bool IsConstantOne(Value *val) {
419 assert(val && "IsConstantOne does not work with NULL val");
420 return isa<ConstantInt>(val) && cast<ConstantInt>(val)->isOne();
423 static Instruction *createMalloc(Instruction *InsertBefore,
424 BasicBlock *InsertAtEnd, Type *IntPtrTy,
425 Type *AllocTy, Value *AllocSize,
426 Value *ArraySize, Function *MallocF,
428 assert(((!InsertBefore && InsertAtEnd) || (InsertBefore && !InsertAtEnd)) &&
429 "createMalloc needs either InsertBefore or InsertAtEnd");
431 // malloc(type) becomes:
432 // bitcast (i8* malloc(typeSize)) to type*
433 // malloc(type, arraySize) becomes:
434 // bitcast (i8 *malloc(typeSize*arraySize)) to type*
436 ArraySize = ConstantInt::get(IntPtrTy, 1);
437 else if (ArraySize->getType() != IntPtrTy) {
439 ArraySize = CastInst::CreateIntegerCast(ArraySize, IntPtrTy, false,
442 ArraySize = CastInst::CreateIntegerCast(ArraySize, IntPtrTy, false,
446 if (!IsConstantOne(ArraySize)) {
447 if (IsConstantOne(AllocSize)) {
448 AllocSize = ArraySize; // Operand * 1 = Operand
449 } else if (Constant *CO = dyn_cast<Constant>(ArraySize)) {
450 Constant *Scale = ConstantExpr::getIntegerCast(CO, IntPtrTy,
452 // Malloc arg is constant product of type size and array size
453 AllocSize = ConstantExpr::getMul(Scale, cast<Constant>(AllocSize));
455 // Multiply type size by the array size...
457 AllocSize = BinaryOperator::CreateMul(ArraySize, AllocSize,
458 "mallocsize", InsertBefore);
460 AllocSize = BinaryOperator::CreateMul(ArraySize, AllocSize,
461 "mallocsize", InsertAtEnd);
465 assert(AllocSize->getType() == IntPtrTy && "malloc arg is wrong size");
466 // Create the call to Malloc.
467 BasicBlock* BB = InsertBefore ? InsertBefore->getParent() : InsertAtEnd;
468 Module* M = BB->getParent()->getParent();
469 Type *BPTy = Type::getInt8PtrTy(BB->getContext());
470 Value *MallocFunc = MallocF;
472 // prototype malloc as "void *malloc(size_t)"
473 MallocFunc = M->getOrInsertFunction("malloc", BPTy, IntPtrTy, NULL);
474 PointerType *AllocPtrType = PointerType::getUnqual(AllocTy);
475 CallInst *MCall = NULL;
476 Instruction *Result = NULL;
478 MCall = CallInst::Create(MallocFunc, AllocSize, "malloccall", InsertBefore);
480 if (Result->getType() != AllocPtrType)
481 // Create a cast instruction to convert to the right type...
482 Result = new BitCastInst(MCall, AllocPtrType, Name, InsertBefore);
484 MCall = CallInst::Create(MallocFunc, AllocSize, "malloccall");
486 if (Result->getType() != AllocPtrType) {
487 InsertAtEnd->getInstList().push_back(MCall);
488 // Create a cast instruction to convert to the right type...
489 Result = new BitCastInst(MCall, AllocPtrType, Name);
492 MCall->setTailCall();
493 if (Function *F = dyn_cast<Function>(MallocFunc)) {
494 MCall->setCallingConv(F->getCallingConv());
495 if (!F->doesNotAlias(0)) F->setDoesNotAlias(0);
497 assert(!MCall->getType()->isVoidTy() && "Malloc has void return type");
502 /// CreateMalloc - Generate the IR for a call to malloc:
503 /// 1. Compute the malloc call's argument as the specified type's size,
504 /// possibly multiplied by the array size if the array size is not
506 /// 2. Call malloc with that argument.
507 /// 3. Bitcast the result of the malloc call to the specified type.
508 Instruction *CallInst::CreateMalloc(Instruction *InsertBefore,
509 Type *IntPtrTy, Type *AllocTy,
510 Value *AllocSize, Value *ArraySize,
513 return createMalloc(InsertBefore, NULL, IntPtrTy, AllocTy, AllocSize,
514 ArraySize, MallocF, Name);
517 /// CreateMalloc - Generate the IR for a call to malloc:
518 /// 1. Compute the malloc call's argument as the specified type's size,
519 /// possibly multiplied by the array size if the array size is not
521 /// 2. Call malloc with that argument.
522 /// 3. Bitcast the result of the malloc call to the specified type.
523 /// Note: This function does not add the bitcast to the basic block, that is the
524 /// responsibility of the caller.
525 Instruction *CallInst::CreateMalloc(BasicBlock *InsertAtEnd,
526 Type *IntPtrTy, Type *AllocTy,
527 Value *AllocSize, Value *ArraySize,
528 Function *MallocF, const Twine &Name) {
529 return createMalloc(NULL, InsertAtEnd, IntPtrTy, AllocTy, AllocSize,
530 ArraySize, MallocF, Name);
533 static Instruction* createFree(Value* Source, Instruction *InsertBefore,
534 BasicBlock *InsertAtEnd) {
535 assert(((!InsertBefore && InsertAtEnd) || (InsertBefore && !InsertAtEnd)) &&
536 "createFree needs either InsertBefore or InsertAtEnd");
537 assert(Source->getType()->isPointerTy() &&
538 "Can not free something of nonpointer type!");
540 BasicBlock* BB = InsertBefore ? InsertBefore->getParent() : InsertAtEnd;
541 Module* M = BB->getParent()->getParent();
543 Type *VoidTy = Type::getVoidTy(M->getContext());
544 Type *IntPtrTy = Type::getInt8PtrTy(M->getContext());
545 // prototype free as "void free(void*)"
546 Value *FreeFunc = M->getOrInsertFunction("free", VoidTy, IntPtrTy, NULL);
547 CallInst* Result = NULL;
548 Value *PtrCast = Source;
550 if (Source->getType() != IntPtrTy)
551 PtrCast = new BitCastInst(Source, IntPtrTy, "", InsertBefore);
552 Result = CallInst::Create(FreeFunc, PtrCast, "", InsertBefore);
554 if (Source->getType() != IntPtrTy)
555 PtrCast = new BitCastInst(Source, IntPtrTy, "", InsertAtEnd);
556 Result = CallInst::Create(FreeFunc, PtrCast, "");
558 Result->setTailCall();
559 if (Function *F = dyn_cast<Function>(FreeFunc))
560 Result->setCallingConv(F->getCallingConv());
565 /// CreateFree - Generate the IR for a call to the builtin free function.
566 Instruction * CallInst::CreateFree(Value* Source, Instruction *InsertBefore) {
567 return createFree(Source, InsertBefore, NULL);
570 /// CreateFree - Generate the IR for a call to the builtin free function.
571 /// Note: This function does not add the call to the basic block, that is the
572 /// responsibility of the caller.
573 Instruction* CallInst::CreateFree(Value* Source, BasicBlock *InsertAtEnd) {
574 Instruction* FreeCall = createFree(Source, NULL, InsertAtEnd);
575 assert(FreeCall && "CreateFree did not create a CallInst");
579 //===----------------------------------------------------------------------===//
580 // InvokeInst Implementation
581 //===----------------------------------------------------------------------===//
583 void InvokeInst::init(Value *Fn, BasicBlock *IfNormal, BasicBlock *IfException,
584 ArrayRef<Value *> Args, const Twine &NameStr) {
585 assert(NumOperands == 3 + Args.size() && "NumOperands not set up?");
588 Op<-1>() = IfException;
592 cast<FunctionType>(cast<PointerType>(Fn->getType())->getElementType());
594 assert(((Args.size() == FTy->getNumParams()) ||
595 (FTy->isVarArg() && Args.size() > FTy->getNumParams())) &&
596 "Invoking a function with bad signature");
598 for (unsigned i = 0, e = Args.size(); i != e; i++)
599 assert((i >= FTy->getNumParams() ||
600 FTy->getParamType(i) == Args[i]->getType()) &&
601 "Invoking a function with a bad signature!");
604 std::copy(Args.begin(), Args.end(), op_begin());
608 InvokeInst::InvokeInst(const InvokeInst &II)
609 : TerminatorInst(II.getType(), Instruction::Invoke,
610 OperandTraits<InvokeInst>::op_end(this)
611 - II.getNumOperands(),
612 II.getNumOperands()) {
613 setAttributes(II.getAttributes());
614 setCallingConv(II.getCallingConv());
615 std::copy(II.op_begin(), II.op_end(), op_begin());
616 SubclassOptionalData = II.SubclassOptionalData;
619 BasicBlock *InvokeInst::getSuccessorV(unsigned idx) const {
620 return getSuccessor(idx);
622 unsigned InvokeInst::getNumSuccessorsV() const {
623 return getNumSuccessors();
625 void InvokeInst::setSuccessorV(unsigned idx, BasicBlock *B) {
626 return setSuccessor(idx, B);
629 bool InvokeInst::paramHasSExtAttr(unsigned i) const {
630 if (AttributeList.getParamAttributes(i).hasSExtAttr())
632 if (const Function *F = getCalledFunction())
633 return F->getParamAttributes(i).hasSExtAttr();
637 bool InvokeInst::paramHasZExtAttr(unsigned i) const {
638 if (AttributeList.getParamAttributes(i).hasZExtAttr())
640 if (const Function *F = getCalledFunction())
641 return F->getParamAttributes(i).hasZExtAttr();
645 bool InvokeInst::paramHasInRegAttr(unsigned i) const {
646 if (AttributeList.getParamAttributes(i).hasInRegAttr())
648 if (const Function *F = getCalledFunction())
649 return F->getParamAttributes(i).hasInRegAttr();
653 bool InvokeInst::paramHasStructRetAttr(unsigned i) const {
654 if (AttributeList.getParamAttributes(i).hasStructRetAttr())
656 if (const Function *F = getCalledFunction())
657 return F->getParamAttributes(i).hasStructRetAttr();
661 bool InvokeInst::paramHasNestAttr(unsigned i) const {
662 if (AttributeList.getParamAttributes(i).hasNestAttr())
664 if (const Function *F = getCalledFunction())
665 return F->getParamAttributes(i).hasNestAttr();
669 bool InvokeInst::paramHasByValAttr(unsigned i) const {
670 if (AttributeList.getParamAttributes(i).hasByValAttr())
672 if (const Function *F = getCalledFunction())
673 return F->getParamAttributes(i).hasByValAttr();
677 bool InvokeInst::paramHasNoAliasAttr(unsigned i) const {
678 if (AttributeList.getParamAttributes(i).hasNoAliasAttr())
680 if (const Function *F = getCalledFunction())
681 return F->getParamAttributes(i).hasNoAliasAttr();
685 bool InvokeInst::paramHasNoCaptureAttr(unsigned i) const {
686 if (AttributeList.getParamAttributes(i).hasNoCaptureAttr())
688 if (const Function *F = getCalledFunction())
689 return F->getParamAttributes(i).hasNoCaptureAttr();
693 bool InvokeInst::paramHasAttr(unsigned i, Attributes attr) const {
694 if (AttributeList.paramHasAttr(i, attr))
696 if (const Function *F = getCalledFunction())
697 return F->paramHasAttr(i, attr);
701 void InvokeInst::addAttribute(unsigned i, Attributes attr) {
702 AttrListPtr PAL = getAttributes();
703 PAL = PAL.addAttr(i, attr);
707 void InvokeInst::removeAttribute(unsigned i, Attributes attr) {
708 AttrListPtr PAL = getAttributes();
709 PAL = PAL.removeAttr(i, attr);
713 LandingPadInst *InvokeInst::getLandingPadInst() const {
714 return cast<LandingPadInst>(getUnwindDest()->getFirstNonPHI());
717 //===----------------------------------------------------------------------===//
718 // ReturnInst Implementation
719 //===----------------------------------------------------------------------===//
721 ReturnInst::ReturnInst(const ReturnInst &RI)
722 : TerminatorInst(Type::getVoidTy(RI.getContext()), Instruction::Ret,
723 OperandTraits<ReturnInst>::op_end(this) -
725 RI.getNumOperands()) {
726 if (RI.getNumOperands())
727 Op<0>() = RI.Op<0>();
728 SubclassOptionalData = RI.SubclassOptionalData;
731 ReturnInst::ReturnInst(LLVMContext &C, Value *retVal, Instruction *InsertBefore)
732 : TerminatorInst(Type::getVoidTy(C), Instruction::Ret,
733 OperandTraits<ReturnInst>::op_end(this) - !!retVal, !!retVal,
738 ReturnInst::ReturnInst(LLVMContext &C, Value *retVal, BasicBlock *InsertAtEnd)
739 : TerminatorInst(Type::getVoidTy(C), Instruction::Ret,
740 OperandTraits<ReturnInst>::op_end(this) - !!retVal, !!retVal,
745 ReturnInst::ReturnInst(LLVMContext &Context, BasicBlock *InsertAtEnd)
746 : TerminatorInst(Type::getVoidTy(Context), Instruction::Ret,
747 OperandTraits<ReturnInst>::op_end(this), 0, InsertAtEnd) {
750 unsigned ReturnInst::getNumSuccessorsV() const {
751 return getNumSuccessors();
754 /// Out-of-line ReturnInst method, put here so the C++ compiler can choose to
755 /// emit the vtable for the class in this translation unit.
756 void ReturnInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
757 llvm_unreachable("ReturnInst has no successors!");
760 BasicBlock *ReturnInst::getSuccessorV(unsigned idx) const {
761 llvm_unreachable("ReturnInst has no successors!");
764 ReturnInst::~ReturnInst() {
767 //===----------------------------------------------------------------------===//
768 // ResumeInst Implementation
769 //===----------------------------------------------------------------------===//
771 ResumeInst::ResumeInst(const ResumeInst &RI)
772 : TerminatorInst(Type::getVoidTy(RI.getContext()), Instruction::Resume,
773 OperandTraits<ResumeInst>::op_begin(this), 1) {
774 Op<0>() = RI.Op<0>();
777 ResumeInst::ResumeInst(Value *Exn, Instruction *InsertBefore)
778 : TerminatorInst(Type::getVoidTy(Exn->getContext()), Instruction::Resume,
779 OperandTraits<ResumeInst>::op_begin(this), 1, InsertBefore) {
783 ResumeInst::ResumeInst(Value *Exn, BasicBlock *InsertAtEnd)
784 : TerminatorInst(Type::getVoidTy(Exn->getContext()), Instruction::Resume,
785 OperandTraits<ResumeInst>::op_begin(this), 1, InsertAtEnd) {
789 unsigned ResumeInst::getNumSuccessorsV() const {
790 return getNumSuccessors();
793 void ResumeInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
794 llvm_unreachable("ResumeInst has no successors!");
797 BasicBlock *ResumeInst::getSuccessorV(unsigned idx) const {
798 llvm_unreachable("ResumeInst has no successors!");
801 //===----------------------------------------------------------------------===//
802 // UnreachableInst Implementation
803 //===----------------------------------------------------------------------===//
805 UnreachableInst::UnreachableInst(LLVMContext &Context,
806 Instruction *InsertBefore)
807 : TerminatorInst(Type::getVoidTy(Context), Instruction::Unreachable,
808 0, 0, InsertBefore) {
810 UnreachableInst::UnreachableInst(LLVMContext &Context, BasicBlock *InsertAtEnd)
811 : TerminatorInst(Type::getVoidTy(Context), Instruction::Unreachable,
815 unsigned UnreachableInst::getNumSuccessorsV() const {
816 return getNumSuccessors();
819 void UnreachableInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
820 llvm_unreachable("UnreachableInst has no successors!");
823 BasicBlock *UnreachableInst::getSuccessorV(unsigned idx) const {
824 llvm_unreachable("UnreachableInst has no successors!");
827 //===----------------------------------------------------------------------===//
828 // BranchInst Implementation
829 //===----------------------------------------------------------------------===//
831 void BranchInst::AssertOK() {
833 assert(getCondition()->getType()->isIntegerTy(1) &&
834 "May only branch on boolean predicates!");
837 BranchInst::BranchInst(BasicBlock *IfTrue, Instruction *InsertBefore)
838 : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
839 OperandTraits<BranchInst>::op_end(this) - 1,
841 assert(IfTrue != 0 && "Branch destination may not be null!");
844 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
845 Instruction *InsertBefore)
846 : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
847 OperandTraits<BranchInst>::op_end(this) - 3,
857 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *InsertAtEnd)
858 : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
859 OperandTraits<BranchInst>::op_end(this) - 1,
861 assert(IfTrue != 0 && "Branch destination may not be null!");
865 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
866 BasicBlock *InsertAtEnd)
867 : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
868 OperandTraits<BranchInst>::op_end(this) - 3,
879 BranchInst::BranchInst(const BranchInst &BI) :
880 TerminatorInst(Type::getVoidTy(BI.getContext()), Instruction::Br,
881 OperandTraits<BranchInst>::op_end(this) - BI.getNumOperands(),
882 BI.getNumOperands()) {
883 Op<-1>() = BI.Op<-1>();
884 if (BI.getNumOperands() != 1) {
885 assert(BI.getNumOperands() == 3 && "BR can have 1 or 3 operands!");
886 Op<-3>() = BI.Op<-3>();
887 Op<-2>() = BI.Op<-2>();
889 SubclassOptionalData = BI.SubclassOptionalData;
892 void BranchInst::swapSuccessors() {
893 assert(isConditional() &&
894 "Cannot swap successors of an unconditional branch");
895 Op<-1>().swap(Op<-2>());
897 // Update profile metadata if present and it matches our structural
899 MDNode *ProfileData = getMetadata(LLVMContext::MD_prof);
900 if (!ProfileData || ProfileData->getNumOperands() != 3)
903 // The first operand is the name. Fetch them backwards and build a new one.
905 ProfileData->getOperand(0),
906 ProfileData->getOperand(2),
907 ProfileData->getOperand(1)
909 setMetadata(LLVMContext::MD_prof,
910 MDNode::get(ProfileData->getContext(), Ops));
913 BasicBlock *BranchInst::getSuccessorV(unsigned idx) const {
914 return getSuccessor(idx);
916 unsigned BranchInst::getNumSuccessorsV() const {
917 return getNumSuccessors();
919 void BranchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
920 setSuccessor(idx, B);
924 //===----------------------------------------------------------------------===//
925 // AllocaInst Implementation
926 //===----------------------------------------------------------------------===//
928 static Value *getAISize(LLVMContext &Context, Value *Amt) {
930 Amt = ConstantInt::get(Type::getInt32Ty(Context), 1);
932 assert(!isa<BasicBlock>(Amt) &&
933 "Passed basic block into allocation size parameter! Use other ctor");
934 assert(Amt->getType()->isIntegerTy() &&
935 "Allocation array size is not an integer!");
940 AllocaInst::AllocaInst(Type *Ty, Value *ArraySize,
941 const Twine &Name, Instruction *InsertBefore)
942 : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
943 getAISize(Ty->getContext(), ArraySize), InsertBefore) {
945 assert(!Ty->isVoidTy() && "Cannot allocate void!");
949 AllocaInst::AllocaInst(Type *Ty, Value *ArraySize,
950 const Twine &Name, BasicBlock *InsertAtEnd)
951 : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
952 getAISize(Ty->getContext(), ArraySize), InsertAtEnd) {
954 assert(!Ty->isVoidTy() && "Cannot allocate void!");
958 AllocaInst::AllocaInst(Type *Ty, const Twine &Name,
959 Instruction *InsertBefore)
960 : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
961 getAISize(Ty->getContext(), 0), InsertBefore) {
963 assert(!Ty->isVoidTy() && "Cannot allocate void!");
967 AllocaInst::AllocaInst(Type *Ty, const Twine &Name,
968 BasicBlock *InsertAtEnd)
969 : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
970 getAISize(Ty->getContext(), 0), InsertAtEnd) {
972 assert(!Ty->isVoidTy() && "Cannot allocate void!");
976 AllocaInst::AllocaInst(Type *Ty, Value *ArraySize, unsigned Align,
977 const Twine &Name, Instruction *InsertBefore)
978 : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
979 getAISize(Ty->getContext(), ArraySize), InsertBefore) {
981 assert(!Ty->isVoidTy() && "Cannot allocate void!");
985 AllocaInst::AllocaInst(Type *Ty, Value *ArraySize, unsigned Align,
986 const Twine &Name, BasicBlock *InsertAtEnd)
987 : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
988 getAISize(Ty->getContext(), ArraySize), InsertAtEnd) {
990 assert(!Ty->isVoidTy() && "Cannot allocate void!");
994 // Out of line virtual method, so the vtable, etc has a home.
995 AllocaInst::~AllocaInst() {
998 void AllocaInst::setAlignment(unsigned Align) {
999 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
1000 assert(Align <= MaximumAlignment &&
1001 "Alignment is greater than MaximumAlignment!");
1002 setInstructionSubclassData(Log2_32(Align) + 1);
1003 assert(getAlignment() == Align && "Alignment representation error!");
1006 bool AllocaInst::isArrayAllocation() const {
1007 if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(0)))
1008 return !CI->isOne();
1012 Type *AllocaInst::getAllocatedType() const {
1013 return getType()->getElementType();
1016 /// isStaticAlloca - Return true if this alloca is in the entry block of the
1017 /// function and is a constant size. If so, the code generator will fold it
1018 /// into the prolog/epilog code, so it is basically free.
1019 bool AllocaInst::isStaticAlloca() const {
1020 // Must be constant size.
1021 if (!isa<ConstantInt>(getArraySize())) return false;
1023 // Must be in the entry block.
1024 const BasicBlock *Parent = getParent();
1025 return Parent == &Parent->getParent()->front();
1028 //===----------------------------------------------------------------------===//
1029 // LoadInst Implementation
1030 //===----------------------------------------------------------------------===//
1032 void LoadInst::AssertOK() {
1033 assert(getOperand(0)->getType()->isPointerTy() &&
1034 "Ptr must have pointer type.");
1035 assert(!(isAtomic() && getAlignment() == 0) &&
1036 "Alignment required for atomic load");
1039 LoadInst::LoadInst(Value *Ptr, const Twine &Name, Instruction *InsertBef)
1040 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1041 Load, Ptr, InsertBef) {
1044 setAtomic(NotAtomic);
1049 LoadInst::LoadInst(Value *Ptr, const Twine &Name, BasicBlock *InsertAE)
1050 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1051 Load, Ptr, InsertAE) {
1054 setAtomic(NotAtomic);
1059 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
1060 Instruction *InsertBef)
1061 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1062 Load, Ptr, InsertBef) {
1063 setVolatile(isVolatile);
1065 setAtomic(NotAtomic);
1070 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
1071 BasicBlock *InsertAE)
1072 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1073 Load, Ptr, InsertAE) {
1074 setVolatile(isVolatile);
1076 setAtomic(NotAtomic);
1081 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
1082 unsigned Align, Instruction *InsertBef)
1083 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1084 Load, Ptr, InsertBef) {
1085 setVolatile(isVolatile);
1086 setAlignment(Align);
1087 setAtomic(NotAtomic);
1092 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
1093 unsigned Align, BasicBlock *InsertAE)
1094 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1095 Load, Ptr, InsertAE) {
1096 setVolatile(isVolatile);
1097 setAlignment(Align);
1098 setAtomic(NotAtomic);
1103 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
1104 unsigned Align, AtomicOrdering Order,
1105 SynchronizationScope SynchScope,
1106 Instruction *InsertBef)
1107 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1108 Load, Ptr, InsertBef) {
1109 setVolatile(isVolatile);
1110 setAlignment(Align);
1111 setAtomic(Order, SynchScope);
1116 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
1117 unsigned Align, AtomicOrdering Order,
1118 SynchronizationScope SynchScope,
1119 BasicBlock *InsertAE)
1120 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1121 Load, Ptr, InsertAE) {
1122 setVolatile(isVolatile);
1123 setAlignment(Align);
1124 setAtomic(Order, SynchScope);
1129 LoadInst::LoadInst(Value *Ptr, const char *Name, Instruction *InsertBef)
1130 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1131 Load, Ptr, InsertBef) {
1134 setAtomic(NotAtomic);
1136 if (Name && Name[0]) setName(Name);
1139 LoadInst::LoadInst(Value *Ptr, const char *Name, BasicBlock *InsertAE)
1140 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1141 Load, Ptr, InsertAE) {
1144 setAtomic(NotAtomic);
1146 if (Name && Name[0]) setName(Name);
1149 LoadInst::LoadInst(Value *Ptr, const char *Name, bool isVolatile,
1150 Instruction *InsertBef)
1151 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1152 Load, Ptr, InsertBef) {
1153 setVolatile(isVolatile);
1155 setAtomic(NotAtomic);
1157 if (Name && Name[0]) setName(Name);
1160 LoadInst::LoadInst(Value *Ptr, const char *Name, bool isVolatile,
1161 BasicBlock *InsertAE)
1162 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1163 Load, Ptr, InsertAE) {
1164 setVolatile(isVolatile);
1166 setAtomic(NotAtomic);
1168 if (Name && Name[0]) setName(Name);
1171 void LoadInst::setAlignment(unsigned Align) {
1172 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
1173 assert(Align <= MaximumAlignment &&
1174 "Alignment is greater than MaximumAlignment!");
1175 setInstructionSubclassData((getSubclassDataFromInstruction() & ~(31 << 1)) |
1176 ((Log2_32(Align)+1)<<1));
1177 assert(getAlignment() == Align && "Alignment representation error!");
1180 //===----------------------------------------------------------------------===//
1181 // StoreInst Implementation
1182 //===----------------------------------------------------------------------===//
1184 void StoreInst::AssertOK() {
1185 assert(getOperand(0) && getOperand(1) && "Both operands must be non-null!");
1186 assert(getOperand(1)->getType()->isPointerTy() &&
1187 "Ptr must have pointer type!");
1188 assert(getOperand(0)->getType() ==
1189 cast<PointerType>(getOperand(1)->getType())->getElementType()
1190 && "Ptr must be a pointer to Val type!");
1191 assert(!(isAtomic() && getAlignment() == 0) &&
1192 "Alignment required for atomic load");
1196 StoreInst::StoreInst(Value *val, Value *addr, Instruction *InsertBefore)
1197 : Instruction(Type::getVoidTy(val->getContext()), Store,
1198 OperandTraits<StoreInst>::op_begin(this),
1199 OperandTraits<StoreInst>::operands(this),
1205 setAtomic(NotAtomic);
1209 StoreInst::StoreInst(Value *val, Value *addr, BasicBlock *InsertAtEnd)
1210 : Instruction(Type::getVoidTy(val->getContext()), Store,
1211 OperandTraits<StoreInst>::op_begin(this),
1212 OperandTraits<StoreInst>::operands(this),
1218 setAtomic(NotAtomic);
1222 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1223 Instruction *InsertBefore)
1224 : Instruction(Type::getVoidTy(val->getContext()), Store,
1225 OperandTraits<StoreInst>::op_begin(this),
1226 OperandTraits<StoreInst>::operands(this),
1230 setVolatile(isVolatile);
1232 setAtomic(NotAtomic);
1236 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1237 unsigned Align, Instruction *InsertBefore)
1238 : Instruction(Type::getVoidTy(val->getContext()), Store,
1239 OperandTraits<StoreInst>::op_begin(this),
1240 OperandTraits<StoreInst>::operands(this),
1244 setVolatile(isVolatile);
1245 setAlignment(Align);
1246 setAtomic(NotAtomic);
1250 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1251 unsigned Align, AtomicOrdering Order,
1252 SynchronizationScope SynchScope,
1253 Instruction *InsertBefore)
1254 : Instruction(Type::getVoidTy(val->getContext()), Store,
1255 OperandTraits<StoreInst>::op_begin(this),
1256 OperandTraits<StoreInst>::operands(this),
1260 setVolatile(isVolatile);
1261 setAlignment(Align);
1262 setAtomic(Order, SynchScope);
1266 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1267 BasicBlock *InsertAtEnd)
1268 : Instruction(Type::getVoidTy(val->getContext()), Store,
1269 OperandTraits<StoreInst>::op_begin(this),
1270 OperandTraits<StoreInst>::operands(this),
1274 setVolatile(isVolatile);
1276 setAtomic(NotAtomic);
1280 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1281 unsigned Align, BasicBlock *InsertAtEnd)
1282 : Instruction(Type::getVoidTy(val->getContext()), Store,
1283 OperandTraits<StoreInst>::op_begin(this),
1284 OperandTraits<StoreInst>::operands(this),
1288 setVolatile(isVolatile);
1289 setAlignment(Align);
1290 setAtomic(NotAtomic);
1294 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1295 unsigned Align, AtomicOrdering Order,
1296 SynchronizationScope SynchScope,
1297 BasicBlock *InsertAtEnd)
1298 : Instruction(Type::getVoidTy(val->getContext()), Store,
1299 OperandTraits<StoreInst>::op_begin(this),
1300 OperandTraits<StoreInst>::operands(this),
1304 setVolatile(isVolatile);
1305 setAlignment(Align);
1306 setAtomic(Order, SynchScope);
1310 void StoreInst::setAlignment(unsigned Align) {
1311 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
1312 assert(Align <= MaximumAlignment &&
1313 "Alignment is greater than MaximumAlignment!");
1314 setInstructionSubclassData((getSubclassDataFromInstruction() & ~(31 << 1)) |
1315 ((Log2_32(Align)+1) << 1));
1316 assert(getAlignment() == Align && "Alignment representation error!");
1319 //===----------------------------------------------------------------------===//
1320 // AtomicCmpXchgInst Implementation
1321 //===----------------------------------------------------------------------===//
1323 void AtomicCmpXchgInst::Init(Value *Ptr, Value *Cmp, Value *NewVal,
1324 AtomicOrdering Ordering,
1325 SynchronizationScope SynchScope) {
1329 setOrdering(Ordering);
1330 setSynchScope(SynchScope);
1332 assert(getOperand(0) && getOperand(1) && getOperand(2) &&
1333 "All operands must be non-null!");
1334 assert(getOperand(0)->getType()->isPointerTy() &&
1335 "Ptr must have pointer type!");
1336 assert(getOperand(1)->getType() ==
1337 cast<PointerType>(getOperand(0)->getType())->getElementType()
1338 && "Ptr must be a pointer to Cmp type!");
1339 assert(getOperand(2)->getType() ==
1340 cast<PointerType>(getOperand(0)->getType())->getElementType()
1341 && "Ptr must be a pointer to NewVal type!");
1342 assert(Ordering != NotAtomic &&
1343 "AtomicCmpXchg instructions must be atomic!");
1346 AtomicCmpXchgInst::AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal,
1347 AtomicOrdering Ordering,
1348 SynchronizationScope SynchScope,
1349 Instruction *InsertBefore)
1350 : Instruction(Cmp->getType(), AtomicCmpXchg,
1351 OperandTraits<AtomicCmpXchgInst>::op_begin(this),
1352 OperandTraits<AtomicCmpXchgInst>::operands(this),
1354 Init(Ptr, Cmp, NewVal, Ordering, SynchScope);
1357 AtomicCmpXchgInst::AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal,
1358 AtomicOrdering Ordering,
1359 SynchronizationScope SynchScope,
1360 BasicBlock *InsertAtEnd)
1361 : Instruction(Cmp->getType(), AtomicCmpXchg,
1362 OperandTraits<AtomicCmpXchgInst>::op_begin(this),
1363 OperandTraits<AtomicCmpXchgInst>::operands(this),
1365 Init(Ptr, Cmp, NewVal, Ordering, SynchScope);
1368 //===----------------------------------------------------------------------===//
1369 // AtomicRMWInst Implementation
1370 //===----------------------------------------------------------------------===//
1372 void AtomicRMWInst::Init(BinOp Operation, Value *Ptr, Value *Val,
1373 AtomicOrdering Ordering,
1374 SynchronizationScope SynchScope) {
1377 setOperation(Operation);
1378 setOrdering(Ordering);
1379 setSynchScope(SynchScope);
1381 assert(getOperand(0) && getOperand(1) &&
1382 "All operands must be non-null!");
1383 assert(getOperand(0)->getType()->isPointerTy() &&
1384 "Ptr must have pointer type!");
1385 assert(getOperand(1)->getType() ==
1386 cast<PointerType>(getOperand(0)->getType())->getElementType()
1387 && "Ptr must be a pointer to Val type!");
1388 assert(Ordering != NotAtomic &&
1389 "AtomicRMW instructions must be atomic!");
1392 AtomicRMWInst::AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val,
1393 AtomicOrdering Ordering,
1394 SynchronizationScope SynchScope,
1395 Instruction *InsertBefore)
1396 : Instruction(Val->getType(), AtomicRMW,
1397 OperandTraits<AtomicRMWInst>::op_begin(this),
1398 OperandTraits<AtomicRMWInst>::operands(this),
1400 Init(Operation, Ptr, Val, Ordering, SynchScope);
1403 AtomicRMWInst::AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val,
1404 AtomicOrdering Ordering,
1405 SynchronizationScope SynchScope,
1406 BasicBlock *InsertAtEnd)
1407 : Instruction(Val->getType(), AtomicRMW,
1408 OperandTraits<AtomicRMWInst>::op_begin(this),
1409 OperandTraits<AtomicRMWInst>::operands(this),
1411 Init(Operation, Ptr, Val, Ordering, SynchScope);
1414 //===----------------------------------------------------------------------===//
1415 // FenceInst Implementation
1416 //===----------------------------------------------------------------------===//
1418 FenceInst::FenceInst(LLVMContext &C, AtomicOrdering Ordering,
1419 SynchronizationScope SynchScope,
1420 Instruction *InsertBefore)
1421 : Instruction(Type::getVoidTy(C), Fence, 0, 0, InsertBefore) {
1422 setOrdering(Ordering);
1423 setSynchScope(SynchScope);
1426 FenceInst::FenceInst(LLVMContext &C, AtomicOrdering Ordering,
1427 SynchronizationScope SynchScope,
1428 BasicBlock *InsertAtEnd)
1429 : Instruction(Type::getVoidTy(C), Fence, 0, 0, InsertAtEnd) {
1430 setOrdering(Ordering);
1431 setSynchScope(SynchScope);
1434 //===----------------------------------------------------------------------===//
1435 // GetElementPtrInst Implementation
1436 //===----------------------------------------------------------------------===//
1438 void GetElementPtrInst::init(Value *Ptr, ArrayRef<Value *> IdxList,
1439 const Twine &Name) {
1440 assert(NumOperands == 1 + IdxList.size() && "NumOperands not initialized?");
1441 OperandList[0] = Ptr;
1442 std::copy(IdxList.begin(), IdxList.end(), op_begin() + 1);
1446 GetElementPtrInst::GetElementPtrInst(const GetElementPtrInst &GEPI)
1447 : Instruction(GEPI.getType(), GetElementPtr,
1448 OperandTraits<GetElementPtrInst>::op_end(this)
1449 - GEPI.getNumOperands(),
1450 GEPI.getNumOperands()) {
1451 std::copy(GEPI.op_begin(), GEPI.op_end(), op_begin());
1452 SubclassOptionalData = GEPI.SubclassOptionalData;
1455 /// getIndexedType - Returns the type of the element that would be accessed with
1456 /// a gep instruction with the specified parameters.
1458 /// The Idxs pointer should point to a continuous piece of memory containing the
1459 /// indices, either as Value* or uint64_t.
1461 /// A null type is returned if the indices are invalid for the specified
1464 template <typename IndexTy>
1465 static Type *getIndexedTypeInternal(Type *Ptr, ArrayRef<IndexTy> IdxList) {
1466 if (Ptr->isVectorTy()) {
1467 assert(IdxList.size() == 1 &&
1468 "GEP with vector pointers must have a single index");
1469 PointerType *PTy = dyn_cast<PointerType>(
1470 cast<VectorType>(Ptr)->getElementType());
1471 assert(PTy && "Gep with invalid vector pointer found");
1472 return PTy->getElementType();
1475 PointerType *PTy = dyn_cast<PointerType>(Ptr);
1476 if (!PTy) return 0; // Type isn't a pointer type!
1477 Type *Agg = PTy->getElementType();
1479 // Handle the special case of the empty set index set, which is always valid.
1480 if (IdxList.empty())
1483 // If there is at least one index, the top level type must be sized, otherwise
1484 // it cannot be 'stepped over'.
1485 if (!Agg->isSized())
1488 unsigned CurIdx = 1;
1489 for (; CurIdx != IdxList.size(); ++CurIdx) {
1490 CompositeType *CT = dyn_cast<CompositeType>(Agg);
1491 if (!CT || CT->isPointerTy()) return 0;
1492 IndexTy Index = IdxList[CurIdx];
1493 if (!CT->indexValid(Index)) return 0;
1494 Agg = CT->getTypeAtIndex(Index);
1496 return CurIdx == IdxList.size() ? Agg : 0;
1499 Type *GetElementPtrInst::getIndexedType(Type *Ptr, ArrayRef<Value *> IdxList) {
1500 return getIndexedTypeInternal(Ptr, IdxList);
1503 Type *GetElementPtrInst::getIndexedType(Type *Ptr,
1504 ArrayRef<Constant *> IdxList) {
1505 return getIndexedTypeInternal(Ptr, IdxList);
1508 Type *GetElementPtrInst::getIndexedType(Type *Ptr, ArrayRef<uint64_t> IdxList) {
1509 return getIndexedTypeInternal(Ptr, IdxList);
1512 unsigned GetElementPtrInst::getAddressSpace(Value *Ptr) {
1513 Type *Ty = Ptr->getType();
1515 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
1516 Ty = VTy->getElementType();
1518 if (PointerType *PTy = dyn_cast<PointerType>(Ty))
1519 return PTy->getAddressSpace();
1521 llvm_unreachable("Invalid GEP pointer type");
1524 /// hasAllZeroIndices - Return true if all of the indices of this GEP are
1525 /// zeros. If so, the result pointer and the first operand have the same
1526 /// value, just potentially different types.
1527 bool GetElementPtrInst::hasAllZeroIndices() const {
1528 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1529 if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(i))) {
1530 if (!CI->isZero()) return false;
1538 /// hasAllConstantIndices - Return true if all of the indices of this GEP are
1539 /// constant integers. If so, the result pointer and the first operand have
1540 /// a constant offset between them.
1541 bool GetElementPtrInst::hasAllConstantIndices() const {
1542 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1543 if (!isa<ConstantInt>(getOperand(i)))
1549 void GetElementPtrInst::setIsInBounds(bool B) {
1550 cast<GEPOperator>(this)->setIsInBounds(B);
1553 bool GetElementPtrInst::isInBounds() const {
1554 return cast<GEPOperator>(this)->isInBounds();
1557 //===----------------------------------------------------------------------===//
1558 // ExtractElementInst Implementation
1559 //===----------------------------------------------------------------------===//
1561 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
1563 Instruction *InsertBef)
1564 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1566 OperandTraits<ExtractElementInst>::op_begin(this),
1568 assert(isValidOperands(Val, Index) &&
1569 "Invalid extractelement instruction operands!");
1575 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
1577 BasicBlock *InsertAE)
1578 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1580 OperandTraits<ExtractElementInst>::op_begin(this),
1582 assert(isValidOperands(Val, Index) &&
1583 "Invalid extractelement instruction operands!");
1591 bool ExtractElementInst::isValidOperands(const Value *Val, const Value *Index) {
1592 if (!Val->getType()->isVectorTy() || !Index->getType()->isIntegerTy(32))
1598 //===----------------------------------------------------------------------===//
1599 // InsertElementInst Implementation
1600 //===----------------------------------------------------------------------===//
1602 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
1604 Instruction *InsertBef)
1605 : Instruction(Vec->getType(), InsertElement,
1606 OperandTraits<InsertElementInst>::op_begin(this),
1608 assert(isValidOperands(Vec, Elt, Index) &&
1609 "Invalid insertelement instruction operands!");
1616 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
1618 BasicBlock *InsertAE)
1619 : Instruction(Vec->getType(), InsertElement,
1620 OperandTraits<InsertElementInst>::op_begin(this),
1622 assert(isValidOperands(Vec, Elt, Index) &&
1623 "Invalid insertelement instruction operands!");
1631 bool InsertElementInst::isValidOperands(const Value *Vec, const Value *Elt,
1632 const Value *Index) {
1633 if (!Vec->getType()->isVectorTy())
1634 return false; // First operand of insertelement must be vector type.
1636 if (Elt->getType() != cast<VectorType>(Vec->getType())->getElementType())
1637 return false;// Second operand of insertelement must be vector element type.
1639 if (!Index->getType()->isIntegerTy(32))
1640 return false; // Third operand of insertelement must be i32.
1645 //===----------------------------------------------------------------------===//
1646 // ShuffleVectorInst Implementation
1647 //===----------------------------------------------------------------------===//
1649 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1651 Instruction *InsertBefore)
1652 : Instruction(VectorType::get(cast<VectorType>(V1->getType())->getElementType(),
1653 cast<VectorType>(Mask->getType())->getNumElements()),
1655 OperandTraits<ShuffleVectorInst>::op_begin(this),
1656 OperandTraits<ShuffleVectorInst>::operands(this),
1658 assert(isValidOperands(V1, V2, Mask) &&
1659 "Invalid shuffle vector instruction operands!");
1666 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1668 BasicBlock *InsertAtEnd)
1669 : Instruction(VectorType::get(cast<VectorType>(V1->getType())->getElementType(),
1670 cast<VectorType>(Mask->getType())->getNumElements()),
1672 OperandTraits<ShuffleVectorInst>::op_begin(this),
1673 OperandTraits<ShuffleVectorInst>::operands(this),
1675 assert(isValidOperands(V1, V2, Mask) &&
1676 "Invalid shuffle vector instruction operands!");
1684 bool ShuffleVectorInst::isValidOperands(const Value *V1, const Value *V2,
1685 const Value *Mask) {
1686 // V1 and V2 must be vectors of the same type.
1687 if (!V1->getType()->isVectorTy() || V1->getType() != V2->getType())
1690 // Mask must be vector of i32.
1691 VectorType *MaskTy = dyn_cast<VectorType>(Mask->getType());
1692 if (MaskTy == 0 || !MaskTy->getElementType()->isIntegerTy(32))
1695 // Check to see if Mask is valid.
1696 if (isa<UndefValue>(Mask) || isa<ConstantAggregateZero>(Mask))
1699 if (const ConstantVector *MV = dyn_cast<ConstantVector>(Mask)) {
1700 unsigned V1Size = cast<VectorType>(V1->getType())->getNumElements();
1701 for (unsigned i = 0, e = MV->getNumOperands(); i != e; ++i) {
1702 if (ConstantInt *CI = dyn_cast<ConstantInt>(MV->getOperand(i))) {
1703 if (CI->uge(V1Size*2))
1705 } else if (!isa<UndefValue>(MV->getOperand(i))) {
1712 if (const ConstantDataSequential *CDS =
1713 dyn_cast<ConstantDataSequential>(Mask)) {
1714 unsigned V1Size = cast<VectorType>(V1->getType())->getNumElements();
1715 for (unsigned i = 0, e = MaskTy->getNumElements(); i != e; ++i)
1716 if (CDS->getElementAsInteger(i) >= V1Size*2)
1721 // The bitcode reader can create a place holder for a forward reference
1722 // used as the shuffle mask. When this occurs, the shuffle mask will
1723 // fall into this case and fail. To avoid this error, do this bit of
1724 // ugliness to allow such a mask pass.
1725 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(Mask))
1726 if (CE->getOpcode() == Instruction::UserOp1)
1732 /// getMaskValue - Return the index from the shuffle mask for the specified
1733 /// output result. This is either -1 if the element is undef or a number less
1734 /// than 2*numelements.
1735 int ShuffleVectorInst::getMaskValue(Constant *Mask, unsigned i) {
1736 assert(i < Mask->getType()->getVectorNumElements() && "Index out of range");
1737 if (ConstantDataSequential *CDS =dyn_cast<ConstantDataSequential>(Mask))
1738 return CDS->getElementAsInteger(i);
1739 Constant *C = Mask->getAggregateElement(i);
1740 if (isa<UndefValue>(C))
1742 return cast<ConstantInt>(C)->getZExtValue();
1745 /// getShuffleMask - Return the full mask for this instruction, where each
1746 /// element is the element number and undef's are returned as -1.
1747 void ShuffleVectorInst::getShuffleMask(Constant *Mask,
1748 SmallVectorImpl<int> &Result) {
1749 unsigned NumElts = Mask->getType()->getVectorNumElements();
1751 if (ConstantDataSequential *CDS=dyn_cast<ConstantDataSequential>(Mask)) {
1752 for (unsigned i = 0; i != NumElts; ++i)
1753 Result.push_back(CDS->getElementAsInteger(i));
1756 for (unsigned i = 0; i != NumElts; ++i) {
1757 Constant *C = Mask->getAggregateElement(i);
1758 Result.push_back(isa<UndefValue>(C) ? -1 :
1759 cast<ConstantInt>(C)->getZExtValue());
1764 //===----------------------------------------------------------------------===//
1765 // InsertValueInst Class
1766 //===----------------------------------------------------------------------===//
1768 void InsertValueInst::init(Value *Agg, Value *Val, ArrayRef<unsigned> Idxs,
1769 const Twine &Name) {
1770 assert(NumOperands == 2 && "NumOperands not initialized?");
1772 // There's no fundamental reason why we require at least one index
1773 // (other than weirdness with &*IdxBegin being invalid; see
1774 // getelementptr's init routine for example). But there's no
1775 // present need to support it.
1776 assert(Idxs.size() > 0 && "InsertValueInst must have at least one index");
1778 assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs) ==
1779 Val->getType() && "Inserted value must match indexed type!");
1783 Indices.append(Idxs.begin(), Idxs.end());
1787 InsertValueInst::InsertValueInst(const InsertValueInst &IVI)
1788 : Instruction(IVI.getType(), InsertValue,
1789 OperandTraits<InsertValueInst>::op_begin(this), 2),
1790 Indices(IVI.Indices) {
1791 Op<0>() = IVI.getOperand(0);
1792 Op<1>() = IVI.getOperand(1);
1793 SubclassOptionalData = IVI.SubclassOptionalData;
1796 //===----------------------------------------------------------------------===//
1797 // ExtractValueInst Class
1798 //===----------------------------------------------------------------------===//
1800 void ExtractValueInst::init(ArrayRef<unsigned> Idxs, const Twine &Name) {
1801 assert(NumOperands == 1 && "NumOperands not initialized?");
1803 // There's no fundamental reason why we require at least one index.
1804 // But there's no present need to support it.
1805 assert(Idxs.size() > 0 && "ExtractValueInst must have at least one index");
1807 Indices.append(Idxs.begin(), Idxs.end());
1811 ExtractValueInst::ExtractValueInst(const ExtractValueInst &EVI)
1812 : UnaryInstruction(EVI.getType(), ExtractValue, EVI.getOperand(0)),
1813 Indices(EVI.Indices) {
1814 SubclassOptionalData = EVI.SubclassOptionalData;
1817 // getIndexedType - Returns the type of the element that would be extracted
1818 // with an extractvalue instruction with the specified parameters.
1820 // A null type is returned if the indices are invalid for the specified
1823 Type *ExtractValueInst::getIndexedType(Type *Agg,
1824 ArrayRef<unsigned> Idxs) {
1825 for (unsigned CurIdx = 0; CurIdx != Idxs.size(); ++CurIdx) {
1826 unsigned Index = Idxs[CurIdx];
1827 // We can't use CompositeType::indexValid(Index) here.
1828 // indexValid() always returns true for arrays because getelementptr allows
1829 // out-of-bounds indices. Since we don't allow those for extractvalue and
1830 // insertvalue we need to check array indexing manually.
1831 // Since the only other types we can index into are struct types it's just
1832 // as easy to check those manually as well.
1833 if (ArrayType *AT = dyn_cast<ArrayType>(Agg)) {
1834 if (Index >= AT->getNumElements())
1836 } else if (StructType *ST = dyn_cast<StructType>(Agg)) {
1837 if (Index >= ST->getNumElements())
1840 // Not a valid type to index into.
1844 Agg = cast<CompositeType>(Agg)->getTypeAtIndex(Index);
1846 return const_cast<Type*>(Agg);
1849 //===----------------------------------------------------------------------===//
1850 // BinaryOperator Class
1851 //===----------------------------------------------------------------------===//
1853 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
1854 Type *Ty, const Twine &Name,
1855 Instruction *InsertBefore)
1856 : Instruction(Ty, iType,
1857 OperandTraits<BinaryOperator>::op_begin(this),
1858 OperandTraits<BinaryOperator>::operands(this),
1866 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
1867 Type *Ty, const Twine &Name,
1868 BasicBlock *InsertAtEnd)
1869 : Instruction(Ty, iType,
1870 OperandTraits<BinaryOperator>::op_begin(this),
1871 OperandTraits<BinaryOperator>::operands(this),
1880 void BinaryOperator::init(BinaryOps iType) {
1881 Value *LHS = getOperand(0), *RHS = getOperand(1);
1882 (void)LHS; (void)RHS; // Silence warnings.
1883 assert(LHS->getType() == RHS->getType() &&
1884 "Binary operator operand types must match!");
1889 assert(getType() == LHS->getType() &&
1890 "Arithmetic operation should return same type as operands!");
1891 assert(getType()->isIntOrIntVectorTy() &&
1892 "Tried to create an integer operation on a non-integer type!");
1894 case FAdd: case FSub:
1896 assert(getType() == LHS->getType() &&
1897 "Arithmetic operation should return same type as operands!");
1898 assert(getType()->isFPOrFPVectorTy() &&
1899 "Tried to create a floating-point operation on a "
1900 "non-floating-point type!");
1904 assert(getType() == LHS->getType() &&
1905 "Arithmetic operation should return same type as operands!");
1906 assert((getType()->isIntegerTy() || (getType()->isVectorTy() &&
1907 cast<VectorType>(getType())->getElementType()->isIntegerTy())) &&
1908 "Incorrect operand type (not integer) for S/UDIV");
1911 assert(getType() == LHS->getType() &&
1912 "Arithmetic operation should return same type as operands!");
1913 assert(getType()->isFPOrFPVectorTy() &&
1914 "Incorrect operand type (not floating point) for FDIV");
1918 assert(getType() == LHS->getType() &&
1919 "Arithmetic operation should return same type as operands!");
1920 assert((getType()->isIntegerTy() || (getType()->isVectorTy() &&
1921 cast<VectorType>(getType())->getElementType()->isIntegerTy())) &&
1922 "Incorrect operand type (not integer) for S/UREM");
1925 assert(getType() == LHS->getType() &&
1926 "Arithmetic operation should return same type as operands!");
1927 assert(getType()->isFPOrFPVectorTy() &&
1928 "Incorrect operand type (not floating point) for FREM");
1933 assert(getType() == LHS->getType() &&
1934 "Shift operation should return same type as operands!");
1935 assert((getType()->isIntegerTy() ||
1936 (getType()->isVectorTy() &&
1937 cast<VectorType>(getType())->getElementType()->isIntegerTy())) &&
1938 "Tried to create a shift operation on a non-integral type!");
1942 assert(getType() == LHS->getType() &&
1943 "Logical operation should return same type as operands!");
1944 assert((getType()->isIntegerTy() ||
1945 (getType()->isVectorTy() &&
1946 cast<VectorType>(getType())->getElementType()->isIntegerTy())) &&
1947 "Tried to create a logical operation on a non-integral type!");
1955 BinaryOperator *BinaryOperator::Create(BinaryOps Op, Value *S1, Value *S2,
1957 Instruction *InsertBefore) {
1958 assert(S1->getType() == S2->getType() &&
1959 "Cannot create binary operator with two operands of differing type!");
1960 return new BinaryOperator(Op, S1, S2, S1->getType(), Name, InsertBefore);
1963 BinaryOperator *BinaryOperator::Create(BinaryOps Op, Value *S1, Value *S2,
1965 BasicBlock *InsertAtEnd) {
1966 BinaryOperator *Res = Create(Op, S1, S2, Name);
1967 InsertAtEnd->getInstList().push_back(Res);
1971 BinaryOperator *BinaryOperator::CreateNeg(Value *Op, const Twine &Name,
1972 Instruction *InsertBefore) {
1973 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1974 return new BinaryOperator(Instruction::Sub,
1976 Op->getType(), Name, InsertBefore);
1979 BinaryOperator *BinaryOperator::CreateNeg(Value *Op, const Twine &Name,
1980 BasicBlock *InsertAtEnd) {
1981 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1982 return new BinaryOperator(Instruction::Sub,
1984 Op->getType(), Name, InsertAtEnd);
1987 BinaryOperator *BinaryOperator::CreateNSWNeg(Value *Op, const Twine &Name,
1988 Instruction *InsertBefore) {
1989 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1990 return BinaryOperator::CreateNSWSub(zero, Op, Name, InsertBefore);
1993 BinaryOperator *BinaryOperator::CreateNSWNeg(Value *Op, const Twine &Name,
1994 BasicBlock *InsertAtEnd) {
1995 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1996 return BinaryOperator::CreateNSWSub(zero, Op, Name, InsertAtEnd);
1999 BinaryOperator *BinaryOperator::CreateNUWNeg(Value *Op, const Twine &Name,
2000 Instruction *InsertBefore) {
2001 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
2002 return BinaryOperator::CreateNUWSub(zero, Op, Name, InsertBefore);
2005 BinaryOperator *BinaryOperator::CreateNUWNeg(Value *Op, const Twine &Name,
2006 BasicBlock *InsertAtEnd) {
2007 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
2008 return BinaryOperator::CreateNUWSub(zero, Op, Name, InsertAtEnd);
2011 BinaryOperator *BinaryOperator::CreateFNeg(Value *Op, const Twine &Name,
2012 Instruction *InsertBefore) {
2013 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
2014 return new BinaryOperator(Instruction::FSub, zero, Op,
2015 Op->getType(), Name, InsertBefore);
2018 BinaryOperator *BinaryOperator::CreateFNeg(Value *Op, const Twine &Name,
2019 BasicBlock *InsertAtEnd) {
2020 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
2021 return new BinaryOperator(Instruction::FSub, zero, Op,
2022 Op->getType(), Name, InsertAtEnd);
2025 BinaryOperator *BinaryOperator::CreateNot(Value *Op, const Twine &Name,
2026 Instruction *InsertBefore) {
2027 Constant *C = Constant::getAllOnesValue(Op->getType());
2028 return new BinaryOperator(Instruction::Xor, Op, C,
2029 Op->getType(), Name, InsertBefore);
2032 BinaryOperator *BinaryOperator::CreateNot(Value *Op, const Twine &Name,
2033 BasicBlock *InsertAtEnd) {
2034 Constant *AllOnes = Constant::getAllOnesValue(Op->getType());
2035 return new BinaryOperator(Instruction::Xor, Op, AllOnes,
2036 Op->getType(), Name, InsertAtEnd);
2040 // isConstantAllOnes - Helper function for several functions below
2041 static inline bool isConstantAllOnes(const Value *V) {
2042 if (const Constant *C = dyn_cast<Constant>(V))
2043 return C->isAllOnesValue();
2047 bool BinaryOperator::isNeg(const Value *V) {
2048 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
2049 if (Bop->getOpcode() == Instruction::Sub)
2050 if (Constant* C = dyn_cast<Constant>(Bop->getOperand(0)))
2051 return C->isNegativeZeroValue();
2055 bool BinaryOperator::isFNeg(const Value *V) {
2056 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
2057 if (Bop->getOpcode() == Instruction::FSub)
2058 if (Constant* C = dyn_cast<Constant>(Bop->getOperand(0)))
2059 return C->isNegativeZeroValue();
2063 bool BinaryOperator::isNot(const Value *V) {
2064 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
2065 return (Bop->getOpcode() == Instruction::Xor &&
2066 (isConstantAllOnes(Bop->getOperand(1)) ||
2067 isConstantAllOnes(Bop->getOperand(0))));
2071 Value *BinaryOperator::getNegArgument(Value *BinOp) {
2072 return cast<BinaryOperator>(BinOp)->getOperand(1);
2075 const Value *BinaryOperator::getNegArgument(const Value *BinOp) {
2076 return getNegArgument(const_cast<Value*>(BinOp));
2079 Value *BinaryOperator::getFNegArgument(Value *BinOp) {
2080 return cast<BinaryOperator>(BinOp)->getOperand(1);
2083 const Value *BinaryOperator::getFNegArgument(const Value *BinOp) {
2084 return getFNegArgument(const_cast<Value*>(BinOp));
2087 Value *BinaryOperator::getNotArgument(Value *BinOp) {
2088 assert(isNot(BinOp) && "getNotArgument on non-'not' instruction!");
2089 BinaryOperator *BO = cast<BinaryOperator>(BinOp);
2090 Value *Op0 = BO->getOperand(0);
2091 Value *Op1 = BO->getOperand(1);
2092 if (isConstantAllOnes(Op0)) return Op1;
2094 assert(isConstantAllOnes(Op1));
2098 const Value *BinaryOperator::getNotArgument(const Value *BinOp) {
2099 return getNotArgument(const_cast<Value*>(BinOp));
2103 // swapOperands - Exchange the two operands to this instruction. This
2104 // instruction is safe to use on any binary instruction and does not
2105 // modify the semantics of the instruction. If the instruction is
2106 // order dependent (SetLT f.e.) the opcode is changed.
2108 bool BinaryOperator::swapOperands() {
2109 if (!isCommutative())
2110 return true; // Can't commute operands
2111 Op<0>().swap(Op<1>());
2115 void BinaryOperator::setHasNoUnsignedWrap(bool b) {
2116 cast<OverflowingBinaryOperator>(this)->setHasNoUnsignedWrap(b);
2119 void BinaryOperator::setHasNoSignedWrap(bool b) {
2120 cast<OverflowingBinaryOperator>(this)->setHasNoSignedWrap(b);
2123 void BinaryOperator::setIsExact(bool b) {
2124 cast<PossiblyExactOperator>(this)->setIsExact(b);
2127 bool BinaryOperator::hasNoUnsignedWrap() const {
2128 return cast<OverflowingBinaryOperator>(this)->hasNoUnsignedWrap();
2131 bool BinaryOperator::hasNoSignedWrap() const {
2132 return cast<OverflowingBinaryOperator>(this)->hasNoSignedWrap();
2135 bool BinaryOperator::isExact() const {
2136 return cast<PossiblyExactOperator>(this)->isExact();
2139 //===----------------------------------------------------------------------===//
2140 // FPMathOperator Class
2141 //===----------------------------------------------------------------------===//
2143 /// getFPAccuracy - Get the maximum error permitted by this operation in ULPs.
2144 /// An accuracy of 0.0 means that the operation should be performed with the
2145 /// default precision.
2146 float FPMathOperator::getFPAccuracy() const {
2148 cast<Instruction>(this)->getMetadata(LLVMContext::MD_fpmath);
2151 ConstantFP *Accuracy = cast<ConstantFP>(MD->getOperand(0));
2152 return Accuracy->getValueAPF().convertToFloat();
2156 //===----------------------------------------------------------------------===//
2158 //===----------------------------------------------------------------------===//
2160 void CastInst::anchor() {}
2162 // Just determine if this cast only deals with integral->integral conversion.
2163 bool CastInst::isIntegerCast() const {
2164 switch (getOpcode()) {
2165 default: return false;
2166 case Instruction::ZExt:
2167 case Instruction::SExt:
2168 case Instruction::Trunc:
2170 case Instruction::BitCast:
2171 return getOperand(0)->getType()->isIntegerTy() &&
2172 getType()->isIntegerTy();
2176 bool CastInst::isLosslessCast() const {
2177 // Only BitCast can be lossless, exit fast if we're not BitCast
2178 if (getOpcode() != Instruction::BitCast)
2181 // Identity cast is always lossless
2182 Type* SrcTy = getOperand(0)->getType();
2183 Type* DstTy = getType();
2187 // Pointer to pointer is always lossless.
2188 if (SrcTy->isPointerTy())
2189 return DstTy->isPointerTy();
2190 return false; // Other types have no identity values
2193 /// This function determines if the CastInst does not require any bits to be
2194 /// changed in order to effect the cast. Essentially, it identifies cases where
2195 /// no code gen is necessary for the cast, hence the name no-op cast. For
2196 /// example, the following are all no-op casts:
2197 /// # bitcast i32* %x to i8*
2198 /// # bitcast <2 x i32> %x to <4 x i16>
2199 /// # ptrtoint i32* %x to i32 ; on 32-bit plaforms only
2200 /// @brief Determine if the described cast is a no-op.
2201 bool CastInst::isNoopCast(Instruction::CastOps Opcode,
2206 default: llvm_unreachable("Invalid CastOp");
2207 case Instruction::Trunc:
2208 case Instruction::ZExt:
2209 case Instruction::SExt:
2210 case Instruction::FPTrunc:
2211 case Instruction::FPExt:
2212 case Instruction::UIToFP:
2213 case Instruction::SIToFP:
2214 case Instruction::FPToUI:
2215 case Instruction::FPToSI:
2216 return false; // These always modify bits
2217 case Instruction::BitCast:
2218 return true; // BitCast never modifies bits.
2219 case Instruction::PtrToInt:
2220 return IntPtrTy->getScalarSizeInBits() ==
2221 DestTy->getScalarSizeInBits();
2222 case Instruction::IntToPtr:
2223 return IntPtrTy->getScalarSizeInBits() ==
2224 SrcTy->getScalarSizeInBits();
2228 /// @brief Determine if a cast is a no-op.
2229 bool CastInst::isNoopCast(Type *IntPtrTy) const {
2230 return isNoopCast(getOpcode(), getOperand(0)->getType(), getType(), IntPtrTy);
2233 /// This function determines if a pair of casts can be eliminated and what
2234 /// opcode should be used in the elimination. This assumes that there are two
2235 /// instructions like this:
2236 /// * %F = firstOpcode SrcTy %x to MidTy
2237 /// * %S = secondOpcode MidTy %F to DstTy
2238 /// The function returns a resultOpcode so these two casts can be replaced with:
2239 /// * %Replacement = resultOpcode %SrcTy %x to DstTy
2240 /// If no such cast is permited, the function returns 0.
2241 unsigned CastInst::isEliminableCastPair(
2242 Instruction::CastOps firstOp, Instruction::CastOps secondOp,
2243 Type *SrcTy, Type *MidTy, Type *DstTy, Type *IntPtrTy) {
2244 // Define the 144 possibilities for these two cast instructions. The values
2245 // in this matrix determine what to do in a given situation and select the
2246 // case in the switch below. The rows correspond to firstOp, the columns
2247 // correspond to secondOp. In looking at the table below, keep in mind
2248 // the following cast properties:
2250 // Size Compare Source Destination
2251 // Operator Src ? Size Type Sign Type Sign
2252 // -------- ------------ ------------------- ---------------------
2253 // TRUNC > Integer Any Integral Any
2254 // ZEXT < Integral Unsigned Integer Any
2255 // SEXT < Integral Signed Integer Any
2256 // FPTOUI n/a FloatPt n/a Integral Unsigned
2257 // FPTOSI n/a FloatPt n/a Integral Signed
2258 // UITOFP n/a Integral Unsigned FloatPt n/a
2259 // SITOFP n/a Integral Signed FloatPt n/a
2260 // FPTRUNC > FloatPt n/a FloatPt n/a
2261 // FPEXT < FloatPt n/a FloatPt n/a
2262 // PTRTOINT n/a Pointer n/a Integral Unsigned
2263 // INTTOPTR n/a Integral Unsigned Pointer n/a
2264 // BITCAST = FirstClass n/a FirstClass n/a
2266 // NOTE: some transforms are safe, but we consider them to be non-profitable.
2267 // For example, we could merge "fptoui double to i32" + "zext i32 to i64",
2268 // into "fptoui double to i64", but this loses information about the range
2269 // of the produced value (we no longer know the top-part is all zeros).
2270 // Further this conversion is often much more expensive for typical hardware,
2271 // and causes issues when building libgcc. We disallow fptosi+sext for the
2273 const unsigned numCastOps =
2274 Instruction::CastOpsEnd - Instruction::CastOpsBegin;
2275 static const uint8_t CastResults[numCastOps][numCastOps] = {
2276 // T F F U S F F P I B -+
2277 // R Z S P P I I T P 2 N T |
2278 // U E E 2 2 2 2 R E I T C +- secondOp
2279 // N X X U S F F N X N 2 V |
2280 // C T T I I P P C T T P T -+
2281 { 1, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // Trunc -+
2282 { 8, 1, 9,99,99, 2, 0,99,99,99, 2, 3 }, // ZExt |
2283 { 8, 0, 1,99,99, 0, 2,99,99,99, 0, 3 }, // SExt |
2284 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // FPToUI |
2285 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // FPToSI |
2286 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4 }, // UIToFP +- firstOp
2287 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4 }, // SIToFP |
2288 { 99,99,99, 0, 0,99,99, 1, 0,99,99, 4 }, // FPTrunc |
2289 { 99,99,99, 2, 2,99,99,10, 2,99,99, 4 }, // FPExt |
2290 { 1, 0, 0,99,99, 0, 0,99,99,99, 7, 3 }, // PtrToInt |
2291 { 99,99,99,99,99,99,99,99,99,13,99,12 }, // IntToPtr |
2292 { 5, 5, 5, 6, 6, 5, 5, 6, 6,11, 5, 1 }, // BitCast -+
2295 // If either of the casts are a bitcast from scalar to vector, disallow the
2296 // merging. However, bitcast of A->B->A are allowed.
2297 bool isFirstBitcast = (firstOp == Instruction::BitCast);
2298 bool isSecondBitcast = (secondOp == Instruction::BitCast);
2299 bool chainedBitcast = (SrcTy == DstTy && isFirstBitcast && isSecondBitcast);
2301 // Check if any of the bitcasts convert scalars<->vectors.
2302 if ((isFirstBitcast && isa<VectorType>(SrcTy) != isa<VectorType>(MidTy)) ||
2303 (isSecondBitcast && isa<VectorType>(MidTy) != isa<VectorType>(DstTy)))
2304 // Unless we are bitcasing to the original type, disallow optimizations.
2305 if (!chainedBitcast) return 0;
2307 int ElimCase = CastResults[firstOp-Instruction::CastOpsBegin]
2308 [secondOp-Instruction::CastOpsBegin];
2311 // categorically disallowed
2314 // allowed, use first cast's opcode
2317 // allowed, use second cast's opcode
2320 // no-op cast in second op implies firstOp as long as the DestTy
2321 // is integer and we are not converting between a vector and a
2323 if (!SrcTy->isVectorTy() && DstTy->isIntegerTy())
2327 // no-op cast in second op implies firstOp as long as the DestTy
2328 // is floating point.
2329 if (DstTy->isFloatingPointTy())
2333 // no-op cast in first op implies secondOp as long as the SrcTy
2335 if (SrcTy->isIntegerTy())
2339 // no-op cast in first op implies secondOp as long as the SrcTy
2340 // is a floating point.
2341 if (SrcTy->isFloatingPointTy())
2345 // ptrtoint, inttoptr -> bitcast (ptr -> ptr) if int size is >= ptr size
2348 unsigned PtrSize = IntPtrTy->getScalarSizeInBits();
2349 unsigned MidSize = MidTy->getScalarSizeInBits();
2350 if (MidSize >= PtrSize)
2351 return Instruction::BitCast;
2355 // ext, trunc -> bitcast, if the SrcTy and DstTy are same size
2356 // ext, trunc -> ext, if sizeof(SrcTy) < sizeof(DstTy)
2357 // ext, trunc -> trunc, if sizeof(SrcTy) > sizeof(DstTy)
2358 unsigned SrcSize = SrcTy->getScalarSizeInBits();
2359 unsigned DstSize = DstTy->getScalarSizeInBits();
2360 if (SrcSize == DstSize)
2361 return Instruction::BitCast;
2362 else if (SrcSize < DstSize)
2366 case 9: // zext, sext -> zext, because sext can't sign extend after zext
2367 return Instruction::ZExt;
2369 // fpext followed by ftrunc is allowed if the bit size returned to is
2370 // the same as the original, in which case its just a bitcast
2372 return Instruction::BitCast;
2373 return 0; // If the types are not the same we can't eliminate it.
2375 // bitcast followed by ptrtoint is allowed as long as the bitcast
2376 // is a pointer to pointer cast.
2377 if (SrcTy->isPointerTy() && MidTy->isPointerTy())
2381 // inttoptr, bitcast -> intptr if bitcast is a ptr to ptr cast
2382 if (MidTy->isPointerTy() && DstTy->isPointerTy())
2386 // inttoptr, ptrtoint -> bitcast if SrcSize<=PtrSize and SrcSize==DstSize
2389 unsigned PtrSize = IntPtrTy->getScalarSizeInBits();
2390 unsigned SrcSize = SrcTy->getScalarSizeInBits();
2391 unsigned DstSize = DstTy->getScalarSizeInBits();
2392 if (SrcSize <= PtrSize && SrcSize == DstSize)
2393 return Instruction::BitCast;
2397 // cast combination can't happen (error in input). This is for all cases
2398 // where the MidTy is not the same for the two cast instructions.
2399 llvm_unreachable("Invalid Cast Combination");
2401 llvm_unreachable("Error in CastResults table!!!");
2405 CastInst *CastInst::Create(Instruction::CastOps op, Value *S, Type *Ty,
2406 const Twine &Name, Instruction *InsertBefore) {
2407 assert(castIsValid(op, S, Ty) && "Invalid cast!");
2408 // Construct and return the appropriate CastInst subclass
2410 case Trunc: return new TruncInst (S, Ty, Name, InsertBefore);
2411 case ZExt: return new ZExtInst (S, Ty, Name, InsertBefore);
2412 case SExt: return new SExtInst (S, Ty, Name, InsertBefore);
2413 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertBefore);
2414 case FPExt: return new FPExtInst (S, Ty, Name, InsertBefore);
2415 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertBefore);
2416 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertBefore);
2417 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertBefore);
2418 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertBefore);
2419 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertBefore);
2420 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertBefore);
2421 case BitCast: return new BitCastInst (S, Ty, Name, InsertBefore);
2422 default: llvm_unreachable("Invalid opcode provided");
2426 CastInst *CastInst::Create(Instruction::CastOps op, Value *S, Type *Ty,
2427 const Twine &Name, BasicBlock *InsertAtEnd) {
2428 assert(castIsValid(op, S, Ty) && "Invalid cast!");
2429 // Construct and return the appropriate CastInst subclass
2431 case Trunc: return new TruncInst (S, Ty, Name, InsertAtEnd);
2432 case ZExt: return new ZExtInst (S, Ty, Name, InsertAtEnd);
2433 case SExt: return new SExtInst (S, Ty, Name, InsertAtEnd);
2434 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertAtEnd);
2435 case FPExt: return new FPExtInst (S, Ty, Name, InsertAtEnd);
2436 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertAtEnd);
2437 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertAtEnd);
2438 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertAtEnd);
2439 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertAtEnd);
2440 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertAtEnd);
2441 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertAtEnd);
2442 case BitCast: return new BitCastInst (S, Ty, Name, InsertAtEnd);
2443 default: llvm_unreachable("Invalid opcode provided");
2447 CastInst *CastInst::CreateZExtOrBitCast(Value *S, Type *Ty,
2449 Instruction *InsertBefore) {
2450 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2451 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2452 return Create(Instruction::ZExt, S, Ty, Name, InsertBefore);
2455 CastInst *CastInst::CreateZExtOrBitCast(Value *S, Type *Ty,
2457 BasicBlock *InsertAtEnd) {
2458 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2459 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2460 return Create(Instruction::ZExt, S, Ty, Name, InsertAtEnd);
2463 CastInst *CastInst::CreateSExtOrBitCast(Value *S, Type *Ty,
2465 Instruction *InsertBefore) {
2466 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2467 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2468 return Create(Instruction::SExt, S, Ty, Name, InsertBefore);
2471 CastInst *CastInst::CreateSExtOrBitCast(Value *S, Type *Ty,
2473 BasicBlock *InsertAtEnd) {
2474 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2475 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2476 return Create(Instruction::SExt, S, Ty, Name, InsertAtEnd);
2479 CastInst *CastInst::CreateTruncOrBitCast(Value *S, Type *Ty,
2481 Instruction *InsertBefore) {
2482 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2483 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2484 return Create(Instruction::Trunc, S, Ty, Name, InsertBefore);
2487 CastInst *CastInst::CreateTruncOrBitCast(Value *S, Type *Ty,
2489 BasicBlock *InsertAtEnd) {
2490 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2491 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2492 return Create(Instruction::Trunc, S, Ty, Name, InsertAtEnd);
2495 CastInst *CastInst::CreatePointerCast(Value *S, Type *Ty,
2497 BasicBlock *InsertAtEnd) {
2498 assert(S->getType()->isPointerTy() && "Invalid cast");
2499 assert((Ty->isIntegerTy() || Ty->isPointerTy()) &&
2502 if (Ty->isIntegerTy())
2503 return Create(Instruction::PtrToInt, S, Ty, Name, InsertAtEnd);
2504 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2507 /// @brief Create a BitCast or a PtrToInt cast instruction
2508 CastInst *CastInst::CreatePointerCast(Value *S, Type *Ty,
2510 Instruction *InsertBefore) {
2511 assert(S->getType()->isPointerTy() && "Invalid cast");
2512 assert((Ty->isIntegerTy() || Ty->isPointerTy()) &&
2515 if (Ty->isIntegerTy())
2516 return Create(Instruction::PtrToInt, S, Ty, Name, InsertBefore);
2517 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2520 CastInst *CastInst::CreateIntegerCast(Value *C, Type *Ty,
2521 bool isSigned, const Twine &Name,
2522 Instruction *InsertBefore) {
2523 assert(C->getType()->isIntOrIntVectorTy() && Ty->isIntOrIntVectorTy() &&
2524 "Invalid integer cast");
2525 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2526 unsigned DstBits = Ty->getScalarSizeInBits();
2527 Instruction::CastOps opcode =
2528 (SrcBits == DstBits ? Instruction::BitCast :
2529 (SrcBits > DstBits ? Instruction::Trunc :
2530 (isSigned ? Instruction::SExt : Instruction::ZExt)));
2531 return Create(opcode, C, Ty, Name, InsertBefore);
2534 CastInst *CastInst::CreateIntegerCast(Value *C, Type *Ty,
2535 bool isSigned, const Twine &Name,
2536 BasicBlock *InsertAtEnd) {
2537 assert(C->getType()->isIntOrIntVectorTy() && Ty->isIntOrIntVectorTy() &&
2539 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2540 unsigned DstBits = Ty->getScalarSizeInBits();
2541 Instruction::CastOps opcode =
2542 (SrcBits == DstBits ? Instruction::BitCast :
2543 (SrcBits > DstBits ? Instruction::Trunc :
2544 (isSigned ? Instruction::SExt : Instruction::ZExt)));
2545 return Create(opcode, C, Ty, Name, InsertAtEnd);
2548 CastInst *CastInst::CreateFPCast(Value *C, Type *Ty,
2550 Instruction *InsertBefore) {
2551 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
2553 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2554 unsigned DstBits = Ty->getScalarSizeInBits();
2555 Instruction::CastOps opcode =
2556 (SrcBits == DstBits ? Instruction::BitCast :
2557 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
2558 return Create(opcode, C, Ty, Name, InsertBefore);
2561 CastInst *CastInst::CreateFPCast(Value *C, Type *Ty,
2563 BasicBlock *InsertAtEnd) {
2564 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
2566 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2567 unsigned DstBits = Ty->getScalarSizeInBits();
2568 Instruction::CastOps opcode =
2569 (SrcBits == DstBits ? Instruction::BitCast :
2570 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
2571 return Create(opcode, C, Ty, Name, InsertAtEnd);
2574 // Check whether it is valid to call getCastOpcode for these types.
2575 // This routine must be kept in sync with getCastOpcode.
2576 bool CastInst::isCastable(Type *SrcTy, Type *DestTy) {
2577 if (!SrcTy->isFirstClassType() || !DestTy->isFirstClassType())
2580 if (SrcTy == DestTy)
2583 if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy))
2584 if (VectorType *DestVecTy = dyn_cast<VectorType>(DestTy))
2585 if (SrcVecTy->getNumElements() == DestVecTy->getNumElements()) {
2586 // An element by element cast. Valid if casting the elements is valid.
2587 SrcTy = SrcVecTy->getElementType();
2588 DestTy = DestVecTy->getElementType();
2591 // Get the bit sizes, we'll need these
2592 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); // 0 for ptr
2593 unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr
2595 // Run through the possibilities ...
2596 if (DestTy->isIntegerTy()) { // Casting to integral
2597 if (SrcTy->isIntegerTy()) { // Casting from integral
2599 } else if (SrcTy->isFloatingPointTy()) { // Casting from floating pt
2601 } else if (SrcTy->isVectorTy()) { // Casting from vector
2602 return DestBits == SrcBits;
2603 } else { // Casting from something else
2604 return SrcTy->isPointerTy();
2606 } else if (DestTy->isFloatingPointTy()) { // Casting to floating pt
2607 if (SrcTy->isIntegerTy()) { // Casting from integral
2609 } else if (SrcTy->isFloatingPointTy()) { // Casting from floating pt
2611 } else if (SrcTy->isVectorTy()) { // Casting from vector
2612 return DestBits == SrcBits;
2613 } else { // Casting from something else
2616 } else if (DestTy->isVectorTy()) { // Casting to vector
2617 return DestBits == SrcBits;
2618 } else if (DestTy->isPointerTy()) { // Casting to pointer
2619 if (SrcTy->isPointerTy()) { // Casting from pointer
2621 } else if (SrcTy->isIntegerTy()) { // Casting from integral
2623 } else { // Casting from something else
2626 } else if (DestTy->isX86_MMXTy()) {
2627 if (SrcTy->isVectorTy()) {
2628 return DestBits == SrcBits; // 64-bit vector to MMX
2632 } else { // Casting to something else
2637 // Provide a way to get a "cast" where the cast opcode is inferred from the
2638 // types and size of the operand. This, basically, is a parallel of the
2639 // logic in the castIsValid function below. This axiom should hold:
2640 // castIsValid( getCastOpcode(Val, Ty), Val, Ty)
2641 // should not assert in castIsValid. In other words, this produces a "correct"
2642 // casting opcode for the arguments passed to it.
2643 // This routine must be kept in sync with isCastable.
2644 Instruction::CastOps
2645 CastInst::getCastOpcode(
2646 const Value *Src, bool SrcIsSigned, Type *DestTy, bool DestIsSigned) {
2647 Type *SrcTy = Src->getType();
2649 assert(SrcTy->isFirstClassType() && DestTy->isFirstClassType() &&
2650 "Only first class types are castable!");
2652 if (SrcTy == DestTy)
2655 if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy))
2656 if (VectorType *DestVecTy = dyn_cast<VectorType>(DestTy))
2657 if (SrcVecTy->getNumElements() == DestVecTy->getNumElements()) {
2658 // An element by element cast. Find the appropriate opcode based on the
2660 SrcTy = SrcVecTy->getElementType();
2661 DestTy = DestVecTy->getElementType();
2664 // Get the bit sizes, we'll need these
2665 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); // 0 for ptr
2666 unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr
2668 // Run through the possibilities ...
2669 if (DestTy->isIntegerTy()) { // Casting to integral
2670 if (SrcTy->isIntegerTy()) { // Casting from integral
2671 if (DestBits < SrcBits)
2672 return Trunc; // int -> smaller int
2673 else if (DestBits > SrcBits) { // its an extension
2675 return SExt; // signed -> SEXT
2677 return ZExt; // unsigned -> ZEXT
2679 return BitCast; // Same size, No-op cast
2681 } else if (SrcTy->isFloatingPointTy()) { // Casting from floating pt
2683 return FPToSI; // FP -> sint
2685 return FPToUI; // FP -> uint
2686 } else if (SrcTy->isVectorTy()) {
2687 assert(DestBits == SrcBits &&
2688 "Casting vector to integer of different width");
2689 return BitCast; // Same size, no-op cast
2691 assert(SrcTy->isPointerTy() &&
2692 "Casting from a value that is not first-class type");
2693 return PtrToInt; // ptr -> int
2695 } else if (DestTy->isFloatingPointTy()) { // Casting to floating pt
2696 if (SrcTy->isIntegerTy()) { // Casting from integral
2698 return SIToFP; // sint -> FP
2700 return UIToFP; // uint -> FP
2701 } else if (SrcTy->isFloatingPointTy()) { // Casting from floating pt
2702 if (DestBits < SrcBits) {
2703 return FPTrunc; // FP -> smaller FP
2704 } else if (DestBits > SrcBits) {
2705 return FPExt; // FP -> larger FP
2707 return BitCast; // same size, no-op cast
2709 } else if (SrcTy->isVectorTy()) {
2710 assert(DestBits == SrcBits &&
2711 "Casting vector to floating point of different width");
2712 return BitCast; // same size, no-op cast
2714 llvm_unreachable("Casting pointer or non-first class to float");
2715 } else if (DestTy->isVectorTy()) {
2716 assert(DestBits == SrcBits &&
2717 "Illegal cast to vector (wrong type or size)");
2719 } else if (DestTy->isPointerTy()) {
2720 if (SrcTy->isPointerTy()) {
2721 return BitCast; // ptr -> ptr
2722 } else if (SrcTy->isIntegerTy()) {
2723 return IntToPtr; // int -> ptr
2725 llvm_unreachable("Casting pointer to other than pointer or int");
2726 } else if (DestTy->isX86_MMXTy()) {
2727 if (SrcTy->isVectorTy()) {
2728 assert(DestBits == SrcBits && "Casting vector of wrong width to X86_MMX");
2729 return BitCast; // 64-bit vector to MMX
2731 llvm_unreachable("Illegal cast to X86_MMX");
2733 llvm_unreachable("Casting to type that is not first-class");
2736 //===----------------------------------------------------------------------===//
2737 // CastInst SubClass Constructors
2738 //===----------------------------------------------------------------------===//
2740 /// Check that the construction parameters for a CastInst are correct. This
2741 /// could be broken out into the separate constructors but it is useful to have
2742 /// it in one place and to eliminate the redundant code for getting the sizes
2743 /// of the types involved.
2745 CastInst::castIsValid(Instruction::CastOps op, Value *S, Type *DstTy) {
2747 // Check for type sanity on the arguments
2748 Type *SrcTy = S->getType();
2749 if (!SrcTy->isFirstClassType() || !DstTy->isFirstClassType() ||
2750 SrcTy->isAggregateType() || DstTy->isAggregateType())
2753 // Get the size of the types in bits, we'll need this later
2754 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
2755 unsigned DstBitSize = DstTy->getScalarSizeInBits();
2757 // If these are vector types, get the lengths of the vectors (using zero for
2758 // scalar types means that checking that vector lengths match also checks that
2759 // scalars are not being converted to vectors or vectors to scalars).
2760 unsigned SrcLength = SrcTy->isVectorTy() ?
2761 cast<VectorType>(SrcTy)->getNumElements() : 0;
2762 unsigned DstLength = DstTy->isVectorTy() ?
2763 cast<VectorType>(DstTy)->getNumElements() : 0;
2765 // Switch on the opcode provided
2767 default: return false; // This is an input error
2768 case Instruction::Trunc:
2769 return SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy() &&
2770 SrcLength == DstLength && SrcBitSize > DstBitSize;
2771 case Instruction::ZExt:
2772 return SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy() &&
2773 SrcLength == DstLength && SrcBitSize < DstBitSize;
2774 case Instruction::SExt:
2775 return SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy() &&
2776 SrcLength == DstLength && SrcBitSize < DstBitSize;
2777 case Instruction::FPTrunc:
2778 return SrcTy->isFPOrFPVectorTy() && DstTy->isFPOrFPVectorTy() &&
2779 SrcLength == DstLength && SrcBitSize > DstBitSize;
2780 case Instruction::FPExt:
2781 return SrcTy->isFPOrFPVectorTy() && DstTy->isFPOrFPVectorTy() &&
2782 SrcLength == DstLength && SrcBitSize < DstBitSize;
2783 case Instruction::UIToFP:
2784 case Instruction::SIToFP:
2785 return SrcTy->isIntOrIntVectorTy() && DstTy->isFPOrFPVectorTy() &&
2786 SrcLength == DstLength;
2787 case Instruction::FPToUI:
2788 case Instruction::FPToSI:
2789 return SrcTy->isFPOrFPVectorTy() && DstTy->isIntOrIntVectorTy() &&
2790 SrcLength == DstLength;
2791 case Instruction::PtrToInt:
2792 if (isa<VectorType>(SrcTy) != isa<VectorType>(DstTy))
2794 if (VectorType *VT = dyn_cast<VectorType>(SrcTy))
2795 if (VT->getNumElements() != cast<VectorType>(DstTy)->getNumElements())
2797 return SrcTy->getScalarType()->isPointerTy() &&
2798 DstTy->getScalarType()->isIntegerTy();
2799 case Instruction::IntToPtr:
2800 if (isa<VectorType>(SrcTy) != isa<VectorType>(DstTy))
2802 if (VectorType *VT = dyn_cast<VectorType>(SrcTy))
2803 if (VT->getNumElements() != cast<VectorType>(DstTy)->getNumElements())
2805 return SrcTy->getScalarType()->isIntegerTy() &&
2806 DstTy->getScalarType()->isPointerTy();
2807 case Instruction::BitCast:
2808 // BitCast implies a no-op cast of type only. No bits change.
2809 // However, you can't cast pointers to anything but pointers.
2810 if (SrcTy->isPointerTy() != DstTy->isPointerTy())
2813 // Now we know we're not dealing with a pointer/non-pointer mismatch. In all
2814 // these cases, the cast is okay if the source and destination bit widths
2816 return SrcTy->getPrimitiveSizeInBits() == DstTy->getPrimitiveSizeInBits();
2820 TruncInst::TruncInst(
2821 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2822 ) : CastInst(Ty, Trunc, S, Name, InsertBefore) {
2823 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
2826 TruncInst::TruncInst(
2827 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2828 ) : CastInst(Ty, Trunc, S, Name, InsertAtEnd) {
2829 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
2833 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2834 ) : CastInst(Ty, ZExt, S, Name, InsertBefore) {
2835 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
2839 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2840 ) : CastInst(Ty, ZExt, S, Name, InsertAtEnd) {
2841 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
2844 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2845 ) : CastInst(Ty, SExt, S, Name, InsertBefore) {
2846 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
2850 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2851 ) : CastInst(Ty, SExt, S, Name, InsertAtEnd) {
2852 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
2855 FPTruncInst::FPTruncInst(
2856 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2857 ) : CastInst(Ty, FPTrunc, S, Name, InsertBefore) {
2858 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
2861 FPTruncInst::FPTruncInst(
2862 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2863 ) : CastInst(Ty, FPTrunc, S, Name, InsertAtEnd) {
2864 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
2867 FPExtInst::FPExtInst(
2868 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2869 ) : CastInst(Ty, FPExt, S, Name, InsertBefore) {
2870 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
2873 FPExtInst::FPExtInst(
2874 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2875 ) : CastInst(Ty, FPExt, S, Name, InsertAtEnd) {
2876 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
2879 UIToFPInst::UIToFPInst(
2880 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2881 ) : CastInst(Ty, UIToFP, S, Name, InsertBefore) {
2882 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
2885 UIToFPInst::UIToFPInst(
2886 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2887 ) : CastInst(Ty, UIToFP, S, Name, InsertAtEnd) {
2888 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
2891 SIToFPInst::SIToFPInst(
2892 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2893 ) : CastInst(Ty, SIToFP, S, Name, InsertBefore) {
2894 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
2897 SIToFPInst::SIToFPInst(
2898 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2899 ) : CastInst(Ty, SIToFP, S, Name, InsertAtEnd) {
2900 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
2903 FPToUIInst::FPToUIInst(
2904 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2905 ) : CastInst(Ty, FPToUI, S, Name, InsertBefore) {
2906 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
2909 FPToUIInst::FPToUIInst(
2910 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2911 ) : CastInst(Ty, FPToUI, S, Name, InsertAtEnd) {
2912 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
2915 FPToSIInst::FPToSIInst(
2916 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2917 ) : CastInst(Ty, FPToSI, S, Name, InsertBefore) {
2918 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
2921 FPToSIInst::FPToSIInst(
2922 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2923 ) : CastInst(Ty, FPToSI, S, Name, InsertAtEnd) {
2924 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
2927 PtrToIntInst::PtrToIntInst(
2928 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2929 ) : CastInst(Ty, PtrToInt, S, Name, InsertBefore) {
2930 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
2933 PtrToIntInst::PtrToIntInst(
2934 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2935 ) : CastInst(Ty, PtrToInt, S, Name, InsertAtEnd) {
2936 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
2939 IntToPtrInst::IntToPtrInst(
2940 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2941 ) : CastInst(Ty, IntToPtr, S, Name, InsertBefore) {
2942 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
2945 IntToPtrInst::IntToPtrInst(
2946 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2947 ) : CastInst(Ty, IntToPtr, S, Name, InsertAtEnd) {
2948 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
2951 BitCastInst::BitCastInst(
2952 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2953 ) : CastInst(Ty, BitCast, S, Name, InsertBefore) {
2954 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
2957 BitCastInst::BitCastInst(
2958 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2959 ) : CastInst(Ty, BitCast, S, Name, InsertAtEnd) {
2960 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
2963 //===----------------------------------------------------------------------===//
2965 //===----------------------------------------------------------------------===//
2967 void CmpInst::anchor() {}
2969 CmpInst::CmpInst(Type *ty, OtherOps op, unsigned short predicate,
2970 Value *LHS, Value *RHS, const Twine &Name,
2971 Instruction *InsertBefore)
2972 : Instruction(ty, op,
2973 OperandTraits<CmpInst>::op_begin(this),
2974 OperandTraits<CmpInst>::operands(this),
2978 setPredicate((Predicate)predicate);
2982 CmpInst::CmpInst(Type *ty, OtherOps op, unsigned short predicate,
2983 Value *LHS, Value *RHS, const Twine &Name,
2984 BasicBlock *InsertAtEnd)
2985 : Instruction(ty, op,
2986 OperandTraits<CmpInst>::op_begin(this),
2987 OperandTraits<CmpInst>::operands(this),
2991 setPredicate((Predicate)predicate);
2996 CmpInst::Create(OtherOps Op, unsigned short predicate,
2997 Value *S1, Value *S2,
2998 const Twine &Name, Instruction *InsertBefore) {
2999 if (Op == Instruction::ICmp) {
3001 return new ICmpInst(InsertBefore, CmpInst::Predicate(predicate),
3004 return new ICmpInst(CmpInst::Predicate(predicate),
3009 return new FCmpInst(InsertBefore, CmpInst::Predicate(predicate),
3012 return new FCmpInst(CmpInst::Predicate(predicate),
3017 CmpInst::Create(OtherOps Op, unsigned short predicate, Value *S1, Value *S2,
3018 const Twine &Name, BasicBlock *InsertAtEnd) {
3019 if (Op == Instruction::ICmp) {
3020 return new ICmpInst(*InsertAtEnd, CmpInst::Predicate(predicate),
3023 return new FCmpInst(*InsertAtEnd, CmpInst::Predicate(predicate),
3027 void CmpInst::swapOperands() {
3028 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
3031 cast<FCmpInst>(this)->swapOperands();
3034 bool CmpInst::isCommutative() const {
3035 if (const ICmpInst *IC = dyn_cast<ICmpInst>(this))
3036 return IC->isCommutative();
3037 return cast<FCmpInst>(this)->isCommutative();
3040 bool CmpInst::isEquality() const {
3041 if (const ICmpInst *IC = dyn_cast<ICmpInst>(this))
3042 return IC->isEquality();
3043 return cast<FCmpInst>(this)->isEquality();
3047 CmpInst::Predicate CmpInst::getInversePredicate(Predicate pred) {
3049 default: llvm_unreachable("Unknown cmp predicate!");
3050 case ICMP_EQ: return ICMP_NE;
3051 case ICMP_NE: return ICMP_EQ;
3052 case ICMP_UGT: return ICMP_ULE;
3053 case ICMP_ULT: return ICMP_UGE;
3054 case ICMP_UGE: return ICMP_ULT;
3055 case ICMP_ULE: return ICMP_UGT;
3056 case ICMP_SGT: return ICMP_SLE;
3057 case ICMP_SLT: return ICMP_SGE;
3058 case ICMP_SGE: return ICMP_SLT;
3059 case ICMP_SLE: return ICMP_SGT;
3061 case FCMP_OEQ: return FCMP_UNE;
3062 case FCMP_ONE: return FCMP_UEQ;
3063 case FCMP_OGT: return FCMP_ULE;
3064 case FCMP_OLT: return FCMP_UGE;
3065 case FCMP_OGE: return FCMP_ULT;
3066 case FCMP_OLE: return FCMP_UGT;
3067 case FCMP_UEQ: return FCMP_ONE;
3068 case FCMP_UNE: return FCMP_OEQ;
3069 case FCMP_UGT: return FCMP_OLE;
3070 case FCMP_ULT: return FCMP_OGE;
3071 case FCMP_UGE: return FCMP_OLT;
3072 case FCMP_ULE: return FCMP_OGT;
3073 case FCMP_ORD: return FCMP_UNO;
3074 case FCMP_UNO: return FCMP_ORD;
3075 case FCMP_TRUE: return FCMP_FALSE;
3076 case FCMP_FALSE: return FCMP_TRUE;
3080 ICmpInst::Predicate ICmpInst::getSignedPredicate(Predicate pred) {
3082 default: llvm_unreachable("Unknown icmp predicate!");
3083 case ICMP_EQ: case ICMP_NE:
3084 case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE:
3086 case ICMP_UGT: return ICMP_SGT;
3087 case ICMP_ULT: return ICMP_SLT;
3088 case ICMP_UGE: return ICMP_SGE;
3089 case ICMP_ULE: return ICMP_SLE;
3093 ICmpInst::Predicate ICmpInst::getUnsignedPredicate(Predicate pred) {
3095 default: llvm_unreachable("Unknown icmp predicate!");
3096 case ICMP_EQ: case ICMP_NE:
3097 case ICMP_UGT: case ICMP_ULT: case ICMP_UGE: case ICMP_ULE:
3099 case ICMP_SGT: return ICMP_UGT;
3100 case ICMP_SLT: return ICMP_ULT;
3101 case ICMP_SGE: return ICMP_UGE;
3102 case ICMP_SLE: return ICMP_ULE;
3106 /// Initialize a set of values that all satisfy the condition with C.
3109 ICmpInst::makeConstantRange(Predicate pred, const APInt &C) {
3112 uint32_t BitWidth = C.getBitWidth();
3114 default: llvm_unreachable("Invalid ICmp opcode to ConstantRange ctor!");
3115 case ICmpInst::ICMP_EQ: Upper++; break;
3116 case ICmpInst::ICMP_NE: Lower++; break;
3117 case ICmpInst::ICMP_ULT:
3118 Lower = APInt::getMinValue(BitWidth);
3119 // Check for an empty-set condition.
3121 return ConstantRange(BitWidth, /*isFullSet=*/false);
3123 case ICmpInst::ICMP_SLT:
3124 Lower = APInt::getSignedMinValue(BitWidth);
3125 // Check for an empty-set condition.
3127 return ConstantRange(BitWidth, /*isFullSet=*/false);
3129 case ICmpInst::ICMP_UGT:
3130 Lower++; Upper = APInt::getMinValue(BitWidth); // Min = Next(Max)
3131 // Check for an empty-set condition.
3133 return ConstantRange(BitWidth, /*isFullSet=*/false);
3135 case ICmpInst::ICMP_SGT:
3136 Lower++; Upper = APInt::getSignedMinValue(BitWidth); // Min = Next(Max)
3137 // Check for an empty-set condition.
3139 return ConstantRange(BitWidth, /*isFullSet=*/false);
3141 case ICmpInst::ICMP_ULE:
3142 Lower = APInt::getMinValue(BitWidth); Upper++;
3143 // Check for a full-set condition.
3145 return ConstantRange(BitWidth, /*isFullSet=*/true);
3147 case ICmpInst::ICMP_SLE:
3148 Lower = APInt::getSignedMinValue(BitWidth); Upper++;
3149 // Check for a full-set condition.
3151 return ConstantRange(BitWidth, /*isFullSet=*/true);
3153 case ICmpInst::ICMP_UGE:
3154 Upper = APInt::getMinValue(BitWidth); // Min = Next(Max)
3155 // Check for a full-set condition.
3157 return ConstantRange(BitWidth, /*isFullSet=*/true);
3159 case ICmpInst::ICMP_SGE:
3160 Upper = APInt::getSignedMinValue(BitWidth); // Min = Next(Max)
3161 // Check for a full-set condition.
3163 return ConstantRange(BitWidth, /*isFullSet=*/true);
3166 return ConstantRange(Lower, Upper);
3169 CmpInst::Predicate CmpInst::getSwappedPredicate(Predicate pred) {
3171 default: llvm_unreachable("Unknown cmp predicate!");
3172 case ICMP_EQ: case ICMP_NE:
3174 case ICMP_SGT: return ICMP_SLT;
3175 case ICMP_SLT: return ICMP_SGT;
3176 case ICMP_SGE: return ICMP_SLE;
3177 case ICMP_SLE: return ICMP_SGE;
3178 case ICMP_UGT: return ICMP_ULT;
3179 case ICMP_ULT: return ICMP_UGT;
3180 case ICMP_UGE: return ICMP_ULE;
3181 case ICMP_ULE: return ICMP_UGE;
3183 case FCMP_FALSE: case FCMP_TRUE:
3184 case FCMP_OEQ: case FCMP_ONE:
3185 case FCMP_UEQ: case FCMP_UNE:
3186 case FCMP_ORD: case FCMP_UNO:
3188 case FCMP_OGT: return FCMP_OLT;
3189 case FCMP_OLT: return FCMP_OGT;
3190 case FCMP_OGE: return FCMP_OLE;
3191 case FCMP_OLE: return FCMP_OGE;
3192 case FCMP_UGT: return FCMP_ULT;
3193 case FCMP_ULT: return FCMP_UGT;
3194 case FCMP_UGE: return FCMP_ULE;
3195 case FCMP_ULE: return FCMP_UGE;
3199 bool CmpInst::isUnsigned(unsigned short predicate) {
3200 switch (predicate) {
3201 default: return false;
3202 case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_ULE: case ICmpInst::ICMP_UGT:
3203 case ICmpInst::ICMP_UGE: return true;
3207 bool CmpInst::isSigned(unsigned short predicate) {
3208 switch (predicate) {
3209 default: return false;
3210 case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_SLE: case ICmpInst::ICMP_SGT:
3211 case ICmpInst::ICMP_SGE: return true;
3215 bool CmpInst::isOrdered(unsigned short predicate) {
3216 switch (predicate) {
3217 default: return false;
3218 case FCmpInst::FCMP_OEQ: case FCmpInst::FCMP_ONE: case FCmpInst::FCMP_OGT:
3219 case FCmpInst::FCMP_OLT: case FCmpInst::FCMP_OGE: case FCmpInst::FCMP_OLE:
3220 case FCmpInst::FCMP_ORD: return true;
3224 bool CmpInst::isUnordered(unsigned short predicate) {
3225 switch (predicate) {
3226 default: return false;
3227 case FCmpInst::FCMP_UEQ: case FCmpInst::FCMP_UNE: case FCmpInst::FCMP_UGT:
3228 case FCmpInst::FCMP_ULT: case FCmpInst::FCMP_UGE: case FCmpInst::FCMP_ULE:
3229 case FCmpInst::FCMP_UNO: return true;
3233 bool CmpInst::isTrueWhenEqual(unsigned short predicate) {
3235 default: return false;
3236 case ICMP_EQ: case ICMP_UGE: case ICMP_ULE: case ICMP_SGE: case ICMP_SLE:
3237 case FCMP_TRUE: case FCMP_UEQ: case FCMP_UGE: case FCMP_ULE: return true;
3241 bool CmpInst::isFalseWhenEqual(unsigned short predicate) {
3243 case ICMP_NE: case ICMP_UGT: case ICMP_ULT: case ICMP_SGT: case ICMP_SLT:
3244 case FCMP_FALSE: case FCMP_ONE: case FCMP_OGT: case FCMP_OLT: return true;
3245 default: return false;
3250 //===----------------------------------------------------------------------===//
3251 // SwitchInst Implementation
3252 //===----------------------------------------------------------------------===//
3254 void SwitchInst::init(Value *Value, BasicBlock *Default, unsigned NumReserved) {
3255 assert(Value && Default && NumReserved);
3256 ReservedSpace = NumReserved;
3258 OperandList = allocHungoffUses(ReservedSpace);
3260 OperandList[0] = Value;
3261 OperandList[1] = Default;
3264 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
3265 /// switch on and a default destination. The number of additional cases can
3266 /// be specified here to make memory allocation more efficient. This
3267 /// constructor can also autoinsert before another instruction.
3268 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
3269 Instruction *InsertBefore)
3270 : TerminatorInst(Type::getVoidTy(Value->getContext()), Instruction::Switch,
3271 0, 0, InsertBefore) {
3272 init(Value, Default, 2+NumCases*2);
3275 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
3276 /// switch on and a default destination. The number of additional cases can
3277 /// be specified here to make memory allocation more efficient. This
3278 /// constructor also autoinserts at the end of the specified BasicBlock.
3279 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
3280 BasicBlock *InsertAtEnd)
3281 : TerminatorInst(Type::getVoidTy(Value->getContext()), Instruction::Switch,
3282 0, 0, InsertAtEnd) {
3283 init(Value, Default, 2+NumCases*2);
3286 SwitchInst::SwitchInst(const SwitchInst &SI)
3287 : TerminatorInst(SI.getType(), Instruction::Switch, 0, 0) {
3288 init(SI.getCondition(), SI.getDefaultDest(), SI.getNumOperands());
3289 NumOperands = SI.getNumOperands();
3290 Use *OL = OperandList, *InOL = SI.OperandList;
3291 for (unsigned i = 2, E = SI.getNumOperands(); i != E; i += 2) {
3293 OL[i+1] = InOL[i+1];
3295 TheSubsets = SI.TheSubsets;
3296 SubclassOptionalData = SI.SubclassOptionalData;
3299 SwitchInst::~SwitchInst() {
3304 /// addCase - Add an entry to the switch instruction...
3306 void SwitchInst::addCase(ConstantInt *OnVal, BasicBlock *Dest) {
3307 IntegersSubsetToBB Mapping;
3309 // FIXME: Currently we work with ConstantInt based cases.
3310 // So inititalize IntItem container directly from ConstantInt.
3311 Mapping.add(IntItem::fromConstantInt(OnVal));
3312 IntegersSubset CaseRanges = Mapping.getCase();
3313 addCase(CaseRanges, Dest);
3316 void SwitchInst::addCase(IntegersSubset& OnVal, BasicBlock *Dest) {
3317 unsigned NewCaseIdx = getNumCases();
3318 unsigned OpNo = NumOperands;
3319 if (OpNo+2 > ReservedSpace)
3320 growOperands(); // Get more space!
3321 // Initialize some new operands.
3322 assert(OpNo+1 < ReservedSpace && "Growing didn't work!");
3323 NumOperands = OpNo+2;
3325 SubsetsIt TheSubsetsIt = TheSubsets.insert(TheSubsets.end(), OnVal);
3327 CaseIt Case(this, NewCaseIdx, TheSubsetsIt);
3328 Case.updateCaseValueOperand(OnVal);
3329 Case.setSuccessor(Dest);
3332 /// removeCase - This method removes the specified case and its successor
3333 /// from the switch instruction.
3334 void SwitchInst::removeCase(CaseIt& i) {
3335 unsigned idx = i.getCaseIndex();
3337 assert(2 + idx*2 < getNumOperands() && "Case index out of range!!!");
3339 unsigned NumOps = getNumOperands();
3340 Use *OL = OperandList;
3342 // Overwrite this case with the end of the list.
3343 if (2 + (idx + 1) * 2 != NumOps) {
3344 OL[2 + idx * 2] = OL[NumOps - 2];
3345 OL[2 + idx * 2 + 1] = OL[NumOps - 1];
3348 // Nuke the last value.
3349 OL[NumOps-2].set(0);
3350 OL[NumOps-2+1].set(0);
3352 // Do the same with TheCases collection:
3353 if (i.SubsetIt != --TheSubsets.end()) {
3354 *i.SubsetIt = TheSubsets.back();
3355 TheSubsets.pop_back();
3357 TheSubsets.pop_back();
3358 i.SubsetIt = TheSubsets.end();
3361 NumOperands = NumOps-2;
3364 /// growOperands - grow operands - This grows the operand list in response
3365 /// to a push_back style of operation. This grows the number of ops by 3 times.
3367 void SwitchInst::growOperands() {
3368 unsigned e = getNumOperands();
3369 unsigned NumOps = e*3;
3371 ReservedSpace = NumOps;
3372 Use *NewOps = allocHungoffUses(NumOps);
3373 Use *OldOps = OperandList;
3374 for (unsigned i = 0; i != e; ++i) {
3375 NewOps[i] = OldOps[i];
3377 OperandList = NewOps;
3378 Use::zap(OldOps, OldOps + e, true);
3382 BasicBlock *SwitchInst::getSuccessorV(unsigned idx) const {
3383 return getSuccessor(idx);
3385 unsigned SwitchInst::getNumSuccessorsV() const {
3386 return getNumSuccessors();
3388 void SwitchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
3389 setSuccessor(idx, B);
3392 //===----------------------------------------------------------------------===//
3393 // IndirectBrInst Implementation
3394 //===----------------------------------------------------------------------===//
3396 void IndirectBrInst::init(Value *Address, unsigned NumDests) {
3397 assert(Address && Address->getType()->isPointerTy() &&
3398 "Address of indirectbr must be a pointer");
3399 ReservedSpace = 1+NumDests;
3401 OperandList = allocHungoffUses(ReservedSpace);
3403 OperandList[0] = Address;
3407 /// growOperands - grow operands - This grows the operand list in response
3408 /// to a push_back style of operation. This grows the number of ops by 2 times.
3410 void IndirectBrInst::growOperands() {
3411 unsigned e = getNumOperands();
3412 unsigned NumOps = e*2;
3414 ReservedSpace = NumOps;
3415 Use *NewOps = allocHungoffUses(NumOps);
3416 Use *OldOps = OperandList;
3417 for (unsigned i = 0; i != e; ++i)
3418 NewOps[i] = OldOps[i];
3419 OperandList = NewOps;
3420 Use::zap(OldOps, OldOps + e, true);
3423 IndirectBrInst::IndirectBrInst(Value *Address, unsigned NumCases,
3424 Instruction *InsertBefore)
3425 : TerminatorInst(Type::getVoidTy(Address->getContext()),Instruction::IndirectBr,
3426 0, 0, InsertBefore) {
3427 init(Address, NumCases);
3430 IndirectBrInst::IndirectBrInst(Value *Address, unsigned NumCases,
3431 BasicBlock *InsertAtEnd)
3432 : TerminatorInst(Type::getVoidTy(Address->getContext()),Instruction::IndirectBr,
3433 0, 0, InsertAtEnd) {
3434 init(Address, NumCases);
3437 IndirectBrInst::IndirectBrInst(const IndirectBrInst &IBI)
3438 : TerminatorInst(Type::getVoidTy(IBI.getContext()), Instruction::IndirectBr,
3439 allocHungoffUses(IBI.getNumOperands()),
3440 IBI.getNumOperands()) {
3441 Use *OL = OperandList, *InOL = IBI.OperandList;
3442 for (unsigned i = 0, E = IBI.getNumOperands(); i != E; ++i)
3444 SubclassOptionalData = IBI.SubclassOptionalData;
3447 IndirectBrInst::~IndirectBrInst() {
3451 /// addDestination - Add a destination.
3453 void IndirectBrInst::addDestination(BasicBlock *DestBB) {
3454 unsigned OpNo = NumOperands;
3455 if (OpNo+1 > ReservedSpace)
3456 growOperands(); // Get more space!
3457 // Initialize some new operands.
3458 assert(OpNo < ReservedSpace && "Growing didn't work!");
3459 NumOperands = OpNo+1;
3460 OperandList[OpNo] = DestBB;
3463 /// removeDestination - This method removes the specified successor from the
3464 /// indirectbr instruction.
3465 void IndirectBrInst::removeDestination(unsigned idx) {
3466 assert(idx < getNumOperands()-1 && "Successor index out of range!");
3468 unsigned NumOps = getNumOperands();
3469 Use *OL = OperandList;
3471 // Replace this value with the last one.
3472 OL[idx+1] = OL[NumOps-1];
3474 // Nuke the last value.
3475 OL[NumOps-1].set(0);
3476 NumOperands = NumOps-1;
3479 BasicBlock *IndirectBrInst::getSuccessorV(unsigned idx) const {
3480 return getSuccessor(idx);
3482 unsigned IndirectBrInst::getNumSuccessorsV() const {
3483 return getNumSuccessors();
3485 void IndirectBrInst::setSuccessorV(unsigned idx, BasicBlock *B) {
3486 setSuccessor(idx, B);
3489 //===----------------------------------------------------------------------===//
3490 // clone_impl() implementations
3491 //===----------------------------------------------------------------------===//
3493 // Define these methods here so vtables don't get emitted into every translation
3494 // unit that uses these classes.
3496 GetElementPtrInst *GetElementPtrInst::clone_impl() const {
3497 return new (getNumOperands()) GetElementPtrInst(*this);
3500 BinaryOperator *BinaryOperator::clone_impl() const {
3501 return Create(getOpcode(), Op<0>(), Op<1>());
3504 FCmpInst* FCmpInst::clone_impl() const {
3505 return new FCmpInst(getPredicate(), Op<0>(), Op<1>());
3508 ICmpInst* ICmpInst::clone_impl() const {
3509 return new ICmpInst(getPredicate(), Op<0>(), Op<1>());
3512 ExtractValueInst *ExtractValueInst::clone_impl() const {
3513 return new ExtractValueInst(*this);
3516 InsertValueInst *InsertValueInst::clone_impl() const {
3517 return new InsertValueInst(*this);
3520 AllocaInst *AllocaInst::clone_impl() const {
3521 return new AllocaInst(getAllocatedType(),
3522 (Value*)getOperand(0),
3526 LoadInst *LoadInst::clone_impl() const {
3527 return new LoadInst(getOperand(0), Twine(), isVolatile(),
3528 getAlignment(), getOrdering(), getSynchScope());
3531 StoreInst *StoreInst::clone_impl() const {
3532 return new StoreInst(getOperand(0), getOperand(1), isVolatile(),
3533 getAlignment(), getOrdering(), getSynchScope());
3537 AtomicCmpXchgInst *AtomicCmpXchgInst::clone_impl() const {
3538 AtomicCmpXchgInst *Result =
3539 new AtomicCmpXchgInst(getOperand(0), getOperand(1), getOperand(2),
3540 getOrdering(), getSynchScope());
3541 Result->setVolatile(isVolatile());
3545 AtomicRMWInst *AtomicRMWInst::clone_impl() const {
3546 AtomicRMWInst *Result =
3547 new AtomicRMWInst(getOperation(),getOperand(0), getOperand(1),
3548 getOrdering(), getSynchScope());
3549 Result->setVolatile(isVolatile());
3553 FenceInst *FenceInst::clone_impl() const {
3554 return new FenceInst(getContext(), getOrdering(), getSynchScope());
3557 TruncInst *TruncInst::clone_impl() const {
3558 return new TruncInst(getOperand(0), getType());
3561 ZExtInst *ZExtInst::clone_impl() const {
3562 return new ZExtInst(getOperand(0), getType());
3565 SExtInst *SExtInst::clone_impl() const {
3566 return new SExtInst(getOperand(0), getType());
3569 FPTruncInst *FPTruncInst::clone_impl() const {
3570 return new FPTruncInst(getOperand(0), getType());
3573 FPExtInst *FPExtInst::clone_impl() const {
3574 return new FPExtInst(getOperand(0), getType());
3577 UIToFPInst *UIToFPInst::clone_impl() const {
3578 return new UIToFPInst(getOperand(0), getType());
3581 SIToFPInst *SIToFPInst::clone_impl() const {
3582 return new SIToFPInst(getOperand(0), getType());
3585 FPToUIInst *FPToUIInst::clone_impl() const {
3586 return new FPToUIInst(getOperand(0), getType());
3589 FPToSIInst *FPToSIInst::clone_impl() const {
3590 return new FPToSIInst(getOperand(0), getType());
3593 PtrToIntInst *PtrToIntInst::clone_impl() const {
3594 return new PtrToIntInst(getOperand(0), getType());
3597 IntToPtrInst *IntToPtrInst::clone_impl() const {
3598 return new IntToPtrInst(getOperand(0), getType());
3601 BitCastInst *BitCastInst::clone_impl() const {
3602 return new BitCastInst(getOperand(0), getType());
3605 CallInst *CallInst::clone_impl() const {
3606 return new(getNumOperands()) CallInst(*this);
3609 SelectInst *SelectInst::clone_impl() const {
3610 return SelectInst::Create(getOperand(0), getOperand(1), getOperand(2));
3613 VAArgInst *VAArgInst::clone_impl() const {
3614 return new VAArgInst(getOperand(0), getType());
3617 ExtractElementInst *ExtractElementInst::clone_impl() const {
3618 return ExtractElementInst::Create(getOperand(0), getOperand(1));
3621 InsertElementInst *InsertElementInst::clone_impl() const {
3622 return InsertElementInst::Create(getOperand(0), getOperand(1), getOperand(2));
3625 ShuffleVectorInst *ShuffleVectorInst::clone_impl() const {
3626 return new ShuffleVectorInst(getOperand(0), getOperand(1), getOperand(2));
3629 PHINode *PHINode::clone_impl() const {
3630 return new PHINode(*this);
3633 LandingPadInst *LandingPadInst::clone_impl() const {
3634 return new LandingPadInst(*this);
3637 ReturnInst *ReturnInst::clone_impl() const {
3638 return new(getNumOperands()) ReturnInst(*this);
3641 BranchInst *BranchInst::clone_impl() const {
3642 return new(getNumOperands()) BranchInst(*this);
3645 SwitchInst *SwitchInst::clone_impl() const {
3646 return new SwitchInst(*this);
3649 IndirectBrInst *IndirectBrInst::clone_impl() const {
3650 return new IndirectBrInst(*this);
3654 InvokeInst *InvokeInst::clone_impl() const {
3655 return new(getNumOperands()) InvokeInst(*this);
3658 ResumeInst *ResumeInst::clone_impl() const {
3659 return new(1) ResumeInst(*this);
3662 UnreachableInst *UnreachableInst::clone_impl() const {
3663 LLVMContext &Context = getContext();
3664 return new UnreachableInst(Context);