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/CallSite.h"
18 #include "llvm/IR/ConstantRange.h"
19 #include "llvm/IR/Constants.h"
20 #include "llvm/IR/DataLayout.h"
21 #include "llvm/IR/DerivedTypes.h"
22 #include "llvm/IR/Function.h"
23 #include "llvm/IR/Module.h"
24 #include "llvm/IR/Operator.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, nullptr, PN.getNumOperands()),
89 ReservedSpace(PN.getNumOperands()) {
90 allocHungoffUses(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;
96 // removeIncomingValue - Remove an incoming value. This is useful if a
97 // predecessor basic block is deleted.
98 Value *PHINode::removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty) {
99 Value *Removed = getIncomingValue(Idx);
101 // Move everything after this operand down.
103 // FIXME: we could just swap with the end of the list, then erase. However,
104 // clients might not expect this to happen. The code as it is thrashes the
105 // use/def lists, which is kinda lame.
106 std::copy(op_begin() + Idx + 1, op_end(), op_begin() + Idx);
107 std::copy(block_begin() + Idx + 1, block_end(), block_begin() + Idx);
109 // Nuke the last value.
110 Op<-1>().set(nullptr);
111 setNumHungOffUseOperands(getNumOperands() - 1);
113 // If the PHI node is dead, because it has zero entries, nuke it now.
114 if (getNumOperands() == 0 && DeletePHIIfEmpty) {
115 // If anyone is using this PHI, make them use a dummy value instead...
116 replaceAllUsesWith(UndefValue::get(getType()));
122 /// growOperands - grow operands - This grows the operand list in response
123 /// to a push_back style of operation. This grows the number of ops by 1.5
126 void PHINode::growOperands() {
127 unsigned e = getNumOperands();
128 unsigned NumOps = e + e / 2;
129 if (NumOps < 2) NumOps = 2; // 2 op PHI nodes are VERY common.
131 ReservedSpace = NumOps;
132 growHungoffUses(ReservedSpace, /* IsPhi */ true);
135 /// hasConstantValue - If the specified PHI node always merges together the same
136 /// value, return the value, otherwise return null.
137 Value *PHINode::hasConstantValue() const {
138 // Exploit the fact that phi nodes always have at least one entry.
139 Value *ConstantValue = getIncomingValue(0);
140 for (unsigned i = 1, e = getNumIncomingValues(); i != e; ++i)
141 if (getIncomingValue(i) != ConstantValue && getIncomingValue(i) != this) {
142 if (ConstantValue != this)
143 return nullptr; // Incoming values not all the same.
144 // The case where the first value is this PHI.
145 ConstantValue = getIncomingValue(i);
147 if (ConstantValue == this)
148 return UndefValue::get(getType());
149 return ConstantValue;
152 //===----------------------------------------------------------------------===//
153 // LandingPadInst Implementation
154 //===----------------------------------------------------------------------===//
156 LandingPadInst::LandingPadInst(Type *RetTy, unsigned NumReservedValues,
157 const Twine &NameStr, Instruction *InsertBefore)
158 : Instruction(RetTy, Instruction::LandingPad, nullptr, 0, InsertBefore) {
159 init(NumReservedValues, NameStr);
162 LandingPadInst::LandingPadInst(Type *RetTy, unsigned NumReservedValues,
163 const Twine &NameStr, BasicBlock *InsertAtEnd)
164 : Instruction(RetTy, Instruction::LandingPad, nullptr, 0, InsertAtEnd) {
165 init(NumReservedValues, NameStr);
168 LandingPadInst::LandingPadInst(const LandingPadInst &LP)
169 : Instruction(LP.getType(), Instruction::LandingPad, nullptr,
170 LP.getNumOperands()),
171 ReservedSpace(LP.getNumOperands()) {
172 allocHungoffUses(LP.getNumOperands());
173 Use *OL = getOperandList();
174 const Use *InOL = LP.getOperandList();
175 for (unsigned I = 0, E = ReservedSpace; I != E; ++I)
178 setCleanup(LP.isCleanup());
181 LandingPadInst *LandingPadInst::Create(Type *RetTy, unsigned NumReservedClauses,
182 const Twine &NameStr,
183 Instruction *InsertBefore) {
184 return new LandingPadInst(RetTy, NumReservedClauses, NameStr, InsertBefore);
187 LandingPadInst *LandingPadInst::Create(Type *RetTy, unsigned NumReservedClauses,
188 const Twine &NameStr,
189 BasicBlock *InsertAtEnd) {
190 return new LandingPadInst(RetTy, NumReservedClauses, NameStr, InsertAtEnd);
193 void LandingPadInst::init(unsigned NumReservedValues, const Twine &NameStr) {
194 ReservedSpace = NumReservedValues;
195 setNumHungOffUseOperands(0);
196 allocHungoffUses(ReservedSpace);
201 /// growOperands - grow operands - This grows the operand list in response to a
202 /// push_back style of operation. This grows the number of ops by 2 times.
203 void LandingPadInst::growOperands(unsigned Size) {
204 unsigned e = getNumOperands();
205 if (ReservedSpace >= e + Size) return;
206 ReservedSpace = (std::max(e, 1U) + Size / 2) * 2;
207 growHungoffUses(ReservedSpace);
210 void LandingPadInst::addClause(Constant *Val) {
211 unsigned OpNo = getNumOperands();
213 assert(OpNo < ReservedSpace && "Growing didn't work!");
214 setNumHungOffUseOperands(getNumOperands() + 1);
215 getOperandList()[OpNo] = Val;
218 //===----------------------------------------------------------------------===//
219 // CallInst Implementation
220 //===----------------------------------------------------------------------===//
222 CallInst::~CallInst() {
225 void CallInst::init(FunctionType *FTy, Value *Func, ArrayRef<Value *> Args,
226 const Twine &NameStr) {
228 assert(getNumOperands() == Args.size() + 1 && "NumOperands not set up?");
232 assert((Args.size() == FTy->getNumParams() ||
233 (FTy->isVarArg() && Args.size() > FTy->getNumParams())) &&
234 "Calling a function with bad signature!");
236 for (unsigned i = 0; i != Args.size(); ++i)
237 assert((i >= FTy->getNumParams() ||
238 FTy->getParamType(i) == Args[i]->getType()) &&
239 "Calling a function with a bad signature!");
242 std::copy(Args.begin(), Args.end(), op_begin());
246 void CallInst::init(Value *Func, const Twine &NameStr) {
248 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
249 assert(getNumOperands() == 1 && "NumOperands not set up?");
252 assert(FTy->getNumParams() == 0 && "Calling a function with bad signature");
257 CallInst::CallInst(Value *Func, const Twine &Name,
258 Instruction *InsertBefore)
259 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
260 ->getElementType())->getReturnType(),
262 OperandTraits<CallInst>::op_end(this) - 1,
267 CallInst::CallInst(Value *Func, const Twine &Name,
268 BasicBlock *InsertAtEnd)
269 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
270 ->getElementType())->getReturnType(),
272 OperandTraits<CallInst>::op_end(this) - 1,
277 CallInst::CallInst(const CallInst &CI)
278 : Instruction(CI.getType(), Instruction::Call,
279 OperandTraits<CallInst>::op_end(this) - CI.getNumOperands(),
280 CI.getNumOperands()),
281 AttributeList(CI.AttributeList), FTy(CI.FTy) {
282 setTailCallKind(CI.getTailCallKind());
283 setCallingConv(CI.getCallingConv());
285 std::copy(CI.op_begin(), CI.op_end(), op_begin());
286 SubclassOptionalData = CI.SubclassOptionalData;
289 void CallInst::addAttribute(unsigned i, Attribute::AttrKind attr) {
290 AttributeSet PAL = getAttributes();
291 PAL = PAL.addAttribute(getContext(), i, attr);
295 void CallInst::removeAttribute(unsigned i, Attribute attr) {
296 AttributeSet PAL = getAttributes();
298 LLVMContext &Context = getContext();
299 PAL = PAL.removeAttributes(Context, i,
300 AttributeSet::get(Context, i, B));
304 void CallInst::addDereferenceableAttr(unsigned i, uint64_t Bytes) {
305 AttributeSet PAL = getAttributes();
306 PAL = PAL.addDereferenceableAttr(getContext(), i, Bytes);
310 void CallInst::addDereferenceableOrNullAttr(unsigned i, uint64_t Bytes) {
311 AttributeSet PAL = getAttributes();
312 PAL = PAL.addDereferenceableOrNullAttr(getContext(), i, Bytes);
316 bool CallInst::hasFnAttrImpl(Attribute::AttrKind A) const {
317 if (AttributeList.hasAttribute(AttributeSet::FunctionIndex, A))
319 if (const Function *F = getCalledFunction())
320 return F->getAttributes().hasAttribute(AttributeSet::FunctionIndex, A);
324 bool CallInst::paramHasAttr(unsigned i, Attribute::AttrKind A) const {
325 if (AttributeList.hasAttribute(i, A))
327 if (const Function *F = getCalledFunction())
328 return F->getAttributes().hasAttribute(i, A);
332 /// IsConstantOne - Return true only if val is constant int 1
333 static bool IsConstantOne(Value *val) {
334 assert(val && "IsConstantOne does not work with nullptr val");
335 const ConstantInt *CVal = dyn_cast<ConstantInt>(val);
336 return CVal && CVal->isOne();
339 static Instruction *createMalloc(Instruction *InsertBefore,
340 BasicBlock *InsertAtEnd, Type *IntPtrTy,
341 Type *AllocTy, Value *AllocSize,
342 Value *ArraySize, Function *MallocF,
344 assert(((!InsertBefore && InsertAtEnd) || (InsertBefore && !InsertAtEnd)) &&
345 "createMalloc needs either InsertBefore or InsertAtEnd");
347 // malloc(type) becomes:
348 // bitcast (i8* malloc(typeSize)) to type*
349 // malloc(type, arraySize) becomes:
350 // bitcast (i8 *malloc(typeSize*arraySize)) to type*
352 ArraySize = ConstantInt::get(IntPtrTy, 1);
353 else if (ArraySize->getType() != IntPtrTy) {
355 ArraySize = CastInst::CreateIntegerCast(ArraySize, IntPtrTy, false,
358 ArraySize = CastInst::CreateIntegerCast(ArraySize, IntPtrTy, false,
362 if (!IsConstantOne(ArraySize)) {
363 if (IsConstantOne(AllocSize)) {
364 AllocSize = ArraySize; // Operand * 1 = Operand
365 } else if (Constant *CO = dyn_cast<Constant>(ArraySize)) {
366 Constant *Scale = ConstantExpr::getIntegerCast(CO, IntPtrTy,
368 // Malloc arg is constant product of type size and array size
369 AllocSize = ConstantExpr::getMul(Scale, cast<Constant>(AllocSize));
371 // Multiply type size by the array size...
373 AllocSize = BinaryOperator::CreateMul(ArraySize, AllocSize,
374 "mallocsize", InsertBefore);
376 AllocSize = BinaryOperator::CreateMul(ArraySize, AllocSize,
377 "mallocsize", InsertAtEnd);
381 assert(AllocSize->getType() == IntPtrTy && "malloc arg is wrong size");
382 // Create the call to Malloc.
383 BasicBlock* BB = InsertBefore ? InsertBefore->getParent() : InsertAtEnd;
384 Module* M = BB->getParent()->getParent();
385 Type *BPTy = Type::getInt8PtrTy(BB->getContext());
386 Value *MallocFunc = MallocF;
388 // prototype malloc as "void *malloc(size_t)"
389 MallocFunc = M->getOrInsertFunction("malloc", BPTy, IntPtrTy, nullptr);
390 PointerType *AllocPtrType = PointerType::getUnqual(AllocTy);
391 CallInst *MCall = nullptr;
392 Instruction *Result = nullptr;
394 MCall = CallInst::Create(MallocFunc, AllocSize, "malloccall", InsertBefore);
396 if (Result->getType() != AllocPtrType)
397 // Create a cast instruction to convert to the right type...
398 Result = new BitCastInst(MCall, AllocPtrType, Name, InsertBefore);
400 MCall = CallInst::Create(MallocFunc, AllocSize, "malloccall");
402 if (Result->getType() != AllocPtrType) {
403 InsertAtEnd->getInstList().push_back(MCall);
404 // Create a cast instruction to convert to the right type...
405 Result = new BitCastInst(MCall, AllocPtrType, Name);
408 MCall->setTailCall();
409 if (Function *F = dyn_cast<Function>(MallocFunc)) {
410 MCall->setCallingConv(F->getCallingConv());
411 if (!F->doesNotAlias(0)) F->setDoesNotAlias(0);
413 assert(!MCall->getType()->isVoidTy() && "Malloc has void return type");
418 /// CreateMalloc - Generate the IR for a call to malloc:
419 /// 1. Compute the malloc call's argument as the specified type's size,
420 /// possibly multiplied by the array size if the array size is not
422 /// 2. Call malloc with that argument.
423 /// 3. Bitcast the result of the malloc call to the specified type.
424 Instruction *CallInst::CreateMalloc(Instruction *InsertBefore,
425 Type *IntPtrTy, Type *AllocTy,
426 Value *AllocSize, Value *ArraySize,
429 return createMalloc(InsertBefore, nullptr, IntPtrTy, AllocTy, AllocSize,
430 ArraySize, MallocF, Name);
433 /// CreateMalloc - Generate the IR for a call to malloc:
434 /// 1. Compute the malloc call's argument as the specified type's size,
435 /// possibly multiplied by the array size if the array size is not
437 /// 2. Call malloc with that argument.
438 /// 3. Bitcast the result of the malloc call to the specified type.
439 /// Note: This function does not add the bitcast to the basic block, that is the
440 /// responsibility of the caller.
441 Instruction *CallInst::CreateMalloc(BasicBlock *InsertAtEnd,
442 Type *IntPtrTy, Type *AllocTy,
443 Value *AllocSize, Value *ArraySize,
444 Function *MallocF, const Twine &Name) {
445 return createMalloc(nullptr, InsertAtEnd, IntPtrTy, AllocTy, AllocSize,
446 ArraySize, MallocF, Name);
449 static Instruction* createFree(Value* Source, Instruction *InsertBefore,
450 BasicBlock *InsertAtEnd) {
451 assert(((!InsertBefore && InsertAtEnd) || (InsertBefore && !InsertAtEnd)) &&
452 "createFree needs either InsertBefore or InsertAtEnd");
453 assert(Source->getType()->isPointerTy() &&
454 "Can not free something of nonpointer type!");
456 BasicBlock* BB = InsertBefore ? InsertBefore->getParent() : InsertAtEnd;
457 Module* M = BB->getParent()->getParent();
459 Type *VoidTy = Type::getVoidTy(M->getContext());
460 Type *IntPtrTy = Type::getInt8PtrTy(M->getContext());
461 // prototype free as "void free(void*)"
462 Value *FreeFunc = M->getOrInsertFunction("free", VoidTy, IntPtrTy, nullptr);
463 CallInst* Result = nullptr;
464 Value *PtrCast = Source;
466 if (Source->getType() != IntPtrTy)
467 PtrCast = new BitCastInst(Source, IntPtrTy, "", InsertBefore);
468 Result = CallInst::Create(FreeFunc, PtrCast, "", InsertBefore);
470 if (Source->getType() != IntPtrTy)
471 PtrCast = new BitCastInst(Source, IntPtrTy, "", InsertAtEnd);
472 Result = CallInst::Create(FreeFunc, PtrCast, "");
474 Result->setTailCall();
475 if (Function *F = dyn_cast<Function>(FreeFunc))
476 Result->setCallingConv(F->getCallingConv());
481 /// CreateFree - Generate the IR for a call to the builtin free function.
482 Instruction * CallInst::CreateFree(Value* Source, Instruction *InsertBefore) {
483 return createFree(Source, InsertBefore, nullptr);
486 /// CreateFree - Generate the IR for a call to the builtin free function.
487 /// Note: This function does not add the call to the basic block, that is the
488 /// responsibility of the caller.
489 Instruction* CallInst::CreateFree(Value* Source, BasicBlock *InsertAtEnd) {
490 Instruction* FreeCall = createFree(Source, nullptr, InsertAtEnd);
491 assert(FreeCall && "CreateFree did not create a CallInst");
495 //===----------------------------------------------------------------------===//
496 // InvokeInst Implementation
497 //===----------------------------------------------------------------------===//
499 void InvokeInst::init(FunctionType *FTy, Value *Fn, BasicBlock *IfNormal,
500 BasicBlock *IfException, ArrayRef<Value *> Args,
501 const Twine &NameStr) {
504 assert(getNumOperands() == 3 + Args.size() && "NumOperands not set up?");
507 Op<-1>() = IfException;
510 assert(((Args.size() == FTy->getNumParams()) ||
511 (FTy->isVarArg() && Args.size() > FTy->getNumParams())) &&
512 "Invoking a function with bad signature");
514 for (unsigned i = 0, e = Args.size(); i != e; i++)
515 assert((i >= FTy->getNumParams() ||
516 FTy->getParamType(i) == Args[i]->getType()) &&
517 "Invoking a function with a bad signature!");
520 std::copy(Args.begin(), Args.end(), op_begin());
524 InvokeInst::InvokeInst(const InvokeInst &II)
525 : TerminatorInst(II.getType(), Instruction::Invoke,
526 OperandTraits<InvokeInst>::op_end(this) -
528 II.getNumOperands()),
529 AttributeList(II.AttributeList), FTy(II.FTy) {
530 setCallingConv(II.getCallingConv());
531 std::copy(II.op_begin(), II.op_end(), op_begin());
532 SubclassOptionalData = II.SubclassOptionalData;
535 BasicBlock *InvokeInst::getSuccessorV(unsigned idx) const {
536 return getSuccessor(idx);
538 unsigned InvokeInst::getNumSuccessorsV() const {
539 return getNumSuccessors();
541 void InvokeInst::setSuccessorV(unsigned idx, BasicBlock *B) {
542 return setSuccessor(idx, B);
545 bool InvokeInst::hasFnAttrImpl(Attribute::AttrKind A) const {
546 if (AttributeList.hasAttribute(AttributeSet::FunctionIndex, A))
548 if (const Function *F = getCalledFunction())
549 return F->getAttributes().hasAttribute(AttributeSet::FunctionIndex, A);
553 bool InvokeInst::paramHasAttr(unsigned i, Attribute::AttrKind A) const {
554 if (AttributeList.hasAttribute(i, A))
556 if (const Function *F = getCalledFunction())
557 return F->getAttributes().hasAttribute(i, A);
561 void InvokeInst::addAttribute(unsigned i, Attribute::AttrKind attr) {
562 AttributeSet PAL = getAttributes();
563 PAL = PAL.addAttribute(getContext(), i, attr);
567 void InvokeInst::removeAttribute(unsigned i, Attribute attr) {
568 AttributeSet PAL = getAttributes();
570 PAL = PAL.removeAttributes(getContext(), i,
571 AttributeSet::get(getContext(), i, B));
575 void InvokeInst::addDereferenceableAttr(unsigned i, uint64_t Bytes) {
576 AttributeSet PAL = getAttributes();
577 PAL = PAL.addDereferenceableAttr(getContext(), i, Bytes);
581 void InvokeInst::addDereferenceableOrNullAttr(unsigned i, uint64_t Bytes) {
582 AttributeSet PAL = getAttributes();
583 PAL = PAL.addDereferenceableOrNullAttr(getContext(), i, Bytes);
587 LandingPadInst *InvokeInst::getLandingPadInst() const {
588 return cast<LandingPadInst>(getUnwindDest()->getFirstNonPHI());
591 //===----------------------------------------------------------------------===//
592 // ReturnInst Implementation
593 //===----------------------------------------------------------------------===//
595 ReturnInst::ReturnInst(const ReturnInst &RI)
596 : TerminatorInst(Type::getVoidTy(RI.getContext()), Instruction::Ret,
597 OperandTraits<ReturnInst>::op_end(this) -
599 RI.getNumOperands()) {
600 if (RI.getNumOperands())
601 Op<0>() = RI.Op<0>();
602 SubclassOptionalData = RI.SubclassOptionalData;
605 ReturnInst::ReturnInst(LLVMContext &C, Value *retVal, Instruction *InsertBefore)
606 : TerminatorInst(Type::getVoidTy(C), Instruction::Ret,
607 OperandTraits<ReturnInst>::op_end(this) - !!retVal, !!retVal,
612 ReturnInst::ReturnInst(LLVMContext &C, Value *retVal, BasicBlock *InsertAtEnd)
613 : TerminatorInst(Type::getVoidTy(C), Instruction::Ret,
614 OperandTraits<ReturnInst>::op_end(this) - !!retVal, !!retVal,
619 ReturnInst::ReturnInst(LLVMContext &Context, BasicBlock *InsertAtEnd)
620 : TerminatorInst(Type::getVoidTy(Context), Instruction::Ret,
621 OperandTraits<ReturnInst>::op_end(this), 0, InsertAtEnd) {
624 unsigned ReturnInst::getNumSuccessorsV() const {
625 return getNumSuccessors();
628 /// Out-of-line ReturnInst method, put here so the C++ compiler can choose to
629 /// emit the vtable for the class in this translation unit.
630 void ReturnInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
631 llvm_unreachable("ReturnInst has no successors!");
634 BasicBlock *ReturnInst::getSuccessorV(unsigned idx) const {
635 llvm_unreachable("ReturnInst has no successors!");
638 ReturnInst::~ReturnInst() {
641 //===----------------------------------------------------------------------===//
642 // ResumeInst Implementation
643 //===----------------------------------------------------------------------===//
645 ResumeInst::ResumeInst(const ResumeInst &RI)
646 : TerminatorInst(Type::getVoidTy(RI.getContext()), Instruction::Resume,
647 OperandTraits<ResumeInst>::op_begin(this), 1) {
648 Op<0>() = RI.Op<0>();
651 ResumeInst::ResumeInst(Value *Exn, Instruction *InsertBefore)
652 : TerminatorInst(Type::getVoidTy(Exn->getContext()), Instruction::Resume,
653 OperandTraits<ResumeInst>::op_begin(this), 1, InsertBefore) {
657 ResumeInst::ResumeInst(Value *Exn, BasicBlock *InsertAtEnd)
658 : TerminatorInst(Type::getVoidTy(Exn->getContext()), Instruction::Resume,
659 OperandTraits<ResumeInst>::op_begin(this), 1, InsertAtEnd) {
663 unsigned ResumeInst::getNumSuccessorsV() const {
664 return getNumSuccessors();
667 void ResumeInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
668 llvm_unreachable("ResumeInst has no successors!");
671 BasicBlock *ResumeInst::getSuccessorV(unsigned idx) const {
672 llvm_unreachable("ResumeInst has no successors!");
675 //===----------------------------------------------------------------------===//
676 // UnreachableInst Implementation
677 //===----------------------------------------------------------------------===//
679 UnreachableInst::UnreachableInst(LLVMContext &Context,
680 Instruction *InsertBefore)
681 : TerminatorInst(Type::getVoidTy(Context), Instruction::Unreachable,
682 nullptr, 0, InsertBefore) {
684 UnreachableInst::UnreachableInst(LLVMContext &Context, BasicBlock *InsertAtEnd)
685 : TerminatorInst(Type::getVoidTy(Context), Instruction::Unreachable,
686 nullptr, 0, InsertAtEnd) {
689 unsigned UnreachableInst::getNumSuccessorsV() const {
690 return getNumSuccessors();
693 void UnreachableInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
694 llvm_unreachable("UnreachableInst has no successors!");
697 BasicBlock *UnreachableInst::getSuccessorV(unsigned idx) const {
698 llvm_unreachable("UnreachableInst has no successors!");
701 //===----------------------------------------------------------------------===//
702 // BranchInst Implementation
703 //===----------------------------------------------------------------------===//
705 void BranchInst::AssertOK() {
707 assert(getCondition()->getType()->isIntegerTy(1) &&
708 "May only branch on boolean predicates!");
711 BranchInst::BranchInst(BasicBlock *IfTrue, Instruction *InsertBefore)
712 : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
713 OperandTraits<BranchInst>::op_end(this) - 1,
715 assert(IfTrue && "Branch destination may not be null!");
718 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
719 Instruction *InsertBefore)
720 : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
721 OperandTraits<BranchInst>::op_end(this) - 3,
731 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *InsertAtEnd)
732 : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
733 OperandTraits<BranchInst>::op_end(this) - 1,
735 assert(IfTrue && "Branch destination may not be null!");
739 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
740 BasicBlock *InsertAtEnd)
741 : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
742 OperandTraits<BranchInst>::op_end(this) - 3,
753 BranchInst::BranchInst(const BranchInst &BI) :
754 TerminatorInst(Type::getVoidTy(BI.getContext()), Instruction::Br,
755 OperandTraits<BranchInst>::op_end(this) - BI.getNumOperands(),
756 BI.getNumOperands()) {
757 Op<-1>() = BI.Op<-1>();
758 if (BI.getNumOperands() != 1) {
759 assert(BI.getNumOperands() == 3 && "BR can have 1 or 3 operands!");
760 Op<-3>() = BI.Op<-3>();
761 Op<-2>() = BI.Op<-2>();
763 SubclassOptionalData = BI.SubclassOptionalData;
766 void BranchInst::swapSuccessors() {
767 assert(isConditional() &&
768 "Cannot swap successors of an unconditional branch");
769 Op<-1>().swap(Op<-2>());
771 // Update profile metadata if present and it matches our structural
773 MDNode *ProfileData = getMetadata(LLVMContext::MD_prof);
774 if (!ProfileData || ProfileData->getNumOperands() != 3)
777 // The first operand is the name. Fetch them backwards and build a new one.
778 Metadata *Ops[] = {ProfileData->getOperand(0), ProfileData->getOperand(2),
779 ProfileData->getOperand(1)};
780 setMetadata(LLVMContext::MD_prof,
781 MDNode::get(ProfileData->getContext(), Ops));
784 BasicBlock *BranchInst::getSuccessorV(unsigned idx) const {
785 return getSuccessor(idx);
787 unsigned BranchInst::getNumSuccessorsV() const {
788 return getNumSuccessors();
790 void BranchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
791 setSuccessor(idx, B);
795 //===----------------------------------------------------------------------===//
796 // AllocaInst Implementation
797 //===----------------------------------------------------------------------===//
799 static Value *getAISize(LLVMContext &Context, Value *Amt) {
801 Amt = ConstantInt::get(Type::getInt32Ty(Context), 1);
803 assert(!isa<BasicBlock>(Amt) &&
804 "Passed basic block into allocation size parameter! Use other ctor");
805 assert(Amt->getType()->isIntegerTy() &&
806 "Allocation array size is not an integer!");
811 AllocaInst::AllocaInst(Type *Ty, const Twine &Name, Instruction *InsertBefore)
812 : AllocaInst(Ty, /*ArraySize=*/nullptr, Name, InsertBefore) {}
814 AllocaInst::AllocaInst(Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd)
815 : AllocaInst(Ty, /*ArraySize=*/nullptr, Name, InsertAtEnd) {}
817 AllocaInst::AllocaInst(Type *Ty, Value *ArraySize, const Twine &Name,
818 Instruction *InsertBefore)
819 : AllocaInst(Ty, ArraySize, /*Align=*/0, Name, InsertBefore) {}
821 AllocaInst::AllocaInst(Type *Ty, Value *ArraySize, const Twine &Name,
822 BasicBlock *InsertAtEnd)
823 : AllocaInst(Ty, ArraySize, /*Align=*/0, Name, InsertAtEnd) {}
825 AllocaInst::AllocaInst(Type *Ty, Value *ArraySize, unsigned Align,
826 const Twine &Name, Instruction *InsertBefore)
827 : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
828 getAISize(Ty->getContext(), ArraySize), InsertBefore),
831 assert(!Ty->isVoidTy() && "Cannot allocate void!");
835 AllocaInst::AllocaInst(Type *Ty, Value *ArraySize, unsigned Align,
836 const Twine &Name, BasicBlock *InsertAtEnd)
837 : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
838 getAISize(Ty->getContext(), ArraySize), InsertAtEnd),
841 assert(!Ty->isVoidTy() && "Cannot allocate void!");
845 // Out of line virtual method, so the vtable, etc has a home.
846 AllocaInst::~AllocaInst() {
849 void AllocaInst::setAlignment(unsigned Align) {
850 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
851 assert(Align <= MaximumAlignment &&
852 "Alignment is greater than MaximumAlignment!");
853 setInstructionSubclassData((getSubclassDataFromInstruction() & ~31) |
854 (Log2_32(Align) + 1));
855 assert(getAlignment() == Align && "Alignment representation error!");
858 bool AllocaInst::isArrayAllocation() const {
859 if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(0)))
864 /// isStaticAlloca - Return true if this alloca is in the entry block of the
865 /// function and is a constant size. If so, the code generator will fold it
866 /// into the prolog/epilog code, so it is basically free.
867 bool AllocaInst::isStaticAlloca() const {
868 // Must be constant size.
869 if (!isa<ConstantInt>(getArraySize())) return false;
871 // Must be in the entry block.
872 const BasicBlock *Parent = getParent();
873 return Parent == &Parent->getParent()->front() && !isUsedWithInAlloca();
876 //===----------------------------------------------------------------------===//
877 // LoadInst Implementation
878 //===----------------------------------------------------------------------===//
880 void LoadInst::AssertOK() {
881 assert(getOperand(0)->getType()->isPointerTy() &&
882 "Ptr must have pointer type.");
883 assert(!(isAtomic() && getAlignment() == 0) &&
884 "Alignment required for atomic load");
887 LoadInst::LoadInst(Value *Ptr, const Twine &Name, Instruction *InsertBef)
888 : LoadInst(Ptr, Name, /*isVolatile=*/false, InsertBef) {}
890 LoadInst::LoadInst(Value *Ptr, const Twine &Name, BasicBlock *InsertAE)
891 : LoadInst(Ptr, Name, /*isVolatile=*/false, InsertAE) {}
893 LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name, bool isVolatile,
894 Instruction *InsertBef)
895 : LoadInst(Ty, Ptr, Name, isVolatile, /*Align=*/0, InsertBef) {}
897 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
898 BasicBlock *InsertAE)
899 : LoadInst(Ptr, Name, isVolatile, /*Align=*/0, InsertAE) {}
901 LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name, bool isVolatile,
902 unsigned Align, Instruction *InsertBef)
903 : LoadInst(Ty, Ptr, Name, isVolatile, Align, NotAtomic, CrossThread,
906 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
907 unsigned Align, BasicBlock *InsertAE)
908 : LoadInst(Ptr, Name, isVolatile, Align, NotAtomic, CrossThread, InsertAE) {
911 LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name, bool isVolatile,
912 unsigned Align, AtomicOrdering Order,
913 SynchronizationScope SynchScope, Instruction *InsertBef)
914 : UnaryInstruction(Ty, Load, Ptr, InsertBef) {
915 assert(Ty == cast<PointerType>(Ptr->getType())->getElementType());
916 setVolatile(isVolatile);
918 setAtomic(Order, SynchScope);
923 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
924 unsigned Align, AtomicOrdering Order,
925 SynchronizationScope SynchScope,
926 BasicBlock *InsertAE)
927 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
928 Load, Ptr, InsertAE) {
929 setVolatile(isVolatile);
931 setAtomic(Order, SynchScope);
936 LoadInst::LoadInst(Value *Ptr, const char *Name, Instruction *InsertBef)
937 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
938 Load, Ptr, InsertBef) {
941 setAtomic(NotAtomic);
943 if (Name && Name[0]) setName(Name);
946 LoadInst::LoadInst(Value *Ptr, const char *Name, BasicBlock *InsertAE)
947 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
948 Load, Ptr, InsertAE) {
951 setAtomic(NotAtomic);
953 if (Name && Name[0]) setName(Name);
956 LoadInst::LoadInst(Type *Ty, Value *Ptr, const char *Name, bool isVolatile,
957 Instruction *InsertBef)
958 : UnaryInstruction(Ty, Load, Ptr, InsertBef) {
959 assert(Ty == cast<PointerType>(Ptr->getType())->getElementType());
960 setVolatile(isVolatile);
962 setAtomic(NotAtomic);
964 if (Name && Name[0]) setName(Name);
967 LoadInst::LoadInst(Value *Ptr, const char *Name, bool isVolatile,
968 BasicBlock *InsertAE)
969 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
970 Load, Ptr, InsertAE) {
971 setVolatile(isVolatile);
973 setAtomic(NotAtomic);
975 if (Name && Name[0]) setName(Name);
978 void LoadInst::setAlignment(unsigned Align) {
979 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
980 assert(Align <= MaximumAlignment &&
981 "Alignment is greater than MaximumAlignment!");
982 setInstructionSubclassData((getSubclassDataFromInstruction() & ~(31 << 1)) |
983 ((Log2_32(Align)+1)<<1));
984 assert(getAlignment() == Align && "Alignment representation error!");
987 //===----------------------------------------------------------------------===//
988 // StoreInst Implementation
989 //===----------------------------------------------------------------------===//
991 void StoreInst::AssertOK() {
992 assert(getOperand(0) && getOperand(1) && "Both operands must be non-null!");
993 assert(getOperand(1)->getType()->isPointerTy() &&
994 "Ptr must have pointer type!");
995 assert(getOperand(0)->getType() ==
996 cast<PointerType>(getOperand(1)->getType())->getElementType()
997 && "Ptr must be a pointer to Val type!");
998 assert(!(isAtomic() && getAlignment() == 0) &&
999 "Alignment required for atomic store");
1002 StoreInst::StoreInst(Value *val, Value *addr, Instruction *InsertBefore)
1003 : StoreInst(val, addr, /*isVolatile=*/false, InsertBefore) {}
1005 StoreInst::StoreInst(Value *val, Value *addr, BasicBlock *InsertAtEnd)
1006 : StoreInst(val, addr, /*isVolatile=*/false, InsertAtEnd) {}
1008 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1009 Instruction *InsertBefore)
1010 : StoreInst(val, addr, isVolatile, /*Align=*/0, InsertBefore) {}
1012 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1013 BasicBlock *InsertAtEnd)
1014 : StoreInst(val, addr, isVolatile, /*Align=*/0, InsertAtEnd) {}
1016 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile, unsigned Align,
1017 Instruction *InsertBefore)
1018 : StoreInst(val, addr, isVolatile, Align, NotAtomic, CrossThread,
1021 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile, unsigned Align,
1022 BasicBlock *InsertAtEnd)
1023 : StoreInst(val, addr, isVolatile, Align, NotAtomic, CrossThread,
1026 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1027 unsigned Align, AtomicOrdering Order,
1028 SynchronizationScope SynchScope,
1029 Instruction *InsertBefore)
1030 : Instruction(Type::getVoidTy(val->getContext()), Store,
1031 OperandTraits<StoreInst>::op_begin(this),
1032 OperandTraits<StoreInst>::operands(this),
1036 setVolatile(isVolatile);
1037 setAlignment(Align);
1038 setAtomic(Order, SynchScope);
1042 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1043 unsigned Align, AtomicOrdering Order,
1044 SynchronizationScope SynchScope,
1045 BasicBlock *InsertAtEnd)
1046 : Instruction(Type::getVoidTy(val->getContext()), Store,
1047 OperandTraits<StoreInst>::op_begin(this),
1048 OperandTraits<StoreInst>::operands(this),
1052 setVolatile(isVolatile);
1053 setAlignment(Align);
1054 setAtomic(Order, SynchScope);
1058 void StoreInst::setAlignment(unsigned Align) {
1059 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
1060 assert(Align <= MaximumAlignment &&
1061 "Alignment is greater than MaximumAlignment!");
1062 setInstructionSubclassData((getSubclassDataFromInstruction() & ~(31 << 1)) |
1063 ((Log2_32(Align)+1) << 1));
1064 assert(getAlignment() == Align && "Alignment representation error!");
1067 //===----------------------------------------------------------------------===//
1068 // AtomicCmpXchgInst Implementation
1069 //===----------------------------------------------------------------------===//
1071 void AtomicCmpXchgInst::Init(Value *Ptr, Value *Cmp, Value *NewVal,
1072 AtomicOrdering SuccessOrdering,
1073 AtomicOrdering FailureOrdering,
1074 SynchronizationScope SynchScope) {
1078 setSuccessOrdering(SuccessOrdering);
1079 setFailureOrdering(FailureOrdering);
1080 setSynchScope(SynchScope);
1082 assert(getOperand(0) && getOperand(1) && getOperand(2) &&
1083 "All operands must be non-null!");
1084 assert(getOperand(0)->getType()->isPointerTy() &&
1085 "Ptr must have pointer type!");
1086 assert(getOperand(1)->getType() ==
1087 cast<PointerType>(getOperand(0)->getType())->getElementType()
1088 && "Ptr must be a pointer to Cmp type!");
1089 assert(getOperand(2)->getType() ==
1090 cast<PointerType>(getOperand(0)->getType())->getElementType()
1091 && "Ptr must be a pointer to NewVal type!");
1092 assert(SuccessOrdering != NotAtomic &&
1093 "AtomicCmpXchg instructions must be atomic!");
1094 assert(FailureOrdering != NotAtomic &&
1095 "AtomicCmpXchg instructions must be atomic!");
1096 assert(SuccessOrdering >= FailureOrdering &&
1097 "AtomicCmpXchg success ordering must be at least as strong as fail");
1098 assert(FailureOrdering != Release && FailureOrdering != AcquireRelease &&
1099 "AtomicCmpXchg failure ordering cannot include release semantics");
1102 AtomicCmpXchgInst::AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal,
1103 AtomicOrdering SuccessOrdering,
1104 AtomicOrdering FailureOrdering,
1105 SynchronizationScope SynchScope,
1106 Instruction *InsertBefore)
1108 StructType::get(Cmp->getType(), Type::getInt1Ty(Cmp->getContext()),
1110 AtomicCmpXchg, OperandTraits<AtomicCmpXchgInst>::op_begin(this),
1111 OperandTraits<AtomicCmpXchgInst>::operands(this), InsertBefore) {
1112 Init(Ptr, Cmp, NewVal, SuccessOrdering, FailureOrdering, SynchScope);
1115 AtomicCmpXchgInst::AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal,
1116 AtomicOrdering SuccessOrdering,
1117 AtomicOrdering FailureOrdering,
1118 SynchronizationScope SynchScope,
1119 BasicBlock *InsertAtEnd)
1121 StructType::get(Cmp->getType(), Type::getInt1Ty(Cmp->getContext()),
1123 AtomicCmpXchg, OperandTraits<AtomicCmpXchgInst>::op_begin(this),
1124 OperandTraits<AtomicCmpXchgInst>::operands(this), InsertAtEnd) {
1125 Init(Ptr, Cmp, NewVal, SuccessOrdering, FailureOrdering, SynchScope);
1128 //===----------------------------------------------------------------------===//
1129 // AtomicRMWInst Implementation
1130 //===----------------------------------------------------------------------===//
1132 void AtomicRMWInst::Init(BinOp Operation, Value *Ptr, Value *Val,
1133 AtomicOrdering Ordering,
1134 SynchronizationScope SynchScope) {
1137 setOperation(Operation);
1138 setOrdering(Ordering);
1139 setSynchScope(SynchScope);
1141 assert(getOperand(0) && getOperand(1) &&
1142 "All operands must be non-null!");
1143 assert(getOperand(0)->getType()->isPointerTy() &&
1144 "Ptr must have pointer type!");
1145 assert(getOperand(1)->getType() ==
1146 cast<PointerType>(getOperand(0)->getType())->getElementType()
1147 && "Ptr must be a pointer to Val type!");
1148 assert(Ordering != NotAtomic &&
1149 "AtomicRMW instructions must be atomic!");
1152 AtomicRMWInst::AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val,
1153 AtomicOrdering Ordering,
1154 SynchronizationScope SynchScope,
1155 Instruction *InsertBefore)
1156 : Instruction(Val->getType(), AtomicRMW,
1157 OperandTraits<AtomicRMWInst>::op_begin(this),
1158 OperandTraits<AtomicRMWInst>::operands(this),
1160 Init(Operation, Ptr, Val, Ordering, SynchScope);
1163 AtomicRMWInst::AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val,
1164 AtomicOrdering Ordering,
1165 SynchronizationScope SynchScope,
1166 BasicBlock *InsertAtEnd)
1167 : Instruction(Val->getType(), AtomicRMW,
1168 OperandTraits<AtomicRMWInst>::op_begin(this),
1169 OperandTraits<AtomicRMWInst>::operands(this),
1171 Init(Operation, Ptr, Val, Ordering, SynchScope);
1174 //===----------------------------------------------------------------------===//
1175 // FenceInst Implementation
1176 //===----------------------------------------------------------------------===//
1178 FenceInst::FenceInst(LLVMContext &C, AtomicOrdering Ordering,
1179 SynchronizationScope SynchScope,
1180 Instruction *InsertBefore)
1181 : Instruction(Type::getVoidTy(C), Fence, nullptr, 0, InsertBefore) {
1182 setOrdering(Ordering);
1183 setSynchScope(SynchScope);
1186 FenceInst::FenceInst(LLVMContext &C, AtomicOrdering Ordering,
1187 SynchronizationScope SynchScope,
1188 BasicBlock *InsertAtEnd)
1189 : Instruction(Type::getVoidTy(C), Fence, nullptr, 0, InsertAtEnd) {
1190 setOrdering(Ordering);
1191 setSynchScope(SynchScope);
1194 //===----------------------------------------------------------------------===//
1195 // GetElementPtrInst Implementation
1196 //===----------------------------------------------------------------------===//
1198 void GetElementPtrInst::init(Value *Ptr, ArrayRef<Value *> IdxList,
1199 const Twine &Name) {
1200 assert(getNumOperands() == 1 + IdxList.size() &&
1201 "NumOperands not initialized?");
1203 std::copy(IdxList.begin(), IdxList.end(), op_begin() + 1);
1207 GetElementPtrInst::GetElementPtrInst(const GetElementPtrInst &GEPI)
1208 : Instruction(GEPI.getType(), GetElementPtr,
1209 OperandTraits<GetElementPtrInst>::op_end(this) -
1210 GEPI.getNumOperands(),
1211 GEPI.getNumOperands()),
1212 SourceElementType(GEPI.SourceElementType),
1213 ResultElementType(GEPI.ResultElementType) {
1214 std::copy(GEPI.op_begin(), GEPI.op_end(), op_begin());
1215 SubclassOptionalData = GEPI.SubclassOptionalData;
1218 /// getIndexedType - Returns the type of the element that would be accessed with
1219 /// a gep instruction with the specified parameters.
1221 /// The Idxs pointer should point to a continuous piece of memory containing the
1222 /// indices, either as Value* or uint64_t.
1224 /// A null type is returned if the indices are invalid for the specified
1227 template <typename IndexTy>
1228 static Type *getIndexedTypeInternal(Type *Agg, ArrayRef<IndexTy> IdxList) {
1229 // Handle the special case of the empty set index set, which is always valid.
1230 if (IdxList.empty())
1233 // If there is at least one index, the top level type must be sized, otherwise
1234 // it cannot be 'stepped over'.
1235 if (!Agg->isSized())
1238 unsigned CurIdx = 1;
1239 for (; CurIdx != IdxList.size(); ++CurIdx) {
1240 CompositeType *CT = dyn_cast<CompositeType>(Agg);
1241 if (!CT || CT->isPointerTy()) return nullptr;
1242 IndexTy Index = IdxList[CurIdx];
1243 if (!CT->indexValid(Index)) return nullptr;
1244 Agg = CT->getTypeAtIndex(Index);
1246 return CurIdx == IdxList.size() ? Agg : nullptr;
1249 Type *GetElementPtrInst::getIndexedType(Type *Ty, ArrayRef<Value *> IdxList) {
1250 return getIndexedTypeInternal(Ty, IdxList);
1253 Type *GetElementPtrInst::getIndexedType(Type *Ty,
1254 ArrayRef<Constant *> IdxList) {
1255 return getIndexedTypeInternal(Ty, IdxList);
1258 Type *GetElementPtrInst::getIndexedType(Type *Ty, ArrayRef<uint64_t> IdxList) {
1259 return getIndexedTypeInternal(Ty, IdxList);
1262 /// hasAllZeroIndices - Return true if all of the indices of this GEP are
1263 /// zeros. If so, the result pointer and the first operand have the same
1264 /// value, just potentially different types.
1265 bool GetElementPtrInst::hasAllZeroIndices() const {
1266 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1267 if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(i))) {
1268 if (!CI->isZero()) return false;
1276 /// hasAllConstantIndices - Return true if all of the indices of this GEP are
1277 /// constant integers. If so, the result pointer and the first operand have
1278 /// a constant offset between them.
1279 bool GetElementPtrInst::hasAllConstantIndices() const {
1280 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1281 if (!isa<ConstantInt>(getOperand(i)))
1287 void GetElementPtrInst::setIsInBounds(bool B) {
1288 cast<GEPOperator>(this)->setIsInBounds(B);
1291 bool GetElementPtrInst::isInBounds() const {
1292 return cast<GEPOperator>(this)->isInBounds();
1295 bool GetElementPtrInst::accumulateConstantOffset(const DataLayout &DL,
1296 APInt &Offset) const {
1297 // Delegate to the generic GEPOperator implementation.
1298 return cast<GEPOperator>(this)->accumulateConstantOffset(DL, Offset);
1301 //===----------------------------------------------------------------------===//
1302 // ExtractElementInst Implementation
1303 //===----------------------------------------------------------------------===//
1305 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
1307 Instruction *InsertBef)
1308 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1310 OperandTraits<ExtractElementInst>::op_begin(this),
1312 assert(isValidOperands(Val, Index) &&
1313 "Invalid extractelement instruction operands!");
1319 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
1321 BasicBlock *InsertAE)
1322 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1324 OperandTraits<ExtractElementInst>::op_begin(this),
1326 assert(isValidOperands(Val, Index) &&
1327 "Invalid extractelement instruction operands!");
1335 bool ExtractElementInst::isValidOperands(const Value *Val, const Value *Index) {
1336 if (!Val->getType()->isVectorTy() || !Index->getType()->isIntegerTy())
1342 //===----------------------------------------------------------------------===//
1343 // InsertElementInst Implementation
1344 //===----------------------------------------------------------------------===//
1346 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
1348 Instruction *InsertBef)
1349 : Instruction(Vec->getType(), InsertElement,
1350 OperandTraits<InsertElementInst>::op_begin(this),
1352 assert(isValidOperands(Vec, Elt, Index) &&
1353 "Invalid insertelement instruction operands!");
1360 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
1362 BasicBlock *InsertAE)
1363 : Instruction(Vec->getType(), InsertElement,
1364 OperandTraits<InsertElementInst>::op_begin(this),
1366 assert(isValidOperands(Vec, Elt, Index) &&
1367 "Invalid insertelement instruction operands!");
1375 bool InsertElementInst::isValidOperands(const Value *Vec, const Value *Elt,
1376 const Value *Index) {
1377 if (!Vec->getType()->isVectorTy())
1378 return false; // First operand of insertelement must be vector type.
1380 if (Elt->getType() != cast<VectorType>(Vec->getType())->getElementType())
1381 return false;// Second operand of insertelement must be vector element type.
1383 if (!Index->getType()->isIntegerTy())
1384 return false; // Third operand of insertelement must be i32.
1389 //===----------------------------------------------------------------------===//
1390 // ShuffleVectorInst Implementation
1391 //===----------------------------------------------------------------------===//
1393 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1395 Instruction *InsertBefore)
1396 : Instruction(VectorType::get(cast<VectorType>(V1->getType())->getElementType(),
1397 cast<VectorType>(Mask->getType())->getNumElements()),
1399 OperandTraits<ShuffleVectorInst>::op_begin(this),
1400 OperandTraits<ShuffleVectorInst>::operands(this),
1402 assert(isValidOperands(V1, V2, Mask) &&
1403 "Invalid shuffle vector instruction operands!");
1410 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1412 BasicBlock *InsertAtEnd)
1413 : Instruction(VectorType::get(cast<VectorType>(V1->getType())->getElementType(),
1414 cast<VectorType>(Mask->getType())->getNumElements()),
1416 OperandTraits<ShuffleVectorInst>::op_begin(this),
1417 OperandTraits<ShuffleVectorInst>::operands(this),
1419 assert(isValidOperands(V1, V2, Mask) &&
1420 "Invalid shuffle vector instruction operands!");
1428 bool ShuffleVectorInst::isValidOperands(const Value *V1, const Value *V2,
1429 const Value *Mask) {
1430 // V1 and V2 must be vectors of the same type.
1431 if (!V1->getType()->isVectorTy() || V1->getType() != V2->getType())
1434 // Mask must be vector of i32.
1435 VectorType *MaskTy = dyn_cast<VectorType>(Mask->getType());
1436 if (!MaskTy || !MaskTy->getElementType()->isIntegerTy(32))
1439 // Check to see if Mask is valid.
1440 if (isa<UndefValue>(Mask) || isa<ConstantAggregateZero>(Mask))
1443 if (const ConstantVector *MV = dyn_cast<ConstantVector>(Mask)) {
1444 unsigned V1Size = cast<VectorType>(V1->getType())->getNumElements();
1445 for (Value *Op : MV->operands()) {
1446 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
1447 if (CI->uge(V1Size*2))
1449 } else if (!isa<UndefValue>(Op)) {
1456 if (const ConstantDataSequential *CDS =
1457 dyn_cast<ConstantDataSequential>(Mask)) {
1458 unsigned V1Size = cast<VectorType>(V1->getType())->getNumElements();
1459 for (unsigned i = 0, e = MaskTy->getNumElements(); i != e; ++i)
1460 if (CDS->getElementAsInteger(i) >= V1Size*2)
1465 // The bitcode reader can create a place holder for a forward reference
1466 // used as the shuffle mask. When this occurs, the shuffle mask will
1467 // fall into this case and fail. To avoid this error, do this bit of
1468 // ugliness to allow such a mask pass.
1469 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(Mask))
1470 if (CE->getOpcode() == Instruction::UserOp1)
1476 /// getMaskValue - Return the index from the shuffle mask for the specified
1477 /// output result. This is either -1 if the element is undef or a number less
1478 /// than 2*numelements.
1479 int ShuffleVectorInst::getMaskValue(Constant *Mask, unsigned i) {
1480 assert(i < Mask->getType()->getVectorNumElements() && "Index out of range");
1481 if (ConstantDataSequential *CDS =dyn_cast<ConstantDataSequential>(Mask))
1482 return CDS->getElementAsInteger(i);
1483 Constant *C = Mask->getAggregateElement(i);
1484 if (isa<UndefValue>(C))
1486 return cast<ConstantInt>(C)->getZExtValue();
1489 /// getShuffleMask - Return the full mask for this instruction, where each
1490 /// element is the element number and undef's are returned as -1.
1491 void ShuffleVectorInst::getShuffleMask(Constant *Mask,
1492 SmallVectorImpl<int> &Result) {
1493 unsigned NumElts = Mask->getType()->getVectorNumElements();
1495 if (ConstantDataSequential *CDS=dyn_cast<ConstantDataSequential>(Mask)) {
1496 for (unsigned i = 0; i != NumElts; ++i)
1497 Result.push_back(CDS->getElementAsInteger(i));
1500 for (unsigned i = 0; i != NumElts; ++i) {
1501 Constant *C = Mask->getAggregateElement(i);
1502 Result.push_back(isa<UndefValue>(C) ? -1 :
1503 cast<ConstantInt>(C)->getZExtValue());
1508 //===----------------------------------------------------------------------===//
1509 // InsertValueInst Class
1510 //===----------------------------------------------------------------------===//
1512 void InsertValueInst::init(Value *Agg, Value *Val, ArrayRef<unsigned> Idxs,
1513 const Twine &Name) {
1514 assert(getNumOperands() == 2 && "NumOperands not initialized?");
1516 // There's no fundamental reason why we require at least one index
1517 // (other than weirdness with &*IdxBegin being invalid; see
1518 // getelementptr's init routine for example). But there's no
1519 // present need to support it.
1520 assert(Idxs.size() > 0 && "InsertValueInst must have at least one index");
1522 assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs) ==
1523 Val->getType() && "Inserted value must match indexed type!");
1527 Indices.append(Idxs.begin(), Idxs.end());
1531 InsertValueInst::InsertValueInst(const InsertValueInst &IVI)
1532 : Instruction(IVI.getType(), InsertValue,
1533 OperandTraits<InsertValueInst>::op_begin(this), 2),
1534 Indices(IVI.Indices) {
1535 Op<0>() = IVI.getOperand(0);
1536 Op<1>() = IVI.getOperand(1);
1537 SubclassOptionalData = IVI.SubclassOptionalData;
1540 //===----------------------------------------------------------------------===//
1541 // ExtractValueInst Class
1542 //===----------------------------------------------------------------------===//
1544 void ExtractValueInst::init(ArrayRef<unsigned> Idxs, const Twine &Name) {
1545 assert(getNumOperands() == 1 && "NumOperands not initialized?");
1547 // There's no fundamental reason why we require at least one index.
1548 // But there's no present need to support it.
1549 assert(Idxs.size() > 0 && "ExtractValueInst must have at least one index");
1551 Indices.append(Idxs.begin(), Idxs.end());
1555 ExtractValueInst::ExtractValueInst(const ExtractValueInst &EVI)
1556 : UnaryInstruction(EVI.getType(), ExtractValue, EVI.getOperand(0)),
1557 Indices(EVI.Indices) {
1558 SubclassOptionalData = EVI.SubclassOptionalData;
1561 // getIndexedType - Returns the type of the element that would be extracted
1562 // with an extractvalue instruction with the specified parameters.
1564 // A null type is returned if the indices are invalid for the specified
1567 Type *ExtractValueInst::getIndexedType(Type *Agg,
1568 ArrayRef<unsigned> Idxs) {
1569 for (unsigned Index : Idxs) {
1570 // We can't use CompositeType::indexValid(Index) here.
1571 // indexValid() always returns true for arrays because getelementptr allows
1572 // out-of-bounds indices. Since we don't allow those for extractvalue and
1573 // insertvalue we need to check array indexing manually.
1574 // Since the only other types we can index into are struct types it's just
1575 // as easy to check those manually as well.
1576 if (ArrayType *AT = dyn_cast<ArrayType>(Agg)) {
1577 if (Index >= AT->getNumElements())
1579 } else if (StructType *ST = dyn_cast<StructType>(Agg)) {
1580 if (Index >= ST->getNumElements())
1583 // Not a valid type to index into.
1587 Agg = cast<CompositeType>(Agg)->getTypeAtIndex(Index);
1589 return const_cast<Type*>(Agg);
1592 //===----------------------------------------------------------------------===//
1593 // BinaryOperator Class
1594 //===----------------------------------------------------------------------===//
1596 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
1597 Type *Ty, const Twine &Name,
1598 Instruction *InsertBefore)
1599 : Instruction(Ty, iType,
1600 OperandTraits<BinaryOperator>::op_begin(this),
1601 OperandTraits<BinaryOperator>::operands(this),
1609 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
1610 Type *Ty, const Twine &Name,
1611 BasicBlock *InsertAtEnd)
1612 : Instruction(Ty, iType,
1613 OperandTraits<BinaryOperator>::op_begin(this),
1614 OperandTraits<BinaryOperator>::operands(this),
1623 void BinaryOperator::init(BinaryOps iType) {
1624 Value *LHS = getOperand(0), *RHS = getOperand(1);
1625 (void)LHS; (void)RHS; // Silence warnings.
1626 assert(LHS->getType() == RHS->getType() &&
1627 "Binary operator operand types must match!");
1632 assert(getType() == LHS->getType() &&
1633 "Arithmetic operation should return same type as operands!");
1634 assert(getType()->isIntOrIntVectorTy() &&
1635 "Tried to create an integer operation on a non-integer type!");
1637 case FAdd: case FSub:
1639 assert(getType() == LHS->getType() &&
1640 "Arithmetic operation should return same type as operands!");
1641 assert(getType()->isFPOrFPVectorTy() &&
1642 "Tried to create a floating-point operation on a "
1643 "non-floating-point type!");
1647 assert(getType() == LHS->getType() &&
1648 "Arithmetic operation should return same type as operands!");
1649 assert((getType()->isIntegerTy() || (getType()->isVectorTy() &&
1650 cast<VectorType>(getType())->getElementType()->isIntegerTy())) &&
1651 "Incorrect operand type (not integer) for S/UDIV");
1654 assert(getType() == LHS->getType() &&
1655 "Arithmetic operation should return same type as operands!");
1656 assert(getType()->isFPOrFPVectorTy() &&
1657 "Incorrect operand type (not floating point) for FDIV");
1661 assert(getType() == LHS->getType() &&
1662 "Arithmetic operation should return same type as operands!");
1663 assert((getType()->isIntegerTy() || (getType()->isVectorTy() &&
1664 cast<VectorType>(getType())->getElementType()->isIntegerTy())) &&
1665 "Incorrect operand type (not integer) for S/UREM");
1668 assert(getType() == LHS->getType() &&
1669 "Arithmetic operation should return same type as operands!");
1670 assert(getType()->isFPOrFPVectorTy() &&
1671 "Incorrect operand type (not floating point) for FREM");
1676 assert(getType() == LHS->getType() &&
1677 "Shift operation should return same type as operands!");
1678 assert((getType()->isIntegerTy() ||
1679 (getType()->isVectorTy() &&
1680 cast<VectorType>(getType())->getElementType()->isIntegerTy())) &&
1681 "Tried to create a shift operation on a non-integral type!");
1685 assert(getType() == LHS->getType() &&
1686 "Logical operation should return same type as operands!");
1687 assert((getType()->isIntegerTy() ||
1688 (getType()->isVectorTy() &&
1689 cast<VectorType>(getType())->getElementType()->isIntegerTy())) &&
1690 "Tried to create a logical operation on a non-integral type!");
1698 BinaryOperator *BinaryOperator::Create(BinaryOps Op, Value *S1, Value *S2,
1700 Instruction *InsertBefore) {
1701 assert(S1->getType() == S2->getType() &&
1702 "Cannot create binary operator with two operands of differing type!");
1703 return new BinaryOperator(Op, S1, S2, S1->getType(), Name, InsertBefore);
1706 BinaryOperator *BinaryOperator::Create(BinaryOps Op, Value *S1, Value *S2,
1708 BasicBlock *InsertAtEnd) {
1709 BinaryOperator *Res = Create(Op, S1, S2, Name);
1710 InsertAtEnd->getInstList().push_back(Res);
1714 BinaryOperator *BinaryOperator::CreateNeg(Value *Op, const Twine &Name,
1715 Instruction *InsertBefore) {
1716 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1717 return new BinaryOperator(Instruction::Sub,
1719 Op->getType(), Name, InsertBefore);
1722 BinaryOperator *BinaryOperator::CreateNeg(Value *Op, const Twine &Name,
1723 BasicBlock *InsertAtEnd) {
1724 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1725 return new BinaryOperator(Instruction::Sub,
1727 Op->getType(), Name, InsertAtEnd);
1730 BinaryOperator *BinaryOperator::CreateNSWNeg(Value *Op, const Twine &Name,
1731 Instruction *InsertBefore) {
1732 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1733 return BinaryOperator::CreateNSWSub(zero, Op, Name, InsertBefore);
1736 BinaryOperator *BinaryOperator::CreateNSWNeg(Value *Op, const Twine &Name,
1737 BasicBlock *InsertAtEnd) {
1738 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1739 return BinaryOperator::CreateNSWSub(zero, Op, Name, InsertAtEnd);
1742 BinaryOperator *BinaryOperator::CreateNUWNeg(Value *Op, const Twine &Name,
1743 Instruction *InsertBefore) {
1744 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1745 return BinaryOperator::CreateNUWSub(zero, Op, Name, InsertBefore);
1748 BinaryOperator *BinaryOperator::CreateNUWNeg(Value *Op, const Twine &Name,
1749 BasicBlock *InsertAtEnd) {
1750 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1751 return BinaryOperator::CreateNUWSub(zero, Op, Name, InsertAtEnd);
1754 BinaryOperator *BinaryOperator::CreateFNeg(Value *Op, const Twine &Name,
1755 Instruction *InsertBefore) {
1756 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1757 return new BinaryOperator(Instruction::FSub, zero, Op,
1758 Op->getType(), Name, InsertBefore);
1761 BinaryOperator *BinaryOperator::CreateFNeg(Value *Op, const Twine &Name,
1762 BasicBlock *InsertAtEnd) {
1763 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1764 return new BinaryOperator(Instruction::FSub, zero, Op,
1765 Op->getType(), Name, InsertAtEnd);
1768 BinaryOperator *BinaryOperator::CreateNot(Value *Op, const Twine &Name,
1769 Instruction *InsertBefore) {
1770 Constant *C = Constant::getAllOnesValue(Op->getType());
1771 return new BinaryOperator(Instruction::Xor, Op, C,
1772 Op->getType(), Name, InsertBefore);
1775 BinaryOperator *BinaryOperator::CreateNot(Value *Op, const Twine &Name,
1776 BasicBlock *InsertAtEnd) {
1777 Constant *AllOnes = Constant::getAllOnesValue(Op->getType());
1778 return new BinaryOperator(Instruction::Xor, Op, AllOnes,
1779 Op->getType(), Name, InsertAtEnd);
1783 // isConstantAllOnes - Helper function for several functions below
1784 static inline bool isConstantAllOnes(const Value *V) {
1785 if (const Constant *C = dyn_cast<Constant>(V))
1786 return C->isAllOnesValue();
1790 bool BinaryOperator::isNeg(const Value *V) {
1791 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1792 if (Bop->getOpcode() == Instruction::Sub)
1793 if (Constant* C = dyn_cast<Constant>(Bop->getOperand(0)))
1794 return C->isNegativeZeroValue();
1798 bool BinaryOperator::isFNeg(const Value *V, bool IgnoreZeroSign) {
1799 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1800 if (Bop->getOpcode() == Instruction::FSub)
1801 if (Constant* C = dyn_cast<Constant>(Bop->getOperand(0))) {
1802 if (!IgnoreZeroSign)
1803 IgnoreZeroSign = cast<Instruction>(V)->hasNoSignedZeros();
1804 return !IgnoreZeroSign ? C->isNegativeZeroValue() : C->isZeroValue();
1809 bool BinaryOperator::isNot(const Value *V) {
1810 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1811 return (Bop->getOpcode() == Instruction::Xor &&
1812 (isConstantAllOnes(Bop->getOperand(1)) ||
1813 isConstantAllOnes(Bop->getOperand(0))));
1817 Value *BinaryOperator::getNegArgument(Value *BinOp) {
1818 return cast<BinaryOperator>(BinOp)->getOperand(1);
1821 const Value *BinaryOperator::getNegArgument(const Value *BinOp) {
1822 return getNegArgument(const_cast<Value*>(BinOp));
1825 Value *BinaryOperator::getFNegArgument(Value *BinOp) {
1826 return cast<BinaryOperator>(BinOp)->getOperand(1);
1829 const Value *BinaryOperator::getFNegArgument(const Value *BinOp) {
1830 return getFNegArgument(const_cast<Value*>(BinOp));
1833 Value *BinaryOperator::getNotArgument(Value *BinOp) {
1834 assert(isNot(BinOp) && "getNotArgument on non-'not' instruction!");
1835 BinaryOperator *BO = cast<BinaryOperator>(BinOp);
1836 Value *Op0 = BO->getOperand(0);
1837 Value *Op1 = BO->getOperand(1);
1838 if (isConstantAllOnes(Op0)) return Op1;
1840 assert(isConstantAllOnes(Op1));
1844 const Value *BinaryOperator::getNotArgument(const Value *BinOp) {
1845 return getNotArgument(const_cast<Value*>(BinOp));
1849 // swapOperands - Exchange the two operands to this instruction. This
1850 // instruction is safe to use on any binary instruction and does not
1851 // modify the semantics of the instruction. If the instruction is
1852 // order dependent (SetLT f.e.) the opcode is changed.
1854 bool BinaryOperator::swapOperands() {
1855 if (!isCommutative())
1856 return true; // Can't commute operands
1857 Op<0>().swap(Op<1>());
1861 void BinaryOperator::setHasNoUnsignedWrap(bool b) {
1862 cast<OverflowingBinaryOperator>(this)->setHasNoUnsignedWrap(b);
1865 void BinaryOperator::setHasNoSignedWrap(bool b) {
1866 cast<OverflowingBinaryOperator>(this)->setHasNoSignedWrap(b);
1869 void BinaryOperator::setIsExact(bool b) {
1870 cast<PossiblyExactOperator>(this)->setIsExact(b);
1873 bool BinaryOperator::hasNoUnsignedWrap() const {
1874 return cast<OverflowingBinaryOperator>(this)->hasNoUnsignedWrap();
1877 bool BinaryOperator::hasNoSignedWrap() const {
1878 return cast<OverflowingBinaryOperator>(this)->hasNoSignedWrap();
1881 bool BinaryOperator::isExact() const {
1882 return cast<PossiblyExactOperator>(this)->isExact();
1885 void BinaryOperator::copyIRFlags(const Value *V) {
1886 // Copy the wrapping flags.
1887 if (auto *OB = dyn_cast<OverflowingBinaryOperator>(V)) {
1888 setHasNoSignedWrap(OB->hasNoSignedWrap());
1889 setHasNoUnsignedWrap(OB->hasNoUnsignedWrap());
1892 // Copy the exact flag.
1893 if (auto *PE = dyn_cast<PossiblyExactOperator>(V))
1894 setIsExact(PE->isExact());
1896 // Copy the fast-math flags.
1897 if (auto *FP = dyn_cast<FPMathOperator>(V))
1898 copyFastMathFlags(FP->getFastMathFlags());
1901 void BinaryOperator::andIRFlags(const Value *V) {
1902 if (auto *OB = dyn_cast<OverflowingBinaryOperator>(V)) {
1903 setHasNoSignedWrap(hasNoSignedWrap() & OB->hasNoSignedWrap());
1904 setHasNoUnsignedWrap(hasNoUnsignedWrap() & OB->hasNoUnsignedWrap());
1907 if (auto *PE = dyn_cast<PossiblyExactOperator>(V))
1908 setIsExact(isExact() & PE->isExact());
1910 if (auto *FP = dyn_cast<FPMathOperator>(V)) {
1911 FastMathFlags FM = getFastMathFlags();
1912 FM &= FP->getFastMathFlags();
1913 copyFastMathFlags(FM);
1918 //===----------------------------------------------------------------------===//
1919 // FPMathOperator Class
1920 //===----------------------------------------------------------------------===//
1922 /// getFPAccuracy - Get the maximum error permitted by this operation in ULPs.
1923 /// An accuracy of 0.0 means that the operation should be performed with the
1924 /// default precision.
1925 float FPMathOperator::getFPAccuracy() const {
1927 cast<Instruction>(this)->getMetadata(LLVMContext::MD_fpmath);
1930 ConstantFP *Accuracy = mdconst::extract<ConstantFP>(MD->getOperand(0));
1931 return Accuracy->getValueAPF().convertToFloat();
1935 //===----------------------------------------------------------------------===//
1937 //===----------------------------------------------------------------------===//
1939 void CastInst::anchor() {}
1941 // Just determine if this cast only deals with integral->integral conversion.
1942 bool CastInst::isIntegerCast() const {
1943 switch (getOpcode()) {
1944 default: return false;
1945 case Instruction::ZExt:
1946 case Instruction::SExt:
1947 case Instruction::Trunc:
1949 case Instruction::BitCast:
1950 return getOperand(0)->getType()->isIntegerTy() &&
1951 getType()->isIntegerTy();
1955 bool CastInst::isLosslessCast() const {
1956 // Only BitCast can be lossless, exit fast if we're not BitCast
1957 if (getOpcode() != Instruction::BitCast)
1960 // Identity cast is always lossless
1961 Type* SrcTy = getOperand(0)->getType();
1962 Type* DstTy = getType();
1966 // Pointer to pointer is always lossless.
1967 if (SrcTy->isPointerTy())
1968 return DstTy->isPointerTy();
1969 return false; // Other types have no identity values
1972 /// This function determines if the CastInst does not require any bits to be
1973 /// changed in order to effect the cast. Essentially, it identifies cases where
1974 /// no code gen is necessary for the cast, hence the name no-op cast. For
1975 /// example, the following are all no-op casts:
1976 /// # bitcast i32* %x to i8*
1977 /// # bitcast <2 x i32> %x to <4 x i16>
1978 /// # ptrtoint i32* %x to i32 ; on 32-bit plaforms only
1979 /// @brief Determine if the described cast is a no-op.
1980 bool CastInst::isNoopCast(Instruction::CastOps Opcode,
1985 default: llvm_unreachable("Invalid CastOp");
1986 case Instruction::Trunc:
1987 case Instruction::ZExt:
1988 case Instruction::SExt:
1989 case Instruction::FPTrunc:
1990 case Instruction::FPExt:
1991 case Instruction::UIToFP:
1992 case Instruction::SIToFP:
1993 case Instruction::FPToUI:
1994 case Instruction::FPToSI:
1995 case Instruction::AddrSpaceCast:
1996 // TODO: Target informations may give a more accurate answer here.
1998 case Instruction::BitCast:
1999 return true; // BitCast never modifies bits.
2000 case Instruction::PtrToInt:
2001 return IntPtrTy->getScalarSizeInBits() ==
2002 DestTy->getScalarSizeInBits();
2003 case Instruction::IntToPtr:
2004 return IntPtrTy->getScalarSizeInBits() ==
2005 SrcTy->getScalarSizeInBits();
2009 /// @brief Determine if a cast is a no-op.
2010 bool CastInst::isNoopCast(Type *IntPtrTy) const {
2011 return isNoopCast(getOpcode(), getOperand(0)->getType(), getType(), IntPtrTy);
2014 bool CastInst::isNoopCast(const DataLayout &DL) const {
2015 Type *PtrOpTy = nullptr;
2016 if (getOpcode() == Instruction::PtrToInt)
2017 PtrOpTy = getOperand(0)->getType();
2018 else if (getOpcode() == Instruction::IntToPtr)
2019 PtrOpTy = getType();
2022 PtrOpTy ? DL.getIntPtrType(PtrOpTy) : DL.getIntPtrType(getContext(), 0);
2024 return isNoopCast(getOpcode(), getOperand(0)->getType(), getType(), IntPtrTy);
2027 /// This function determines if a pair of casts can be eliminated and what
2028 /// opcode should be used in the elimination. This assumes that there are two
2029 /// instructions like this:
2030 /// * %F = firstOpcode SrcTy %x to MidTy
2031 /// * %S = secondOpcode MidTy %F to DstTy
2032 /// The function returns a resultOpcode so these two casts can be replaced with:
2033 /// * %Replacement = resultOpcode %SrcTy %x to DstTy
2034 /// If no such cast is permited, the function returns 0.
2035 unsigned CastInst::isEliminableCastPair(
2036 Instruction::CastOps firstOp, Instruction::CastOps secondOp,
2037 Type *SrcTy, Type *MidTy, Type *DstTy, Type *SrcIntPtrTy, Type *MidIntPtrTy,
2038 Type *DstIntPtrTy) {
2039 // Define the 144 possibilities for these two cast instructions. The values
2040 // in this matrix determine what to do in a given situation and select the
2041 // case in the switch below. The rows correspond to firstOp, the columns
2042 // correspond to secondOp. In looking at the table below, keep in mind
2043 // the following cast properties:
2045 // Size Compare Source Destination
2046 // Operator Src ? Size Type Sign Type Sign
2047 // -------- ------------ ------------------- ---------------------
2048 // TRUNC > Integer Any Integral Any
2049 // ZEXT < Integral Unsigned Integer Any
2050 // SEXT < Integral Signed Integer Any
2051 // FPTOUI n/a FloatPt n/a Integral Unsigned
2052 // FPTOSI n/a FloatPt n/a Integral Signed
2053 // UITOFP n/a Integral Unsigned FloatPt n/a
2054 // SITOFP n/a Integral Signed FloatPt n/a
2055 // FPTRUNC > FloatPt n/a FloatPt n/a
2056 // FPEXT < FloatPt n/a FloatPt n/a
2057 // PTRTOINT n/a Pointer n/a Integral Unsigned
2058 // INTTOPTR n/a Integral Unsigned Pointer n/a
2059 // BITCAST = FirstClass n/a FirstClass n/a
2060 // ADDRSPCST n/a Pointer n/a Pointer n/a
2062 // NOTE: some transforms are safe, but we consider them to be non-profitable.
2063 // For example, we could merge "fptoui double to i32" + "zext i32 to i64",
2064 // into "fptoui double to i64", but this loses information about the range
2065 // of the produced value (we no longer know the top-part is all zeros).
2066 // Further this conversion is often much more expensive for typical hardware,
2067 // and causes issues when building libgcc. We disallow fptosi+sext for the
2069 const unsigned numCastOps =
2070 Instruction::CastOpsEnd - Instruction::CastOpsBegin;
2071 static const uint8_t CastResults[numCastOps][numCastOps] = {
2072 // T F F U S F F P I B A -+
2073 // R Z S P P I I T P 2 N T S |
2074 // U E E 2 2 2 2 R E I T C C +- secondOp
2075 // N X X U S F F N X N 2 V V |
2076 // C T T I I P P C T T P T T -+
2077 { 1, 0, 0,99,99, 0, 0,99,99,99, 0, 3, 0}, // Trunc -+
2078 { 8, 1, 9,99,99, 2,17,99,99,99, 2, 3, 0}, // ZExt |
2079 { 8, 0, 1,99,99, 0, 2,99,99,99, 0, 3, 0}, // SExt |
2080 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3, 0}, // FPToUI |
2081 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3, 0}, // FPToSI |
2082 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4, 0}, // UIToFP +- firstOp
2083 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4, 0}, // SIToFP |
2084 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4, 0}, // FPTrunc |
2085 { 99,99,99, 2, 2,99,99,10, 2,99,99, 4, 0}, // FPExt |
2086 { 1, 0, 0,99,99, 0, 0,99,99,99, 7, 3, 0}, // PtrToInt |
2087 { 99,99,99,99,99,99,99,99,99,11,99,15, 0}, // IntToPtr |
2088 { 5, 5, 5, 6, 6, 5, 5, 6, 6,16, 5, 1,14}, // BitCast |
2089 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,13,12}, // AddrSpaceCast -+
2092 // If either of the casts are a bitcast from scalar to vector, disallow the
2093 // merging. However, bitcast of A->B->A are allowed.
2094 bool isFirstBitcast = (firstOp == Instruction::BitCast);
2095 bool isSecondBitcast = (secondOp == Instruction::BitCast);
2096 bool chainedBitcast = (SrcTy == DstTy && isFirstBitcast && isSecondBitcast);
2098 // Check if any of the bitcasts convert scalars<->vectors.
2099 if ((isFirstBitcast && isa<VectorType>(SrcTy) != isa<VectorType>(MidTy)) ||
2100 (isSecondBitcast && isa<VectorType>(MidTy) != isa<VectorType>(DstTy)))
2101 // Unless we are bitcasing to the original type, disallow optimizations.
2102 if (!chainedBitcast) return 0;
2104 int ElimCase = CastResults[firstOp-Instruction::CastOpsBegin]
2105 [secondOp-Instruction::CastOpsBegin];
2108 // Categorically disallowed.
2111 // Allowed, use first cast's opcode.
2114 // Allowed, use second cast's opcode.
2117 // No-op cast in second op implies firstOp as long as the DestTy
2118 // is integer and we are not converting between a vector and a
2120 if (!SrcTy->isVectorTy() && DstTy->isIntegerTy())
2124 // No-op cast in second op implies firstOp as long as the DestTy
2125 // is floating point.
2126 if (DstTy->isFloatingPointTy())
2130 // No-op cast in first op implies secondOp as long as the SrcTy
2132 if (SrcTy->isIntegerTy())
2136 // No-op cast in first op implies secondOp as long as the SrcTy
2137 // is a floating point.
2138 if (SrcTy->isFloatingPointTy())
2142 // Cannot simplify if address spaces are different!
2143 if (SrcTy->getPointerAddressSpace() != DstTy->getPointerAddressSpace())
2146 unsigned MidSize = MidTy->getScalarSizeInBits();
2147 // We can still fold this without knowing the actual sizes as long we
2148 // know that the intermediate pointer is the largest possible
2150 // FIXME: Is this always true?
2152 return Instruction::BitCast;
2154 // ptrtoint, inttoptr -> bitcast (ptr -> ptr) if int size is >= ptr size.
2155 if (!SrcIntPtrTy || DstIntPtrTy != SrcIntPtrTy)
2157 unsigned PtrSize = SrcIntPtrTy->getScalarSizeInBits();
2158 if (MidSize >= PtrSize)
2159 return Instruction::BitCast;
2163 // ext, trunc -> bitcast, if the SrcTy and DstTy are same size
2164 // ext, trunc -> ext, if sizeof(SrcTy) < sizeof(DstTy)
2165 // ext, trunc -> trunc, if sizeof(SrcTy) > sizeof(DstTy)
2166 unsigned SrcSize = SrcTy->getScalarSizeInBits();
2167 unsigned DstSize = DstTy->getScalarSizeInBits();
2168 if (SrcSize == DstSize)
2169 return Instruction::BitCast;
2170 else if (SrcSize < DstSize)
2175 // zext, sext -> zext, because sext can't sign extend after zext
2176 return Instruction::ZExt;
2178 // fpext followed by ftrunc is allowed if the bit size returned to is
2179 // the same as the original, in which case its just a bitcast
2181 return Instruction::BitCast;
2182 return 0; // If the types are not the same we can't eliminate it.
2184 // inttoptr, ptrtoint -> bitcast if SrcSize<=PtrSize and SrcSize==DstSize
2187 unsigned PtrSize = MidIntPtrTy->getScalarSizeInBits();
2188 unsigned SrcSize = SrcTy->getScalarSizeInBits();
2189 unsigned DstSize = DstTy->getScalarSizeInBits();
2190 if (SrcSize <= PtrSize && SrcSize == DstSize)
2191 return Instruction::BitCast;
2195 // addrspacecast, addrspacecast -> bitcast, if SrcAS == DstAS
2196 // addrspacecast, addrspacecast -> addrspacecast, if SrcAS != DstAS
2197 if (SrcTy->getPointerAddressSpace() != DstTy->getPointerAddressSpace())
2198 return Instruction::AddrSpaceCast;
2199 return Instruction::BitCast;
2202 // FIXME: this state can be merged with (1), but the following assert
2203 // is useful to check the correcteness of the sequence due to semantic
2204 // change of bitcast.
2206 SrcTy->isPtrOrPtrVectorTy() &&
2207 MidTy->isPtrOrPtrVectorTy() &&
2208 DstTy->isPtrOrPtrVectorTy() &&
2209 SrcTy->getPointerAddressSpace() != MidTy->getPointerAddressSpace() &&
2210 MidTy->getPointerAddressSpace() == DstTy->getPointerAddressSpace() &&
2211 "Illegal addrspacecast, bitcast sequence!");
2212 // Allowed, use first cast's opcode
2215 // bitcast, addrspacecast -> addrspacecast if the element type of
2216 // bitcast's source is the same as that of addrspacecast's destination.
2217 if (SrcTy->getPointerElementType() == DstTy->getPointerElementType())
2218 return Instruction::AddrSpaceCast;
2222 // FIXME: this state can be merged with (1), but the following assert
2223 // is useful to check the correcteness of the sequence due to semantic
2224 // change of bitcast.
2226 SrcTy->isIntOrIntVectorTy() &&
2227 MidTy->isPtrOrPtrVectorTy() &&
2228 DstTy->isPtrOrPtrVectorTy() &&
2229 MidTy->getPointerAddressSpace() == DstTy->getPointerAddressSpace() &&
2230 "Illegal inttoptr, bitcast sequence!");
2231 // Allowed, use first cast's opcode
2234 // FIXME: this state can be merged with (2), but the following assert
2235 // is useful to check the correcteness of the sequence due to semantic
2236 // change of bitcast.
2238 SrcTy->isPtrOrPtrVectorTy() &&
2239 MidTy->isPtrOrPtrVectorTy() &&
2240 DstTy->isIntOrIntVectorTy() &&
2241 SrcTy->getPointerAddressSpace() == MidTy->getPointerAddressSpace() &&
2242 "Illegal bitcast, ptrtoint sequence!");
2243 // Allowed, use second cast's opcode
2246 // (sitofp (zext x)) -> (uitofp x)
2247 return Instruction::UIToFP;
2249 // Cast combination can't happen (error in input). This is for all cases
2250 // where the MidTy is not the same for the two cast instructions.
2251 llvm_unreachable("Invalid Cast Combination");
2253 llvm_unreachable("Error in CastResults table!!!");
2257 CastInst *CastInst::Create(Instruction::CastOps op, Value *S, Type *Ty,
2258 const Twine &Name, Instruction *InsertBefore) {
2259 assert(castIsValid(op, S, Ty) && "Invalid cast!");
2260 // Construct and return the appropriate CastInst subclass
2262 case Trunc: return new TruncInst (S, Ty, Name, InsertBefore);
2263 case ZExt: return new ZExtInst (S, Ty, Name, InsertBefore);
2264 case SExt: return new SExtInst (S, Ty, Name, InsertBefore);
2265 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertBefore);
2266 case FPExt: return new FPExtInst (S, Ty, Name, InsertBefore);
2267 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertBefore);
2268 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertBefore);
2269 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertBefore);
2270 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertBefore);
2271 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertBefore);
2272 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertBefore);
2273 case BitCast: return new BitCastInst (S, Ty, Name, InsertBefore);
2274 case AddrSpaceCast: return new AddrSpaceCastInst (S, Ty, Name, InsertBefore);
2275 default: llvm_unreachable("Invalid opcode provided");
2279 CastInst *CastInst::Create(Instruction::CastOps op, Value *S, Type *Ty,
2280 const Twine &Name, BasicBlock *InsertAtEnd) {
2281 assert(castIsValid(op, S, Ty) && "Invalid cast!");
2282 // Construct and return the appropriate CastInst subclass
2284 case Trunc: return new TruncInst (S, Ty, Name, InsertAtEnd);
2285 case ZExt: return new ZExtInst (S, Ty, Name, InsertAtEnd);
2286 case SExt: return new SExtInst (S, Ty, Name, InsertAtEnd);
2287 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertAtEnd);
2288 case FPExt: return new FPExtInst (S, Ty, Name, InsertAtEnd);
2289 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertAtEnd);
2290 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertAtEnd);
2291 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertAtEnd);
2292 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertAtEnd);
2293 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertAtEnd);
2294 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertAtEnd);
2295 case BitCast: return new BitCastInst (S, Ty, Name, InsertAtEnd);
2296 case AddrSpaceCast: return new AddrSpaceCastInst (S, Ty, Name, InsertAtEnd);
2297 default: llvm_unreachable("Invalid opcode provided");
2301 CastInst *CastInst::CreateZExtOrBitCast(Value *S, Type *Ty,
2303 Instruction *InsertBefore) {
2304 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2305 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2306 return Create(Instruction::ZExt, S, Ty, Name, InsertBefore);
2309 CastInst *CastInst::CreateZExtOrBitCast(Value *S, Type *Ty,
2311 BasicBlock *InsertAtEnd) {
2312 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2313 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2314 return Create(Instruction::ZExt, S, Ty, Name, InsertAtEnd);
2317 CastInst *CastInst::CreateSExtOrBitCast(Value *S, Type *Ty,
2319 Instruction *InsertBefore) {
2320 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2321 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2322 return Create(Instruction::SExt, S, Ty, Name, InsertBefore);
2325 CastInst *CastInst::CreateSExtOrBitCast(Value *S, Type *Ty,
2327 BasicBlock *InsertAtEnd) {
2328 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2329 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2330 return Create(Instruction::SExt, S, Ty, Name, InsertAtEnd);
2333 CastInst *CastInst::CreateTruncOrBitCast(Value *S, Type *Ty,
2335 Instruction *InsertBefore) {
2336 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2337 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2338 return Create(Instruction::Trunc, S, Ty, Name, InsertBefore);
2341 CastInst *CastInst::CreateTruncOrBitCast(Value *S, Type *Ty,
2343 BasicBlock *InsertAtEnd) {
2344 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2345 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2346 return Create(Instruction::Trunc, S, Ty, Name, InsertAtEnd);
2349 CastInst *CastInst::CreatePointerCast(Value *S, Type *Ty,
2351 BasicBlock *InsertAtEnd) {
2352 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
2353 assert((Ty->isIntOrIntVectorTy() || Ty->isPtrOrPtrVectorTy()) &&
2355 assert(Ty->isVectorTy() == S->getType()->isVectorTy() && "Invalid cast");
2356 assert((!Ty->isVectorTy() ||
2357 Ty->getVectorNumElements() == S->getType()->getVectorNumElements()) &&
2360 if (Ty->isIntOrIntVectorTy())
2361 return Create(Instruction::PtrToInt, S, Ty, Name, InsertAtEnd);
2363 return CreatePointerBitCastOrAddrSpaceCast(S, Ty, Name, InsertAtEnd);
2366 /// @brief Create a BitCast or a PtrToInt cast instruction
2367 CastInst *CastInst::CreatePointerCast(Value *S, Type *Ty,
2369 Instruction *InsertBefore) {
2370 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
2371 assert((Ty->isIntOrIntVectorTy() || Ty->isPtrOrPtrVectorTy()) &&
2373 assert(Ty->isVectorTy() == S->getType()->isVectorTy() && "Invalid cast");
2374 assert((!Ty->isVectorTy() ||
2375 Ty->getVectorNumElements() == S->getType()->getVectorNumElements()) &&
2378 if (Ty->isIntOrIntVectorTy())
2379 return Create(Instruction::PtrToInt, S, Ty, Name, InsertBefore);
2381 return CreatePointerBitCastOrAddrSpaceCast(S, Ty, Name, InsertBefore);
2384 CastInst *CastInst::CreatePointerBitCastOrAddrSpaceCast(
2387 BasicBlock *InsertAtEnd) {
2388 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
2389 assert(Ty->isPtrOrPtrVectorTy() && "Invalid cast");
2391 if (S->getType()->getPointerAddressSpace() != Ty->getPointerAddressSpace())
2392 return Create(Instruction::AddrSpaceCast, S, Ty, Name, InsertAtEnd);
2394 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2397 CastInst *CastInst::CreatePointerBitCastOrAddrSpaceCast(
2400 Instruction *InsertBefore) {
2401 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
2402 assert(Ty->isPtrOrPtrVectorTy() && "Invalid cast");
2404 if (S->getType()->getPointerAddressSpace() != Ty->getPointerAddressSpace())
2405 return Create(Instruction::AddrSpaceCast, S, Ty, Name, InsertBefore);
2407 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2410 CastInst *CastInst::CreateBitOrPointerCast(Value *S, Type *Ty,
2412 Instruction *InsertBefore) {
2413 if (S->getType()->isPointerTy() && Ty->isIntegerTy())
2414 return Create(Instruction::PtrToInt, S, Ty, Name, InsertBefore);
2415 if (S->getType()->isIntegerTy() && Ty->isPointerTy())
2416 return Create(Instruction::IntToPtr, S, Ty, Name, InsertBefore);
2418 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2421 CastInst *CastInst::CreateIntegerCast(Value *C, Type *Ty,
2422 bool isSigned, const Twine &Name,
2423 Instruction *InsertBefore) {
2424 assert(C->getType()->isIntOrIntVectorTy() && Ty->isIntOrIntVectorTy() &&
2425 "Invalid integer cast");
2426 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2427 unsigned DstBits = Ty->getScalarSizeInBits();
2428 Instruction::CastOps opcode =
2429 (SrcBits == DstBits ? Instruction::BitCast :
2430 (SrcBits > DstBits ? Instruction::Trunc :
2431 (isSigned ? Instruction::SExt : Instruction::ZExt)));
2432 return Create(opcode, C, Ty, Name, InsertBefore);
2435 CastInst *CastInst::CreateIntegerCast(Value *C, Type *Ty,
2436 bool isSigned, const Twine &Name,
2437 BasicBlock *InsertAtEnd) {
2438 assert(C->getType()->isIntOrIntVectorTy() && Ty->isIntOrIntVectorTy() &&
2440 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2441 unsigned DstBits = Ty->getScalarSizeInBits();
2442 Instruction::CastOps opcode =
2443 (SrcBits == DstBits ? Instruction::BitCast :
2444 (SrcBits > DstBits ? Instruction::Trunc :
2445 (isSigned ? Instruction::SExt : Instruction::ZExt)));
2446 return Create(opcode, C, Ty, Name, InsertAtEnd);
2449 CastInst *CastInst::CreateFPCast(Value *C, Type *Ty,
2451 Instruction *InsertBefore) {
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, InsertBefore);
2462 CastInst *CastInst::CreateFPCast(Value *C, Type *Ty,
2464 BasicBlock *InsertAtEnd) {
2465 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
2467 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2468 unsigned DstBits = Ty->getScalarSizeInBits();
2469 Instruction::CastOps opcode =
2470 (SrcBits == DstBits ? Instruction::BitCast :
2471 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
2472 return Create(opcode, C, Ty, Name, InsertAtEnd);
2475 // Check whether it is valid to call getCastOpcode for these types.
2476 // This routine must be kept in sync with getCastOpcode.
2477 bool CastInst::isCastable(Type *SrcTy, Type *DestTy) {
2478 if (!SrcTy->isFirstClassType() || !DestTy->isFirstClassType())
2481 if (SrcTy == DestTy)
2484 if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy))
2485 if (VectorType *DestVecTy = dyn_cast<VectorType>(DestTy))
2486 if (SrcVecTy->getNumElements() == DestVecTy->getNumElements()) {
2487 // An element by element cast. Valid if casting the elements is valid.
2488 SrcTy = SrcVecTy->getElementType();
2489 DestTy = DestVecTy->getElementType();
2492 // Get the bit sizes, we'll need these
2493 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); // 0 for ptr
2494 unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr
2496 // Run through the possibilities ...
2497 if (DestTy->isIntegerTy()) { // Casting to integral
2498 if (SrcTy->isIntegerTy()) // Casting from integral
2500 if (SrcTy->isFloatingPointTy()) // Casting from floating pt
2502 if (SrcTy->isVectorTy()) // Casting from vector
2503 return DestBits == SrcBits;
2504 // Casting from something else
2505 return SrcTy->isPointerTy();
2507 if (DestTy->isFloatingPointTy()) { // Casting to floating pt
2508 if (SrcTy->isIntegerTy()) // Casting from integral
2510 if (SrcTy->isFloatingPointTy()) // Casting from floating pt
2512 if (SrcTy->isVectorTy()) // Casting from vector
2513 return DestBits == SrcBits;
2514 // Casting from something else
2517 if (DestTy->isVectorTy()) // Casting to vector
2518 return DestBits == SrcBits;
2519 if (DestTy->isPointerTy()) { // Casting to pointer
2520 if (SrcTy->isPointerTy()) // Casting from pointer
2522 return SrcTy->isIntegerTy(); // Casting from integral
2524 if (DestTy->isX86_MMXTy()) {
2525 if (SrcTy->isVectorTy())
2526 return DestBits == SrcBits; // 64-bit vector to MMX
2528 } // Casting to something else
2532 bool CastInst::isBitCastable(Type *SrcTy, Type *DestTy) {
2533 if (!SrcTy->isFirstClassType() || !DestTy->isFirstClassType())
2536 if (SrcTy == DestTy)
2539 if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy)) {
2540 if (VectorType *DestVecTy = dyn_cast<VectorType>(DestTy)) {
2541 if (SrcVecTy->getNumElements() == DestVecTy->getNumElements()) {
2542 // An element by element cast. Valid if casting the elements is valid.
2543 SrcTy = SrcVecTy->getElementType();
2544 DestTy = DestVecTy->getElementType();
2549 if (PointerType *DestPtrTy = dyn_cast<PointerType>(DestTy)) {
2550 if (PointerType *SrcPtrTy = dyn_cast<PointerType>(SrcTy)) {
2551 return SrcPtrTy->getAddressSpace() == DestPtrTy->getAddressSpace();
2555 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); // 0 for ptr
2556 unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr
2558 // Could still have vectors of pointers if the number of elements doesn't
2560 if (SrcBits == 0 || DestBits == 0)
2563 if (SrcBits != DestBits)
2566 if (DestTy->isX86_MMXTy() || SrcTy->isX86_MMXTy())
2572 bool CastInst::isBitOrNoopPointerCastable(Type *SrcTy, Type *DestTy,
2573 const DataLayout &DL) {
2574 if (auto *PtrTy = dyn_cast<PointerType>(SrcTy))
2575 if (auto *IntTy = dyn_cast<IntegerType>(DestTy))
2576 return IntTy->getBitWidth() == DL.getPointerTypeSizeInBits(PtrTy);
2577 if (auto *PtrTy = dyn_cast<PointerType>(DestTy))
2578 if (auto *IntTy = dyn_cast<IntegerType>(SrcTy))
2579 return IntTy->getBitWidth() == DL.getPointerTypeSizeInBits(PtrTy);
2581 return isBitCastable(SrcTy, DestTy);
2584 // Provide a way to get a "cast" where the cast opcode is inferred from the
2585 // types and size of the operand. This, basically, is a parallel of the
2586 // logic in the castIsValid function below. This axiom should hold:
2587 // castIsValid( getCastOpcode(Val, Ty), Val, Ty)
2588 // should not assert in castIsValid. In other words, this produces a "correct"
2589 // casting opcode for the arguments passed to it.
2590 // This routine must be kept in sync with isCastable.
2591 Instruction::CastOps
2592 CastInst::getCastOpcode(
2593 const Value *Src, bool SrcIsSigned, Type *DestTy, bool DestIsSigned) {
2594 Type *SrcTy = Src->getType();
2596 assert(SrcTy->isFirstClassType() && DestTy->isFirstClassType() &&
2597 "Only first class types are castable!");
2599 if (SrcTy == DestTy)
2602 // FIXME: Check address space sizes here
2603 if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy))
2604 if (VectorType *DestVecTy = dyn_cast<VectorType>(DestTy))
2605 if (SrcVecTy->getNumElements() == DestVecTy->getNumElements()) {
2606 // An element by element cast. Find the appropriate opcode based on the
2608 SrcTy = SrcVecTy->getElementType();
2609 DestTy = DestVecTy->getElementType();
2612 // Get the bit sizes, we'll need these
2613 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); // 0 for ptr
2614 unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr
2616 // Run through the possibilities ...
2617 if (DestTy->isIntegerTy()) { // Casting to integral
2618 if (SrcTy->isIntegerTy()) { // Casting from integral
2619 if (DestBits < SrcBits)
2620 return Trunc; // int -> smaller int
2621 else if (DestBits > SrcBits) { // its an extension
2623 return SExt; // signed -> SEXT
2625 return ZExt; // unsigned -> ZEXT
2627 return BitCast; // Same size, No-op cast
2629 } else if (SrcTy->isFloatingPointTy()) { // Casting from floating pt
2631 return FPToSI; // FP -> sint
2633 return FPToUI; // FP -> uint
2634 } else if (SrcTy->isVectorTy()) {
2635 assert(DestBits == SrcBits &&
2636 "Casting vector to integer of different width");
2637 return BitCast; // Same size, no-op cast
2639 assert(SrcTy->isPointerTy() &&
2640 "Casting from a value that is not first-class type");
2641 return PtrToInt; // ptr -> int
2643 } else if (DestTy->isFloatingPointTy()) { // Casting to floating pt
2644 if (SrcTy->isIntegerTy()) { // Casting from integral
2646 return SIToFP; // sint -> FP
2648 return UIToFP; // uint -> FP
2649 } else if (SrcTy->isFloatingPointTy()) { // Casting from floating pt
2650 if (DestBits < SrcBits) {
2651 return FPTrunc; // FP -> smaller FP
2652 } else if (DestBits > SrcBits) {
2653 return FPExt; // FP -> larger FP
2655 return BitCast; // same size, no-op cast
2657 } else if (SrcTy->isVectorTy()) {
2658 assert(DestBits == SrcBits &&
2659 "Casting vector to floating point of different width");
2660 return BitCast; // same size, no-op cast
2662 llvm_unreachable("Casting pointer or non-first class to float");
2663 } else if (DestTy->isVectorTy()) {
2664 assert(DestBits == SrcBits &&
2665 "Illegal cast to vector (wrong type or size)");
2667 } else if (DestTy->isPointerTy()) {
2668 if (SrcTy->isPointerTy()) {
2669 if (DestTy->getPointerAddressSpace() != SrcTy->getPointerAddressSpace())
2670 return AddrSpaceCast;
2671 return BitCast; // ptr -> ptr
2672 } else if (SrcTy->isIntegerTy()) {
2673 return IntToPtr; // int -> ptr
2675 llvm_unreachable("Casting pointer to other than pointer or int");
2676 } else if (DestTy->isX86_MMXTy()) {
2677 if (SrcTy->isVectorTy()) {
2678 assert(DestBits == SrcBits && "Casting vector of wrong width to X86_MMX");
2679 return BitCast; // 64-bit vector to MMX
2681 llvm_unreachable("Illegal cast to X86_MMX");
2683 llvm_unreachable("Casting to type that is not first-class");
2686 //===----------------------------------------------------------------------===//
2687 // CastInst SubClass Constructors
2688 //===----------------------------------------------------------------------===//
2690 /// Check that the construction parameters for a CastInst are correct. This
2691 /// could be broken out into the separate constructors but it is useful to have
2692 /// it in one place and to eliminate the redundant code for getting the sizes
2693 /// of the types involved.
2695 CastInst::castIsValid(Instruction::CastOps op, Value *S, Type *DstTy) {
2697 // Check for type sanity on the arguments
2698 Type *SrcTy = S->getType();
2700 if (!SrcTy->isFirstClassType() || !DstTy->isFirstClassType() ||
2701 SrcTy->isAggregateType() || DstTy->isAggregateType())
2704 // Get the size of the types in bits, we'll need this later
2705 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
2706 unsigned DstBitSize = DstTy->getScalarSizeInBits();
2708 // If these are vector types, get the lengths of the vectors (using zero for
2709 // scalar types means that checking that vector lengths match also checks that
2710 // scalars are not being converted to vectors or vectors to scalars).
2711 unsigned SrcLength = SrcTy->isVectorTy() ?
2712 cast<VectorType>(SrcTy)->getNumElements() : 0;
2713 unsigned DstLength = DstTy->isVectorTy() ?
2714 cast<VectorType>(DstTy)->getNumElements() : 0;
2716 // Switch on the opcode provided
2718 default: return false; // This is an input error
2719 case Instruction::Trunc:
2720 return SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy() &&
2721 SrcLength == DstLength && SrcBitSize > DstBitSize;
2722 case Instruction::ZExt:
2723 return SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy() &&
2724 SrcLength == DstLength && SrcBitSize < DstBitSize;
2725 case Instruction::SExt:
2726 return SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy() &&
2727 SrcLength == DstLength && SrcBitSize < DstBitSize;
2728 case Instruction::FPTrunc:
2729 return SrcTy->isFPOrFPVectorTy() && DstTy->isFPOrFPVectorTy() &&
2730 SrcLength == DstLength && SrcBitSize > DstBitSize;
2731 case Instruction::FPExt:
2732 return SrcTy->isFPOrFPVectorTy() && DstTy->isFPOrFPVectorTy() &&
2733 SrcLength == DstLength && SrcBitSize < DstBitSize;
2734 case Instruction::UIToFP:
2735 case Instruction::SIToFP:
2736 return SrcTy->isIntOrIntVectorTy() && DstTy->isFPOrFPVectorTy() &&
2737 SrcLength == DstLength;
2738 case Instruction::FPToUI:
2739 case Instruction::FPToSI:
2740 return SrcTy->isFPOrFPVectorTy() && DstTy->isIntOrIntVectorTy() &&
2741 SrcLength == DstLength;
2742 case Instruction::PtrToInt:
2743 if (isa<VectorType>(SrcTy) != isa<VectorType>(DstTy))
2745 if (VectorType *VT = dyn_cast<VectorType>(SrcTy))
2746 if (VT->getNumElements() != cast<VectorType>(DstTy)->getNumElements())
2748 return SrcTy->getScalarType()->isPointerTy() &&
2749 DstTy->getScalarType()->isIntegerTy();
2750 case Instruction::IntToPtr:
2751 if (isa<VectorType>(SrcTy) != isa<VectorType>(DstTy))
2753 if (VectorType *VT = dyn_cast<VectorType>(SrcTy))
2754 if (VT->getNumElements() != cast<VectorType>(DstTy)->getNumElements())
2756 return SrcTy->getScalarType()->isIntegerTy() &&
2757 DstTy->getScalarType()->isPointerTy();
2758 case Instruction::BitCast: {
2759 PointerType *SrcPtrTy = dyn_cast<PointerType>(SrcTy->getScalarType());
2760 PointerType *DstPtrTy = dyn_cast<PointerType>(DstTy->getScalarType());
2762 // BitCast implies a no-op cast of type only. No bits change.
2763 // However, you can't cast pointers to anything but pointers.
2764 if (!SrcPtrTy != !DstPtrTy)
2767 // For non-pointer cases, the cast is okay if the source and destination bit
2768 // widths are identical.
2770 return SrcTy->getPrimitiveSizeInBits() == DstTy->getPrimitiveSizeInBits();
2772 // If both are pointers then the address spaces must match.
2773 if (SrcPtrTy->getAddressSpace() != DstPtrTy->getAddressSpace())
2776 // A vector of pointers must have the same number of elements.
2777 if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy)) {
2778 if (VectorType *DstVecTy = dyn_cast<VectorType>(DstTy))
2779 return (SrcVecTy->getNumElements() == DstVecTy->getNumElements());
2786 case Instruction::AddrSpaceCast: {
2787 PointerType *SrcPtrTy = dyn_cast<PointerType>(SrcTy->getScalarType());
2791 PointerType *DstPtrTy = dyn_cast<PointerType>(DstTy->getScalarType());
2795 if (SrcPtrTy->getAddressSpace() == DstPtrTy->getAddressSpace())
2798 if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy)) {
2799 if (VectorType *DstVecTy = dyn_cast<VectorType>(DstTy))
2800 return (SrcVecTy->getNumElements() == DstVecTy->getNumElements());
2810 TruncInst::TruncInst(
2811 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2812 ) : CastInst(Ty, Trunc, S, Name, InsertBefore) {
2813 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
2816 TruncInst::TruncInst(
2817 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2818 ) : CastInst(Ty, Trunc, S, Name, InsertAtEnd) {
2819 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
2823 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2824 ) : CastInst(Ty, ZExt, S, Name, InsertBefore) {
2825 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
2829 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2830 ) : CastInst(Ty, ZExt, S, Name, InsertAtEnd) {
2831 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
2834 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2835 ) : CastInst(Ty, SExt, S, Name, InsertBefore) {
2836 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
2840 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2841 ) : CastInst(Ty, SExt, S, Name, InsertAtEnd) {
2842 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
2845 FPTruncInst::FPTruncInst(
2846 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2847 ) : CastInst(Ty, FPTrunc, S, Name, InsertBefore) {
2848 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
2851 FPTruncInst::FPTruncInst(
2852 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2853 ) : CastInst(Ty, FPTrunc, S, Name, InsertAtEnd) {
2854 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
2857 FPExtInst::FPExtInst(
2858 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2859 ) : CastInst(Ty, FPExt, S, Name, InsertBefore) {
2860 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
2863 FPExtInst::FPExtInst(
2864 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2865 ) : CastInst(Ty, FPExt, S, Name, InsertAtEnd) {
2866 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
2869 UIToFPInst::UIToFPInst(
2870 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2871 ) : CastInst(Ty, UIToFP, S, Name, InsertBefore) {
2872 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
2875 UIToFPInst::UIToFPInst(
2876 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2877 ) : CastInst(Ty, UIToFP, S, Name, InsertAtEnd) {
2878 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
2881 SIToFPInst::SIToFPInst(
2882 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2883 ) : CastInst(Ty, SIToFP, S, Name, InsertBefore) {
2884 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
2887 SIToFPInst::SIToFPInst(
2888 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2889 ) : CastInst(Ty, SIToFP, S, Name, InsertAtEnd) {
2890 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
2893 FPToUIInst::FPToUIInst(
2894 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2895 ) : CastInst(Ty, FPToUI, S, Name, InsertBefore) {
2896 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
2899 FPToUIInst::FPToUIInst(
2900 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2901 ) : CastInst(Ty, FPToUI, S, Name, InsertAtEnd) {
2902 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
2905 FPToSIInst::FPToSIInst(
2906 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2907 ) : CastInst(Ty, FPToSI, S, Name, InsertBefore) {
2908 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
2911 FPToSIInst::FPToSIInst(
2912 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2913 ) : CastInst(Ty, FPToSI, S, Name, InsertAtEnd) {
2914 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
2917 PtrToIntInst::PtrToIntInst(
2918 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2919 ) : CastInst(Ty, PtrToInt, S, Name, InsertBefore) {
2920 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
2923 PtrToIntInst::PtrToIntInst(
2924 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2925 ) : CastInst(Ty, PtrToInt, S, Name, InsertAtEnd) {
2926 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
2929 IntToPtrInst::IntToPtrInst(
2930 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2931 ) : CastInst(Ty, IntToPtr, S, Name, InsertBefore) {
2932 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
2935 IntToPtrInst::IntToPtrInst(
2936 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2937 ) : CastInst(Ty, IntToPtr, S, Name, InsertAtEnd) {
2938 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
2941 BitCastInst::BitCastInst(
2942 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2943 ) : CastInst(Ty, BitCast, S, Name, InsertBefore) {
2944 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
2947 BitCastInst::BitCastInst(
2948 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2949 ) : CastInst(Ty, BitCast, S, Name, InsertAtEnd) {
2950 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
2953 AddrSpaceCastInst::AddrSpaceCastInst(
2954 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2955 ) : CastInst(Ty, AddrSpaceCast, S, Name, InsertBefore) {
2956 assert(castIsValid(getOpcode(), S, Ty) && "Illegal AddrSpaceCast");
2959 AddrSpaceCastInst::AddrSpaceCastInst(
2960 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2961 ) : CastInst(Ty, AddrSpaceCast, S, Name, InsertAtEnd) {
2962 assert(castIsValid(getOpcode(), S, Ty) && "Illegal AddrSpaceCast");
2965 //===----------------------------------------------------------------------===//
2967 //===----------------------------------------------------------------------===//
2969 void CmpInst::anchor() {}
2971 CmpInst::CmpInst(Type *ty, OtherOps op, unsigned short predicate,
2972 Value *LHS, Value *RHS, const Twine &Name,
2973 Instruction *InsertBefore)
2974 : Instruction(ty, op,
2975 OperandTraits<CmpInst>::op_begin(this),
2976 OperandTraits<CmpInst>::operands(this),
2980 setPredicate((Predicate)predicate);
2984 CmpInst::CmpInst(Type *ty, OtherOps op, unsigned short predicate,
2985 Value *LHS, Value *RHS, const Twine &Name,
2986 BasicBlock *InsertAtEnd)
2987 : Instruction(ty, op,
2988 OperandTraits<CmpInst>::op_begin(this),
2989 OperandTraits<CmpInst>::operands(this),
2993 setPredicate((Predicate)predicate);
2998 CmpInst::Create(OtherOps Op, unsigned short predicate,
2999 Value *S1, Value *S2,
3000 const Twine &Name, Instruction *InsertBefore) {
3001 if (Op == Instruction::ICmp) {
3003 return new ICmpInst(InsertBefore, CmpInst::Predicate(predicate),
3006 return new ICmpInst(CmpInst::Predicate(predicate),
3011 return new FCmpInst(InsertBefore, CmpInst::Predicate(predicate),
3014 return new FCmpInst(CmpInst::Predicate(predicate),
3019 CmpInst::Create(OtherOps Op, unsigned short predicate, Value *S1, Value *S2,
3020 const Twine &Name, BasicBlock *InsertAtEnd) {
3021 if (Op == Instruction::ICmp) {
3022 return new ICmpInst(*InsertAtEnd, CmpInst::Predicate(predicate),
3025 return new FCmpInst(*InsertAtEnd, CmpInst::Predicate(predicate),
3029 void CmpInst::swapOperands() {
3030 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
3033 cast<FCmpInst>(this)->swapOperands();
3036 bool CmpInst::isCommutative() const {
3037 if (const ICmpInst *IC = dyn_cast<ICmpInst>(this))
3038 return IC->isCommutative();
3039 return cast<FCmpInst>(this)->isCommutative();
3042 bool CmpInst::isEquality() const {
3043 if (const ICmpInst *IC = dyn_cast<ICmpInst>(this))
3044 return IC->isEquality();
3045 return cast<FCmpInst>(this)->isEquality();
3049 CmpInst::Predicate CmpInst::getInversePredicate(Predicate pred) {
3051 default: llvm_unreachable("Unknown cmp predicate!");
3052 case ICMP_EQ: return ICMP_NE;
3053 case ICMP_NE: return ICMP_EQ;
3054 case ICMP_UGT: return ICMP_ULE;
3055 case ICMP_ULT: return ICMP_UGE;
3056 case ICMP_UGE: return ICMP_ULT;
3057 case ICMP_ULE: return ICMP_UGT;
3058 case ICMP_SGT: return ICMP_SLE;
3059 case ICMP_SLT: return ICMP_SGE;
3060 case ICMP_SGE: return ICMP_SLT;
3061 case ICMP_SLE: return ICMP_SGT;
3063 case FCMP_OEQ: return FCMP_UNE;
3064 case FCMP_ONE: return FCMP_UEQ;
3065 case FCMP_OGT: return FCMP_ULE;
3066 case FCMP_OLT: return FCMP_UGE;
3067 case FCMP_OGE: return FCMP_ULT;
3068 case FCMP_OLE: return FCMP_UGT;
3069 case FCMP_UEQ: return FCMP_ONE;
3070 case FCMP_UNE: return FCMP_OEQ;
3071 case FCMP_UGT: return FCMP_OLE;
3072 case FCMP_ULT: return FCMP_OGE;
3073 case FCMP_UGE: return FCMP_OLT;
3074 case FCMP_ULE: return FCMP_OGT;
3075 case FCMP_ORD: return FCMP_UNO;
3076 case FCMP_UNO: return FCMP_ORD;
3077 case FCMP_TRUE: return FCMP_FALSE;
3078 case FCMP_FALSE: return FCMP_TRUE;
3082 ICmpInst::Predicate ICmpInst::getSignedPredicate(Predicate pred) {
3084 default: llvm_unreachable("Unknown icmp predicate!");
3085 case ICMP_EQ: case ICMP_NE:
3086 case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE:
3088 case ICMP_UGT: return ICMP_SGT;
3089 case ICMP_ULT: return ICMP_SLT;
3090 case ICMP_UGE: return ICMP_SGE;
3091 case ICMP_ULE: return ICMP_SLE;
3095 ICmpInst::Predicate ICmpInst::getUnsignedPredicate(Predicate pred) {
3097 default: llvm_unreachable("Unknown icmp predicate!");
3098 case ICMP_EQ: case ICMP_NE:
3099 case ICMP_UGT: case ICMP_ULT: case ICMP_UGE: case ICMP_ULE:
3101 case ICMP_SGT: return ICMP_UGT;
3102 case ICMP_SLT: return ICMP_ULT;
3103 case ICMP_SGE: return ICMP_UGE;
3104 case ICMP_SLE: return ICMP_ULE;
3108 /// Initialize a set of values that all satisfy the condition with C.
3111 ICmpInst::makeConstantRange(Predicate pred, const APInt &C) {
3114 uint32_t BitWidth = C.getBitWidth();
3116 default: llvm_unreachable("Invalid ICmp opcode to ConstantRange ctor!");
3117 case ICmpInst::ICMP_EQ: ++Upper; break;
3118 case ICmpInst::ICMP_NE: ++Lower; break;
3119 case ICmpInst::ICMP_ULT:
3120 Lower = APInt::getMinValue(BitWidth);
3121 // Check for an empty-set condition.
3123 return ConstantRange(BitWidth, /*isFullSet=*/false);
3125 case ICmpInst::ICMP_SLT:
3126 Lower = APInt::getSignedMinValue(BitWidth);
3127 // Check for an empty-set condition.
3129 return ConstantRange(BitWidth, /*isFullSet=*/false);
3131 case ICmpInst::ICMP_UGT:
3132 ++Lower; Upper = APInt::getMinValue(BitWidth); // Min = Next(Max)
3133 // Check for an empty-set condition.
3135 return ConstantRange(BitWidth, /*isFullSet=*/false);
3137 case ICmpInst::ICMP_SGT:
3138 ++Lower; Upper = APInt::getSignedMinValue(BitWidth); // Min = Next(Max)
3139 // Check for an empty-set condition.
3141 return ConstantRange(BitWidth, /*isFullSet=*/false);
3143 case ICmpInst::ICMP_ULE:
3144 Lower = APInt::getMinValue(BitWidth); ++Upper;
3145 // Check for a full-set condition.
3147 return ConstantRange(BitWidth, /*isFullSet=*/true);
3149 case ICmpInst::ICMP_SLE:
3150 Lower = APInt::getSignedMinValue(BitWidth); ++Upper;
3151 // Check for a full-set condition.
3153 return ConstantRange(BitWidth, /*isFullSet=*/true);
3155 case ICmpInst::ICMP_UGE:
3156 Upper = APInt::getMinValue(BitWidth); // Min = Next(Max)
3157 // Check for a full-set condition.
3159 return ConstantRange(BitWidth, /*isFullSet=*/true);
3161 case ICmpInst::ICMP_SGE:
3162 Upper = APInt::getSignedMinValue(BitWidth); // Min = Next(Max)
3163 // Check for a full-set condition.
3165 return ConstantRange(BitWidth, /*isFullSet=*/true);
3168 return ConstantRange(Lower, Upper);
3171 CmpInst::Predicate CmpInst::getSwappedPredicate(Predicate pred) {
3173 default: llvm_unreachable("Unknown cmp predicate!");
3174 case ICMP_EQ: case ICMP_NE:
3176 case ICMP_SGT: return ICMP_SLT;
3177 case ICMP_SLT: return ICMP_SGT;
3178 case ICMP_SGE: return ICMP_SLE;
3179 case ICMP_SLE: return ICMP_SGE;
3180 case ICMP_UGT: return ICMP_ULT;
3181 case ICMP_ULT: return ICMP_UGT;
3182 case ICMP_UGE: return ICMP_ULE;
3183 case ICMP_ULE: return ICMP_UGE;
3185 case FCMP_FALSE: case FCMP_TRUE:
3186 case FCMP_OEQ: case FCMP_ONE:
3187 case FCMP_UEQ: case FCMP_UNE:
3188 case FCMP_ORD: case FCMP_UNO:
3190 case FCMP_OGT: return FCMP_OLT;
3191 case FCMP_OLT: return FCMP_OGT;
3192 case FCMP_OGE: return FCMP_OLE;
3193 case FCMP_OLE: return FCMP_OGE;
3194 case FCMP_UGT: return FCMP_ULT;
3195 case FCMP_ULT: return FCMP_UGT;
3196 case FCMP_UGE: return FCMP_ULE;
3197 case FCMP_ULE: return FCMP_UGE;
3201 bool CmpInst::isUnsigned(unsigned short predicate) {
3202 switch (predicate) {
3203 default: return false;
3204 case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_ULE: case ICmpInst::ICMP_UGT:
3205 case ICmpInst::ICMP_UGE: return true;
3209 bool CmpInst::isSigned(unsigned short predicate) {
3210 switch (predicate) {
3211 default: return false;
3212 case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_SLE: case ICmpInst::ICMP_SGT:
3213 case ICmpInst::ICMP_SGE: return true;
3217 bool CmpInst::isOrdered(unsigned short predicate) {
3218 switch (predicate) {
3219 default: return false;
3220 case FCmpInst::FCMP_OEQ: case FCmpInst::FCMP_ONE: case FCmpInst::FCMP_OGT:
3221 case FCmpInst::FCMP_OLT: case FCmpInst::FCMP_OGE: case FCmpInst::FCMP_OLE:
3222 case FCmpInst::FCMP_ORD: return true;
3226 bool CmpInst::isUnordered(unsigned short predicate) {
3227 switch (predicate) {
3228 default: return false;
3229 case FCmpInst::FCMP_UEQ: case FCmpInst::FCMP_UNE: case FCmpInst::FCMP_UGT:
3230 case FCmpInst::FCMP_ULT: case FCmpInst::FCMP_UGE: case FCmpInst::FCMP_ULE:
3231 case FCmpInst::FCMP_UNO: return true;
3235 bool CmpInst::isTrueWhenEqual(unsigned short predicate) {
3237 default: return false;
3238 case ICMP_EQ: case ICMP_UGE: case ICMP_ULE: case ICMP_SGE: case ICMP_SLE:
3239 case FCMP_TRUE: case FCMP_UEQ: case FCMP_UGE: case FCMP_ULE: return true;
3243 bool CmpInst::isFalseWhenEqual(unsigned short predicate) {
3245 case ICMP_NE: case ICMP_UGT: case ICMP_ULT: case ICMP_SGT: case ICMP_SLT:
3246 case FCMP_FALSE: case FCMP_ONE: case FCMP_OGT: case FCMP_OLT: return true;
3247 default: return false;
3252 //===----------------------------------------------------------------------===//
3253 // SwitchInst Implementation
3254 //===----------------------------------------------------------------------===//
3256 void SwitchInst::init(Value *Value, BasicBlock *Default, unsigned NumReserved) {
3257 assert(Value && Default && NumReserved);
3258 ReservedSpace = NumReserved;
3259 setNumHungOffUseOperands(2);
3260 allocHungoffUses(ReservedSpace);
3266 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
3267 /// switch on and a default destination. The number of additional cases can
3268 /// be specified here to make memory allocation more efficient. This
3269 /// constructor can also autoinsert before another instruction.
3270 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
3271 Instruction *InsertBefore)
3272 : TerminatorInst(Type::getVoidTy(Value->getContext()), Instruction::Switch,
3273 nullptr, 0, InsertBefore) {
3274 init(Value, Default, 2+NumCases*2);
3277 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
3278 /// switch on and a default destination. The number of additional cases can
3279 /// be specified here to make memory allocation more efficient. This
3280 /// constructor also autoinserts at the end of the specified BasicBlock.
3281 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
3282 BasicBlock *InsertAtEnd)
3283 : TerminatorInst(Type::getVoidTy(Value->getContext()), Instruction::Switch,
3284 nullptr, 0, InsertAtEnd) {
3285 init(Value, Default, 2+NumCases*2);
3288 SwitchInst::SwitchInst(const SwitchInst &SI)
3289 : TerminatorInst(SI.getType(), Instruction::Switch, nullptr, 0) {
3290 init(SI.getCondition(), SI.getDefaultDest(), SI.getNumOperands());
3291 setNumHungOffUseOperands(SI.getNumOperands());
3292 Use *OL = getOperandList();
3293 const Use *InOL = SI.getOperandList();
3294 for (unsigned i = 2, E = SI.getNumOperands(); i != E; i += 2) {
3296 OL[i+1] = InOL[i+1];
3298 SubclassOptionalData = SI.SubclassOptionalData;
3302 /// addCase - Add an entry to the switch instruction...
3304 void SwitchInst::addCase(ConstantInt *OnVal, BasicBlock *Dest) {
3305 unsigned NewCaseIdx = getNumCases();
3306 unsigned OpNo = getNumOperands();
3307 if (OpNo+2 > ReservedSpace)
3308 growOperands(); // Get more space!
3309 // Initialize some new operands.
3310 assert(OpNo+1 < ReservedSpace && "Growing didn't work!");
3311 setNumHungOffUseOperands(OpNo+2);
3312 CaseIt Case(this, NewCaseIdx);
3313 Case.setValue(OnVal);
3314 Case.setSuccessor(Dest);
3317 /// removeCase - This method removes the specified case and its successor
3318 /// from the switch instruction.
3319 void SwitchInst::removeCase(CaseIt i) {
3320 unsigned idx = i.getCaseIndex();
3322 assert(2 + idx*2 < getNumOperands() && "Case index out of range!!!");
3324 unsigned NumOps = getNumOperands();
3325 Use *OL = getOperandList();
3327 // Overwrite this case with the end of the list.
3328 if (2 + (idx + 1) * 2 != NumOps) {
3329 OL[2 + idx * 2] = OL[NumOps - 2];
3330 OL[2 + idx * 2 + 1] = OL[NumOps - 1];
3333 // Nuke the last value.
3334 OL[NumOps-2].set(nullptr);
3335 OL[NumOps-2+1].set(nullptr);
3336 setNumHungOffUseOperands(NumOps-2);
3339 /// growOperands - grow operands - This grows the operand list in response
3340 /// to a push_back style of operation. This grows the number of ops by 3 times.
3342 void SwitchInst::growOperands() {
3343 unsigned e = getNumOperands();
3344 unsigned NumOps = e*3;
3346 ReservedSpace = NumOps;
3347 growHungoffUses(ReservedSpace);
3351 BasicBlock *SwitchInst::getSuccessorV(unsigned idx) const {
3352 return getSuccessor(idx);
3354 unsigned SwitchInst::getNumSuccessorsV() const {
3355 return getNumSuccessors();
3357 void SwitchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
3358 setSuccessor(idx, B);
3361 //===----------------------------------------------------------------------===//
3362 // IndirectBrInst Implementation
3363 //===----------------------------------------------------------------------===//
3365 void IndirectBrInst::init(Value *Address, unsigned NumDests) {
3366 assert(Address && Address->getType()->isPointerTy() &&
3367 "Address of indirectbr must be a pointer");
3368 ReservedSpace = 1+NumDests;
3369 setNumHungOffUseOperands(1);
3370 allocHungoffUses(ReservedSpace);
3376 /// growOperands - grow operands - This grows the operand list in response
3377 /// to a push_back style of operation. This grows the number of ops by 2 times.
3379 void IndirectBrInst::growOperands() {
3380 unsigned e = getNumOperands();
3381 unsigned NumOps = e*2;
3383 ReservedSpace = NumOps;
3384 growHungoffUses(ReservedSpace);
3387 IndirectBrInst::IndirectBrInst(Value *Address, unsigned NumCases,
3388 Instruction *InsertBefore)
3389 : TerminatorInst(Type::getVoidTy(Address->getContext()),Instruction::IndirectBr,
3390 nullptr, 0, InsertBefore) {
3391 init(Address, NumCases);
3394 IndirectBrInst::IndirectBrInst(Value *Address, unsigned NumCases,
3395 BasicBlock *InsertAtEnd)
3396 : TerminatorInst(Type::getVoidTy(Address->getContext()),Instruction::IndirectBr,
3397 nullptr, 0, InsertAtEnd) {
3398 init(Address, NumCases);
3401 IndirectBrInst::IndirectBrInst(const IndirectBrInst &IBI)
3402 : TerminatorInst(Type::getVoidTy(IBI.getContext()), Instruction::IndirectBr,
3403 nullptr, IBI.getNumOperands()) {
3404 allocHungoffUses(IBI.getNumOperands());
3405 Use *OL = getOperandList();
3406 const Use *InOL = IBI.getOperandList();
3407 for (unsigned i = 0, E = IBI.getNumOperands(); i != E; ++i)
3409 SubclassOptionalData = IBI.SubclassOptionalData;
3412 /// addDestination - Add a destination.
3414 void IndirectBrInst::addDestination(BasicBlock *DestBB) {
3415 unsigned OpNo = getNumOperands();
3416 if (OpNo+1 > ReservedSpace)
3417 growOperands(); // Get more space!
3418 // Initialize some new operands.
3419 assert(OpNo < ReservedSpace && "Growing didn't work!");
3420 setNumHungOffUseOperands(OpNo+1);
3421 getOperandList()[OpNo] = DestBB;
3424 /// removeDestination - This method removes the specified successor from the
3425 /// indirectbr instruction.
3426 void IndirectBrInst::removeDestination(unsigned idx) {
3427 assert(idx < getNumOperands()-1 && "Successor index out of range!");
3429 unsigned NumOps = getNumOperands();
3430 Use *OL = getOperandList();
3432 // Replace this value with the last one.
3433 OL[idx+1] = OL[NumOps-1];
3435 // Nuke the last value.
3436 OL[NumOps-1].set(nullptr);
3437 setNumHungOffUseOperands(NumOps-1);
3440 BasicBlock *IndirectBrInst::getSuccessorV(unsigned idx) const {
3441 return getSuccessor(idx);
3443 unsigned IndirectBrInst::getNumSuccessorsV() const {
3444 return getNumSuccessors();
3446 void IndirectBrInst::setSuccessorV(unsigned idx, BasicBlock *B) {
3447 setSuccessor(idx, B);
3450 //===----------------------------------------------------------------------===//
3451 // clone_impl() implementations
3452 //===----------------------------------------------------------------------===//
3454 // Define these methods here so vtables don't get emitted into every translation
3455 // unit that uses these classes.
3457 GetElementPtrInst *GetElementPtrInst::clone_impl() const {
3458 return new (getNumOperands()) GetElementPtrInst(*this);
3461 BinaryOperator *BinaryOperator::clone_impl() const {
3462 return Create(getOpcode(), Op<0>(), Op<1>());
3465 FCmpInst* FCmpInst::clone_impl() const {
3466 return new FCmpInst(getPredicate(), Op<0>(), Op<1>());
3469 ICmpInst* ICmpInst::clone_impl() const {
3470 return new ICmpInst(getPredicate(), Op<0>(), Op<1>());
3473 ExtractValueInst *ExtractValueInst::clone_impl() const {
3474 return new ExtractValueInst(*this);
3477 InsertValueInst *InsertValueInst::clone_impl() const {
3478 return new InsertValueInst(*this);
3481 AllocaInst *AllocaInst::clone_impl() const {
3482 AllocaInst *Result = new AllocaInst(getAllocatedType(),
3483 (Value *)getOperand(0), getAlignment());
3484 Result->setUsedWithInAlloca(isUsedWithInAlloca());
3488 LoadInst *LoadInst::clone_impl() const {
3489 return new LoadInst(getOperand(0), Twine(), isVolatile(),
3490 getAlignment(), getOrdering(), getSynchScope());
3493 StoreInst *StoreInst::clone_impl() const {
3494 return new StoreInst(getOperand(0), getOperand(1), isVolatile(),
3495 getAlignment(), getOrdering(), getSynchScope());
3499 AtomicCmpXchgInst *AtomicCmpXchgInst::clone_impl() const {
3500 AtomicCmpXchgInst *Result =
3501 new AtomicCmpXchgInst(getOperand(0), getOperand(1), getOperand(2),
3502 getSuccessOrdering(), getFailureOrdering(),
3504 Result->setVolatile(isVolatile());
3505 Result->setWeak(isWeak());
3509 AtomicRMWInst *AtomicRMWInst::clone_impl() const {
3510 AtomicRMWInst *Result =
3511 new AtomicRMWInst(getOperation(),getOperand(0), getOperand(1),
3512 getOrdering(), getSynchScope());
3513 Result->setVolatile(isVolatile());
3517 FenceInst *FenceInst::clone_impl() const {
3518 return new FenceInst(getContext(), getOrdering(), getSynchScope());
3521 TruncInst *TruncInst::clone_impl() const {
3522 return new TruncInst(getOperand(0), getType());
3525 ZExtInst *ZExtInst::clone_impl() const {
3526 return new ZExtInst(getOperand(0), getType());
3529 SExtInst *SExtInst::clone_impl() const {
3530 return new SExtInst(getOperand(0), getType());
3533 FPTruncInst *FPTruncInst::clone_impl() const {
3534 return new FPTruncInst(getOperand(0), getType());
3537 FPExtInst *FPExtInst::clone_impl() const {
3538 return new FPExtInst(getOperand(0), getType());
3541 UIToFPInst *UIToFPInst::clone_impl() const {
3542 return new UIToFPInst(getOperand(0), getType());
3545 SIToFPInst *SIToFPInst::clone_impl() const {
3546 return new SIToFPInst(getOperand(0), getType());
3549 FPToUIInst *FPToUIInst::clone_impl() const {
3550 return new FPToUIInst(getOperand(0), getType());
3553 FPToSIInst *FPToSIInst::clone_impl() const {
3554 return new FPToSIInst(getOperand(0), getType());
3557 PtrToIntInst *PtrToIntInst::clone_impl() const {
3558 return new PtrToIntInst(getOperand(0), getType());
3561 IntToPtrInst *IntToPtrInst::clone_impl() const {
3562 return new IntToPtrInst(getOperand(0), getType());
3565 BitCastInst *BitCastInst::clone_impl() const {
3566 return new BitCastInst(getOperand(0), getType());
3569 AddrSpaceCastInst *AddrSpaceCastInst::clone_impl() const {
3570 return new AddrSpaceCastInst(getOperand(0), getType());
3573 CallInst *CallInst::clone_impl() const {
3574 return new(getNumOperands()) CallInst(*this);
3577 SelectInst *SelectInst::clone_impl() const {
3578 return SelectInst::Create(getOperand(0), getOperand(1), getOperand(2));
3581 VAArgInst *VAArgInst::clone_impl() const {
3582 return new VAArgInst(getOperand(0), getType());
3585 ExtractElementInst *ExtractElementInst::clone_impl() const {
3586 return ExtractElementInst::Create(getOperand(0), getOperand(1));
3589 InsertElementInst *InsertElementInst::clone_impl() const {
3590 return InsertElementInst::Create(getOperand(0), getOperand(1), getOperand(2));
3593 ShuffleVectorInst *ShuffleVectorInst::clone_impl() const {
3594 return new ShuffleVectorInst(getOperand(0), getOperand(1), getOperand(2));
3597 PHINode *PHINode::clone_impl() const {
3598 return new PHINode(*this);
3601 LandingPadInst *LandingPadInst::clone_impl() const {
3602 return new LandingPadInst(*this);
3605 ReturnInst *ReturnInst::clone_impl() const {
3606 return new(getNumOperands()) ReturnInst(*this);
3609 BranchInst *BranchInst::clone_impl() const {
3610 return new(getNumOperands()) BranchInst(*this);
3613 SwitchInst *SwitchInst::clone_impl() const {
3614 return new SwitchInst(*this);
3617 IndirectBrInst *IndirectBrInst::clone_impl() const {
3618 return new IndirectBrInst(*this);
3622 InvokeInst *InvokeInst::clone_impl() const {
3623 return new(getNumOperands()) InvokeInst(*this);
3626 ResumeInst *ResumeInst::clone_impl() const {
3627 return new(1) ResumeInst(*this);
3630 UnreachableInst *UnreachableInst::clone_impl() const {
3631 LLVMContext &Context = getContext();
3632 return new UnreachableInst(Context);