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,
89 allocHungoffUses(PN.getNumOperands()), PN.getNumOperands()),
90 ReservedSpace(PN.getNumOperands()) {
91 std::copy(PN.op_begin(), PN.op_end(), op_begin());
92 std::copy(PN.block_begin(), PN.block_end(), block_begin());
93 SubclassOptionalData = PN.SubclassOptionalData;
100 Use *PHINode::allocHungoffUses(unsigned N) const {
101 // Allocate the array of Uses of the incoming values, followed by a pointer
102 // (with bottom bit set) to the User, followed by the array of pointers to
103 // the incoming basic blocks.
104 size_t size = N * sizeof(Use) + sizeof(Use::UserRef)
105 + N * sizeof(BasicBlock*);
106 Use *Begin = static_cast<Use*>(::operator new(size));
107 Use *End = Begin + N;
108 (void) new(End) Use::UserRef(const_cast<PHINode*>(this), 1);
109 return Use::initTags(Begin, End);
112 // removeIncomingValue - Remove an incoming value. This is useful if a
113 // predecessor basic block is deleted.
114 Value *PHINode::removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty) {
115 Value *Removed = getIncomingValue(Idx);
117 // Move everything after this operand down.
119 // FIXME: we could just swap with the end of the list, then erase. However,
120 // clients might not expect this to happen. The code as it is thrashes the
121 // use/def lists, which is kinda lame.
122 std::copy(op_begin() + Idx + 1, op_end(), op_begin() + Idx);
123 std::copy(block_begin() + Idx + 1, block_end(), block_begin() + Idx);
125 // Nuke the last value.
126 Op<-1>().set(nullptr);
129 // If the PHI node is dead, because it has zero entries, nuke it now.
130 if (getNumOperands() == 0 && DeletePHIIfEmpty) {
131 // If anyone is using this PHI, make them use a dummy value instead...
132 replaceAllUsesWith(UndefValue::get(getType()));
138 /// growOperands - grow operands - This grows the operand list in response
139 /// to a push_back style of operation. This grows the number of ops by 1.5
142 void PHINode::growOperands() {
143 unsigned e = getNumOperands();
144 unsigned NumOps = e + e / 2;
145 if (NumOps < 2) NumOps = 2; // 2 op PHI nodes are VERY common.
147 Use *OldOps = op_begin();
148 BasicBlock **OldBlocks = block_begin();
150 ReservedSpace = NumOps;
151 OperandList = allocHungoffUses(ReservedSpace);
153 std::copy(OldOps, OldOps + e, op_begin());
154 std::copy(OldBlocks, OldBlocks + e, block_begin());
156 Use::zap(OldOps, OldOps + e, true);
159 /// hasConstantValue - If the specified PHI node always merges together the same
160 /// value, return the value, otherwise return null.
161 Value *PHINode::hasConstantValue() const {
162 // Exploit the fact that phi nodes always have at least one entry.
163 Value *ConstantValue = getIncomingValue(0);
164 for (unsigned i = 1, e = getNumIncomingValues(); i != e; ++i)
165 if (getIncomingValue(i) != ConstantValue && getIncomingValue(i) != this) {
166 if (ConstantValue != this)
167 return nullptr; // Incoming values not all the same.
168 // The case where the first value is this PHI.
169 ConstantValue = getIncomingValue(i);
171 if (ConstantValue == this)
172 return UndefValue::get(getType());
173 return ConstantValue;
176 //===----------------------------------------------------------------------===//
177 // LandingPadInst Implementation
178 //===----------------------------------------------------------------------===//
180 LandingPadInst::LandingPadInst(Type *RetTy, Value *PersonalityFn,
181 unsigned NumReservedValues, const Twine &NameStr,
182 Instruction *InsertBefore)
183 : Instruction(RetTy, Instruction::LandingPad, nullptr, 0, InsertBefore) {
184 init(PersonalityFn, 1 + NumReservedValues, NameStr);
187 LandingPadInst::LandingPadInst(Type *RetTy, Value *PersonalityFn,
188 unsigned NumReservedValues, const Twine &NameStr,
189 BasicBlock *InsertAtEnd)
190 : Instruction(RetTy, Instruction::LandingPad, nullptr, 0, InsertAtEnd) {
191 init(PersonalityFn, 1 + NumReservedValues, NameStr);
194 LandingPadInst::LandingPadInst(const LandingPadInst &LP)
195 : Instruction(LP.getType(), Instruction::LandingPad,
196 allocHungoffUses(LP.getNumOperands()), LP.getNumOperands()),
197 ReservedSpace(LP.getNumOperands()) {
198 Use *OL = OperandList, *InOL = LP.OperandList;
199 for (unsigned I = 0, E = ReservedSpace; I != E; ++I)
202 setCleanup(LP.isCleanup());
205 LandingPadInst::~LandingPadInst() {
209 LandingPadInst *LandingPadInst::Create(Type *RetTy, Value *PersonalityFn,
210 unsigned NumReservedClauses,
211 const Twine &NameStr,
212 Instruction *InsertBefore) {
213 return new LandingPadInst(RetTy, PersonalityFn, NumReservedClauses, NameStr,
217 LandingPadInst *LandingPadInst::Create(Type *RetTy, Value *PersonalityFn,
218 unsigned NumReservedClauses,
219 const Twine &NameStr,
220 BasicBlock *InsertAtEnd) {
221 return new LandingPadInst(RetTy, PersonalityFn, NumReservedClauses, NameStr,
225 void LandingPadInst::init(Value *PersFn, unsigned NumReservedValues,
226 const Twine &NameStr) {
227 ReservedSpace = NumReservedValues;
229 OperandList = allocHungoffUses(ReservedSpace);
230 OperandList[0] = PersFn;
235 /// growOperands - grow operands - This grows the operand list in response to a
236 /// push_back style of operation. This grows the number of ops by 2 times.
237 void LandingPadInst::growOperands(unsigned Size) {
238 unsigned e = getNumOperands();
239 if (ReservedSpace >= e + Size) return;
240 ReservedSpace = (e + Size / 2) * 2;
242 Use *NewOps = allocHungoffUses(ReservedSpace);
243 Use *OldOps = OperandList;
244 for (unsigned i = 0; i != e; ++i)
245 NewOps[i] = OldOps[i];
247 OperandList = NewOps;
248 Use::zap(OldOps, OldOps + e, true);
251 void LandingPadInst::addClause(Constant *Val) {
252 unsigned OpNo = getNumOperands();
254 assert(OpNo < ReservedSpace && "Growing didn't work!");
256 OperandList[OpNo] = Val;
259 //===----------------------------------------------------------------------===//
260 // CallInst Implementation
261 //===----------------------------------------------------------------------===//
263 CallInst::~CallInst() {
266 void CallInst::init(Value *Func, ArrayRef<Value *> Args, const Twine &NameStr) {
267 assert(NumOperands == Args.size() + 1 && "NumOperands not set up?");
272 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
274 assert((Args.size() == FTy->getNumParams() ||
275 (FTy->isVarArg() && Args.size() > FTy->getNumParams())) &&
276 "Calling a function with bad signature!");
278 for (unsigned i = 0; i != Args.size(); ++i)
279 assert((i >= FTy->getNumParams() ||
280 FTy->getParamType(i) == Args[i]->getType()) &&
281 "Calling a function with a bad signature!");
284 std::copy(Args.begin(), Args.end(), op_begin());
288 void CallInst::init(Value *Func, const Twine &NameStr) {
289 assert(NumOperands == 1 && "NumOperands not set up?");
294 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
296 assert(FTy->getNumParams() == 0 && "Calling a function with bad signature");
302 CallInst::CallInst(Value *Func, const Twine &Name,
303 Instruction *InsertBefore)
304 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
305 ->getElementType())->getReturnType(),
307 OperandTraits<CallInst>::op_end(this) - 1,
312 CallInst::CallInst(Value *Func, const Twine &Name,
313 BasicBlock *InsertAtEnd)
314 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
315 ->getElementType())->getReturnType(),
317 OperandTraits<CallInst>::op_end(this) - 1,
322 CallInst::CallInst(const CallInst &CI)
323 : Instruction(CI.getType(), Instruction::Call,
324 OperandTraits<CallInst>::op_end(this) - CI.getNumOperands(),
325 CI.getNumOperands()) {
326 setAttributes(CI.getAttributes());
327 setTailCallKind(CI.getTailCallKind());
328 setCallingConv(CI.getCallingConv());
330 std::copy(CI.op_begin(), CI.op_end(), op_begin());
331 SubclassOptionalData = CI.SubclassOptionalData;
334 void CallInst::addAttribute(unsigned i, Attribute::AttrKind attr) {
335 AttributeSet PAL = getAttributes();
336 PAL = PAL.addAttribute(getContext(), i, attr);
340 void CallInst::removeAttribute(unsigned i, Attribute attr) {
341 AttributeSet PAL = getAttributes();
343 LLVMContext &Context = getContext();
344 PAL = PAL.removeAttributes(Context, i,
345 AttributeSet::get(Context, i, B));
349 void CallInst::addDereferenceableAttr(unsigned i, uint64_t Bytes) {
350 AttributeSet PAL = getAttributes();
351 PAL = PAL.addDereferenceableAttr(getContext(), i, Bytes);
355 bool CallInst::hasFnAttrImpl(Attribute::AttrKind A) const {
356 if (AttributeList.hasAttribute(AttributeSet::FunctionIndex, A))
358 if (const Function *F = getCalledFunction())
359 return F->getAttributes().hasAttribute(AttributeSet::FunctionIndex, A);
363 bool CallInst::paramHasAttr(unsigned i, Attribute::AttrKind A) const {
364 if (AttributeList.hasAttribute(i, A))
366 if (const Function *F = getCalledFunction())
367 return F->getAttributes().hasAttribute(i, A);
371 /// IsConstantOne - Return true only if val is constant int 1
372 static bool IsConstantOne(Value *val) {
373 assert(val && "IsConstantOne does not work with nullptr val");
374 const ConstantInt *CVal = dyn_cast<ConstantInt>(val);
375 return CVal && CVal->isOne();
378 static Instruction *createMalloc(Instruction *InsertBefore,
379 BasicBlock *InsertAtEnd, Type *IntPtrTy,
380 Type *AllocTy, Value *AllocSize,
381 Value *ArraySize, Function *MallocF,
383 assert(((!InsertBefore && InsertAtEnd) || (InsertBefore && !InsertAtEnd)) &&
384 "createMalloc needs either InsertBefore or InsertAtEnd");
386 // malloc(type) becomes:
387 // bitcast (i8* malloc(typeSize)) to type*
388 // malloc(type, arraySize) becomes:
389 // bitcast (i8 *malloc(typeSize*arraySize)) to type*
391 ArraySize = ConstantInt::get(IntPtrTy, 1);
392 else if (ArraySize->getType() != IntPtrTy) {
394 ArraySize = CastInst::CreateIntegerCast(ArraySize, IntPtrTy, false,
397 ArraySize = CastInst::CreateIntegerCast(ArraySize, IntPtrTy, false,
401 if (!IsConstantOne(ArraySize)) {
402 if (IsConstantOne(AllocSize)) {
403 AllocSize = ArraySize; // Operand * 1 = Operand
404 } else if (Constant *CO = dyn_cast<Constant>(ArraySize)) {
405 Constant *Scale = ConstantExpr::getIntegerCast(CO, IntPtrTy,
407 // Malloc arg is constant product of type size and array size
408 AllocSize = ConstantExpr::getMul(Scale, cast<Constant>(AllocSize));
410 // Multiply type size by the array size...
412 AllocSize = BinaryOperator::CreateMul(ArraySize, AllocSize,
413 "mallocsize", InsertBefore);
415 AllocSize = BinaryOperator::CreateMul(ArraySize, AllocSize,
416 "mallocsize", InsertAtEnd);
420 assert(AllocSize->getType() == IntPtrTy && "malloc arg is wrong size");
421 // Create the call to Malloc.
422 BasicBlock* BB = InsertBefore ? InsertBefore->getParent() : InsertAtEnd;
423 Module* M = BB->getParent()->getParent();
424 Type *BPTy = Type::getInt8PtrTy(BB->getContext());
425 Value *MallocFunc = MallocF;
427 // prototype malloc as "void *malloc(size_t)"
428 MallocFunc = M->getOrInsertFunction("malloc", BPTy, IntPtrTy, nullptr);
429 PointerType *AllocPtrType = PointerType::getUnqual(AllocTy);
430 CallInst *MCall = nullptr;
431 Instruction *Result = nullptr;
433 MCall = CallInst::Create(MallocFunc, AllocSize, "malloccall", InsertBefore);
435 if (Result->getType() != AllocPtrType)
436 // Create a cast instruction to convert to the right type...
437 Result = new BitCastInst(MCall, AllocPtrType, Name, InsertBefore);
439 MCall = CallInst::Create(MallocFunc, AllocSize, "malloccall");
441 if (Result->getType() != AllocPtrType) {
442 InsertAtEnd->getInstList().push_back(MCall);
443 // Create a cast instruction to convert to the right type...
444 Result = new BitCastInst(MCall, AllocPtrType, Name);
447 MCall->setTailCall();
448 if (Function *F = dyn_cast<Function>(MallocFunc)) {
449 MCall->setCallingConv(F->getCallingConv());
450 if (!F->doesNotAlias(0)) F->setDoesNotAlias(0);
452 assert(!MCall->getType()->isVoidTy() && "Malloc has void return type");
457 /// CreateMalloc - Generate the IR for a call to malloc:
458 /// 1. Compute the malloc call's argument as the specified type's size,
459 /// possibly multiplied by the array size if the array size is not
461 /// 2. Call malloc with that argument.
462 /// 3. Bitcast the result of the malloc call to the specified type.
463 Instruction *CallInst::CreateMalloc(Instruction *InsertBefore,
464 Type *IntPtrTy, Type *AllocTy,
465 Value *AllocSize, Value *ArraySize,
468 return createMalloc(InsertBefore, nullptr, IntPtrTy, AllocTy, AllocSize,
469 ArraySize, MallocF, Name);
472 /// CreateMalloc - Generate the IR for a call to malloc:
473 /// 1. Compute the malloc call's argument as the specified type's size,
474 /// possibly multiplied by the array size if the array size is not
476 /// 2. Call malloc with that argument.
477 /// 3. Bitcast the result of the malloc call to the specified type.
478 /// Note: This function does not add the bitcast to the basic block, that is the
479 /// responsibility of the caller.
480 Instruction *CallInst::CreateMalloc(BasicBlock *InsertAtEnd,
481 Type *IntPtrTy, Type *AllocTy,
482 Value *AllocSize, Value *ArraySize,
483 Function *MallocF, const Twine &Name) {
484 return createMalloc(nullptr, InsertAtEnd, IntPtrTy, AllocTy, AllocSize,
485 ArraySize, MallocF, Name);
488 static Instruction* createFree(Value* Source, Instruction *InsertBefore,
489 BasicBlock *InsertAtEnd) {
490 assert(((!InsertBefore && InsertAtEnd) || (InsertBefore && !InsertAtEnd)) &&
491 "createFree needs either InsertBefore or InsertAtEnd");
492 assert(Source->getType()->isPointerTy() &&
493 "Can not free something of nonpointer type!");
495 BasicBlock* BB = InsertBefore ? InsertBefore->getParent() : InsertAtEnd;
496 Module* M = BB->getParent()->getParent();
498 Type *VoidTy = Type::getVoidTy(M->getContext());
499 Type *IntPtrTy = Type::getInt8PtrTy(M->getContext());
500 // prototype free as "void free(void*)"
501 Value *FreeFunc = M->getOrInsertFunction("free", VoidTy, IntPtrTy, nullptr);
502 CallInst* Result = nullptr;
503 Value *PtrCast = Source;
505 if (Source->getType() != IntPtrTy)
506 PtrCast = new BitCastInst(Source, IntPtrTy, "", InsertBefore);
507 Result = CallInst::Create(FreeFunc, PtrCast, "", InsertBefore);
509 if (Source->getType() != IntPtrTy)
510 PtrCast = new BitCastInst(Source, IntPtrTy, "", InsertAtEnd);
511 Result = CallInst::Create(FreeFunc, PtrCast, "");
513 Result->setTailCall();
514 if (Function *F = dyn_cast<Function>(FreeFunc))
515 Result->setCallingConv(F->getCallingConv());
520 /// CreateFree - Generate the IR for a call to the builtin free function.
521 Instruction * CallInst::CreateFree(Value* Source, Instruction *InsertBefore) {
522 return createFree(Source, InsertBefore, nullptr);
525 /// CreateFree - Generate the IR for a call to the builtin free function.
526 /// Note: This function does not add the call to the basic block, that is the
527 /// responsibility of the caller.
528 Instruction* CallInst::CreateFree(Value* Source, BasicBlock *InsertAtEnd) {
529 Instruction* FreeCall = createFree(Source, nullptr, InsertAtEnd);
530 assert(FreeCall && "CreateFree did not create a CallInst");
534 //===----------------------------------------------------------------------===//
535 // InvokeInst Implementation
536 //===----------------------------------------------------------------------===//
538 void InvokeInst::init(Value *Fn, BasicBlock *IfNormal, BasicBlock *IfException,
539 ArrayRef<Value *> Args, const Twine &NameStr) {
540 assert(NumOperands == 3 + Args.size() && "NumOperands not set up?");
543 Op<-1>() = IfException;
547 cast<FunctionType>(cast<PointerType>(Fn->getType())->getElementType());
549 assert(((Args.size() == FTy->getNumParams()) ||
550 (FTy->isVarArg() && Args.size() > FTy->getNumParams())) &&
551 "Invoking a function with bad signature");
553 for (unsigned i = 0, e = Args.size(); i != e; i++)
554 assert((i >= FTy->getNumParams() ||
555 FTy->getParamType(i) == Args[i]->getType()) &&
556 "Invoking a function with a bad signature!");
559 std::copy(Args.begin(), Args.end(), op_begin());
563 InvokeInst::InvokeInst(const InvokeInst &II)
564 : TerminatorInst(II.getType(), Instruction::Invoke,
565 OperandTraits<InvokeInst>::op_end(this)
566 - II.getNumOperands(),
567 II.getNumOperands()) {
568 setAttributes(II.getAttributes());
569 setCallingConv(II.getCallingConv());
570 std::copy(II.op_begin(), II.op_end(), op_begin());
571 SubclassOptionalData = II.SubclassOptionalData;
574 BasicBlock *InvokeInst::getSuccessorV(unsigned idx) const {
575 return getSuccessor(idx);
577 unsigned InvokeInst::getNumSuccessorsV() const {
578 return getNumSuccessors();
580 void InvokeInst::setSuccessorV(unsigned idx, BasicBlock *B) {
581 return setSuccessor(idx, B);
584 bool InvokeInst::hasFnAttrImpl(Attribute::AttrKind A) const {
585 if (AttributeList.hasAttribute(AttributeSet::FunctionIndex, A))
587 if (const Function *F = getCalledFunction())
588 return F->getAttributes().hasAttribute(AttributeSet::FunctionIndex, A);
592 bool InvokeInst::paramHasAttr(unsigned i, Attribute::AttrKind A) const {
593 if (AttributeList.hasAttribute(i, A))
595 if (const Function *F = getCalledFunction())
596 return F->getAttributes().hasAttribute(i, A);
600 void InvokeInst::addAttribute(unsigned i, Attribute::AttrKind attr) {
601 AttributeSet PAL = getAttributes();
602 PAL = PAL.addAttribute(getContext(), i, attr);
606 void InvokeInst::removeAttribute(unsigned i, Attribute attr) {
607 AttributeSet PAL = getAttributes();
609 PAL = PAL.removeAttributes(getContext(), i,
610 AttributeSet::get(getContext(), i, B));
614 void InvokeInst::addDereferenceableAttr(unsigned i, uint64_t Bytes) {
615 AttributeSet PAL = getAttributes();
616 PAL = PAL.addDereferenceableAttr(getContext(), i, Bytes);
620 LandingPadInst *InvokeInst::getLandingPadInst() const {
621 return cast<LandingPadInst>(getUnwindDest()->getFirstNonPHI());
624 //===----------------------------------------------------------------------===//
625 // ReturnInst Implementation
626 //===----------------------------------------------------------------------===//
628 ReturnInst::ReturnInst(const ReturnInst &RI)
629 : TerminatorInst(Type::getVoidTy(RI.getContext()), Instruction::Ret,
630 OperandTraits<ReturnInst>::op_end(this) -
632 RI.getNumOperands()) {
633 if (RI.getNumOperands())
634 Op<0>() = RI.Op<0>();
635 SubclassOptionalData = RI.SubclassOptionalData;
638 ReturnInst::ReturnInst(LLVMContext &C, Value *retVal, Instruction *InsertBefore)
639 : TerminatorInst(Type::getVoidTy(C), Instruction::Ret,
640 OperandTraits<ReturnInst>::op_end(this) - !!retVal, !!retVal,
645 ReturnInst::ReturnInst(LLVMContext &C, Value *retVal, BasicBlock *InsertAtEnd)
646 : TerminatorInst(Type::getVoidTy(C), Instruction::Ret,
647 OperandTraits<ReturnInst>::op_end(this) - !!retVal, !!retVal,
652 ReturnInst::ReturnInst(LLVMContext &Context, BasicBlock *InsertAtEnd)
653 : TerminatorInst(Type::getVoidTy(Context), Instruction::Ret,
654 OperandTraits<ReturnInst>::op_end(this), 0, InsertAtEnd) {
657 unsigned ReturnInst::getNumSuccessorsV() const {
658 return getNumSuccessors();
661 /// Out-of-line ReturnInst method, put here so the C++ compiler can choose to
662 /// emit the vtable for the class in this translation unit.
663 void ReturnInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
664 llvm_unreachable("ReturnInst has no successors!");
667 BasicBlock *ReturnInst::getSuccessorV(unsigned idx) const {
668 llvm_unreachable("ReturnInst has no successors!");
671 ReturnInst::~ReturnInst() {
674 //===----------------------------------------------------------------------===//
675 // ResumeInst Implementation
676 //===----------------------------------------------------------------------===//
678 ResumeInst::ResumeInst(const ResumeInst &RI)
679 : TerminatorInst(Type::getVoidTy(RI.getContext()), Instruction::Resume,
680 OperandTraits<ResumeInst>::op_begin(this), 1) {
681 Op<0>() = RI.Op<0>();
684 ResumeInst::ResumeInst(Value *Exn, Instruction *InsertBefore)
685 : TerminatorInst(Type::getVoidTy(Exn->getContext()), Instruction::Resume,
686 OperandTraits<ResumeInst>::op_begin(this), 1, InsertBefore) {
690 ResumeInst::ResumeInst(Value *Exn, BasicBlock *InsertAtEnd)
691 : TerminatorInst(Type::getVoidTy(Exn->getContext()), Instruction::Resume,
692 OperandTraits<ResumeInst>::op_begin(this), 1, InsertAtEnd) {
696 unsigned ResumeInst::getNumSuccessorsV() const {
697 return getNumSuccessors();
700 void ResumeInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
701 llvm_unreachable("ResumeInst has no successors!");
704 BasicBlock *ResumeInst::getSuccessorV(unsigned idx) const {
705 llvm_unreachable("ResumeInst has no successors!");
708 //===----------------------------------------------------------------------===//
709 // UnreachableInst Implementation
710 //===----------------------------------------------------------------------===//
712 UnreachableInst::UnreachableInst(LLVMContext &Context,
713 Instruction *InsertBefore)
714 : TerminatorInst(Type::getVoidTy(Context), Instruction::Unreachable,
715 nullptr, 0, InsertBefore) {
717 UnreachableInst::UnreachableInst(LLVMContext &Context, BasicBlock *InsertAtEnd)
718 : TerminatorInst(Type::getVoidTy(Context), Instruction::Unreachable,
719 nullptr, 0, InsertAtEnd) {
722 unsigned UnreachableInst::getNumSuccessorsV() const {
723 return getNumSuccessors();
726 void UnreachableInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
727 llvm_unreachable("UnreachableInst has no successors!");
730 BasicBlock *UnreachableInst::getSuccessorV(unsigned idx) const {
731 llvm_unreachable("UnreachableInst has no successors!");
734 //===----------------------------------------------------------------------===//
735 // BranchInst Implementation
736 //===----------------------------------------------------------------------===//
738 void BranchInst::AssertOK() {
740 assert(getCondition()->getType()->isIntegerTy(1) &&
741 "May only branch on boolean predicates!");
744 BranchInst::BranchInst(BasicBlock *IfTrue, Instruction *InsertBefore)
745 : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
746 OperandTraits<BranchInst>::op_end(this) - 1,
748 assert(IfTrue && "Branch destination may not be null!");
751 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
752 Instruction *InsertBefore)
753 : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
754 OperandTraits<BranchInst>::op_end(this) - 3,
764 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *InsertAtEnd)
765 : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
766 OperandTraits<BranchInst>::op_end(this) - 1,
768 assert(IfTrue && "Branch destination may not be null!");
772 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
773 BasicBlock *InsertAtEnd)
774 : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
775 OperandTraits<BranchInst>::op_end(this) - 3,
786 BranchInst::BranchInst(const BranchInst &BI) :
787 TerminatorInst(Type::getVoidTy(BI.getContext()), Instruction::Br,
788 OperandTraits<BranchInst>::op_end(this) - BI.getNumOperands(),
789 BI.getNumOperands()) {
790 Op<-1>() = BI.Op<-1>();
791 if (BI.getNumOperands() != 1) {
792 assert(BI.getNumOperands() == 3 && "BR can have 1 or 3 operands!");
793 Op<-3>() = BI.Op<-3>();
794 Op<-2>() = BI.Op<-2>();
796 SubclassOptionalData = BI.SubclassOptionalData;
799 void BranchInst::swapSuccessors() {
800 assert(isConditional() &&
801 "Cannot swap successors of an unconditional branch");
802 Op<-1>().swap(Op<-2>());
804 // Update profile metadata if present and it matches our structural
806 MDNode *ProfileData = getMetadata(LLVMContext::MD_prof);
807 if (!ProfileData || ProfileData->getNumOperands() != 3)
810 // The first operand is the name. Fetch them backwards and build a new one.
811 Metadata *Ops[] = {ProfileData->getOperand(0), ProfileData->getOperand(2),
812 ProfileData->getOperand(1)};
813 setMetadata(LLVMContext::MD_prof,
814 MDNode::get(ProfileData->getContext(), Ops));
817 BasicBlock *BranchInst::getSuccessorV(unsigned idx) const {
818 return getSuccessor(idx);
820 unsigned BranchInst::getNumSuccessorsV() const {
821 return getNumSuccessors();
823 void BranchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
824 setSuccessor(idx, B);
828 //===----------------------------------------------------------------------===//
829 // AllocaInst Implementation
830 //===----------------------------------------------------------------------===//
832 static Value *getAISize(LLVMContext &Context, Value *Amt) {
834 Amt = ConstantInt::get(Type::getInt32Ty(Context), 1);
836 assert(!isa<BasicBlock>(Amt) &&
837 "Passed basic block into allocation size parameter! Use other ctor");
838 assert(Amt->getType()->isIntegerTy() &&
839 "Allocation array size is not an integer!");
844 AllocaInst::AllocaInst(Type *Ty, Value *ArraySize,
845 const Twine &Name, Instruction *InsertBefore)
846 : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
847 getAISize(Ty->getContext(), ArraySize), InsertBefore) {
849 assert(!Ty->isVoidTy() && "Cannot allocate void!");
853 AllocaInst::AllocaInst(Type *Ty, Value *ArraySize,
854 const Twine &Name, BasicBlock *InsertAtEnd)
855 : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
856 getAISize(Ty->getContext(), ArraySize), InsertAtEnd) {
858 assert(!Ty->isVoidTy() && "Cannot allocate void!");
862 AllocaInst::AllocaInst(Type *Ty, const Twine &Name,
863 Instruction *InsertBefore)
864 : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
865 getAISize(Ty->getContext(), nullptr), InsertBefore) {
867 assert(!Ty->isVoidTy() && "Cannot allocate void!");
871 AllocaInst::AllocaInst(Type *Ty, const Twine &Name,
872 BasicBlock *InsertAtEnd)
873 : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
874 getAISize(Ty->getContext(), nullptr), InsertAtEnd) {
876 assert(!Ty->isVoidTy() && "Cannot allocate void!");
880 AllocaInst::AllocaInst(Type *Ty, Value *ArraySize, unsigned Align,
881 const Twine &Name, Instruction *InsertBefore)
882 : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
883 getAISize(Ty->getContext(), ArraySize), InsertBefore) {
885 assert(!Ty->isVoidTy() && "Cannot allocate void!");
889 AllocaInst::AllocaInst(Type *Ty, Value *ArraySize, unsigned Align,
890 const Twine &Name, BasicBlock *InsertAtEnd)
891 : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
892 getAISize(Ty->getContext(), ArraySize), InsertAtEnd) {
894 assert(!Ty->isVoidTy() && "Cannot allocate void!");
898 // Out of line virtual method, so the vtable, etc has a home.
899 AllocaInst::~AllocaInst() {
902 void AllocaInst::setAlignment(unsigned Align) {
903 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
904 assert(Align <= MaximumAlignment &&
905 "Alignment is greater than MaximumAlignment!");
906 setInstructionSubclassData((getSubclassDataFromInstruction() & ~31) |
907 (Log2_32(Align) + 1));
908 assert(getAlignment() == Align && "Alignment representation error!");
911 bool AllocaInst::isArrayAllocation() const {
912 if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(0)))
917 Type *AllocaInst::getAllocatedType() const {
918 return getType()->getElementType();
921 /// isStaticAlloca - Return true if this alloca is in the entry block of the
922 /// function and is a constant size. If so, the code generator will fold it
923 /// into the prolog/epilog code, so it is basically free.
924 bool AllocaInst::isStaticAlloca() const {
925 // Must be constant size.
926 if (!isa<ConstantInt>(getArraySize())) return false;
928 // Must be in the entry block.
929 const BasicBlock *Parent = getParent();
930 return Parent == &Parent->getParent()->front() && !isUsedWithInAlloca();
933 //===----------------------------------------------------------------------===//
934 // LoadInst Implementation
935 //===----------------------------------------------------------------------===//
937 void LoadInst::AssertOK() {
938 assert(getOperand(0)->getType()->isPointerTy() &&
939 "Ptr must have pointer type.");
940 assert(!(isAtomic() && getAlignment() == 0) &&
941 "Alignment required for atomic load");
944 LoadInst::LoadInst(Value *Ptr, const Twine &Name, Instruction *InsertBef)
945 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
946 Load, Ptr, InsertBef) {
949 setAtomic(NotAtomic);
954 LoadInst::LoadInst(Value *Ptr, const Twine &Name, BasicBlock *InsertAE)
955 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
956 Load, Ptr, InsertAE) {
959 setAtomic(NotAtomic);
964 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
965 Instruction *InsertBef)
966 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
967 Load, Ptr, InsertBef) {
968 setVolatile(isVolatile);
970 setAtomic(NotAtomic);
975 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
976 BasicBlock *InsertAE)
977 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
978 Load, Ptr, InsertAE) {
979 setVolatile(isVolatile);
981 setAtomic(NotAtomic);
986 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
987 unsigned Align, Instruction *InsertBef)
988 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
989 Load, Ptr, InsertBef) {
990 setVolatile(isVolatile);
992 setAtomic(NotAtomic);
997 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
998 unsigned Align, BasicBlock *InsertAE)
999 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1000 Load, Ptr, InsertAE) {
1001 setVolatile(isVolatile);
1002 setAlignment(Align);
1003 setAtomic(NotAtomic);
1008 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
1009 unsigned Align, AtomicOrdering Order,
1010 SynchronizationScope SynchScope,
1011 Instruction *InsertBef)
1012 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1013 Load, Ptr, InsertBef) {
1014 setVolatile(isVolatile);
1015 setAlignment(Align);
1016 setAtomic(Order, SynchScope);
1021 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
1022 unsigned Align, AtomicOrdering Order,
1023 SynchronizationScope SynchScope,
1024 BasicBlock *InsertAE)
1025 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1026 Load, Ptr, InsertAE) {
1027 setVolatile(isVolatile);
1028 setAlignment(Align);
1029 setAtomic(Order, SynchScope);
1034 LoadInst::LoadInst(Value *Ptr, const char *Name, Instruction *InsertBef)
1035 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1036 Load, Ptr, InsertBef) {
1039 setAtomic(NotAtomic);
1041 if (Name && Name[0]) setName(Name);
1044 LoadInst::LoadInst(Value *Ptr, const char *Name, BasicBlock *InsertAE)
1045 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1046 Load, Ptr, InsertAE) {
1049 setAtomic(NotAtomic);
1051 if (Name && Name[0]) setName(Name);
1054 LoadInst::LoadInst(Value *Ptr, const char *Name, bool isVolatile,
1055 Instruction *InsertBef)
1056 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1057 Load, Ptr, InsertBef) {
1058 setVolatile(isVolatile);
1060 setAtomic(NotAtomic);
1062 if (Name && Name[0]) setName(Name);
1065 LoadInst::LoadInst(Value *Ptr, const char *Name, bool isVolatile,
1066 BasicBlock *InsertAE)
1067 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1068 Load, Ptr, InsertAE) {
1069 setVolatile(isVolatile);
1071 setAtomic(NotAtomic);
1073 if (Name && Name[0]) setName(Name);
1076 void LoadInst::setAlignment(unsigned Align) {
1077 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
1078 assert(Align <= MaximumAlignment &&
1079 "Alignment is greater than MaximumAlignment!");
1080 setInstructionSubclassData((getSubclassDataFromInstruction() & ~(31 << 1)) |
1081 ((Log2_32(Align)+1)<<1));
1082 assert(getAlignment() == Align && "Alignment representation error!");
1085 //===----------------------------------------------------------------------===//
1086 // StoreInst Implementation
1087 //===----------------------------------------------------------------------===//
1089 void StoreInst::AssertOK() {
1090 assert(getOperand(0) && getOperand(1) && "Both operands must be non-null!");
1091 assert(getOperand(1)->getType()->isPointerTy() &&
1092 "Ptr must have pointer type!");
1093 assert(getOperand(0)->getType() ==
1094 cast<PointerType>(getOperand(1)->getType())->getElementType()
1095 && "Ptr must be a pointer to Val type!");
1096 assert(!(isAtomic() && getAlignment() == 0) &&
1097 "Alignment required for atomic store");
1101 StoreInst::StoreInst(Value *val, Value *addr, Instruction *InsertBefore)
1102 : Instruction(Type::getVoidTy(val->getContext()), Store,
1103 OperandTraits<StoreInst>::op_begin(this),
1104 OperandTraits<StoreInst>::operands(this),
1110 setAtomic(NotAtomic);
1114 StoreInst::StoreInst(Value *val, Value *addr, BasicBlock *InsertAtEnd)
1115 : Instruction(Type::getVoidTy(val->getContext()), Store,
1116 OperandTraits<StoreInst>::op_begin(this),
1117 OperandTraits<StoreInst>::operands(this),
1123 setAtomic(NotAtomic);
1127 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1128 Instruction *InsertBefore)
1129 : Instruction(Type::getVoidTy(val->getContext()), Store,
1130 OperandTraits<StoreInst>::op_begin(this),
1131 OperandTraits<StoreInst>::operands(this),
1135 setVolatile(isVolatile);
1137 setAtomic(NotAtomic);
1141 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1142 unsigned Align, Instruction *InsertBefore)
1143 : Instruction(Type::getVoidTy(val->getContext()), Store,
1144 OperandTraits<StoreInst>::op_begin(this),
1145 OperandTraits<StoreInst>::operands(this),
1149 setVolatile(isVolatile);
1150 setAlignment(Align);
1151 setAtomic(NotAtomic);
1155 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1156 unsigned Align, AtomicOrdering Order,
1157 SynchronizationScope SynchScope,
1158 Instruction *InsertBefore)
1159 : Instruction(Type::getVoidTy(val->getContext()), Store,
1160 OperandTraits<StoreInst>::op_begin(this),
1161 OperandTraits<StoreInst>::operands(this),
1165 setVolatile(isVolatile);
1166 setAlignment(Align);
1167 setAtomic(Order, SynchScope);
1171 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1172 BasicBlock *InsertAtEnd)
1173 : Instruction(Type::getVoidTy(val->getContext()), Store,
1174 OperandTraits<StoreInst>::op_begin(this),
1175 OperandTraits<StoreInst>::operands(this),
1179 setVolatile(isVolatile);
1181 setAtomic(NotAtomic);
1185 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1186 unsigned Align, BasicBlock *InsertAtEnd)
1187 : Instruction(Type::getVoidTy(val->getContext()), Store,
1188 OperandTraits<StoreInst>::op_begin(this),
1189 OperandTraits<StoreInst>::operands(this),
1193 setVolatile(isVolatile);
1194 setAlignment(Align);
1195 setAtomic(NotAtomic);
1199 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1200 unsigned Align, AtomicOrdering Order,
1201 SynchronizationScope SynchScope,
1202 BasicBlock *InsertAtEnd)
1203 : Instruction(Type::getVoidTy(val->getContext()), Store,
1204 OperandTraits<StoreInst>::op_begin(this),
1205 OperandTraits<StoreInst>::operands(this),
1209 setVolatile(isVolatile);
1210 setAlignment(Align);
1211 setAtomic(Order, SynchScope);
1215 void StoreInst::setAlignment(unsigned Align) {
1216 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
1217 assert(Align <= MaximumAlignment &&
1218 "Alignment is greater than MaximumAlignment!");
1219 setInstructionSubclassData((getSubclassDataFromInstruction() & ~(31 << 1)) |
1220 ((Log2_32(Align)+1) << 1));
1221 assert(getAlignment() == Align && "Alignment representation error!");
1224 //===----------------------------------------------------------------------===//
1225 // AtomicCmpXchgInst Implementation
1226 //===----------------------------------------------------------------------===//
1228 void AtomicCmpXchgInst::Init(Value *Ptr, Value *Cmp, Value *NewVal,
1229 AtomicOrdering SuccessOrdering,
1230 AtomicOrdering FailureOrdering,
1231 SynchronizationScope SynchScope) {
1235 setSuccessOrdering(SuccessOrdering);
1236 setFailureOrdering(FailureOrdering);
1237 setSynchScope(SynchScope);
1239 assert(getOperand(0) && getOperand(1) && getOperand(2) &&
1240 "All operands must be non-null!");
1241 assert(getOperand(0)->getType()->isPointerTy() &&
1242 "Ptr must have pointer type!");
1243 assert(getOperand(1)->getType() ==
1244 cast<PointerType>(getOperand(0)->getType())->getElementType()
1245 && "Ptr must be a pointer to Cmp type!");
1246 assert(getOperand(2)->getType() ==
1247 cast<PointerType>(getOperand(0)->getType())->getElementType()
1248 && "Ptr must be a pointer to NewVal type!");
1249 assert(SuccessOrdering != NotAtomic &&
1250 "AtomicCmpXchg instructions must be atomic!");
1251 assert(FailureOrdering != NotAtomic &&
1252 "AtomicCmpXchg instructions must be atomic!");
1253 assert(SuccessOrdering >= FailureOrdering &&
1254 "AtomicCmpXchg success ordering must be at least as strong as fail");
1255 assert(FailureOrdering != Release && FailureOrdering != AcquireRelease &&
1256 "AtomicCmpXchg failure ordering cannot include release semantics");
1259 AtomicCmpXchgInst::AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal,
1260 AtomicOrdering SuccessOrdering,
1261 AtomicOrdering FailureOrdering,
1262 SynchronizationScope SynchScope,
1263 Instruction *InsertBefore)
1265 StructType::get(Cmp->getType(), Type::getInt1Ty(Cmp->getContext()),
1267 AtomicCmpXchg, OperandTraits<AtomicCmpXchgInst>::op_begin(this),
1268 OperandTraits<AtomicCmpXchgInst>::operands(this), InsertBefore) {
1269 Init(Ptr, Cmp, NewVal, SuccessOrdering, FailureOrdering, SynchScope);
1272 AtomicCmpXchgInst::AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal,
1273 AtomicOrdering SuccessOrdering,
1274 AtomicOrdering FailureOrdering,
1275 SynchronizationScope SynchScope,
1276 BasicBlock *InsertAtEnd)
1278 StructType::get(Cmp->getType(), Type::getInt1Ty(Cmp->getContext()),
1280 AtomicCmpXchg, OperandTraits<AtomicCmpXchgInst>::op_begin(this),
1281 OperandTraits<AtomicCmpXchgInst>::operands(this), InsertAtEnd) {
1282 Init(Ptr, Cmp, NewVal, SuccessOrdering, FailureOrdering, SynchScope);
1285 //===----------------------------------------------------------------------===//
1286 // AtomicRMWInst Implementation
1287 //===----------------------------------------------------------------------===//
1289 void AtomicRMWInst::Init(BinOp Operation, Value *Ptr, Value *Val,
1290 AtomicOrdering Ordering,
1291 SynchronizationScope SynchScope) {
1294 setOperation(Operation);
1295 setOrdering(Ordering);
1296 setSynchScope(SynchScope);
1298 assert(getOperand(0) && getOperand(1) &&
1299 "All operands must be non-null!");
1300 assert(getOperand(0)->getType()->isPointerTy() &&
1301 "Ptr must have pointer type!");
1302 assert(getOperand(1)->getType() ==
1303 cast<PointerType>(getOperand(0)->getType())->getElementType()
1304 && "Ptr must be a pointer to Val type!");
1305 assert(Ordering != NotAtomic &&
1306 "AtomicRMW instructions must be atomic!");
1309 AtomicRMWInst::AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val,
1310 AtomicOrdering Ordering,
1311 SynchronizationScope SynchScope,
1312 Instruction *InsertBefore)
1313 : Instruction(Val->getType(), AtomicRMW,
1314 OperandTraits<AtomicRMWInst>::op_begin(this),
1315 OperandTraits<AtomicRMWInst>::operands(this),
1317 Init(Operation, Ptr, Val, Ordering, SynchScope);
1320 AtomicRMWInst::AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val,
1321 AtomicOrdering Ordering,
1322 SynchronizationScope SynchScope,
1323 BasicBlock *InsertAtEnd)
1324 : Instruction(Val->getType(), AtomicRMW,
1325 OperandTraits<AtomicRMWInst>::op_begin(this),
1326 OperandTraits<AtomicRMWInst>::operands(this),
1328 Init(Operation, Ptr, Val, Ordering, SynchScope);
1331 //===----------------------------------------------------------------------===//
1332 // FenceInst Implementation
1333 //===----------------------------------------------------------------------===//
1335 FenceInst::FenceInst(LLVMContext &C, AtomicOrdering Ordering,
1336 SynchronizationScope SynchScope,
1337 Instruction *InsertBefore)
1338 : Instruction(Type::getVoidTy(C), Fence, nullptr, 0, InsertBefore) {
1339 setOrdering(Ordering);
1340 setSynchScope(SynchScope);
1343 FenceInst::FenceInst(LLVMContext &C, AtomicOrdering Ordering,
1344 SynchronizationScope SynchScope,
1345 BasicBlock *InsertAtEnd)
1346 : Instruction(Type::getVoidTy(C), Fence, nullptr, 0, InsertAtEnd) {
1347 setOrdering(Ordering);
1348 setSynchScope(SynchScope);
1351 //===----------------------------------------------------------------------===//
1352 // GetElementPtrInst Implementation
1353 //===----------------------------------------------------------------------===//
1355 void GetElementPtrInst::init(Value *Ptr, ArrayRef<Value *> IdxList,
1356 const Twine &Name) {
1357 assert(NumOperands == 1 + IdxList.size() && "NumOperands not initialized?");
1358 OperandList[0] = Ptr;
1359 std::copy(IdxList.begin(), IdxList.end(), op_begin() + 1);
1363 GetElementPtrInst::GetElementPtrInst(const GetElementPtrInst &GEPI)
1364 : Instruction(GEPI.getType(), GetElementPtr,
1365 OperandTraits<GetElementPtrInst>::op_end(this)
1366 - GEPI.getNumOperands(),
1367 GEPI.getNumOperands()) {
1368 std::copy(GEPI.op_begin(), GEPI.op_end(), op_begin());
1369 SubclassOptionalData = GEPI.SubclassOptionalData;
1372 /// getIndexedType - Returns the type of the element that would be accessed with
1373 /// a gep instruction with the specified parameters.
1375 /// The Idxs pointer should point to a continuous piece of memory containing the
1376 /// indices, either as Value* or uint64_t.
1378 /// A null type is returned if the indices are invalid for the specified
1381 template <typename IndexTy>
1382 static Type *getIndexedTypeInternal(Type *Ptr, ArrayRef<IndexTy> IdxList) {
1383 PointerType *PTy = dyn_cast<PointerType>(Ptr->getScalarType());
1384 if (!PTy) return nullptr; // Type isn't a pointer type!
1385 Type *Agg = PTy->getElementType();
1387 // Handle the special case of the empty set index set, which is always valid.
1388 if (IdxList.empty())
1391 // If there is at least one index, the top level type must be sized, otherwise
1392 // it cannot be 'stepped over'.
1393 if (!Agg->isSized())
1396 unsigned CurIdx = 1;
1397 for (; CurIdx != IdxList.size(); ++CurIdx) {
1398 CompositeType *CT = dyn_cast<CompositeType>(Agg);
1399 if (!CT || CT->isPointerTy()) return nullptr;
1400 IndexTy Index = IdxList[CurIdx];
1401 if (!CT->indexValid(Index)) return nullptr;
1402 Agg = CT->getTypeAtIndex(Index);
1404 return CurIdx == IdxList.size() ? Agg : nullptr;
1407 Type *GetElementPtrInst::getIndexedType(Type *Ptr, ArrayRef<Value *> IdxList) {
1408 return getIndexedTypeInternal(Ptr, IdxList);
1411 Type *GetElementPtrInst::getIndexedType(Type *Ptr,
1412 ArrayRef<Constant *> IdxList) {
1413 return getIndexedTypeInternal(Ptr, IdxList);
1416 Type *GetElementPtrInst::getIndexedType(Type *Ptr, ArrayRef<uint64_t> IdxList) {
1417 return getIndexedTypeInternal(Ptr, IdxList);
1420 /// hasAllZeroIndices - Return true if all of the indices of this GEP are
1421 /// zeros. If so, the result pointer and the first operand have the same
1422 /// value, just potentially different types.
1423 bool GetElementPtrInst::hasAllZeroIndices() const {
1424 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1425 if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(i))) {
1426 if (!CI->isZero()) return false;
1434 /// hasAllConstantIndices - Return true if all of the indices of this GEP are
1435 /// constant integers. If so, the result pointer and the first operand have
1436 /// a constant offset between them.
1437 bool GetElementPtrInst::hasAllConstantIndices() const {
1438 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1439 if (!isa<ConstantInt>(getOperand(i)))
1445 void GetElementPtrInst::setIsInBounds(bool B) {
1446 cast<GEPOperator>(this)->setIsInBounds(B);
1449 bool GetElementPtrInst::isInBounds() const {
1450 return cast<GEPOperator>(this)->isInBounds();
1453 bool GetElementPtrInst::accumulateConstantOffset(const DataLayout &DL,
1454 APInt &Offset) const {
1455 // Delegate to the generic GEPOperator implementation.
1456 return cast<GEPOperator>(this)->accumulateConstantOffset(DL, Offset);
1459 //===----------------------------------------------------------------------===//
1460 // ExtractElementInst Implementation
1461 //===----------------------------------------------------------------------===//
1463 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
1465 Instruction *InsertBef)
1466 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1468 OperandTraits<ExtractElementInst>::op_begin(this),
1470 assert(isValidOperands(Val, Index) &&
1471 "Invalid extractelement instruction operands!");
1477 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
1479 BasicBlock *InsertAE)
1480 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1482 OperandTraits<ExtractElementInst>::op_begin(this),
1484 assert(isValidOperands(Val, Index) &&
1485 "Invalid extractelement instruction operands!");
1493 bool ExtractElementInst::isValidOperands(const Value *Val, const Value *Index) {
1494 if (!Val->getType()->isVectorTy() || !Index->getType()->isIntegerTy())
1500 //===----------------------------------------------------------------------===//
1501 // InsertElementInst Implementation
1502 //===----------------------------------------------------------------------===//
1504 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
1506 Instruction *InsertBef)
1507 : Instruction(Vec->getType(), InsertElement,
1508 OperandTraits<InsertElementInst>::op_begin(this),
1510 assert(isValidOperands(Vec, Elt, Index) &&
1511 "Invalid insertelement instruction operands!");
1518 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
1520 BasicBlock *InsertAE)
1521 : Instruction(Vec->getType(), InsertElement,
1522 OperandTraits<InsertElementInst>::op_begin(this),
1524 assert(isValidOperands(Vec, Elt, Index) &&
1525 "Invalid insertelement instruction operands!");
1533 bool InsertElementInst::isValidOperands(const Value *Vec, const Value *Elt,
1534 const Value *Index) {
1535 if (!Vec->getType()->isVectorTy())
1536 return false; // First operand of insertelement must be vector type.
1538 if (Elt->getType() != cast<VectorType>(Vec->getType())->getElementType())
1539 return false;// Second operand of insertelement must be vector element type.
1541 if (!Index->getType()->isIntegerTy())
1542 return false; // Third operand of insertelement must be i32.
1547 //===----------------------------------------------------------------------===//
1548 // ShuffleVectorInst Implementation
1549 //===----------------------------------------------------------------------===//
1551 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1553 Instruction *InsertBefore)
1554 : Instruction(VectorType::get(cast<VectorType>(V1->getType())->getElementType(),
1555 cast<VectorType>(Mask->getType())->getNumElements()),
1557 OperandTraits<ShuffleVectorInst>::op_begin(this),
1558 OperandTraits<ShuffleVectorInst>::operands(this),
1560 assert(isValidOperands(V1, V2, Mask) &&
1561 "Invalid shuffle vector instruction operands!");
1568 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1570 BasicBlock *InsertAtEnd)
1571 : Instruction(VectorType::get(cast<VectorType>(V1->getType())->getElementType(),
1572 cast<VectorType>(Mask->getType())->getNumElements()),
1574 OperandTraits<ShuffleVectorInst>::op_begin(this),
1575 OperandTraits<ShuffleVectorInst>::operands(this),
1577 assert(isValidOperands(V1, V2, Mask) &&
1578 "Invalid shuffle vector instruction operands!");
1586 bool ShuffleVectorInst::isValidOperands(const Value *V1, const Value *V2,
1587 const Value *Mask) {
1588 // V1 and V2 must be vectors of the same type.
1589 if (!V1->getType()->isVectorTy() || V1->getType() != V2->getType())
1592 // Mask must be vector of i32.
1593 VectorType *MaskTy = dyn_cast<VectorType>(Mask->getType());
1594 if (!MaskTy || !MaskTy->getElementType()->isIntegerTy(32))
1597 // Check to see if Mask is valid.
1598 if (isa<UndefValue>(Mask) || isa<ConstantAggregateZero>(Mask))
1601 if (const ConstantVector *MV = dyn_cast<ConstantVector>(Mask)) {
1602 unsigned V1Size = cast<VectorType>(V1->getType())->getNumElements();
1603 for (Value *Op : MV->operands()) {
1604 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
1605 if (CI->uge(V1Size*2))
1607 } else if (!isa<UndefValue>(Op)) {
1614 if (const ConstantDataSequential *CDS =
1615 dyn_cast<ConstantDataSequential>(Mask)) {
1616 unsigned V1Size = cast<VectorType>(V1->getType())->getNumElements();
1617 for (unsigned i = 0, e = MaskTy->getNumElements(); i != e; ++i)
1618 if (CDS->getElementAsInteger(i) >= V1Size*2)
1623 // The bitcode reader can create a place holder for a forward reference
1624 // used as the shuffle mask. When this occurs, the shuffle mask will
1625 // fall into this case and fail. To avoid this error, do this bit of
1626 // ugliness to allow such a mask pass.
1627 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(Mask))
1628 if (CE->getOpcode() == Instruction::UserOp1)
1634 /// getMaskValue - Return the index from the shuffle mask for the specified
1635 /// output result. This is either -1 if the element is undef or a number less
1636 /// than 2*numelements.
1637 int ShuffleVectorInst::getMaskValue(Constant *Mask, unsigned i) {
1638 assert(i < Mask->getType()->getVectorNumElements() && "Index out of range");
1639 if (ConstantDataSequential *CDS =dyn_cast<ConstantDataSequential>(Mask))
1640 return CDS->getElementAsInteger(i);
1641 Constant *C = Mask->getAggregateElement(i);
1642 if (isa<UndefValue>(C))
1644 return cast<ConstantInt>(C)->getZExtValue();
1647 /// getShuffleMask - Return the full mask for this instruction, where each
1648 /// element is the element number and undef's are returned as -1.
1649 void ShuffleVectorInst::getShuffleMask(Constant *Mask,
1650 SmallVectorImpl<int> &Result) {
1651 unsigned NumElts = Mask->getType()->getVectorNumElements();
1653 if (ConstantDataSequential *CDS=dyn_cast<ConstantDataSequential>(Mask)) {
1654 for (unsigned i = 0; i != NumElts; ++i)
1655 Result.push_back(CDS->getElementAsInteger(i));
1658 for (unsigned i = 0; i != NumElts; ++i) {
1659 Constant *C = Mask->getAggregateElement(i);
1660 Result.push_back(isa<UndefValue>(C) ? -1 :
1661 cast<ConstantInt>(C)->getZExtValue());
1666 //===----------------------------------------------------------------------===//
1667 // InsertValueInst Class
1668 //===----------------------------------------------------------------------===//
1670 void InsertValueInst::init(Value *Agg, Value *Val, ArrayRef<unsigned> Idxs,
1671 const Twine &Name) {
1672 assert(NumOperands == 2 && "NumOperands not initialized?");
1674 // There's no fundamental reason why we require at least one index
1675 // (other than weirdness with &*IdxBegin being invalid; see
1676 // getelementptr's init routine for example). But there's no
1677 // present need to support it.
1678 assert(Idxs.size() > 0 && "InsertValueInst must have at least one index");
1680 assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs) ==
1681 Val->getType() && "Inserted value must match indexed type!");
1685 Indices.append(Idxs.begin(), Idxs.end());
1689 InsertValueInst::InsertValueInst(const InsertValueInst &IVI)
1690 : Instruction(IVI.getType(), InsertValue,
1691 OperandTraits<InsertValueInst>::op_begin(this), 2),
1692 Indices(IVI.Indices) {
1693 Op<0>() = IVI.getOperand(0);
1694 Op<1>() = IVI.getOperand(1);
1695 SubclassOptionalData = IVI.SubclassOptionalData;
1698 //===----------------------------------------------------------------------===//
1699 // ExtractValueInst Class
1700 //===----------------------------------------------------------------------===//
1702 void ExtractValueInst::init(ArrayRef<unsigned> Idxs, const Twine &Name) {
1703 assert(NumOperands == 1 && "NumOperands not initialized?");
1705 // There's no fundamental reason why we require at least one index.
1706 // But there's no present need to support it.
1707 assert(Idxs.size() > 0 && "ExtractValueInst must have at least one index");
1709 Indices.append(Idxs.begin(), Idxs.end());
1713 ExtractValueInst::ExtractValueInst(const ExtractValueInst &EVI)
1714 : UnaryInstruction(EVI.getType(), ExtractValue, EVI.getOperand(0)),
1715 Indices(EVI.Indices) {
1716 SubclassOptionalData = EVI.SubclassOptionalData;
1719 // getIndexedType - Returns the type of the element that would be extracted
1720 // with an extractvalue instruction with the specified parameters.
1722 // A null type is returned if the indices are invalid for the specified
1725 Type *ExtractValueInst::getIndexedType(Type *Agg,
1726 ArrayRef<unsigned> Idxs) {
1727 for (unsigned Index : Idxs) {
1728 // We can't use CompositeType::indexValid(Index) here.
1729 // indexValid() always returns true for arrays because getelementptr allows
1730 // out-of-bounds indices. Since we don't allow those for extractvalue and
1731 // insertvalue we need to check array indexing manually.
1732 // Since the only other types we can index into are struct types it's just
1733 // as easy to check those manually as well.
1734 if (ArrayType *AT = dyn_cast<ArrayType>(Agg)) {
1735 if (Index >= AT->getNumElements())
1737 } else if (StructType *ST = dyn_cast<StructType>(Agg)) {
1738 if (Index >= ST->getNumElements())
1741 // Not a valid type to index into.
1745 Agg = cast<CompositeType>(Agg)->getTypeAtIndex(Index);
1747 return const_cast<Type*>(Agg);
1750 //===----------------------------------------------------------------------===//
1751 // BinaryOperator Class
1752 //===----------------------------------------------------------------------===//
1754 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
1755 Type *Ty, const Twine &Name,
1756 Instruction *InsertBefore)
1757 : Instruction(Ty, iType,
1758 OperandTraits<BinaryOperator>::op_begin(this),
1759 OperandTraits<BinaryOperator>::operands(this),
1767 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
1768 Type *Ty, const Twine &Name,
1769 BasicBlock *InsertAtEnd)
1770 : Instruction(Ty, iType,
1771 OperandTraits<BinaryOperator>::op_begin(this),
1772 OperandTraits<BinaryOperator>::operands(this),
1781 void BinaryOperator::init(BinaryOps iType) {
1782 Value *LHS = getOperand(0), *RHS = getOperand(1);
1783 (void)LHS; (void)RHS; // Silence warnings.
1784 assert(LHS->getType() == RHS->getType() &&
1785 "Binary operator operand types must match!");
1790 assert(getType() == LHS->getType() &&
1791 "Arithmetic operation should return same type as operands!");
1792 assert(getType()->isIntOrIntVectorTy() &&
1793 "Tried to create an integer operation on a non-integer type!");
1795 case FAdd: case FSub:
1797 assert(getType() == LHS->getType() &&
1798 "Arithmetic operation should return same type as operands!");
1799 assert(getType()->isFPOrFPVectorTy() &&
1800 "Tried to create a floating-point operation on a "
1801 "non-floating-point type!");
1805 assert(getType() == LHS->getType() &&
1806 "Arithmetic operation should return same type as operands!");
1807 assert((getType()->isIntegerTy() || (getType()->isVectorTy() &&
1808 cast<VectorType>(getType())->getElementType()->isIntegerTy())) &&
1809 "Incorrect operand type (not integer) for S/UDIV");
1812 assert(getType() == LHS->getType() &&
1813 "Arithmetic operation should return same type as operands!");
1814 assert(getType()->isFPOrFPVectorTy() &&
1815 "Incorrect operand type (not floating point) for FDIV");
1819 assert(getType() == LHS->getType() &&
1820 "Arithmetic operation should return same type as operands!");
1821 assert((getType()->isIntegerTy() || (getType()->isVectorTy() &&
1822 cast<VectorType>(getType())->getElementType()->isIntegerTy())) &&
1823 "Incorrect operand type (not integer) for S/UREM");
1826 assert(getType() == LHS->getType() &&
1827 "Arithmetic operation should return same type as operands!");
1828 assert(getType()->isFPOrFPVectorTy() &&
1829 "Incorrect operand type (not floating point) for FREM");
1834 assert(getType() == LHS->getType() &&
1835 "Shift operation should return same type as operands!");
1836 assert((getType()->isIntegerTy() ||
1837 (getType()->isVectorTy() &&
1838 cast<VectorType>(getType())->getElementType()->isIntegerTy())) &&
1839 "Tried to create a shift operation on a non-integral type!");
1843 assert(getType() == LHS->getType() &&
1844 "Logical operation should return same type as operands!");
1845 assert((getType()->isIntegerTy() ||
1846 (getType()->isVectorTy() &&
1847 cast<VectorType>(getType())->getElementType()->isIntegerTy())) &&
1848 "Tried to create a logical operation on a non-integral type!");
1856 BinaryOperator *BinaryOperator::Create(BinaryOps Op, Value *S1, Value *S2,
1858 Instruction *InsertBefore) {
1859 assert(S1->getType() == S2->getType() &&
1860 "Cannot create binary operator with two operands of differing type!");
1861 return new BinaryOperator(Op, S1, S2, S1->getType(), Name, InsertBefore);
1864 BinaryOperator *BinaryOperator::Create(BinaryOps Op, Value *S1, Value *S2,
1866 BasicBlock *InsertAtEnd) {
1867 BinaryOperator *Res = Create(Op, S1, S2, Name);
1868 InsertAtEnd->getInstList().push_back(Res);
1872 BinaryOperator *BinaryOperator::CreateNeg(Value *Op, const Twine &Name,
1873 Instruction *InsertBefore) {
1874 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1875 return new BinaryOperator(Instruction::Sub,
1877 Op->getType(), Name, InsertBefore);
1880 BinaryOperator *BinaryOperator::CreateNeg(Value *Op, const Twine &Name,
1881 BasicBlock *InsertAtEnd) {
1882 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1883 return new BinaryOperator(Instruction::Sub,
1885 Op->getType(), Name, InsertAtEnd);
1888 BinaryOperator *BinaryOperator::CreateNSWNeg(Value *Op, const Twine &Name,
1889 Instruction *InsertBefore) {
1890 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1891 return BinaryOperator::CreateNSWSub(zero, Op, Name, InsertBefore);
1894 BinaryOperator *BinaryOperator::CreateNSWNeg(Value *Op, const Twine &Name,
1895 BasicBlock *InsertAtEnd) {
1896 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1897 return BinaryOperator::CreateNSWSub(zero, Op, Name, InsertAtEnd);
1900 BinaryOperator *BinaryOperator::CreateNUWNeg(Value *Op, const Twine &Name,
1901 Instruction *InsertBefore) {
1902 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1903 return BinaryOperator::CreateNUWSub(zero, Op, Name, InsertBefore);
1906 BinaryOperator *BinaryOperator::CreateNUWNeg(Value *Op, const Twine &Name,
1907 BasicBlock *InsertAtEnd) {
1908 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1909 return BinaryOperator::CreateNUWSub(zero, Op, Name, InsertAtEnd);
1912 BinaryOperator *BinaryOperator::CreateFNeg(Value *Op, const Twine &Name,
1913 Instruction *InsertBefore) {
1914 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1915 return new BinaryOperator(Instruction::FSub, zero, Op,
1916 Op->getType(), Name, InsertBefore);
1919 BinaryOperator *BinaryOperator::CreateFNeg(Value *Op, const Twine &Name,
1920 BasicBlock *InsertAtEnd) {
1921 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
1922 return new BinaryOperator(Instruction::FSub, zero, Op,
1923 Op->getType(), Name, InsertAtEnd);
1926 BinaryOperator *BinaryOperator::CreateNot(Value *Op, const Twine &Name,
1927 Instruction *InsertBefore) {
1928 Constant *C = Constant::getAllOnesValue(Op->getType());
1929 return new BinaryOperator(Instruction::Xor, Op, C,
1930 Op->getType(), Name, InsertBefore);
1933 BinaryOperator *BinaryOperator::CreateNot(Value *Op, const Twine &Name,
1934 BasicBlock *InsertAtEnd) {
1935 Constant *AllOnes = Constant::getAllOnesValue(Op->getType());
1936 return new BinaryOperator(Instruction::Xor, Op, AllOnes,
1937 Op->getType(), Name, InsertAtEnd);
1941 // isConstantAllOnes - Helper function for several functions below
1942 static inline bool isConstantAllOnes(const Value *V) {
1943 if (const Constant *C = dyn_cast<Constant>(V))
1944 return C->isAllOnesValue();
1948 bool BinaryOperator::isNeg(const Value *V) {
1949 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1950 if (Bop->getOpcode() == Instruction::Sub)
1951 if (Constant* C = dyn_cast<Constant>(Bop->getOperand(0)))
1952 return C->isNegativeZeroValue();
1956 bool BinaryOperator::isFNeg(const Value *V, bool IgnoreZeroSign) {
1957 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1958 if (Bop->getOpcode() == Instruction::FSub)
1959 if (Constant* C = dyn_cast<Constant>(Bop->getOperand(0))) {
1960 if (!IgnoreZeroSign)
1961 IgnoreZeroSign = cast<Instruction>(V)->hasNoSignedZeros();
1962 return !IgnoreZeroSign ? C->isNegativeZeroValue() : C->isZeroValue();
1967 bool BinaryOperator::isNot(const Value *V) {
1968 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
1969 return (Bop->getOpcode() == Instruction::Xor &&
1970 (isConstantAllOnes(Bop->getOperand(1)) ||
1971 isConstantAllOnes(Bop->getOperand(0))));
1975 Value *BinaryOperator::getNegArgument(Value *BinOp) {
1976 return cast<BinaryOperator>(BinOp)->getOperand(1);
1979 const Value *BinaryOperator::getNegArgument(const Value *BinOp) {
1980 return getNegArgument(const_cast<Value*>(BinOp));
1983 Value *BinaryOperator::getFNegArgument(Value *BinOp) {
1984 return cast<BinaryOperator>(BinOp)->getOperand(1);
1987 const Value *BinaryOperator::getFNegArgument(const Value *BinOp) {
1988 return getFNegArgument(const_cast<Value*>(BinOp));
1991 Value *BinaryOperator::getNotArgument(Value *BinOp) {
1992 assert(isNot(BinOp) && "getNotArgument on non-'not' instruction!");
1993 BinaryOperator *BO = cast<BinaryOperator>(BinOp);
1994 Value *Op0 = BO->getOperand(0);
1995 Value *Op1 = BO->getOperand(1);
1996 if (isConstantAllOnes(Op0)) return Op1;
1998 assert(isConstantAllOnes(Op1));
2002 const Value *BinaryOperator::getNotArgument(const Value *BinOp) {
2003 return getNotArgument(const_cast<Value*>(BinOp));
2007 // swapOperands - Exchange the two operands to this instruction. This
2008 // instruction is safe to use on any binary instruction and does not
2009 // modify the semantics of the instruction. If the instruction is
2010 // order dependent (SetLT f.e.) the opcode is changed.
2012 bool BinaryOperator::swapOperands() {
2013 if (!isCommutative())
2014 return true; // Can't commute operands
2015 Op<0>().swap(Op<1>());
2019 void BinaryOperator::setHasNoUnsignedWrap(bool b) {
2020 cast<OverflowingBinaryOperator>(this)->setHasNoUnsignedWrap(b);
2023 void BinaryOperator::setHasNoSignedWrap(bool b) {
2024 cast<OverflowingBinaryOperator>(this)->setHasNoSignedWrap(b);
2027 void BinaryOperator::setIsExact(bool b) {
2028 cast<PossiblyExactOperator>(this)->setIsExact(b);
2031 bool BinaryOperator::hasNoUnsignedWrap() const {
2032 return cast<OverflowingBinaryOperator>(this)->hasNoUnsignedWrap();
2035 bool BinaryOperator::hasNoSignedWrap() const {
2036 return cast<OverflowingBinaryOperator>(this)->hasNoSignedWrap();
2039 bool BinaryOperator::isExact() const {
2040 return cast<PossiblyExactOperator>(this)->isExact();
2043 void BinaryOperator::copyIRFlags(const Value *V) {
2044 // Copy the wrapping flags.
2045 if (auto *OB = dyn_cast<OverflowingBinaryOperator>(V)) {
2046 setHasNoSignedWrap(OB->hasNoSignedWrap());
2047 setHasNoUnsignedWrap(OB->hasNoUnsignedWrap());
2050 // Copy the exact flag.
2051 if (auto *PE = dyn_cast<PossiblyExactOperator>(V))
2052 setIsExact(PE->isExact());
2054 // Copy the fast-math flags.
2055 if (auto *FP = dyn_cast<FPMathOperator>(V))
2056 copyFastMathFlags(FP->getFastMathFlags());
2059 void BinaryOperator::andIRFlags(const Value *V) {
2060 if (auto *OB = dyn_cast<OverflowingBinaryOperator>(V)) {
2061 setHasNoSignedWrap(hasNoSignedWrap() & OB->hasNoSignedWrap());
2062 setHasNoUnsignedWrap(hasNoUnsignedWrap() & OB->hasNoUnsignedWrap());
2065 if (auto *PE = dyn_cast<PossiblyExactOperator>(V))
2066 setIsExact(isExact() & PE->isExact());
2068 if (auto *FP = dyn_cast<FPMathOperator>(V)) {
2069 FastMathFlags FM = getFastMathFlags();
2070 FM &= FP->getFastMathFlags();
2071 copyFastMathFlags(FM);
2076 //===----------------------------------------------------------------------===//
2077 // FPMathOperator Class
2078 //===----------------------------------------------------------------------===//
2080 /// getFPAccuracy - Get the maximum error permitted by this operation in ULPs.
2081 /// An accuracy of 0.0 means that the operation should be performed with the
2082 /// default precision.
2083 float FPMathOperator::getFPAccuracy() const {
2085 cast<Instruction>(this)->getMetadata(LLVMContext::MD_fpmath);
2088 ConstantFP *Accuracy = mdconst::extract<ConstantFP>(MD->getOperand(0));
2089 return Accuracy->getValueAPF().convertToFloat();
2093 //===----------------------------------------------------------------------===//
2095 //===----------------------------------------------------------------------===//
2097 void CastInst::anchor() {}
2099 // Just determine if this cast only deals with integral->integral conversion.
2100 bool CastInst::isIntegerCast() const {
2101 switch (getOpcode()) {
2102 default: return false;
2103 case Instruction::ZExt:
2104 case Instruction::SExt:
2105 case Instruction::Trunc:
2107 case Instruction::BitCast:
2108 return getOperand(0)->getType()->isIntegerTy() &&
2109 getType()->isIntegerTy();
2113 bool CastInst::isLosslessCast() const {
2114 // Only BitCast can be lossless, exit fast if we're not BitCast
2115 if (getOpcode() != Instruction::BitCast)
2118 // Identity cast is always lossless
2119 Type* SrcTy = getOperand(0)->getType();
2120 Type* DstTy = getType();
2124 // Pointer to pointer is always lossless.
2125 if (SrcTy->isPointerTy())
2126 return DstTy->isPointerTy();
2127 return false; // Other types have no identity values
2130 /// This function determines if the CastInst does not require any bits to be
2131 /// changed in order to effect the cast. Essentially, it identifies cases where
2132 /// no code gen is necessary for the cast, hence the name no-op cast. For
2133 /// example, the following are all no-op casts:
2134 /// # bitcast i32* %x to i8*
2135 /// # bitcast <2 x i32> %x to <4 x i16>
2136 /// # ptrtoint i32* %x to i32 ; on 32-bit plaforms only
2137 /// @brief Determine if the described cast is a no-op.
2138 bool CastInst::isNoopCast(Instruction::CastOps Opcode,
2143 default: llvm_unreachable("Invalid CastOp");
2144 case Instruction::Trunc:
2145 case Instruction::ZExt:
2146 case Instruction::SExt:
2147 case Instruction::FPTrunc:
2148 case Instruction::FPExt:
2149 case Instruction::UIToFP:
2150 case Instruction::SIToFP:
2151 case Instruction::FPToUI:
2152 case Instruction::FPToSI:
2153 case Instruction::AddrSpaceCast:
2154 // TODO: Target informations may give a more accurate answer here.
2156 case Instruction::BitCast:
2157 return true; // BitCast never modifies bits.
2158 case Instruction::PtrToInt:
2159 return IntPtrTy->getScalarSizeInBits() ==
2160 DestTy->getScalarSizeInBits();
2161 case Instruction::IntToPtr:
2162 return IntPtrTy->getScalarSizeInBits() ==
2163 SrcTy->getScalarSizeInBits();
2167 /// @brief Determine if a cast is a no-op.
2168 bool CastInst::isNoopCast(Type *IntPtrTy) const {
2169 return isNoopCast(getOpcode(), getOperand(0)->getType(), getType(), IntPtrTy);
2172 bool CastInst::isNoopCast(const DataLayout *DL) const {
2174 // Assume maximum pointer size.
2175 return isNoopCast(Type::getInt64Ty(getContext()));
2178 Type *PtrOpTy = nullptr;
2179 if (getOpcode() == Instruction::PtrToInt)
2180 PtrOpTy = getOperand(0)->getType();
2181 else if (getOpcode() == Instruction::IntToPtr)
2182 PtrOpTy = getType();
2184 Type *IntPtrTy = PtrOpTy
2185 ? DL->getIntPtrType(PtrOpTy)
2186 : DL->getIntPtrType(getContext(), 0);
2188 return isNoopCast(getOpcode(), getOperand(0)->getType(), getType(), IntPtrTy);
2191 /// This function determines if a pair of casts can be eliminated and what
2192 /// opcode should be used in the elimination. This assumes that there are two
2193 /// instructions like this:
2194 /// * %F = firstOpcode SrcTy %x to MidTy
2195 /// * %S = secondOpcode MidTy %F to DstTy
2196 /// The function returns a resultOpcode so these two casts can be replaced with:
2197 /// * %Replacement = resultOpcode %SrcTy %x to DstTy
2198 /// If no such cast is permited, the function returns 0.
2199 unsigned CastInst::isEliminableCastPair(
2200 Instruction::CastOps firstOp, Instruction::CastOps secondOp,
2201 Type *SrcTy, Type *MidTy, Type *DstTy, Type *SrcIntPtrTy, Type *MidIntPtrTy,
2202 Type *DstIntPtrTy) {
2203 // Define the 144 possibilities for these two cast instructions. The values
2204 // in this matrix determine what to do in a given situation and select the
2205 // case in the switch below. The rows correspond to firstOp, the columns
2206 // correspond to secondOp. In looking at the table below, keep in mind
2207 // the following cast properties:
2209 // Size Compare Source Destination
2210 // Operator Src ? Size Type Sign Type Sign
2211 // -------- ------------ ------------------- ---------------------
2212 // TRUNC > Integer Any Integral Any
2213 // ZEXT < Integral Unsigned Integer Any
2214 // SEXT < Integral Signed Integer Any
2215 // FPTOUI n/a FloatPt n/a Integral Unsigned
2216 // FPTOSI n/a FloatPt n/a Integral Signed
2217 // UITOFP n/a Integral Unsigned FloatPt n/a
2218 // SITOFP n/a Integral Signed FloatPt n/a
2219 // FPTRUNC > FloatPt n/a FloatPt n/a
2220 // FPEXT < FloatPt n/a FloatPt n/a
2221 // PTRTOINT n/a Pointer n/a Integral Unsigned
2222 // INTTOPTR n/a Integral Unsigned Pointer n/a
2223 // BITCAST = FirstClass n/a FirstClass n/a
2224 // ADDRSPCST n/a Pointer n/a Pointer n/a
2226 // NOTE: some transforms are safe, but we consider them to be non-profitable.
2227 // For example, we could merge "fptoui double to i32" + "zext i32 to i64",
2228 // into "fptoui double to i64", but this loses information about the range
2229 // of the produced value (we no longer know the top-part is all zeros).
2230 // Further this conversion is often much more expensive for typical hardware,
2231 // and causes issues when building libgcc. We disallow fptosi+sext for the
2233 const unsigned numCastOps =
2234 Instruction::CastOpsEnd - Instruction::CastOpsBegin;
2235 static const uint8_t CastResults[numCastOps][numCastOps] = {
2236 // T F F U S F F P I B A -+
2237 // R Z S P P I I T P 2 N T S |
2238 // U E E 2 2 2 2 R E I T C C +- secondOp
2239 // N X X U S F F N X N 2 V V |
2240 // C T T I I P P C T T P T T -+
2241 { 1, 0, 0,99,99, 0, 0,99,99,99, 0, 3, 0}, // Trunc -+
2242 { 8, 1, 9,99,99, 2, 0,99,99,99, 2, 3, 0}, // ZExt |
2243 { 8, 0, 1,99,99, 0, 2,99,99,99, 0, 3, 0}, // SExt |
2244 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3, 0}, // FPToUI |
2245 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3, 0}, // FPToSI |
2246 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4, 0}, // UIToFP +- firstOp
2247 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4, 0}, // SIToFP |
2248 { 99,99,99, 0, 0,99,99, 1, 0,99,99, 4, 0}, // FPTrunc |
2249 { 99,99,99, 2, 2,99,99,10, 2,99,99, 4, 0}, // FPExt |
2250 { 1, 0, 0,99,99, 0, 0,99,99,99, 7, 3, 0}, // PtrToInt |
2251 { 99,99,99,99,99,99,99,99,99,11,99,15, 0}, // IntToPtr |
2252 { 5, 5, 5, 6, 6, 5, 5, 6, 6,16, 5, 1,14}, // BitCast |
2253 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,13,12}, // AddrSpaceCast -+
2256 // If either of the casts are a bitcast from scalar to vector, disallow the
2257 // merging. However, bitcast of A->B->A are allowed.
2258 bool isFirstBitcast = (firstOp == Instruction::BitCast);
2259 bool isSecondBitcast = (secondOp == Instruction::BitCast);
2260 bool chainedBitcast = (SrcTy == DstTy && isFirstBitcast && isSecondBitcast);
2262 // Check if any of the bitcasts convert scalars<->vectors.
2263 if ((isFirstBitcast && isa<VectorType>(SrcTy) != isa<VectorType>(MidTy)) ||
2264 (isSecondBitcast && isa<VectorType>(MidTy) != isa<VectorType>(DstTy)))
2265 // Unless we are bitcasing to the original type, disallow optimizations.
2266 if (!chainedBitcast) return 0;
2268 int ElimCase = CastResults[firstOp-Instruction::CastOpsBegin]
2269 [secondOp-Instruction::CastOpsBegin];
2272 // Categorically disallowed.
2275 // Allowed, use first cast's opcode.
2278 // Allowed, use second cast's opcode.
2281 // No-op cast in second op implies firstOp as long as the DestTy
2282 // is integer and we are not converting between a vector and a
2284 if (!SrcTy->isVectorTy() && DstTy->isIntegerTy())
2288 // No-op cast in second op implies firstOp as long as the DestTy
2289 // is floating point.
2290 if (DstTy->isFloatingPointTy())
2294 // No-op cast in first op implies secondOp as long as the SrcTy
2296 if (SrcTy->isIntegerTy())
2300 // No-op cast in first op implies secondOp as long as the SrcTy
2301 // is a floating point.
2302 if (SrcTy->isFloatingPointTy())
2306 // Cannot simplify if address spaces are different!
2307 if (SrcTy->getPointerAddressSpace() != DstTy->getPointerAddressSpace())
2310 unsigned MidSize = MidTy->getScalarSizeInBits();
2311 // We can still fold this without knowing the actual sizes as long we
2312 // know that the intermediate pointer is the largest possible
2314 // FIXME: Is this always true?
2316 return Instruction::BitCast;
2318 // ptrtoint, inttoptr -> bitcast (ptr -> ptr) if int size is >= ptr size.
2319 if (!SrcIntPtrTy || DstIntPtrTy != SrcIntPtrTy)
2321 unsigned PtrSize = SrcIntPtrTy->getScalarSizeInBits();
2322 if (MidSize >= PtrSize)
2323 return Instruction::BitCast;
2327 // ext, trunc -> bitcast, if the SrcTy and DstTy are same size
2328 // ext, trunc -> ext, if sizeof(SrcTy) < sizeof(DstTy)
2329 // ext, trunc -> trunc, if sizeof(SrcTy) > sizeof(DstTy)
2330 unsigned SrcSize = SrcTy->getScalarSizeInBits();
2331 unsigned DstSize = DstTy->getScalarSizeInBits();
2332 if (SrcSize == DstSize)
2333 return Instruction::BitCast;
2334 else if (SrcSize < DstSize)
2339 // zext, sext -> zext, because sext can't sign extend after zext
2340 return Instruction::ZExt;
2342 // fpext followed by ftrunc is allowed if the bit size returned to is
2343 // the same as the original, in which case its just a bitcast
2345 return Instruction::BitCast;
2346 return 0; // If the types are not the same we can't eliminate it.
2348 // inttoptr, ptrtoint -> bitcast if SrcSize<=PtrSize and SrcSize==DstSize
2351 unsigned PtrSize = MidIntPtrTy->getScalarSizeInBits();
2352 unsigned SrcSize = SrcTy->getScalarSizeInBits();
2353 unsigned DstSize = DstTy->getScalarSizeInBits();
2354 if (SrcSize <= PtrSize && SrcSize == DstSize)
2355 return Instruction::BitCast;
2359 // addrspacecast, addrspacecast -> bitcast, if SrcAS == DstAS
2360 // addrspacecast, addrspacecast -> addrspacecast, if SrcAS != DstAS
2361 if (SrcTy->getPointerAddressSpace() != DstTy->getPointerAddressSpace())
2362 return Instruction::AddrSpaceCast;
2363 return Instruction::BitCast;
2366 // FIXME: this state can be merged with (1), but the following assert
2367 // is useful to check the correcteness of the sequence due to semantic
2368 // change of bitcast.
2370 SrcTy->isPtrOrPtrVectorTy() &&
2371 MidTy->isPtrOrPtrVectorTy() &&
2372 DstTy->isPtrOrPtrVectorTy() &&
2373 SrcTy->getPointerAddressSpace() != MidTy->getPointerAddressSpace() &&
2374 MidTy->getPointerAddressSpace() == DstTy->getPointerAddressSpace() &&
2375 "Illegal addrspacecast, bitcast sequence!");
2376 // Allowed, use first cast's opcode
2379 // bitcast, addrspacecast -> addrspacecast if the element type of
2380 // bitcast's source is the same as that of addrspacecast's destination.
2381 if (SrcTy->getPointerElementType() == DstTy->getPointerElementType())
2382 return Instruction::AddrSpaceCast;
2386 // FIXME: this state can be merged with (1), but the following assert
2387 // is useful to check the correcteness of the sequence due to semantic
2388 // change of bitcast.
2390 SrcTy->isIntOrIntVectorTy() &&
2391 MidTy->isPtrOrPtrVectorTy() &&
2392 DstTy->isPtrOrPtrVectorTy() &&
2393 MidTy->getPointerAddressSpace() == DstTy->getPointerAddressSpace() &&
2394 "Illegal inttoptr, bitcast sequence!");
2395 // Allowed, use first cast's opcode
2398 // FIXME: this state can be merged with (2), but the following assert
2399 // is useful to check the correcteness of the sequence due to semantic
2400 // change of bitcast.
2402 SrcTy->isPtrOrPtrVectorTy() &&
2403 MidTy->isPtrOrPtrVectorTy() &&
2404 DstTy->isIntOrIntVectorTy() &&
2405 SrcTy->getPointerAddressSpace() == MidTy->getPointerAddressSpace() &&
2406 "Illegal bitcast, ptrtoint sequence!");
2407 // Allowed, use second cast's opcode
2410 // Cast combination can't happen (error in input). This is for all cases
2411 // where the MidTy is not the same for the two cast instructions.
2412 llvm_unreachable("Invalid Cast Combination");
2414 llvm_unreachable("Error in CastResults table!!!");
2418 CastInst *CastInst::Create(Instruction::CastOps op, Value *S, Type *Ty,
2419 const Twine &Name, Instruction *InsertBefore) {
2420 assert(castIsValid(op, S, Ty) && "Invalid cast!");
2421 // Construct and return the appropriate CastInst subclass
2423 case Trunc: return new TruncInst (S, Ty, Name, InsertBefore);
2424 case ZExt: return new ZExtInst (S, Ty, Name, InsertBefore);
2425 case SExt: return new SExtInst (S, Ty, Name, InsertBefore);
2426 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertBefore);
2427 case FPExt: return new FPExtInst (S, Ty, Name, InsertBefore);
2428 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertBefore);
2429 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertBefore);
2430 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertBefore);
2431 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertBefore);
2432 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertBefore);
2433 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertBefore);
2434 case BitCast: return new BitCastInst (S, Ty, Name, InsertBefore);
2435 case AddrSpaceCast: return new AddrSpaceCastInst (S, Ty, Name, InsertBefore);
2436 default: llvm_unreachable("Invalid opcode provided");
2440 CastInst *CastInst::Create(Instruction::CastOps op, Value *S, Type *Ty,
2441 const Twine &Name, BasicBlock *InsertAtEnd) {
2442 assert(castIsValid(op, S, Ty) && "Invalid cast!");
2443 // Construct and return the appropriate CastInst subclass
2445 case Trunc: return new TruncInst (S, Ty, Name, InsertAtEnd);
2446 case ZExt: return new ZExtInst (S, Ty, Name, InsertAtEnd);
2447 case SExt: return new SExtInst (S, Ty, Name, InsertAtEnd);
2448 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertAtEnd);
2449 case FPExt: return new FPExtInst (S, Ty, Name, InsertAtEnd);
2450 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertAtEnd);
2451 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertAtEnd);
2452 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertAtEnd);
2453 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertAtEnd);
2454 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertAtEnd);
2455 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertAtEnd);
2456 case BitCast: return new BitCastInst (S, Ty, Name, InsertAtEnd);
2457 case AddrSpaceCast: return new AddrSpaceCastInst (S, Ty, Name, InsertAtEnd);
2458 default: llvm_unreachable("Invalid opcode provided");
2462 CastInst *CastInst::CreateZExtOrBitCast(Value *S, Type *Ty,
2464 Instruction *InsertBefore) {
2465 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2466 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2467 return Create(Instruction::ZExt, S, Ty, Name, InsertBefore);
2470 CastInst *CastInst::CreateZExtOrBitCast(Value *S, Type *Ty,
2472 BasicBlock *InsertAtEnd) {
2473 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2474 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2475 return Create(Instruction::ZExt, S, Ty, Name, InsertAtEnd);
2478 CastInst *CastInst::CreateSExtOrBitCast(Value *S, Type *Ty,
2480 Instruction *InsertBefore) {
2481 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2482 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2483 return Create(Instruction::SExt, S, Ty, Name, InsertBefore);
2486 CastInst *CastInst::CreateSExtOrBitCast(Value *S, Type *Ty,
2488 BasicBlock *InsertAtEnd) {
2489 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2490 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2491 return Create(Instruction::SExt, S, Ty, Name, InsertAtEnd);
2494 CastInst *CastInst::CreateTruncOrBitCast(Value *S, Type *Ty,
2496 Instruction *InsertBefore) {
2497 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2498 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2499 return Create(Instruction::Trunc, S, Ty, Name, InsertBefore);
2502 CastInst *CastInst::CreateTruncOrBitCast(Value *S, Type *Ty,
2504 BasicBlock *InsertAtEnd) {
2505 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2506 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2507 return Create(Instruction::Trunc, S, Ty, Name, InsertAtEnd);
2510 CastInst *CastInst::CreatePointerCast(Value *S, Type *Ty,
2512 BasicBlock *InsertAtEnd) {
2513 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
2514 assert((Ty->isIntOrIntVectorTy() || Ty->isPtrOrPtrVectorTy()) &&
2516 assert(Ty->isVectorTy() == S->getType()->isVectorTy() && "Invalid cast");
2517 assert((!Ty->isVectorTy() ||
2518 Ty->getVectorNumElements() == S->getType()->getVectorNumElements()) &&
2521 if (Ty->isIntOrIntVectorTy())
2522 return Create(Instruction::PtrToInt, S, Ty, Name, InsertAtEnd);
2524 return CreatePointerBitCastOrAddrSpaceCast(S, Ty, Name, InsertAtEnd);
2527 /// @brief Create a BitCast or a PtrToInt cast instruction
2528 CastInst *CastInst::CreatePointerCast(Value *S, Type *Ty,
2530 Instruction *InsertBefore) {
2531 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
2532 assert((Ty->isIntOrIntVectorTy() || Ty->isPtrOrPtrVectorTy()) &&
2534 assert(Ty->isVectorTy() == S->getType()->isVectorTy() && "Invalid cast");
2535 assert((!Ty->isVectorTy() ||
2536 Ty->getVectorNumElements() == S->getType()->getVectorNumElements()) &&
2539 if (Ty->isIntOrIntVectorTy())
2540 return Create(Instruction::PtrToInt, S, Ty, Name, InsertBefore);
2542 return CreatePointerBitCastOrAddrSpaceCast(S, Ty, Name, InsertBefore);
2545 CastInst *CastInst::CreatePointerBitCastOrAddrSpaceCast(
2548 BasicBlock *InsertAtEnd) {
2549 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
2550 assert(Ty->isPtrOrPtrVectorTy() && "Invalid cast");
2552 if (S->getType()->getPointerAddressSpace() != Ty->getPointerAddressSpace())
2553 return Create(Instruction::AddrSpaceCast, S, Ty, Name, InsertAtEnd);
2555 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2558 CastInst *CastInst::CreatePointerBitCastOrAddrSpaceCast(
2561 Instruction *InsertBefore) {
2562 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
2563 assert(Ty->isPtrOrPtrVectorTy() && "Invalid cast");
2565 if (S->getType()->getPointerAddressSpace() != Ty->getPointerAddressSpace())
2566 return Create(Instruction::AddrSpaceCast, S, Ty, Name, InsertBefore);
2568 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2571 CastInst *CastInst::CreateBitOrPointerCast(Value *S, Type *Ty,
2573 Instruction *InsertBefore) {
2574 if (S->getType()->isPointerTy() && Ty->isIntegerTy())
2575 return Create(Instruction::PtrToInt, S, Ty, Name, InsertBefore);
2576 if (S->getType()->isIntegerTy() && Ty->isPointerTy())
2577 return Create(Instruction::IntToPtr, S, Ty, Name, InsertBefore);
2579 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2582 CastInst *CastInst::CreateIntegerCast(Value *C, Type *Ty,
2583 bool isSigned, const Twine &Name,
2584 Instruction *InsertBefore) {
2585 assert(C->getType()->isIntOrIntVectorTy() && Ty->isIntOrIntVectorTy() &&
2586 "Invalid integer cast");
2587 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2588 unsigned DstBits = Ty->getScalarSizeInBits();
2589 Instruction::CastOps opcode =
2590 (SrcBits == DstBits ? Instruction::BitCast :
2591 (SrcBits > DstBits ? Instruction::Trunc :
2592 (isSigned ? Instruction::SExt : Instruction::ZExt)));
2593 return Create(opcode, C, Ty, Name, InsertBefore);
2596 CastInst *CastInst::CreateIntegerCast(Value *C, Type *Ty,
2597 bool isSigned, const Twine &Name,
2598 BasicBlock *InsertAtEnd) {
2599 assert(C->getType()->isIntOrIntVectorTy() && Ty->isIntOrIntVectorTy() &&
2601 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2602 unsigned DstBits = Ty->getScalarSizeInBits();
2603 Instruction::CastOps opcode =
2604 (SrcBits == DstBits ? Instruction::BitCast :
2605 (SrcBits > DstBits ? Instruction::Trunc :
2606 (isSigned ? Instruction::SExt : Instruction::ZExt)));
2607 return Create(opcode, C, Ty, Name, InsertAtEnd);
2610 CastInst *CastInst::CreateFPCast(Value *C, Type *Ty,
2612 Instruction *InsertBefore) {
2613 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
2615 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2616 unsigned DstBits = Ty->getScalarSizeInBits();
2617 Instruction::CastOps opcode =
2618 (SrcBits == DstBits ? Instruction::BitCast :
2619 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
2620 return Create(opcode, C, Ty, Name, InsertBefore);
2623 CastInst *CastInst::CreateFPCast(Value *C, Type *Ty,
2625 BasicBlock *InsertAtEnd) {
2626 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
2628 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2629 unsigned DstBits = Ty->getScalarSizeInBits();
2630 Instruction::CastOps opcode =
2631 (SrcBits == DstBits ? Instruction::BitCast :
2632 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
2633 return Create(opcode, C, Ty, Name, InsertAtEnd);
2636 // Check whether it is valid to call getCastOpcode for these types.
2637 // This routine must be kept in sync with getCastOpcode.
2638 bool CastInst::isCastable(Type *SrcTy, Type *DestTy) {
2639 if (!SrcTy->isFirstClassType() || !DestTy->isFirstClassType())
2642 if (SrcTy == DestTy)
2645 if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy))
2646 if (VectorType *DestVecTy = dyn_cast<VectorType>(DestTy))
2647 if (SrcVecTy->getNumElements() == DestVecTy->getNumElements()) {
2648 // An element by element cast. Valid if casting the elements is valid.
2649 SrcTy = SrcVecTy->getElementType();
2650 DestTy = DestVecTy->getElementType();
2653 // Get the bit sizes, we'll need these
2654 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); // 0 for ptr
2655 unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr
2657 // Run through the possibilities ...
2658 if (DestTy->isIntegerTy()) { // Casting to integral
2659 if (SrcTy->isIntegerTy()) { // Casting from integral
2661 } else if (SrcTy->isFloatingPointTy()) { // Casting from floating pt
2663 } else if (SrcTy->isVectorTy()) { // Casting from vector
2664 return DestBits == SrcBits;
2665 } else { // Casting from something else
2666 return SrcTy->isPointerTy();
2668 } else if (DestTy->isFloatingPointTy()) { // Casting to floating pt
2669 if (SrcTy->isIntegerTy()) { // Casting from integral
2671 } else if (SrcTy->isFloatingPointTy()) { // Casting from floating pt
2673 } else if (SrcTy->isVectorTy()) { // Casting from vector
2674 return DestBits == SrcBits;
2675 } else { // Casting from something else
2678 } else if (DestTy->isVectorTy()) { // Casting to vector
2679 return DestBits == SrcBits;
2680 } else if (DestTy->isPointerTy()) { // Casting to pointer
2681 if (SrcTy->isPointerTy()) { // Casting from pointer
2683 } else if (SrcTy->isIntegerTy()) { // Casting from integral
2685 } else { // Casting from something else
2688 } else if (DestTy->isX86_MMXTy()) {
2689 if (SrcTy->isVectorTy()) {
2690 return DestBits == SrcBits; // 64-bit vector to MMX
2694 } else { // Casting to something else
2699 bool CastInst::isBitCastable(Type *SrcTy, Type *DestTy) {
2700 if (!SrcTy->isFirstClassType() || !DestTy->isFirstClassType())
2703 if (SrcTy == DestTy)
2706 if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy)) {
2707 if (VectorType *DestVecTy = dyn_cast<VectorType>(DestTy)) {
2708 if (SrcVecTy->getNumElements() == DestVecTy->getNumElements()) {
2709 // An element by element cast. Valid if casting the elements is valid.
2710 SrcTy = SrcVecTy->getElementType();
2711 DestTy = DestVecTy->getElementType();
2716 if (PointerType *DestPtrTy = dyn_cast<PointerType>(DestTy)) {
2717 if (PointerType *SrcPtrTy = dyn_cast<PointerType>(SrcTy)) {
2718 return SrcPtrTy->getAddressSpace() == DestPtrTy->getAddressSpace();
2722 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); // 0 for ptr
2723 unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr
2725 // Could still have vectors of pointers if the number of elements doesn't
2727 if (SrcBits == 0 || DestBits == 0)
2730 if (SrcBits != DestBits)
2733 if (DestTy->isX86_MMXTy() || SrcTy->isX86_MMXTy())
2739 bool CastInst::isBitOrNoopPointerCastable(Type *SrcTy, Type *DestTy,
2740 const DataLayout *DL) {
2741 if (auto *PtrTy = dyn_cast<PointerType>(SrcTy))
2742 if (auto *IntTy = dyn_cast<IntegerType>(DestTy))
2743 return DL && IntTy->getBitWidth() == DL->getPointerTypeSizeInBits(PtrTy);
2744 if (auto *PtrTy = dyn_cast<PointerType>(DestTy))
2745 if (auto *IntTy = dyn_cast<IntegerType>(SrcTy))
2746 return DL && IntTy->getBitWidth() == DL->getPointerTypeSizeInBits(PtrTy);
2748 return isBitCastable(SrcTy, DestTy);
2751 // Provide a way to get a "cast" where the cast opcode is inferred from the
2752 // types and size of the operand. This, basically, is a parallel of the
2753 // logic in the castIsValid function below. This axiom should hold:
2754 // castIsValid( getCastOpcode(Val, Ty), Val, Ty)
2755 // should not assert in castIsValid. In other words, this produces a "correct"
2756 // casting opcode for the arguments passed to it.
2757 // This routine must be kept in sync with isCastable.
2758 Instruction::CastOps
2759 CastInst::getCastOpcode(
2760 const Value *Src, bool SrcIsSigned, Type *DestTy, bool DestIsSigned) {
2761 Type *SrcTy = Src->getType();
2763 assert(SrcTy->isFirstClassType() && DestTy->isFirstClassType() &&
2764 "Only first class types are castable!");
2766 if (SrcTy == DestTy)
2769 // FIXME: Check address space sizes here
2770 if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy))
2771 if (VectorType *DestVecTy = dyn_cast<VectorType>(DestTy))
2772 if (SrcVecTy->getNumElements() == DestVecTy->getNumElements()) {
2773 // An element by element cast. Find the appropriate opcode based on the
2775 SrcTy = SrcVecTy->getElementType();
2776 DestTy = DestVecTy->getElementType();
2779 // Get the bit sizes, we'll need these
2780 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); // 0 for ptr
2781 unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr
2783 // Run through the possibilities ...
2784 if (DestTy->isIntegerTy()) { // Casting to integral
2785 if (SrcTy->isIntegerTy()) { // Casting from integral
2786 if (DestBits < SrcBits)
2787 return Trunc; // int -> smaller int
2788 else if (DestBits > SrcBits) { // its an extension
2790 return SExt; // signed -> SEXT
2792 return ZExt; // unsigned -> ZEXT
2794 return BitCast; // Same size, No-op cast
2796 } else if (SrcTy->isFloatingPointTy()) { // Casting from floating pt
2798 return FPToSI; // FP -> sint
2800 return FPToUI; // FP -> uint
2801 } else if (SrcTy->isVectorTy()) {
2802 assert(DestBits == SrcBits &&
2803 "Casting vector to integer of different width");
2804 return BitCast; // Same size, no-op cast
2806 assert(SrcTy->isPointerTy() &&
2807 "Casting from a value that is not first-class type");
2808 return PtrToInt; // ptr -> int
2810 } else if (DestTy->isFloatingPointTy()) { // Casting to floating pt
2811 if (SrcTy->isIntegerTy()) { // Casting from integral
2813 return SIToFP; // sint -> FP
2815 return UIToFP; // uint -> FP
2816 } else if (SrcTy->isFloatingPointTy()) { // Casting from floating pt
2817 if (DestBits < SrcBits) {
2818 return FPTrunc; // FP -> smaller FP
2819 } else if (DestBits > SrcBits) {
2820 return FPExt; // FP -> larger FP
2822 return BitCast; // same size, no-op cast
2824 } else if (SrcTy->isVectorTy()) {
2825 assert(DestBits == SrcBits &&
2826 "Casting vector to floating point of different width");
2827 return BitCast; // same size, no-op cast
2829 llvm_unreachable("Casting pointer or non-first class to float");
2830 } else if (DestTy->isVectorTy()) {
2831 assert(DestBits == SrcBits &&
2832 "Illegal cast to vector (wrong type or size)");
2834 } else if (DestTy->isPointerTy()) {
2835 if (SrcTy->isPointerTy()) {
2836 if (DestTy->getPointerAddressSpace() != SrcTy->getPointerAddressSpace())
2837 return AddrSpaceCast;
2838 return BitCast; // ptr -> ptr
2839 } else if (SrcTy->isIntegerTy()) {
2840 return IntToPtr; // int -> ptr
2842 llvm_unreachable("Casting pointer to other than pointer or int");
2843 } else if (DestTy->isX86_MMXTy()) {
2844 if (SrcTy->isVectorTy()) {
2845 assert(DestBits == SrcBits && "Casting vector of wrong width to X86_MMX");
2846 return BitCast; // 64-bit vector to MMX
2848 llvm_unreachable("Illegal cast to X86_MMX");
2850 llvm_unreachable("Casting to type that is not first-class");
2853 //===----------------------------------------------------------------------===//
2854 // CastInst SubClass Constructors
2855 //===----------------------------------------------------------------------===//
2857 /// Check that the construction parameters for a CastInst are correct. This
2858 /// could be broken out into the separate constructors but it is useful to have
2859 /// it in one place and to eliminate the redundant code for getting the sizes
2860 /// of the types involved.
2862 CastInst::castIsValid(Instruction::CastOps op, Value *S, Type *DstTy) {
2864 // Check for type sanity on the arguments
2865 Type *SrcTy = S->getType();
2867 if (!SrcTy->isFirstClassType() || !DstTy->isFirstClassType() ||
2868 SrcTy->isAggregateType() || DstTy->isAggregateType())
2871 // Get the size of the types in bits, we'll need this later
2872 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
2873 unsigned DstBitSize = DstTy->getScalarSizeInBits();
2875 // If these are vector types, get the lengths of the vectors (using zero for
2876 // scalar types means that checking that vector lengths match also checks that
2877 // scalars are not being converted to vectors or vectors to scalars).
2878 unsigned SrcLength = SrcTy->isVectorTy() ?
2879 cast<VectorType>(SrcTy)->getNumElements() : 0;
2880 unsigned DstLength = DstTy->isVectorTy() ?
2881 cast<VectorType>(DstTy)->getNumElements() : 0;
2883 // Switch on the opcode provided
2885 default: return false; // This is an input error
2886 case Instruction::Trunc:
2887 return SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy() &&
2888 SrcLength == DstLength && SrcBitSize > DstBitSize;
2889 case Instruction::ZExt:
2890 return SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy() &&
2891 SrcLength == DstLength && SrcBitSize < DstBitSize;
2892 case Instruction::SExt:
2893 return SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy() &&
2894 SrcLength == DstLength && SrcBitSize < DstBitSize;
2895 case Instruction::FPTrunc:
2896 return SrcTy->isFPOrFPVectorTy() && DstTy->isFPOrFPVectorTy() &&
2897 SrcLength == DstLength && SrcBitSize > DstBitSize;
2898 case Instruction::FPExt:
2899 return SrcTy->isFPOrFPVectorTy() && DstTy->isFPOrFPVectorTy() &&
2900 SrcLength == DstLength && SrcBitSize < DstBitSize;
2901 case Instruction::UIToFP:
2902 case Instruction::SIToFP:
2903 return SrcTy->isIntOrIntVectorTy() && DstTy->isFPOrFPVectorTy() &&
2904 SrcLength == DstLength;
2905 case Instruction::FPToUI:
2906 case Instruction::FPToSI:
2907 return SrcTy->isFPOrFPVectorTy() && DstTy->isIntOrIntVectorTy() &&
2908 SrcLength == DstLength;
2909 case Instruction::PtrToInt:
2910 if (isa<VectorType>(SrcTy) != isa<VectorType>(DstTy))
2912 if (VectorType *VT = dyn_cast<VectorType>(SrcTy))
2913 if (VT->getNumElements() != cast<VectorType>(DstTy)->getNumElements())
2915 return SrcTy->getScalarType()->isPointerTy() &&
2916 DstTy->getScalarType()->isIntegerTy();
2917 case Instruction::IntToPtr:
2918 if (isa<VectorType>(SrcTy) != isa<VectorType>(DstTy))
2920 if (VectorType *VT = dyn_cast<VectorType>(SrcTy))
2921 if (VT->getNumElements() != cast<VectorType>(DstTy)->getNumElements())
2923 return SrcTy->getScalarType()->isIntegerTy() &&
2924 DstTy->getScalarType()->isPointerTy();
2925 case Instruction::BitCast: {
2926 PointerType *SrcPtrTy = dyn_cast<PointerType>(SrcTy->getScalarType());
2927 PointerType *DstPtrTy = dyn_cast<PointerType>(DstTy->getScalarType());
2929 // BitCast implies a no-op cast of type only. No bits change.
2930 // However, you can't cast pointers to anything but pointers.
2931 if (!SrcPtrTy != !DstPtrTy)
2934 // For non-pointer cases, the cast is okay if the source and destination bit
2935 // widths are identical.
2937 return SrcTy->getPrimitiveSizeInBits() == DstTy->getPrimitiveSizeInBits();
2939 // If both are pointers then the address spaces must match.
2940 if (SrcPtrTy->getAddressSpace() != DstPtrTy->getAddressSpace())
2943 // A vector of pointers must have the same number of elements.
2944 if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy)) {
2945 if (VectorType *DstVecTy = dyn_cast<VectorType>(DstTy))
2946 return (SrcVecTy->getNumElements() == DstVecTy->getNumElements());
2953 case Instruction::AddrSpaceCast: {
2954 PointerType *SrcPtrTy = dyn_cast<PointerType>(SrcTy->getScalarType());
2958 PointerType *DstPtrTy = dyn_cast<PointerType>(DstTy->getScalarType());
2962 if (SrcPtrTy->getAddressSpace() == DstPtrTy->getAddressSpace())
2965 if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy)) {
2966 if (VectorType *DstVecTy = dyn_cast<VectorType>(DstTy))
2967 return (SrcVecTy->getNumElements() == DstVecTy->getNumElements());
2977 TruncInst::TruncInst(
2978 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2979 ) : CastInst(Ty, Trunc, S, Name, InsertBefore) {
2980 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
2983 TruncInst::TruncInst(
2984 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2985 ) : CastInst(Ty, Trunc, S, Name, InsertAtEnd) {
2986 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
2990 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
2991 ) : CastInst(Ty, ZExt, S, Name, InsertBefore) {
2992 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
2996 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
2997 ) : CastInst(Ty, ZExt, S, Name, InsertAtEnd) {
2998 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
3001 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3002 ) : CastInst(Ty, SExt, S, Name, InsertBefore) {
3003 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
3007 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3008 ) : CastInst(Ty, SExt, S, Name, InsertAtEnd) {
3009 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
3012 FPTruncInst::FPTruncInst(
3013 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3014 ) : CastInst(Ty, FPTrunc, S, Name, InsertBefore) {
3015 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
3018 FPTruncInst::FPTruncInst(
3019 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3020 ) : CastInst(Ty, FPTrunc, S, Name, InsertAtEnd) {
3021 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
3024 FPExtInst::FPExtInst(
3025 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3026 ) : CastInst(Ty, FPExt, S, Name, InsertBefore) {
3027 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
3030 FPExtInst::FPExtInst(
3031 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3032 ) : CastInst(Ty, FPExt, S, Name, InsertAtEnd) {
3033 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
3036 UIToFPInst::UIToFPInst(
3037 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3038 ) : CastInst(Ty, UIToFP, S, Name, InsertBefore) {
3039 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
3042 UIToFPInst::UIToFPInst(
3043 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3044 ) : CastInst(Ty, UIToFP, S, Name, InsertAtEnd) {
3045 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
3048 SIToFPInst::SIToFPInst(
3049 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3050 ) : CastInst(Ty, SIToFP, S, Name, InsertBefore) {
3051 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
3054 SIToFPInst::SIToFPInst(
3055 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3056 ) : CastInst(Ty, SIToFP, S, Name, InsertAtEnd) {
3057 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
3060 FPToUIInst::FPToUIInst(
3061 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3062 ) : CastInst(Ty, FPToUI, S, Name, InsertBefore) {
3063 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
3066 FPToUIInst::FPToUIInst(
3067 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3068 ) : CastInst(Ty, FPToUI, S, Name, InsertAtEnd) {
3069 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
3072 FPToSIInst::FPToSIInst(
3073 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3074 ) : CastInst(Ty, FPToSI, S, Name, InsertBefore) {
3075 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
3078 FPToSIInst::FPToSIInst(
3079 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3080 ) : CastInst(Ty, FPToSI, S, Name, InsertAtEnd) {
3081 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
3084 PtrToIntInst::PtrToIntInst(
3085 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3086 ) : CastInst(Ty, PtrToInt, S, Name, InsertBefore) {
3087 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
3090 PtrToIntInst::PtrToIntInst(
3091 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3092 ) : CastInst(Ty, PtrToInt, S, Name, InsertAtEnd) {
3093 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
3096 IntToPtrInst::IntToPtrInst(
3097 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3098 ) : CastInst(Ty, IntToPtr, S, Name, InsertBefore) {
3099 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
3102 IntToPtrInst::IntToPtrInst(
3103 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3104 ) : CastInst(Ty, IntToPtr, S, Name, InsertAtEnd) {
3105 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
3108 BitCastInst::BitCastInst(
3109 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3110 ) : CastInst(Ty, BitCast, S, Name, InsertBefore) {
3111 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
3114 BitCastInst::BitCastInst(
3115 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3116 ) : CastInst(Ty, BitCast, S, Name, InsertAtEnd) {
3117 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
3120 AddrSpaceCastInst::AddrSpaceCastInst(
3121 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3122 ) : CastInst(Ty, AddrSpaceCast, S, Name, InsertBefore) {
3123 assert(castIsValid(getOpcode(), S, Ty) && "Illegal AddrSpaceCast");
3126 AddrSpaceCastInst::AddrSpaceCastInst(
3127 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3128 ) : CastInst(Ty, AddrSpaceCast, S, Name, InsertAtEnd) {
3129 assert(castIsValid(getOpcode(), S, Ty) && "Illegal AddrSpaceCast");
3132 //===----------------------------------------------------------------------===//
3134 //===----------------------------------------------------------------------===//
3136 void CmpInst::anchor() {}
3138 CmpInst::CmpInst(Type *ty, OtherOps op, unsigned short predicate,
3139 Value *LHS, Value *RHS, const Twine &Name,
3140 Instruction *InsertBefore)
3141 : Instruction(ty, op,
3142 OperandTraits<CmpInst>::op_begin(this),
3143 OperandTraits<CmpInst>::operands(this),
3147 setPredicate((Predicate)predicate);
3151 CmpInst::CmpInst(Type *ty, OtherOps op, unsigned short predicate,
3152 Value *LHS, Value *RHS, const Twine &Name,
3153 BasicBlock *InsertAtEnd)
3154 : Instruction(ty, op,
3155 OperandTraits<CmpInst>::op_begin(this),
3156 OperandTraits<CmpInst>::operands(this),
3160 setPredicate((Predicate)predicate);
3165 CmpInst::Create(OtherOps Op, unsigned short predicate,
3166 Value *S1, Value *S2,
3167 const Twine &Name, Instruction *InsertBefore) {
3168 if (Op == Instruction::ICmp) {
3170 return new ICmpInst(InsertBefore, CmpInst::Predicate(predicate),
3173 return new ICmpInst(CmpInst::Predicate(predicate),
3178 return new FCmpInst(InsertBefore, CmpInst::Predicate(predicate),
3181 return new FCmpInst(CmpInst::Predicate(predicate),
3186 CmpInst::Create(OtherOps Op, unsigned short predicate, Value *S1, Value *S2,
3187 const Twine &Name, BasicBlock *InsertAtEnd) {
3188 if (Op == Instruction::ICmp) {
3189 return new ICmpInst(*InsertAtEnd, CmpInst::Predicate(predicate),
3192 return new FCmpInst(*InsertAtEnd, CmpInst::Predicate(predicate),
3196 void CmpInst::swapOperands() {
3197 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
3200 cast<FCmpInst>(this)->swapOperands();
3203 bool CmpInst::isCommutative() const {
3204 if (const ICmpInst *IC = dyn_cast<ICmpInst>(this))
3205 return IC->isCommutative();
3206 return cast<FCmpInst>(this)->isCommutative();
3209 bool CmpInst::isEquality() const {
3210 if (const ICmpInst *IC = dyn_cast<ICmpInst>(this))
3211 return IC->isEquality();
3212 return cast<FCmpInst>(this)->isEquality();
3216 CmpInst::Predicate CmpInst::getInversePredicate(Predicate pred) {
3218 default: llvm_unreachable("Unknown cmp predicate!");
3219 case ICMP_EQ: return ICMP_NE;
3220 case ICMP_NE: return ICMP_EQ;
3221 case ICMP_UGT: return ICMP_ULE;
3222 case ICMP_ULT: return ICMP_UGE;
3223 case ICMP_UGE: return ICMP_ULT;
3224 case ICMP_ULE: return ICMP_UGT;
3225 case ICMP_SGT: return ICMP_SLE;
3226 case ICMP_SLT: return ICMP_SGE;
3227 case ICMP_SGE: return ICMP_SLT;
3228 case ICMP_SLE: return ICMP_SGT;
3230 case FCMP_OEQ: return FCMP_UNE;
3231 case FCMP_ONE: return FCMP_UEQ;
3232 case FCMP_OGT: return FCMP_ULE;
3233 case FCMP_OLT: return FCMP_UGE;
3234 case FCMP_OGE: return FCMP_ULT;
3235 case FCMP_OLE: return FCMP_UGT;
3236 case FCMP_UEQ: return FCMP_ONE;
3237 case FCMP_UNE: return FCMP_OEQ;
3238 case FCMP_UGT: return FCMP_OLE;
3239 case FCMP_ULT: return FCMP_OGE;
3240 case FCMP_UGE: return FCMP_OLT;
3241 case FCMP_ULE: return FCMP_OGT;
3242 case FCMP_ORD: return FCMP_UNO;
3243 case FCMP_UNO: return FCMP_ORD;
3244 case FCMP_TRUE: return FCMP_FALSE;
3245 case FCMP_FALSE: return FCMP_TRUE;
3249 ICmpInst::Predicate ICmpInst::getSignedPredicate(Predicate pred) {
3251 default: llvm_unreachable("Unknown icmp predicate!");
3252 case ICMP_EQ: case ICMP_NE:
3253 case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE:
3255 case ICMP_UGT: return ICMP_SGT;
3256 case ICMP_ULT: return ICMP_SLT;
3257 case ICMP_UGE: return ICMP_SGE;
3258 case ICMP_ULE: return ICMP_SLE;
3262 ICmpInst::Predicate ICmpInst::getUnsignedPredicate(Predicate pred) {
3264 default: llvm_unreachable("Unknown icmp predicate!");
3265 case ICMP_EQ: case ICMP_NE:
3266 case ICMP_UGT: case ICMP_ULT: case ICMP_UGE: case ICMP_ULE:
3268 case ICMP_SGT: return ICMP_UGT;
3269 case ICMP_SLT: return ICMP_ULT;
3270 case ICMP_SGE: return ICMP_UGE;
3271 case ICMP_SLE: return ICMP_ULE;
3275 /// Initialize a set of values that all satisfy the condition with C.
3278 ICmpInst::makeConstantRange(Predicate pred, const APInt &C) {
3281 uint32_t BitWidth = C.getBitWidth();
3283 default: llvm_unreachable("Invalid ICmp opcode to ConstantRange ctor!");
3284 case ICmpInst::ICMP_EQ: ++Upper; break;
3285 case ICmpInst::ICMP_NE: ++Lower; break;
3286 case ICmpInst::ICMP_ULT:
3287 Lower = APInt::getMinValue(BitWidth);
3288 // Check for an empty-set condition.
3290 return ConstantRange(BitWidth, /*isFullSet=*/false);
3292 case ICmpInst::ICMP_SLT:
3293 Lower = APInt::getSignedMinValue(BitWidth);
3294 // Check for an empty-set condition.
3296 return ConstantRange(BitWidth, /*isFullSet=*/false);
3298 case ICmpInst::ICMP_UGT:
3299 ++Lower; Upper = APInt::getMinValue(BitWidth); // Min = Next(Max)
3300 // Check for an empty-set condition.
3302 return ConstantRange(BitWidth, /*isFullSet=*/false);
3304 case ICmpInst::ICMP_SGT:
3305 ++Lower; Upper = APInt::getSignedMinValue(BitWidth); // Min = Next(Max)
3306 // Check for an empty-set condition.
3308 return ConstantRange(BitWidth, /*isFullSet=*/false);
3310 case ICmpInst::ICMP_ULE:
3311 Lower = APInt::getMinValue(BitWidth); ++Upper;
3312 // Check for a full-set condition.
3314 return ConstantRange(BitWidth, /*isFullSet=*/true);
3316 case ICmpInst::ICMP_SLE:
3317 Lower = APInt::getSignedMinValue(BitWidth); ++Upper;
3318 // Check for a full-set condition.
3320 return ConstantRange(BitWidth, /*isFullSet=*/true);
3322 case ICmpInst::ICMP_UGE:
3323 Upper = APInt::getMinValue(BitWidth); // Min = Next(Max)
3324 // Check for a full-set condition.
3326 return ConstantRange(BitWidth, /*isFullSet=*/true);
3328 case ICmpInst::ICMP_SGE:
3329 Upper = APInt::getSignedMinValue(BitWidth); // Min = Next(Max)
3330 // Check for a full-set condition.
3332 return ConstantRange(BitWidth, /*isFullSet=*/true);
3335 return ConstantRange(Lower, Upper);
3338 CmpInst::Predicate CmpInst::getSwappedPredicate(Predicate pred) {
3340 default: llvm_unreachable("Unknown cmp predicate!");
3341 case ICMP_EQ: case ICMP_NE:
3343 case ICMP_SGT: return ICMP_SLT;
3344 case ICMP_SLT: return ICMP_SGT;
3345 case ICMP_SGE: return ICMP_SLE;
3346 case ICMP_SLE: return ICMP_SGE;
3347 case ICMP_UGT: return ICMP_ULT;
3348 case ICMP_ULT: return ICMP_UGT;
3349 case ICMP_UGE: return ICMP_ULE;
3350 case ICMP_ULE: return ICMP_UGE;
3352 case FCMP_FALSE: case FCMP_TRUE:
3353 case FCMP_OEQ: case FCMP_ONE:
3354 case FCMP_UEQ: case FCMP_UNE:
3355 case FCMP_ORD: case FCMP_UNO:
3357 case FCMP_OGT: return FCMP_OLT;
3358 case FCMP_OLT: return FCMP_OGT;
3359 case FCMP_OGE: return FCMP_OLE;
3360 case FCMP_OLE: return FCMP_OGE;
3361 case FCMP_UGT: return FCMP_ULT;
3362 case FCMP_ULT: return FCMP_UGT;
3363 case FCMP_UGE: return FCMP_ULE;
3364 case FCMP_ULE: return FCMP_UGE;
3368 bool CmpInst::isUnsigned(unsigned short predicate) {
3369 switch (predicate) {
3370 default: return false;
3371 case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_ULE: case ICmpInst::ICMP_UGT:
3372 case ICmpInst::ICMP_UGE: return true;
3376 bool CmpInst::isSigned(unsigned short predicate) {
3377 switch (predicate) {
3378 default: return false;
3379 case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_SLE: case ICmpInst::ICMP_SGT:
3380 case ICmpInst::ICMP_SGE: return true;
3384 bool CmpInst::isOrdered(unsigned short predicate) {
3385 switch (predicate) {
3386 default: return false;
3387 case FCmpInst::FCMP_OEQ: case FCmpInst::FCMP_ONE: case FCmpInst::FCMP_OGT:
3388 case FCmpInst::FCMP_OLT: case FCmpInst::FCMP_OGE: case FCmpInst::FCMP_OLE:
3389 case FCmpInst::FCMP_ORD: return true;
3393 bool CmpInst::isUnordered(unsigned short predicate) {
3394 switch (predicate) {
3395 default: return false;
3396 case FCmpInst::FCMP_UEQ: case FCmpInst::FCMP_UNE: case FCmpInst::FCMP_UGT:
3397 case FCmpInst::FCMP_ULT: case FCmpInst::FCMP_UGE: case FCmpInst::FCMP_ULE:
3398 case FCmpInst::FCMP_UNO: return true;
3402 bool CmpInst::isTrueWhenEqual(unsigned short predicate) {
3404 default: return false;
3405 case ICMP_EQ: case ICMP_UGE: case ICMP_ULE: case ICMP_SGE: case ICMP_SLE:
3406 case FCMP_TRUE: case FCMP_UEQ: case FCMP_UGE: case FCMP_ULE: return true;
3410 bool CmpInst::isFalseWhenEqual(unsigned short predicate) {
3412 case ICMP_NE: case ICMP_UGT: case ICMP_ULT: case ICMP_SGT: case ICMP_SLT:
3413 case FCMP_FALSE: case FCMP_ONE: case FCMP_OGT: case FCMP_OLT: return true;
3414 default: return false;
3419 //===----------------------------------------------------------------------===//
3420 // SwitchInst Implementation
3421 //===----------------------------------------------------------------------===//
3423 void SwitchInst::init(Value *Value, BasicBlock *Default, unsigned NumReserved) {
3424 assert(Value && Default && NumReserved);
3425 ReservedSpace = NumReserved;
3427 OperandList = allocHungoffUses(ReservedSpace);
3429 OperandList[0] = Value;
3430 OperandList[1] = Default;
3433 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
3434 /// switch on and a default destination. The number of additional cases can
3435 /// be specified here to make memory allocation more efficient. This
3436 /// constructor can also autoinsert before another instruction.
3437 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
3438 Instruction *InsertBefore)
3439 : TerminatorInst(Type::getVoidTy(Value->getContext()), Instruction::Switch,
3440 nullptr, 0, InsertBefore) {
3441 init(Value, Default, 2+NumCases*2);
3444 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
3445 /// switch on and a default destination. The number of additional cases can
3446 /// be specified here to make memory allocation more efficient. This
3447 /// constructor also autoinserts at the end of the specified BasicBlock.
3448 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
3449 BasicBlock *InsertAtEnd)
3450 : TerminatorInst(Type::getVoidTy(Value->getContext()), Instruction::Switch,
3451 nullptr, 0, InsertAtEnd) {
3452 init(Value, Default, 2+NumCases*2);
3455 SwitchInst::SwitchInst(const SwitchInst &SI)
3456 : TerminatorInst(SI.getType(), Instruction::Switch, nullptr, 0) {
3457 init(SI.getCondition(), SI.getDefaultDest(), SI.getNumOperands());
3458 NumOperands = SI.getNumOperands();
3459 Use *OL = OperandList, *InOL = SI.OperandList;
3460 for (unsigned i = 2, E = SI.getNumOperands(); i != E; i += 2) {
3462 OL[i+1] = InOL[i+1];
3464 SubclassOptionalData = SI.SubclassOptionalData;
3467 SwitchInst::~SwitchInst() {
3472 /// addCase - Add an entry to the switch instruction...
3474 void SwitchInst::addCase(ConstantInt *OnVal, BasicBlock *Dest) {
3475 unsigned NewCaseIdx = getNumCases();
3476 unsigned OpNo = NumOperands;
3477 if (OpNo+2 > ReservedSpace)
3478 growOperands(); // Get more space!
3479 // Initialize some new operands.
3480 assert(OpNo+1 < ReservedSpace && "Growing didn't work!");
3481 NumOperands = OpNo+2;
3482 CaseIt Case(this, NewCaseIdx);
3483 Case.setValue(OnVal);
3484 Case.setSuccessor(Dest);
3487 /// removeCase - This method removes the specified case and its successor
3488 /// from the switch instruction.
3489 void SwitchInst::removeCase(CaseIt i) {
3490 unsigned idx = i.getCaseIndex();
3492 assert(2 + idx*2 < getNumOperands() && "Case index out of range!!!");
3494 unsigned NumOps = getNumOperands();
3495 Use *OL = OperandList;
3497 // Overwrite this case with the end of the list.
3498 if (2 + (idx + 1) * 2 != NumOps) {
3499 OL[2 + idx * 2] = OL[NumOps - 2];
3500 OL[2 + idx * 2 + 1] = OL[NumOps - 1];
3503 // Nuke the last value.
3504 OL[NumOps-2].set(nullptr);
3505 OL[NumOps-2+1].set(nullptr);
3506 NumOperands = NumOps-2;
3509 /// growOperands - grow operands - This grows the operand list in response
3510 /// to a push_back style of operation. This grows the number of ops by 3 times.
3512 void SwitchInst::growOperands() {
3513 unsigned e = getNumOperands();
3514 unsigned NumOps = e*3;
3516 ReservedSpace = NumOps;
3517 Use *NewOps = allocHungoffUses(NumOps);
3518 Use *OldOps = OperandList;
3519 for (unsigned i = 0; i != e; ++i) {
3520 NewOps[i] = OldOps[i];
3522 OperandList = NewOps;
3523 Use::zap(OldOps, OldOps + e, true);
3527 BasicBlock *SwitchInst::getSuccessorV(unsigned idx) const {
3528 return getSuccessor(idx);
3530 unsigned SwitchInst::getNumSuccessorsV() const {
3531 return getNumSuccessors();
3533 void SwitchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
3534 setSuccessor(idx, B);
3537 //===----------------------------------------------------------------------===//
3538 // IndirectBrInst Implementation
3539 //===----------------------------------------------------------------------===//
3541 void IndirectBrInst::init(Value *Address, unsigned NumDests) {
3542 assert(Address && Address->getType()->isPointerTy() &&
3543 "Address of indirectbr must be a pointer");
3544 ReservedSpace = 1+NumDests;
3546 OperandList = allocHungoffUses(ReservedSpace);
3548 OperandList[0] = Address;
3552 /// growOperands - grow operands - This grows the operand list in response
3553 /// to a push_back style of operation. This grows the number of ops by 2 times.
3555 void IndirectBrInst::growOperands() {
3556 unsigned e = getNumOperands();
3557 unsigned NumOps = e*2;
3559 ReservedSpace = NumOps;
3560 Use *NewOps = allocHungoffUses(NumOps);
3561 Use *OldOps = OperandList;
3562 for (unsigned i = 0; i != e; ++i)
3563 NewOps[i] = OldOps[i];
3564 OperandList = NewOps;
3565 Use::zap(OldOps, OldOps + e, true);
3568 IndirectBrInst::IndirectBrInst(Value *Address, unsigned NumCases,
3569 Instruction *InsertBefore)
3570 : TerminatorInst(Type::getVoidTy(Address->getContext()),Instruction::IndirectBr,
3571 nullptr, 0, InsertBefore) {
3572 init(Address, NumCases);
3575 IndirectBrInst::IndirectBrInst(Value *Address, unsigned NumCases,
3576 BasicBlock *InsertAtEnd)
3577 : TerminatorInst(Type::getVoidTy(Address->getContext()),Instruction::IndirectBr,
3578 nullptr, 0, InsertAtEnd) {
3579 init(Address, NumCases);
3582 IndirectBrInst::IndirectBrInst(const IndirectBrInst &IBI)
3583 : TerminatorInst(Type::getVoidTy(IBI.getContext()), Instruction::IndirectBr,
3584 allocHungoffUses(IBI.getNumOperands()),
3585 IBI.getNumOperands()) {
3586 Use *OL = OperandList, *InOL = IBI.OperandList;
3587 for (unsigned i = 0, E = IBI.getNumOperands(); i != E; ++i)
3589 SubclassOptionalData = IBI.SubclassOptionalData;
3592 IndirectBrInst::~IndirectBrInst() {
3596 /// addDestination - Add a destination.
3598 void IndirectBrInst::addDestination(BasicBlock *DestBB) {
3599 unsigned OpNo = NumOperands;
3600 if (OpNo+1 > ReservedSpace)
3601 growOperands(); // Get more space!
3602 // Initialize some new operands.
3603 assert(OpNo < ReservedSpace && "Growing didn't work!");
3604 NumOperands = OpNo+1;
3605 OperandList[OpNo] = DestBB;
3608 /// removeDestination - This method removes the specified successor from the
3609 /// indirectbr instruction.
3610 void IndirectBrInst::removeDestination(unsigned idx) {
3611 assert(idx < getNumOperands()-1 && "Successor index out of range!");
3613 unsigned NumOps = getNumOperands();
3614 Use *OL = OperandList;
3616 // Replace this value with the last one.
3617 OL[idx+1] = OL[NumOps-1];
3619 // Nuke the last value.
3620 OL[NumOps-1].set(nullptr);
3621 NumOperands = NumOps-1;
3624 BasicBlock *IndirectBrInst::getSuccessorV(unsigned idx) const {
3625 return getSuccessor(idx);
3627 unsigned IndirectBrInst::getNumSuccessorsV() const {
3628 return getNumSuccessors();
3630 void IndirectBrInst::setSuccessorV(unsigned idx, BasicBlock *B) {
3631 setSuccessor(idx, B);
3634 //===----------------------------------------------------------------------===//
3635 // clone_impl() implementations
3636 //===----------------------------------------------------------------------===//
3638 // Define these methods here so vtables don't get emitted into every translation
3639 // unit that uses these classes.
3641 GetElementPtrInst *GetElementPtrInst::clone_impl() const {
3642 return new (getNumOperands()) GetElementPtrInst(*this);
3645 BinaryOperator *BinaryOperator::clone_impl() const {
3646 return Create(getOpcode(), Op<0>(), Op<1>());
3649 FCmpInst* FCmpInst::clone_impl() const {
3650 return new FCmpInst(getPredicate(), Op<0>(), Op<1>());
3653 ICmpInst* ICmpInst::clone_impl() const {
3654 return new ICmpInst(getPredicate(), Op<0>(), Op<1>());
3657 ExtractValueInst *ExtractValueInst::clone_impl() const {
3658 return new ExtractValueInst(*this);
3661 InsertValueInst *InsertValueInst::clone_impl() const {
3662 return new InsertValueInst(*this);
3665 AllocaInst *AllocaInst::clone_impl() const {
3666 AllocaInst *Result = new AllocaInst(getAllocatedType(),
3667 (Value *)getOperand(0), getAlignment());
3668 Result->setUsedWithInAlloca(isUsedWithInAlloca());
3672 LoadInst *LoadInst::clone_impl() const {
3673 return new LoadInst(getOperand(0), Twine(), isVolatile(),
3674 getAlignment(), getOrdering(), getSynchScope());
3677 StoreInst *StoreInst::clone_impl() const {
3678 return new StoreInst(getOperand(0), getOperand(1), isVolatile(),
3679 getAlignment(), getOrdering(), getSynchScope());
3683 AtomicCmpXchgInst *AtomicCmpXchgInst::clone_impl() const {
3684 AtomicCmpXchgInst *Result =
3685 new AtomicCmpXchgInst(getOperand(0), getOperand(1), getOperand(2),
3686 getSuccessOrdering(), getFailureOrdering(),
3688 Result->setVolatile(isVolatile());
3689 Result->setWeak(isWeak());
3693 AtomicRMWInst *AtomicRMWInst::clone_impl() const {
3694 AtomicRMWInst *Result =
3695 new AtomicRMWInst(getOperation(),getOperand(0), getOperand(1),
3696 getOrdering(), getSynchScope());
3697 Result->setVolatile(isVolatile());
3701 FenceInst *FenceInst::clone_impl() const {
3702 return new FenceInst(getContext(), getOrdering(), getSynchScope());
3705 TruncInst *TruncInst::clone_impl() const {
3706 return new TruncInst(getOperand(0), getType());
3709 ZExtInst *ZExtInst::clone_impl() const {
3710 return new ZExtInst(getOperand(0), getType());
3713 SExtInst *SExtInst::clone_impl() const {
3714 return new SExtInst(getOperand(0), getType());
3717 FPTruncInst *FPTruncInst::clone_impl() const {
3718 return new FPTruncInst(getOperand(0), getType());
3721 FPExtInst *FPExtInst::clone_impl() const {
3722 return new FPExtInst(getOperand(0), getType());
3725 UIToFPInst *UIToFPInst::clone_impl() const {
3726 return new UIToFPInst(getOperand(0), getType());
3729 SIToFPInst *SIToFPInst::clone_impl() const {
3730 return new SIToFPInst(getOperand(0), getType());
3733 FPToUIInst *FPToUIInst::clone_impl() const {
3734 return new FPToUIInst(getOperand(0), getType());
3737 FPToSIInst *FPToSIInst::clone_impl() const {
3738 return new FPToSIInst(getOperand(0), getType());
3741 PtrToIntInst *PtrToIntInst::clone_impl() const {
3742 return new PtrToIntInst(getOperand(0), getType());
3745 IntToPtrInst *IntToPtrInst::clone_impl() const {
3746 return new IntToPtrInst(getOperand(0), getType());
3749 BitCastInst *BitCastInst::clone_impl() const {
3750 return new BitCastInst(getOperand(0), getType());
3753 AddrSpaceCastInst *AddrSpaceCastInst::clone_impl() const {
3754 return new AddrSpaceCastInst(getOperand(0), getType());
3757 CallInst *CallInst::clone_impl() const {
3758 return new(getNumOperands()) CallInst(*this);
3761 SelectInst *SelectInst::clone_impl() const {
3762 return SelectInst::Create(getOperand(0), getOperand(1), getOperand(2));
3765 VAArgInst *VAArgInst::clone_impl() const {
3766 return new VAArgInst(getOperand(0), getType());
3769 ExtractElementInst *ExtractElementInst::clone_impl() const {
3770 return ExtractElementInst::Create(getOperand(0), getOperand(1));
3773 InsertElementInst *InsertElementInst::clone_impl() const {
3774 return InsertElementInst::Create(getOperand(0), getOperand(1), getOperand(2));
3777 ShuffleVectorInst *ShuffleVectorInst::clone_impl() const {
3778 return new ShuffleVectorInst(getOperand(0), getOperand(1), getOperand(2));
3781 PHINode *PHINode::clone_impl() const {
3782 return new PHINode(*this);
3785 LandingPadInst *LandingPadInst::clone_impl() const {
3786 return new LandingPadInst(*this);
3789 ReturnInst *ReturnInst::clone_impl() const {
3790 return new(getNumOperands()) ReturnInst(*this);
3793 BranchInst *BranchInst::clone_impl() const {
3794 return new(getNumOperands()) BranchInst(*this);
3797 SwitchInst *SwitchInst::clone_impl() const {
3798 return new SwitchInst(*this);
3801 IndirectBrInst *IndirectBrInst::clone_impl() const {
3802 return new IndirectBrInst(*this);
3806 InvokeInst *InvokeInst::clone_impl() const {
3807 return new(getNumOperands()) InvokeInst(*this);
3810 ResumeInst *ResumeInst::clone_impl() const {
3811 return new(1) ResumeInst(*this);
3814 UnreachableInst *UnreachableInst::clone_impl() const {
3815 LLVMContext &Context = getContext();
3816 return new UnreachableInst(Context);