1 //===-- Instructions.cpp - Implement the LLVM instructions ----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements all of the non-inline methods for the LLVM instruction
13 //===----------------------------------------------------------------------===//
15 #include "llvm/IR/Instructions.h"
16 #include "LLVMContextImpl.h"
17 #include "llvm/IR/Constants.h"
18 #include "llvm/IR/DataLayout.h"
19 #include "llvm/IR/DerivedTypes.h"
20 #include "llvm/IR/Function.h"
21 #include "llvm/IR/Module.h"
22 #include "llvm/IR/Operator.h"
23 #include "llvm/Support/CallSite.h"
24 #include "llvm/Support/ConstantRange.h"
25 #include "llvm/Support/ErrorHandling.h"
26 #include "llvm/Support/MathExtras.h"
29 //===----------------------------------------------------------------------===//
31 //===----------------------------------------------------------------------===//
33 User::op_iterator CallSite::getCallee() const {
34 Instruction *II(getInstruction());
36 ? cast<CallInst>(II)->op_end() - 1 // Skip Callee
37 : cast<InvokeInst>(II)->op_end() - 3; // Skip BB, BB, Callee
40 //===----------------------------------------------------------------------===//
41 // TerminatorInst Class
42 //===----------------------------------------------------------------------===//
44 // Out of line virtual method, so the vtable, etc has a home.
45 TerminatorInst::~TerminatorInst() {
48 //===----------------------------------------------------------------------===//
49 // UnaryInstruction Class
50 //===----------------------------------------------------------------------===//
52 // Out of line virtual method, so the vtable, etc has a home.
53 UnaryInstruction::~UnaryInstruction() {
56 //===----------------------------------------------------------------------===//
58 //===----------------------------------------------------------------------===//
60 /// areInvalidOperands - Return a string if the specified operands are invalid
61 /// for a select operation, otherwise return null.
62 const char *SelectInst::areInvalidOperands(Value *Op0, Value *Op1, Value *Op2) {
63 if (Op1->getType() != Op2->getType())
64 return "both values to select must have same type";
66 if (VectorType *VT = dyn_cast<VectorType>(Op0->getType())) {
68 if (VT->getElementType() != Type::getInt1Ty(Op0->getContext()))
69 return "vector select condition element type must be i1";
70 VectorType *ET = dyn_cast<VectorType>(Op1->getType());
72 return "selected values for vector select must be vectors";
73 if (ET->getNumElements() != VT->getNumElements())
74 return "vector select requires selected vectors to have "
75 "the same vector length as select condition";
76 } else if (Op0->getType() != Type::getInt1Ty(Op0->getContext())) {
77 return "select condition must be i1 or <n x i1>";
83 //===----------------------------------------------------------------------===//
85 //===----------------------------------------------------------------------===//
87 PHINode::PHINode(const PHINode &PN)
88 : Instruction(PN.getType(), Instruction::PHI,
89 allocHungoffUses(PN.getNumOperands()), PN.getNumOperands()),
90 ReservedSpace(PN.getNumOperands()) {
91 std::copy(PN.op_begin(), PN.op_end(), op_begin());
92 std::copy(PN.block_begin(), PN.block_end(), block_begin());
93 SubclassOptionalData = PN.SubclassOptionalData;
100 Use *PHINode::allocHungoffUses(unsigned N) const {
101 // Allocate the array of Uses of the incoming values, followed by a pointer
102 // (with bottom bit set) to the User, followed by the array of pointers to
103 // the incoming basic blocks.
104 size_t size = N * sizeof(Use) + sizeof(Use::UserRef)
105 + N * sizeof(BasicBlock*);
106 Use *Begin = static_cast<Use*>(::operator new(size));
107 Use *End = Begin + N;
108 (void) new(End) Use::UserRef(const_cast<PHINode*>(this), 1);
109 return Use::initTags(Begin, End);
112 // removeIncomingValue - Remove an incoming value. This is useful if a
113 // predecessor basic block is deleted.
114 Value *PHINode::removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty) {
115 Value *Removed = getIncomingValue(Idx);
117 // Move everything after this operand down.
119 // FIXME: we could just swap with the end of the list, then erase. However,
120 // clients might not expect this to happen. The code as it is thrashes the
121 // use/def lists, which is kinda lame.
122 std::copy(op_begin() + Idx + 1, op_end(), op_begin() + Idx);
123 std::copy(block_begin() + Idx + 1, block_end(), block_begin() + Idx);
125 // Nuke the last value.
129 // If the PHI node is dead, because it has zero entries, nuke it now.
130 if (getNumOperands() == 0 && DeletePHIIfEmpty) {
131 // If anyone is using this PHI, make them use a dummy value instead...
132 replaceAllUsesWith(UndefValue::get(getType()));
138 /// growOperands - grow operands - This grows the operand list in response
139 /// to a push_back style of operation. This grows the number of ops by 1.5
142 void PHINode::growOperands() {
143 unsigned e = getNumOperands();
144 unsigned NumOps = e + e / 2;
145 if (NumOps < 2) NumOps = 2; // 2 op PHI nodes are VERY common.
147 Use *OldOps = op_begin();
148 BasicBlock **OldBlocks = block_begin();
150 ReservedSpace = NumOps;
151 OperandList = allocHungoffUses(ReservedSpace);
153 std::copy(OldOps, OldOps + e, op_begin());
154 std::copy(OldBlocks, OldBlocks + e, block_begin());
156 Use::zap(OldOps, OldOps + e, true);
159 /// hasConstantValue - If the specified PHI node always merges together the same
160 /// value, return the value, otherwise return null.
161 Value *PHINode::hasConstantValue() const {
162 // Exploit the fact that phi nodes always have at least one entry.
163 Value *ConstantValue = getIncomingValue(0);
164 for (unsigned i = 1, e = getNumIncomingValues(); i != e; ++i)
165 if (getIncomingValue(i) != ConstantValue && getIncomingValue(i) != this) {
166 if (ConstantValue != this)
167 return 0; // Incoming values not all the same.
168 // The case where the first value is this PHI.
169 ConstantValue = getIncomingValue(i);
171 if (ConstantValue == this)
172 return UndefValue::get(getType());
173 return ConstantValue;
176 //===----------------------------------------------------------------------===//
177 // LandingPadInst Implementation
178 //===----------------------------------------------------------------------===//
180 LandingPadInst::LandingPadInst(Type *RetTy, Value *PersonalityFn,
181 unsigned NumReservedValues, const Twine &NameStr,
182 Instruction *InsertBefore)
183 : Instruction(RetTy, Instruction::LandingPad, 0, 0, InsertBefore) {
184 init(PersonalityFn, 1 + NumReservedValues, NameStr);
187 LandingPadInst::LandingPadInst(Type *RetTy, Value *PersonalityFn,
188 unsigned NumReservedValues, const Twine &NameStr,
189 BasicBlock *InsertAtEnd)
190 : Instruction(RetTy, Instruction::LandingPad, 0, 0, InsertAtEnd) {
191 init(PersonalityFn, 1 + NumReservedValues, NameStr);
194 LandingPadInst::LandingPadInst(const LandingPadInst &LP)
195 : Instruction(LP.getType(), Instruction::LandingPad,
196 allocHungoffUses(LP.getNumOperands()), LP.getNumOperands()),
197 ReservedSpace(LP.getNumOperands()) {
198 Use *OL = OperandList, *InOL = LP.OperandList;
199 for (unsigned I = 0, E = ReservedSpace; I != E; ++I)
202 setCleanup(LP.isCleanup());
205 LandingPadInst::~LandingPadInst() {
209 LandingPadInst *LandingPadInst::Create(Type *RetTy, Value *PersonalityFn,
210 unsigned NumReservedClauses,
211 const Twine &NameStr,
212 Instruction *InsertBefore) {
213 return new LandingPadInst(RetTy, PersonalityFn, NumReservedClauses, NameStr,
217 LandingPadInst *LandingPadInst::Create(Type *RetTy, Value *PersonalityFn,
218 unsigned NumReservedClauses,
219 const Twine &NameStr,
220 BasicBlock *InsertAtEnd) {
221 return new LandingPadInst(RetTy, PersonalityFn, NumReservedClauses, NameStr,
225 void LandingPadInst::init(Value *PersFn, unsigned NumReservedValues,
226 const Twine &NameStr) {
227 ReservedSpace = NumReservedValues;
229 OperandList = allocHungoffUses(ReservedSpace);
230 OperandList[0] = PersFn;
235 /// growOperands - grow operands - This grows the operand list in response to a
236 /// push_back style of operation. This grows the number of ops by 2 times.
237 void LandingPadInst::growOperands(unsigned Size) {
238 unsigned e = getNumOperands();
239 if (ReservedSpace >= e + Size) return;
240 ReservedSpace = (e + Size / 2) * 2;
242 Use *NewOps = allocHungoffUses(ReservedSpace);
243 Use *OldOps = OperandList;
244 for (unsigned i = 0; i != e; ++i)
245 NewOps[i] = OldOps[i];
247 OperandList = NewOps;
248 Use::zap(OldOps, OldOps + e, true);
251 void LandingPadInst::addClause(Value *Val) {
252 unsigned OpNo = getNumOperands();
254 assert(OpNo < ReservedSpace && "Growing didn't work!");
256 OperandList[OpNo] = Val;
259 //===----------------------------------------------------------------------===//
260 // CallInst Implementation
261 //===----------------------------------------------------------------------===//
263 CallInst::~CallInst() {
266 void CallInst::init(Value *Func, ArrayRef<Value *> Args, const Twine &NameStr) {
267 assert(NumOperands == Args.size() + 1 && "NumOperands not set up?");
272 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
274 assert((Args.size() == FTy->getNumParams() ||
275 (FTy->isVarArg() && Args.size() > FTy->getNumParams())) &&
276 "Calling a function with bad signature!");
278 for (unsigned i = 0; i != Args.size(); ++i)
279 assert((i >= FTy->getNumParams() ||
280 FTy->getParamType(i) == Args[i]->getType()) &&
281 "Calling a function with a bad signature!");
284 std::copy(Args.begin(), Args.end(), op_begin());
288 void CallInst::init(Value *Func, const Twine &NameStr) {
289 assert(NumOperands == 1 && "NumOperands not set up?");
294 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
296 assert(FTy->getNumParams() == 0 && "Calling a function with bad signature");
302 CallInst::CallInst(Value *Func, const Twine &Name,
303 Instruction *InsertBefore)
304 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
305 ->getElementType())->getReturnType(),
307 OperandTraits<CallInst>::op_end(this) - 1,
312 CallInst::CallInst(Value *Func, const Twine &Name,
313 BasicBlock *InsertAtEnd)
314 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
315 ->getElementType())->getReturnType(),
317 OperandTraits<CallInst>::op_end(this) - 1,
322 CallInst::CallInst(const CallInst &CI)
323 : Instruction(CI.getType(), Instruction::Call,
324 OperandTraits<CallInst>::op_end(this) - CI.getNumOperands(),
325 CI.getNumOperands()) {
326 setAttributes(CI.getAttributes());
327 setTailCall(CI.isTailCall());
328 setCallingConv(CI.getCallingConv());
330 std::copy(CI.op_begin(), CI.op_end(), op_begin());
331 SubclassOptionalData = CI.SubclassOptionalData;
334 void CallInst::addAttribute(unsigned i, Attribute attr) {
335 AttributeSet PAL = getAttributes();
337 LLVMContext &Context = getContext();
338 PAL = PAL.addAttributes(Context, i,
339 AttributeSet::get(Context, i, B));
343 void CallInst::removeAttribute(unsigned i, Attribute attr) {
344 AttributeSet PAL = getAttributes();
346 LLVMContext &Context = getContext();
347 PAL = PAL.removeAttributes(Context, i,
348 AttributeSet::get(Context, i, B));
352 bool CallInst::hasFnAttr(Attribute::AttrKind A) const {
353 if (AttributeList.hasAttribute(AttributeSet::FunctionIndex, A))
355 if (const Function *F = getCalledFunction())
356 return F->getAttributes().hasAttribute(AttributeSet::FunctionIndex, A);
360 bool CallInst::paramHasAttr(unsigned i, Attribute::AttrKind A) const {
361 if (AttributeList.hasAttribute(i, A))
363 if (const Function *F = getCalledFunction())
364 return F->getAttributes().hasAttribute(i, A);
368 /// IsConstantOne - Return true only if val is constant int 1
369 static bool IsConstantOne(Value *val) {
370 assert(val && "IsConstantOne does not work with NULL val");
371 return isa<ConstantInt>(val) && cast<ConstantInt>(val)->isOne();
374 static Instruction *createMalloc(Instruction *InsertBefore,
375 BasicBlock *InsertAtEnd, Type *IntPtrTy,
376 Type *AllocTy, Value *AllocSize,
377 Value *ArraySize, Function *MallocF,
379 assert(((!InsertBefore && InsertAtEnd) || (InsertBefore && !InsertAtEnd)) &&
380 "createMalloc needs either InsertBefore or InsertAtEnd");
382 // malloc(type) becomes:
383 // bitcast (i8* malloc(typeSize)) to type*
384 // malloc(type, arraySize) becomes:
385 // bitcast (i8 *malloc(typeSize*arraySize)) to type*
387 ArraySize = ConstantInt::get(IntPtrTy, 1);
388 else if (ArraySize->getType() != IntPtrTy) {
390 ArraySize = CastInst::CreateIntegerCast(ArraySize, IntPtrTy, false,
393 ArraySize = CastInst::CreateIntegerCast(ArraySize, IntPtrTy, false,
397 if (!IsConstantOne(ArraySize)) {
398 if (IsConstantOne(AllocSize)) {
399 AllocSize = ArraySize; // Operand * 1 = Operand
400 } else if (Constant *CO = dyn_cast<Constant>(ArraySize)) {
401 Constant *Scale = ConstantExpr::getIntegerCast(CO, IntPtrTy,
403 // Malloc arg is constant product of type size and array size
404 AllocSize = ConstantExpr::getMul(Scale, cast<Constant>(AllocSize));
406 // Multiply type size by the array size...
408 AllocSize = BinaryOperator::CreateMul(ArraySize, AllocSize,
409 "mallocsize", InsertBefore);
411 AllocSize = BinaryOperator::CreateMul(ArraySize, AllocSize,
412 "mallocsize", InsertAtEnd);
416 assert(AllocSize->getType() == IntPtrTy && "malloc arg is wrong size");
417 // Create the call to Malloc.
418 BasicBlock* BB = InsertBefore ? InsertBefore->getParent() : InsertAtEnd;
419 Module* M = BB->getParent()->getParent();
420 Type *BPTy = Type::getInt8PtrTy(BB->getContext());
421 Value *MallocFunc = MallocF;
423 // prototype malloc as "void *malloc(size_t)"
424 MallocFunc = M->getOrInsertFunction("malloc", BPTy, IntPtrTy, NULL);
425 PointerType *AllocPtrType = PointerType::getUnqual(AllocTy);
426 CallInst *MCall = NULL;
427 Instruction *Result = NULL;
429 MCall = CallInst::Create(MallocFunc, AllocSize, "malloccall", InsertBefore);
431 if (Result->getType() != AllocPtrType)
432 // Create a cast instruction to convert to the right type...
433 Result = new BitCastInst(MCall, AllocPtrType, Name, InsertBefore);
435 MCall = CallInst::Create(MallocFunc, AllocSize, "malloccall");
437 if (Result->getType() != AllocPtrType) {
438 InsertAtEnd->getInstList().push_back(MCall);
439 // Create a cast instruction to convert to the right type...
440 Result = new BitCastInst(MCall, AllocPtrType, Name);
443 MCall->setTailCall();
444 if (Function *F = dyn_cast<Function>(MallocFunc)) {
445 MCall->setCallingConv(F->getCallingConv());
446 if (!F->doesNotAlias(0)) F->setDoesNotAlias(0);
448 assert(!MCall->getType()->isVoidTy() && "Malloc has void return type");
453 /// CreateMalloc - Generate the IR for a call to malloc:
454 /// 1. Compute the malloc call's argument as the specified type's size,
455 /// possibly multiplied by the array size if the array size is not
457 /// 2. Call malloc with that argument.
458 /// 3. Bitcast the result of the malloc call to the specified type.
459 Instruction *CallInst::CreateMalloc(Instruction *InsertBefore,
460 Type *IntPtrTy, Type *AllocTy,
461 Value *AllocSize, Value *ArraySize,
464 return createMalloc(InsertBefore, NULL, IntPtrTy, AllocTy, AllocSize,
465 ArraySize, MallocF, Name);
468 /// CreateMalloc - Generate the IR for a call to malloc:
469 /// 1. Compute the malloc call's argument as the specified type's size,
470 /// possibly multiplied by the array size if the array size is not
472 /// 2. Call malloc with that argument.
473 /// 3. Bitcast the result of the malloc call to the specified type.
474 /// Note: This function does not add the bitcast to the basic block, that is the
475 /// responsibility of the caller.
476 Instruction *CallInst::CreateMalloc(BasicBlock *InsertAtEnd,
477 Type *IntPtrTy, Type *AllocTy,
478 Value *AllocSize, Value *ArraySize,
479 Function *MallocF, const Twine &Name) {
480 return createMalloc(NULL, InsertAtEnd, IntPtrTy, AllocTy, AllocSize,
481 ArraySize, MallocF, Name);
484 static Instruction* createFree(Value* Source, Instruction *InsertBefore,
485 BasicBlock *InsertAtEnd) {
486 assert(((!InsertBefore && InsertAtEnd) || (InsertBefore && !InsertAtEnd)) &&
487 "createFree needs either InsertBefore or InsertAtEnd");
488 assert(Source->getType()->isPointerTy() &&
489 "Can not free something of nonpointer type!");
491 BasicBlock* BB = InsertBefore ? InsertBefore->getParent() : InsertAtEnd;
492 Module* M = BB->getParent()->getParent();
494 Type *VoidTy = Type::getVoidTy(M->getContext());
495 Type *IntPtrTy = Type::getInt8PtrTy(M->getContext());
496 // prototype free as "void free(void*)"
497 Value *FreeFunc = M->getOrInsertFunction("free", VoidTy, IntPtrTy, NULL);
498 CallInst* Result = NULL;
499 Value *PtrCast = Source;
501 if (Source->getType() != IntPtrTy)
502 PtrCast = new BitCastInst(Source, IntPtrTy, "", InsertBefore);
503 Result = CallInst::Create(FreeFunc, PtrCast, "", InsertBefore);
505 if (Source->getType() != IntPtrTy)
506 PtrCast = new BitCastInst(Source, IntPtrTy, "", InsertAtEnd);
507 Result = CallInst::Create(FreeFunc, PtrCast, "");
509 Result->setTailCall();
510 if (Function *F = dyn_cast<Function>(FreeFunc))
511 Result->setCallingConv(F->getCallingConv());
516 /// CreateFree - Generate the IR for a call to the builtin free function.
517 Instruction * CallInst::CreateFree(Value* Source, Instruction *InsertBefore) {
518 return createFree(Source, InsertBefore, NULL);
521 /// CreateFree - Generate the IR for a call to the builtin free function.
522 /// Note: This function does not add the call to the basic block, that is the
523 /// responsibility of the caller.
524 Instruction* CallInst::CreateFree(Value* Source, BasicBlock *InsertAtEnd) {
525 Instruction* FreeCall = createFree(Source, NULL, InsertAtEnd);
526 assert(FreeCall && "CreateFree did not create a CallInst");
530 //===----------------------------------------------------------------------===//
531 // InvokeInst Implementation
532 //===----------------------------------------------------------------------===//
534 void InvokeInst::init(Value *Fn, BasicBlock *IfNormal, BasicBlock *IfException,
535 ArrayRef<Value *> Args, const Twine &NameStr) {
536 assert(NumOperands == 3 + Args.size() && "NumOperands not set up?");
539 Op<-1>() = IfException;
543 cast<FunctionType>(cast<PointerType>(Fn->getType())->getElementType());
545 assert(((Args.size() == FTy->getNumParams()) ||
546 (FTy->isVarArg() && Args.size() > FTy->getNumParams())) &&
547 "Invoking a function with bad signature");
549 for (unsigned i = 0, e = Args.size(); i != e; i++)
550 assert((i >= FTy->getNumParams() ||
551 FTy->getParamType(i) == Args[i]->getType()) &&
552 "Invoking a function with a bad signature!");
555 std::copy(Args.begin(), Args.end(), op_begin());
559 InvokeInst::InvokeInst(const InvokeInst &II)
560 : TerminatorInst(II.getType(), Instruction::Invoke,
561 OperandTraits<InvokeInst>::op_end(this)
562 - II.getNumOperands(),
563 II.getNumOperands()) {
564 setAttributes(II.getAttributes());
565 setCallingConv(II.getCallingConv());
566 std::copy(II.op_begin(), II.op_end(), op_begin());
567 SubclassOptionalData = II.SubclassOptionalData;
570 BasicBlock *InvokeInst::getSuccessorV(unsigned idx) const {
571 return getSuccessor(idx);
573 unsigned InvokeInst::getNumSuccessorsV() const {
574 return getNumSuccessors();
576 void InvokeInst::setSuccessorV(unsigned idx, BasicBlock *B) {
577 return setSuccessor(idx, B);
580 bool InvokeInst::hasFnAttr(Attribute::AttrKind A) const {
581 if (AttributeList.hasAttribute(AttributeSet::FunctionIndex, A))
583 if (const Function *F = getCalledFunction())
584 return F->getAttributes().hasAttribute(AttributeSet::FunctionIndex, A);
588 bool InvokeInst::paramHasAttr(unsigned i, Attribute::AttrKind A) const {
589 if (AttributeList.hasAttribute(i, A))
591 if (const Function *F = getCalledFunction())
592 return F->getAttributes().hasAttribute(i, A);
596 void InvokeInst::addAttribute(unsigned i, Attribute attr) {
597 AttributeSet PAL = getAttributes();
599 PAL = PAL.addAttributes(getContext(), i,
600 AttributeSet::get(getContext(), i, B));
604 void InvokeInst::removeAttribute(unsigned i, Attribute attr) {
605 AttributeSet PAL = getAttributes();
607 PAL = PAL.removeAttributes(getContext(), i,
608 AttributeSet::get(getContext(), i, B));
612 LandingPadInst *InvokeInst::getLandingPadInst() const {
613 return cast<LandingPadInst>(getUnwindDest()->getFirstNonPHI());
616 //===----------------------------------------------------------------------===//
617 // ReturnInst Implementation
618 //===----------------------------------------------------------------------===//
620 ReturnInst::ReturnInst(const ReturnInst &RI)
621 : TerminatorInst(Type::getVoidTy(RI.getContext()), Instruction::Ret,
622 OperandTraits<ReturnInst>::op_end(this) -
624 RI.getNumOperands()) {
625 if (RI.getNumOperands())
626 Op<0>() = RI.Op<0>();
627 SubclassOptionalData = RI.SubclassOptionalData;
630 ReturnInst::ReturnInst(LLVMContext &C, Value *retVal, Instruction *InsertBefore)
631 : TerminatorInst(Type::getVoidTy(C), Instruction::Ret,
632 OperandTraits<ReturnInst>::op_end(this) - !!retVal, !!retVal,
637 ReturnInst::ReturnInst(LLVMContext &C, Value *retVal, BasicBlock *InsertAtEnd)
638 : TerminatorInst(Type::getVoidTy(C), Instruction::Ret,
639 OperandTraits<ReturnInst>::op_end(this) - !!retVal, !!retVal,
644 ReturnInst::ReturnInst(LLVMContext &Context, BasicBlock *InsertAtEnd)
645 : TerminatorInst(Type::getVoidTy(Context), Instruction::Ret,
646 OperandTraits<ReturnInst>::op_end(this), 0, InsertAtEnd) {
649 unsigned ReturnInst::getNumSuccessorsV() const {
650 return getNumSuccessors();
653 /// Out-of-line ReturnInst method, put here so the C++ compiler can choose to
654 /// emit the vtable for the class in this translation unit.
655 void ReturnInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
656 llvm_unreachable("ReturnInst has no successors!");
659 BasicBlock *ReturnInst::getSuccessorV(unsigned idx) const {
660 llvm_unreachable("ReturnInst has no successors!");
663 ReturnInst::~ReturnInst() {
666 //===----------------------------------------------------------------------===//
667 // ResumeInst Implementation
668 //===----------------------------------------------------------------------===//
670 ResumeInst::ResumeInst(const ResumeInst &RI)
671 : TerminatorInst(Type::getVoidTy(RI.getContext()), Instruction::Resume,
672 OperandTraits<ResumeInst>::op_begin(this), 1) {
673 Op<0>() = RI.Op<0>();
676 ResumeInst::ResumeInst(Value *Exn, Instruction *InsertBefore)
677 : TerminatorInst(Type::getVoidTy(Exn->getContext()), Instruction::Resume,
678 OperandTraits<ResumeInst>::op_begin(this), 1, InsertBefore) {
682 ResumeInst::ResumeInst(Value *Exn, BasicBlock *InsertAtEnd)
683 : TerminatorInst(Type::getVoidTy(Exn->getContext()), Instruction::Resume,
684 OperandTraits<ResumeInst>::op_begin(this), 1, InsertAtEnd) {
688 unsigned ResumeInst::getNumSuccessorsV() const {
689 return getNumSuccessors();
692 void ResumeInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
693 llvm_unreachable("ResumeInst has no successors!");
696 BasicBlock *ResumeInst::getSuccessorV(unsigned idx) const {
697 llvm_unreachable("ResumeInst has no successors!");
700 //===----------------------------------------------------------------------===//
701 // UnreachableInst Implementation
702 //===----------------------------------------------------------------------===//
704 UnreachableInst::UnreachableInst(LLVMContext &Context,
705 Instruction *InsertBefore)
706 : TerminatorInst(Type::getVoidTy(Context), Instruction::Unreachable,
707 0, 0, InsertBefore) {
709 UnreachableInst::UnreachableInst(LLVMContext &Context, BasicBlock *InsertAtEnd)
710 : TerminatorInst(Type::getVoidTy(Context), Instruction::Unreachable,
714 unsigned UnreachableInst::getNumSuccessorsV() const {
715 return getNumSuccessors();
718 void UnreachableInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
719 llvm_unreachable("UnreachableInst has no successors!");
722 BasicBlock *UnreachableInst::getSuccessorV(unsigned idx) const {
723 llvm_unreachable("UnreachableInst has no successors!");
726 //===----------------------------------------------------------------------===//
727 // BranchInst Implementation
728 //===----------------------------------------------------------------------===//
730 void BranchInst::AssertOK() {
732 assert(getCondition()->getType()->isIntegerTy(1) &&
733 "May only branch on boolean predicates!");
736 BranchInst::BranchInst(BasicBlock *IfTrue, Instruction *InsertBefore)
737 : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
738 OperandTraits<BranchInst>::op_end(this) - 1,
740 assert(IfTrue != 0 && "Branch destination may not be null!");
743 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
744 Instruction *InsertBefore)
745 : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
746 OperandTraits<BranchInst>::op_end(this) - 3,
756 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *InsertAtEnd)
757 : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
758 OperandTraits<BranchInst>::op_end(this) - 1,
760 assert(IfTrue != 0 && "Branch destination may not be null!");
764 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
765 BasicBlock *InsertAtEnd)
766 : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
767 OperandTraits<BranchInst>::op_end(this) - 3,
778 BranchInst::BranchInst(const BranchInst &BI) :
779 TerminatorInst(Type::getVoidTy(BI.getContext()), Instruction::Br,
780 OperandTraits<BranchInst>::op_end(this) - BI.getNumOperands(),
781 BI.getNumOperands()) {
782 Op<-1>() = BI.Op<-1>();
783 if (BI.getNumOperands() != 1) {
784 assert(BI.getNumOperands() == 3 && "BR can have 1 or 3 operands!");
785 Op<-3>() = BI.Op<-3>();
786 Op<-2>() = BI.Op<-2>();
788 SubclassOptionalData = BI.SubclassOptionalData;
791 void BranchInst::swapSuccessors() {
792 assert(isConditional() &&
793 "Cannot swap successors of an unconditional branch");
794 Op<-1>().swap(Op<-2>());
796 // Update profile metadata if present and it matches our structural
798 MDNode *ProfileData = getMetadata(LLVMContext::MD_prof);
799 if (!ProfileData || ProfileData->getNumOperands() != 3)
802 // The first operand is the name. Fetch them backwards and build a new one.
804 ProfileData->getOperand(0),
805 ProfileData->getOperand(2),
806 ProfileData->getOperand(1)
808 setMetadata(LLVMContext::MD_prof,
809 MDNode::get(ProfileData->getContext(), Ops));
812 BasicBlock *BranchInst::getSuccessorV(unsigned idx) const {
813 return getSuccessor(idx);
815 unsigned BranchInst::getNumSuccessorsV() const {
816 return getNumSuccessors();
818 void BranchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
819 setSuccessor(idx, B);
823 //===----------------------------------------------------------------------===//
824 // AllocaInst Implementation
825 //===----------------------------------------------------------------------===//
827 static Value *getAISize(LLVMContext &Context, Value *Amt) {
829 Amt = ConstantInt::get(Type::getInt32Ty(Context), 1);
831 assert(!isa<BasicBlock>(Amt) &&
832 "Passed basic block into allocation size parameter! Use other ctor");
833 assert(Amt->getType()->isIntegerTy() &&
834 "Allocation array size is not an integer!");
839 AllocaInst::AllocaInst(Type *Ty, Value *ArraySize,
840 const Twine &Name, Instruction *InsertBefore)
841 : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
842 getAISize(Ty->getContext(), ArraySize), InsertBefore) {
844 assert(!Ty->isVoidTy() && "Cannot allocate void!");
848 AllocaInst::AllocaInst(Type *Ty, Value *ArraySize,
849 const Twine &Name, BasicBlock *InsertAtEnd)
850 : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
851 getAISize(Ty->getContext(), ArraySize), InsertAtEnd) {
853 assert(!Ty->isVoidTy() && "Cannot allocate void!");
857 AllocaInst::AllocaInst(Type *Ty, const Twine &Name,
858 Instruction *InsertBefore)
859 : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
860 getAISize(Ty->getContext(), 0), InsertBefore) {
862 assert(!Ty->isVoidTy() && "Cannot allocate void!");
866 AllocaInst::AllocaInst(Type *Ty, const Twine &Name,
867 BasicBlock *InsertAtEnd)
868 : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
869 getAISize(Ty->getContext(), 0), InsertAtEnd) {
871 assert(!Ty->isVoidTy() && "Cannot allocate void!");
875 AllocaInst::AllocaInst(Type *Ty, Value *ArraySize, unsigned Align,
876 const Twine &Name, Instruction *InsertBefore)
877 : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
878 getAISize(Ty->getContext(), ArraySize), InsertBefore) {
880 assert(!Ty->isVoidTy() && "Cannot allocate void!");
884 AllocaInst::AllocaInst(Type *Ty, Value *ArraySize, unsigned Align,
885 const Twine &Name, BasicBlock *InsertAtEnd)
886 : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
887 getAISize(Ty->getContext(), ArraySize), InsertAtEnd) {
889 assert(!Ty->isVoidTy() && "Cannot allocate void!");
893 // Out of line virtual method, so the vtable, etc has a home.
894 AllocaInst::~AllocaInst() {
897 void AllocaInst::setAlignment(unsigned Align) {
898 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
899 assert(Align <= MaximumAlignment &&
900 "Alignment is greater than MaximumAlignment!");
901 setInstructionSubclassData(Log2_32(Align) + 1);
902 assert(getAlignment() == Align && "Alignment representation error!");
905 bool AllocaInst::isArrayAllocation() const {
906 if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(0)))
911 Type *AllocaInst::getAllocatedType() const {
912 return getType()->getElementType();
915 /// isStaticAlloca - Return true if this alloca is in the entry block of the
916 /// function and is a constant size. If so, the code generator will fold it
917 /// into the prolog/epilog code, so it is basically free.
918 bool AllocaInst::isStaticAlloca() const {
919 // Must be constant size.
920 if (!isa<ConstantInt>(getArraySize())) return false;
922 // Must be in the entry block.
923 const BasicBlock *Parent = getParent();
924 return Parent == &Parent->getParent()->front();
927 //===----------------------------------------------------------------------===//
928 // LoadInst Implementation
929 //===----------------------------------------------------------------------===//
931 void LoadInst::AssertOK() {
932 assert(getOperand(0)->getType()->isPointerTy() &&
933 "Ptr must have pointer type.");
934 assert(!(isAtomic() && getAlignment() == 0) &&
935 "Alignment required for atomic load");
938 LoadInst::LoadInst(Value *Ptr, const Twine &Name, Instruction *InsertBef)
939 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
940 Load, Ptr, InsertBef) {
943 setAtomic(NotAtomic);
948 LoadInst::LoadInst(Value *Ptr, const Twine &Name, BasicBlock *InsertAE)
949 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
950 Load, Ptr, InsertAE) {
953 setAtomic(NotAtomic);
958 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
959 Instruction *InsertBef)
960 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
961 Load, Ptr, InsertBef) {
962 setVolatile(isVolatile);
964 setAtomic(NotAtomic);
969 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
970 BasicBlock *InsertAE)
971 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
972 Load, Ptr, InsertAE) {
973 setVolatile(isVolatile);
975 setAtomic(NotAtomic);
980 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
981 unsigned Align, Instruction *InsertBef)
982 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
983 Load, Ptr, InsertBef) {
984 setVolatile(isVolatile);
986 setAtomic(NotAtomic);
991 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
992 unsigned Align, BasicBlock *InsertAE)
993 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
994 Load, Ptr, InsertAE) {
995 setVolatile(isVolatile);
997 setAtomic(NotAtomic);
1002 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
1003 unsigned Align, AtomicOrdering Order,
1004 SynchronizationScope SynchScope,
1005 Instruction *InsertBef)
1006 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1007 Load, Ptr, InsertBef) {
1008 setVolatile(isVolatile);
1009 setAlignment(Align);
1010 setAtomic(Order, SynchScope);
1015 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
1016 unsigned Align, AtomicOrdering Order,
1017 SynchronizationScope SynchScope,
1018 BasicBlock *InsertAE)
1019 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1020 Load, Ptr, InsertAE) {
1021 setVolatile(isVolatile);
1022 setAlignment(Align);
1023 setAtomic(Order, SynchScope);
1028 LoadInst::LoadInst(Value *Ptr, const char *Name, Instruction *InsertBef)
1029 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1030 Load, Ptr, InsertBef) {
1033 setAtomic(NotAtomic);
1035 if (Name && Name[0]) setName(Name);
1038 LoadInst::LoadInst(Value *Ptr, const char *Name, BasicBlock *InsertAE)
1039 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1040 Load, Ptr, InsertAE) {
1043 setAtomic(NotAtomic);
1045 if (Name && Name[0]) setName(Name);
1048 LoadInst::LoadInst(Value *Ptr, const char *Name, bool isVolatile,
1049 Instruction *InsertBef)
1050 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1051 Load, Ptr, InsertBef) {
1052 setVolatile(isVolatile);
1054 setAtomic(NotAtomic);
1056 if (Name && Name[0]) setName(Name);
1059 LoadInst::LoadInst(Value *Ptr, const char *Name, bool isVolatile,
1060 BasicBlock *InsertAE)
1061 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1062 Load, Ptr, InsertAE) {
1063 setVolatile(isVolatile);
1065 setAtomic(NotAtomic);
1067 if (Name && Name[0]) setName(Name);
1070 void LoadInst::setAlignment(unsigned Align) {
1071 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
1072 assert(Align <= MaximumAlignment &&
1073 "Alignment is greater than MaximumAlignment!");
1074 setInstructionSubclassData((getSubclassDataFromInstruction() & ~(31 << 1)) |
1075 ((Log2_32(Align)+1)<<1));
1076 assert(getAlignment() == Align && "Alignment representation error!");
1079 //===----------------------------------------------------------------------===//
1080 // StoreInst Implementation
1081 //===----------------------------------------------------------------------===//
1083 void StoreInst::AssertOK() {
1084 assert(getOperand(0) && getOperand(1) && "Both operands must be non-null!");
1085 assert(getOperand(1)->getType()->isPointerTy() &&
1086 "Ptr must have pointer type!");
1087 assert(getOperand(0)->getType() ==
1088 cast<PointerType>(getOperand(1)->getType())->getElementType()
1089 && "Ptr must be a pointer to Val type!");
1090 assert(!(isAtomic() && getAlignment() == 0) &&
1091 "Alignment required for atomic load");
1095 StoreInst::StoreInst(Value *val, Value *addr, Instruction *InsertBefore)
1096 : Instruction(Type::getVoidTy(val->getContext()), Store,
1097 OperandTraits<StoreInst>::op_begin(this),
1098 OperandTraits<StoreInst>::operands(this),
1104 setAtomic(NotAtomic);
1108 StoreInst::StoreInst(Value *val, Value *addr, BasicBlock *InsertAtEnd)
1109 : Instruction(Type::getVoidTy(val->getContext()), Store,
1110 OperandTraits<StoreInst>::op_begin(this),
1111 OperandTraits<StoreInst>::operands(this),
1117 setAtomic(NotAtomic);
1121 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1122 Instruction *InsertBefore)
1123 : Instruction(Type::getVoidTy(val->getContext()), Store,
1124 OperandTraits<StoreInst>::op_begin(this),
1125 OperandTraits<StoreInst>::operands(this),
1129 setVolatile(isVolatile);
1131 setAtomic(NotAtomic);
1135 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1136 unsigned Align, Instruction *InsertBefore)
1137 : Instruction(Type::getVoidTy(val->getContext()), Store,
1138 OperandTraits<StoreInst>::op_begin(this),
1139 OperandTraits<StoreInst>::operands(this),
1143 setVolatile(isVolatile);
1144 setAlignment(Align);
1145 setAtomic(NotAtomic);
1149 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1150 unsigned Align, AtomicOrdering Order,
1151 SynchronizationScope SynchScope,
1152 Instruction *InsertBefore)
1153 : Instruction(Type::getVoidTy(val->getContext()), Store,
1154 OperandTraits<StoreInst>::op_begin(this),
1155 OperandTraits<StoreInst>::operands(this),
1159 setVolatile(isVolatile);
1160 setAlignment(Align);
1161 setAtomic(Order, SynchScope);
1165 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1166 BasicBlock *InsertAtEnd)
1167 : Instruction(Type::getVoidTy(val->getContext()), Store,
1168 OperandTraits<StoreInst>::op_begin(this),
1169 OperandTraits<StoreInst>::operands(this),
1173 setVolatile(isVolatile);
1175 setAtomic(NotAtomic);
1179 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1180 unsigned Align, BasicBlock *InsertAtEnd)
1181 : Instruction(Type::getVoidTy(val->getContext()), Store,
1182 OperandTraits<StoreInst>::op_begin(this),
1183 OperandTraits<StoreInst>::operands(this),
1187 setVolatile(isVolatile);
1188 setAlignment(Align);
1189 setAtomic(NotAtomic);
1193 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1194 unsigned Align, AtomicOrdering Order,
1195 SynchronizationScope SynchScope,
1196 BasicBlock *InsertAtEnd)
1197 : Instruction(Type::getVoidTy(val->getContext()), Store,
1198 OperandTraits<StoreInst>::op_begin(this),
1199 OperandTraits<StoreInst>::operands(this),
1203 setVolatile(isVolatile);
1204 setAlignment(Align);
1205 setAtomic(Order, SynchScope);
1209 void StoreInst::setAlignment(unsigned Align) {
1210 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
1211 assert(Align <= MaximumAlignment &&
1212 "Alignment is greater than MaximumAlignment!");
1213 setInstructionSubclassData((getSubclassDataFromInstruction() & ~(31 << 1)) |
1214 ((Log2_32(Align)+1) << 1));
1215 assert(getAlignment() == Align && "Alignment representation error!");
1218 //===----------------------------------------------------------------------===//
1219 // AtomicCmpXchgInst Implementation
1220 //===----------------------------------------------------------------------===//
1222 void AtomicCmpXchgInst::Init(Value *Ptr, Value *Cmp, Value *NewVal,
1223 AtomicOrdering Ordering,
1224 SynchronizationScope SynchScope) {
1228 setOrdering(Ordering);
1229 setSynchScope(SynchScope);
1231 assert(getOperand(0) && getOperand(1) && getOperand(2) &&
1232 "All operands must be non-null!");
1233 assert(getOperand(0)->getType()->isPointerTy() &&
1234 "Ptr must have pointer type!");
1235 assert(getOperand(1)->getType() ==
1236 cast<PointerType>(getOperand(0)->getType())->getElementType()
1237 && "Ptr must be a pointer to Cmp type!");
1238 assert(getOperand(2)->getType() ==
1239 cast<PointerType>(getOperand(0)->getType())->getElementType()
1240 && "Ptr must be a pointer to NewVal type!");
1241 assert(Ordering != NotAtomic &&
1242 "AtomicCmpXchg instructions must be atomic!");
1245 AtomicCmpXchgInst::AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal,
1246 AtomicOrdering Ordering,
1247 SynchronizationScope SynchScope,
1248 Instruction *InsertBefore)
1249 : Instruction(Cmp->getType(), AtomicCmpXchg,
1250 OperandTraits<AtomicCmpXchgInst>::op_begin(this),
1251 OperandTraits<AtomicCmpXchgInst>::operands(this),
1253 Init(Ptr, Cmp, NewVal, Ordering, SynchScope);
1256 AtomicCmpXchgInst::AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal,
1257 AtomicOrdering Ordering,
1258 SynchronizationScope SynchScope,
1259 BasicBlock *InsertAtEnd)
1260 : Instruction(Cmp->getType(), AtomicCmpXchg,
1261 OperandTraits<AtomicCmpXchgInst>::op_begin(this),
1262 OperandTraits<AtomicCmpXchgInst>::operands(this),
1264 Init(Ptr, Cmp, NewVal, Ordering, SynchScope);
1267 //===----------------------------------------------------------------------===//
1268 // AtomicRMWInst Implementation
1269 //===----------------------------------------------------------------------===//
1271 void AtomicRMWInst::Init(BinOp Operation, Value *Ptr, Value *Val,
1272 AtomicOrdering Ordering,
1273 SynchronizationScope SynchScope) {
1276 setOperation(Operation);
1277 setOrdering(Ordering);
1278 setSynchScope(SynchScope);
1280 assert(getOperand(0) && getOperand(1) &&
1281 "All operands must be non-null!");
1282 assert(getOperand(0)->getType()->isPointerTy() &&
1283 "Ptr must have pointer type!");
1284 assert(getOperand(1)->getType() ==
1285 cast<PointerType>(getOperand(0)->getType())->getElementType()
1286 && "Ptr must be a pointer to Val type!");
1287 assert(Ordering != NotAtomic &&
1288 "AtomicRMW instructions must be atomic!");
1291 AtomicRMWInst::AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val,
1292 AtomicOrdering Ordering,
1293 SynchronizationScope SynchScope,
1294 Instruction *InsertBefore)
1295 : Instruction(Val->getType(), AtomicRMW,
1296 OperandTraits<AtomicRMWInst>::op_begin(this),
1297 OperandTraits<AtomicRMWInst>::operands(this),
1299 Init(Operation, Ptr, Val, Ordering, SynchScope);
1302 AtomicRMWInst::AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val,
1303 AtomicOrdering Ordering,
1304 SynchronizationScope SynchScope,
1305 BasicBlock *InsertAtEnd)
1306 : Instruction(Val->getType(), AtomicRMW,
1307 OperandTraits<AtomicRMWInst>::op_begin(this),
1308 OperandTraits<AtomicRMWInst>::operands(this),
1310 Init(Operation, Ptr, Val, Ordering, SynchScope);
1313 //===----------------------------------------------------------------------===//
1314 // FenceInst Implementation
1315 //===----------------------------------------------------------------------===//
1317 FenceInst::FenceInst(LLVMContext &C, AtomicOrdering Ordering,
1318 SynchronizationScope SynchScope,
1319 Instruction *InsertBefore)
1320 : Instruction(Type::getVoidTy(C), Fence, 0, 0, InsertBefore) {
1321 setOrdering(Ordering);
1322 setSynchScope(SynchScope);
1325 FenceInst::FenceInst(LLVMContext &C, AtomicOrdering Ordering,
1326 SynchronizationScope SynchScope,
1327 BasicBlock *InsertAtEnd)
1328 : Instruction(Type::getVoidTy(C), Fence, 0, 0, InsertAtEnd) {
1329 setOrdering(Ordering);
1330 setSynchScope(SynchScope);
1333 //===----------------------------------------------------------------------===//
1334 // GetElementPtrInst Implementation
1335 //===----------------------------------------------------------------------===//
1337 void GetElementPtrInst::init(Value *Ptr, ArrayRef<Value *> IdxList,
1338 const Twine &Name) {
1339 assert(NumOperands == 1 + IdxList.size() && "NumOperands not initialized?");
1340 OperandList[0] = Ptr;
1341 std::copy(IdxList.begin(), IdxList.end(), op_begin() + 1);
1345 GetElementPtrInst::GetElementPtrInst(const GetElementPtrInst &GEPI)
1346 : Instruction(GEPI.getType(), GetElementPtr,
1347 OperandTraits<GetElementPtrInst>::op_end(this)
1348 - GEPI.getNumOperands(),
1349 GEPI.getNumOperands()) {
1350 std::copy(GEPI.op_begin(), GEPI.op_end(), op_begin());
1351 SubclassOptionalData = GEPI.SubclassOptionalData;
1354 /// getIndexedType - Returns the type of the element that would be accessed with
1355 /// a gep instruction with the specified parameters.
1357 /// The Idxs pointer should point to a continuous piece of memory containing the
1358 /// indices, either as Value* or uint64_t.
1360 /// A null type is returned if the indices are invalid for the specified
1363 template <typename IndexTy>
1364 static Type *getIndexedTypeInternal(Type *Ptr, ArrayRef<IndexTy> IdxList) {
1365 PointerType *PTy = dyn_cast<PointerType>(Ptr->getScalarType());
1366 if (!PTy) return 0; // Type isn't a pointer type!
1367 Type *Agg = PTy->getElementType();
1369 // Handle the special case of the empty set index set, which is always valid.
1370 if (IdxList.empty())
1373 // If there is at least one index, the top level type must be sized, otherwise
1374 // it cannot be 'stepped over'.
1375 if (!Agg->isSized())
1378 unsigned CurIdx = 1;
1379 for (; CurIdx != IdxList.size(); ++CurIdx) {
1380 CompositeType *CT = dyn_cast<CompositeType>(Agg);
1381 if (!CT || CT->isPointerTy()) return 0;
1382 IndexTy Index = IdxList[CurIdx];
1383 if (!CT->indexValid(Index)) return 0;
1384 Agg = CT->getTypeAtIndex(Index);
1386 return CurIdx == IdxList.size() ? Agg : 0;
1389 Type *GetElementPtrInst::getIndexedType(Type *Ptr, ArrayRef<Value *> IdxList) {
1390 return getIndexedTypeInternal(Ptr, IdxList);
1393 Type *GetElementPtrInst::getIndexedType(Type *Ptr,
1394 ArrayRef<Constant *> IdxList) {
1395 return getIndexedTypeInternal(Ptr, IdxList);
1398 Type *GetElementPtrInst::getIndexedType(Type *Ptr, ArrayRef<uint64_t> IdxList) {
1399 return getIndexedTypeInternal(Ptr, IdxList);
1402 /// hasAllZeroIndices - Return true if all of the indices of this GEP are
1403 /// zeros. If so, the result pointer and the first operand have the same
1404 /// value, just potentially different types.
1405 bool GetElementPtrInst::hasAllZeroIndices() const {
1406 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1407 if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(i))) {
1408 if (!CI->isZero()) return false;
1416 /// hasAllConstantIndices - Return true if all of the indices of this GEP are
1417 /// constant integers. If so, the result pointer and the first operand have
1418 /// a constant offset between them.
1419 bool GetElementPtrInst::hasAllConstantIndices() const {
1420 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1421 if (!isa<ConstantInt>(getOperand(i)))
1427 void GetElementPtrInst::setIsInBounds(bool B) {
1428 cast<GEPOperator>(this)->setIsInBounds(B);
1431 bool GetElementPtrInst::isInBounds() const {
1432 return cast<GEPOperator>(this)->isInBounds();
1435 bool GetElementPtrInst::accumulateConstantOffset(const DataLayout &DL,
1436 APInt &Offset) const {
1437 // Delegate to the generic GEPOperator implementation.
1438 return cast<GEPOperator>(this)->accumulateConstantOffset(DL, Offset);
1441 //===----------------------------------------------------------------------===//
1442 // ExtractElementInst Implementation
1443 //===----------------------------------------------------------------------===//
1445 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
1447 Instruction *InsertBef)
1448 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1450 OperandTraits<ExtractElementInst>::op_begin(this),
1452 assert(isValidOperands(Val, Index) &&
1453 "Invalid extractelement instruction operands!");
1459 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
1461 BasicBlock *InsertAE)
1462 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1464 OperandTraits<ExtractElementInst>::op_begin(this),
1466 assert(isValidOperands(Val, Index) &&
1467 "Invalid extractelement instruction operands!");
1475 bool ExtractElementInst::isValidOperands(const Value *Val, const Value *Index) {
1476 if (!Val->getType()->isVectorTy() || !Index->getType()->isIntegerTy(32))
1482 //===----------------------------------------------------------------------===//
1483 // InsertElementInst Implementation
1484 //===----------------------------------------------------------------------===//
1486 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
1488 Instruction *InsertBef)
1489 : Instruction(Vec->getType(), InsertElement,
1490 OperandTraits<InsertElementInst>::op_begin(this),
1492 assert(isValidOperands(Vec, Elt, Index) &&
1493 "Invalid insertelement instruction operands!");
1500 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
1502 BasicBlock *InsertAE)
1503 : Instruction(Vec->getType(), InsertElement,
1504 OperandTraits<InsertElementInst>::op_begin(this),
1506 assert(isValidOperands(Vec, Elt, Index) &&
1507 "Invalid insertelement instruction operands!");
1515 bool InsertElementInst::isValidOperands(const Value *Vec, const Value *Elt,
1516 const Value *Index) {
1517 if (!Vec->getType()->isVectorTy())
1518 return false; // First operand of insertelement must be vector type.
1520 if (Elt->getType() != cast<VectorType>(Vec->getType())->getElementType())
1521 return false;// Second operand of insertelement must be vector element type.
1523 if (!Index->getType()->isIntegerTy(32))
1524 return false; // Third operand of insertelement must be i32.
1529 //===----------------------------------------------------------------------===//
1530 // ShuffleVectorInst Implementation
1531 //===----------------------------------------------------------------------===//
1533 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1535 Instruction *InsertBefore)
1536 : Instruction(VectorType::get(cast<VectorType>(V1->getType())->getElementType(),
1537 cast<VectorType>(Mask->getType())->getNumElements()),
1539 OperandTraits<ShuffleVectorInst>::op_begin(this),
1540 OperandTraits<ShuffleVectorInst>::operands(this),
1542 assert(isValidOperands(V1, V2, Mask) &&
1543 "Invalid shuffle vector instruction operands!");
1550 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1552 BasicBlock *InsertAtEnd)
1553 : Instruction(VectorType::get(cast<VectorType>(V1->getType())->getElementType(),
1554 cast<VectorType>(Mask->getType())->getNumElements()),
1556 OperandTraits<ShuffleVectorInst>::op_begin(this),
1557 OperandTraits<ShuffleVectorInst>::operands(this),
1559 assert(isValidOperands(V1, V2, Mask) &&
1560 "Invalid shuffle vector instruction operands!");
1568 bool ShuffleVectorInst::isValidOperands(const Value *V1, const Value *V2,
1569 const Value *Mask) {
1570 // V1 and V2 must be vectors of the same type.
1571 if (!V1->getType()->isVectorTy() || V1->getType() != V2->getType())
1574 // Mask must be vector of i32.
1575 VectorType *MaskTy = dyn_cast<VectorType>(Mask->getType());
1576 if (MaskTy == 0 || !MaskTy->getElementType()->isIntegerTy(32))
1579 // Check to see if Mask is valid.
1580 if (isa<UndefValue>(Mask) || isa<ConstantAggregateZero>(Mask))
1583 if (const ConstantVector *MV = dyn_cast<ConstantVector>(Mask)) {
1584 unsigned V1Size = cast<VectorType>(V1->getType())->getNumElements();
1585 for (unsigned i = 0, e = MV->getNumOperands(); i != e; ++i) {
1586 if (ConstantInt *CI = dyn_cast<ConstantInt>(MV->getOperand(i))) {
1587 if (CI->uge(V1Size*2))
1589 } else if (!isa<UndefValue>(MV->getOperand(i))) {
1596 if (const ConstantDataSequential *CDS =
1597 dyn_cast<ConstantDataSequential>(Mask)) {
1598 unsigned V1Size = cast<VectorType>(V1->getType())->getNumElements();
1599 for (unsigned i = 0, e = MaskTy->getNumElements(); i != e; ++i)
1600 if (CDS->getElementAsInteger(i) >= V1Size*2)
1605 // The bitcode reader can create a place holder for a forward reference
1606 // used as the shuffle mask. When this occurs, the shuffle mask will
1607 // fall into this case and fail. To avoid this error, do this bit of
1608 // ugliness to allow such a mask pass.
1609 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(Mask))
1610 if (CE->getOpcode() == Instruction::UserOp1)
1616 /// getMaskValue - Return the index from the shuffle mask for the specified
1617 /// output result. This is either -1 if the element is undef or a number less
1618 /// than 2*numelements.
1619 int ShuffleVectorInst::getMaskValue(Constant *Mask, unsigned i) {
1620 assert(i < Mask->getType()->getVectorNumElements() && "Index out of range");
1621 if (ConstantDataSequential *CDS =dyn_cast<ConstantDataSequential>(Mask))
1622 return CDS->getElementAsInteger(i);
1623 Constant *C = Mask->getAggregateElement(i);
1624 if (isa<UndefValue>(C))
1626 return cast<ConstantInt>(C)->getZExtValue();
1629 /// getShuffleMask - Return the full mask for this instruction, where each
1630 /// element is the element number and undef's are returned as -1.
1631 void ShuffleVectorInst::getShuffleMask(Constant *Mask,
1632 SmallVectorImpl<int> &Result) {
1633 unsigned NumElts = Mask->getType()->getVectorNumElements();
1635 if (ConstantDataSequential *CDS=dyn_cast<ConstantDataSequential>(Mask)) {
1636 for (unsigned i = 0; i != NumElts; ++i)
1637 Result.push_back(CDS->getElementAsInteger(i));
1640 for (unsigned i = 0; i != NumElts; ++i) {
1641 Constant *C = Mask->getAggregateElement(i);
1642 Result.push_back(isa<UndefValue>(C) ? -1 :
1643 cast<ConstantInt>(C)->getZExtValue());
1648 //===----------------------------------------------------------------------===//
1649 // InsertValueInst Class
1650 //===----------------------------------------------------------------------===//
1652 void InsertValueInst::init(Value *Agg, Value *Val, ArrayRef<unsigned> Idxs,
1653 const Twine &Name) {
1654 assert(NumOperands == 2 && "NumOperands not initialized?");
1656 // There's no fundamental reason why we require at least one index
1657 // (other than weirdness with &*IdxBegin being invalid; see
1658 // getelementptr's init routine for example). But there's no
1659 // present need to support it.
1660 assert(Idxs.size() > 0 && "InsertValueInst must have at least one index");
1662 assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs) ==
1663 Val->getType() && "Inserted value must match indexed type!");
1667 Indices.append(Idxs.begin(), Idxs.end());
1671 InsertValueInst::InsertValueInst(const InsertValueInst &IVI)
1672 : Instruction(IVI.getType(), InsertValue,
1673 OperandTraits<InsertValueInst>::op_begin(this), 2),
1674 Indices(IVI.Indices) {
1675 Op<0>() = IVI.getOperand(0);
1676 Op<1>() = IVI.getOperand(1);
1677 SubclassOptionalData = IVI.SubclassOptionalData;
1680 //===----------------------------------------------------------------------===//
1681 // ExtractValueInst Class
1682 //===----------------------------------------------------------------------===//
1684 void ExtractValueInst::init(ArrayRef<unsigned> Idxs, const Twine &Name) {
1685 assert(NumOperands == 1 && "NumOperands not initialized?");
1687 // There's no fundamental reason why we require at least one index.
1688 // But there's no present need to support it.
1689 assert(Idxs.size() > 0 && "ExtractValueInst must have at least one index");
1691 Indices.append(Idxs.begin(), Idxs.end());
1695 ExtractValueInst::ExtractValueInst(const ExtractValueInst &EVI)
1696 : UnaryInstruction(EVI.getType(), ExtractValue, EVI.getOperand(0)),
1697 Indices(EVI.Indices) {
1698 SubclassOptionalData = EVI.SubclassOptionalData;
1701 // getIndexedType - Returns the type of the element that would be extracted
1702 // with an extractvalue instruction with the specified parameters.
1704 // A null type is returned if the indices are invalid for the specified
1707 Type *ExtractValueInst::getIndexedType(Type *Agg,
1708 ArrayRef<unsigned> Idxs) {
1709 for (unsigned CurIdx = 0; CurIdx != Idxs.size(); ++CurIdx) {
1710 unsigned Index = Idxs[CurIdx];
1711 // We can't use CompositeType::indexValid(Index) here.
1712 // indexValid() always returns true for arrays because getelementptr allows
1713 // out-of-bounds indices. Since we don't allow those for extractvalue and
1714 // insertvalue we need to check array indexing manually.
1715 // Since the only other types we can index into are struct types it's just
1716 // as easy to check those manually as well.
1717 if (ArrayType *AT = dyn_cast<ArrayType>(Agg)) {
1718 if (Index >= AT->getNumElements())
1720 } else if (StructType *ST = dyn_cast<StructType>(Agg)) {
1721 if (Index >= ST->getNumElements())
1724 // Not a valid type to index into.
1728 Agg = cast<CompositeType>(Agg)->getTypeAtIndex(Index);
1730 return const_cast<Type*>(Agg);
1733 //===----------------------------------------------------------------------===//
1734 // BinaryOperator Class
1735 //===----------------------------------------------------------------------===//
1737 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
1738 Type *Ty, const Twine &Name,
1739 Instruction *InsertBefore)
1740 : Instruction(Ty, iType,
1741 OperandTraits<BinaryOperator>::op_begin(this),
1742 OperandTraits<BinaryOperator>::operands(this),
1750 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
1751 Type *Ty, const Twine &Name,
1752 BasicBlock *InsertAtEnd)
1753 : Instruction(Ty, iType,
1754 OperandTraits<BinaryOperator>::op_begin(this),
1755 OperandTraits<BinaryOperator>::operands(this),
1764 void BinaryOperator::init(BinaryOps iType) {
1765 Value *LHS = getOperand(0), *RHS = getOperand(1);
1766 (void)LHS; (void)RHS; // Silence warnings.
1767 assert(LHS->getType() == RHS->getType() &&
1768 "Binary operator operand types must match!");
1773 assert(getType() == LHS->getType() &&
1774 "Arithmetic operation should return same type as operands!");
1775 assert(getType()->isIntOrIntVectorTy() &&
1776 "Tried to create an integer operation on a non-integer type!");
1778 case FAdd: case FSub:
1780 assert(getType() == LHS->getType() &&
1781 "Arithmetic operation should return same type as operands!");
1782 assert(getType()->isFPOrFPVectorTy() &&
1783 "Tried to create a floating-point operation on a "
1784 "non-floating-point type!");
1788 assert(getType() == LHS->getType() &&
1789 "Arithmetic operation should return same type as operands!");
1790 assert((getType()->isIntegerTy() || (getType()->isVectorTy() &&
1791 cast<VectorType>(getType())->getElementType()->isIntegerTy())) &&
1792 "Incorrect operand type (not integer) for S/UDIV");
1795 assert(getType() == LHS->getType() &&
1796 "Arithmetic operation should return same type as operands!");
1797 assert(getType()->isFPOrFPVectorTy() &&
1798 "Incorrect operand type (not floating point) for FDIV");
1802 assert(getType() == LHS->getType() &&
1803 "Arithmetic operation should return same type as operands!");
1804 assert((getType()->isIntegerTy() || (getType()->isVectorTy() &&
1805 cast<VectorType>(getType())->getElementType()->isIntegerTy())) &&
1806 "Incorrect operand type (not integer) for S/UREM");
1809 assert(getType() == LHS->getType() &&
1810 "Arithmetic operation should return same type as operands!");
1811 assert(getType()->isFPOrFPVectorTy() &&
1812 "Incorrect operand type (not floating point) for FREM");
1817 assert(getType() == LHS->getType() &&
1818 "Shift operation should return same type as operands!");
1819 assert((getType()->isIntegerTy() ||
1820 (getType()->isVectorTy() &&
1821 cast<VectorType>(getType())->getElementType()->isIntegerTy())) &&
1822 "Tried to create a shift operation on a non-integral type!");
1826 assert(getType() == LHS->getType() &&
1827 "Logical operation should return same type as operands!");
1828 assert((getType()->isIntegerTy() ||
1829 (getType()->isVectorTy() &&
1830 cast<VectorType>(getType())->getElementType()->isIntegerTy())) &&
1831 "Tried to create a logical operation on a non-integral type!");
1839 BinaryOperator *BinaryOperator::Create(BinaryOps Op, Value *S1, Value *S2,
1841 Instruction *InsertBefore) {
1842 assert(S1->getType() == S2->getType() &&
1843 "Cannot create binary operator with two operands of differing type!");
1844 return new BinaryOperator(Op, S1, S2, S1->getType(), Name, InsertBefore);
1847 BinaryOperator *BinaryOperator::Create(BinaryOps Op, Value *S1, Value *S2,
1849 BasicBlock *InsertAtEnd) {
1850 BinaryOperator *Res = Create(Op, S1, S2, Name);
1851 InsertAtEnd->getInstList().push_back(Res);
1855 BinaryOperator *BinaryOperator::CreateNeg(Value *Op, const Twine &Name,
1856 Instruction *InsertBefore) {
1857 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1858 return new BinaryOperator(Instruction::Sub,
1860 Op->getType(), Name, InsertBefore);
1863 BinaryOperator *BinaryOperator::CreateNeg(Value *Op, const Twine &Name,
1864 BasicBlock *InsertAtEnd) {
1865 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1866 return new BinaryOperator(Instruction::Sub,
1868 Op->getType(), Name, InsertAtEnd);
1871 BinaryOperator *BinaryOperator::CreateNSWNeg(Value *Op, const Twine &Name,
1872 Instruction *InsertBefore) {
1873 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1874 return BinaryOperator::CreateNSWSub(zero, Op, Name, InsertBefore);
1877 BinaryOperator *BinaryOperator::CreateNSWNeg(Value *Op, const Twine &Name,
1878 BasicBlock *InsertAtEnd) {
1879 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1880 return BinaryOperator::CreateNSWSub(zero, Op, Name, InsertAtEnd);
1883 BinaryOperator *BinaryOperator::CreateNUWNeg(Value *Op, const Twine &Name,
1884 Instruction *InsertBefore) {
1885 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1886 return BinaryOperator::CreateNUWSub(zero, Op, Name, InsertBefore);
1889 BinaryOperator *BinaryOperator::CreateNUWNeg(Value *Op, const Twine &Name,
1890 BasicBlock *InsertAtEnd) {
1891 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1892 return BinaryOperator::CreateNUWSub(zero, Op, Name, InsertAtEnd);
1895 BinaryOperator *BinaryOperator::CreateFNeg(Value *Op, const Twine &Name,
1896 Instruction *InsertBefore) {
1897 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1898 return new BinaryOperator(Instruction::FSub, zero, Op,
1899 Op->getType(), Name, InsertBefore);
1902 BinaryOperator *BinaryOperator::CreateFNeg(Value *Op, const Twine &Name,
1903 BasicBlock *InsertAtEnd) {
1904 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1905 return new BinaryOperator(Instruction::FSub, zero, Op,
1906 Op->getType(), Name, InsertAtEnd);
1909 BinaryOperator *BinaryOperator::CreateNot(Value *Op, const Twine &Name,
1910 Instruction *InsertBefore) {
1911 Constant *C = Constant::getAllOnesValue(Op->getType());
1912 return new BinaryOperator(Instruction::Xor, Op, C,
1913 Op->getType(), Name, InsertBefore);
1916 BinaryOperator *BinaryOperator::CreateNot(Value *Op, const Twine &Name,
1917 BasicBlock *InsertAtEnd) {
1918 Constant *AllOnes = Constant::getAllOnesValue(Op->getType());
1919 return new BinaryOperator(Instruction::Xor, Op, AllOnes,
1920 Op->getType(), Name, InsertAtEnd);
1924 // isConstantAllOnes - Helper function for several functions below
1925 static inline bool isConstantAllOnes(const Value *V) {
1926 if (const Constant *C = dyn_cast<Constant>(V))
1927 return C->isAllOnesValue();
1931 bool BinaryOperator::isNeg(const Value *V) {
1932 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1933 if (Bop->getOpcode() == Instruction::Sub)
1934 if (Constant* C = dyn_cast<Constant>(Bop->getOperand(0)))
1935 return C->isNegativeZeroValue();
1939 bool BinaryOperator::isFNeg(const Value *V, bool IgnoreZeroSign) {
1940 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1941 if (Bop->getOpcode() == Instruction::FSub)
1942 if (Constant* C = dyn_cast<Constant>(Bop->getOperand(0))) {
1943 if (!IgnoreZeroSign)
1944 IgnoreZeroSign = cast<Instruction>(V)->hasNoSignedZeros();
1945 return !IgnoreZeroSign ? C->isNegativeZeroValue() : C->isZeroValue();
1950 bool BinaryOperator::isNot(const Value *V) {
1951 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1952 return (Bop->getOpcode() == Instruction::Xor &&
1953 (isConstantAllOnes(Bop->getOperand(1)) ||
1954 isConstantAllOnes(Bop->getOperand(0))));
1958 Value *BinaryOperator::getNegArgument(Value *BinOp) {
1959 return cast<BinaryOperator>(BinOp)->getOperand(1);
1962 const Value *BinaryOperator::getNegArgument(const Value *BinOp) {
1963 return getNegArgument(const_cast<Value*>(BinOp));
1966 Value *BinaryOperator::getFNegArgument(Value *BinOp) {
1967 return cast<BinaryOperator>(BinOp)->getOperand(1);
1970 const Value *BinaryOperator::getFNegArgument(const Value *BinOp) {
1971 return getFNegArgument(const_cast<Value*>(BinOp));
1974 Value *BinaryOperator::getNotArgument(Value *BinOp) {
1975 assert(isNot(BinOp) && "getNotArgument on non-'not' instruction!");
1976 BinaryOperator *BO = cast<BinaryOperator>(BinOp);
1977 Value *Op0 = BO->getOperand(0);
1978 Value *Op1 = BO->getOperand(1);
1979 if (isConstantAllOnes(Op0)) return Op1;
1981 assert(isConstantAllOnes(Op1));
1985 const Value *BinaryOperator::getNotArgument(const Value *BinOp) {
1986 return getNotArgument(const_cast<Value*>(BinOp));
1990 // swapOperands - Exchange the two operands to this instruction. This
1991 // instruction is safe to use on any binary instruction and does not
1992 // modify the semantics of the instruction. If the instruction is
1993 // order dependent (SetLT f.e.) the opcode is changed.
1995 bool BinaryOperator::swapOperands() {
1996 if (!isCommutative())
1997 return true; // Can't commute operands
1998 Op<0>().swap(Op<1>());
2002 void BinaryOperator::setHasNoUnsignedWrap(bool b) {
2003 cast<OverflowingBinaryOperator>(this)->setHasNoUnsignedWrap(b);
2006 void BinaryOperator::setHasNoSignedWrap(bool b) {
2007 cast<OverflowingBinaryOperator>(this)->setHasNoSignedWrap(b);
2010 void BinaryOperator::setIsExact(bool b) {
2011 cast<PossiblyExactOperator>(this)->setIsExact(b);
2014 bool BinaryOperator::hasNoUnsignedWrap() const {
2015 return cast<OverflowingBinaryOperator>(this)->hasNoUnsignedWrap();
2018 bool BinaryOperator::hasNoSignedWrap() const {
2019 return cast<OverflowingBinaryOperator>(this)->hasNoSignedWrap();
2022 bool BinaryOperator::isExact() const {
2023 return cast<PossiblyExactOperator>(this)->isExact();
2026 //===----------------------------------------------------------------------===//
2027 // FPMathOperator Class
2028 //===----------------------------------------------------------------------===//
2030 /// getFPAccuracy - Get the maximum error permitted by this operation in ULPs.
2031 /// An accuracy of 0.0 means that the operation should be performed with the
2032 /// default precision.
2033 float FPMathOperator::getFPAccuracy() const {
2035 cast<Instruction>(this)->getMetadata(LLVMContext::MD_fpmath);
2038 ConstantFP *Accuracy = cast<ConstantFP>(MD->getOperand(0));
2039 return Accuracy->getValueAPF().convertToFloat();
2043 //===----------------------------------------------------------------------===//
2045 //===----------------------------------------------------------------------===//
2047 void CastInst::anchor() {}
2049 // Just determine if this cast only deals with integral->integral conversion.
2050 bool CastInst::isIntegerCast() const {
2051 switch (getOpcode()) {
2052 default: return false;
2053 case Instruction::ZExt:
2054 case Instruction::SExt:
2055 case Instruction::Trunc:
2057 case Instruction::BitCast:
2058 return getOperand(0)->getType()->isIntegerTy() &&
2059 getType()->isIntegerTy();
2063 bool CastInst::isLosslessCast() const {
2064 // Only BitCast can be lossless, exit fast if we're not BitCast
2065 if (getOpcode() != Instruction::BitCast)
2068 // Identity cast is always lossless
2069 Type* SrcTy = getOperand(0)->getType();
2070 Type* DstTy = getType();
2074 // Pointer to pointer is always lossless.
2075 if (SrcTy->isPointerTy())
2076 return DstTy->isPointerTy();
2077 return false; // Other types have no identity values
2080 /// This function determines if the CastInst does not require any bits to be
2081 /// changed in order to effect the cast. Essentially, it identifies cases where
2082 /// no code gen is necessary for the cast, hence the name no-op cast. For
2083 /// example, the following are all no-op casts:
2084 /// # bitcast i32* %x to i8*
2085 /// # bitcast <2 x i32> %x to <4 x i16>
2086 /// # ptrtoint i32* %x to i32 ; on 32-bit plaforms only
2087 /// @brief Determine if the described cast is a no-op.
2088 bool CastInst::isNoopCast(Instruction::CastOps Opcode,
2093 default: llvm_unreachable("Invalid CastOp");
2094 case Instruction::Trunc:
2095 case Instruction::ZExt:
2096 case Instruction::SExt:
2097 case Instruction::FPTrunc:
2098 case Instruction::FPExt:
2099 case Instruction::UIToFP:
2100 case Instruction::SIToFP:
2101 case Instruction::FPToUI:
2102 case Instruction::FPToSI:
2103 return false; // These always modify bits
2104 case Instruction::BitCast:
2105 return true; // BitCast never modifies bits.
2106 case Instruction::PtrToInt:
2107 return IntPtrTy->getScalarSizeInBits() ==
2108 DestTy->getScalarSizeInBits();
2109 case Instruction::IntToPtr:
2110 return IntPtrTy->getScalarSizeInBits() ==
2111 SrcTy->getScalarSizeInBits();
2115 /// @brief Determine if a cast is a no-op.
2116 bool CastInst::isNoopCast(Type *IntPtrTy) const {
2117 return isNoopCast(getOpcode(), getOperand(0)->getType(), getType(), IntPtrTy);
2120 /// This function determines if a pair of casts can be eliminated and what
2121 /// opcode should be used in the elimination. This assumes that there are two
2122 /// instructions like this:
2123 /// * %F = firstOpcode SrcTy %x to MidTy
2124 /// * %S = secondOpcode MidTy %F to DstTy
2125 /// The function returns a resultOpcode so these two casts can be replaced with:
2126 /// * %Replacement = resultOpcode %SrcTy %x to DstTy
2127 /// If no such cast is permited, the function returns 0.
2128 unsigned CastInst::isEliminableCastPair(
2129 Instruction::CastOps firstOp, Instruction::CastOps secondOp,
2130 Type *SrcTy, Type *MidTy, Type *DstTy, Type *SrcIntPtrTy, Type *MidIntPtrTy,
2131 Type *DstIntPtrTy) {
2132 // Define the 144 possibilities for these two cast instructions. The values
2133 // in this matrix determine what to do in a given situation and select the
2134 // case in the switch below. The rows correspond to firstOp, the columns
2135 // correspond to secondOp. In looking at the table below, keep in mind
2136 // the following cast properties:
2138 // Size Compare Source Destination
2139 // Operator Src ? Size Type Sign Type Sign
2140 // -------- ------------ ------------------- ---------------------
2141 // TRUNC > Integer Any Integral Any
2142 // ZEXT < Integral Unsigned Integer Any
2143 // SEXT < Integral Signed Integer Any
2144 // FPTOUI n/a FloatPt n/a Integral Unsigned
2145 // FPTOSI n/a FloatPt n/a Integral Signed
2146 // UITOFP n/a Integral Unsigned FloatPt n/a
2147 // SITOFP n/a Integral Signed FloatPt n/a
2148 // FPTRUNC > FloatPt n/a FloatPt n/a
2149 // FPEXT < FloatPt n/a FloatPt n/a
2150 // PTRTOINT n/a Pointer n/a Integral Unsigned
2151 // INTTOPTR n/a Integral Unsigned Pointer n/a
2152 // BITCAST = FirstClass n/a FirstClass n/a
2154 // NOTE: some transforms are safe, but we consider them to be non-profitable.
2155 // For example, we could merge "fptoui double to i32" + "zext i32 to i64",
2156 // into "fptoui double to i64", but this loses information about the range
2157 // of the produced value (we no longer know the top-part is all zeros).
2158 // Further this conversion is often much more expensive for typical hardware,
2159 // and causes issues when building libgcc. We disallow fptosi+sext for the
2161 const unsigned numCastOps =
2162 Instruction::CastOpsEnd - Instruction::CastOpsBegin;
2163 static const uint8_t CastResults[numCastOps][numCastOps] = {
2164 // T F F U S F F P I B -+
2165 // R Z S P P I I T P 2 N T |
2166 // U E E 2 2 2 2 R E I T C +- secondOp
2167 // N X X U S F F N X N 2 V |
2168 // C T T I I P P C T T P T -+
2169 { 1, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // Trunc -+
2170 { 8, 1, 9,99,99, 2, 0,99,99,99, 2, 3 }, // ZExt |
2171 { 8, 0, 1,99,99, 0, 2,99,99,99, 0, 3 }, // SExt |
2172 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // FPToUI |
2173 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3 }, // FPToSI |
2174 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4 }, // UIToFP +- firstOp
2175 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4 }, // SIToFP |
2176 { 99,99,99, 0, 0,99,99, 1, 0,99,99, 4 }, // FPTrunc |
2177 { 99,99,99, 2, 2,99,99,10, 2,99,99, 4 }, // FPExt |
2178 { 1, 0, 0,99,99, 0, 0,99,99,99, 7, 3 }, // PtrToInt |
2179 { 99,99,99,99,99,99,99,99,99,13,99,12 }, // IntToPtr |
2180 { 5, 5, 5, 6, 6, 5, 5, 6, 6,11, 5, 1 }, // BitCast -+
2183 // If either of the casts are a bitcast from scalar to vector, disallow the
2184 // merging. However, bitcast of A->B->A are allowed.
2185 bool isFirstBitcast = (firstOp == Instruction::BitCast);
2186 bool isSecondBitcast = (secondOp == Instruction::BitCast);
2187 bool chainedBitcast = (SrcTy == DstTy && isFirstBitcast && isSecondBitcast);
2189 // Check if any of the bitcasts convert scalars<->vectors.
2190 if ((isFirstBitcast && isa<VectorType>(SrcTy) != isa<VectorType>(MidTy)) ||
2191 (isSecondBitcast && isa<VectorType>(MidTy) != isa<VectorType>(DstTy)))
2192 // Unless we are bitcasing to the original type, disallow optimizations.
2193 if (!chainedBitcast) return 0;
2195 int ElimCase = CastResults[firstOp-Instruction::CastOpsBegin]
2196 [secondOp-Instruction::CastOpsBegin];
2199 // categorically disallowed
2202 // allowed, use first cast's opcode
2205 // allowed, use second cast's opcode
2208 // no-op cast in second op implies firstOp as long as the DestTy
2209 // is integer and we are not converting between a vector and a
2211 if (!SrcTy->isVectorTy() && DstTy->isIntegerTy())
2215 // no-op cast in second op implies firstOp as long as the DestTy
2216 // is floating point.
2217 if (DstTy->isFloatingPointTy())
2221 // no-op cast in first op implies secondOp as long as the SrcTy
2223 if (SrcTy->isIntegerTy())
2227 // no-op cast in first op implies secondOp as long as the SrcTy
2228 // is a floating point.
2229 if (SrcTy->isFloatingPointTy())
2233 // ptrtoint, inttoptr -> bitcast (ptr -> ptr) if int size is >= ptr size
2234 if (!SrcIntPtrTy || DstIntPtrTy != SrcIntPtrTy)
2236 unsigned PtrSize = SrcIntPtrTy->getScalarSizeInBits();
2237 unsigned MidSize = MidTy->getScalarSizeInBits();
2238 if (MidSize >= PtrSize)
2239 return Instruction::BitCast;
2243 // ext, trunc -> bitcast, if the SrcTy and DstTy are same size
2244 // ext, trunc -> ext, if sizeof(SrcTy) < sizeof(DstTy)
2245 // ext, trunc -> trunc, if sizeof(SrcTy) > sizeof(DstTy)
2246 unsigned SrcSize = SrcTy->getScalarSizeInBits();
2247 unsigned DstSize = DstTy->getScalarSizeInBits();
2248 if (SrcSize == DstSize)
2249 return Instruction::BitCast;
2250 else if (SrcSize < DstSize)
2254 case 9: // zext, sext -> zext, because sext can't sign extend after zext
2255 return Instruction::ZExt;
2257 // fpext followed by ftrunc is allowed if the bit size returned to is
2258 // the same as the original, in which case its just a bitcast
2260 return Instruction::BitCast;
2261 return 0; // If the types are not the same we can't eliminate it.
2263 // bitcast followed by ptrtoint is allowed as long as the bitcast
2264 // is a pointer to pointer cast.
2265 if (SrcTy->isPointerTy() && MidTy->isPointerTy())
2269 // inttoptr, bitcast -> intptr if bitcast is a ptr to ptr cast
2270 if (MidTy->isPointerTy() && DstTy->isPointerTy())
2274 // inttoptr, ptrtoint -> bitcast if SrcSize<=PtrSize and SrcSize==DstSize
2277 unsigned PtrSize = MidIntPtrTy->getScalarSizeInBits();
2278 unsigned SrcSize = SrcTy->getScalarSizeInBits();
2279 unsigned DstSize = DstTy->getScalarSizeInBits();
2280 if (SrcSize <= PtrSize && SrcSize == DstSize)
2281 return Instruction::BitCast;
2285 // cast combination can't happen (error in input). This is for all cases
2286 // where the MidTy is not the same for the two cast instructions.
2287 llvm_unreachable("Invalid Cast Combination");
2289 llvm_unreachable("Error in CastResults table!!!");
2293 CastInst *CastInst::Create(Instruction::CastOps op, Value *S, Type *Ty,
2294 const Twine &Name, Instruction *InsertBefore) {
2295 assert(castIsValid(op, S, Ty) && "Invalid cast!");
2296 // Construct and return the appropriate CastInst subclass
2298 case Trunc: return new TruncInst (S, Ty, Name, InsertBefore);
2299 case ZExt: return new ZExtInst (S, Ty, Name, InsertBefore);
2300 case SExt: return new SExtInst (S, Ty, Name, InsertBefore);
2301 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertBefore);
2302 case FPExt: return new FPExtInst (S, Ty, Name, InsertBefore);
2303 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertBefore);
2304 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertBefore);
2305 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertBefore);
2306 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertBefore);
2307 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertBefore);
2308 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertBefore);
2309 case BitCast: return new BitCastInst (S, Ty, Name, InsertBefore);
2310 default: llvm_unreachable("Invalid opcode provided");
2314 CastInst *CastInst::Create(Instruction::CastOps op, Value *S, Type *Ty,
2315 const Twine &Name, BasicBlock *InsertAtEnd) {
2316 assert(castIsValid(op, S, Ty) && "Invalid cast!");
2317 // Construct and return the appropriate CastInst subclass
2319 case Trunc: return new TruncInst (S, Ty, Name, InsertAtEnd);
2320 case ZExt: return new ZExtInst (S, Ty, Name, InsertAtEnd);
2321 case SExt: return new SExtInst (S, Ty, Name, InsertAtEnd);
2322 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertAtEnd);
2323 case FPExt: return new FPExtInst (S, Ty, Name, InsertAtEnd);
2324 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertAtEnd);
2325 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertAtEnd);
2326 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertAtEnd);
2327 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertAtEnd);
2328 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertAtEnd);
2329 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertAtEnd);
2330 case BitCast: return new BitCastInst (S, Ty, Name, InsertAtEnd);
2331 default: llvm_unreachable("Invalid opcode provided");
2335 CastInst *CastInst::CreateZExtOrBitCast(Value *S, Type *Ty,
2337 Instruction *InsertBefore) {
2338 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2339 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2340 return Create(Instruction::ZExt, S, Ty, Name, InsertBefore);
2343 CastInst *CastInst::CreateZExtOrBitCast(Value *S, Type *Ty,
2345 BasicBlock *InsertAtEnd) {
2346 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2347 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2348 return Create(Instruction::ZExt, S, Ty, Name, InsertAtEnd);
2351 CastInst *CastInst::CreateSExtOrBitCast(Value *S, Type *Ty,
2353 Instruction *InsertBefore) {
2354 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2355 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2356 return Create(Instruction::SExt, S, Ty, Name, InsertBefore);
2359 CastInst *CastInst::CreateSExtOrBitCast(Value *S, Type *Ty,
2361 BasicBlock *InsertAtEnd) {
2362 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2363 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2364 return Create(Instruction::SExt, S, Ty, Name, InsertAtEnd);
2367 CastInst *CastInst::CreateTruncOrBitCast(Value *S, Type *Ty,
2369 Instruction *InsertBefore) {
2370 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2371 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2372 return Create(Instruction::Trunc, S, Ty, Name, InsertBefore);
2375 CastInst *CastInst::CreateTruncOrBitCast(Value *S, Type *Ty,
2377 BasicBlock *InsertAtEnd) {
2378 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2379 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2380 return Create(Instruction::Trunc, S, Ty, Name, InsertAtEnd);
2383 CastInst *CastInst::CreatePointerCast(Value *S, Type *Ty,
2385 BasicBlock *InsertAtEnd) {
2386 assert(S->getType()->isPointerTy() && "Invalid cast");
2387 assert((Ty->isIntegerTy() || Ty->isPointerTy()) &&
2390 if (Ty->isIntegerTy())
2391 return Create(Instruction::PtrToInt, S, Ty, Name, InsertAtEnd);
2392 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2395 /// @brief Create a BitCast or a PtrToInt cast instruction
2396 CastInst *CastInst::CreatePointerCast(Value *S, Type *Ty,
2398 Instruction *InsertBefore) {
2399 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
2400 assert((Ty->isIntOrIntVectorTy() || Ty->isPtrOrPtrVectorTy()) &&
2403 if (Ty->isIntOrIntVectorTy())
2404 return Create(Instruction::PtrToInt, S, Ty, Name, InsertBefore);
2405 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2408 CastInst *CastInst::CreateIntegerCast(Value *C, Type *Ty,
2409 bool isSigned, const Twine &Name,
2410 Instruction *InsertBefore) {
2411 assert(C->getType()->isIntOrIntVectorTy() && Ty->isIntOrIntVectorTy() &&
2412 "Invalid integer cast");
2413 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2414 unsigned DstBits = Ty->getScalarSizeInBits();
2415 Instruction::CastOps opcode =
2416 (SrcBits == DstBits ? Instruction::BitCast :
2417 (SrcBits > DstBits ? Instruction::Trunc :
2418 (isSigned ? Instruction::SExt : Instruction::ZExt)));
2419 return Create(opcode, C, Ty, Name, InsertBefore);
2422 CastInst *CastInst::CreateIntegerCast(Value *C, Type *Ty,
2423 bool isSigned, const Twine &Name,
2424 BasicBlock *InsertAtEnd) {
2425 assert(C->getType()->isIntOrIntVectorTy() && Ty->isIntOrIntVectorTy() &&
2427 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2428 unsigned DstBits = Ty->getScalarSizeInBits();
2429 Instruction::CastOps opcode =
2430 (SrcBits == DstBits ? Instruction::BitCast :
2431 (SrcBits > DstBits ? Instruction::Trunc :
2432 (isSigned ? Instruction::SExt : Instruction::ZExt)));
2433 return Create(opcode, C, Ty, Name, InsertAtEnd);
2436 CastInst *CastInst::CreateFPCast(Value *C, Type *Ty,
2438 Instruction *InsertBefore) {
2439 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
2441 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2442 unsigned DstBits = Ty->getScalarSizeInBits();
2443 Instruction::CastOps opcode =
2444 (SrcBits == DstBits ? Instruction::BitCast :
2445 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
2446 return Create(opcode, C, Ty, Name, InsertBefore);
2449 CastInst *CastInst::CreateFPCast(Value *C, Type *Ty,
2451 BasicBlock *InsertAtEnd) {
2452 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
2454 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2455 unsigned DstBits = Ty->getScalarSizeInBits();
2456 Instruction::CastOps opcode =
2457 (SrcBits == DstBits ? Instruction::BitCast :
2458 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
2459 return Create(opcode, C, Ty, Name, InsertAtEnd);
2462 // Check whether it is valid to call getCastOpcode for these types.
2463 // This routine must be kept in sync with getCastOpcode.
2464 bool CastInst::isCastable(Type *SrcTy, Type *DestTy) {
2465 if (!SrcTy->isFirstClassType() || !DestTy->isFirstClassType())
2468 if (SrcTy == DestTy)
2471 if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy))
2472 if (VectorType *DestVecTy = dyn_cast<VectorType>(DestTy))
2473 if (SrcVecTy->getNumElements() == DestVecTy->getNumElements()) {
2474 // An element by element cast. Valid if casting the elements is valid.
2475 SrcTy = SrcVecTy->getElementType();
2476 DestTy = DestVecTy->getElementType();
2479 // Get the bit sizes, we'll need these
2480 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); // 0 for ptr
2481 unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr
2483 // Run through the possibilities ...
2484 if (DestTy->isIntegerTy()) { // Casting to integral
2485 if (SrcTy->isIntegerTy()) { // Casting from integral
2487 } else if (SrcTy->isFloatingPointTy()) { // Casting from floating pt
2489 } else if (SrcTy->isVectorTy()) { // Casting from vector
2490 return DestBits == SrcBits;
2491 } else { // Casting from something else
2492 return SrcTy->isPointerTy();
2494 } else if (DestTy->isFloatingPointTy()) { // Casting to floating pt
2495 if (SrcTy->isIntegerTy()) { // Casting from integral
2497 } else if (SrcTy->isFloatingPointTy()) { // Casting from floating pt
2499 } else if (SrcTy->isVectorTy()) { // Casting from vector
2500 return DestBits == SrcBits;
2501 } else { // Casting from something else
2504 } else if (DestTy->isVectorTy()) { // Casting to vector
2505 return DestBits == SrcBits;
2506 } else if (DestTy->isPointerTy()) { // Casting to pointer
2507 if (SrcTy->isPointerTy()) { // Casting from pointer
2509 } else if (SrcTy->isIntegerTy()) { // Casting from integral
2511 } else { // Casting from something else
2514 } else if (DestTy->isX86_MMXTy()) {
2515 if (SrcTy->isVectorTy()) {
2516 return DestBits == SrcBits; // 64-bit vector to MMX
2520 } else { // Casting to something else
2525 // Provide a way to get a "cast" where the cast opcode is inferred from the
2526 // types and size of the operand. This, basically, is a parallel of the
2527 // logic in the castIsValid function below. This axiom should hold:
2528 // castIsValid( getCastOpcode(Val, Ty), Val, Ty)
2529 // should not assert in castIsValid. In other words, this produces a "correct"
2530 // casting opcode for the arguments passed to it.
2531 // This routine must be kept in sync with isCastable.
2532 Instruction::CastOps
2533 CastInst::getCastOpcode(
2534 const Value *Src, bool SrcIsSigned, Type *DestTy, bool DestIsSigned) {
2535 Type *SrcTy = Src->getType();
2537 assert(SrcTy->isFirstClassType() && DestTy->isFirstClassType() &&
2538 "Only first class types are castable!");
2540 if (SrcTy == DestTy)
2543 if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy))
2544 if (VectorType *DestVecTy = dyn_cast<VectorType>(DestTy))
2545 if (SrcVecTy->getNumElements() == DestVecTy->getNumElements()) {
2546 // An element by element cast. Find the appropriate opcode based on the
2548 SrcTy = SrcVecTy->getElementType();
2549 DestTy = DestVecTy->getElementType();
2552 // Get the bit sizes, we'll need these
2553 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); // 0 for ptr
2554 unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr
2556 // Run through the possibilities ...
2557 if (DestTy->isIntegerTy()) { // Casting to integral
2558 if (SrcTy->isIntegerTy()) { // Casting from integral
2559 if (DestBits < SrcBits)
2560 return Trunc; // int -> smaller int
2561 else if (DestBits > SrcBits) { // its an extension
2563 return SExt; // signed -> SEXT
2565 return ZExt; // unsigned -> ZEXT
2567 return BitCast; // Same size, No-op cast
2569 } else if (SrcTy->isFloatingPointTy()) { // Casting from floating pt
2571 return FPToSI; // FP -> sint
2573 return FPToUI; // FP -> uint
2574 } else if (SrcTy->isVectorTy()) {
2575 assert(DestBits == SrcBits &&
2576 "Casting vector to integer of different width");
2577 return BitCast; // Same size, no-op cast
2579 assert(SrcTy->isPointerTy() &&
2580 "Casting from a value that is not first-class type");
2581 return PtrToInt; // ptr -> int
2583 } else if (DestTy->isFloatingPointTy()) { // Casting to floating pt
2584 if (SrcTy->isIntegerTy()) { // Casting from integral
2586 return SIToFP; // sint -> FP
2588 return UIToFP; // uint -> FP
2589 } else if (SrcTy->isFloatingPointTy()) { // Casting from floating pt
2590 if (DestBits < SrcBits) {
2591 return FPTrunc; // FP -> smaller FP
2592 } else if (DestBits > SrcBits) {
2593 return FPExt; // FP -> larger FP
2595 return BitCast; // same size, no-op cast
2597 } else if (SrcTy->isVectorTy()) {
2598 assert(DestBits == SrcBits &&
2599 "Casting vector to floating point of different width");
2600 return BitCast; // same size, no-op cast
2602 llvm_unreachable("Casting pointer or non-first class to float");
2603 } else if (DestTy->isVectorTy()) {
2604 assert(DestBits == SrcBits &&
2605 "Illegal cast to vector (wrong type or size)");
2607 } else if (DestTy->isPointerTy()) {
2608 if (SrcTy->isPointerTy()) {
2609 return BitCast; // ptr -> ptr
2610 } else if (SrcTy->isIntegerTy()) {
2611 return IntToPtr; // int -> ptr
2613 llvm_unreachable("Casting pointer to other than pointer or int");
2614 } else if (DestTy->isX86_MMXTy()) {
2615 if (SrcTy->isVectorTy()) {
2616 assert(DestBits == SrcBits && "Casting vector of wrong width to X86_MMX");
2617 return BitCast; // 64-bit vector to MMX
2619 llvm_unreachable("Illegal cast to X86_MMX");
2621 llvm_unreachable("Casting to type that is not first-class");
2624 //===----------------------------------------------------------------------===//
2625 // CastInst SubClass Constructors
2626 //===----------------------------------------------------------------------===//
2628 /// Check that the construction parameters for a CastInst are correct. This
2629 /// could be broken out into the separate constructors but it is useful to have
2630 /// it in one place and to eliminate the redundant code for getting the sizes
2631 /// of the types involved.
2633 CastInst::castIsValid(Instruction::CastOps op, Value *S, Type *DstTy) {
2635 // Check for type sanity on the arguments
2636 Type *SrcTy = S->getType();
2638 // If this is a cast to the same type then it's trivially true.
2642 if (!SrcTy->isFirstClassType() || !DstTy->isFirstClassType() ||
2643 SrcTy->isAggregateType() || DstTy->isAggregateType())
2646 // Get the size of the types in bits, we'll need this later
2647 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
2648 unsigned DstBitSize = DstTy->getScalarSizeInBits();
2650 // If these are vector types, get the lengths of the vectors (using zero for
2651 // scalar types means that checking that vector lengths match also checks that
2652 // scalars are not being converted to vectors or vectors to scalars).
2653 unsigned SrcLength = SrcTy->isVectorTy() ?
2654 cast<VectorType>(SrcTy)->getNumElements() : 0;
2655 unsigned DstLength = DstTy->isVectorTy() ?
2656 cast<VectorType>(DstTy)->getNumElements() : 0;
2658 // Switch on the opcode provided
2660 default: return false; // This is an input error
2661 case Instruction::Trunc:
2662 return SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy() &&
2663 SrcLength == DstLength && SrcBitSize > DstBitSize;
2664 case Instruction::ZExt:
2665 return SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy() &&
2666 SrcLength == DstLength && SrcBitSize < DstBitSize;
2667 case Instruction::SExt:
2668 return SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy() &&
2669 SrcLength == DstLength && SrcBitSize < DstBitSize;
2670 case Instruction::FPTrunc:
2671 return SrcTy->isFPOrFPVectorTy() && DstTy->isFPOrFPVectorTy() &&
2672 SrcLength == DstLength && SrcBitSize > DstBitSize;
2673 case Instruction::FPExt:
2674 return SrcTy->isFPOrFPVectorTy() && DstTy->isFPOrFPVectorTy() &&
2675 SrcLength == DstLength && SrcBitSize < DstBitSize;
2676 case Instruction::UIToFP:
2677 case Instruction::SIToFP:
2678 return SrcTy->isIntOrIntVectorTy() && DstTy->isFPOrFPVectorTy() &&
2679 SrcLength == DstLength;
2680 case Instruction::FPToUI:
2681 case Instruction::FPToSI:
2682 return SrcTy->isFPOrFPVectorTy() && DstTy->isIntOrIntVectorTy() &&
2683 SrcLength == DstLength;
2684 case Instruction::PtrToInt:
2685 if (isa<VectorType>(SrcTy) != isa<VectorType>(DstTy))
2687 if (VectorType *VT = dyn_cast<VectorType>(SrcTy))
2688 if (VT->getNumElements() != cast<VectorType>(DstTy)->getNumElements())
2690 return SrcTy->getScalarType()->isPointerTy() &&
2691 DstTy->getScalarType()->isIntegerTy();
2692 case Instruction::IntToPtr:
2693 if (isa<VectorType>(SrcTy) != isa<VectorType>(DstTy))
2695 if (VectorType *VT = dyn_cast<VectorType>(SrcTy))
2696 if (VT->getNumElements() != cast<VectorType>(DstTy)->getNumElements())
2698 return SrcTy->getScalarType()->isIntegerTy() &&
2699 DstTy->getScalarType()->isPointerTy();
2700 case Instruction::BitCast:
2701 // BitCast implies a no-op cast of type only. No bits change.
2702 // However, you can't cast pointers to anything but pointers.
2703 if (SrcTy->isPointerTy() != DstTy->isPointerTy())
2706 // Now we know we're not dealing with a pointer/non-pointer mismatch. In all
2707 // these cases, the cast is okay if the source and destination bit widths
2709 return SrcTy->getPrimitiveSizeInBits() == DstTy->getPrimitiveSizeInBits();
2713 TruncInst::TruncInst(
2714 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2715 ) : CastInst(Ty, Trunc, S, Name, InsertBefore) {
2716 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
2719 TruncInst::TruncInst(
2720 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2721 ) : CastInst(Ty, Trunc, S, Name, InsertAtEnd) {
2722 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
2726 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2727 ) : CastInst(Ty, ZExt, S, Name, InsertBefore) {
2728 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
2732 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2733 ) : CastInst(Ty, ZExt, S, Name, InsertAtEnd) {
2734 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
2737 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2738 ) : CastInst(Ty, SExt, S, Name, InsertBefore) {
2739 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
2743 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2744 ) : CastInst(Ty, SExt, S, Name, InsertAtEnd) {
2745 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
2748 FPTruncInst::FPTruncInst(
2749 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2750 ) : CastInst(Ty, FPTrunc, S, Name, InsertBefore) {
2751 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
2754 FPTruncInst::FPTruncInst(
2755 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2756 ) : CastInst(Ty, FPTrunc, S, Name, InsertAtEnd) {
2757 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
2760 FPExtInst::FPExtInst(
2761 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2762 ) : CastInst(Ty, FPExt, S, Name, InsertBefore) {
2763 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
2766 FPExtInst::FPExtInst(
2767 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2768 ) : CastInst(Ty, FPExt, S, Name, InsertAtEnd) {
2769 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
2772 UIToFPInst::UIToFPInst(
2773 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2774 ) : CastInst(Ty, UIToFP, S, Name, InsertBefore) {
2775 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
2778 UIToFPInst::UIToFPInst(
2779 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2780 ) : CastInst(Ty, UIToFP, S, Name, InsertAtEnd) {
2781 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
2784 SIToFPInst::SIToFPInst(
2785 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2786 ) : CastInst(Ty, SIToFP, S, Name, InsertBefore) {
2787 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
2790 SIToFPInst::SIToFPInst(
2791 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2792 ) : CastInst(Ty, SIToFP, S, Name, InsertAtEnd) {
2793 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
2796 FPToUIInst::FPToUIInst(
2797 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2798 ) : CastInst(Ty, FPToUI, S, Name, InsertBefore) {
2799 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
2802 FPToUIInst::FPToUIInst(
2803 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2804 ) : CastInst(Ty, FPToUI, S, Name, InsertAtEnd) {
2805 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
2808 FPToSIInst::FPToSIInst(
2809 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2810 ) : CastInst(Ty, FPToSI, S, Name, InsertBefore) {
2811 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
2814 FPToSIInst::FPToSIInst(
2815 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2816 ) : CastInst(Ty, FPToSI, S, Name, InsertAtEnd) {
2817 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
2820 PtrToIntInst::PtrToIntInst(
2821 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2822 ) : CastInst(Ty, PtrToInt, S, Name, InsertBefore) {
2823 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
2826 PtrToIntInst::PtrToIntInst(
2827 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2828 ) : CastInst(Ty, PtrToInt, S, Name, InsertAtEnd) {
2829 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
2832 IntToPtrInst::IntToPtrInst(
2833 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2834 ) : CastInst(Ty, IntToPtr, S, Name, InsertBefore) {
2835 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
2838 IntToPtrInst::IntToPtrInst(
2839 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2840 ) : CastInst(Ty, IntToPtr, S, Name, InsertAtEnd) {
2841 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
2844 BitCastInst::BitCastInst(
2845 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2846 ) : CastInst(Ty, BitCast, S, Name, InsertBefore) {
2847 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
2850 BitCastInst::BitCastInst(
2851 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2852 ) : CastInst(Ty, BitCast, S, Name, InsertAtEnd) {
2853 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
2856 //===----------------------------------------------------------------------===//
2858 //===----------------------------------------------------------------------===//
2860 void CmpInst::anchor() {}
2862 CmpInst::CmpInst(Type *ty, OtherOps op, unsigned short predicate,
2863 Value *LHS, Value *RHS, const Twine &Name,
2864 Instruction *InsertBefore)
2865 : Instruction(ty, op,
2866 OperandTraits<CmpInst>::op_begin(this),
2867 OperandTraits<CmpInst>::operands(this),
2871 setPredicate((Predicate)predicate);
2875 CmpInst::CmpInst(Type *ty, OtherOps op, unsigned short predicate,
2876 Value *LHS, Value *RHS, const Twine &Name,
2877 BasicBlock *InsertAtEnd)
2878 : Instruction(ty, op,
2879 OperandTraits<CmpInst>::op_begin(this),
2880 OperandTraits<CmpInst>::operands(this),
2884 setPredicate((Predicate)predicate);
2889 CmpInst::Create(OtherOps Op, unsigned short predicate,
2890 Value *S1, Value *S2,
2891 const Twine &Name, Instruction *InsertBefore) {
2892 if (Op == Instruction::ICmp) {
2894 return new ICmpInst(InsertBefore, CmpInst::Predicate(predicate),
2897 return new ICmpInst(CmpInst::Predicate(predicate),
2902 return new FCmpInst(InsertBefore, CmpInst::Predicate(predicate),
2905 return new FCmpInst(CmpInst::Predicate(predicate),
2910 CmpInst::Create(OtherOps Op, unsigned short predicate, Value *S1, Value *S2,
2911 const Twine &Name, BasicBlock *InsertAtEnd) {
2912 if (Op == Instruction::ICmp) {
2913 return new ICmpInst(*InsertAtEnd, CmpInst::Predicate(predicate),
2916 return new FCmpInst(*InsertAtEnd, CmpInst::Predicate(predicate),
2920 void CmpInst::swapOperands() {
2921 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
2924 cast<FCmpInst>(this)->swapOperands();
2927 bool CmpInst::isCommutative() const {
2928 if (const ICmpInst *IC = dyn_cast<ICmpInst>(this))
2929 return IC->isCommutative();
2930 return cast<FCmpInst>(this)->isCommutative();
2933 bool CmpInst::isEquality() const {
2934 if (const ICmpInst *IC = dyn_cast<ICmpInst>(this))
2935 return IC->isEquality();
2936 return cast<FCmpInst>(this)->isEquality();
2940 CmpInst::Predicate CmpInst::getInversePredicate(Predicate pred) {
2942 default: llvm_unreachable("Unknown cmp predicate!");
2943 case ICMP_EQ: return ICMP_NE;
2944 case ICMP_NE: return ICMP_EQ;
2945 case ICMP_UGT: return ICMP_ULE;
2946 case ICMP_ULT: return ICMP_UGE;
2947 case ICMP_UGE: return ICMP_ULT;
2948 case ICMP_ULE: return ICMP_UGT;
2949 case ICMP_SGT: return ICMP_SLE;
2950 case ICMP_SLT: return ICMP_SGE;
2951 case ICMP_SGE: return ICMP_SLT;
2952 case ICMP_SLE: return ICMP_SGT;
2954 case FCMP_OEQ: return FCMP_UNE;
2955 case FCMP_ONE: return FCMP_UEQ;
2956 case FCMP_OGT: return FCMP_ULE;
2957 case FCMP_OLT: return FCMP_UGE;
2958 case FCMP_OGE: return FCMP_ULT;
2959 case FCMP_OLE: return FCMP_UGT;
2960 case FCMP_UEQ: return FCMP_ONE;
2961 case FCMP_UNE: return FCMP_OEQ;
2962 case FCMP_UGT: return FCMP_OLE;
2963 case FCMP_ULT: return FCMP_OGE;
2964 case FCMP_UGE: return FCMP_OLT;
2965 case FCMP_ULE: return FCMP_OGT;
2966 case FCMP_ORD: return FCMP_UNO;
2967 case FCMP_UNO: return FCMP_ORD;
2968 case FCMP_TRUE: return FCMP_FALSE;
2969 case FCMP_FALSE: return FCMP_TRUE;
2973 ICmpInst::Predicate ICmpInst::getSignedPredicate(Predicate pred) {
2975 default: llvm_unreachable("Unknown icmp predicate!");
2976 case ICMP_EQ: case ICMP_NE:
2977 case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE:
2979 case ICMP_UGT: return ICMP_SGT;
2980 case ICMP_ULT: return ICMP_SLT;
2981 case ICMP_UGE: return ICMP_SGE;
2982 case ICMP_ULE: return ICMP_SLE;
2986 ICmpInst::Predicate ICmpInst::getUnsignedPredicate(Predicate pred) {
2988 default: llvm_unreachable("Unknown icmp predicate!");
2989 case ICMP_EQ: case ICMP_NE:
2990 case ICMP_UGT: case ICMP_ULT: case ICMP_UGE: case ICMP_ULE:
2992 case ICMP_SGT: return ICMP_UGT;
2993 case ICMP_SLT: return ICMP_ULT;
2994 case ICMP_SGE: return ICMP_UGE;
2995 case ICMP_SLE: return ICMP_ULE;
2999 /// Initialize a set of values that all satisfy the condition with C.
3002 ICmpInst::makeConstantRange(Predicate pred, const APInt &C) {
3005 uint32_t BitWidth = C.getBitWidth();
3007 default: llvm_unreachable("Invalid ICmp opcode to ConstantRange ctor!");
3008 case ICmpInst::ICMP_EQ: Upper++; break;
3009 case ICmpInst::ICMP_NE: Lower++; break;
3010 case ICmpInst::ICMP_ULT:
3011 Lower = APInt::getMinValue(BitWidth);
3012 // Check for an empty-set condition.
3014 return ConstantRange(BitWidth, /*isFullSet=*/false);
3016 case ICmpInst::ICMP_SLT:
3017 Lower = APInt::getSignedMinValue(BitWidth);
3018 // Check for an empty-set condition.
3020 return ConstantRange(BitWidth, /*isFullSet=*/false);
3022 case ICmpInst::ICMP_UGT:
3023 Lower++; Upper = APInt::getMinValue(BitWidth); // Min = Next(Max)
3024 // Check for an empty-set condition.
3026 return ConstantRange(BitWidth, /*isFullSet=*/false);
3028 case ICmpInst::ICMP_SGT:
3029 Lower++; Upper = APInt::getSignedMinValue(BitWidth); // Min = Next(Max)
3030 // Check for an empty-set condition.
3032 return ConstantRange(BitWidth, /*isFullSet=*/false);
3034 case ICmpInst::ICMP_ULE:
3035 Lower = APInt::getMinValue(BitWidth); Upper++;
3036 // Check for a full-set condition.
3038 return ConstantRange(BitWidth, /*isFullSet=*/true);
3040 case ICmpInst::ICMP_SLE:
3041 Lower = APInt::getSignedMinValue(BitWidth); Upper++;
3042 // Check for a full-set condition.
3044 return ConstantRange(BitWidth, /*isFullSet=*/true);
3046 case ICmpInst::ICMP_UGE:
3047 Upper = APInt::getMinValue(BitWidth); // Min = Next(Max)
3048 // Check for a full-set condition.
3050 return ConstantRange(BitWidth, /*isFullSet=*/true);
3052 case ICmpInst::ICMP_SGE:
3053 Upper = APInt::getSignedMinValue(BitWidth); // Min = Next(Max)
3054 // Check for a full-set condition.
3056 return ConstantRange(BitWidth, /*isFullSet=*/true);
3059 return ConstantRange(Lower, Upper);
3062 CmpInst::Predicate CmpInst::getSwappedPredicate(Predicate pred) {
3064 default: llvm_unreachable("Unknown cmp predicate!");
3065 case ICMP_EQ: case ICMP_NE:
3067 case ICMP_SGT: return ICMP_SLT;
3068 case ICMP_SLT: return ICMP_SGT;
3069 case ICMP_SGE: return ICMP_SLE;
3070 case ICMP_SLE: return ICMP_SGE;
3071 case ICMP_UGT: return ICMP_ULT;
3072 case ICMP_ULT: return ICMP_UGT;
3073 case ICMP_UGE: return ICMP_ULE;
3074 case ICMP_ULE: return ICMP_UGE;
3076 case FCMP_FALSE: case FCMP_TRUE:
3077 case FCMP_OEQ: case FCMP_ONE:
3078 case FCMP_UEQ: case FCMP_UNE:
3079 case FCMP_ORD: case FCMP_UNO:
3081 case FCMP_OGT: return FCMP_OLT;
3082 case FCMP_OLT: return FCMP_OGT;
3083 case FCMP_OGE: return FCMP_OLE;
3084 case FCMP_OLE: return FCMP_OGE;
3085 case FCMP_UGT: return FCMP_ULT;
3086 case FCMP_ULT: return FCMP_UGT;
3087 case FCMP_UGE: return FCMP_ULE;
3088 case FCMP_ULE: return FCMP_UGE;
3092 bool CmpInst::isUnsigned(unsigned short predicate) {
3093 switch (predicate) {
3094 default: return false;
3095 case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_ULE: case ICmpInst::ICMP_UGT:
3096 case ICmpInst::ICMP_UGE: return true;
3100 bool CmpInst::isSigned(unsigned short predicate) {
3101 switch (predicate) {
3102 default: return false;
3103 case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_SLE: case ICmpInst::ICMP_SGT:
3104 case ICmpInst::ICMP_SGE: return true;
3108 bool CmpInst::isOrdered(unsigned short predicate) {
3109 switch (predicate) {
3110 default: return false;
3111 case FCmpInst::FCMP_OEQ: case FCmpInst::FCMP_ONE: case FCmpInst::FCMP_OGT:
3112 case FCmpInst::FCMP_OLT: case FCmpInst::FCMP_OGE: case FCmpInst::FCMP_OLE:
3113 case FCmpInst::FCMP_ORD: return true;
3117 bool CmpInst::isUnordered(unsigned short predicate) {
3118 switch (predicate) {
3119 default: return false;
3120 case FCmpInst::FCMP_UEQ: case FCmpInst::FCMP_UNE: case FCmpInst::FCMP_UGT:
3121 case FCmpInst::FCMP_ULT: case FCmpInst::FCMP_UGE: case FCmpInst::FCMP_ULE:
3122 case FCmpInst::FCMP_UNO: return true;
3126 bool CmpInst::isTrueWhenEqual(unsigned short predicate) {
3128 default: return false;
3129 case ICMP_EQ: case ICMP_UGE: case ICMP_ULE: case ICMP_SGE: case ICMP_SLE:
3130 case FCMP_TRUE: case FCMP_UEQ: case FCMP_UGE: case FCMP_ULE: return true;
3134 bool CmpInst::isFalseWhenEqual(unsigned short predicate) {
3136 case ICMP_NE: case ICMP_UGT: case ICMP_ULT: case ICMP_SGT: case ICMP_SLT:
3137 case FCMP_FALSE: case FCMP_ONE: case FCMP_OGT: case FCMP_OLT: return true;
3138 default: return false;
3143 //===----------------------------------------------------------------------===//
3144 // SwitchInst Implementation
3145 //===----------------------------------------------------------------------===//
3147 void SwitchInst::init(Value *Value, BasicBlock *Default, unsigned NumReserved) {
3148 assert(Value && Default && NumReserved);
3149 ReservedSpace = NumReserved;
3151 OperandList = allocHungoffUses(ReservedSpace);
3153 OperandList[0] = Value;
3154 OperandList[1] = Default;
3157 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
3158 /// switch on and a default destination. The number of additional cases can
3159 /// be specified here to make memory allocation more efficient. This
3160 /// constructor can also autoinsert before another instruction.
3161 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
3162 Instruction *InsertBefore)
3163 : TerminatorInst(Type::getVoidTy(Value->getContext()), Instruction::Switch,
3164 0, 0, InsertBefore) {
3165 init(Value, Default, 2+NumCases*2);
3168 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
3169 /// switch on and a default destination. The number of additional cases can
3170 /// be specified here to make memory allocation more efficient. This
3171 /// constructor also autoinserts at the end of the specified BasicBlock.
3172 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
3173 BasicBlock *InsertAtEnd)
3174 : TerminatorInst(Type::getVoidTy(Value->getContext()), Instruction::Switch,
3175 0, 0, InsertAtEnd) {
3176 init(Value, Default, 2+NumCases*2);
3179 SwitchInst::SwitchInst(const SwitchInst &SI)
3180 : TerminatorInst(SI.getType(), Instruction::Switch, 0, 0) {
3181 init(SI.getCondition(), SI.getDefaultDest(), SI.getNumOperands());
3182 NumOperands = SI.getNumOperands();
3183 Use *OL = OperandList, *InOL = SI.OperandList;
3184 for (unsigned i = 2, E = SI.getNumOperands(); i != E; i += 2) {
3186 OL[i+1] = InOL[i+1];
3188 TheSubsets = SI.TheSubsets;
3189 SubclassOptionalData = SI.SubclassOptionalData;
3192 SwitchInst::~SwitchInst() {
3197 /// addCase - Add an entry to the switch instruction...
3199 void SwitchInst::addCase(ConstantInt *OnVal, BasicBlock *Dest) {
3200 IntegersSubsetToBB Mapping;
3202 // FIXME: Currently we work with ConstantInt based cases.
3203 // So inititalize IntItem container directly from ConstantInt.
3204 Mapping.add(IntItem::fromConstantInt(OnVal));
3205 IntegersSubset CaseRanges = Mapping.getCase();
3206 addCase(CaseRanges, Dest);
3209 void SwitchInst::addCase(IntegersSubset& OnVal, BasicBlock *Dest) {
3210 unsigned NewCaseIdx = getNumCases();
3211 unsigned OpNo = NumOperands;
3212 if (OpNo+2 > ReservedSpace)
3213 growOperands(); // Get more space!
3214 // Initialize some new operands.
3215 assert(OpNo+1 < ReservedSpace && "Growing didn't work!");
3216 NumOperands = OpNo+2;
3218 SubsetsIt TheSubsetsIt = TheSubsets.insert(TheSubsets.end(), OnVal);
3220 CaseIt Case(this, NewCaseIdx, TheSubsetsIt);
3221 Case.updateCaseValueOperand(OnVal);
3222 Case.setSuccessor(Dest);
3225 /// removeCase - This method removes the specified case and its successor
3226 /// from the switch instruction.
3227 void SwitchInst::removeCase(CaseIt& i) {
3228 unsigned idx = i.getCaseIndex();
3230 assert(2 + idx*2 < getNumOperands() && "Case index out of range!!!");
3232 unsigned NumOps = getNumOperands();
3233 Use *OL = OperandList;
3235 // Overwrite this case with the end of the list.
3236 if (2 + (idx + 1) * 2 != NumOps) {
3237 OL[2 + idx * 2] = OL[NumOps - 2];
3238 OL[2 + idx * 2 + 1] = OL[NumOps - 1];
3241 // Nuke the last value.
3242 OL[NumOps-2].set(0);
3243 OL[NumOps-2+1].set(0);
3245 // Do the same with TheCases collection:
3246 if (i.SubsetIt != --TheSubsets.end()) {
3247 *i.SubsetIt = TheSubsets.back();
3248 TheSubsets.pop_back();
3250 TheSubsets.pop_back();
3251 i.SubsetIt = TheSubsets.end();
3254 NumOperands = NumOps-2;
3257 /// growOperands - grow operands - This grows the operand list in response
3258 /// to a push_back style of operation. This grows the number of ops by 3 times.
3260 void SwitchInst::growOperands() {
3261 unsigned e = getNumOperands();
3262 unsigned NumOps = e*3;
3264 ReservedSpace = NumOps;
3265 Use *NewOps = allocHungoffUses(NumOps);
3266 Use *OldOps = OperandList;
3267 for (unsigned i = 0; i != e; ++i) {
3268 NewOps[i] = OldOps[i];
3270 OperandList = NewOps;
3271 Use::zap(OldOps, OldOps + e, true);
3275 BasicBlock *SwitchInst::getSuccessorV(unsigned idx) const {
3276 return getSuccessor(idx);
3278 unsigned SwitchInst::getNumSuccessorsV() const {
3279 return getNumSuccessors();
3281 void SwitchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
3282 setSuccessor(idx, B);
3285 //===----------------------------------------------------------------------===//
3286 // IndirectBrInst Implementation
3287 //===----------------------------------------------------------------------===//
3289 void IndirectBrInst::init(Value *Address, unsigned NumDests) {
3290 assert(Address && Address->getType()->isPointerTy() &&
3291 "Address of indirectbr must be a pointer");
3292 ReservedSpace = 1+NumDests;
3294 OperandList = allocHungoffUses(ReservedSpace);
3296 OperandList[0] = Address;
3300 /// growOperands - grow operands - This grows the operand list in response
3301 /// to a push_back style of operation. This grows the number of ops by 2 times.
3303 void IndirectBrInst::growOperands() {
3304 unsigned e = getNumOperands();
3305 unsigned NumOps = e*2;
3307 ReservedSpace = NumOps;
3308 Use *NewOps = allocHungoffUses(NumOps);
3309 Use *OldOps = OperandList;
3310 for (unsigned i = 0; i != e; ++i)
3311 NewOps[i] = OldOps[i];
3312 OperandList = NewOps;
3313 Use::zap(OldOps, OldOps + e, true);
3316 IndirectBrInst::IndirectBrInst(Value *Address, unsigned NumCases,
3317 Instruction *InsertBefore)
3318 : TerminatorInst(Type::getVoidTy(Address->getContext()),Instruction::IndirectBr,
3319 0, 0, InsertBefore) {
3320 init(Address, NumCases);
3323 IndirectBrInst::IndirectBrInst(Value *Address, unsigned NumCases,
3324 BasicBlock *InsertAtEnd)
3325 : TerminatorInst(Type::getVoidTy(Address->getContext()),Instruction::IndirectBr,
3326 0, 0, InsertAtEnd) {
3327 init(Address, NumCases);
3330 IndirectBrInst::IndirectBrInst(const IndirectBrInst &IBI)
3331 : TerminatorInst(Type::getVoidTy(IBI.getContext()), Instruction::IndirectBr,
3332 allocHungoffUses(IBI.getNumOperands()),
3333 IBI.getNumOperands()) {
3334 Use *OL = OperandList, *InOL = IBI.OperandList;
3335 for (unsigned i = 0, E = IBI.getNumOperands(); i != E; ++i)
3337 SubclassOptionalData = IBI.SubclassOptionalData;
3340 IndirectBrInst::~IndirectBrInst() {
3344 /// addDestination - Add a destination.
3346 void IndirectBrInst::addDestination(BasicBlock *DestBB) {
3347 unsigned OpNo = NumOperands;
3348 if (OpNo+1 > ReservedSpace)
3349 growOperands(); // Get more space!
3350 // Initialize some new operands.
3351 assert(OpNo < ReservedSpace && "Growing didn't work!");
3352 NumOperands = OpNo+1;
3353 OperandList[OpNo] = DestBB;
3356 /// removeDestination - This method removes the specified successor from the
3357 /// indirectbr instruction.
3358 void IndirectBrInst::removeDestination(unsigned idx) {
3359 assert(idx < getNumOperands()-1 && "Successor index out of range!");
3361 unsigned NumOps = getNumOperands();
3362 Use *OL = OperandList;
3364 // Replace this value with the last one.
3365 OL[idx+1] = OL[NumOps-1];
3367 // Nuke the last value.
3368 OL[NumOps-1].set(0);
3369 NumOperands = NumOps-1;
3372 BasicBlock *IndirectBrInst::getSuccessorV(unsigned idx) const {
3373 return getSuccessor(idx);
3375 unsigned IndirectBrInst::getNumSuccessorsV() const {
3376 return getNumSuccessors();
3378 void IndirectBrInst::setSuccessorV(unsigned idx, BasicBlock *B) {
3379 setSuccessor(idx, B);
3382 //===----------------------------------------------------------------------===//
3383 // clone_impl() implementations
3384 //===----------------------------------------------------------------------===//
3386 // Define these methods here so vtables don't get emitted into every translation
3387 // unit that uses these classes.
3389 GetElementPtrInst *GetElementPtrInst::clone_impl() const {
3390 return new (getNumOperands()) GetElementPtrInst(*this);
3393 BinaryOperator *BinaryOperator::clone_impl() const {
3394 return Create(getOpcode(), Op<0>(), Op<1>());
3397 FCmpInst* FCmpInst::clone_impl() const {
3398 return new FCmpInst(getPredicate(), Op<0>(), Op<1>());
3401 ICmpInst* ICmpInst::clone_impl() const {
3402 return new ICmpInst(getPredicate(), Op<0>(), Op<1>());
3405 ExtractValueInst *ExtractValueInst::clone_impl() const {
3406 return new ExtractValueInst(*this);
3409 InsertValueInst *InsertValueInst::clone_impl() const {
3410 return new InsertValueInst(*this);
3413 AllocaInst *AllocaInst::clone_impl() const {
3414 return new AllocaInst(getAllocatedType(),
3415 (Value*)getOperand(0),
3419 LoadInst *LoadInst::clone_impl() const {
3420 return new LoadInst(getOperand(0), Twine(), isVolatile(),
3421 getAlignment(), getOrdering(), getSynchScope());
3424 StoreInst *StoreInst::clone_impl() const {
3425 return new StoreInst(getOperand(0), getOperand(1), isVolatile(),
3426 getAlignment(), getOrdering(), getSynchScope());
3430 AtomicCmpXchgInst *AtomicCmpXchgInst::clone_impl() const {
3431 AtomicCmpXchgInst *Result =
3432 new AtomicCmpXchgInst(getOperand(0), getOperand(1), getOperand(2),
3433 getOrdering(), getSynchScope());
3434 Result->setVolatile(isVolatile());
3438 AtomicRMWInst *AtomicRMWInst::clone_impl() const {
3439 AtomicRMWInst *Result =
3440 new AtomicRMWInst(getOperation(),getOperand(0), getOperand(1),
3441 getOrdering(), getSynchScope());
3442 Result->setVolatile(isVolatile());
3446 FenceInst *FenceInst::clone_impl() const {
3447 return new FenceInst(getContext(), getOrdering(), getSynchScope());
3450 TruncInst *TruncInst::clone_impl() const {
3451 return new TruncInst(getOperand(0), getType());
3454 ZExtInst *ZExtInst::clone_impl() const {
3455 return new ZExtInst(getOperand(0), getType());
3458 SExtInst *SExtInst::clone_impl() const {
3459 return new SExtInst(getOperand(0), getType());
3462 FPTruncInst *FPTruncInst::clone_impl() const {
3463 return new FPTruncInst(getOperand(0), getType());
3466 FPExtInst *FPExtInst::clone_impl() const {
3467 return new FPExtInst(getOperand(0), getType());
3470 UIToFPInst *UIToFPInst::clone_impl() const {
3471 return new UIToFPInst(getOperand(0), getType());
3474 SIToFPInst *SIToFPInst::clone_impl() const {
3475 return new SIToFPInst(getOperand(0), getType());
3478 FPToUIInst *FPToUIInst::clone_impl() const {
3479 return new FPToUIInst(getOperand(0), getType());
3482 FPToSIInst *FPToSIInst::clone_impl() const {
3483 return new FPToSIInst(getOperand(0), getType());
3486 PtrToIntInst *PtrToIntInst::clone_impl() const {
3487 return new PtrToIntInst(getOperand(0), getType());
3490 IntToPtrInst *IntToPtrInst::clone_impl() const {
3491 return new IntToPtrInst(getOperand(0), getType());
3494 BitCastInst *BitCastInst::clone_impl() const {
3495 return new BitCastInst(getOperand(0), getType());
3498 CallInst *CallInst::clone_impl() const {
3499 return new(getNumOperands()) CallInst(*this);
3502 SelectInst *SelectInst::clone_impl() const {
3503 return SelectInst::Create(getOperand(0), getOperand(1), getOperand(2));
3506 VAArgInst *VAArgInst::clone_impl() const {
3507 return new VAArgInst(getOperand(0), getType());
3510 ExtractElementInst *ExtractElementInst::clone_impl() const {
3511 return ExtractElementInst::Create(getOperand(0), getOperand(1));
3514 InsertElementInst *InsertElementInst::clone_impl() const {
3515 return InsertElementInst::Create(getOperand(0), getOperand(1), getOperand(2));
3518 ShuffleVectorInst *ShuffleVectorInst::clone_impl() const {
3519 return new ShuffleVectorInst(getOperand(0), getOperand(1), getOperand(2));
3522 PHINode *PHINode::clone_impl() const {
3523 return new PHINode(*this);
3526 LandingPadInst *LandingPadInst::clone_impl() const {
3527 return new LandingPadInst(*this);
3530 ReturnInst *ReturnInst::clone_impl() const {
3531 return new(getNumOperands()) ReturnInst(*this);
3534 BranchInst *BranchInst::clone_impl() const {
3535 return new(getNumOperands()) BranchInst(*this);
3538 SwitchInst *SwitchInst::clone_impl() const {
3539 return new SwitchInst(*this);
3542 IndirectBrInst *IndirectBrInst::clone_impl() const {
3543 return new IndirectBrInst(*this);
3547 InvokeInst *InvokeInst::clone_impl() const {
3548 return new(getNumOperands()) InvokeInst(*this);
3551 ResumeInst *ResumeInst::clone_impl() const {
3552 return new(1) ResumeInst(*this);
3555 UnreachableInst *UnreachableInst::clone_impl() const {
3556 LLVMContext &Context = getContext();
3557 return new UnreachableInst(Context);