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);
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, Value *PersonalityFn,
157 unsigned NumReservedValues, const Twine &NameStr,
158 Instruction *InsertBefore)
159 : Instruction(RetTy, Instruction::LandingPad, nullptr, 0, InsertBefore) {
160 init(PersonalityFn, 1 + NumReservedValues, NameStr);
163 LandingPadInst::LandingPadInst(Type *RetTy, Value *PersonalityFn,
164 unsigned NumReservedValues, const Twine &NameStr,
165 BasicBlock *InsertAtEnd)
166 : Instruction(RetTy, Instruction::LandingPad, nullptr, 0, InsertAtEnd) {
167 init(PersonalityFn, 1 + NumReservedValues, NameStr);
170 LandingPadInst::LandingPadInst(const LandingPadInst &LP)
171 : Instruction(LP.getType(), Instruction::LandingPad, nullptr,
172 LP.getNumOperands()),
173 ReservedSpace(LP.getNumOperands()) {
174 allocHungoffUses(LP.getNumOperands());
175 Use *OL = OperandList, *InOL = LP.OperandList;
176 for (unsigned I = 0, E = ReservedSpace; I != E; ++I)
179 setCleanup(LP.isCleanup());
182 LandingPadInst *LandingPadInst::Create(Type *RetTy, Value *PersonalityFn,
183 unsigned NumReservedClauses,
184 const Twine &NameStr,
185 Instruction *InsertBefore) {
186 return new LandingPadInst(RetTy, PersonalityFn, NumReservedClauses, NameStr,
190 LandingPadInst *LandingPadInst::Create(Type *RetTy, Value *PersonalityFn,
191 unsigned NumReservedClauses,
192 const Twine &NameStr,
193 BasicBlock *InsertAtEnd) {
194 return new LandingPadInst(RetTy, PersonalityFn, NumReservedClauses, NameStr,
198 void LandingPadInst::init(Value *PersFn, unsigned NumReservedValues,
199 const Twine &NameStr) {
200 ReservedSpace = NumReservedValues;
202 allocHungoffUses(ReservedSpace);
208 /// growOperands - grow operands - This grows the operand list in response to a
209 /// push_back style of operation. This grows the number of ops by 2 times.
210 void LandingPadInst::growOperands(unsigned Size) {
211 unsigned e = getNumOperands();
212 if (ReservedSpace >= e + Size) return;
213 ReservedSpace = (e + Size / 2) * 2;
214 growHungoffUses(ReservedSpace);
217 void LandingPadInst::addClause(Constant *Val) {
218 unsigned OpNo = getNumOperands();
220 assert(OpNo < ReservedSpace && "Growing didn't work!");
222 OperandList[OpNo] = Val;
225 //===----------------------------------------------------------------------===//
226 // CallInst Implementation
227 //===----------------------------------------------------------------------===//
229 CallInst::~CallInst() {
232 void CallInst::init(FunctionType *FTy, Value *Func, ArrayRef<Value *> Args,
233 const Twine &NameStr) {
235 assert(NumOperands == Args.size() + 1 && "NumOperands not set up?");
239 assert((Args.size() == FTy->getNumParams() ||
240 (FTy->isVarArg() && Args.size() > FTy->getNumParams())) &&
241 "Calling a function with bad signature!");
243 for (unsigned i = 0; i != Args.size(); ++i)
244 assert((i >= FTy->getNumParams() ||
245 FTy->getParamType(i) == Args[i]->getType()) &&
246 "Calling a function with a bad signature!");
249 std::copy(Args.begin(), Args.end(), op_begin());
253 void CallInst::init(Value *Func, const Twine &NameStr) {
255 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
256 assert(NumOperands == 1 && "NumOperands not set up?");
259 assert(FTy->getNumParams() == 0 && "Calling a function with bad signature");
264 CallInst::CallInst(Value *Func, const Twine &Name,
265 Instruction *InsertBefore)
266 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
267 ->getElementType())->getReturnType(),
269 OperandTraits<CallInst>::op_end(this) - 1,
274 CallInst::CallInst(Value *Func, const Twine &Name,
275 BasicBlock *InsertAtEnd)
276 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
277 ->getElementType())->getReturnType(),
279 OperandTraits<CallInst>::op_end(this) - 1,
284 CallInst::CallInst(const CallInst &CI)
285 : Instruction(CI.getType(), Instruction::Call,
286 OperandTraits<CallInst>::op_end(this) - CI.getNumOperands(),
287 CI.getNumOperands()),
288 AttributeList(CI.AttributeList), FTy(CI.FTy) {
289 setTailCallKind(CI.getTailCallKind());
290 setCallingConv(CI.getCallingConv());
292 std::copy(CI.op_begin(), CI.op_end(), op_begin());
293 SubclassOptionalData = CI.SubclassOptionalData;
296 void CallInst::addAttribute(unsigned i, Attribute::AttrKind attr) {
297 AttributeSet PAL = getAttributes();
298 PAL = PAL.addAttribute(getContext(), i, attr);
302 void CallInst::removeAttribute(unsigned i, Attribute attr) {
303 AttributeSet PAL = getAttributes();
305 LLVMContext &Context = getContext();
306 PAL = PAL.removeAttributes(Context, i,
307 AttributeSet::get(Context, i, B));
311 void CallInst::addDereferenceableAttr(unsigned i, uint64_t Bytes) {
312 AttributeSet PAL = getAttributes();
313 PAL = PAL.addDereferenceableAttr(getContext(), i, Bytes);
317 void CallInst::addDereferenceableOrNullAttr(unsigned i, uint64_t Bytes) {
318 AttributeSet PAL = getAttributes();
319 PAL = PAL.addDereferenceableOrNullAttr(getContext(), i, Bytes);
323 bool CallInst::hasFnAttrImpl(Attribute::AttrKind A) const {
324 if (AttributeList.hasAttribute(AttributeSet::FunctionIndex, A))
326 if (const Function *F = getCalledFunction())
327 return F->getAttributes().hasAttribute(AttributeSet::FunctionIndex, A);
331 bool CallInst::paramHasAttr(unsigned i, Attribute::AttrKind A) const {
332 if (AttributeList.hasAttribute(i, A))
334 if (const Function *F = getCalledFunction())
335 return F->getAttributes().hasAttribute(i, A);
339 /// IsConstantOne - Return true only if val is constant int 1
340 static bool IsConstantOne(Value *val) {
341 assert(val && "IsConstantOne does not work with nullptr val");
342 const ConstantInt *CVal = dyn_cast<ConstantInt>(val);
343 return CVal && CVal->isOne();
346 static Instruction *createMalloc(Instruction *InsertBefore,
347 BasicBlock *InsertAtEnd, Type *IntPtrTy,
348 Type *AllocTy, Value *AllocSize,
349 Value *ArraySize, Function *MallocF,
351 assert(((!InsertBefore && InsertAtEnd) || (InsertBefore && !InsertAtEnd)) &&
352 "createMalloc needs either InsertBefore or InsertAtEnd");
354 // malloc(type) becomes:
355 // bitcast (i8* malloc(typeSize)) to type*
356 // malloc(type, arraySize) becomes:
357 // bitcast (i8 *malloc(typeSize*arraySize)) to type*
359 ArraySize = ConstantInt::get(IntPtrTy, 1);
360 else if (ArraySize->getType() != IntPtrTy) {
362 ArraySize = CastInst::CreateIntegerCast(ArraySize, IntPtrTy, false,
365 ArraySize = CastInst::CreateIntegerCast(ArraySize, IntPtrTy, false,
369 if (!IsConstantOne(ArraySize)) {
370 if (IsConstantOne(AllocSize)) {
371 AllocSize = ArraySize; // Operand * 1 = Operand
372 } else if (Constant *CO = dyn_cast<Constant>(ArraySize)) {
373 Constant *Scale = ConstantExpr::getIntegerCast(CO, IntPtrTy,
375 // Malloc arg is constant product of type size and array size
376 AllocSize = ConstantExpr::getMul(Scale, cast<Constant>(AllocSize));
378 // Multiply type size by the array size...
380 AllocSize = BinaryOperator::CreateMul(ArraySize, AllocSize,
381 "mallocsize", InsertBefore);
383 AllocSize = BinaryOperator::CreateMul(ArraySize, AllocSize,
384 "mallocsize", InsertAtEnd);
388 assert(AllocSize->getType() == IntPtrTy && "malloc arg is wrong size");
389 // Create the call to Malloc.
390 BasicBlock* BB = InsertBefore ? InsertBefore->getParent() : InsertAtEnd;
391 Module* M = BB->getParent()->getParent();
392 Type *BPTy = Type::getInt8PtrTy(BB->getContext());
393 Value *MallocFunc = MallocF;
395 // prototype malloc as "void *malloc(size_t)"
396 MallocFunc = M->getOrInsertFunction("malloc", BPTy, IntPtrTy, nullptr);
397 PointerType *AllocPtrType = PointerType::getUnqual(AllocTy);
398 CallInst *MCall = nullptr;
399 Instruction *Result = nullptr;
401 MCall = CallInst::Create(MallocFunc, AllocSize, "malloccall", InsertBefore);
403 if (Result->getType() != AllocPtrType)
404 // Create a cast instruction to convert to the right type...
405 Result = new BitCastInst(MCall, AllocPtrType, Name, InsertBefore);
407 MCall = CallInst::Create(MallocFunc, AllocSize, "malloccall");
409 if (Result->getType() != AllocPtrType) {
410 InsertAtEnd->getInstList().push_back(MCall);
411 // Create a cast instruction to convert to the right type...
412 Result = new BitCastInst(MCall, AllocPtrType, Name);
415 MCall->setTailCall();
416 if (Function *F = dyn_cast<Function>(MallocFunc)) {
417 MCall->setCallingConv(F->getCallingConv());
418 if (!F->doesNotAlias(0)) F->setDoesNotAlias(0);
420 assert(!MCall->getType()->isVoidTy() && "Malloc has void return type");
425 /// CreateMalloc - Generate the IR for a call to malloc:
426 /// 1. Compute the malloc call's argument as the specified type's size,
427 /// possibly multiplied by the array size if the array size is not
429 /// 2. Call malloc with that argument.
430 /// 3. Bitcast the result of the malloc call to the specified type.
431 Instruction *CallInst::CreateMalloc(Instruction *InsertBefore,
432 Type *IntPtrTy, Type *AllocTy,
433 Value *AllocSize, Value *ArraySize,
436 return createMalloc(InsertBefore, nullptr, IntPtrTy, AllocTy, AllocSize,
437 ArraySize, MallocF, Name);
440 /// CreateMalloc - Generate the IR for a call to malloc:
441 /// 1. Compute the malloc call's argument as the specified type's size,
442 /// possibly multiplied by the array size if the array size is not
444 /// 2. Call malloc with that argument.
445 /// 3. Bitcast the result of the malloc call to the specified type.
446 /// Note: This function does not add the bitcast to the basic block, that is the
447 /// responsibility of the caller.
448 Instruction *CallInst::CreateMalloc(BasicBlock *InsertAtEnd,
449 Type *IntPtrTy, Type *AllocTy,
450 Value *AllocSize, Value *ArraySize,
451 Function *MallocF, const Twine &Name) {
452 return createMalloc(nullptr, InsertAtEnd, IntPtrTy, AllocTy, AllocSize,
453 ArraySize, MallocF, Name);
456 static Instruction* createFree(Value* Source, Instruction *InsertBefore,
457 BasicBlock *InsertAtEnd) {
458 assert(((!InsertBefore && InsertAtEnd) || (InsertBefore && !InsertAtEnd)) &&
459 "createFree needs either InsertBefore or InsertAtEnd");
460 assert(Source->getType()->isPointerTy() &&
461 "Can not free something of nonpointer type!");
463 BasicBlock* BB = InsertBefore ? InsertBefore->getParent() : InsertAtEnd;
464 Module* M = BB->getParent()->getParent();
466 Type *VoidTy = Type::getVoidTy(M->getContext());
467 Type *IntPtrTy = Type::getInt8PtrTy(M->getContext());
468 // prototype free as "void free(void*)"
469 Value *FreeFunc = M->getOrInsertFunction("free", VoidTy, IntPtrTy, nullptr);
470 CallInst* Result = nullptr;
471 Value *PtrCast = Source;
473 if (Source->getType() != IntPtrTy)
474 PtrCast = new BitCastInst(Source, IntPtrTy, "", InsertBefore);
475 Result = CallInst::Create(FreeFunc, PtrCast, "", InsertBefore);
477 if (Source->getType() != IntPtrTy)
478 PtrCast = new BitCastInst(Source, IntPtrTy, "", InsertAtEnd);
479 Result = CallInst::Create(FreeFunc, PtrCast, "");
481 Result->setTailCall();
482 if (Function *F = dyn_cast<Function>(FreeFunc))
483 Result->setCallingConv(F->getCallingConv());
488 /// CreateFree - Generate the IR for a call to the builtin free function.
489 Instruction * CallInst::CreateFree(Value* Source, Instruction *InsertBefore) {
490 return createFree(Source, InsertBefore, nullptr);
493 /// CreateFree - Generate the IR for a call to the builtin free function.
494 /// Note: This function does not add the call to the basic block, that is the
495 /// responsibility of the caller.
496 Instruction* CallInst::CreateFree(Value* Source, BasicBlock *InsertAtEnd) {
497 Instruction* FreeCall = createFree(Source, nullptr, InsertAtEnd);
498 assert(FreeCall && "CreateFree did not create a CallInst");
502 //===----------------------------------------------------------------------===//
503 // InvokeInst Implementation
504 //===----------------------------------------------------------------------===//
506 void InvokeInst::init(FunctionType *FTy, Value *Fn, BasicBlock *IfNormal,
507 BasicBlock *IfException, ArrayRef<Value *> Args,
508 const Twine &NameStr) {
511 assert(NumOperands == 3 + Args.size() && "NumOperands not set up?");
514 Op<-1>() = IfException;
517 assert(((Args.size() == FTy->getNumParams()) ||
518 (FTy->isVarArg() && Args.size() > FTy->getNumParams())) &&
519 "Invoking a function with bad signature");
521 for (unsigned i = 0, e = Args.size(); i != e; i++)
522 assert((i >= FTy->getNumParams() ||
523 FTy->getParamType(i) == Args[i]->getType()) &&
524 "Invoking a function with a bad signature!");
527 std::copy(Args.begin(), Args.end(), op_begin());
531 InvokeInst::InvokeInst(const InvokeInst &II)
532 : TerminatorInst(II.getType(), Instruction::Invoke,
533 OperandTraits<InvokeInst>::op_end(this) -
535 II.getNumOperands()),
536 AttributeList(II.AttributeList), FTy(II.FTy) {
537 setCallingConv(II.getCallingConv());
538 std::copy(II.op_begin(), II.op_end(), op_begin());
539 SubclassOptionalData = II.SubclassOptionalData;
542 BasicBlock *InvokeInst::getSuccessorV(unsigned idx) const {
543 return getSuccessor(idx);
545 unsigned InvokeInst::getNumSuccessorsV() const {
546 return getNumSuccessors();
548 void InvokeInst::setSuccessorV(unsigned idx, BasicBlock *B) {
549 return setSuccessor(idx, B);
552 bool InvokeInst::hasFnAttrImpl(Attribute::AttrKind A) const {
553 if (AttributeList.hasAttribute(AttributeSet::FunctionIndex, A))
555 if (const Function *F = getCalledFunction())
556 return F->getAttributes().hasAttribute(AttributeSet::FunctionIndex, A);
560 bool InvokeInst::paramHasAttr(unsigned i, Attribute::AttrKind A) const {
561 if (AttributeList.hasAttribute(i, A))
563 if (const Function *F = getCalledFunction())
564 return F->getAttributes().hasAttribute(i, A);
568 void InvokeInst::addAttribute(unsigned i, Attribute::AttrKind attr) {
569 AttributeSet PAL = getAttributes();
570 PAL = PAL.addAttribute(getContext(), i, attr);
574 void InvokeInst::removeAttribute(unsigned i, Attribute attr) {
575 AttributeSet PAL = getAttributes();
577 PAL = PAL.removeAttributes(getContext(), i,
578 AttributeSet::get(getContext(), i, B));
582 void InvokeInst::addDereferenceableAttr(unsigned i, uint64_t Bytes) {
583 AttributeSet PAL = getAttributes();
584 PAL = PAL.addDereferenceableAttr(getContext(), i, Bytes);
588 void InvokeInst::addDereferenceableOrNullAttr(unsigned i, uint64_t Bytes) {
589 AttributeSet PAL = getAttributes();
590 PAL = PAL.addDereferenceableOrNullAttr(getContext(), i, Bytes);
594 LandingPadInst *InvokeInst::getLandingPadInst() const {
595 return cast<LandingPadInst>(getUnwindDest()->getFirstNonPHI());
598 //===----------------------------------------------------------------------===//
599 // ReturnInst Implementation
600 //===----------------------------------------------------------------------===//
602 ReturnInst::ReturnInst(const ReturnInst &RI)
603 : TerminatorInst(Type::getVoidTy(RI.getContext()), Instruction::Ret,
604 OperandTraits<ReturnInst>::op_end(this) -
606 RI.getNumOperands()) {
607 if (RI.getNumOperands())
608 Op<0>() = RI.Op<0>();
609 SubclassOptionalData = RI.SubclassOptionalData;
612 ReturnInst::ReturnInst(LLVMContext &C, Value *retVal, Instruction *InsertBefore)
613 : TerminatorInst(Type::getVoidTy(C), Instruction::Ret,
614 OperandTraits<ReturnInst>::op_end(this) - !!retVal, !!retVal,
619 ReturnInst::ReturnInst(LLVMContext &C, Value *retVal, BasicBlock *InsertAtEnd)
620 : TerminatorInst(Type::getVoidTy(C), Instruction::Ret,
621 OperandTraits<ReturnInst>::op_end(this) - !!retVal, !!retVal,
626 ReturnInst::ReturnInst(LLVMContext &Context, BasicBlock *InsertAtEnd)
627 : TerminatorInst(Type::getVoidTy(Context), Instruction::Ret,
628 OperandTraits<ReturnInst>::op_end(this), 0, InsertAtEnd) {
631 unsigned ReturnInst::getNumSuccessorsV() const {
632 return getNumSuccessors();
635 /// Out-of-line ReturnInst method, put here so the C++ compiler can choose to
636 /// emit the vtable for the class in this translation unit.
637 void ReturnInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
638 llvm_unreachable("ReturnInst has no successors!");
641 BasicBlock *ReturnInst::getSuccessorV(unsigned idx) const {
642 llvm_unreachable("ReturnInst has no successors!");
645 ReturnInst::~ReturnInst() {
648 //===----------------------------------------------------------------------===//
649 // ResumeInst Implementation
650 //===----------------------------------------------------------------------===//
652 ResumeInst::ResumeInst(const ResumeInst &RI)
653 : TerminatorInst(Type::getVoidTy(RI.getContext()), Instruction::Resume,
654 OperandTraits<ResumeInst>::op_begin(this), 1) {
655 Op<0>() = RI.Op<0>();
658 ResumeInst::ResumeInst(Value *Exn, Instruction *InsertBefore)
659 : TerminatorInst(Type::getVoidTy(Exn->getContext()), Instruction::Resume,
660 OperandTraits<ResumeInst>::op_begin(this), 1, InsertBefore) {
664 ResumeInst::ResumeInst(Value *Exn, BasicBlock *InsertAtEnd)
665 : TerminatorInst(Type::getVoidTy(Exn->getContext()), Instruction::Resume,
666 OperandTraits<ResumeInst>::op_begin(this), 1, InsertAtEnd) {
670 unsigned ResumeInst::getNumSuccessorsV() const {
671 return getNumSuccessors();
674 void ResumeInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
675 llvm_unreachable("ResumeInst has no successors!");
678 BasicBlock *ResumeInst::getSuccessorV(unsigned idx) const {
679 llvm_unreachable("ResumeInst has no successors!");
682 //===----------------------------------------------------------------------===//
683 // UnreachableInst Implementation
684 //===----------------------------------------------------------------------===//
686 UnreachableInst::UnreachableInst(LLVMContext &Context,
687 Instruction *InsertBefore)
688 : TerminatorInst(Type::getVoidTy(Context), Instruction::Unreachable,
689 nullptr, 0, InsertBefore) {
691 UnreachableInst::UnreachableInst(LLVMContext &Context, BasicBlock *InsertAtEnd)
692 : TerminatorInst(Type::getVoidTy(Context), Instruction::Unreachable,
693 nullptr, 0, InsertAtEnd) {
696 unsigned UnreachableInst::getNumSuccessorsV() const {
697 return getNumSuccessors();
700 void UnreachableInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
701 llvm_unreachable("UnreachableInst has no successors!");
704 BasicBlock *UnreachableInst::getSuccessorV(unsigned idx) const {
705 llvm_unreachable("UnreachableInst has no successors!");
708 //===----------------------------------------------------------------------===//
709 // BranchInst Implementation
710 //===----------------------------------------------------------------------===//
712 void BranchInst::AssertOK() {
714 assert(getCondition()->getType()->isIntegerTy(1) &&
715 "May only branch on boolean predicates!");
718 BranchInst::BranchInst(BasicBlock *IfTrue, Instruction *InsertBefore)
719 : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
720 OperandTraits<BranchInst>::op_end(this) - 1,
722 assert(IfTrue && "Branch destination may not be null!");
725 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
726 Instruction *InsertBefore)
727 : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
728 OperandTraits<BranchInst>::op_end(this) - 3,
738 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *InsertAtEnd)
739 : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
740 OperandTraits<BranchInst>::op_end(this) - 1,
742 assert(IfTrue && "Branch destination may not be null!");
746 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
747 BasicBlock *InsertAtEnd)
748 : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
749 OperandTraits<BranchInst>::op_end(this) - 3,
760 BranchInst::BranchInst(const BranchInst &BI) :
761 TerminatorInst(Type::getVoidTy(BI.getContext()), Instruction::Br,
762 OperandTraits<BranchInst>::op_end(this) - BI.getNumOperands(),
763 BI.getNumOperands()) {
764 Op<-1>() = BI.Op<-1>();
765 if (BI.getNumOperands() != 1) {
766 assert(BI.getNumOperands() == 3 && "BR can have 1 or 3 operands!");
767 Op<-3>() = BI.Op<-3>();
768 Op<-2>() = BI.Op<-2>();
770 SubclassOptionalData = BI.SubclassOptionalData;
773 void BranchInst::swapSuccessors() {
774 assert(isConditional() &&
775 "Cannot swap successors of an unconditional branch");
776 Op<-1>().swap(Op<-2>());
778 // Update profile metadata if present and it matches our structural
780 MDNode *ProfileData = getMetadata(LLVMContext::MD_prof);
781 if (!ProfileData || ProfileData->getNumOperands() != 3)
784 // The first operand is the name. Fetch them backwards and build a new one.
785 Metadata *Ops[] = {ProfileData->getOperand(0), ProfileData->getOperand(2),
786 ProfileData->getOperand(1)};
787 setMetadata(LLVMContext::MD_prof,
788 MDNode::get(ProfileData->getContext(), Ops));
791 BasicBlock *BranchInst::getSuccessorV(unsigned idx) const {
792 return getSuccessor(idx);
794 unsigned BranchInst::getNumSuccessorsV() const {
795 return getNumSuccessors();
797 void BranchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
798 setSuccessor(idx, B);
802 //===----------------------------------------------------------------------===//
803 // AllocaInst Implementation
804 //===----------------------------------------------------------------------===//
806 static Value *getAISize(LLVMContext &Context, Value *Amt) {
808 Amt = ConstantInt::get(Type::getInt32Ty(Context), 1);
810 assert(!isa<BasicBlock>(Amt) &&
811 "Passed basic block into allocation size parameter! Use other ctor");
812 assert(Amt->getType()->isIntegerTy() &&
813 "Allocation array size is not an integer!");
818 AllocaInst::AllocaInst(Type *Ty, const Twine &Name, Instruction *InsertBefore)
819 : AllocaInst(Ty, /*ArraySize=*/nullptr, Name, InsertBefore) {}
821 AllocaInst::AllocaInst(Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd)
822 : AllocaInst(Ty, /*ArraySize=*/nullptr, Name, InsertAtEnd) {}
824 AllocaInst::AllocaInst(Type *Ty, Value *ArraySize, const Twine &Name,
825 Instruction *InsertBefore)
826 : AllocaInst(Ty, ArraySize, /*Align=*/0, Name, InsertBefore) {}
828 AllocaInst::AllocaInst(Type *Ty, Value *ArraySize, const Twine &Name,
829 BasicBlock *InsertAtEnd)
830 : AllocaInst(Ty, ArraySize, /*Align=*/0, Name, InsertAtEnd) {}
832 AllocaInst::AllocaInst(Type *Ty, Value *ArraySize, unsigned Align,
833 const Twine &Name, Instruction *InsertBefore)
834 : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
835 getAISize(Ty->getContext(), ArraySize), InsertBefore),
838 assert(!Ty->isVoidTy() && "Cannot allocate void!");
842 AllocaInst::AllocaInst(Type *Ty, Value *ArraySize, unsigned Align,
843 const Twine &Name, BasicBlock *InsertAtEnd)
844 : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
845 getAISize(Ty->getContext(), ArraySize), InsertAtEnd),
848 assert(!Ty->isVoidTy() && "Cannot allocate void!");
852 // Out of line virtual method, so the vtable, etc has a home.
853 AllocaInst::~AllocaInst() {
856 void AllocaInst::setAlignment(unsigned Align) {
857 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
858 assert(Align <= MaximumAlignment &&
859 "Alignment is greater than MaximumAlignment!");
860 setInstructionSubclassData((getSubclassDataFromInstruction() & ~31) |
861 (Log2_32(Align) + 1));
862 assert(getAlignment() == Align && "Alignment representation error!");
865 bool AllocaInst::isArrayAllocation() const {
866 if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(0)))
871 /// isStaticAlloca - Return true if this alloca is in the entry block of the
872 /// function and is a constant size. If so, the code generator will fold it
873 /// into the prolog/epilog code, so it is basically free.
874 bool AllocaInst::isStaticAlloca() const {
875 // Must be constant size.
876 if (!isa<ConstantInt>(getArraySize())) return false;
878 // Must be in the entry block.
879 const BasicBlock *Parent = getParent();
880 return Parent == &Parent->getParent()->front() && !isUsedWithInAlloca();
883 //===----------------------------------------------------------------------===//
884 // LoadInst Implementation
885 //===----------------------------------------------------------------------===//
887 void LoadInst::AssertOK() {
888 assert(getOperand(0)->getType()->isPointerTy() &&
889 "Ptr must have pointer type.");
890 assert(!(isAtomic() && getAlignment() == 0) &&
891 "Alignment required for atomic load");
894 LoadInst::LoadInst(Value *Ptr, const Twine &Name, Instruction *InsertBef)
895 : LoadInst(Ptr, Name, /*isVolatile=*/false, InsertBef) {}
897 LoadInst::LoadInst(Value *Ptr, const Twine &Name, BasicBlock *InsertAE)
898 : LoadInst(Ptr, Name, /*isVolatile=*/false, InsertAE) {}
900 LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name, bool isVolatile,
901 Instruction *InsertBef)
902 : LoadInst(Ty, Ptr, Name, isVolatile, /*Align=*/0, InsertBef) {}
904 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
905 BasicBlock *InsertAE)
906 : LoadInst(Ptr, Name, isVolatile, /*Align=*/0, InsertAE) {}
908 LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name, bool isVolatile,
909 unsigned Align, Instruction *InsertBef)
910 : LoadInst(Ty, Ptr, Name, isVolatile, Align, NotAtomic, CrossThread,
913 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
914 unsigned Align, BasicBlock *InsertAE)
915 : LoadInst(Ptr, Name, isVolatile, Align, NotAtomic, CrossThread, InsertAE) {
918 LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name, bool isVolatile,
919 unsigned Align, AtomicOrdering Order,
920 SynchronizationScope SynchScope, Instruction *InsertBef)
921 : UnaryInstruction(Ty, Load, Ptr, InsertBef) {
922 assert(Ty == cast<PointerType>(Ptr->getType())->getElementType());
923 setVolatile(isVolatile);
925 setAtomic(Order, SynchScope);
930 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
931 unsigned Align, AtomicOrdering Order,
932 SynchronizationScope SynchScope,
933 BasicBlock *InsertAE)
934 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
935 Load, Ptr, InsertAE) {
936 setVolatile(isVolatile);
938 setAtomic(Order, SynchScope);
943 LoadInst::LoadInst(Value *Ptr, const char *Name, Instruction *InsertBef)
944 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
945 Load, Ptr, InsertBef) {
948 setAtomic(NotAtomic);
950 if (Name && Name[0]) setName(Name);
953 LoadInst::LoadInst(Value *Ptr, const char *Name, BasicBlock *InsertAE)
954 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
955 Load, Ptr, InsertAE) {
958 setAtomic(NotAtomic);
960 if (Name && Name[0]) setName(Name);
963 LoadInst::LoadInst(Type *Ty, Value *Ptr, const char *Name, bool isVolatile,
964 Instruction *InsertBef)
965 : UnaryInstruction(Ty, Load, Ptr, InsertBef) {
966 assert(Ty == cast<PointerType>(Ptr->getType())->getElementType());
967 setVolatile(isVolatile);
969 setAtomic(NotAtomic);
971 if (Name && Name[0]) setName(Name);
974 LoadInst::LoadInst(Value *Ptr, const char *Name, bool isVolatile,
975 BasicBlock *InsertAE)
976 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
977 Load, Ptr, InsertAE) {
978 setVolatile(isVolatile);
980 setAtomic(NotAtomic);
982 if (Name && Name[0]) setName(Name);
985 void LoadInst::setAlignment(unsigned Align) {
986 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
987 assert(Align <= MaximumAlignment &&
988 "Alignment is greater than MaximumAlignment!");
989 setInstructionSubclassData((getSubclassDataFromInstruction() & ~(31 << 1)) |
990 ((Log2_32(Align)+1)<<1));
991 assert(getAlignment() == Align && "Alignment representation error!");
994 //===----------------------------------------------------------------------===//
995 // StoreInst Implementation
996 //===----------------------------------------------------------------------===//
998 void StoreInst::AssertOK() {
999 assert(getOperand(0) && getOperand(1) && "Both operands must be non-null!");
1000 assert(getOperand(1)->getType()->isPointerTy() &&
1001 "Ptr must have pointer type!");
1002 assert(getOperand(0)->getType() ==
1003 cast<PointerType>(getOperand(1)->getType())->getElementType()
1004 && "Ptr must be a pointer to Val type!");
1005 assert(!(isAtomic() && getAlignment() == 0) &&
1006 "Alignment required for atomic store");
1009 StoreInst::StoreInst(Value *val, Value *addr, Instruction *InsertBefore)
1010 : StoreInst(val, addr, /*isVolatile=*/false, InsertBefore) {}
1012 StoreInst::StoreInst(Value *val, Value *addr, BasicBlock *InsertAtEnd)
1013 : StoreInst(val, addr, /*isVolatile=*/false, InsertAtEnd) {}
1015 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1016 Instruction *InsertBefore)
1017 : StoreInst(val, addr, isVolatile, /*Align=*/0, InsertBefore) {}
1019 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1020 BasicBlock *InsertAtEnd)
1021 : StoreInst(val, addr, isVolatile, /*Align=*/0, InsertAtEnd) {}
1023 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile, unsigned Align,
1024 Instruction *InsertBefore)
1025 : StoreInst(val, addr, isVolatile, Align, NotAtomic, CrossThread,
1028 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile, unsigned Align,
1029 BasicBlock *InsertAtEnd)
1030 : StoreInst(val, addr, isVolatile, Align, NotAtomic, CrossThread,
1033 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1034 unsigned Align, AtomicOrdering Order,
1035 SynchronizationScope SynchScope,
1036 Instruction *InsertBefore)
1037 : Instruction(Type::getVoidTy(val->getContext()), Store,
1038 OperandTraits<StoreInst>::op_begin(this),
1039 OperandTraits<StoreInst>::operands(this),
1043 setVolatile(isVolatile);
1044 setAlignment(Align);
1045 setAtomic(Order, SynchScope);
1049 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1050 unsigned Align, AtomicOrdering Order,
1051 SynchronizationScope SynchScope,
1052 BasicBlock *InsertAtEnd)
1053 : Instruction(Type::getVoidTy(val->getContext()), Store,
1054 OperandTraits<StoreInst>::op_begin(this),
1055 OperandTraits<StoreInst>::operands(this),
1059 setVolatile(isVolatile);
1060 setAlignment(Align);
1061 setAtomic(Order, SynchScope);
1065 void StoreInst::setAlignment(unsigned Align) {
1066 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
1067 assert(Align <= MaximumAlignment &&
1068 "Alignment is greater than MaximumAlignment!");
1069 setInstructionSubclassData((getSubclassDataFromInstruction() & ~(31 << 1)) |
1070 ((Log2_32(Align)+1) << 1));
1071 assert(getAlignment() == Align && "Alignment representation error!");
1074 //===----------------------------------------------------------------------===//
1075 // AtomicCmpXchgInst Implementation
1076 //===----------------------------------------------------------------------===//
1078 void AtomicCmpXchgInst::Init(Value *Ptr, Value *Cmp, Value *NewVal,
1079 AtomicOrdering SuccessOrdering,
1080 AtomicOrdering FailureOrdering,
1081 SynchronizationScope SynchScope) {
1085 setSuccessOrdering(SuccessOrdering);
1086 setFailureOrdering(FailureOrdering);
1087 setSynchScope(SynchScope);
1089 assert(getOperand(0) && getOperand(1) && getOperand(2) &&
1090 "All operands must be non-null!");
1091 assert(getOperand(0)->getType()->isPointerTy() &&
1092 "Ptr must have pointer type!");
1093 assert(getOperand(1)->getType() ==
1094 cast<PointerType>(getOperand(0)->getType())->getElementType()
1095 && "Ptr must be a pointer to Cmp type!");
1096 assert(getOperand(2)->getType() ==
1097 cast<PointerType>(getOperand(0)->getType())->getElementType()
1098 && "Ptr must be a pointer to NewVal type!");
1099 assert(SuccessOrdering != NotAtomic &&
1100 "AtomicCmpXchg instructions must be atomic!");
1101 assert(FailureOrdering != NotAtomic &&
1102 "AtomicCmpXchg instructions must be atomic!");
1103 assert(SuccessOrdering >= FailureOrdering &&
1104 "AtomicCmpXchg success ordering must be at least as strong as fail");
1105 assert(FailureOrdering != Release && FailureOrdering != AcquireRelease &&
1106 "AtomicCmpXchg failure ordering cannot include release semantics");
1109 AtomicCmpXchgInst::AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal,
1110 AtomicOrdering SuccessOrdering,
1111 AtomicOrdering FailureOrdering,
1112 SynchronizationScope SynchScope,
1113 Instruction *InsertBefore)
1115 StructType::get(Cmp->getType(), Type::getInt1Ty(Cmp->getContext()),
1117 AtomicCmpXchg, OperandTraits<AtomicCmpXchgInst>::op_begin(this),
1118 OperandTraits<AtomicCmpXchgInst>::operands(this), InsertBefore) {
1119 Init(Ptr, Cmp, NewVal, SuccessOrdering, FailureOrdering, SynchScope);
1122 AtomicCmpXchgInst::AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal,
1123 AtomicOrdering SuccessOrdering,
1124 AtomicOrdering FailureOrdering,
1125 SynchronizationScope SynchScope,
1126 BasicBlock *InsertAtEnd)
1128 StructType::get(Cmp->getType(), Type::getInt1Ty(Cmp->getContext()),
1130 AtomicCmpXchg, OperandTraits<AtomicCmpXchgInst>::op_begin(this),
1131 OperandTraits<AtomicCmpXchgInst>::operands(this), InsertAtEnd) {
1132 Init(Ptr, Cmp, NewVal, SuccessOrdering, FailureOrdering, SynchScope);
1135 //===----------------------------------------------------------------------===//
1136 // AtomicRMWInst Implementation
1137 //===----------------------------------------------------------------------===//
1139 void AtomicRMWInst::Init(BinOp Operation, Value *Ptr, Value *Val,
1140 AtomicOrdering Ordering,
1141 SynchronizationScope SynchScope) {
1144 setOperation(Operation);
1145 setOrdering(Ordering);
1146 setSynchScope(SynchScope);
1148 assert(getOperand(0) && getOperand(1) &&
1149 "All operands must be non-null!");
1150 assert(getOperand(0)->getType()->isPointerTy() &&
1151 "Ptr must have pointer type!");
1152 assert(getOperand(1)->getType() ==
1153 cast<PointerType>(getOperand(0)->getType())->getElementType()
1154 && "Ptr must be a pointer to Val type!");
1155 assert(Ordering != NotAtomic &&
1156 "AtomicRMW instructions must be atomic!");
1159 AtomicRMWInst::AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val,
1160 AtomicOrdering Ordering,
1161 SynchronizationScope SynchScope,
1162 Instruction *InsertBefore)
1163 : Instruction(Val->getType(), AtomicRMW,
1164 OperandTraits<AtomicRMWInst>::op_begin(this),
1165 OperandTraits<AtomicRMWInst>::operands(this),
1167 Init(Operation, Ptr, Val, Ordering, SynchScope);
1170 AtomicRMWInst::AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val,
1171 AtomicOrdering Ordering,
1172 SynchronizationScope SynchScope,
1173 BasicBlock *InsertAtEnd)
1174 : Instruction(Val->getType(), AtomicRMW,
1175 OperandTraits<AtomicRMWInst>::op_begin(this),
1176 OperandTraits<AtomicRMWInst>::operands(this),
1178 Init(Operation, Ptr, Val, Ordering, SynchScope);
1181 //===----------------------------------------------------------------------===//
1182 // FenceInst Implementation
1183 //===----------------------------------------------------------------------===//
1185 FenceInst::FenceInst(LLVMContext &C, AtomicOrdering Ordering,
1186 SynchronizationScope SynchScope,
1187 Instruction *InsertBefore)
1188 : Instruction(Type::getVoidTy(C), Fence, nullptr, 0, InsertBefore) {
1189 setOrdering(Ordering);
1190 setSynchScope(SynchScope);
1193 FenceInst::FenceInst(LLVMContext &C, AtomicOrdering Ordering,
1194 SynchronizationScope SynchScope,
1195 BasicBlock *InsertAtEnd)
1196 : Instruction(Type::getVoidTy(C), Fence, nullptr, 0, InsertAtEnd) {
1197 setOrdering(Ordering);
1198 setSynchScope(SynchScope);
1201 //===----------------------------------------------------------------------===//
1202 // GetElementPtrInst Implementation
1203 //===----------------------------------------------------------------------===//
1205 void GetElementPtrInst::init(Value *Ptr, ArrayRef<Value *> IdxList,
1206 const Twine &Name) {
1207 assert(NumOperands == 1 + IdxList.size() && "NumOperands not initialized?");
1209 std::copy(IdxList.begin(), IdxList.end(), op_begin() + 1);
1213 GetElementPtrInst::GetElementPtrInst(const GetElementPtrInst &GEPI)
1214 : Instruction(GEPI.getType(), GetElementPtr,
1215 OperandTraits<GetElementPtrInst>::op_end(this) -
1216 GEPI.getNumOperands(),
1217 GEPI.getNumOperands()),
1218 SourceElementType(GEPI.SourceElementType),
1219 ResultElementType(GEPI.ResultElementType) {
1220 std::copy(GEPI.op_begin(), GEPI.op_end(), op_begin());
1221 SubclassOptionalData = GEPI.SubclassOptionalData;
1224 /// getIndexedType - Returns the type of the element that would be accessed with
1225 /// a gep instruction with the specified parameters.
1227 /// The Idxs pointer should point to a continuous piece of memory containing the
1228 /// indices, either as Value* or uint64_t.
1230 /// A null type is returned if the indices are invalid for the specified
1233 template <typename IndexTy>
1234 static Type *getIndexedTypeInternal(Type *Agg, ArrayRef<IndexTy> IdxList) {
1235 // Handle the special case of the empty set index set, which is always valid.
1236 if (IdxList.empty())
1239 // If there is at least one index, the top level type must be sized, otherwise
1240 // it cannot be 'stepped over'.
1241 if (!Agg->isSized())
1244 unsigned CurIdx = 1;
1245 for (; CurIdx != IdxList.size(); ++CurIdx) {
1246 CompositeType *CT = dyn_cast<CompositeType>(Agg);
1247 if (!CT || CT->isPointerTy()) return nullptr;
1248 IndexTy Index = IdxList[CurIdx];
1249 if (!CT->indexValid(Index)) return nullptr;
1250 Agg = CT->getTypeAtIndex(Index);
1252 return CurIdx == IdxList.size() ? Agg : nullptr;
1255 Type *GetElementPtrInst::getIndexedType(Type *Ty, ArrayRef<Value *> IdxList) {
1256 return getIndexedTypeInternal(Ty, IdxList);
1259 Type *GetElementPtrInst::getIndexedType(Type *Ty,
1260 ArrayRef<Constant *> IdxList) {
1261 return getIndexedTypeInternal(Ty, IdxList);
1264 Type *GetElementPtrInst::getIndexedType(Type *Ty, ArrayRef<uint64_t> IdxList) {
1265 return getIndexedTypeInternal(Ty, IdxList);
1268 /// hasAllZeroIndices - Return true if all of the indices of this GEP are
1269 /// zeros. If so, the result pointer and the first operand have the same
1270 /// value, just potentially different types.
1271 bool GetElementPtrInst::hasAllZeroIndices() const {
1272 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1273 if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(i))) {
1274 if (!CI->isZero()) return false;
1282 /// hasAllConstantIndices - Return true if all of the indices of this GEP are
1283 /// constant integers. If so, the result pointer and the first operand have
1284 /// a constant offset between them.
1285 bool GetElementPtrInst::hasAllConstantIndices() const {
1286 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1287 if (!isa<ConstantInt>(getOperand(i)))
1293 void GetElementPtrInst::setIsInBounds(bool B) {
1294 cast<GEPOperator>(this)->setIsInBounds(B);
1297 bool GetElementPtrInst::isInBounds() const {
1298 return cast<GEPOperator>(this)->isInBounds();
1301 bool GetElementPtrInst::accumulateConstantOffset(const DataLayout &DL,
1302 APInt &Offset) const {
1303 // Delegate to the generic GEPOperator implementation.
1304 return cast<GEPOperator>(this)->accumulateConstantOffset(DL, Offset);
1307 //===----------------------------------------------------------------------===//
1308 // ExtractElementInst Implementation
1309 //===----------------------------------------------------------------------===//
1311 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
1313 Instruction *InsertBef)
1314 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1316 OperandTraits<ExtractElementInst>::op_begin(this),
1318 assert(isValidOperands(Val, Index) &&
1319 "Invalid extractelement instruction operands!");
1325 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
1327 BasicBlock *InsertAE)
1328 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1330 OperandTraits<ExtractElementInst>::op_begin(this),
1332 assert(isValidOperands(Val, Index) &&
1333 "Invalid extractelement instruction operands!");
1341 bool ExtractElementInst::isValidOperands(const Value *Val, const Value *Index) {
1342 if (!Val->getType()->isVectorTy() || !Index->getType()->isIntegerTy())
1348 //===----------------------------------------------------------------------===//
1349 // InsertElementInst Implementation
1350 //===----------------------------------------------------------------------===//
1352 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
1354 Instruction *InsertBef)
1355 : Instruction(Vec->getType(), InsertElement,
1356 OperandTraits<InsertElementInst>::op_begin(this),
1358 assert(isValidOperands(Vec, Elt, Index) &&
1359 "Invalid insertelement instruction operands!");
1366 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
1368 BasicBlock *InsertAE)
1369 : Instruction(Vec->getType(), InsertElement,
1370 OperandTraits<InsertElementInst>::op_begin(this),
1372 assert(isValidOperands(Vec, Elt, Index) &&
1373 "Invalid insertelement instruction operands!");
1381 bool InsertElementInst::isValidOperands(const Value *Vec, const Value *Elt,
1382 const Value *Index) {
1383 if (!Vec->getType()->isVectorTy())
1384 return false; // First operand of insertelement must be vector type.
1386 if (Elt->getType() != cast<VectorType>(Vec->getType())->getElementType())
1387 return false;// Second operand of insertelement must be vector element type.
1389 if (!Index->getType()->isIntegerTy())
1390 return false; // Third operand of insertelement must be i32.
1395 //===----------------------------------------------------------------------===//
1396 // ShuffleVectorInst Implementation
1397 //===----------------------------------------------------------------------===//
1399 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1401 Instruction *InsertBefore)
1402 : Instruction(VectorType::get(cast<VectorType>(V1->getType())->getElementType(),
1403 cast<VectorType>(Mask->getType())->getNumElements()),
1405 OperandTraits<ShuffleVectorInst>::op_begin(this),
1406 OperandTraits<ShuffleVectorInst>::operands(this),
1408 assert(isValidOperands(V1, V2, Mask) &&
1409 "Invalid shuffle vector instruction operands!");
1416 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1418 BasicBlock *InsertAtEnd)
1419 : Instruction(VectorType::get(cast<VectorType>(V1->getType())->getElementType(),
1420 cast<VectorType>(Mask->getType())->getNumElements()),
1422 OperandTraits<ShuffleVectorInst>::op_begin(this),
1423 OperandTraits<ShuffleVectorInst>::operands(this),
1425 assert(isValidOperands(V1, V2, Mask) &&
1426 "Invalid shuffle vector instruction operands!");
1434 bool ShuffleVectorInst::isValidOperands(const Value *V1, const Value *V2,
1435 const Value *Mask) {
1436 // V1 and V2 must be vectors of the same type.
1437 if (!V1->getType()->isVectorTy() || V1->getType() != V2->getType())
1440 // Mask must be vector of i32.
1441 VectorType *MaskTy = dyn_cast<VectorType>(Mask->getType());
1442 if (!MaskTy || !MaskTy->getElementType()->isIntegerTy(32))
1445 // Check to see if Mask is valid.
1446 if (isa<UndefValue>(Mask) || isa<ConstantAggregateZero>(Mask))
1449 if (const ConstantVector *MV = dyn_cast<ConstantVector>(Mask)) {
1450 unsigned V1Size = cast<VectorType>(V1->getType())->getNumElements();
1451 for (Value *Op : MV->operands()) {
1452 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
1453 if (CI->uge(V1Size*2))
1455 } else if (!isa<UndefValue>(Op)) {
1462 if (const ConstantDataSequential *CDS =
1463 dyn_cast<ConstantDataSequential>(Mask)) {
1464 unsigned V1Size = cast<VectorType>(V1->getType())->getNumElements();
1465 for (unsigned i = 0, e = MaskTy->getNumElements(); i != e; ++i)
1466 if (CDS->getElementAsInteger(i) >= V1Size*2)
1471 // The bitcode reader can create a place holder for a forward reference
1472 // used as the shuffle mask. When this occurs, the shuffle mask will
1473 // fall into this case and fail. To avoid this error, do this bit of
1474 // ugliness to allow such a mask pass.
1475 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(Mask))
1476 if (CE->getOpcode() == Instruction::UserOp1)
1482 /// getMaskValue - Return the index from the shuffle mask for the specified
1483 /// output result. This is either -1 if the element is undef or a number less
1484 /// than 2*numelements.
1485 int ShuffleVectorInst::getMaskValue(Constant *Mask, unsigned i) {
1486 assert(i < Mask->getType()->getVectorNumElements() && "Index out of range");
1487 if (ConstantDataSequential *CDS =dyn_cast<ConstantDataSequential>(Mask))
1488 return CDS->getElementAsInteger(i);
1489 Constant *C = Mask->getAggregateElement(i);
1490 if (isa<UndefValue>(C))
1492 return cast<ConstantInt>(C)->getZExtValue();
1495 /// getShuffleMask - Return the full mask for this instruction, where each
1496 /// element is the element number and undef's are returned as -1.
1497 void ShuffleVectorInst::getShuffleMask(Constant *Mask,
1498 SmallVectorImpl<int> &Result) {
1499 unsigned NumElts = Mask->getType()->getVectorNumElements();
1501 if (ConstantDataSequential *CDS=dyn_cast<ConstantDataSequential>(Mask)) {
1502 for (unsigned i = 0; i != NumElts; ++i)
1503 Result.push_back(CDS->getElementAsInteger(i));
1506 for (unsigned i = 0; i != NumElts; ++i) {
1507 Constant *C = Mask->getAggregateElement(i);
1508 Result.push_back(isa<UndefValue>(C) ? -1 :
1509 cast<ConstantInt>(C)->getZExtValue());
1514 //===----------------------------------------------------------------------===//
1515 // InsertValueInst Class
1516 //===----------------------------------------------------------------------===//
1518 void InsertValueInst::init(Value *Agg, Value *Val, ArrayRef<unsigned> Idxs,
1519 const Twine &Name) {
1520 assert(NumOperands == 2 && "NumOperands not initialized?");
1522 // There's no fundamental reason why we require at least one index
1523 // (other than weirdness with &*IdxBegin being invalid; see
1524 // getelementptr's init routine for example). But there's no
1525 // present need to support it.
1526 assert(Idxs.size() > 0 && "InsertValueInst must have at least one index");
1528 assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs) ==
1529 Val->getType() && "Inserted value must match indexed type!");
1533 Indices.append(Idxs.begin(), Idxs.end());
1537 InsertValueInst::InsertValueInst(const InsertValueInst &IVI)
1538 : Instruction(IVI.getType(), InsertValue,
1539 OperandTraits<InsertValueInst>::op_begin(this), 2),
1540 Indices(IVI.Indices) {
1541 Op<0>() = IVI.getOperand(0);
1542 Op<1>() = IVI.getOperand(1);
1543 SubclassOptionalData = IVI.SubclassOptionalData;
1546 //===----------------------------------------------------------------------===//
1547 // ExtractValueInst Class
1548 //===----------------------------------------------------------------------===//
1550 void ExtractValueInst::init(ArrayRef<unsigned> Idxs, const Twine &Name) {
1551 assert(NumOperands == 1 && "NumOperands not initialized?");
1553 // There's no fundamental reason why we require at least one index.
1554 // But there's no present need to support it.
1555 assert(Idxs.size() > 0 && "ExtractValueInst must have at least one index");
1557 Indices.append(Idxs.begin(), Idxs.end());
1561 ExtractValueInst::ExtractValueInst(const ExtractValueInst &EVI)
1562 : UnaryInstruction(EVI.getType(), ExtractValue, EVI.getOperand(0)),
1563 Indices(EVI.Indices) {
1564 SubclassOptionalData = EVI.SubclassOptionalData;
1567 // getIndexedType - Returns the type of the element that would be extracted
1568 // with an extractvalue instruction with the specified parameters.
1570 // A null type is returned if the indices are invalid for the specified
1573 Type *ExtractValueInst::getIndexedType(Type *Agg,
1574 ArrayRef<unsigned> Idxs) {
1575 for (unsigned Index : Idxs) {
1576 // We can't use CompositeType::indexValid(Index) here.
1577 // indexValid() always returns true for arrays because getelementptr allows
1578 // out-of-bounds indices. Since we don't allow those for extractvalue and
1579 // insertvalue we need to check array indexing manually.
1580 // Since the only other types we can index into are struct types it's just
1581 // as easy to check those manually as well.
1582 if (ArrayType *AT = dyn_cast<ArrayType>(Agg)) {
1583 if (Index >= AT->getNumElements())
1585 } else if (StructType *ST = dyn_cast<StructType>(Agg)) {
1586 if (Index >= ST->getNumElements())
1589 // Not a valid type to index into.
1593 Agg = cast<CompositeType>(Agg)->getTypeAtIndex(Index);
1595 return const_cast<Type*>(Agg);
1598 //===----------------------------------------------------------------------===//
1599 // BinaryOperator Class
1600 //===----------------------------------------------------------------------===//
1602 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
1603 Type *Ty, const Twine &Name,
1604 Instruction *InsertBefore)
1605 : Instruction(Ty, iType,
1606 OperandTraits<BinaryOperator>::op_begin(this),
1607 OperandTraits<BinaryOperator>::operands(this),
1615 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
1616 Type *Ty, const Twine &Name,
1617 BasicBlock *InsertAtEnd)
1618 : Instruction(Ty, iType,
1619 OperandTraits<BinaryOperator>::op_begin(this),
1620 OperandTraits<BinaryOperator>::operands(this),
1629 void BinaryOperator::init(BinaryOps iType) {
1630 Value *LHS = getOperand(0), *RHS = getOperand(1);
1631 (void)LHS; (void)RHS; // Silence warnings.
1632 assert(LHS->getType() == RHS->getType() &&
1633 "Binary operator operand types must match!");
1638 assert(getType() == LHS->getType() &&
1639 "Arithmetic operation should return same type as operands!");
1640 assert(getType()->isIntOrIntVectorTy() &&
1641 "Tried to create an integer operation on a non-integer type!");
1643 case FAdd: case FSub:
1645 assert(getType() == LHS->getType() &&
1646 "Arithmetic operation should return same type as operands!");
1647 assert(getType()->isFPOrFPVectorTy() &&
1648 "Tried to create a floating-point operation on a "
1649 "non-floating-point type!");
1653 assert(getType() == LHS->getType() &&
1654 "Arithmetic operation should return same type as operands!");
1655 assert((getType()->isIntegerTy() || (getType()->isVectorTy() &&
1656 cast<VectorType>(getType())->getElementType()->isIntegerTy())) &&
1657 "Incorrect operand type (not integer) for S/UDIV");
1660 assert(getType() == LHS->getType() &&
1661 "Arithmetic operation should return same type as operands!");
1662 assert(getType()->isFPOrFPVectorTy() &&
1663 "Incorrect operand type (not floating point) for FDIV");
1667 assert(getType() == LHS->getType() &&
1668 "Arithmetic operation should return same type as operands!");
1669 assert((getType()->isIntegerTy() || (getType()->isVectorTy() &&
1670 cast<VectorType>(getType())->getElementType()->isIntegerTy())) &&
1671 "Incorrect operand type (not integer) for S/UREM");
1674 assert(getType() == LHS->getType() &&
1675 "Arithmetic operation should return same type as operands!");
1676 assert(getType()->isFPOrFPVectorTy() &&
1677 "Incorrect operand type (not floating point) for FREM");
1682 assert(getType() == LHS->getType() &&
1683 "Shift operation should return same type as operands!");
1684 assert((getType()->isIntegerTy() ||
1685 (getType()->isVectorTy() &&
1686 cast<VectorType>(getType())->getElementType()->isIntegerTy())) &&
1687 "Tried to create a shift operation on a non-integral type!");
1691 assert(getType() == LHS->getType() &&
1692 "Logical operation should return same type as operands!");
1693 assert((getType()->isIntegerTy() ||
1694 (getType()->isVectorTy() &&
1695 cast<VectorType>(getType())->getElementType()->isIntegerTy())) &&
1696 "Tried to create a logical operation on a non-integral type!");
1704 BinaryOperator *BinaryOperator::Create(BinaryOps Op, Value *S1, Value *S2,
1706 Instruction *InsertBefore) {
1707 assert(S1->getType() == S2->getType() &&
1708 "Cannot create binary operator with two operands of differing type!");
1709 return new BinaryOperator(Op, S1, S2, S1->getType(), Name, InsertBefore);
1712 BinaryOperator *BinaryOperator::Create(BinaryOps Op, Value *S1, Value *S2,
1714 BasicBlock *InsertAtEnd) {
1715 BinaryOperator *Res = Create(Op, S1, S2, Name);
1716 InsertAtEnd->getInstList().push_back(Res);
1720 BinaryOperator *BinaryOperator::CreateNeg(Value *Op, const Twine &Name,
1721 Instruction *InsertBefore) {
1722 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1723 return new BinaryOperator(Instruction::Sub,
1725 Op->getType(), Name, InsertBefore);
1728 BinaryOperator *BinaryOperator::CreateNeg(Value *Op, const Twine &Name,
1729 BasicBlock *InsertAtEnd) {
1730 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1731 return new BinaryOperator(Instruction::Sub,
1733 Op->getType(), Name, InsertAtEnd);
1736 BinaryOperator *BinaryOperator::CreateNSWNeg(Value *Op, const Twine &Name,
1737 Instruction *InsertBefore) {
1738 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1739 return BinaryOperator::CreateNSWSub(zero, Op, Name, InsertBefore);
1742 BinaryOperator *BinaryOperator::CreateNSWNeg(Value *Op, const Twine &Name,
1743 BasicBlock *InsertAtEnd) {
1744 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1745 return BinaryOperator::CreateNSWSub(zero, Op, Name, InsertAtEnd);
1748 BinaryOperator *BinaryOperator::CreateNUWNeg(Value *Op, const Twine &Name,
1749 Instruction *InsertBefore) {
1750 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1751 return BinaryOperator::CreateNUWSub(zero, Op, Name, InsertBefore);
1754 BinaryOperator *BinaryOperator::CreateNUWNeg(Value *Op, const Twine &Name,
1755 BasicBlock *InsertAtEnd) {
1756 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1757 return BinaryOperator::CreateNUWSub(zero, Op, Name, InsertAtEnd);
1760 BinaryOperator *BinaryOperator::CreateFNeg(Value *Op, const Twine &Name,
1761 Instruction *InsertBefore) {
1762 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1763 return new BinaryOperator(Instruction::FSub, zero, Op,
1764 Op->getType(), Name, InsertBefore);
1767 BinaryOperator *BinaryOperator::CreateFNeg(Value *Op, const Twine &Name,
1768 BasicBlock *InsertAtEnd) {
1769 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1770 return new BinaryOperator(Instruction::FSub, zero, Op,
1771 Op->getType(), Name, InsertAtEnd);
1774 BinaryOperator *BinaryOperator::CreateNot(Value *Op, const Twine &Name,
1775 Instruction *InsertBefore) {
1776 Constant *C = Constant::getAllOnesValue(Op->getType());
1777 return new BinaryOperator(Instruction::Xor, Op, C,
1778 Op->getType(), Name, InsertBefore);
1781 BinaryOperator *BinaryOperator::CreateNot(Value *Op, const Twine &Name,
1782 BasicBlock *InsertAtEnd) {
1783 Constant *AllOnes = Constant::getAllOnesValue(Op->getType());
1784 return new BinaryOperator(Instruction::Xor, Op, AllOnes,
1785 Op->getType(), Name, InsertAtEnd);
1789 // isConstantAllOnes - Helper function for several functions below
1790 static inline bool isConstantAllOnes(const Value *V) {
1791 if (const Constant *C = dyn_cast<Constant>(V))
1792 return C->isAllOnesValue();
1796 bool BinaryOperator::isNeg(const Value *V) {
1797 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1798 if (Bop->getOpcode() == Instruction::Sub)
1799 if (Constant* C = dyn_cast<Constant>(Bop->getOperand(0)))
1800 return C->isNegativeZeroValue();
1804 bool BinaryOperator::isFNeg(const Value *V, bool IgnoreZeroSign) {
1805 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1806 if (Bop->getOpcode() == Instruction::FSub)
1807 if (Constant* C = dyn_cast<Constant>(Bop->getOperand(0))) {
1808 if (!IgnoreZeroSign)
1809 IgnoreZeroSign = cast<Instruction>(V)->hasNoSignedZeros();
1810 return !IgnoreZeroSign ? C->isNegativeZeroValue() : C->isZeroValue();
1815 bool BinaryOperator::isNot(const Value *V) {
1816 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1817 return (Bop->getOpcode() == Instruction::Xor &&
1818 (isConstantAllOnes(Bop->getOperand(1)) ||
1819 isConstantAllOnes(Bop->getOperand(0))));
1823 Value *BinaryOperator::getNegArgument(Value *BinOp) {
1824 return cast<BinaryOperator>(BinOp)->getOperand(1);
1827 const Value *BinaryOperator::getNegArgument(const Value *BinOp) {
1828 return getNegArgument(const_cast<Value*>(BinOp));
1831 Value *BinaryOperator::getFNegArgument(Value *BinOp) {
1832 return cast<BinaryOperator>(BinOp)->getOperand(1);
1835 const Value *BinaryOperator::getFNegArgument(const Value *BinOp) {
1836 return getFNegArgument(const_cast<Value*>(BinOp));
1839 Value *BinaryOperator::getNotArgument(Value *BinOp) {
1840 assert(isNot(BinOp) && "getNotArgument on non-'not' instruction!");
1841 BinaryOperator *BO = cast<BinaryOperator>(BinOp);
1842 Value *Op0 = BO->getOperand(0);
1843 Value *Op1 = BO->getOperand(1);
1844 if (isConstantAllOnes(Op0)) return Op1;
1846 assert(isConstantAllOnes(Op1));
1850 const Value *BinaryOperator::getNotArgument(const Value *BinOp) {
1851 return getNotArgument(const_cast<Value*>(BinOp));
1855 // swapOperands - Exchange the two operands to this instruction. This
1856 // instruction is safe to use on any binary instruction and does not
1857 // modify the semantics of the instruction. If the instruction is
1858 // order dependent (SetLT f.e.) the opcode is changed.
1860 bool BinaryOperator::swapOperands() {
1861 if (!isCommutative())
1862 return true; // Can't commute operands
1863 Op<0>().swap(Op<1>());
1867 void BinaryOperator::setHasNoUnsignedWrap(bool b) {
1868 cast<OverflowingBinaryOperator>(this)->setHasNoUnsignedWrap(b);
1871 void BinaryOperator::setHasNoSignedWrap(bool b) {
1872 cast<OverflowingBinaryOperator>(this)->setHasNoSignedWrap(b);
1875 void BinaryOperator::setIsExact(bool b) {
1876 cast<PossiblyExactOperator>(this)->setIsExact(b);
1879 bool BinaryOperator::hasNoUnsignedWrap() const {
1880 return cast<OverflowingBinaryOperator>(this)->hasNoUnsignedWrap();
1883 bool BinaryOperator::hasNoSignedWrap() const {
1884 return cast<OverflowingBinaryOperator>(this)->hasNoSignedWrap();
1887 bool BinaryOperator::isExact() const {
1888 return cast<PossiblyExactOperator>(this)->isExact();
1891 void BinaryOperator::copyIRFlags(const Value *V) {
1892 // Copy the wrapping flags.
1893 if (auto *OB = dyn_cast<OverflowingBinaryOperator>(V)) {
1894 setHasNoSignedWrap(OB->hasNoSignedWrap());
1895 setHasNoUnsignedWrap(OB->hasNoUnsignedWrap());
1898 // Copy the exact flag.
1899 if (auto *PE = dyn_cast<PossiblyExactOperator>(V))
1900 setIsExact(PE->isExact());
1902 // Copy the fast-math flags.
1903 if (auto *FP = dyn_cast<FPMathOperator>(V))
1904 copyFastMathFlags(FP->getFastMathFlags());
1907 void BinaryOperator::andIRFlags(const Value *V) {
1908 if (auto *OB = dyn_cast<OverflowingBinaryOperator>(V)) {
1909 setHasNoSignedWrap(hasNoSignedWrap() & OB->hasNoSignedWrap());
1910 setHasNoUnsignedWrap(hasNoUnsignedWrap() & OB->hasNoUnsignedWrap());
1913 if (auto *PE = dyn_cast<PossiblyExactOperator>(V))
1914 setIsExact(isExact() & PE->isExact());
1916 if (auto *FP = dyn_cast<FPMathOperator>(V)) {
1917 FastMathFlags FM = getFastMathFlags();
1918 FM &= FP->getFastMathFlags();
1919 copyFastMathFlags(FM);
1924 //===----------------------------------------------------------------------===//
1925 // FPMathOperator Class
1926 //===----------------------------------------------------------------------===//
1928 /// getFPAccuracy - Get the maximum error permitted by this operation in ULPs.
1929 /// An accuracy of 0.0 means that the operation should be performed with the
1930 /// default precision.
1931 float FPMathOperator::getFPAccuracy() const {
1933 cast<Instruction>(this)->getMetadata(LLVMContext::MD_fpmath);
1936 ConstantFP *Accuracy = mdconst::extract<ConstantFP>(MD->getOperand(0));
1937 return Accuracy->getValueAPF().convertToFloat();
1941 //===----------------------------------------------------------------------===//
1943 //===----------------------------------------------------------------------===//
1945 void CastInst::anchor() {}
1947 // Just determine if this cast only deals with integral->integral conversion.
1948 bool CastInst::isIntegerCast() const {
1949 switch (getOpcode()) {
1950 default: return false;
1951 case Instruction::ZExt:
1952 case Instruction::SExt:
1953 case Instruction::Trunc:
1955 case Instruction::BitCast:
1956 return getOperand(0)->getType()->isIntegerTy() &&
1957 getType()->isIntegerTy();
1961 bool CastInst::isLosslessCast() const {
1962 // Only BitCast can be lossless, exit fast if we're not BitCast
1963 if (getOpcode() != Instruction::BitCast)
1966 // Identity cast is always lossless
1967 Type* SrcTy = getOperand(0)->getType();
1968 Type* DstTy = getType();
1972 // Pointer to pointer is always lossless.
1973 if (SrcTy->isPointerTy())
1974 return DstTy->isPointerTy();
1975 return false; // Other types have no identity values
1978 /// This function determines if the CastInst does not require any bits to be
1979 /// changed in order to effect the cast. Essentially, it identifies cases where
1980 /// no code gen is necessary for the cast, hence the name no-op cast. For
1981 /// example, the following are all no-op casts:
1982 /// # bitcast i32* %x to i8*
1983 /// # bitcast <2 x i32> %x to <4 x i16>
1984 /// # ptrtoint i32* %x to i32 ; on 32-bit plaforms only
1985 /// @brief Determine if the described cast is a no-op.
1986 bool CastInst::isNoopCast(Instruction::CastOps Opcode,
1991 default: llvm_unreachable("Invalid CastOp");
1992 case Instruction::Trunc:
1993 case Instruction::ZExt:
1994 case Instruction::SExt:
1995 case Instruction::FPTrunc:
1996 case Instruction::FPExt:
1997 case Instruction::UIToFP:
1998 case Instruction::SIToFP:
1999 case Instruction::FPToUI:
2000 case Instruction::FPToSI:
2001 case Instruction::AddrSpaceCast:
2002 // TODO: Target informations may give a more accurate answer here.
2004 case Instruction::BitCast:
2005 return true; // BitCast never modifies bits.
2006 case Instruction::PtrToInt:
2007 return IntPtrTy->getScalarSizeInBits() ==
2008 DestTy->getScalarSizeInBits();
2009 case Instruction::IntToPtr:
2010 return IntPtrTy->getScalarSizeInBits() ==
2011 SrcTy->getScalarSizeInBits();
2015 /// @brief Determine if a cast is a no-op.
2016 bool CastInst::isNoopCast(Type *IntPtrTy) const {
2017 return isNoopCast(getOpcode(), getOperand(0)->getType(), getType(), IntPtrTy);
2020 bool CastInst::isNoopCast(const DataLayout &DL) const {
2021 Type *PtrOpTy = nullptr;
2022 if (getOpcode() == Instruction::PtrToInt)
2023 PtrOpTy = getOperand(0)->getType();
2024 else if (getOpcode() == Instruction::IntToPtr)
2025 PtrOpTy = getType();
2028 PtrOpTy ? DL.getIntPtrType(PtrOpTy) : DL.getIntPtrType(getContext(), 0);
2030 return isNoopCast(getOpcode(), getOperand(0)->getType(), getType(), IntPtrTy);
2033 /// This function determines if a pair of casts can be eliminated and what
2034 /// opcode should be used in the elimination. This assumes that there are two
2035 /// instructions like this:
2036 /// * %F = firstOpcode SrcTy %x to MidTy
2037 /// * %S = secondOpcode MidTy %F to DstTy
2038 /// The function returns a resultOpcode so these two casts can be replaced with:
2039 /// * %Replacement = resultOpcode %SrcTy %x to DstTy
2040 /// If no such cast is permited, the function returns 0.
2041 unsigned CastInst::isEliminableCastPair(
2042 Instruction::CastOps firstOp, Instruction::CastOps secondOp,
2043 Type *SrcTy, Type *MidTy, Type *DstTy, Type *SrcIntPtrTy, Type *MidIntPtrTy,
2044 Type *DstIntPtrTy) {
2045 // Define the 144 possibilities for these two cast instructions. The values
2046 // in this matrix determine what to do in a given situation and select the
2047 // case in the switch below. The rows correspond to firstOp, the columns
2048 // correspond to secondOp. In looking at the table below, keep in mind
2049 // the following cast properties:
2051 // Size Compare Source Destination
2052 // Operator Src ? Size Type Sign Type Sign
2053 // -------- ------------ ------------------- ---------------------
2054 // TRUNC > Integer Any Integral Any
2055 // ZEXT < Integral Unsigned Integer Any
2056 // SEXT < Integral Signed Integer Any
2057 // FPTOUI n/a FloatPt n/a Integral Unsigned
2058 // FPTOSI n/a FloatPt n/a Integral Signed
2059 // UITOFP n/a Integral Unsigned FloatPt n/a
2060 // SITOFP n/a Integral Signed FloatPt n/a
2061 // FPTRUNC > FloatPt n/a FloatPt n/a
2062 // FPEXT < FloatPt n/a FloatPt n/a
2063 // PTRTOINT n/a Pointer n/a Integral Unsigned
2064 // INTTOPTR n/a Integral Unsigned Pointer n/a
2065 // BITCAST = FirstClass n/a FirstClass n/a
2066 // ADDRSPCST n/a Pointer n/a Pointer n/a
2068 // NOTE: some transforms are safe, but we consider them to be non-profitable.
2069 // For example, we could merge "fptoui double to i32" + "zext i32 to i64",
2070 // into "fptoui double to i64", but this loses information about the range
2071 // of the produced value (we no longer know the top-part is all zeros).
2072 // Further this conversion is often much more expensive for typical hardware,
2073 // and causes issues when building libgcc. We disallow fptosi+sext for the
2075 const unsigned numCastOps =
2076 Instruction::CastOpsEnd - Instruction::CastOpsBegin;
2077 static const uint8_t CastResults[numCastOps][numCastOps] = {
2078 // T F F U S F F P I B A -+
2079 // R Z S P P I I T P 2 N T S |
2080 // U E E 2 2 2 2 R E I T C C +- secondOp
2081 // N X X U S F F N X N 2 V V |
2082 // C T T I I P P C T T P T T -+
2083 { 1, 0, 0,99,99, 0, 0,99,99,99, 0, 3, 0}, // Trunc -+
2084 { 8, 1, 9,99,99, 2,17,99,99,99, 2, 3, 0}, // ZExt |
2085 { 8, 0, 1,99,99, 0, 2,99,99,99, 0, 3, 0}, // SExt |
2086 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3, 0}, // FPToUI |
2087 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3, 0}, // FPToSI |
2088 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4, 0}, // UIToFP +- firstOp
2089 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4, 0}, // SIToFP |
2090 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4, 0}, // FPTrunc |
2091 { 99,99,99, 2, 2,99,99,10, 2,99,99, 4, 0}, // FPExt |
2092 { 1, 0, 0,99,99, 0, 0,99,99,99, 7, 3, 0}, // PtrToInt |
2093 { 99,99,99,99,99,99,99,99,99,11,99,15, 0}, // IntToPtr |
2094 { 5, 5, 5, 6, 6, 5, 5, 6, 6,16, 5, 1,14}, // BitCast |
2095 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,13,12}, // AddrSpaceCast -+
2098 // If either of the casts are a bitcast from scalar to vector, disallow the
2099 // merging. However, bitcast of A->B->A are allowed.
2100 bool isFirstBitcast = (firstOp == Instruction::BitCast);
2101 bool isSecondBitcast = (secondOp == Instruction::BitCast);
2102 bool chainedBitcast = (SrcTy == DstTy && isFirstBitcast && isSecondBitcast);
2104 // Check if any of the bitcasts convert scalars<->vectors.
2105 if ((isFirstBitcast && isa<VectorType>(SrcTy) != isa<VectorType>(MidTy)) ||
2106 (isSecondBitcast && isa<VectorType>(MidTy) != isa<VectorType>(DstTy)))
2107 // Unless we are bitcasing to the original type, disallow optimizations.
2108 if (!chainedBitcast) return 0;
2110 int ElimCase = CastResults[firstOp-Instruction::CastOpsBegin]
2111 [secondOp-Instruction::CastOpsBegin];
2114 // Categorically disallowed.
2117 // Allowed, use first cast's opcode.
2120 // Allowed, use second cast's opcode.
2123 // No-op cast in second op implies firstOp as long as the DestTy
2124 // is integer and we are not converting between a vector and a
2126 if (!SrcTy->isVectorTy() && DstTy->isIntegerTy())
2130 // No-op cast in second op implies firstOp as long as the DestTy
2131 // is floating point.
2132 if (DstTy->isFloatingPointTy())
2136 // No-op cast in first op implies secondOp as long as the SrcTy
2138 if (SrcTy->isIntegerTy())
2142 // No-op cast in first op implies secondOp as long as the SrcTy
2143 // is a floating point.
2144 if (SrcTy->isFloatingPointTy())
2148 // Cannot simplify if address spaces are different!
2149 if (SrcTy->getPointerAddressSpace() != DstTy->getPointerAddressSpace())
2152 unsigned MidSize = MidTy->getScalarSizeInBits();
2153 // We can still fold this without knowing the actual sizes as long we
2154 // know that the intermediate pointer is the largest possible
2156 // FIXME: Is this always true?
2158 return Instruction::BitCast;
2160 // ptrtoint, inttoptr -> bitcast (ptr -> ptr) if int size is >= ptr size.
2161 if (!SrcIntPtrTy || DstIntPtrTy != SrcIntPtrTy)
2163 unsigned PtrSize = SrcIntPtrTy->getScalarSizeInBits();
2164 if (MidSize >= PtrSize)
2165 return Instruction::BitCast;
2169 // ext, trunc -> bitcast, if the SrcTy and DstTy are same size
2170 // ext, trunc -> ext, if sizeof(SrcTy) < sizeof(DstTy)
2171 // ext, trunc -> trunc, if sizeof(SrcTy) > sizeof(DstTy)
2172 unsigned SrcSize = SrcTy->getScalarSizeInBits();
2173 unsigned DstSize = DstTy->getScalarSizeInBits();
2174 if (SrcSize == DstSize)
2175 return Instruction::BitCast;
2176 else if (SrcSize < DstSize)
2181 // zext, sext -> zext, because sext can't sign extend after zext
2182 return Instruction::ZExt;
2184 // fpext followed by ftrunc is allowed if the bit size returned to is
2185 // the same as the original, in which case its just a bitcast
2187 return Instruction::BitCast;
2188 return 0; // If the types are not the same we can't eliminate it.
2190 // inttoptr, ptrtoint -> bitcast if SrcSize<=PtrSize and SrcSize==DstSize
2193 unsigned PtrSize = MidIntPtrTy->getScalarSizeInBits();
2194 unsigned SrcSize = SrcTy->getScalarSizeInBits();
2195 unsigned DstSize = DstTy->getScalarSizeInBits();
2196 if (SrcSize <= PtrSize && SrcSize == DstSize)
2197 return Instruction::BitCast;
2201 // addrspacecast, addrspacecast -> bitcast, if SrcAS == DstAS
2202 // addrspacecast, addrspacecast -> addrspacecast, if SrcAS != DstAS
2203 if (SrcTy->getPointerAddressSpace() != DstTy->getPointerAddressSpace())
2204 return Instruction::AddrSpaceCast;
2205 return Instruction::BitCast;
2208 // FIXME: this state can be merged with (1), but the following assert
2209 // is useful to check the correcteness of the sequence due to semantic
2210 // change of bitcast.
2212 SrcTy->isPtrOrPtrVectorTy() &&
2213 MidTy->isPtrOrPtrVectorTy() &&
2214 DstTy->isPtrOrPtrVectorTy() &&
2215 SrcTy->getPointerAddressSpace() != MidTy->getPointerAddressSpace() &&
2216 MidTy->getPointerAddressSpace() == DstTy->getPointerAddressSpace() &&
2217 "Illegal addrspacecast, bitcast sequence!");
2218 // Allowed, use first cast's opcode
2221 // bitcast, addrspacecast -> addrspacecast if the element type of
2222 // bitcast's source is the same as that of addrspacecast's destination.
2223 if (SrcTy->getPointerElementType() == DstTy->getPointerElementType())
2224 return Instruction::AddrSpaceCast;
2228 // FIXME: this state can be merged with (1), but the following assert
2229 // is useful to check the correcteness of the sequence due to semantic
2230 // change of bitcast.
2232 SrcTy->isIntOrIntVectorTy() &&
2233 MidTy->isPtrOrPtrVectorTy() &&
2234 DstTy->isPtrOrPtrVectorTy() &&
2235 MidTy->getPointerAddressSpace() == DstTy->getPointerAddressSpace() &&
2236 "Illegal inttoptr, bitcast sequence!");
2237 // Allowed, use first cast's opcode
2240 // FIXME: this state can be merged with (2), but the following assert
2241 // is useful to check the correcteness of the sequence due to semantic
2242 // change of bitcast.
2244 SrcTy->isPtrOrPtrVectorTy() &&
2245 MidTy->isPtrOrPtrVectorTy() &&
2246 DstTy->isIntOrIntVectorTy() &&
2247 SrcTy->getPointerAddressSpace() == MidTy->getPointerAddressSpace() &&
2248 "Illegal bitcast, ptrtoint sequence!");
2249 // Allowed, use second cast's opcode
2252 // (sitofp (zext x)) -> (uitofp x)
2253 return Instruction::UIToFP;
2255 // Cast combination can't happen (error in input). This is for all cases
2256 // where the MidTy is not the same for the two cast instructions.
2257 llvm_unreachable("Invalid Cast Combination");
2259 llvm_unreachable("Error in CastResults table!!!");
2263 CastInst *CastInst::Create(Instruction::CastOps op, Value *S, Type *Ty,
2264 const Twine &Name, Instruction *InsertBefore) {
2265 assert(castIsValid(op, S, Ty) && "Invalid cast!");
2266 // Construct and return the appropriate CastInst subclass
2268 case Trunc: return new TruncInst (S, Ty, Name, InsertBefore);
2269 case ZExt: return new ZExtInst (S, Ty, Name, InsertBefore);
2270 case SExt: return new SExtInst (S, Ty, Name, InsertBefore);
2271 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertBefore);
2272 case FPExt: return new FPExtInst (S, Ty, Name, InsertBefore);
2273 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertBefore);
2274 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertBefore);
2275 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertBefore);
2276 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertBefore);
2277 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertBefore);
2278 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertBefore);
2279 case BitCast: return new BitCastInst (S, Ty, Name, InsertBefore);
2280 case AddrSpaceCast: return new AddrSpaceCastInst (S, Ty, Name, InsertBefore);
2281 default: llvm_unreachable("Invalid opcode provided");
2285 CastInst *CastInst::Create(Instruction::CastOps op, Value *S, Type *Ty,
2286 const Twine &Name, BasicBlock *InsertAtEnd) {
2287 assert(castIsValid(op, S, Ty) && "Invalid cast!");
2288 // Construct and return the appropriate CastInst subclass
2290 case Trunc: return new TruncInst (S, Ty, Name, InsertAtEnd);
2291 case ZExt: return new ZExtInst (S, Ty, Name, InsertAtEnd);
2292 case SExt: return new SExtInst (S, Ty, Name, InsertAtEnd);
2293 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertAtEnd);
2294 case FPExt: return new FPExtInst (S, Ty, Name, InsertAtEnd);
2295 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertAtEnd);
2296 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertAtEnd);
2297 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertAtEnd);
2298 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertAtEnd);
2299 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertAtEnd);
2300 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertAtEnd);
2301 case BitCast: return new BitCastInst (S, Ty, Name, InsertAtEnd);
2302 case AddrSpaceCast: return new AddrSpaceCastInst (S, Ty, Name, InsertAtEnd);
2303 default: llvm_unreachable("Invalid opcode provided");
2307 CastInst *CastInst::CreateZExtOrBitCast(Value *S, Type *Ty,
2309 Instruction *InsertBefore) {
2310 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2311 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2312 return Create(Instruction::ZExt, S, Ty, Name, InsertBefore);
2315 CastInst *CastInst::CreateZExtOrBitCast(Value *S, Type *Ty,
2317 BasicBlock *InsertAtEnd) {
2318 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2319 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2320 return Create(Instruction::ZExt, S, Ty, Name, InsertAtEnd);
2323 CastInst *CastInst::CreateSExtOrBitCast(Value *S, Type *Ty,
2325 Instruction *InsertBefore) {
2326 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2327 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2328 return Create(Instruction::SExt, S, Ty, Name, InsertBefore);
2331 CastInst *CastInst::CreateSExtOrBitCast(Value *S, Type *Ty,
2333 BasicBlock *InsertAtEnd) {
2334 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2335 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2336 return Create(Instruction::SExt, S, Ty, Name, InsertAtEnd);
2339 CastInst *CastInst::CreateTruncOrBitCast(Value *S, Type *Ty,
2341 Instruction *InsertBefore) {
2342 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2343 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2344 return Create(Instruction::Trunc, S, Ty, Name, InsertBefore);
2347 CastInst *CastInst::CreateTruncOrBitCast(Value *S, Type *Ty,
2349 BasicBlock *InsertAtEnd) {
2350 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2351 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2352 return Create(Instruction::Trunc, S, Ty, Name, InsertAtEnd);
2355 CastInst *CastInst::CreatePointerCast(Value *S, Type *Ty,
2357 BasicBlock *InsertAtEnd) {
2358 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
2359 assert((Ty->isIntOrIntVectorTy() || Ty->isPtrOrPtrVectorTy()) &&
2361 assert(Ty->isVectorTy() == S->getType()->isVectorTy() && "Invalid cast");
2362 assert((!Ty->isVectorTy() ||
2363 Ty->getVectorNumElements() == S->getType()->getVectorNumElements()) &&
2366 if (Ty->isIntOrIntVectorTy())
2367 return Create(Instruction::PtrToInt, S, Ty, Name, InsertAtEnd);
2369 return CreatePointerBitCastOrAddrSpaceCast(S, Ty, Name, InsertAtEnd);
2372 /// @brief Create a BitCast or a PtrToInt cast instruction
2373 CastInst *CastInst::CreatePointerCast(Value *S, Type *Ty,
2375 Instruction *InsertBefore) {
2376 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
2377 assert((Ty->isIntOrIntVectorTy() || Ty->isPtrOrPtrVectorTy()) &&
2379 assert(Ty->isVectorTy() == S->getType()->isVectorTy() && "Invalid cast");
2380 assert((!Ty->isVectorTy() ||
2381 Ty->getVectorNumElements() == S->getType()->getVectorNumElements()) &&
2384 if (Ty->isIntOrIntVectorTy())
2385 return Create(Instruction::PtrToInt, S, Ty, Name, InsertBefore);
2387 return CreatePointerBitCastOrAddrSpaceCast(S, Ty, Name, InsertBefore);
2390 CastInst *CastInst::CreatePointerBitCastOrAddrSpaceCast(
2393 BasicBlock *InsertAtEnd) {
2394 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
2395 assert(Ty->isPtrOrPtrVectorTy() && "Invalid cast");
2397 if (S->getType()->getPointerAddressSpace() != Ty->getPointerAddressSpace())
2398 return Create(Instruction::AddrSpaceCast, S, Ty, Name, InsertAtEnd);
2400 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2403 CastInst *CastInst::CreatePointerBitCastOrAddrSpaceCast(
2406 Instruction *InsertBefore) {
2407 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
2408 assert(Ty->isPtrOrPtrVectorTy() && "Invalid cast");
2410 if (S->getType()->getPointerAddressSpace() != Ty->getPointerAddressSpace())
2411 return Create(Instruction::AddrSpaceCast, S, Ty, Name, InsertBefore);
2413 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2416 CastInst *CastInst::CreateBitOrPointerCast(Value *S, Type *Ty,
2418 Instruction *InsertBefore) {
2419 if (S->getType()->isPointerTy() && Ty->isIntegerTy())
2420 return Create(Instruction::PtrToInt, S, Ty, Name, InsertBefore);
2421 if (S->getType()->isIntegerTy() && Ty->isPointerTy())
2422 return Create(Instruction::IntToPtr, S, Ty, Name, InsertBefore);
2424 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2427 CastInst *CastInst::CreateIntegerCast(Value *C, Type *Ty,
2428 bool isSigned, const Twine &Name,
2429 Instruction *InsertBefore) {
2430 assert(C->getType()->isIntOrIntVectorTy() && Ty->isIntOrIntVectorTy() &&
2431 "Invalid integer cast");
2432 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2433 unsigned DstBits = Ty->getScalarSizeInBits();
2434 Instruction::CastOps opcode =
2435 (SrcBits == DstBits ? Instruction::BitCast :
2436 (SrcBits > DstBits ? Instruction::Trunc :
2437 (isSigned ? Instruction::SExt : Instruction::ZExt)));
2438 return Create(opcode, C, Ty, Name, InsertBefore);
2441 CastInst *CastInst::CreateIntegerCast(Value *C, Type *Ty,
2442 bool isSigned, const Twine &Name,
2443 BasicBlock *InsertAtEnd) {
2444 assert(C->getType()->isIntOrIntVectorTy() && Ty->isIntOrIntVectorTy() &&
2446 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2447 unsigned DstBits = Ty->getScalarSizeInBits();
2448 Instruction::CastOps opcode =
2449 (SrcBits == DstBits ? Instruction::BitCast :
2450 (SrcBits > DstBits ? Instruction::Trunc :
2451 (isSigned ? Instruction::SExt : Instruction::ZExt)));
2452 return Create(opcode, C, Ty, Name, InsertAtEnd);
2455 CastInst *CastInst::CreateFPCast(Value *C, Type *Ty,
2457 Instruction *InsertBefore) {
2458 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
2460 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2461 unsigned DstBits = Ty->getScalarSizeInBits();
2462 Instruction::CastOps opcode =
2463 (SrcBits == DstBits ? Instruction::BitCast :
2464 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
2465 return Create(opcode, C, Ty, Name, InsertBefore);
2468 CastInst *CastInst::CreateFPCast(Value *C, Type *Ty,
2470 BasicBlock *InsertAtEnd) {
2471 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
2473 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2474 unsigned DstBits = Ty->getScalarSizeInBits();
2475 Instruction::CastOps opcode =
2476 (SrcBits == DstBits ? Instruction::BitCast :
2477 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
2478 return Create(opcode, C, Ty, Name, InsertAtEnd);
2481 // Check whether it is valid to call getCastOpcode for these types.
2482 // This routine must be kept in sync with getCastOpcode.
2483 bool CastInst::isCastable(Type *SrcTy, Type *DestTy) {
2484 if (!SrcTy->isFirstClassType() || !DestTy->isFirstClassType())
2487 if (SrcTy == DestTy)
2490 if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy))
2491 if (VectorType *DestVecTy = dyn_cast<VectorType>(DestTy))
2492 if (SrcVecTy->getNumElements() == DestVecTy->getNumElements()) {
2493 // An element by element cast. Valid if casting the elements is valid.
2494 SrcTy = SrcVecTy->getElementType();
2495 DestTy = DestVecTy->getElementType();
2498 // Get the bit sizes, we'll need these
2499 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); // 0 for ptr
2500 unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr
2502 // Run through the possibilities ...
2503 if (DestTy->isIntegerTy()) { // Casting to integral
2504 if (SrcTy->isIntegerTy()) // Casting from integral
2506 if (SrcTy->isFloatingPointTy()) // Casting from floating pt
2508 if (SrcTy->isVectorTy()) // Casting from vector
2509 return DestBits == SrcBits;
2510 // Casting from something else
2511 return SrcTy->isPointerTy();
2513 if (DestTy->isFloatingPointTy()) { // Casting to floating pt
2514 if (SrcTy->isIntegerTy()) // Casting from integral
2516 if (SrcTy->isFloatingPointTy()) // Casting from floating pt
2518 if (SrcTy->isVectorTy()) // Casting from vector
2519 return DestBits == SrcBits;
2520 // Casting from something else
2523 if (DestTy->isVectorTy()) // Casting to vector
2524 return DestBits == SrcBits;
2525 if (DestTy->isPointerTy()) { // Casting to pointer
2526 if (SrcTy->isPointerTy()) // Casting from pointer
2528 return SrcTy->isIntegerTy(); // Casting from integral
2530 if (DestTy->isX86_MMXTy()) {
2531 if (SrcTy->isVectorTy())
2532 return DestBits == SrcBits; // 64-bit vector to MMX
2534 } // Casting to something else
2538 bool CastInst::isBitCastable(Type *SrcTy, Type *DestTy) {
2539 if (!SrcTy->isFirstClassType() || !DestTy->isFirstClassType())
2542 if (SrcTy == DestTy)
2545 if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy)) {
2546 if (VectorType *DestVecTy = dyn_cast<VectorType>(DestTy)) {
2547 if (SrcVecTy->getNumElements() == DestVecTy->getNumElements()) {
2548 // An element by element cast. Valid if casting the elements is valid.
2549 SrcTy = SrcVecTy->getElementType();
2550 DestTy = DestVecTy->getElementType();
2555 if (PointerType *DestPtrTy = dyn_cast<PointerType>(DestTy)) {
2556 if (PointerType *SrcPtrTy = dyn_cast<PointerType>(SrcTy)) {
2557 return SrcPtrTy->getAddressSpace() == DestPtrTy->getAddressSpace();
2561 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); // 0 for ptr
2562 unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr
2564 // Could still have vectors of pointers if the number of elements doesn't
2566 if (SrcBits == 0 || DestBits == 0)
2569 if (SrcBits != DestBits)
2572 if (DestTy->isX86_MMXTy() || SrcTy->isX86_MMXTy())
2578 bool CastInst::isBitOrNoopPointerCastable(Type *SrcTy, Type *DestTy,
2579 const DataLayout &DL) {
2580 if (auto *PtrTy = dyn_cast<PointerType>(SrcTy))
2581 if (auto *IntTy = dyn_cast<IntegerType>(DestTy))
2582 return IntTy->getBitWidth() == DL.getPointerTypeSizeInBits(PtrTy);
2583 if (auto *PtrTy = dyn_cast<PointerType>(DestTy))
2584 if (auto *IntTy = dyn_cast<IntegerType>(SrcTy))
2585 return IntTy->getBitWidth() == DL.getPointerTypeSizeInBits(PtrTy);
2587 return isBitCastable(SrcTy, DestTy);
2590 // Provide a way to get a "cast" where the cast opcode is inferred from the
2591 // types and size of the operand. This, basically, is a parallel of the
2592 // logic in the castIsValid function below. This axiom should hold:
2593 // castIsValid( getCastOpcode(Val, Ty), Val, Ty)
2594 // should not assert in castIsValid. In other words, this produces a "correct"
2595 // casting opcode for the arguments passed to it.
2596 // This routine must be kept in sync with isCastable.
2597 Instruction::CastOps
2598 CastInst::getCastOpcode(
2599 const Value *Src, bool SrcIsSigned, Type *DestTy, bool DestIsSigned) {
2600 Type *SrcTy = Src->getType();
2602 assert(SrcTy->isFirstClassType() && DestTy->isFirstClassType() &&
2603 "Only first class types are castable!");
2605 if (SrcTy == DestTy)
2608 // FIXME: Check address space sizes here
2609 if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy))
2610 if (VectorType *DestVecTy = dyn_cast<VectorType>(DestTy))
2611 if (SrcVecTy->getNumElements() == DestVecTy->getNumElements()) {
2612 // An element by element cast. Find the appropriate opcode based on the
2614 SrcTy = SrcVecTy->getElementType();
2615 DestTy = DestVecTy->getElementType();
2618 // Get the bit sizes, we'll need these
2619 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); // 0 for ptr
2620 unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr
2622 // Run through the possibilities ...
2623 if (DestTy->isIntegerTy()) { // Casting to integral
2624 if (SrcTy->isIntegerTy()) { // Casting from integral
2625 if (DestBits < SrcBits)
2626 return Trunc; // int -> smaller int
2627 else if (DestBits > SrcBits) { // its an extension
2629 return SExt; // signed -> SEXT
2631 return ZExt; // unsigned -> ZEXT
2633 return BitCast; // Same size, No-op cast
2635 } else if (SrcTy->isFloatingPointTy()) { // Casting from floating pt
2637 return FPToSI; // FP -> sint
2639 return FPToUI; // FP -> uint
2640 } else if (SrcTy->isVectorTy()) {
2641 assert(DestBits == SrcBits &&
2642 "Casting vector to integer of different width");
2643 return BitCast; // Same size, no-op cast
2645 assert(SrcTy->isPointerTy() &&
2646 "Casting from a value that is not first-class type");
2647 return PtrToInt; // ptr -> int
2649 } else if (DestTy->isFloatingPointTy()) { // Casting to floating pt
2650 if (SrcTy->isIntegerTy()) { // Casting from integral
2652 return SIToFP; // sint -> FP
2654 return UIToFP; // uint -> FP
2655 } else if (SrcTy->isFloatingPointTy()) { // Casting from floating pt
2656 if (DestBits < SrcBits) {
2657 return FPTrunc; // FP -> smaller FP
2658 } else if (DestBits > SrcBits) {
2659 return FPExt; // FP -> larger FP
2661 return BitCast; // same size, no-op cast
2663 } else if (SrcTy->isVectorTy()) {
2664 assert(DestBits == SrcBits &&
2665 "Casting vector to floating point of different width");
2666 return BitCast; // same size, no-op cast
2668 llvm_unreachable("Casting pointer or non-first class to float");
2669 } else if (DestTy->isVectorTy()) {
2670 assert(DestBits == SrcBits &&
2671 "Illegal cast to vector (wrong type or size)");
2673 } else if (DestTy->isPointerTy()) {
2674 if (SrcTy->isPointerTy()) {
2675 if (DestTy->getPointerAddressSpace() != SrcTy->getPointerAddressSpace())
2676 return AddrSpaceCast;
2677 return BitCast; // ptr -> ptr
2678 } else if (SrcTy->isIntegerTy()) {
2679 return IntToPtr; // int -> ptr
2681 llvm_unreachable("Casting pointer to other than pointer or int");
2682 } else if (DestTy->isX86_MMXTy()) {
2683 if (SrcTy->isVectorTy()) {
2684 assert(DestBits == SrcBits && "Casting vector of wrong width to X86_MMX");
2685 return BitCast; // 64-bit vector to MMX
2687 llvm_unreachable("Illegal cast to X86_MMX");
2689 llvm_unreachable("Casting to type that is not first-class");
2692 //===----------------------------------------------------------------------===//
2693 // CastInst SubClass Constructors
2694 //===----------------------------------------------------------------------===//
2696 /// Check that the construction parameters for a CastInst are correct. This
2697 /// could be broken out into the separate constructors but it is useful to have
2698 /// it in one place and to eliminate the redundant code for getting the sizes
2699 /// of the types involved.
2701 CastInst::castIsValid(Instruction::CastOps op, Value *S, Type *DstTy) {
2703 // Check for type sanity on the arguments
2704 Type *SrcTy = S->getType();
2706 if (!SrcTy->isFirstClassType() || !DstTy->isFirstClassType() ||
2707 SrcTy->isAggregateType() || DstTy->isAggregateType())
2710 // Get the size of the types in bits, we'll need this later
2711 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
2712 unsigned DstBitSize = DstTy->getScalarSizeInBits();
2714 // If these are vector types, get the lengths of the vectors (using zero for
2715 // scalar types means that checking that vector lengths match also checks that
2716 // scalars are not being converted to vectors or vectors to scalars).
2717 unsigned SrcLength = SrcTy->isVectorTy() ?
2718 cast<VectorType>(SrcTy)->getNumElements() : 0;
2719 unsigned DstLength = DstTy->isVectorTy() ?
2720 cast<VectorType>(DstTy)->getNumElements() : 0;
2722 // Switch on the opcode provided
2724 default: return false; // This is an input error
2725 case Instruction::Trunc:
2726 return SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy() &&
2727 SrcLength == DstLength && SrcBitSize > DstBitSize;
2728 case Instruction::ZExt:
2729 return SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy() &&
2730 SrcLength == DstLength && SrcBitSize < DstBitSize;
2731 case Instruction::SExt:
2732 return SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy() &&
2733 SrcLength == DstLength && SrcBitSize < DstBitSize;
2734 case Instruction::FPTrunc:
2735 return SrcTy->isFPOrFPVectorTy() && DstTy->isFPOrFPVectorTy() &&
2736 SrcLength == DstLength && SrcBitSize > DstBitSize;
2737 case Instruction::FPExt:
2738 return SrcTy->isFPOrFPVectorTy() && DstTy->isFPOrFPVectorTy() &&
2739 SrcLength == DstLength && SrcBitSize < DstBitSize;
2740 case Instruction::UIToFP:
2741 case Instruction::SIToFP:
2742 return SrcTy->isIntOrIntVectorTy() && DstTy->isFPOrFPVectorTy() &&
2743 SrcLength == DstLength;
2744 case Instruction::FPToUI:
2745 case Instruction::FPToSI:
2746 return SrcTy->isFPOrFPVectorTy() && DstTy->isIntOrIntVectorTy() &&
2747 SrcLength == DstLength;
2748 case Instruction::PtrToInt:
2749 if (isa<VectorType>(SrcTy) != isa<VectorType>(DstTy))
2751 if (VectorType *VT = dyn_cast<VectorType>(SrcTy))
2752 if (VT->getNumElements() != cast<VectorType>(DstTy)->getNumElements())
2754 return SrcTy->getScalarType()->isPointerTy() &&
2755 DstTy->getScalarType()->isIntegerTy();
2756 case Instruction::IntToPtr:
2757 if (isa<VectorType>(SrcTy) != isa<VectorType>(DstTy))
2759 if (VectorType *VT = dyn_cast<VectorType>(SrcTy))
2760 if (VT->getNumElements() != cast<VectorType>(DstTy)->getNumElements())
2762 return SrcTy->getScalarType()->isIntegerTy() &&
2763 DstTy->getScalarType()->isPointerTy();
2764 case Instruction::BitCast: {
2765 PointerType *SrcPtrTy = dyn_cast<PointerType>(SrcTy->getScalarType());
2766 PointerType *DstPtrTy = dyn_cast<PointerType>(DstTy->getScalarType());
2768 // BitCast implies a no-op cast of type only. No bits change.
2769 // However, you can't cast pointers to anything but pointers.
2770 if (!SrcPtrTy != !DstPtrTy)
2773 // For non-pointer cases, the cast is okay if the source and destination bit
2774 // widths are identical.
2776 return SrcTy->getPrimitiveSizeInBits() == DstTy->getPrimitiveSizeInBits();
2778 // If both are pointers then the address spaces must match.
2779 if (SrcPtrTy->getAddressSpace() != DstPtrTy->getAddressSpace())
2782 // A vector of pointers must have the same number of elements.
2783 if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy)) {
2784 if (VectorType *DstVecTy = dyn_cast<VectorType>(DstTy))
2785 return (SrcVecTy->getNumElements() == DstVecTy->getNumElements());
2792 case Instruction::AddrSpaceCast: {
2793 PointerType *SrcPtrTy = dyn_cast<PointerType>(SrcTy->getScalarType());
2797 PointerType *DstPtrTy = dyn_cast<PointerType>(DstTy->getScalarType());
2801 if (SrcPtrTy->getAddressSpace() == DstPtrTy->getAddressSpace())
2804 if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy)) {
2805 if (VectorType *DstVecTy = dyn_cast<VectorType>(DstTy))
2806 return (SrcVecTy->getNumElements() == DstVecTy->getNumElements());
2816 TruncInst::TruncInst(
2817 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2818 ) : CastInst(Ty, Trunc, S, Name, InsertBefore) {
2819 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
2822 TruncInst::TruncInst(
2823 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2824 ) : CastInst(Ty, Trunc, S, Name, InsertAtEnd) {
2825 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
2829 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2830 ) : CastInst(Ty, ZExt, S, Name, InsertBefore) {
2831 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
2835 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2836 ) : CastInst(Ty, ZExt, S, Name, InsertAtEnd) {
2837 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
2840 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2841 ) : CastInst(Ty, SExt, S, Name, InsertBefore) {
2842 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
2846 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2847 ) : CastInst(Ty, SExt, S, Name, InsertAtEnd) {
2848 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
2851 FPTruncInst::FPTruncInst(
2852 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2853 ) : CastInst(Ty, FPTrunc, S, Name, InsertBefore) {
2854 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
2857 FPTruncInst::FPTruncInst(
2858 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2859 ) : CastInst(Ty, FPTrunc, S, Name, InsertAtEnd) {
2860 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
2863 FPExtInst::FPExtInst(
2864 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2865 ) : CastInst(Ty, FPExt, S, Name, InsertBefore) {
2866 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
2869 FPExtInst::FPExtInst(
2870 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2871 ) : CastInst(Ty, FPExt, S, Name, InsertAtEnd) {
2872 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
2875 UIToFPInst::UIToFPInst(
2876 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2877 ) : CastInst(Ty, UIToFP, S, Name, InsertBefore) {
2878 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
2881 UIToFPInst::UIToFPInst(
2882 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2883 ) : CastInst(Ty, UIToFP, S, Name, InsertAtEnd) {
2884 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
2887 SIToFPInst::SIToFPInst(
2888 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2889 ) : CastInst(Ty, SIToFP, S, Name, InsertBefore) {
2890 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
2893 SIToFPInst::SIToFPInst(
2894 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2895 ) : CastInst(Ty, SIToFP, S, Name, InsertAtEnd) {
2896 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
2899 FPToUIInst::FPToUIInst(
2900 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2901 ) : CastInst(Ty, FPToUI, S, Name, InsertBefore) {
2902 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
2905 FPToUIInst::FPToUIInst(
2906 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2907 ) : CastInst(Ty, FPToUI, S, Name, InsertAtEnd) {
2908 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
2911 FPToSIInst::FPToSIInst(
2912 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2913 ) : CastInst(Ty, FPToSI, S, Name, InsertBefore) {
2914 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
2917 FPToSIInst::FPToSIInst(
2918 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2919 ) : CastInst(Ty, FPToSI, S, Name, InsertAtEnd) {
2920 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
2923 PtrToIntInst::PtrToIntInst(
2924 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2925 ) : CastInst(Ty, PtrToInt, S, Name, InsertBefore) {
2926 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
2929 PtrToIntInst::PtrToIntInst(
2930 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2931 ) : CastInst(Ty, PtrToInt, S, Name, InsertAtEnd) {
2932 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
2935 IntToPtrInst::IntToPtrInst(
2936 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2937 ) : CastInst(Ty, IntToPtr, S, Name, InsertBefore) {
2938 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
2941 IntToPtrInst::IntToPtrInst(
2942 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2943 ) : CastInst(Ty, IntToPtr, S, Name, InsertAtEnd) {
2944 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
2947 BitCastInst::BitCastInst(
2948 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2949 ) : CastInst(Ty, BitCast, S, Name, InsertBefore) {
2950 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
2953 BitCastInst::BitCastInst(
2954 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2955 ) : CastInst(Ty, BitCast, S, Name, InsertAtEnd) {
2956 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
2959 AddrSpaceCastInst::AddrSpaceCastInst(
2960 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2961 ) : CastInst(Ty, AddrSpaceCast, S, Name, InsertBefore) {
2962 assert(castIsValid(getOpcode(), S, Ty) && "Illegal AddrSpaceCast");
2965 AddrSpaceCastInst::AddrSpaceCastInst(
2966 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2967 ) : CastInst(Ty, AddrSpaceCast, S, Name, InsertAtEnd) {
2968 assert(castIsValid(getOpcode(), S, Ty) && "Illegal AddrSpaceCast");
2971 //===----------------------------------------------------------------------===//
2973 //===----------------------------------------------------------------------===//
2975 void CmpInst::anchor() {}
2977 CmpInst::CmpInst(Type *ty, OtherOps op, unsigned short predicate,
2978 Value *LHS, Value *RHS, const Twine &Name,
2979 Instruction *InsertBefore)
2980 : Instruction(ty, op,
2981 OperandTraits<CmpInst>::op_begin(this),
2982 OperandTraits<CmpInst>::operands(this),
2986 setPredicate((Predicate)predicate);
2990 CmpInst::CmpInst(Type *ty, OtherOps op, unsigned short predicate,
2991 Value *LHS, Value *RHS, const Twine &Name,
2992 BasicBlock *InsertAtEnd)
2993 : Instruction(ty, op,
2994 OperandTraits<CmpInst>::op_begin(this),
2995 OperandTraits<CmpInst>::operands(this),
2999 setPredicate((Predicate)predicate);
3004 CmpInst::Create(OtherOps Op, unsigned short predicate,
3005 Value *S1, Value *S2,
3006 const Twine &Name, Instruction *InsertBefore) {
3007 if (Op == Instruction::ICmp) {
3009 return new ICmpInst(InsertBefore, CmpInst::Predicate(predicate),
3012 return new ICmpInst(CmpInst::Predicate(predicate),
3017 return new FCmpInst(InsertBefore, CmpInst::Predicate(predicate),
3020 return new FCmpInst(CmpInst::Predicate(predicate),
3025 CmpInst::Create(OtherOps Op, unsigned short predicate, Value *S1, Value *S2,
3026 const Twine &Name, BasicBlock *InsertAtEnd) {
3027 if (Op == Instruction::ICmp) {
3028 return new ICmpInst(*InsertAtEnd, CmpInst::Predicate(predicate),
3031 return new FCmpInst(*InsertAtEnd, CmpInst::Predicate(predicate),
3035 void CmpInst::swapOperands() {
3036 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
3039 cast<FCmpInst>(this)->swapOperands();
3042 bool CmpInst::isCommutative() const {
3043 if (const ICmpInst *IC = dyn_cast<ICmpInst>(this))
3044 return IC->isCommutative();
3045 return cast<FCmpInst>(this)->isCommutative();
3048 bool CmpInst::isEquality() const {
3049 if (const ICmpInst *IC = dyn_cast<ICmpInst>(this))
3050 return IC->isEquality();
3051 return cast<FCmpInst>(this)->isEquality();
3055 CmpInst::Predicate CmpInst::getInversePredicate(Predicate pred) {
3057 default: llvm_unreachable("Unknown cmp predicate!");
3058 case ICMP_EQ: return ICMP_NE;
3059 case ICMP_NE: return ICMP_EQ;
3060 case ICMP_UGT: return ICMP_ULE;
3061 case ICMP_ULT: return ICMP_UGE;
3062 case ICMP_UGE: return ICMP_ULT;
3063 case ICMP_ULE: return ICMP_UGT;
3064 case ICMP_SGT: return ICMP_SLE;
3065 case ICMP_SLT: return ICMP_SGE;
3066 case ICMP_SGE: return ICMP_SLT;
3067 case ICMP_SLE: return ICMP_SGT;
3069 case FCMP_OEQ: return FCMP_UNE;
3070 case FCMP_ONE: return FCMP_UEQ;
3071 case FCMP_OGT: return FCMP_ULE;
3072 case FCMP_OLT: return FCMP_UGE;
3073 case FCMP_OGE: return FCMP_ULT;
3074 case FCMP_OLE: return FCMP_UGT;
3075 case FCMP_UEQ: return FCMP_ONE;
3076 case FCMP_UNE: return FCMP_OEQ;
3077 case FCMP_UGT: return FCMP_OLE;
3078 case FCMP_ULT: return FCMP_OGE;
3079 case FCMP_UGE: return FCMP_OLT;
3080 case FCMP_ULE: return FCMP_OGT;
3081 case FCMP_ORD: return FCMP_UNO;
3082 case FCMP_UNO: return FCMP_ORD;
3083 case FCMP_TRUE: return FCMP_FALSE;
3084 case FCMP_FALSE: return FCMP_TRUE;
3088 ICmpInst::Predicate ICmpInst::getSignedPredicate(Predicate pred) {
3090 default: llvm_unreachable("Unknown icmp predicate!");
3091 case ICMP_EQ: case ICMP_NE:
3092 case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE:
3094 case ICMP_UGT: return ICMP_SGT;
3095 case ICMP_ULT: return ICMP_SLT;
3096 case ICMP_UGE: return ICMP_SGE;
3097 case ICMP_ULE: return ICMP_SLE;
3101 ICmpInst::Predicate ICmpInst::getUnsignedPredicate(Predicate pred) {
3103 default: llvm_unreachable("Unknown icmp predicate!");
3104 case ICMP_EQ: case ICMP_NE:
3105 case ICMP_UGT: case ICMP_ULT: case ICMP_UGE: case ICMP_ULE:
3107 case ICMP_SGT: return ICMP_UGT;
3108 case ICMP_SLT: return ICMP_ULT;
3109 case ICMP_SGE: return ICMP_UGE;
3110 case ICMP_SLE: return ICMP_ULE;
3114 /// Initialize a set of values that all satisfy the condition with C.
3117 ICmpInst::makeConstantRange(Predicate pred, const APInt &C) {
3120 uint32_t BitWidth = C.getBitWidth();
3122 default: llvm_unreachable("Invalid ICmp opcode to ConstantRange ctor!");
3123 case ICmpInst::ICMP_EQ: ++Upper; break;
3124 case ICmpInst::ICMP_NE: ++Lower; break;
3125 case ICmpInst::ICMP_ULT:
3126 Lower = APInt::getMinValue(BitWidth);
3127 // Check for an empty-set condition.
3129 return ConstantRange(BitWidth, /*isFullSet=*/false);
3131 case ICmpInst::ICMP_SLT:
3132 Lower = APInt::getSignedMinValue(BitWidth);
3133 // Check for an empty-set condition.
3135 return ConstantRange(BitWidth, /*isFullSet=*/false);
3137 case ICmpInst::ICMP_UGT:
3138 ++Lower; Upper = APInt::getMinValue(BitWidth); // Min = Next(Max)
3139 // Check for an empty-set condition.
3141 return ConstantRange(BitWidth, /*isFullSet=*/false);
3143 case ICmpInst::ICMP_SGT:
3144 ++Lower; Upper = APInt::getSignedMinValue(BitWidth); // Min = Next(Max)
3145 // Check for an empty-set condition.
3147 return ConstantRange(BitWidth, /*isFullSet=*/false);
3149 case ICmpInst::ICMP_ULE:
3150 Lower = APInt::getMinValue(BitWidth); ++Upper;
3151 // Check for a full-set condition.
3153 return ConstantRange(BitWidth, /*isFullSet=*/true);
3155 case ICmpInst::ICMP_SLE:
3156 Lower = APInt::getSignedMinValue(BitWidth); ++Upper;
3157 // Check for a full-set condition.
3159 return ConstantRange(BitWidth, /*isFullSet=*/true);
3161 case ICmpInst::ICMP_UGE:
3162 Upper = APInt::getMinValue(BitWidth); // Min = Next(Max)
3163 // Check for a full-set condition.
3165 return ConstantRange(BitWidth, /*isFullSet=*/true);
3167 case ICmpInst::ICMP_SGE:
3168 Upper = APInt::getSignedMinValue(BitWidth); // Min = Next(Max)
3169 // Check for a full-set condition.
3171 return ConstantRange(BitWidth, /*isFullSet=*/true);
3174 return ConstantRange(Lower, Upper);
3177 CmpInst::Predicate CmpInst::getSwappedPredicate(Predicate pred) {
3179 default: llvm_unreachable("Unknown cmp predicate!");
3180 case ICMP_EQ: case ICMP_NE:
3182 case ICMP_SGT: return ICMP_SLT;
3183 case ICMP_SLT: return ICMP_SGT;
3184 case ICMP_SGE: return ICMP_SLE;
3185 case ICMP_SLE: return ICMP_SGE;
3186 case ICMP_UGT: return ICMP_ULT;
3187 case ICMP_ULT: return ICMP_UGT;
3188 case ICMP_UGE: return ICMP_ULE;
3189 case ICMP_ULE: return ICMP_UGE;
3191 case FCMP_FALSE: case FCMP_TRUE:
3192 case FCMP_OEQ: case FCMP_ONE:
3193 case FCMP_UEQ: case FCMP_UNE:
3194 case FCMP_ORD: case FCMP_UNO:
3196 case FCMP_OGT: return FCMP_OLT;
3197 case FCMP_OLT: return FCMP_OGT;
3198 case FCMP_OGE: return FCMP_OLE;
3199 case FCMP_OLE: return FCMP_OGE;
3200 case FCMP_UGT: return FCMP_ULT;
3201 case FCMP_ULT: return FCMP_UGT;
3202 case FCMP_UGE: return FCMP_ULE;
3203 case FCMP_ULE: return FCMP_UGE;
3207 bool CmpInst::isUnsigned(unsigned short predicate) {
3208 switch (predicate) {
3209 default: return false;
3210 case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_ULE: case ICmpInst::ICMP_UGT:
3211 case ICmpInst::ICMP_UGE: return true;
3215 bool CmpInst::isSigned(unsigned short predicate) {
3216 switch (predicate) {
3217 default: return false;
3218 case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_SLE: case ICmpInst::ICMP_SGT:
3219 case ICmpInst::ICMP_SGE: return true;
3223 bool CmpInst::isOrdered(unsigned short predicate) {
3224 switch (predicate) {
3225 default: return false;
3226 case FCmpInst::FCMP_OEQ: case FCmpInst::FCMP_ONE: case FCmpInst::FCMP_OGT:
3227 case FCmpInst::FCMP_OLT: case FCmpInst::FCMP_OGE: case FCmpInst::FCMP_OLE:
3228 case FCmpInst::FCMP_ORD: return true;
3232 bool CmpInst::isUnordered(unsigned short predicate) {
3233 switch (predicate) {
3234 default: return false;
3235 case FCmpInst::FCMP_UEQ: case FCmpInst::FCMP_UNE: case FCmpInst::FCMP_UGT:
3236 case FCmpInst::FCMP_ULT: case FCmpInst::FCMP_UGE: case FCmpInst::FCMP_ULE:
3237 case FCmpInst::FCMP_UNO: return true;
3241 bool CmpInst::isTrueWhenEqual(unsigned short predicate) {
3243 default: return false;
3244 case ICMP_EQ: case ICMP_UGE: case ICMP_ULE: case ICMP_SGE: case ICMP_SLE:
3245 case FCMP_TRUE: case FCMP_UEQ: case FCMP_UGE: case FCMP_ULE: return true;
3249 bool CmpInst::isFalseWhenEqual(unsigned short predicate) {
3251 case ICMP_NE: case ICMP_UGT: case ICMP_ULT: case ICMP_SGT: case ICMP_SLT:
3252 case FCMP_FALSE: case FCMP_ONE: case FCMP_OGT: case FCMP_OLT: return true;
3253 default: return false;
3258 //===----------------------------------------------------------------------===//
3259 // SwitchInst Implementation
3260 //===----------------------------------------------------------------------===//
3262 void SwitchInst::init(Value *Value, BasicBlock *Default, unsigned NumReserved) {
3263 assert(Value && Default && NumReserved);
3264 ReservedSpace = NumReserved;
3266 allocHungoffUses(ReservedSpace);
3272 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
3273 /// switch on and a default destination. The number of additional cases can
3274 /// be specified here to make memory allocation more efficient. This
3275 /// constructor can also autoinsert before another instruction.
3276 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
3277 Instruction *InsertBefore)
3278 : TerminatorInst(Type::getVoidTy(Value->getContext()), Instruction::Switch,
3279 nullptr, 0, InsertBefore) {
3280 init(Value, Default, 2+NumCases*2);
3283 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
3284 /// switch on and a default destination. The number of additional cases can
3285 /// be specified here to make memory allocation more efficient. This
3286 /// constructor also autoinserts at the end of the specified BasicBlock.
3287 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
3288 BasicBlock *InsertAtEnd)
3289 : TerminatorInst(Type::getVoidTy(Value->getContext()), Instruction::Switch,
3290 nullptr, 0, InsertAtEnd) {
3291 init(Value, Default, 2+NumCases*2);
3294 SwitchInst::SwitchInst(const SwitchInst &SI)
3295 : TerminatorInst(SI.getType(), Instruction::Switch, nullptr, 0) {
3296 init(SI.getCondition(), SI.getDefaultDest(), SI.getNumOperands());
3297 NumOperands = SI.getNumOperands();
3298 Use *OL = OperandList, *InOL = SI.OperandList;
3299 for (unsigned i = 2, E = SI.getNumOperands(); i != E; i += 2) {
3301 OL[i+1] = InOL[i+1];
3303 SubclassOptionalData = SI.SubclassOptionalData;
3307 /// addCase - Add an entry to the switch instruction...
3309 void SwitchInst::addCase(ConstantInt *OnVal, BasicBlock *Dest) {
3310 unsigned NewCaseIdx = getNumCases();
3311 unsigned OpNo = NumOperands;
3312 if (OpNo+2 > ReservedSpace)
3313 growOperands(); // Get more space!
3314 // Initialize some new operands.
3315 assert(OpNo+1 < ReservedSpace && "Growing didn't work!");
3316 NumOperands = OpNo+2;
3317 CaseIt Case(this, NewCaseIdx);
3318 Case.setValue(OnVal);
3319 Case.setSuccessor(Dest);
3322 /// removeCase - This method removes the specified case and its successor
3323 /// from the switch instruction.
3324 void SwitchInst::removeCase(CaseIt i) {
3325 unsigned idx = i.getCaseIndex();
3327 assert(2 + idx*2 < getNumOperands() && "Case index out of range!!!");
3329 unsigned NumOps = getNumOperands();
3330 Use *OL = OperandList;
3332 // Overwrite this case with the end of the list.
3333 if (2 + (idx + 1) * 2 != NumOps) {
3334 OL[2 + idx * 2] = OL[NumOps - 2];
3335 OL[2 + idx * 2 + 1] = OL[NumOps - 1];
3338 // Nuke the last value.
3339 OL[NumOps-2].set(nullptr);
3340 OL[NumOps-2+1].set(nullptr);
3341 NumOperands = NumOps-2;
3344 /// growOperands - grow operands - This grows the operand list in response
3345 /// to a push_back style of operation. This grows the number of ops by 3 times.
3347 void SwitchInst::growOperands() {
3348 unsigned e = getNumOperands();
3349 unsigned NumOps = e*3;
3351 ReservedSpace = NumOps;
3352 growHungoffUses(ReservedSpace);
3356 BasicBlock *SwitchInst::getSuccessorV(unsigned idx) const {
3357 return getSuccessor(idx);
3359 unsigned SwitchInst::getNumSuccessorsV() const {
3360 return getNumSuccessors();
3362 void SwitchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
3363 setSuccessor(idx, B);
3366 //===----------------------------------------------------------------------===//
3367 // IndirectBrInst Implementation
3368 //===----------------------------------------------------------------------===//
3370 void IndirectBrInst::init(Value *Address, unsigned NumDests) {
3371 assert(Address && Address->getType()->isPointerTy() &&
3372 "Address of indirectbr must be a pointer");
3373 ReservedSpace = 1+NumDests;
3375 allocHungoffUses(ReservedSpace);
3381 /// growOperands - grow operands - This grows the operand list in response
3382 /// to a push_back style of operation. This grows the number of ops by 2 times.
3384 void IndirectBrInst::growOperands() {
3385 unsigned e = getNumOperands();
3386 unsigned NumOps = e*2;
3388 ReservedSpace = NumOps;
3389 growHungoffUses(ReservedSpace);
3392 IndirectBrInst::IndirectBrInst(Value *Address, unsigned NumCases,
3393 Instruction *InsertBefore)
3394 : TerminatorInst(Type::getVoidTy(Address->getContext()),Instruction::IndirectBr,
3395 nullptr, 0, InsertBefore) {
3396 init(Address, NumCases);
3399 IndirectBrInst::IndirectBrInst(Value *Address, unsigned NumCases,
3400 BasicBlock *InsertAtEnd)
3401 : TerminatorInst(Type::getVoidTy(Address->getContext()),Instruction::IndirectBr,
3402 nullptr, 0, InsertAtEnd) {
3403 init(Address, NumCases);
3406 IndirectBrInst::IndirectBrInst(const IndirectBrInst &IBI)
3407 : TerminatorInst(Type::getVoidTy(IBI.getContext()), Instruction::IndirectBr,
3408 nullptr, IBI.getNumOperands()) {
3409 allocHungoffUses(IBI.getNumOperands());
3410 Use *OL = OperandList, *InOL = IBI.OperandList;
3411 for (unsigned i = 0, E = IBI.getNumOperands(); i != E; ++i)
3413 SubclassOptionalData = IBI.SubclassOptionalData;
3416 /// addDestination - Add a destination.
3418 void IndirectBrInst::addDestination(BasicBlock *DestBB) {
3419 unsigned OpNo = NumOperands;
3420 if (OpNo+1 > ReservedSpace)
3421 growOperands(); // Get more space!
3422 // Initialize some new operands.
3423 assert(OpNo < ReservedSpace && "Growing didn't work!");
3424 NumOperands = OpNo+1;
3425 OperandList[OpNo] = DestBB;
3428 /// removeDestination - This method removes the specified successor from the
3429 /// indirectbr instruction.
3430 void IndirectBrInst::removeDestination(unsigned idx) {
3431 assert(idx < getNumOperands()-1 && "Successor index out of range!");
3433 unsigned NumOps = getNumOperands();
3434 Use *OL = OperandList;
3436 // Replace this value with the last one.
3437 OL[idx+1] = OL[NumOps-1];
3439 // Nuke the last value.
3440 OL[NumOps-1].set(nullptr);
3441 NumOperands = NumOps-1;
3444 BasicBlock *IndirectBrInst::getSuccessorV(unsigned idx) const {
3445 return getSuccessor(idx);
3447 unsigned IndirectBrInst::getNumSuccessorsV() const {
3448 return getNumSuccessors();
3450 void IndirectBrInst::setSuccessorV(unsigned idx, BasicBlock *B) {
3451 setSuccessor(idx, B);
3454 //===----------------------------------------------------------------------===//
3455 // clone_impl() implementations
3456 //===----------------------------------------------------------------------===//
3458 // Define these methods here so vtables don't get emitted into every translation
3459 // unit that uses these classes.
3461 GetElementPtrInst *GetElementPtrInst::clone_impl() const {
3462 return new (getNumOperands()) GetElementPtrInst(*this);
3465 BinaryOperator *BinaryOperator::clone_impl() const {
3466 return Create(getOpcode(), Op<0>(), Op<1>());
3469 FCmpInst* FCmpInst::clone_impl() const {
3470 return new FCmpInst(getPredicate(), Op<0>(), Op<1>());
3473 ICmpInst* ICmpInst::clone_impl() const {
3474 return new ICmpInst(getPredicate(), Op<0>(), Op<1>());
3477 ExtractValueInst *ExtractValueInst::clone_impl() const {
3478 return new ExtractValueInst(*this);
3481 InsertValueInst *InsertValueInst::clone_impl() const {
3482 return new InsertValueInst(*this);
3485 AllocaInst *AllocaInst::clone_impl() const {
3486 AllocaInst *Result = new AllocaInst(getAllocatedType(),
3487 (Value *)getOperand(0), getAlignment());
3488 Result->setUsedWithInAlloca(isUsedWithInAlloca());
3492 LoadInst *LoadInst::clone_impl() const {
3493 return new LoadInst(getOperand(0), Twine(), isVolatile(),
3494 getAlignment(), getOrdering(), getSynchScope());
3497 StoreInst *StoreInst::clone_impl() const {
3498 return new StoreInst(getOperand(0), getOperand(1), isVolatile(),
3499 getAlignment(), getOrdering(), getSynchScope());
3503 AtomicCmpXchgInst *AtomicCmpXchgInst::clone_impl() const {
3504 AtomicCmpXchgInst *Result =
3505 new AtomicCmpXchgInst(getOperand(0), getOperand(1), getOperand(2),
3506 getSuccessOrdering(), getFailureOrdering(),
3508 Result->setVolatile(isVolatile());
3509 Result->setWeak(isWeak());
3513 AtomicRMWInst *AtomicRMWInst::clone_impl() const {
3514 AtomicRMWInst *Result =
3515 new AtomicRMWInst(getOperation(),getOperand(0), getOperand(1),
3516 getOrdering(), getSynchScope());
3517 Result->setVolatile(isVolatile());
3521 FenceInst *FenceInst::clone_impl() const {
3522 return new FenceInst(getContext(), getOrdering(), getSynchScope());
3525 TruncInst *TruncInst::clone_impl() const {
3526 return new TruncInst(getOperand(0), getType());
3529 ZExtInst *ZExtInst::clone_impl() const {
3530 return new ZExtInst(getOperand(0), getType());
3533 SExtInst *SExtInst::clone_impl() const {
3534 return new SExtInst(getOperand(0), getType());
3537 FPTruncInst *FPTruncInst::clone_impl() const {
3538 return new FPTruncInst(getOperand(0), getType());
3541 FPExtInst *FPExtInst::clone_impl() const {
3542 return new FPExtInst(getOperand(0), getType());
3545 UIToFPInst *UIToFPInst::clone_impl() const {
3546 return new UIToFPInst(getOperand(0), getType());
3549 SIToFPInst *SIToFPInst::clone_impl() const {
3550 return new SIToFPInst(getOperand(0), getType());
3553 FPToUIInst *FPToUIInst::clone_impl() const {
3554 return new FPToUIInst(getOperand(0), getType());
3557 FPToSIInst *FPToSIInst::clone_impl() const {
3558 return new FPToSIInst(getOperand(0), getType());
3561 PtrToIntInst *PtrToIntInst::clone_impl() const {
3562 return new PtrToIntInst(getOperand(0), getType());
3565 IntToPtrInst *IntToPtrInst::clone_impl() const {
3566 return new IntToPtrInst(getOperand(0), getType());
3569 BitCastInst *BitCastInst::clone_impl() const {
3570 return new BitCastInst(getOperand(0), getType());
3573 AddrSpaceCastInst *AddrSpaceCastInst::clone_impl() const {
3574 return new AddrSpaceCastInst(getOperand(0), getType());
3577 CallInst *CallInst::clone_impl() const {
3578 return new(getNumOperands()) CallInst(*this);
3581 SelectInst *SelectInst::clone_impl() const {
3582 return SelectInst::Create(getOperand(0), getOperand(1), getOperand(2));
3585 VAArgInst *VAArgInst::clone_impl() const {
3586 return new VAArgInst(getOperand(0), getType());
3589 ExtractElementInst *ExtractElementInst::clone_impl() const {
3590 return ExtractElementInst::Create(getOperand(0), getOperand(1));
3593 InsertElementInst *InsertElementInst::clone_impl() const {
3594 return InsertElementInst::Create(getOperand(0), getOperand(1), getOperand(2));
3597 ShuffleVectorInst *ShuffleVectorInst::clone_impl() const {
3598 return new ShuffleVectorInst(getOperand(0), getOperand(1), getOperand(2));
3601 PHINode *PHINode::clone_impl() const {
3602 return new PHINode(*this);
3605 LandingPadInst *LandingPadInst::clone_impl() const {
3606 return new LandingPadInst(*this);
3609 ReturnInst *ReturnInst::clone_impl() const {
3610 return new(getNumOperands()) ReturnInst(*this);
3613 BranchInst *BranchInst::clone_impl() const {
3614 return new(getNumOperands()) BranchInst(*this);
3617 SwitchInst *SwitchInst::clone_impl() const {
3618 return new SwitchInst(*this);
3621 IndirectBrInst *IndirectBrInst::clone_impl() const {
3622 return new IndirectBrInst(*this);
3626 InvokeInst *InvokeInst::clone_impl() const {
3627 return new(getNumOperands()) InvokeInst(*this);
3630 ResumeInst *ResumeInst::clone_impl() const {
3631 return new(1) ResumeInst(*this);
3634 UnreachableInst *UnreachableInst::clone_impl() const {
3635 LLVMContext &Context = getContext();
3636 return new UnreachableInst(Context);