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 (Op1->getType()->isTokenTy())
67 return "select values cannot have token type";
69 if (VectorType *VT = dyn_cast<VectorType>(Op0->getType())) {
71 if (VT->getElementType() != Type::getInt1Ty(Op0->getContext()))
72 return "vector select condition element type must be i1";
73 VectorType *ET = dyn_cast<VectorType>(Op1->getType());
75 return "selected values for vector select must be vectors";
76 if (ET->getNumElements() != VT->getNumElements())
77 return "vector select requires selected vectors to have "
78 "the same vector length as select condition";
79 } else if (Op0->getType() != Type::getInt1Ty(Op0->getContext())) {
80 return "select condition must be i1 or <n x i1>";
86 //===----------------------------------------------------------------------===//
88 //===----------------------------------------------------------------------===//
90 PHINode::PHINode(const PHINode &PN)
91 : Instruction(PN.getType(), Instruction::PHI, nullptr, PN.getNumOperands()),
92 ReservedSpace(PN.getNumOperands()) {
93 allocHungoffUses(PN.getNumOperands());
94 std::copy(PN.op_begin(), PN.op_end(), op_begin());
95 std::copy(PN.block_begin(), PN.block_end(), block_begin());
96 SubclassOptionalData = PN.SubclassOptionalData;
99 // removeIncomingValue - Remove an incoming value. This is useful if a
100 // predecessor basic block is deleted.
101 Value *PHINode::removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty) {
102 Value *Removed = getIncomingValue(Idx);
104 // Move everything after this operand down.
106 // FIXME: we could just swap with the end of the list, then erase. However,
107 // clients might not expect this to happen. The code as it is thrashes the
108 // use/def lists, which is kinda lame.
109 std::copy(op_begin() + Idx + 1, op_end(), op_begin() + Idx);
110 std::copy(block_begin() + Idx + 1, block_end(), block_begin() + Idx);
112 // Nuke the last value.
113 Op<-1>().set(nullptr);
114 setNumHungOffUseOperands(getNumOperands() - 1);
116 // If the PHI node is dead, because it has zero entries, nuke it now.
117 if (getNumOperands() == 0 && DeletePHIIfEmpty) {
118 // If anyone is using this PHI, make them use a dummy value instead...
119 replaceAllUsesWith(UndefValue::get(getType()));
125 /// growOperands - grow operands - This grows the operand list in response
126 /// to a push_back style of operation. This grows the number of ops by 1.5
129 void PHINode::growOperands() {
130 unsigned e = getNumOperands();
131 unsigned NumOps = e + e / 2;
132 if (NumOps < 2) NumOps = 2; // 2 op PHI nodes are VERY common.
134 ReservedSpace = NumOps;
135 growHungoffUses(ReservedSpace, /* IsPhi */ true);
138 /// hasConstantValue - If the specified PHI node always merges together the same
139 /// value, return the value, otherwise return null.
140 Value *PHINode::hasConstantValue() const {
141 // Exploit the fact that phi nodes always have at least one entry.
142 Value *ConstantValue = getIncomingValue(0);
143 for (unsigned i = 1, e = getNumIncomingValues(); i != e; ++i)
144 if (getIncomingValue(i) != ConstantValue && getIncomingValue(i) != this) {
145 if (ConstantValue != this)
146 return nullptr; // Incoming values not all the same.
147 // The case where the first value is this PHI.
148 ConstantValue = getIncomingValue(i);
150 if (ConstantValue == this)
151 return UndefValue::get(getType());
152 return ConstantValue;
155 //===----------------------------------------------------------------------===//
156 // LandingPadInst Implementation
157 //===----------------------------------------------------------------------===//
159 LandingPadInst::LandingPadInst(Type *RetTy, unsigned NumReservedValues,
160 const Twine &NameStr, Instruction *InsertBefore)
161 : Instruction(RetTy, Instruction::LandingPad, nullptr, 0, InsertBefore) {
162 init(NumReservedValues, NameStr);
165 LandingPadInst::LandingPadInst(Type *RetTy, unsigned NumReservedValues,
166 const Twine &NameStr, BasicBlock *InsertAtEnd)
167 : Instruction(RetTy, Instruction::LandingPad, nullptr, 0, InsertAtEnd) {
168 init(NumReservedValues, NameStr);
171 LandingPadInst::LandingPadInst(const LandingPadInst &LP)
172 : Instruction(LP.getType(), Instruction::LandingPad, nullptr,
173 LP.getNumOperands()),
174 ReservedSpace(LP.getNumOperands()) {
175 allocHungoffUses(LP.getNumOperands());
176 Use *OL = getOperandList();
177 const Use *InOL = LP.getOperandList();
178 for (unsigned I = 0, E = ReservedSpace; I != E; ++I)
181 setCleanup(LP.isCleanup());
184 LandingPadInst *LandingPadInst::Create(Type *RetTy, unsigned NumReservedClauses,
185 const Twine &NameStr,
186 Instruction *InsertBefore) {
187 return new LandingPadInst(RetTy, NumReservedClauses, NameStr, InsertBefore);
190 LandingPadInst *LandingPadInst::Create(Type *RetTy, unsigned NumReservedClauses,
191 const Twine &NameStr,
192 BasicBlock *InsertAtEnd) {
193 return new LandingPadInst(RetTy, NumReservedClauses, NameStr, InsertAtEnd);
196 void LandingPadInst::init(unsigned NumReservedValues, const Twine &NameStr) {
197 ReservedSpace = NumReservedValues;
198 setNumHungOffUseOperands(0);
199 allocHungoffUses(ReservedSpace);
204 /// growOperands - grow operands - This grows the operand list in response to a
205 /// push_back style of operation. This grows the number of ops by 2 times.
206 void LandingPadInst::growOperands(unsigned Size) {
207 unsigned e = getNumOperands();
208 if (ReservedSpace >= e + Size) return;
209 ReservedSpace = (std::max(e, 1U) + Size / 2) * 2;
210 growHungoffUses(ReservedSpace);
213 void LandingPadInst::addClause(Constant *Val) {
214 unsigned OpNo = getNumOperands();
216 assert(OpNo < ReservedSpace && "Growing didn't work!");
217 setNumHungOffUseOperands(getNumOperands() + 1);
218 getOperandList()[OpNo] = Val;
221 //===----------------------------------------------------------------------===//
222 // CallInst Implementation
223 //===----------------------------------------------------------------------===//
225 CallInst::~CallInst() {
228 void CallInst::init(FunctionType *FTy, Value *Func, ArrayRef<Value *> Args,
229 ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr) {
231 assert(getNumOperands() == Args.size() + CountBundleInputs(Bundles) + 1 &&
232 "NumOperands not set up?");
236 assert((Args.size() == FTy->getNumParams() ||
237 (FTy->isVarArg() && Args.size() > FTy->getNumParams())) &&
238 "Calling a function with bad signature!");
240 for (unsigned i = 0; i != Args.size(); ++i)
241 assert((i >= FTy->getNumParams() ||
242 FTy->getParamType(i) == Args[i]->getType()) &&
243 "Calling a function with a bad signature!");
246 std::copy(Args.begin(), Args.end(), op_begin());
248 auto It = populateBundleOperandInfos(Bundles, Args.size());
250 assert(It + 1 == op_end() && "Should add up!");
255 void CallInst::init(Value *Func, const Twine &NameStr) {
257 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
258 assert(getNumOperands() == 1 && "NumOperands not set up?");
261 assert(FTy->getNumParams() == 0 && "Calling a function with bad signature");
266 CallInst::CallInst(Value *Func, const Twine &Name,
267 Instruction *InsertBefore)
268 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
269 ->getElementType())->getReturnType(),
271 OperandTraits<CallInst>::op_end(this) - 1,
276 CallInst::CallInst(Value *Func, const Twine &Name,
277 BasicBlock *InsertAtEnd)
278 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
279 ->getElementType())->getReturnType(),
281 OperandTraits<CallInst>::op_end(this) - 1,
286 CallInst::CallInst(const CallInst &CI)
287 : Instruction(CI.getType(), Instruction::Call,
288 OperandTraits<CallInst>::op_end(this) - CI.getNumOperands(),
289 CI.getNumOperands()),
290 AttributeList(CI.AttributeList), FTy(CI.FTy) {
291 setTailCallKind(CI.getTailCallKind());
292 setCallingConv(CI.getCallingConv());
294 std::copy(CI.op_begin(), CI.op_end(), op_begin());
295 std::copy(CI.bundle_op_info_begin(), CI.bundle_op_info_end(),
296 bundle_op_info_begin());
297 SubclassOptionalData = CI.SubclassOptionalData;
300 void CallInst::addAttribute(unsigned i, Attribute::AttrKind attr) {
301 AttributeSet PAL = getAttributes();
302 PAL = PAL.addAttribute(getContext(), i, attr);
306 void CallInst::addAttribute(unsigned i, StringRef Kind, StringRef Value) {
307 AttributeSet PAL = getAttributes();
308 PAL = PAL.addAttribute(getContext(), i, Kind, Value);
312 void CallInst::removeAttribute(unsigned i, Attribute attr) {
313 AttributeSet PAL = getAttributes();
315 LLVMContext &Context = getContext();
316 PAL = PAL.removeAttributes(Context, i,
317 AttributeSet::get(Context, i, B));
321 void CallInst::addDereferenceableAttr(unsigned i, uint64_t Bytes) {
322 AttributeSet PAL = getAttributes();
323 PAL = PAL.addDereferenceableAttr(getContext(), i, Bytes);
327 void CallInst::addDereferenceableOrNullAttr(unsigned i, uint64_t Bytes) {
328 AttributeSet PAL = getAttributes();
329 PAL = PAL.addDereferenceableOrNullAttr(getContext(), i, Bytes);
333 bool CallInst::paramHasAttr(unsigned i, Attribute::AttrKind A) const {
334 assert(i < (getNumArgOperands() + 1) && "Param index out of bounds!");
336 if (AttributeList.hasAttribute(i, A))
338 if (const Function *F = getCalledFunction())
339 return F->getAttributes().hasAttribute(i, A);
343 bool CallInst::dataOperandHasImpliedAttr(unsigned i,
344 Attribute::AttrKind A) const {
346 // There are getNumOperands() - 1 data operands. The last operand is the
348 assert(i < getNumOperands() && "Data operand index out of bounds!");
350 // The attribute A can either be directly specified, if the operand in
351 // question is a call argument; or be indirectly implied by the kind of its
352 // containing operand bundle, if the operand is a bundle operand.
354 if (i < (getNumArgOperands() + 1))
355 return paramHasAttr(i, A);
357 assert(hasOperandBundles() && i >= (getBundleOperandsStartIndex() + 1) &&
358 "Must be either a call argument or an operand bundle!");
359 return getOperandBundleForOperand(i - 1).operandsHaveAttr(A);
362 /// IsConstantOne - Return true only if val is constant int 1
363 static bool IsConstantOne(Value *val) {
364 assert(val && "IsConstantOne does not work with nullptr val");
365 const ConstantInt *CVal = dyn_cast<ConstantInt>(val);
366 return CVal && CVal->isOne();
369 static Instruction *createMalloc(Instruction *InsertBefore,
370 BasicBlock *InsertAtEnd, Type *IntPtrTy,
371 Type *AllocTy, Value *AllocSize,
372 Value *ArraySize, Function *MallocF,
374 assert(((!InsertBefore && InsertAtEnd) || (InsertBefore && !InsertAtEnd)) &&
375 "createMalloc needs either InsertBefore or InsertAtEnd");
377 // malloc(type) becomes:
378 // bitcast (i8* malloc(typeSize)) to type*
379 // malloc(type, arraySize) becomes:
380 // bitcast (i8 *malloc(typeSize*arraySize)) to type*
382 ArraySize = ConstantInt::get(IntPtrTy, 1);
383 else if (ArraySize->getType() != IntPtrTy) {
385 ArraySize = CastInst::CreateIntegerCast(ArraySize, IntPtrTy, false,
388 ArraySize = CastInst::CreateIntegerCast(ArraySize, IntPtrTy, false,
392 if (!IsConstantOne(ArraySize)) {
393 if (IsConstantOne(AllocSize)) {
394 AllocSize = ArraySize; // Operand * 1 = Operand
395 } else if (Constant *CO = dyn_cast<Constant>(ArraySize)) {
396 Constant *Scale = ConstantExpr::getIntegerCast(CO, IntPtrTy,
398 // Malloc arg is constant product of type size and array size
399 AllocSize = ConstantExpr::getMul(Scale, cast<Constant>(AllocSize));
401 // Multiply type size by the array size...
403 AllocSize = BinaryOperator::CreateMul(ArraySize, AllocSize,
404 "mallocsize", InsertBefore);
406 AllocSize = BinaryOperator::CreateMul(ArraySize, AllocSize,
407 "mallocsize", InsertAtEnd);
411 assert(AllocSize->getType() == IntPtrTy && "malloc arg is wrong size");
412 // Create the call to Malloc.
413 BasicBlock* BB = InsertBefore ? InsertBefore->getParent() : InsertAtEnd;
414 Module* M = BB->getParent()->getParent();
415 Type *BPTy = Type::getInt8PtrTy(BB->getContext());
416 Value *MallocFunc = MallocF;
418 // prototype malloc as "void *malloc(size_t)"
419 MallocFunc = M->getOrInsertFunction("malloc", BPTy, IntPtrTy, nullptr);
420 PointerType *AllocPtrType = PointerType::getUnqual(AllocTy);
421 CallInst *MCall = nullptr;
422 Instruction *Result = nullptr;
424 MCall = CallInst::Create(MallocFunc, AllocSize, "malloccall", InsertBefore);
426 if (Result->getType() != AllocPtrType)
427 // Create a cast instruction to convert to the right type...
428 Result = new BitCastInst(MCall, AllocPtrType, Name, InsertBefore);
430 MCall = CallInst::Create(MallocFunc, AllocSize, "malloccall");
432 if (Result->getType() != AllocPtrType) {
433 InsertAtEnd->getInstList().push_back(MCall);
434 // Create a cast instruction to convert to the right type...
435 Result = new BitCastInst(MCall, AllocPtrType, Name);
438 MCall->setTailCall();
439 if (Function *F = dyn_cast<Function>(MallocFunc)) {
440 MCall->setCallingConv(F->getCallingConv());
441 if (!F->doesNotAlias(0)) F->setDoesNotAlias(0);
443 assert(!MCall->getType()->isVoidTy() && "Malloc has void return type");
448 /// CreateMalloc - Generate the IR for a call to malloc:
449 /// 1. Compute the malloc call's argument as the specified type's size,
450 /// possibly multiplied by the array size if the array size is not
452 /// 2. Call malloc with that argument.
453 /// 3. Bitcast the result of the malloc call to the specified type.
454 Instruction *CallInst::CreateMalloc(Instruction *InsertBefore,
455 Type *IntPtrTy, Type *AllocTy,
456 Value *AllocSize, Value *ArraySize,
459 return createMalloc(InsertBefore, nullptr, IntPtrTy, AllocTy, AllocSize,
460 ArraySize, MallocF, Name);
463 /// CreateMalloc - Generate the IR for a call to malloc:
464 /// 1. Compute the malloc call's argument as the specified type's size,
465 /// possibly multiplied by the array size if the array size is not
467 /// 2. Call malloc with that argument.
468 /// 3. Bitcast the result of the malloc call to the specified type.
469 /// Note: This function does not add the bitcast to the basic block, that is the
470 /// responsibility of the caller.
471 Instruction *CallInst::CreateMalloc(BasicBlock *InsertAtEnd,
472 Type *IntPtrTy, Type *AllocTy,
473 Value *AllocSize, Value *ArraySize,
474 Function *MallocF, const Twine &Name) {
475 return createMalloc(nullptr, InsertAtEnd, IntPtrTy, AllocTy, AllocSize,
476 ArraySize, MallocF, Name);
479 static Instruction* createFree(Value* Source, Instruction *InsertBefore,
480 BasicBlock *InsertAtEnd) {
481 assert(((!InsertBefore && InsertAtEnd) || (InsertBefore && !InsertAtEnd)) &&
482 "createFree needs either InsertBefore or InsertAtEnd");
483 assert(Source->getType()->isPointerTy() &&
484 "Can not free something of nonpointer type!");
486 BasicBlock* BB = InsertBefore ? InsertBefore->getParent() : InsertAtEnd;
487 Module* M = BB->getParent()->getParent();
489 Type *VoidTy = Type::getVoidTy(M->getContext());
490 Type *IntPtrTy = Type::getInt8PtrTy(M->getContext());
491 // prototype free as "void free(void*)"
492 Value *FreeFunc = M->getOrInsertFunction("free", VoidTy, IntPtrTy, nullptr);
493 CallInst* Result = nullptr;
494 Value *PtrCast = Source;
496 if (Source->getType() != IntPtrTy)
497 PtrCast = new BitCastInst(Source, IntPtrTy, "", InsertBefore);
498 Result = CallInst::Create(FreeFunc, PtrCast, "", InsertBefore);
500 if (Source->getType() != IntPtrTy)
501 PtrCast = new BitCastInst(Source, IntPtrTy, "", InsertAtEnd);
502 Result = CallInst::Create(FreeFunc, PtrCast, "");
504 Result->setTailCall();
505 if (Function *F = dyn_cast<Function>(FreeFunc))
506 Result->setCallingConv(F->getCallingConv());
511 /// CreateFree - Generate the IR for a call to the builtin free function.
512 Instruction * CallInst::CreateFree(Value* Source, Instruction *InsertBefore) {
513 return createFree(Source, InsertBefore, nullptr);
516 /// CreateFree - Generate the IR for a call to the builtin free function.
517 /// Note: This function does not add the call to the basic block, that is the
518 /// responsibility of the caller.
519 Instruction* CallInst::CreateFree(Value* Source, BasicBlock *InsertAtEnd) {
520 Instruction* FreeCall = createFree(Source, nullptr, InsertAtEnd);
521 assert(FreeCall && "CreateFree did not create a CallInst");
525 //===----------------------------------------------------------------------===//
526 // InvokeInst Implementation
527 //===----------------------------------------------------------------------===//
529 void InvokeInst::init(FunctionType *FTy, Value *Fn, BasicBlock *IfNormal,
530 BasicBlock *IfException, ArrayRef<Value *> Args,
531 ArrayRef<OperandBundleDef> Bundles,
532 const Twine &NameStr) {
535 assert(getNumOperands() == 3 + Args.size() + CountBundleInputs(Bundles) &&
536 "NumOperands not set up?");
539 Op<-1>() = IfException;
542 assert(((Args.size() == FTy->getNumParams()) ||
543 (FTy->isVarArg() && Args.size() > FTy->getNumParams())) &&
544 "Invoking a function with bad signature");
546 for (unsigned i = 0, e = Args.size(); i != e; i++)
547 assert((i >= FTy->getNumParams() ||
548 FTy->getParamType(i) == Args[i]->getType()) &&
549 "Invoking a function with a bad signature!");
552 std::copy(Args.begin(), Args.end(), op_begin());
554 auto It = populateBundleOperandInfos(Bundles, Args.size());
556 assert(It + 3 == op_end() && "Should add up!");
561 InvokeInst::InvokeInst(const InvokeInst &II)
562 : TerminatorInst(II.getType(), Instruction::Invoke,
563 OperandTraits<InvokeInst>::op_end(this) -
565 II.getNumOperands()),
566 AttributeList(II.AttributeList), FTy(II.FTy) {
567 setCallingConv(II.getCallingConv());
568 std::copy(II.op_begin(), II.op_end(), op_begin());
569 std::copy(II.bundle_op_info_begin(), II.bundle_op_info_end(),
570 bundle_op_info_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))
588 // Operand bundles override attributes on the called function, but don't
589 // override attributes directly present on the invoke instruction.
590 if (isFnAttrDisallowedByOpBundle(A))
593 if (const Function *F = getCalledFunction())
594 return F->getAttributes().hasAttribute(AttributeSet::FunctionIndex, A);
598 bool InvokeInst::paramHasAttr(unsigned i, Attribute::AttrKind A) const {
599 assert(i < (getNumArgOperands() + 1) && "Param index out of bounds!");
601 if (AttributeList.hasAttribute(i, A))
603 if (const Function *F = getCalledFunction())
604 return F->getAttributes().hasAttribute(i, A);
608 bool InvokeInst::dataOperandHasImpliedAttr(unsigned i,
609 Attribute::AttrKind A) const {
610 // There are getNumOperands() - 3 data operands. The last three operands are
611 // the callee and the two successor basic blocks.
612 assert(i < (getNumOperands() - 2) && "Data operand index out of bounds!");
614 // The attribute A can either be directly specified, if the operand in
615 // question is an invoke argument; or be indirectly implied by the kind of its
616 // containing operand bundle, if the operand is a bundle operand.
618 if (i < (getNumArgOperands() + 1))
619 return paramHasAttr(i, A);
621 assert(hasOperandBundles() && i >= (getBundleOperandsStartIndex() + 1) &&
622 "Must be either an invoke argument or an operand bundle!");
623 return getOperandBundleForOperand(i - 1).operandsHaveAttr(A);
626 void InvokeInst::addAttribute(unsigned i, Attribute::AttrKind attr) {
627 AttributeSet PAL = getAttributes();
628 PAL = PAL.addAttribute(getContext(), i, attr);
632 void InvokeInst::removeAttribute(unsigned i, Attribute attr) {
633 AttributeSet PAL = getAttributes();
635 PAL = PAL.removeAttributes(getContext(), i,
636 AttributeSet::get(getContext(), i, B));
640 void InvokeInst::addDereferenceableAttr(unsigned i, uint64_t Bytes) {
641 AttributeSet PAL = getAttributes();
642 PAL = PAL.addDereferenceableAttr(getContext(), i, Bytes);
646 void InvokeInst::addDereferenceableOrNullAttr(unsigned i, uint64_t Bytes) {
647 AttributeSet PAL = getAttributes();
648 PAL = PAL.addDereferenceableOrNullAttr(getContext(), i, Bytes);
652 LandingPadInst *InvokeInst::getLandingPadInst() const {
653 return cast<LandingPadInst>(getUnwindDest()->getFirstNonPHI());
656 //===----------------------------------------------------------------------===//
657 // ReturnInst Implementation
658 //===----------------------------------------------------------------------===//
660 ReturnInst::ReturnInst(const ReturnInst &RI)
661 : TerminatorInst(Type::getVoidTy(RI.getContext()), Instruction::Ret,
662 OperandTraits<ReturnInst>::op_end(this) -
664 RI.getNumOperands()) {
665 if (RI.getNumOperands())
666 Op<0>() = RI.Op<0>();
667 SubclassOptionalData = RI.SubclassOptionalData;
670 ReturnInst::ReturnInst(LLVMContext &C, Value *retVal, Instruction *InsertBefore)
671 : TerminatorInst(Type::getVoidTy(C), Instruction::Ret,
672 OperandTraits<ReturnInst>::op_end(this) - !!retVal, !!retVal,
677 ReturnInst::ReturnInst(LLVMContext &C, Value *retVal, BasicBlock *InsertAtEnd)
678 : TerminatorInst(Type::getVoidTy(C), Instruction::Ret,
679 OperandTraits<ReturnInst>::op_end(this) - !!retVal, !!retVal,
684 ReturnInst::ReturnInst(LLVMContext &Context, BasicBlock *InsertAtEnd)
685 : TerminatorInst(Type::getVoidTy(Context), Instruction::Ret,
686 OperandTraits<ReturnInst>::op_end(this), 0, InsertAtEnd) {
689 unsigned ReturnInst::getNumSuccessorsV() const {
690 return getNumSuccessors();
693 /// Out-of-line ReturnInst method, put here so the C++ compiler can choose to
694 /// emit the vtable for the class in this translation unit.
695 void ReturnInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
696 llvm_unreachable("ReturnInst has no successors!");
699 BasicBlock *ReturnInst::getSuccessorV(unsigned idx) const {
700 llvm_unreachable("ReturnInst has no successors!");
703 ReturnInst::~ReturnInst() {
706 //===----------------------------------------------------------------------===//
707 // ResumeInst Implementation
708 //===----------------------------------------------------------------------===//
710 ResumeInst::ResumeInst(const ResumeInst &RI)
711 : TerminatorInst(Type::getVoidTy(RI.getContext()), Instruction::Resume,
712 OperandTraits<ResumeInst>::op_begin(this), 1) {
713 Op<0>() = RI.Op<0>();
716 ResumeInst::ResumeInst(Value *Exn, Instruction *InsertBefore)
717 : TerminatorInst(Type::getVoidTy(Exn->getContext()), Instruction::Resume,
718 OperandTraits<ResumeInst>::op_begin(this), 1, InsertBefore) {
722 ResumeInst::ResumeInst(Value *Exn, BasicBlock *InsertAtEnd)
723 : TerminatorInst(Type::getVoidTy(Exn->getContext()), Instruction::Resume,
724 OperandTraits<ResumeInst>::op_begin(this), 1, InsertAtEnd) {
728 unsigned ResumeInst::getNumSuccessorsV() const {
729 return getNumSuccessors();
732 void ResumeInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
733 llvm_unreachable("ResumeInst has no successors!");
736 BasicBlock *ResumeInst::getSuccessorV(unsigned idx) const {
737 llvm_unreachable("ResumeInst has no successors!");
740 //===----------------------------------------------------------------------===//
741 // CleanupEndPadInst Implementation
742 //===----------------------------------------------------------------------===//
744 CleanupEndPadInst::CleanupEndPadInst(const CleanupEndPadInst &CEPI)
745 : TerminatorInst(CEPI.getType(), Instruction::CleanupEndPad,
746 OperandTraits<CleanupEndPadInst>::op_end(this) -
747 CEPI.getNumOperands(),
748 CEPI.getNumOperands()) {
749 setInstructionSubclassData(CEPI.getSubclassDataFromInstruction());
750 setCleanupPad(CEPI.getCleanupPad());
751 if (BasicBlock *UnwindDest = CEPI.getUnwindDest())
752 setUnwindDest(UnwindDest);
755 void CleanupEndPadInst::init(CleanupPadInst *CleanupPad, BasicBlock *UnwindBB) {
756 setCleanupPad(CleanupPad);
758 setInstructionSubclassData(getSubclassDataFromInstruction() | 1);
759 setUnwindDest(UnwindBB);
763 CleanupEndPadInst::CleanupEndPadInst(CleanupPadInst *CleanupPad,
764 BasicBlock *UnwindBB, unsigned Values,
765 Instruction *InsertBefore)
766 : TerminatorInst(Type::getVoidTy(CleanupPad->getContext()),
767 Instruction::CleanupEndPad,
768 OperandTraits<CleanupEndPadInst>::op_end(this) - Values,
769 Values, InsertBefore) {
770 init(CleanupPad, UnwindBB);
773 CleanupEndPadInst::CleanupEndPadInst(CleanupPadInst *CleanupPad,
774 BasicBlock *UnwindBB, unsigned Values,
775 BasicBlock *InsertAtEnd)
776 : TerminatorInst(Type::getVoidTy(CleanupPad->getContext()),
777 Instruction::CleanupEndPad,
778 OperandTraits<CleanupEndPadInst>::op_end(this) - Values,
779 Values, InsertAtEnd) {
780 init(CleanupPad, UnwindBB);
783 BasicBlock *CleanupEndPadInst::getSuccessorV(unsigned Idx) const {
785 return getUnwindDest();
787 unsigned CleanupEndPadInst::getNumSuccessorsV() const {
788 return getNumSuccessors();
790 void CleanupEndPadInst::setSuccessorV(unsigned Idx, BasicBlock *B) {
795 //===----------------------------------------------------------------------===//
796 // CleanupReturnInst Implementation
797 //===----------------------------------------------------------------------===//
799 CleanupReturnInst::CleanupReturnInst(const CleanupReturnInst &CRI)
800 : TerminatorInst(CRI.getType(), Instruction::CleanupRet,
801 OperandTraits<CleanupReturnInst>::op_end(this) -
802 CRI.getNumOperands(),
803 CRI.getNumOperands()) {
804 setInstructionSubclassData(CRI.getSubclassDataFromInstruction());
805 Op<-1>() = CRI.Op<-1>();
806 if (CRI.hasUnwindDest())
807 Op<-2>() = CRI.Op<-2>();
810 void CleanupReturnInst::init(CleanupPadInst *CleanupPad, BasicBlock *UnwindBB) {
812 setInstructionSubclassData(getSubclassDataFromInstruction() | 1);
814 Op<-1>() = CleanupPad;
819 CleanupReturnInst::CleanupReturnInst(CleanupPadInst *CleanupPad,
820 BasicBlock *UnwindBB, unsigned Values,
821 Instruction *InsertBefore)
822 : TerminatorInst(Type::getVoidTy(CleanupPad->getContext()),
823 Instruction::CleanupRet,
824 OperandTraits<CleanupReturnInst>::op_end(this) - Values,
825 Values, InsertBefore) {
826 init(CleanupPad, UnwindBB);
829 CleanupReturnInst::CleanupReturnInst(CleanupPadInst *CleanupPad,
830 BasicBlock *UnwindBB, unsigned Values,
831 BasicBlock *InsertAtEnd)
832 : TerminatorInst(Type::getVoidTy(CleanupPad->getContext()),
833 Instruction::CleanupRet,
834 OperandTraits<CleanupReturnInst>::op_end(this) - Values,
835 Values, InsertAtEnd) {
836 init(CleanupPad, UnwindBB);
839 BasicBlock *CleanupReturnInst::getSuccessorV(unsigned Idx) const {
841 return getUnwindDest();
843 unsigned CleanupReturnInst::getNumSuccessorsV() const {
844 return getNumSuccessors();
846 void CleanupReturnInst::setSuccessorV(unsigned Idx, BasicBlock *B) {
851 //===----------------------------------------------------------------------===//
852 // CatchEndPadInst Implementation
853 //===----------------------------------------------------------------------===//
855 CatchEndPadInst::CatchEndPadInst(const CatchEndPadInst &CRI)
856 : TerminatorInst(CRI.getType(), Instruction::CatchEndPad,
857 OperandTraits<CatchEndPadInst>::op_end(this) -
858 CRI.getNumOperands(),
859 CRI.getNumOperands()) {
860 setInstructionSubclassData(CRI.getSubclassDataFromInstruction());
861 if (BasicBlock *UnwindDest = CRI.getUnwindDest())
862 setUnwindDest(UnwindDest);
865 void CatchEndPadInst::init(BasicBlock *UnwindBB) {
867 setInstructionSubclassData(getSubclassDataFromInstruction() | 1);
868 setUnwindDest(UnwindBB);
872 CatchEndPadInst::CatchEndPadInst(LLVMContext &C, BasicBlock *UnwindBB,
873 unsigned Values, Instruction *InsertBefore)
874 : TerminatorInst(Type::getVoidTy(C), Instruction::CatchEndPad,
875 OperandTraits<CatchEndPadInst>::op_end(this) - Values,
876 Values, InsertBefore) {
880 CatchEndPadInst::CatchEndPadInst(LLVMContext &C, BasicBlock *UnwindBB,
881 unsigned Values, BasicBlock *InsertAtEnd)
882 : TerminatorInst(Type::getVoidTy(C), Instruction::CatchEndPad,
883 OperandTraits<CatchEndPadInst>::op_end(this) - Values,
884 Values, InsertAtEnd) {
888 BasicBlock *CatchEndPadInst::getSuccessorV(unsigned Idx) const {
890 return getUnwindDest();
892 unsigned CatchEndPadInst::getNumSuccessorsV() const {
893 return getNumSuccessors();
895 void CatchEndPadInst::setSuccessorV(unsigned Idx, BasicBlock *B) {
900 //===----------------------------------------------------------------------===//
901 // CatchReturnInst Implementation
902 //===----------------------------------------------------------------------===//
903 void CatchReturnInst::init(CatchPadInst *CatchPad, BasicBlock *BB) {
908 CatchReturnInst::CatchReturnInst(const CatchReturnInst &CRI)
909 : TerminatorInst(Type::getVoidTy(CRI.getContext()), Instruction::CatchRet,
910 OperandTraits<CatchReturnInst>::op_begin(this), 2) {
911 Op<0>() = CRI.Op<0>();
912 Op<1>() = CRI.Op<1>();
915 CatchReturnInst::CatchReturnInst(CatchPadInst *CatchPad, BasicBlock *BB,
916 Instruction *InsertBefore)
917 : TerminatorInst(Type::getVoidTy(BB->getContext()), Instruction::CatchRet,
918 OperandTraits<CatchReturnInst>::op_begin(this), 2,
923 CatchReturnInst::CatchReturnInst(CatchPadInst *CatchPad, BasicBlock *BB,
924 BasicBlock *InsertAtEnd)
925 : TerminatorInst(Type::getVoidTy(BB->getContext()), Instruction::CatchRet,
926 OperandTraits<CatchReturnInst>::op_begin(this), 2,
931 BasicBlock *CatchReturnInst::getSuccessorV(unsigned Idx) const {
932 assert(Idx < getNumSuccessors() && "Successor # out of range for catchret!");
933 return getSuccessor();
935 unsigned CatchReturnInst::getNumSuccessorsV() const {
936 return getNumSuccessors();
938 void CatchReturnInst::setSuccessorV(unsigned Idx, BasicBlock *B) {
939 assert(Idx < getNumSuccessors() && "Successor # out of range for catchret!");
943 //===----------------------------------------------------------------------===//
944 // CatchPadInst Implementation
945 //===----------------------------------------------------------------------===//
946 void CatchPadInst::init(BasicBlock *IfNormal, BasicBlock *IfException,
947 ArrayRef<Value *> Args, const Twine &NameStr) {
948 assert(getNumOperands() == 2 + Args.size() && "NumOperands not set up?");
950 Op<-1>() = IfException;
951 std::copy(Args.begin(), Args.end(), op_begin());
955 CatchPadInst::CatchPadInst(const CatchPadInst &CPI)
956 : TerminatorInst(CPI.getType(), Instruction::CatchPad,
957 OperandTraits<CatchPadInst>::op_end(this) -
958 CPI.getNumOperands(),
959 CPI.getNumOperands()) {
960 std::copy(CPI.op_begin(), CPI.op_end(), op_begin());
963 CatchPadInst::CatchPadInst(BasicBlock *IfNormal, BasicBlock *IfException,
964 ArrayRef<Value *> Args, unsigned Values,
965 const Twine &NameStr, Instruction *InsertBefore)
966 : TerminatorInst(Type::getTokenTy(IfNormal->getContext()),
967 Instruction::CatchPad,
968 OperandTraits<CatchPadInst>::op_end(this) - Values, Values,
970 init(IfNormal, IfException, Args, NameStr);
973 CatchPadInst::CatchPadInst(BasicBlock *IfNormal, BasicBlock *IfException,
974 ArrayRef<Value *> Args, unsigned Values,
975 const Twine &NameStr, BasicBlock *InsertAtEnd)
976 : TerminatorInst(Type::getTokenTy(IfNormal->getContext()),
977 Instruction::CatchPad,
978 OperandTraits<CatchPadInst>::op_end(this) - Values, Values,
980 init(IfNormal, IfException, Args, NameStr);
983 BasicBlock *CatchPadInst::getSuccessorV(unsigned Idx) const {
984 return getSuccessor(Idx);
986 unsigned CatchPadInst::getNumSuccessorsV() const {
987 return getNumSuccessors();
989 void CatchPadInst::setSuccessorV(unsigned Idx, BasicBlock *B) {
990 return setSuccessor(Idx, B);
993 //===----------------------------------------------------------------------===//
994 // TerminatePadInst Implementation
995 //===----------------------------------------------------------------------===//
996 void TerminatePadInst::init(BasicBlock *BB, ArrayRef<Value *> Args) {
998 setInstructionSubclassData(getSubclassDataFromInstruction() | 1);
1001 std::copy(Args.begin(), Args.end(), op_begin());
1004 TerminatePadInst::TerminatePadInst(const TerminatePadInst &TPI)
1005 : TerminatorInst(TPI.getType(), Instruction::TerminatePad,
1006 OperandTraits<TerminatePadInst>::op_end(this) -
1007 TPI.getNumOperands(),
1008 TPI.getNumOperands()) {
1009 setInstructionSubclassData(TPI.getSubclassDataFromInstruction());
1010 std::copy(TPI.op_begin(), TPI.op_end(), op_begin());
1013 TerminatePadInst::TerminatePadInst(LLVMContext &C, BasicBlock *BB,
1014 ArrayRef<Value *> Args, unsigned Values,
1015 Instruction *InsertBefore)
1016 : TerminatorInst(Type::getVoidTy(C), Instruction::TerminatePad,
1017 OperandTraits<TerminatePadInst>::op_end(this) - Values,
1018 Values, InsertBefore) {
1022 TerminatePadInst::TerminatePadInst(LLVMContext &C, BasicBlock *BB,
1023 ArrayRef<Value *> Args, unsigned Values,
1024 BasicBlock *InsertAtEnd)
1025 : TerminatorInst(Type::getVoidTy(C), Instruction::TerminatePad,
1026 OperandTraits<TerminatePadInst>::op_end(this) - Values,
1027 Values, InsertAtEnd) {
1031 BasicBlock *TerminatePadInst::getSuccessorV(unsigned Idx) const {
1033 return getUnwindDest();
1035 unsigned TerminatePadInst::getNumSuccessorsV() const {
1036 return getNumSuccessors();
1038 void TerminatePadInst::setSuccessorV(unsigned Idx, BasicBlock *B) {
1040 return setUnwindDest(B);
1043 //===----------------------------------------------------------------------===//
1044 // CleanupPadInst Implementation
1045 //===----------------------------------------------------------------------===//
1046 void CleanupPadInst::init(ArrayRef<Value *> Args, const Twine &NameStr) {
1047 assert(getNumOperands() == Args.size() && "NumOperands not set up?");
1048 std::copy(Args.begin(), Args.end(), op_begin());
1052 CleanupPadInst::CleanupPadInst(const CleanupPadInst &CPI)
1053 : Instruction(CPI.getType(), Instruction::CleanupPad,
1054 OperandTraits<CleanupPadInst>::op_end(this) -
1055 CPI.getNumOperands(),
1056 CPI.getNumOperands()) {
1057 std::copy(CPI.op_begin(), CPI.op_end(), op_begin());
1060 CleanupPadInst::CleanupPadInst(LLVMContext &C, ArrayRef<Value *> Args,
1061 const Twine &NameStr, Instruction *InsertBefore)
1062 : Instruction(Type::getTokenTy(C), Instruction::CleanupPad,
1063 OperandTraits<CleanupPadInst>::op_end(this) - Args.size(),
1064 Args.size(), InsertBefore) {
1065 init(Args, NameStr);
1068 CleanupPadInst::CleanupPadInst(LLVMContext &C, ArrayRef<Value *> Args,
1069 const Twine &NameStr, BasicBlock *InsertAtEnd)
1070 : Instruction(Type::getTokenTy(C), Instruction::CleanupPad,
1071 OperandTraits<CleanupPadInst>::op_end(this) - Args.size(),
1072 Args.size(), InsertAtEnd) {
1073 init(Args, NameStr);
1076 //===----------------------------------------------------------------------===//
1077 // UnreachableInst Implementation
1078 //===----------------------------------------------------------------------===//
1080 UnreachableInst::UnreachableInst(LLVMContext &Context,
1081 Instruction *InsertBefore)
1082 : TerminatorInst(Type::getVoidTy(Context), Instruction::Unreachable,
1083 nullptr, 0, InsertBefore) {
1085 UnreachableInst::UnreachableInst(LLVMContext &Context, BasicBlock *InsertAtEnd)
1086 : TerminatorInst(Type::getVoidTy(Context), Instruction::Unreachable,
1087 nullptr, 0, InsertAtEnd) {
1090 unsigned UnreachableInst::getNumSuccessorsV() const {
1091 return getNumSuccessors();
1094 void UnreachableInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
1095 llvm_unreachable("UnreachableInst has no successors!");
1098 BasicBlock *UnreachableInst::getSuccessorV(unsigned idx) const {
1099 llvm_unreachable("UnreachableInst has no successors!");
1102 //===----------------------------------------------------------------------===//
1103 // BranchInst Implementation
1104 //===----------------------------------------------------------------------===//
1106 void BranchInst::AssertOK() {
1107 if (isConditional())
1108 assert(getCondition()->getType()->isIntegerTy(1) &&
1109 "May only branch on boolean predicates!");
1112 BranchInst::BranchInst(BasicBlock *IfTrue, Instruction *InsertBefore)
1113 : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
1114 OperandTraits<BranchInst>::op_end(this) - 1,
1116 assert(IfTrue && "Branch destination may not be null!");
1119 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
1120 Instruction *InsertBefore)
1121 : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
1122 OperandTraits<BranchInst>::op_end(this) - 3,
1132 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *InsertAtEnd)
1133 : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
1134 OperandTraits<BranchInst>::op_end(this) - 1,
1136 assert(IfTrue && "Branch destination may not be null!");
1140 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
1141 BasicBlock *InsertAtEnd)
1142 : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
1143 OperandTraits<BranchInst>::op_end(this) - 3,
1154 BranchInst::BranchInst(const BranchInst &BI) :
1155 TerminatorInst(Type::getVoidTy(BI.getContext()), Instruction::Br,
1156 OperandTraits<BranchInst>::op_end(this) - BI.getNumOperands(),
1157 BI.getNumOperands()) {
1158 Op<-1>() = BI.Op<-1>();
1159 if (BI.getNumOperands() != 1) {
1160 assert(BI.getNumOperands() == 3 && "BR can have 1 or 3 operands!");
1161 Op<-3>() = BI.Op<-3>();
1162 Op<-2>() = BI.Op<-2>();
1164 SubclassOptionalData = BI.SubclassOptionalData;
1167 void BranchInst::swapSuccessors() {
1168 assert(isConditional() &&
1169 "Cannot swap successors of an unconditional branch");
1170 Op<-1>().swap(Op<-2>());
1172 // Update profile metadata if present and it matches our structural
1174 MDNode *ProfileData = getMetadata(LLVMContext::MD_prof);
1175 if (!ProfileData || ProfileData->getNumOperands() != 3)
1178 // The first operand is the name. Fetch them backwards and build a new one.
1179 Metadata *Ops[] = {ProfileData->getOperand(0), ProfileData->getOperand(2),
1180 ProfileData->getOperand(1)};
1181 setMetadata(LLVMContext::MD_prof,
1182 MDNode::get(ProfileData->getContext(), Ops));
1185 BasicBlock *BranchInst::getSuccessorV(unsigned idx) const {
1186 return getSuccessor(idx);
1188 unsigned BranchInst::getNumSuccessorsV() const {
1189 return getNumSuccessors();
1191 void BranchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
1192 setSuccessor(idx, B);
1196 //===----------------------------------------------------------------------===//
1197 // AllocaInst Implementation
1198 //===----------------------------------------------------------------------===//
1200 static Value *getAISize(LLVMContext &Context, Value *Amt) {
1202 Amt = ConstantInt::get(Type::getInt32Ty(Context), 1);
1204 assert(!isa<BasicBlock>(Amt) &&
1205 "Passed basic block into allocation size parameter! Use other ctor");
1206 assert(Amt->getType()->isIntegerTy() &&
1207 "Allocation array size is not an integer!");
1212 AllocaInst::AllocaInst(Type *Ty, const Twine &Name, Instruction *InsertBefore)
1213 : AllocaInst(Ty, /*ArraySize=*/nullptr, Name, InsertBefore) {}
1215 AllocaInst::AllocaInst(Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd)
1216 : AllocaInst(Ty, /*ArraySize=*/nullptr, Name, InsertAtEnd) {}
1218 AllocaInst::AllocaInst(Type *Ty, Value *ArraySize, const Twine &Name,
1219 Instruction *InsertBefore)
1220 : AllocaInst(Ty, ArraySize, /*Align=*/0, Name, InsertBefore) {}
1222 AllocaInst::AllocaInst(Type *Ty, Value *ArraySize, const Twine &Name,
1223 BasicBlock *InsertAtEnd)
1224 : AllocaInst(Ty, ArraySize, /*Align=*/0, Name, InsertAtEnd) {}
1226 AllocaInst::AllocaInst(Type *Ty, Value *ArraySize, unsigned Align,
1227 const Twine &Name, Instruction *InsertBefore)
1228 : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
1229 getAISize(Ty->getContext(), ArraySize), InsertBefore),
1231 setAlignment(Align);
1232 assert(!Ty->isVoidTy() && "Cannot allocate void!");
1236 AllocaInst::AllocaInst(Type *Ty, Value *ArraySize, unsigned Align,
1237 const Twine &Name, BasicBlock *InsertAtEnd)
1238 : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
1239 getAISize(Ty->getContext(), ArraySize), InsertAtEnd),
1241 setAlignment(Align);
1242 assert(!Ty->isVoidTy() && "Cannot allocate void!");
1246 // Out of line virtual method, so the vtable, etc has a home.
1247 AllocaInst::~AllocaInst() {
1250 void AllocaInst::setAlignment(unsigned Align) {
1251 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
1252 assert(Align <= MaximumAlignment &&
1253 "Alignment is greater than MaximumAlignment!");
1254 setInstructionSubclassData((getSubclassDataFromInstruction() & ~31) |
1255 (Log2_32(Align) + 1));
1256 assert(getAlignment() == Align && "Alignment representation error!");
1259 bool AllocaInst::isArrayAllocation() const {
1260 if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(0)))
1261 return !CI->isOne();
1265 /// isStaticAlloca - Return true if this alloca is in the entry block of the
1266 /// function and is a constant size. If so, the code generator will fold it
1267 /// into the prolog/epilog code, so it is basically free.
1268 bool AllocaInst::isStaticAlloca() const {
1269 // Must be constant size.
1270 if (!isa<ConstantInt>(getArraySize())) return false;
1272 // Must be in the entry block.
1273 const BasicBlock *Parent = getParent();
1274 return Parent == &Parent->getParent()->front() && !isUsedWithInAlloca();
1277 //===----------------------------------------------------------------------===//
1278 // LoadInst Implementation
1279 //===----------------------------------------------------------------------===//
1281 void LoadInst::AssertOK() {
1282 assert(getOperand(0)->getType()->isPointerTy() &&
1283 "Ptr must have pointer type.");
1284 assert(!(isAtomic() && getAlignment() == 0) &&
1285 "Alignment required for atomic load");
1288 LoadInst::LoadInst(Value *Ptr, const Twine &Name, Instruction *InsertBef)
1289 : LoadInst(Ptr, Name, /*isVolatile=*/false, InsertBef) {}
1291 LoadInst::LoadInst(Value *Ptr, const Twine &Name, BasicBlock *InsertAE)
1292 : LoadInst(Ptr, Name, /*isVolatile=*/false, InsertAE) {}
1294 LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name, bool isVolatile,
1295 Instruction *InsertBef)
1296 : LoadInst(Ty, Ptr, Name, isVolatile, /*Align=*/0, InsertBef) {}
1298 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
1299 BasicBlock *InsertAE)
1300 : LoadInst(Ptr, Name, isVolatile, /*Align=*/0, InsertAE) {}
1302 LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name, bool isVolatile,
1303 unsigned Align, Instruction *InsertBef)
1304 : LoadInst(Ty, Ptr, Name, isVolatile, Align, NotAtomic, CrossThread,
1307 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
1308 unsigned Align, BasicBlock *InsertAE)
1309 : LoadInst(Ptr, Name, isVolatile, Align, NotAtomic, CrossThread, InsertAE) {
1312 LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name, bool isVolatile,
1313 unsigned Align, AtomicOrdering Order,
1314 SynchronizationScope SynchScope, Instruction *InsertBef)
1315 : UnaryInstruction(Ty, Load, Ptr, InsertBef) {
1316 assert(Ty == cast<PointerType>(Ptr->getType())->getElementType());
1317 setVolatile(isVolatile);
1318 setAlignment(Align);
1319 setAtomic(Order, SynchScope);
1324 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
1325 unsigned Align, AtomicOrdering Order,
1326 SynchronizationScope SynchScope,
1327 BasicBlock *InsertAE)
1328 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1329 Load, Ptr, InsertAE) {
1330 setVolatile(isVolatile);
1331 setAlignment(Align);
1332 setAtomic(Order, SynchScope);
1337 LoadInst::LoadInst(Value *Ptr, const char *Name, Instruction *InsertBef)
1338 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1339 Load, Ptr, InsertBef) {
1342 setAtomic(NotAtomic);
1344 if (Name && Name[0]) setName(Name);
1347 LoadInst::LoadInst(Value *Ptr, const char *Name, BasicBlock *InsertAE)
1348 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1349 Load, Ptr, InsertAE) {
1352 setAtomic(NotAtomic);
1354 if (Name && Name[0]) setName(Name);
1357 LoadInst::LoadInst(Type *Ty, Value *Ptr, const char *Name, bool isVolatile,
1358 Instruction *InsertBef)
1359 : UnaryInstruction(Ty, Load, Ptr, InsertBef) {
1360 assert(Ty == cast<PointerType>(Ptr->getType())->getElementType());
1361 setVolatile(isVolatile);
1363 setAtomic(NotAtomic);
1365 if (Name && Name[0]) setName(Name);
1368 LoadInst::LoadInst(Value *Ptr, const char *Name, bool isVolatile,
1369 BasicBlock *InsertAE)
1370 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1371 Load, Ptr, InsertAE) {
1372 setVolatile(isVolatile);
1374 setAtomic(NotAtomic);
1376 if (Name && Name[0]) setName(Name);
1379 void LoadInst::setAlignment(unsigned Align) {
1380 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
1381 assert(Align <= MaximumAlignment &&
1382 "Alignment is greater than MaximumAlignment!");
1383 setInstructionSubclassData((getSubclassDataFromInstruction() & ~(31 << 1)) |
1384 ((Log2_32(Align)+1)<<1));
1385 assert(getAlignment() == Align && "Alignment representation error!");
1388 //===----------------------------------------------------------------------===//
1389 // StoreInst Implementation
1390 //===----------------------------------------------------------------------===//
1392 void StoreInst::AssertOK() {
1393 assert(getOperand(0) && getOperand(1) && "Both operands must be non-null!");
1394 assert(getOperand(1)->getType()->isPointerTy() &&
1395 "Ptr must have pointer type!");
1396 assert(getOperand(0)->getType() ==
1397 cast<PointerType>(getOperand(1)->getType())->getElementType()
1398 && "Ptr must be a pointer to Val type!");
1399 assert(!(isAtomic() && getAlignment() == 0) &&
1400 "Alignment required for atomic store");
1403 StoreInst::StoreInst(Value *val, Value *addr, Instruction *InsertBefore)
1404 : StoreInst(val, addr, /*isVolatile=*/false, InsertBefore) {}
1406 StoreInst::StoreInst(Value *val, Value *addr, BasicBlock *InsertAtEnd)
1407 : StoreInst(val, addr, /*isVolatile=*/false, InsertAtEnd) {}
1409 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1410 Instruction *InsertBefore)
1411 : StoreInst(val, addr, isVolatile, /*Align=*/0, InsertBefore) {}
1413 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1414 BasicBlock *InsertAtEnd)
1415 : StoreInst(val, addr, isVolatile, /*Align=*/0, InsertAtEnd) {}
1417 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile, unsigned Align,
1418 Instruction *InsertBefore)
1419 : StoreInst(val, addr, isVolatile, Align, NotAtomic, CrossThread,
1422 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile, unsigned Align,
1423 BasicBlock *InsertAtEnd)
1424 : StoreInst(val, addr, isVolatile, Align, NotAtomic, CrossThread,
1427 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1428 unsigned Align, AtomicOrdering Order,
1429 SynchronizationScope SynchScope,
1430 Instruction *InsertBefore)
1431 : Instruction(Type::getVoidTy(val->getContext()), Store,
1432 OperandTraits<StoreInst>::op_begin(this),
1433 OperandTraits<StoreInst>::operands(this),
1437 setVolatile(isVolatile);
1438 setAlignment(Align);
1439 setAtomic(Order, SynchScope);
1443 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1444 unsigned Align, AtomicOrdering Order,
1445 SynchronizationScope SynchScope,
1446 BasicBlock *InsertAtEnd)
1447 : Instruction(Type::getVoidTy(val->getContext()), Store,
1448 OperandTraits<StoreInst>::op_begin(this),
1449 OperandTraits<StoreInst>::operands(this),
1453 setVolatile(isVolatile);
1454 setAlignment(Align);
1455 setAtomic(Order, SynchScope);
1459 void StoreInst::setAlignment(unsigned Align) {
1460 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
1461 assert(Align <= MaximumAlignment &&
1462 "Alignment is greater than MaximumAlignment!");
1463 setInstructionSubclassData((getSubclassDataFromInstruction() & ~(31 << 1)) |
1464 ((Log2_32(Align)+1) << 1));
1465 assert(getAlignment() == Align && "Alignment representation error!");
1468 //===----------------------------------------------------------------------===//
1469 // AtomicCmpXchgInst Implementation
1470 //===----------------------------------------------------------------------===//
1472 void AtomicCmpXchgInst::Init(Value *Ptr, Value *Cmp, Value *NewVal,
1473 AtomicOrdering SuccessOrdering,
1474 AtomicOrdering FailureOrdering,
1475 SynchronizationScope SynchScope) {
1479 setSuccessOrdering(SuccessOrdering);
1480 setFailureOrdering(FailureOrdering);
1481 setSynchScope(SynchScope);
1483 assert(getOperand(0) && getOperand(1) && getOperand(2) &&
1484 "All operands must be non-null!");
1485 assert(getOperand(0)->getType()->isPointerTy() &&
1486 "Ptr must have pointer type!");
1487 assert(getOperand(1)->getType() ==
1488 cast<PointerType>(getOperand(0)->getType())->getElementType()
1489 && "Ptr must be a pointer to Cmp type!");
1490 assert(getOperand(2)->getType() ==
1491 cast<PointerType>(getOperand(0)->getType())->getElementType()
1492 && "Ptr must be a pointer to NewVal type!");
1493 assert(SuccessOrdering != NotAtomic &&
1494 "AtomicCmpXchg instructions must be atomic!");
1495 assert(FailureOrdering != NotAtomic &&
1496 "AtomicCmpXchg instructions must be atomic!");
1497 assert(SuccessOrdering >= FailureOrdering &&
1498 "AtomicCmpXchg success ordering must be at least as strong as fail");
1499 assert(FailureOrdering != Release && FailureOrdering != AcquireRelease &&
1500 "AtomicCmpXchg failure ordering cannot include release semantics");
1503 AtomicCmpXchgInst::AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal,
1504 AtomicOrdering SuccessOrdering,
1505 AtomicOrdering FailureOrdering,
1506 SynchronizationScope SynchScope,
1507 Instruction *InsertBefore)
1509 StructType::get(Cmp->getType(), Type::getInt1Ty(Cmp->getContext()),
1511 AtomicCmpXchg, OperandTraits<AtomicCmpXchgInst>::op_begin(this),
1512 OperandTraits<AtomicCmpXchgInst>::operands(this), InsertBefore) {
1513 Init(Ptr, Cmp, NewVal, SuccessOrdering, FailureOrdering, SynchScope);
1516 AtomicCmpXchgInst::AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal,
1517 AtomicOrdering SuccessOrdering,
1518 AtomicOrdering FailureOrdering,
1519 SynchronizationScope SynchScope,
1520 BasicBlock *InsertAtEnd)
1522 StructType::get(Cmp->getType(), Type::getInt1Ty(Cmp->getContext()),
1524 AtomicCmpXchg, OperandTraits<AtomicCmpXchgInst>::op_begin(this),
1525 OperandTraits<AtomicCmpXchgInst>::operands(this), InsertAtEnd) {
1526 Init(Ptr, Cmp, NewVal, SuccessOrdering, FailureOrdering, SynchScope);
1529 //===----------------------------------------------------------------------===//
1530 // AtomicRMWInst Implementation
1531 //===----------------------------------------------------------------------===//
1533 void AtomicRMWInst::Init(BinOp Operation, Value *Ptr, Value *Val,
1534 AtomicOrdering Ordering,
1535 SynchronizationScope SynchScope) {
1538 setOperation(Operation);
1539 setOrdering(Ordering);
1540 setSynchScope(SynchScope);
1542 assert(getOperand(0) && getOperand(1) &&
1543 "All operands must be non-null!");
1544 assert(getOperand(0)->getType()->isPointerTy() &&
1545 "Ptr must have pointer type!");
1546 assert(getOperand(1)->getType() ==
1547 cast<PointerType>(getOperand(0)->getType())->getElementType()
1548 && "Ptr must be a pointer to Val type!");
1549 assert(Ordering != NotAtomic &&
1550 "AtomicRMW instructions must be atomic!");
1553 AtomicRMWInst::AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val,
1554 AtomicOrdering Ordering,
1555 SynchronizationScope SynchScope,
1556 Instruction *InsertBefore)
1557 : Instruction(Val->getType(), AtomicRMW,
1558 OperandTraits<AtomicRMWInst>::op_begin(this),
1559 OperandTraits<AtomicRMWInst>::operands(this),
1561 Init(Operation, Ptr, Val, Ordering, SynchScope);
1564 AtomicRMWInst::AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val,
1565 AtomicOrdering Ordering,
1566 SynchronizationScope SynchScope,
1567 BasicBlock *InsertAtEnd)
1568 : Instruction(Val->getType(), AtomicRMW,
1569 OperandTraits<AtomicRMWInst>::op_begin(this),
1570 OperandTraits<AtomicRMWInst>::operands(this),
1572 Init(Operation, Ptr, Val, Ordering, SynchScope);
1575 //===----------------------------------------------------------------------===//
1576 // FenceInst Implementation
1577 //===----------------------------------------------------------------------===//
1579 FenceInst::FenceInst(LLVMContext &C, AtomicOrdering Ordering,
1580 SynchronizationScope SynchScope,
1581 Instruction *InsertBefore)
1582 : Instruction(Type::getVoidTy(C), Fence, nullptr, 0, InsertBefore) {
1583 setOrdering(Ordering);
1584 setSynchScope(SynchScope);
1587 FenceInst::FenceInst(LLVMContext &C, AtomicOrdering Ordering,
1588 SynchronizationScope SynchScope,
1589 BasicBlock *InsertAtEnd)
1590 : Instruction(Type::getVoidTy(C), Fence, nullptr, 0, InsertAtEnd) {
1591 setOrdering(Ordering);
1592 setSynchScope(SynchScope);
1595 //===----------------------------------------------------------------------===//
1596 // GetElementPtrInst Implementation
1597 //===----------------------------------------------------------------------===//
1599 void GetElementPtrInst::init(Value *Ptr, ArrayRef<Value *> IdxList,
1600 const Twine &Name) {
1601 assert(getNumOperands() == 1 + IdxList.size() &&
1602 "NumOperands not initialized?");
1604 std::copy(IdxList.begin(), IdxList.end(), op_begin() + 1);
1608 GetElementPtrInst::GetElementPtrInst(const GetElementPtrInst &GEPI)
1609 : Instruction(GEPI.getType(), GetElementPtr,
1610 OperandTraits<GetElementPtrInst>::op_end(this) -
1611 GEPI.getNumOperands(),
1612 GEPI.getNumOperands()),
1613 SourceElementType(GEPI.SourceElementType),
1614 ResultElementType(GEPI.ResultElementType) {
1615 std::copy(GEPI.op_begin(), GEPI.op_end(), op_begin());
1616 SubclassOptionalData = GEPI.SubclassOptionalData;
1619 /// getIndexedType - Returns the type of the element that would be accessed with
1620 /// a gep instruction with the specified parameters.
1622 /// The Idxs pointer should point to a continuous piece of memory containing the
1623 /// indices, either as Value* or uint64_t.
1625 /// A null type is returned if the indices are invalid for the specified
1628 template <typename IndexTy>
1629 static Type *getIndexedTypeInternal(Type *Agg, ArrayRef<IndexTy> IdxList) {
1630 // Handle the special case of the empty set index set, which is always valid.
1631 if (IdxList.empty())
1634 // If there is at least one index, the top level type must be sized, otherwise
1635 // it cannot be 'stepped over'.
1636 if (!Agg->isSized())
1639 unsigned CurIdx = 1;
1640 for (; CurIdx != IdxList.size(); ++CurIdx) {
1641 CompositeType *CT = dyn_cast<CompositeType>(Agg);
1642 if (!CT || CT->isPointerTy()) return nullptr;
1643 IndexTy Index = IdxList[CurIdx];
1644 if (!CT->indexValid(Index)) return nullptr;
1645 Agg = CT->getTypeAtIndex(Index);
1647 return CurIdx == IdxList.size() ? Agg : nullptr;
1650 Type *GetElementPtrInst::getIndexedType(Type *Ty, ArrayRef<Value *> IdxList) {
1651 return getIndexedTypeInternal(Ty, IdxList);
1654 Type *GetElementPtrInst::getIndexedType(Type *Ty,
1655 ArrayRef<Constant *> IdxList) {
1656 return getIndexedTypeInternal(Ty, IdxList);
1659 Type *GetElementPtrInst::getIndexedType(Type *Ty, ArrayRef<uint64_t> IdxList) {
1660 return getIndexedTypeInternal(Ty, IdxList);
1663 /// hasAllZeroIndices - Return true if all of the indices of this GEP are
1664 /// zeros. If so, the result pointer and the first operand have the same
1665 /// value, just potentially different types.
1666 bool GetElementPtrInst::hasAllZeroIndices() const {
1667 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1668 if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(i))) {
1669 if (!CI->isZero()) return false;
1677 /// hasAllConstantIndices - Return true if all of the indices of this GEP are
1678 /// constant integers. If so, the result pointer and the first operand have
1679 /// a constant offset between them.
1680 bool GetElementPtrInst::hasAllConstantIndices() const {
1681 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1682 if (!isa<ConstantInt>(getOperand(i)))
1688 void GetElementPtrInst::setIsInBounds(bool B) {
1689 cast<GEPOperator>(this)->setIsInBounds(B);
1692 bool GetElementPtrInst::isInBounds() const {
1693 return cast<GEPOperator>(this)->isInBounds();
1696 bool GetElementPtrInst::accumulateConstantOffset(const DataLayout &DL,
1697 APInt &Offset) const {
1698 // Delegate to the generic GEPOperator implementation.
1699 return cast<GEPOperator>(this)->accumulateConstantOffset(DL, Offset);
1702 //===----------------------------------------------------------------------===//
1703 // ExtractElementInst Implementation
1704 //===----------------------------------------------------------------------===//
1706 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
1708 Instruction *InsertBef)
1709 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1711 OperandTraits<ExtractElementInst>::op_begin(this),
1713 assert(isValidOperands(Val, Index) &&
1714 "Invalid extractelement instruction operands!");
1720 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
1722 BasicBlock *InsertAE)
1723 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1725 OperandTraits<ExtractElementInst>::op_begin(this),
1727 assert(isValidOperands(Val, Index) &&
1728 "Invalid extractelement instruction operands!");
1736 bool ExtractElementInst::isValidOperands(const Value *Val, const Value *Index) {
1737 if (!Val->getType()->isVectorTy() || !Index->getType()->isIntegerTy())
1743 //===----------------------------------------------------------------------===//
1744 // InsertElementInst Implementation
1745 //===----------------------------------------------------------------------===//
1747 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
1749 Instruction *InsertBef)
1750 : Instruction(Vec->getType(), InsertElement,
1751 OperandTraits<InsertElementInst>::op_begin(this),
1753 assert(isValidOperands(Vec, Elt, Index) &&
1754 "Invalid insertelement instruction operands!");
1761 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
1763 BasicBlock *InsertAE)
1764 : Instruction(Vec->getType(), InsertElement,
1765 OperandTraits<InsertElementInst>::op_begin(this),
1767 assert(isValidOperands(Vec, Elt, Index) &&
1768 "Invalid insertelement instruction operands!");
1776 bool InsertElementInst::isValidOperands(const Value *Vec, const Value *Elt,
1777 const Value *Index) {
1778 if (!Vec->getType()->isVectorTy())
1779 return false; // First operand of insertelement must be vector type.
1781 if (Elt->getType() != cast<VectorType>(Vec->getType())->getElementType())
1782 return false;// Second operand of insertelement must be vector element type.
1784 if (!Index->getType()->isIntegerTy())
1785 return false; // Third operand of insertelement must be i32.
1790 //===----------------------------------------------------------------------===//
1791 // ShuffleVectorInst Implementation
1792 //===----------------------------------------------------------------------===//
1794 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1796 Instruction *InsertBefore)
1797 : Instruction(VectorType::get(cast<VectorType>(V1->getType())->getElementType(),
1798 cast<VectorType>(Mask->getType())->getNumElements()),
1800 OperandTraits<ShuffleVectorInst>::op_begin(this),
1801 OperandTraits<ShuffleVectorInst>::operands(this),
1803 assert(isValidOperands(V1, V2, Mask) &&
1804 "Invalid shuffle vector instruction operands!");
1811 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1813 BasicBlock *InsertAtEnd)
1814 : Instruction(VectorType::get(cast<VectorType>(V1->getType())->getElementType(),
1815 cast<VectorType>(Mask->getType())->getNumElements()),
1817 OperandTraits<ShuffleVectorInst>::op_begin(this),
1818 OperandTraits<ShuffleVectorInst>::operands(this),
1820 assert(isValidOperands(V1, V2, Mask) &&
1821 "Invalid shuffle vector instruction operands!");
1829 bool ShuffleVectorInst::isValidOperands(const Value *V1, const Value *V2,
1830 const Value *Mask) {
1831 // V1 and V2 must be vectors of the same type.
1832 if (!V1->getType()->isVectorTy() || V1->getType() != V2->getType())
1835 // Mask must be vector of i32.
1836 VectorType *MaskTy = dyn_cast<VectorType>(Mask->getType());
1837 if (!MaskTy || !MaskTy->getElementType()->isIntegerTy(32))
1840 // Check to see if Mask is valid.
1841 if (isa<UndefValue>(Mask) || isa<ConstantAggregateZero>(Mask))
1844 if (const ConstantVector *MV = dyn_cast<ConstantVector>(Mask)) {
1845 unsigned V1Size = cast<VectorType>(V1->getType())->getNumElements();
1846 for (Value *Op : MV->operands()) {
1847 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
1848 if (CI->uge(V1Size*2))
1850 } else if (!isa<UndefValue>(Op)) {
1857 if (const ConstantDataSequential *CDS =
1858 dyn_cast<ConstantDataSequential>(Mask)) {
1859 unsigned V1Size = cast<VectorType>(V1->getType())->getNumElements();
1860 for (unsigned i = 0, e = MaskTy->getNumElements(); i != e; ++i)
1861 if (CDS->getElementAsInteger(i) >= V1Size*2)
1866 // The bitcode reader can create a place holder for a forward reference
1867 // used as the shuffle mask. When this occurs, the shuffle mask will
1868 // fall into this case and fail. To avoid this error, do this bit of
1869 // ugliness to allow such a mask pass.
1870 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(Mask))
1871 if (CE->getOpcode() == Instruction::UserOp1)
1877 /// getMaskValue - Return the index from the shuffle mask for the specified
1878 /// output result. This is either -1 if the element is undef or a number less
1879 /// than 2*numelements.
1880 int ShuffleVectorInst::getMaskValue(Constant *Mask, unsigned i) {
1881 assert(i < Mask->getType()->getVectorNumElements() && "Index out of range");
1882 if (ConstantDataSequential *CDS =dyn_cast<ConstantDataSequential>(Mask))
1883 return CDS->getElementAsInteger(i);
1884 Constant *C = Mask->getAggregateElement(i);
1885 if (isa<UndefValue>(C))
1887 return cast<ConstantInt>(C)->getZExtValue();
1890 /// getShuffleMask - Return the full mask for this instruction, where each
1891 /// element is the element number and undef's are returned as -1.
1892 void ShuffleVectorInst::getShuffleMask(Constant *Mask,
1893 SmallVectorImpl<int> &Result) {
1894 unsigned NumElts = Mask->getType()->getVectorNumElements();
1896 if (ConstantDataSequential *CDS=dyn_cast<ConstantDataSequential>(Mask)) {
1897 for (unsigned i = 0; i != NumElts; ++i)
1898 Result.push_back(CDS->getElementAsInteger(i));
1901 for (unsigned i = 0; i != NumElts; ++i) {
1902 Constant *C = Mask->getAggregateElement(i);
1903 Result.push_back(isa<UndefValue>(C) ? -1 :
1904 cast<ConstantInt>(C)->getZExtValue());
1909 //===----------------------------------------------------------------------===//
1910 // InsertValueInst Class
1911 //===----------------------------------------------------------------------===//
1913 void InsertValueInst::init(Value *Agg, Value *Val, ArrayRef<unsigned> Idxs,
1914 const Twine &Name) {
1915 assert(getNumOperands() == 2 && "NumOperands not initialized?");
1917 // There's no fundamental reason why we require at least one index
1918 // (other than weirdness with &*IdxBegin being invalid; see
1919 // getelementptr's init routine for example). But there's no
1920 // present need to support it.
1921 assert(Idxs.size() > 0 && "InsertValueInst must have at least one index");
1923 assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs) ==
1924 Val->getType() && "Inserted value must match indexed type!");
1928 Indices.append(Idxs.begin(), Idxs.end());
1932 InsertValueInst::InsertValueInst(const InsertValueInst &IVI)
1933 : Instruction(IVI.getType(), InsertValue,
1934 OperandTraits<InsertValueInst>::op_begin(this), 2),
1935 Indices(IVI.Indices) {
1936 Op<0>() = IVI.getOperand(0);
1937 Op<1>() = IVI.getOperand(1);
1938 SubclassOptionalData = IVI.SubclassOptionalData;
1941 //===----------------------------------------------------------------------===//
1942 // ExtractValueInst Class
1943 //===----------------------------------------------------------------------===//
1945 void ExtractValueInst::init(ArrayRef<unsigned> Idxs, const Twine &Name) {
1946 assert(getNumOperands() == 1 && "NumOperands not initialized?");
1948 // There's no fundamental reason why we require at least one index.
1949 // But there's no present need to support it.
1950 assert(Idxs.size() > 0 && "ExtractValueInst must have at least one index");
1952 Indices.append(Idxs.begin(), Idxs.end());
1956 ExtractValueInst::ExtractValueInst(const ExtractValueInst &EVI)
1957 : UnaryInstruction(EVI.getType(), ExtractValue, EVI.getOperand(0)),
1958 Indices(EVI.Indices) {
1959 SubclassOptionalData = EVI.SubclassOptionalData;
1962 // getIndexedType - Returns the type of the element that would be extracted
1963 // with an extractvalue instruction with the specified parameters.
1965 // A null type is returned if the indices are invalid for the specified
1968 Type *ExtractValueInst::getIndexedType(Type *Agg,
1969 ArrayRef<unsigned> Idxs) {
1970 for (unsigned Index : Idxs) {
1971 // We can't use CompositeType::indexValid(Index) here.
1972 // indexValid() always returns true for arrays because getelementptr allows
1973 // out-of-bounds indices. Since we don't allow those for extractvalue and
1974 // insertvalue we need to check array indexing manually.
1975 // Since the only other types we can index into are struct types it's just
1976 // as easy to check those manually as well.
1977 if (ArrayType *AT = dyn_cast<ArrayType>(Agg)) {
1978 if (Index >= AT->getNumElements())
1980 } else if (StructType *ST = dyn_cast<StructType>(Agg)) {
1981 if (Index >= ST->getNumElements())
1984 // Not a valid type to index into.
1988 Agg = cast<CompositeType>(Agg)->getTypeAtIndex(Index);
1990 return const_cast<Type*>(Agg);
1993 //===----------------------------------------------------------------------===//
1994 // BinaryOperator Class
1995 //===----------------------------------------------------------------------===//
1997 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
1998 Type *Ty, const Twine &Name,
1999 Instruction *InsertBefore)
2000 : Instruction(Ty, iType,
2001 OperandTraits<BinaryOperator>::op_begin(this),
2002 OperandTraits<BinaryOperator>::operands(this),
2010 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
2011 Type *Ty, const Twine &Name,
2012 BasicBlock *InsertAtEnd)
2013 : Instruction(Ty, iType,
2014 OperandTraits<BinaryOperator>::op_begin(this),
2015 OperandTraits<BinaryOperator>::operands(this),
2024 void BinaryOperator::init(BinaryOps iType) {
2025 Value *LHS = getOperand(0), *RHS = getOperand(1);
2026 (void)LHS; (void)RHS; // Silence warnings.
2027 assert(LHS->getType() == RHS->getType() &&
2028 "Binary operator operand types must match!");
2033 assert(getType() == LHS->getType() &&
2034 "Arithmetic operation should return same type as operands!");
2035 assert(getType()->isIntOrIntVectorTy() &&
2036 "Tried to create an integer operation on a non-integer type!");
2038 case FAdd: case FSub:
2040 assert(getType() == LHS->getType() &&
2041 "Arithmetic operation should return same type as operands!");
2042 assert(getType()->isFPOrFPVectorTy() &&
2043 "Tried to create a floating-point operation on a "
2044 "non-floating-point type!");
2048 assert(getType() == LHS->getType() &&
2049 "Arithmetic operation should return same type as operands!");
2050 assert((getType()->isIntegerTy() || (getType()->isVectorTy() &&
2051 cast<VectorType>(getType())->getElementType()->isIntegerTy())) &&
2052 "Incorrect operand type (not integer) for S/UDIV");
2055 assert(getType() == LHS->getType() &&
2056 "Arithmetic operation should return same type as operands!");
2057 assert(getType()->isFPOrFPVectorTy() &&
2058 "Incorrect operand type (not floating point) for FDIV");
2062 assert(getType() == LHS->getType() &&
2063 "Arithmetic operation should return same type as operands!");
2064 assert((getType()->isIntegerTy() || (getType()->isVectorTy() &&
2065 cast<VectorType>(getType())->getElementType()->isIntegerTy())) &&
2066 "Incorrect operand type (not integer) for S/UREM");
2069 assert(getType() == LHS->getType() &&
2070 "Arithmetic operation should return same type as operands!");
2071 assert(getType()->isFPOrFPVectorTy() &&
2072 "Incorrect operand type (not floating point) for FREM");
2077 assert(getType() == LHS->getType() &&
2078 "Shift operation should return same type as operands!");
2079 assert((getType()->isIntegerTy() ||
2080 (getType()->isVectorTy() &&
2081 cast<VectorType>(getType())->getElementType()->isIntegerTy())) &&
2082 "Tried to create a shift operation on a non-integral type!");
2086 assert(getType() == LHS->getType() &&
2087 "Logical operation should return same type as operands!");
2088 assert((getType()->isIntegerTy() ||
2089 (getType()->isVectorTy() &&
2090 cast<VectorType>(getType())->getElementType()->isIntegerTy())) &&
2091 "Tried to create a logical operation on a non-integral type!");
2099 BinaryOperator *BinaryOperator::Create(BinaryOps Op, Value *S1, Value *S2,
2101 Instruction *InsertBefore) {
2102 assert(S1->getType() == S2->getType() &&
2103 "Cannot create binary operator with two operands of differing type!");
2104 return new BinaryOperator(Op, S1, S2, S1->getType(), Name, InsertBefore);
2107 BinaryOperator *BinaryOperator::Create(BinaryOps Op, Value *S1, Value *S2,
2109 BasicBlock *InsertAtEnd) {
2110 BinaryOperator *Res = Create(Op, S1, S2, Name);
2111 InsertAtEnd->getInstList().push_back(Res);
2115 BinaryOperator *BinaryOperator::CreateNeg(Value *Op, const Twine &Name,
2116 Instruction *InsertBefore) {
2117 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
2118 return new BinaryOperator(Instruction::Sub,
2120 Op->getType(), Name, InsertBefore);
2123 BinaryOperator *BinaryOperator::CreateNeg(Value *Op, const Twine &Name,
2124 BasicBlock *InsertAtEnd) {
2125 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
2126 return new BinaryOperator(Instruction::Sub,
2128 Op->getType(), Name, InsertAtEnd);
2131 BinaryOperator *BinaryOperator::CreateNSWNeg(Value *Op, const Twine &Name,
2132 Instruction *InsertBefore) {
2133 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
2134 return BinaryOperator::CreateNSWSub(zero, Op, Name, InsertBefore);
2137 BinaryOperator *BinaryOperator::CreateNSWNeg(Value *Op, const Twine &Name,
2138 BasicBlock *InsertAtEnd) {
2139 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
2140 return BinaryOperator::CreateNSWSub(zero, Op, Name, InsertAtEnd);
2143 BinaryOperator *BinaryOperator::CreateNUWNeg(Value *Op, const Twine &Name,
2144 Instruction *InsertBefore) {
2145 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
2146 return BinaryOperator::CreateNUWSub(zero, Op, Name, InsertBefore);
2149 BinaryOperator *BinaryOperator::CreateNUWNeg(Value *Op, const Twine &Name,
2150 BasicBlock *InsertAtEnd) {
2151 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
2152 return BinaryOperator::CreateNUWSub(zero, Op, Name, InsertAtEnd);
2155 BinaryOperator *BinaryOperator::CreateFNeg(Value *Op, const Twine &Name,
2156 Instruction *InsertBefore) {
2157 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
2158 return new BinaryOperator(Instruction::FSub, zero, Op,
2159 Op->getType(), Name, InsertBefore);
2162 BinaryOperator *BinaryOperator::CreateFNeg(Value *Op, const Twine &Name,
2163 BasicBlock *InsertAtEnd) {
2164 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
2165 return new BinaryOperator(Instruction::FSub, zero, Op,
2166 Op->getType(), Name, InsertAtEnd);
2169 BinaryOperator *BinaryOperator::CreateNot(Value *Op, const Twine &Name,
2170 Instruction *InsertBefore) {
2171 Constant *C = Constant::getAllOnesValue(Op->getType());
2172 return new BinaryOperator(Instruction::Xor, Op, C,
2173 Op->getType(), Name, InsertBefore);
2176 BinaryOperator *BinaryOperator::CreateNot(Value *Op, const Twine &Name,
2177 BasicBlock *InsertAtEnd) {
2178 Constant *AllOnes = Constant::getAllOnesValue(Op->getType());
2179 return new BinaryOperator(Instruction::Xor, Op, AllOnes,
2180 Op->getType(), Name, InsertAtEnd);
2184 // isConstantAllOnes - Helper function for several functions below
2185 static inline bool isConstantAllOnes(const Value *V) {
2186 if (const Constant *C = dyn_cast<Constant>(V))
2187 return C->isAllOnesValue();
2191 bool BinaryOperator::isNeg(const Value *V) {
2192 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
2193 if (Bop->getOpcode() == Instruction::Sub)
2194 if (Constant* C = dyn_cast<Constant>(Bop->getOperand(0)))
2195 return C->isNegativeZeroValue();
2199 bool BinaryOperator::isFNeg(const Value *V, bool IgnoreZeroSign) {
2200 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
2201 if (Bop->getOpcode() == Instruction::FSub)
2202 if (Constant* C = dyn_cast<Constant>(Bop->getOperand(0))) {
2203 if (!IgnoreZeroSign)
2204 IgnoreZeroSign = cast<Instruction>(V)->hasNoSignedZeros();
2205 return !IgnoreZeroSign ? C->isNegativeZeroValue() : C->isZeroValue();
2210 bool BinaryOperator::isNot(const Value *V) {
2211 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
2212 return (Bop->getOpcode() == Instruction::Xor &&
2213 (isConstantAllOnes(Bop->getOperand(1)) ||
2214 isConstantAllOnes(Bop->getOperand(0))));
2218 Value *BinaryOperator::getNegArgument(Value *BinOp) {
2219 return cast<BinaryOperator>(BinOp)->getOperand(1);
2222 const Value *BinaryOperator::getNegArgument(const Value *BinOp) {
2223 return getNegArgument(const_cast<Value*>(BinOp));
2226 Value *BinaryOperator::getFNegArgument(Value *BinOp) {
2227 return cast<BinaryOperator>(BinOp)->getOperand(1);
2230 const Value *BinaryOperator::getFNegArgument(const Value *BinOp) {
2231 return getFNegArgument(const_cast<Value*>(BinOp));
2234 Value *BinaryOperator::getNotArgument(Value *BinOp) {
2235 assert(isNot(BinOp) && "getNotArgument on non-'not' instruction!");
2236 BinaryOperator *BO = cast<BinaryOperator>(BinOp);
2237 Value *Op0 = BO->getOperand(0);
2238 Value *Op1 = BO->getOperand(1);
2239 if (isConstantAllOnes(Op0)) return Op1;
2241 assert(isConstantAllOnes(Op1));
2245 const Value *BinaryOperator::getNotArgument(const Value *BinOp) {
2246 return getNotArgument(const_cast<Value*>(BinOp));
2250 // swapOperands - Exchange the two operands to this instruction. This
2251 // instruction is safe to use on any binary instruction and does not
2252 // modify the semantics of the instruction. If the instruction is
2253 // order dependent (SetLT f.e.) the opcode is changed.
2255 bool BinaryOperator::swapOperands() {
2256 if (!isCommutative())
2257 return true; // Can't commute operands
2258 Op<0>().swap(Op<1>());
2262 void BinaryOperator::setHasNoUnsignedWrap(bool b) {
2263 cast<OverflowingBinaryOperator>(this)->setHasNoUnsignedWrap(b);
2266 void BinaryOperator::setHasNoSignedWrap(bool b) {
2267 cast<OverflowingBinaryOperator>(this)->setHasNoSignedWrap(b);
2270 void BinaryOperator::setIsExact(bool b) {
2271 cast<PossiblyExactOperator>(this)->setIsExact(b);
2274 bool BinaryOperator::hasNoUnsignedWrap() const {
2275 return cast<OverflowingBinaryOperator>(this)->hasNoUnsignedWrap();
2278 bool BinaryOperator::hasNoSignedWrap() const {
2279 return cast<OverflowingBinaryOperator>(this)->hasNoSignedWrap();
2282 bool BinaryOperator::isExact() const {
2283 return cast<PossiblyExactOperator>(this)->isExact();
2286 void BinaryOperator::copyIRFlags(const Value *V) {
2287 // Copy the wrapping flags.
2288 if (auto *OB = dyn_cast<OverflowingBinaryOperator>(V)) {
2289 setHasNoSignedWrap(OB->hasNoSignedWrap());
2290 setHasNoUnsignedWrap(OB->hasNoUnsignedWrap());
2293 // Copy the exact flag.
2294 if (auto *PE = dyn_cast<PossiblyExactOperator>(V))
2295 setIsExact(PE->isExact());
2297 // Copy the fast-math flags.
2298 if (auto *FP = dyn_cast<FPMathOperator>(V))
2299 copyFastMathFlags(FP->getFastMathFlags());
2302 void BinaryOperator::andIRFlags(const Value *V) {
2303 if (auto *OB = dyn_cast<OverflowingBinaryOperator>(V)) {
2304 setHasNoSignedWrap(hasNoSignedWrap() & OB->hasNoSignedWrap());
2305 setHasNoUnsignedWrap(hasNoUnsignedWrap() & OB->hasNoUnsignedWrap());
2308 if (auto *PE = dyn_cast<PossiblyExactOperator>(V))
2309 setIsExact(isExact() & PE->isExact());
2311 if (auto *FP = dyn_cast<FPMathOperator>(V)) {
2312 FastMathFlags FM = getFastMathFlags();
2313 FM &= FP->getFastMathFlags();
2314 copyFastMathFlags(FM);
2319 //===----------------------------------------------------------------------===//
2320 // FPMathOperator Class
2321 //===----------------------------------------------------------------------===//
2323 /// getFPAccuracy - Get the maximum error permitted by this operation in ULPs.
2324 /// An accuracy of 0.0 means that the operation should be performed with the
2325 /// default precision.
2326 float FPMathOperator::getFPAccuracy() const {
2328 cast<Instruction>(this)->getMetadata(LLVMContext::MD_fpmath);
2331 ConstantFP *Accuracy = mdconst::extract<ConstantFP>(MD->getOperand(0));
2332 return Accuracy->getValueAPF().convertToFloat();
2336 //===----------------------------------------------------------------------===//
2338 //===----------------------------------------------------------------------===//
2340 void CastInst::anchor() {}
2342 // Just determine if this cast only deals with integral->integral conversion.
2343 bool CastInst::isIntegerCast() const {
2344 switch (getOpcode()) {
2345 default: return false;
2346 case Instruction::ZExt:
2347 case Instruction::SExt:
2348 case Instruction::Trunc:
2350 case Instruction::BitCast:
2351 return getOperand(0)->getType()->isIntegerTy() &&
2352 getType()->isIntegerTy();
2356 bool CastInst::isLosslessCast() const {
2357 // Only BitCast can be lossless, exit fast if we're not BitCast
2358 if (getOpcode() != Instruction::BitCast)
2361 // Identity cast is always lossless
2362 Type* SrcTy = getOperand(0)->getType();
2363 Type* DstTy = getType();
2367 // Pointer to pointer is always lossless.
2368 if (SrcTy->isPointerTy())
2369 return DstTy->isPointerTy();
2370 return false; // Other types have no identity values
2373 /// This function determines if the CastInst does not require any bits to be
2374 /// changed in order to effect the cast. Essentially, it identifies cases where
2375 /// no code gen is necessary for the cast, hence the name no-op cast. For
2376 /// example, the following are all no-op casts:
2377 /// # bitcast i32* %x to i8*
2378 /// # bitcast <2 x i32> %x to <4 x i16>
2379 /// # ptrtoint i32* %x to i32 ; on 32-bit plaforms only
2380 /// @brief Determine if the described cast is a no-op.
2381 bool CastInst::isNoopCast(Instruction::CastOps Opcode,
2386 default: llvm_unreachable("Invalid CastOp");
2387 case Instruction::Trunc:
2388 case Instruction::ZExt:
2389 case Instruction::SExt:
2390 case Instruction::FPTrunc:
2391 case Instruction::FPExt:
2392 case Instruction::UIToFP:
2393 case Instruction::SIToFP:
2394 case Instruction::FPToUI:
2395 case Instruction::FPToSI:
2396 case Instruction::AddrSpaceCast:
2397 // TODO: Target informations may give a more accurate answer here.
2399 case Instruction::BitCast:
2400 return true; // BitCast never modifies bits.
2401 case Instruction::PtrToInt:
2402 return IntPtrTy->getScalarSizeInBits() ==
2403 DestTy->getScalarSizeInBits();
2404 case Instruction::IntToPtr:
2405 return IntPtrTy->getScalarSizeInBits() ==
2406 SrcTy->getScalarSizeInBits();
2410 /// @brief Determine if a cast is a no-op.
2411 bool CastInst::isNoopCast(Type *IntPtrTy) const {
2412 return isNoopCast(getOpcode(), getOperand(0)->getType(), getType(), IntPtrTy);
2415 bool CastInst::isNoopCast(const DataLayout &DL) const {
2416 Type *PtrOpTy = nullptr;
2417 if (getOpcode() == Instruction::PtrToInt)
2418 PtrOpTy = getOperand(0)->getType();
2419 else if (getOpcode() == Instruction::IntToPtr)
2420 PtrOpTy = getType();
2423 PtrOpTy ? DL.getIntPtrType(PtrOpTy) : DL.getIntPtrType(getContext(), 0);
2425 return isNoopCast(getOpcode(), getOperand(0)->getType(), getType(), IntPtrTy);
2428 /// This function determines if a pair of casts can be eliminated and what
2429 /// opcode should be used in the elimination. This assumes that there are two
2430 /// instructions like this:
2431 /// * %F = firstOpcode SrcTy %x to MidTy
2432 /// * %S = secondOpcode MidTy %F to DstTy
2433 /// The function returns a resultOpcode so these two casts can be replaced with:
2434 /// * %Replacement = resultOpcode %SrcTy %x to DstTy
2435 /// If no such cast is permited, the function returns 0.
2436 unsigned CastInst::isEliminableCastPair(
2437 Instruction::CastOps firstOp, Instruction::CastOps secondOp,
2438 Type *SrcTy, Type *MidTy, Type *DstTy, Type *SrcIntPtrTy, Type *MidIntPtrTy,
2439 Type *DstIntPtrTy) {
2440 // Define the 144 possibilities for these two cast instructions. The values
2441 // in this matrix determine what to do in a given situation and select the
2442 // case in the switch below. The rows correspond to firstOp, the columns
2443 // correspond to secondOp. In looking at the table below, keep in mind
2444 // the following cast properties:
2446 // Size Compare Source Destination
2447 // Operator Src ? Size Type Sign Type Sign
2448 // -------- ------------ ------------------- ---------------------
2449 // TRUNC > Integer Any Integral Any
2450 // ZEXT < Integral Unsigned Integer Any
2451 // SEXT < Integral Signed Integer Any
2452 // FPTOUI n/a FloatPt n/a Integral Unsigned
2453 // FPTOSI n/a FloatPt n/a Integral Signed
2454 // UITOFP n/a Integral Unsigned FloatPt n/a
2455 // SITOFP n/a Integral Signed FloatPt n/a
2456 // FPTRUNC > FloatPt n/a FloatPt n/a
2457 // FPEXT < FloatPt n/a FloatPt n/a
2458 // PTRTOINT n/a Pointer n/a Integral Unsigned
2459 // INTTOPTR n/a Integral Unsigned Pointer n/a
2460 // BITCAST = FirstClass n/a FirstClass n/a
2461 // ADDRSPCST n/a Pointer n/a Pointer n/a
2463 // NOTE: some transforms are safe, but we consider them to be non-profitable.
2464 // For example, we could merge "fptoui double to i32" + "zext i32 to i64",
2465 // into "fptoui double to i64", but this loses information about the range
2466 // of the produced value (we no longer know the top-part is all zeros).
2467 // Further this conversion is often much more expensive for typical hardware,
2468 // and causes issues when building libgcc. We disallow fptosi+sext for the
2470 const unsigned numCastOps =
2471 Instruction::CastOpsEnd - Instruction::CastOpsBegin;
2472 static const uint8_t CastResults[numCastOps][numCastOps] = {
2473 // T F F U S F F P I B A -+
2474 // R Z S P P I I T P 2 N T S |
2475 // U E E 2 2 2 2 R E I T C C +- secondOp
2476 // N X X U S F F N X N 2 V V |
2477 // C T T I I P P C T T P T T -+
2478 { 1, 0, 0,99,99, 0, 0,99,99,99, 0, 3, 0}, // Trunc -+
2479 { 8, 1, 9,99,99, 2,17,99,99,99, 2, 3, 0}, // ZExt |
2480 { 8, 0, 1,99,99, 0, 2,99,99,99, 0, 3, 0}, // SExt |
2481 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3, 0}, // FPToUI |
2482 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3, 0}, // FPToSI |
2483 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4, 0}, // UIToFP +- firstOp
2484 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4, 0}, // SIToFP |
2485 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4, 0}, // FPTrunc |
2486 { 99,99,99, 2, 2,99,99,10, 2,99,99, 4, 0}, // FPExt |
2487 { 1, 0, 0,99,99, 0, 0,99,99,99, 7, 3, 0}, // PtrToInt |
2488 { 99,99,99,99,99,99,99,99,99,11,99,15, 0}, // IntToPtr |
2489 { 5, 5, 5, 6, 6, 5, 5, 6, 6,16, 5, 1,14}, // BitCast |
2490 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,13,12}, // AddrSpaceCast -+
2493 // If either of the casts are a bitcast from scalar to vector, disallow the
2494 // merging. However, bitcast of A->B->A are allowed.
2495 bool isFirstBitcast = (firstOp == Instruction::BitCast);
2496 bool isSecondBitcast = (secondOp == Instruction::BitCast);
2497 bool chainedBitcast = (SrcTy == DstTy && isFirstBitcast && isSecondBitcast);
2499 // Check if any of the bitcasts convert scalars<->vectors.
2500 if ((isFirstBitcast && isa<VectorType>(SrcTy) != isa<VectorType>(MidTy)) ||
2501 (isSecondBitcast && isa<VectorType>(MidTy) != isa<VectorType>(DstTy)))
2502 // Unless we are bitcasing to the original type, disallow optimizations.
2503 if (!chainedBitcast) return 0;
2505 int ElimCase = CastResults[firstOp-Instruction::CastOpsBegin]
2506 [secondOp-Instruction::CastOpsBegin];
2509 // Categorically disallowed.
2512 // Allowed, use first cast's opcode.
2515 // Allowed, use second cast's opcode.
2518 // No-op cast in second op implies firstOp as long as the DestTy
2519 // is integer and we are not converting between a vector and a
2521 if (!SrcTy->isVectorTy() && DstTy->isIntegerTy())
2525 // No-op cast in second op implies firstOp as long as the DestTy
2526 // is floating point.
2527 if (DstTy->isFloatingPointTy())
2531 // No-op cast in first op implies secondOp as long as the SrcTy
2533 if (SrcTy->isIntegerTy())
2537 // No-op cast in first op implies secondOp as long as the SrcTy
2538 // is a floating point.
2539 if (SrcTy->isFloatingPointTy())
2543 // Cannot simplify if address spaces are different!
2544 if (SrcTy->getPointerAddressSpace() != DstTy->getPointerAddressSpace())
2547 unsigned MidSize = MidTy->getScalarSizeInBits();
2548 // We can still fold this without knowing the actual sizes as long we
2549 // know that the intermediate pointer is the largest possible
2551 // FIXME: Is this always true?
2553 return Instruction::BitCast;
2555 // ptrtoint, inttoptr -> bitcast (ptr -> ptr) if int size is >= ptr size.
2556 if (!SrcIntPtrTy || DstIntPtrTy != SrcIntPtrTy)
2558 unsigned PtrSize = SrcIntPtrTy->getScalarSizeInBits();
2559 if (MidSize >= PtrSize)
2560 return Instruction::BitCast;
2564 // ext, trunc -> bitcast, if the SrcTy and DstTy are same size
2565 // ext, trunc -> ext, if sizeof(SrcTy) < sizeof(DstTy)
2566 // ext, trunc -> trunc, if sizeof(SrcTy) > sizeof(DstTy)
2567 unsigned SrcSize = SrcTy->getScalarSizeInBits();
2568 unsigned DstSize = DstTy->getScalarSizeInBits();
2569 if (SrcSize == DstSize)
2570 return Instruction::BitCast;
2571 else if (SrcSize < DstSize)
2576 // zext, sext -> zext, because sext can't sign extend after zext
2577 return Instruction::ZExt;
2579 // fpext followed by ftrunc is allowed if the bit size returned to is
2580 // the same as the original, in which case its just a bitcast
2582 return Instruction::BitCast;
2583 return 0; // If the types are not the same we can't eliminate it.
2585 // inttoptr, ptrtoint -> bitcast if SrcSize<=PtrSize and SrcSize==DstSize
2588 unsigned PtrSize = MidIntPtrTy->getScalarSizeInBits();
2589 unsigned SrcSize = SrcTy->getScalarSizeInBits();
2590 unsigned DstSize = DstTy->getScalarSizeInBits();
2591 if (SrcSize <= PtrSize && SrcSize == DstSize)
2592 return Instruction::BitCast;
2596 // addrspacecast, addrspacecast -> bitcast, if SrcAS == DstAS
2597 // addrspacecast, addrspacecast -> addrspacecast, if SrcAS != DstAS
2598 if (SrcTy->getPointerAddressSpace() != DstTy->getPointerAddressSpace())
2599 return Instruction::AddrSpaceCast;
2600 return Instruction::BitCast;
2603 // FIXME: this state can be merged with (1), but the following assert
2604 // is useful to check the correcteness of the sequence due to semantic
2605 // change of bitcast.
2607 SrcTy->isPtrOrPtrVectorTy() &&
2608 MidTy->isPtrOrPtrVectorTy() &&
2609 DstTy->isPtrOrPtrVectorTy() &&
2610 SrcTy->getPointerAddressSpace() != MidTy->getPointerAddressSpace() &&
2611 MidTy->getPointerAddressSpace() == DstTy->getPointerAddressSpace() &&
2612 "Illegal addrspacecast, bitcast sequence!");
2613 // Allowed, use first cast's opcode
2616 // bitcast, addrspacecast -> addrspacecast if the element type of
2617 // bitcast's source is the same as that of addrspacecast's destination.
2618 if (SrcTy->getPointerElementType() == DstTy->getPointerElementType())
2619 return Instruction::AddrSpaceCast;
2623 // FIXME: this state can be merged with (1), but the following assert
2624 // is useful to check the correcteness of the sequence due to semantic
2625 // change of bitcast.
2627 SrcTy->isIntOrIntVectorTy() &&
2628 MidTy->isPtrOrPtrVectorTy() &&
2629 DstTy->isPtrOrPtrVectorTy() &&
2630 MidTy->getPointerAddressSpace() == DstTy->getPointerAddressSpace() &&
2631 "Illegal inttoptr, bitcast sequence!");
2632 // Allowed, use first cast's opcode
2635 // FIXME: this state can be merged with (2), but the following assert
2636 // is useful to check the correcteness of the sequence due to semantic
2637 // change of bitcast.
2639 SrcTy->isPtrOrPtrVectorTy() &&
2640 MidTy->isPtrOrPtrVectorTy() &&
2641 DstTy->isIntOrIntVectorTy() &&
2642 SrcTy->getPointerAddressSpace() == MidTy->getPointerAddressSpace() &&
2643 "Illegal bitcast, ptrtoint sequence!");
2644 // Allowed, use second cast's opcode
2647 // (sitofp (zext x)) -> (uitofp x)
2648 return Instruction::UIToFP;
2650 // Cast combination can't happen (error in input). This is for all cases
2651 // where the MidTy is not the same for the two cast instructions.
2652 llvm_unreachable("Invalid Cast Combination");
2654 llvm_unreachable("Error in CastResults table!!!");
2658 CastInst *CastInst::Create(Instruction::CastOps op, Value *S, Type *Ty,
2659 const Twine &Name, Instruction *InsertBefore) {
2660 assert(castIsValid(op, S, Ty) && "Invalid cast!");
2661 // Construct and return the appropriate CastInst subclass
2663 case Trunc: return new TruncInst (S, Ty, Name, InsertBefore);
2664 case ZExt: return new ZExtInst (S, Ty, Name, InsertBefore);
2665 case SExt: return new SExtInst (S, Ty, Name, InsertBefore);
2666 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertBefore);
2667 case FPExt: return new FPExtInst (S, Ty, Name, InsertBefore);
2668 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertBefore);
2669 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertBefore);
2670 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertBefore);
2671 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertBefore);
2672 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertBefore);
2673 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertBefore);
2674 case BitCast: return new BitCastInst (S, Ty, Name, InsertBefore);
2675 case AddrSpaceCast: return new AddrSpaceCastInst (S, Ty, Name, InsertBefore);
2676 default: llvm_unreachable("Invalid opcode provided");
2680 CastInst *CastInst::Create(Instruction::CastOps op, Value *S, Type *Ty,
2681 const Twine &Name, BasicBlock *InsertAtEnd) {
2682 assert(castIsValid(op, S, Ty) && "Invalid cast!");
2683 // Construct and return the appropriate CastInst subclass
2685 case Trunc: return new TruncInst (S, Ty, Name, InsertAtEnd);
2686 case ZExt: return new ZExtInst (S, Ty, Name, InsertAtEnd);
2687 case SExt: return new SExtInst (S, Ty, Name, InsertAtEnd);
2688 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertAtEnd);
2689 case FPExt: return new FPExtInst (S, Ty, Name, InsertAtEnd);
2690 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertAtEnd);
2691 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertAtEnd);
2692 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertAtEnd);
2693 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertAtEnd);
2694 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertAtEnd);
2695 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertAtEnd);
2696 case BitCast: return new BitCastInst (S, Ty, Name, InsertAtEnd);
2697 case AddrSpaceCast: return new AddrSpaceCastInst (S, Ty, Name, InsertAtEnd);
2698 default: llvm_unreachable("Invalid opcode provided");
2702 CastInst *CastInst::CreateZExtOrBitCast(Value *S, Type *Ty,
2704 Instruction *InsertBefore) {
2705 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2706 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2707 return Create(Instruction::ZExt, S, Ty, Name, InsertBefore);
2710 CastInst *CastInst::CreateZExtOrBitCast(Value *S, Type *Ty,
2712 BasicBlock *InsertAtEnd) {
2713 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2714 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2715 return Create(Instruction::ZExt, S, Ty, Name, InsertAtEnd);
2718 CastInst *CastInst::CreateSExtOrBitCast(Value *S, Type *Ty,
2720 Instruction *InsertBefore) {
2721 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2722 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2723 return Create(Instruction::SExt, S, Ty, Name, InsertBefore);
2726 CastInst *CastInst::CreateSExtOrBitCast(Value *S, Type *Ty,
2728 BasicBlock *InsertAtEnd) {
2729 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2730 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2731 return Create(Instruction::SExt, S, Ty, Name, InsertAtEnd);
2734 CastInst *CastInst::CreateTruncOrBitCast(Value *S, Type *Ty,
2736 Instruction *InsertBefore) {
2737 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2738 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2739 return Create(Instruction::Trunc, S, Ty, Name, InsertBefore);
2742 CastInst *CastInst::CreateTruncOrBitCast(Value *S, Type *Ty,
2744 BasicBlock *InsertAtEnd) {
2745 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2746 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2747 return Create(Instruction::Trunc, S, Ty, Name, InsertAtEnd);
2750 CastInst *CastInst::CreatePointerCast(Value *S, Type *Ty,
2752 BasicBlock *InsertAtEnd) {
2753 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
2754 assert((Ty->isIntOrIntVectorTy() || Ty->isPtrOrPtrVectorTy()) &&
2756 assert(Ty->isVectorTy() == S->getType()->isVectorTy() && "Invalid cast");
2757 assert((!Ty->isVectorTy() ||
2758 Ty->getVectorNumElements() == S->getType()->getVectorNumElements()) &&
2761 if (Ty->isIntOrIntVectorTy())
2762 return Create(Instruction::PtrToInt, S, Ty, Name, InsertAtEnd);
2764 return CreatePointerBitCastOrAddrSpaceCast(S, Ty, Name, InsertAtEnd);
2767 /// @brief Create a BitCast or a PtrToInt cast instruction
2768 CastInst *CastInst::CreatePointerCast(Value *S, Type *Ty,
2770 Instruction *InsertBefore) {
2771 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
2772 assert((Ty->isIntOrIntVectorTy() || Ty->isPtrOrPtrVectorTy()) &&
2774 assert(Ty->isVectorTy() == S->getType()->isVectorTy() && "Invalid cast");
2775 assert((!Ty->isVectorTy() ||
2776 Ty->getVectorNumElements() == S->getType()->getVectorNumElements()) &&
2779 if (Ty->isIntOrIntVectorTy())
2780 return Create(Instruction::PtrToInt, S, Ty, Name, InsertBefore);
2782 return CreatePointerBitCastOrAddrSpaceCast(S, Ty, Name, InsertBefore);
2785 CastInst *CastInst::CreatePointerBitCastOrAddrSpaceCast(
2788 BasicBlock *InsertAtEnd) {
2789 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
2790 assert(Ty->isPtrOrPtrVectorTy() && "Invalid cast");
2792 if (S->getType()->getPointerAddressSpace() != Ty->getPointerAddressSpace())
2793 return Create(Instruction::AddrSpaceCast, S, Ty, Name, InsertAtEnd);
2795 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2798 CastInst *CastInst::CreatePointerBitCastOrAddrSpaceCast(
2801 Instruction *InsertBefore) {
2802 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
2803 assert(Ty->isPtrOrPtrVectorTy() && "Invalid cast");
2805 if (S->getType()->getPointerAddressSpace() != Ty->getPointerAddressSpace())
2806 return Create(Instruction::AddrSpaceCast, S, Ty, Name, InsertBefore);
2808 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2811 CastInst *CastInst::CreateBitOrPointerCast(Value *S, Type *Ty,
2813 Instruction *InsertBefore) {
2814 if (S->getType()->isPointerTy() && Ty->isIntegerTy())
2815 return Create(Instruction::PtrToInt, S, Ty, Name, InsertBefore);
2816 if (S->getType()->isIntegerTy() && Ty->isPointerTy())
2817 return Create(Instruction::IntToPtr, S, Ty, Name, InsertBefore);
2819 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2822 CastInst *CastInst::CreateIntegerCast(Value *C, Type *Ty,
2823 bool isSigned, const Twine &Name,
2824 Instruction *InsertBefore) {
2825 assert(C->getType()->isIntOrIntVectorTy() && Ty->isIntOrIntVectorTy() &&
2826 "Invalid integer cast");
2827 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2828 unsigned DstBits = Ty->getScalarSizeInBits();
2829 Instruction::CastOps opcode =
2830 (SrcBits == DstBits ? Instruction::BitCast :
2831 (SrcBits > DstBits ? Instruction::Trunc :
2832 (isSigned ? Instruction::SExt : Instruction::ZExt)));
2833 return Create(opcode, C, Ty, Name, InsertBefore);
2836 CastInst *CastInst::CreateIntegerCast(Value *C, Type *Ty,
2837 bool isSigned, const Twine &Name,
2838 BasicBlock *InsertAtEnd) {
2839 assert(C->getType()->isIntOrIntVectorTy() && Ty->isIntOrIntVectorTy() &&
2841 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2842 unsigned DstBits = Ty->getScalarSizeInBits();
2843 Instruction::CastOps opcode =
2844 (SrcBits == DstBits ? Instruction::BitCast :
2845 (SrcBits > DstBits ? Instruction::Trunc :
2846 (isSigned ? Instruction::SExt : Instruction::ZExt)));
2847 return Create(opcode, C, Ty, Name, InsertAtEnd);
2850 CastInst *CastInst::CreateFPCast(Value *C, Type *Ty,
2852 Instruction *InsertBefore) {
2853 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
2855 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2856 unsigned DstBits = Ty->getScalarSizeInBits();
2857 Instruction::CastOps opcode =
2858 (SrcBits == DstBits ? Instruction::BitCast :
2859 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
2860 return Create(opcode, C, Ty, Name, InsertBefore);
2863 CastInst *CastInst::CreateFPCast(Value *C, Type *Ty,
2865 BasicBlock *InsertAtEnd) {
2866 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
2868 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2869 unsigned DstBits = Ty->getScalarSizeInBits();
2870 Instruction::CastOps opcode =
2871 (SrcBits == DstBits ? Instruction::BitCast :
2872 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
2873 return Create(opcode, C, Ty, Name, InsertAtEnd);
2876 // Check whether it is valid to call getCastOpcode for these types.
2877 // This routine must be kept in sync with getCastOpcode.
2878 bool CastInst::isCastable(Type *SrcTy, Type *DestTy) {
2879 if (!SrcTy->isFirstClassType() || !DestTy->isFirstClassType())
2882 if (SrcTy == DestTy)
2885 if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy))
2886 if (VectorType *DestVecTy = dyn_cast<VectorType>(DestTy))
2887 if (SrcVecTy->getNumElements() == DestVecTy->getNumElements()) {
2888 // An element by element cast. Valid if casting the elements is valid.
2889 SrcTy = SrcVecTy->getElementType();
2890 DestTy = DestVecTy->getElementType();
2893 // Get the bit sizes, we'll need these
2894 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); // 0 for ptr
2895 unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr
2897 // Run through the possibilities ...
2898 if (DestTy->isIntegerTy()) { // Casting to integral
2899 if (SrcTy->isIntegerTy()) // Casting from integral
2901 if (SrcTy->isFloatingPointTy()) // Casting from floating pt
2903 if (SrcTy->isVectorTy()) // Casting from vector
2904 return DestBits == SrcBits;
2905 // Casting from something else
2906 return SrcTy->isPointerTy();
2908 if (DestTy->isFloatingPointTy()) { // Casting to floating pt
2909 if (SrcTy->isIntegerTy()) // Casting from integral
2911 if (SrcTy->isFloatingPointTy()) // Casting from floating pt
2913 if (SrcTy->isVectorTy()) // Casting from vector
2914 return DestBits == SrcBits;
2915 // Casting from something else
2918 if (DestTy->isVectorTy()) // Casting to vector
2919 return DestBits == SrcBits;
2920 if (DestTy->isPointerTy()) { // Casting to pointer
2921 if (SrcTy->isPointerTy()) // Casting from pointer
2923 return SrcTy->isIntegerTy(); // Casting from integral
2925 if (DestTy->isX86_MMXTy()) {
2926 if (SrcTy->isVectorTy())
2927 return DestBits == SrcBits; // 64-bit vector to MMX
2929 } // Casting to something else
2933 bool CastInst::isBitCastable(Type *SrcTy, Type *DestTy) {
2934 if (!SrcTy->isFirstClassType() || !DestTy->isFirstClassType())
2937 if (SrcTy == DestTy)
2940 if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy)) {
2941 if (VectorType *DestVecTy = dyn_cast<VectorType>(DestTy)) {
2942 if (SrcVecTy->getNumElements() == DestVecTy->getNumElements()) {
2943 // An element by element cast. Valid if casting the elements is valid.
2944 SrcTy = SrcVecTy->getElementType();
2945 DestTy = DestVecTy->getElementType();
2950 if (PointerType *DestPtrTy = dyn_cast<PointerType>(DestTy)) {
2951 if (PointerType *SrcPtrTy = dyn_cast<PointerType>(SrcTy)) {
2952 return SrcPtrTy->getAddressSpace() == DestPtrTy->getAddressSpace();
2956 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); // 0 for ptr
2957 unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr
2959 // Could still have vectors of pointers if the number of elements doesn't
2961 if (SrcBits == 0 || DestBits == 0)
2964 if (SrcBits != DestBits)
2967 if (DestTy->isX86_MMXTy() || SrcTy->isX86_MMXTy())
2973 bool CastInst::isBitOrNoopPointerCastable(Type *SrcTy, Type *DestTy,
2974 const DataLayout &DL) {
2975 if (auto *PtrTy = dyn_cast<PointerType>(SrcTy))
2976 if (auto *IntTy = dyn_cast<IntegerType>(DestTy))
2977 return IntTy->getBitWidth() == DL.getPointerTypeSizeInBits(PtrTy);
2978 if (auto *PtrTy = dyn_cast<PointerType>(DestTy))
2979 if (auto *IntTy = dyn_cast<IntegerType>(SrcTy))
2980 return IntTy->getBitWidth() == DL.getPointerTypeSizeInBits(PtrTy);
2982 return isBitCastable(SrcTy, DestTy);
2985 // Provide a way to get a "cast" where the cast opcode is inferred from the
2986 // types and size of the operand. This, basically, is a parallel of the
2987 // logic in the castIsValid function below. This axiom should hold:
2988 // castIsValid( getCastOpcode(Val, Ty), Val, Ty)
2989 // should not assert in castIsValid. In other words, this produces a "correct"
2990 // casting opcode for the arguments passed to it.
2991 // This routine must be kept in sync with isCastable.
2992 Instruction::CastOps
2993 CastInst::getCastOpcode(
2994 const Value *Src, bool SrcIsSigned, Type *DestTy, bool DestIsSigned) {
2995 Type *SrcTy = Src->getType();
2997 assert(SrcTy->isFirstClassType() && DestTy->isFirstClassType() &&
2998 "Only first class types are castable!");
3000 if (SrcTy == DestTy)
3003 // FIXME: Check address space sizes here
3004 if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy))
3005 if (VectorType *DestVecTy = dyn_cast<VectorType>(DestTy))
3006 if (SrcVecTy->getNumElements() == DestVecTy->getNumElements()) {
3007 // An element by element cast. Find the appropriate opcode based on the
3009 SrcTy = SrcVecTy->getElementType();
3010 DestTy = DestVecTy->getElementType();
3013 // Get the bit sizes, we'll need these
3014 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); // 0 for ptr
3015 unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr
3017 // Run through the possibilities ...
3018 if (DestTy->isIntegerTy()) { // Casting to integral
3019 if (SrcTy->isIntegerTy()) { // Casting from integral
3020 if (DestBits < SrcBits)
3021 return Trunc; // int -> smaller int
3022 else if (DestBits > SrcBits) { // its an extension
3024 return SExt; // signed -> SEXT
3026 return ZExt; // unsigned -> ZEXT
3028 return BitCast; // Same size, No-op cast
3030 } else if (SrcTy->isFloatingPointTy()) { // Casting from floating pt
3032 return FPToSI; // FP -> sint
3034 return FPToUI; // FP -> uint
3035 } else if (SrcTy->isVectorTy()) {
3036 assert(DestBits == SrcBits &&
3037 "Casting vector to integer of different width");
3038 return BitCast; // Same size, no-op cast
3040 assert(SrcTy->isPointerTy() &&
3041 "Casting from a value that is not first-class type");
3042 return PtrToInt; // ptr -> int
3044 } else if (DestTy->isFloatingPointTy()) { // Casting to floating pt
3045 if (SrcTy->isIntegerTy()) { // Casting from integral
3047 return SIToFP; // sint -> FP
3049 return UIToFP; // uint -> FP
3050 } else if (SrcTy->isFloatingPointTy()) { // Casting from floating pt
3051 if (DestBits < SrcBits) {
3052 return FPTrunc; // FP -> smaller FP
3053 } else if (DestBits > SrcBits) {
3054 return FPExt; // FP -> larger FP
3056 return BitCast; // same size, no-op cast
3058 } else if (SrcTy->isVectorTy()) {
3059 assert(DestBits == SrcBits &&
3060 "Casting vector to floating point of different width");
3061 return BitCast; // same size, no-op cast
3063 llvm_unreachable("Casting pointer or non-first class to float");
3064 } else if (DestTy->isVectorTy()) {
3065 assert(DestBits == SrcBits &&
3066 "Illegal cast to vector (wrong type or size)");
3068 } else if (DestTy->isPointerTy()) {
3069 if (SrcTy->isPointerTy()) {
3070 if (DestTy->getPointerAddressSpace() != SrcTy->getPointerAddressSpace())
3071 return AddrSpaceCast;
3072 return BitCast; // ptr -> ptr
3073 } else if (SrcTy->isIntegerTy()) {
3074 return IntToPtr; // int -> ptr
3076 llvm_unreachable("Casting pointer to other than pointer or int");
3077 } else if (DestTy->isX86_MMXTy()) {
3078 if (SrcTy->isVectorTy()) {
3079 assert(DestBits == SrcBits && "Casting vector of wrong width to X86_MMX");
3080 return BitCast; // 64-bit vector to MMX
3082 llvm_unreachable("Illegal cast to X86_MMX");
3084 llvm_unreachable("Casting to type that is not first-class");
3087 //===----------------------------------------------------------------------===//
3088 // CastInst SubClass Constructors
3089 //===----------------------------------------------------------------------===//
3091 /// Check that the construction parameters for a CastInst are correct. This
3092 /// could be broken out into the separate constructors but it is useful to have
3093 /// it in one place and to eliminate the redundant code for getting the sizes
3094 /// of the types involved.
3096 CastInst::castIsValid(Instruction::CastOps op, Value *S, Type *DstTy) {
3098 // Check for type sanity on the arguments
3099 Type *SrcTy = S->getType();
3101 if (!SrcTy->isFirstClassType() || !DstTy->isFirstClassType() ||
3102 SrcTy->isAggregateType() || DstTy->isAggregateType())
3105 // Get the size of the types in bits, we'll need this later
3106 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
3107 unsigned DstBitSize = DstTy->getScalarSizeInBits();
3109 // If these are vector types, get the lengths of the vectors (using zero for
3110 // scalar types means that checking that vector lengths match also checks that
3111 // scalars are not being converted to vectors or vectors to scalars).
3112 unsigned SrcLength = SrcTy->isVectorTy() ?
3113 cast<VectorType>(SrcTy)->getNumElements() : 0;
3114 unsigned DstLength = DstTy->isVectorTy() ?
3115 cast<VectorType>(DstTy)->getNumElements() : 0;
3117 // Switch on the opcode provided
3119 default: return false; // This is an input error
3120 case Instruction::Trunc:
3121 return SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy() &&
3122 SrcLength == DstLength && SrcBitSize > DstBitSize;
3123 case Instruction::ZExt:
3124 return SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy() &&
3125 SrcLength == DstLength && SrcBitSize < DstBitSize;
3126 case Instruction::SExt:
3127 return SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy() &&
3128 SrcLength == DstLength && SrcBitSize < DstBitSize;
3129 case Instruction::FPTrunc:
3130 return SrcTy->isFPOrFPVectorTy() && DstTy->isFPOrFPVectorTy() &&
3131 SrcLength == DstLength && SrcBitSize > DstBitSize;
3132 case Instruction::FPExt:
3133 return SrcTy->isFPOrFPVectorTy() && DstTy->isFPOrFPVectorTy() &&
3134 SrcLength == DstLength && SrcBitSize < DstBitSize;
3135 case Instruction::UIToFP:
3136 case Instruction::SIToFP:
3137 return SrcTy->isIntOrIntVectorTy() && DstTy->isFPOrFPVectorTy() &&
3138 SrcLength == DstLength;
3139 case Instruction::FPToUI:
3140 case Instruction::FPToSI:
3141 return SrcTy->isFPOrFPVectorTy() && DstTy->isIntOrIntVectorTy() &&
3142 SrcLength == DstLength;
3143 case Instruction::PtrToInt:
3144 if (isa<VectorType>(SrcTy) != isa<VectorType>(DstTy))
3146 if (VectorType *VT = dyn_cast<VectorType>(SrcTy))
3147 if (VT->getNumElements() != cast<VectorType>(DstTy)->getNumElements())
3149 return SrcTy->getScalarType()->isPointerTy() &&
3150 DstTy->getScalarType()->isIntegerTy();
3151 case Instruction::IntToPtr:
3152 if (isa<VectorType>(SrcTy) != isa<VectorType>(DstTy))
3154 if (VectorType *VT = dyn_cast<VectorType>(SrcTy))
3155 if (VT->getNumElements() != cast<VectorType>(DstTy)->getNumElements())
3157 return SrcTy->getScalarType()->isIntegerTy() &&
3158 DstTy->getScalarType()->isPointerTy();
3159 case Instruction::BitCast: {
3160 PointerType *SrcPtrTy = dyn_cast<PointerType>(SrcTy->getScalarType());
3161 PointerType *DstPtrTy = dyn_cast<PointerType>(DstTy->getScalarType());
3163 // BitCast implies a no-op cast of type only. No bits change.
3164 // However, you can't cast pointers to anything but pointers.
3165 if (!SrcPtrTy != !DstPtrTy)
3168 // For non-pointer cases, the cast is okay if the source and destination bit
3169 // widths are identical.
3171 return SrcTy->getPrimitiveSizeInBits() == DstTy->getPrimitiveSizeInBits();
3173 // If both are pointers then the address spaces must match.
3174 if (SrcPtrTy->getAddressSpace() != DstPtrTy->getAddressSpace())
3177 // A vector of pointers must have the same number of elements.
3178 if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy)) {
3179 if (VectorType *DstVecTy = dyn_cast<VectorType>(DstTy))
3180 return (SrcVecTy->getNumElements() == DstVecTy->getNumElements());
3187 case Instruction::AddrSpaceCast: {
3188 PointerType *SrcPtrTy = dyn_cast<PointerType>(SrcTy->getScalarType());
3192 PointerType *DstPtrTy = dyn_cast<PointerType>(DstTy->getScalarType());
3196 if (SrcPtrTy->getAddressSpace() == DstPtrTy->getAddressSpace())
3199 if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy)) {
3200 if (VectorType *DstVecTy = dyn_cast<VectorType>(DstTy))
3201 return (SrcVecTy->getNumElements() == DstVecTy->getNumElements());
3211 TruncInst::TruncInst(
3212 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3213 ) : CastInst(Ty, Trunc, S, Name, InsertBefore) {
3214 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
3217 TruncInst::TruncInst(
3218 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3219 ) : CastInst(Ty, Trunc, S, Name, InsertAtEnd) {
3220 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
3224 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3225 ) : CastInst(Ty, ZExt, S, Name, InsertBefore) {
3226 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
3230 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3231 ) : CastInst(Ty, ZExt, S, Name, InsertAtEnd) {
3232 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
3235 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3236 ) : CastInst(Ty, SExt, S, Name, InsertBefore) {
3237 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
3241 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3242 ) : CastInst(Ty, SExt, S, Name, InsertAtEnd) {
3243 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
3246 FPTruncInst::FPTruncInst(
3247 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3248 ) : CastInst(Ty, FPTrunc, S, Name, InsertBefore) {
3249 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
3252 FPTruncInst::FPTruncInst(
3253 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3254 ) : CastInst(Ty, FPTrunc, S, Name, InsertAtEnd) {
3255 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
3258 FPExtInst::FPExtInst(
3259 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3260 ) : CastInst(Ty, FPExt, S, Name, InsertBefore) {
3261 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
3264 FPExtInst::FPExtInst(
3265 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3266 ) : CastInst(Ty, FPExt, S, Name, InsertAtEnd) {
3267 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
3270 UIToFPInst::UIToFPInst(
3271 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3272 ) : CastInst(Ty, UIToFP, S, Name, InsertBefore) {
3273 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
3276 UIToFPInst::UIToFPInst(
3277 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3278 ) : CastInst(Ty, UIToFP, S, Name, InsertAtEnd) {
3279 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
3282 SIToFPInst::SIToFPInst(
3283 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3284 ) : CastInst(Ty, SIToFP, S, Name, InsertBefore) {
3285 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
3288 SIToFPInst::SIToFPInst(
3289 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3290 ) : CastInst(Ty, SIToFP, S, Name, InsertAtEnd) {
3291 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
3294 FPToUIInst::FPToUIInst(
3295 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3296 ) : CastInst(Ty, FPToUI, S, Name, InsertBefore) {
3297 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
3300 FPToUIInst::FPToUIInst(
3301 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3302 ) : CastInst(Ty, FPToUI, S, Name, InsertAtEnd) {
3303 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
3306 FPToSIInst::FPToSIInst(
3307 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3308 ) : CastInst(Ty, FPToSI, S, Name, InsertBefore) {
3309 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
3312 FPToSIInst::FPToSIInst(
3313 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3314 ) : CastInst(Ty, FPToSI, S, Name, InsertAtEnd) {
3315 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
3318 PtrToIntInst::PtrToIntInst(
3319 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3320 ) : CastInst(Ty, PtrToInt, S, Name, InsertBefore) {
3321 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
3324 PtrToIntInst::PtrToIntInst(
3325 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3326 ) : CastInst(Ty, PtrToInt, S, Name, InsertAtEnd) {
3327 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
3330 IntToPtrInst::IntToPtrInst(
3331 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3332 ) : CastInst(Ty, IntToPtr, S, Name, InsertBefore) {
3333 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
3336 IntToPtrInst::IntToPtrInst(
3337 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3338 ) : CastInst(Ty, IntToPtr, S, Name, InsertAtEnd) {
3339 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
3342 BitCastInst::BitCastInst(
3343 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3344 ) : CastInst(Ty, BitCast, S, Name, InsertBefore) {
3345 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
3348 BitCastInst::BitCastInst(
3349 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3350 ) : CastInst(Ty, BitCast, S, Name, InsertAtEnd) {
3351 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
3354 AddrSpaceCastInst::AddrSpaceCastInst(
3355 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3356 ) : CastInst(Ty, AddrSpaceCast, S, Name, InsertBefore) {
3357 assert(castIsValid(getOpcode(), S, Ty) && "Illegal AddrSpaceCast");
3360 AddrSpaceCastInst::AddrSpaceCastInst(
3361 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3362 ) : CastInst(Ty, AddrSpaceCast, S, Name, InsertAtEnd) {
3363 assert(castIsValid(getOpcode(), S, Ty) && "Illegal AddrSpaceCast");
3366 //===----------------------------------------------------------------------===//
3368 //===----------------------------------------------------------------------===//
3370 void CmpInst::anchor() {}
3372 CmpInst::CmpInst(Type *ty, OtherOps op, unsigned short predicate,
3373 Value *LHS, Value *RHS, const Twine &Name,
3374 Instruction *InsertBefore)
3375 : Instruction(ty, op,
3376 OperandTraits<CmpInst>::op_begin(this),
3377 OperandTraits<CmpInst>::operands(this),
3381 setPredicate((Predicate)predicate);
3385 CmpInst::CmpInst(Type *ty, OtherOps op, unsigned short predicate,
3386 Value *LHS, Value *RHS, const Twine &Name,
3387 BasicBlock *InsertAtEnd)
3388 : Instruction(ty, op,
3389 OperandTraits<CmpInst>::op_begin(this),
3390 OperandTraits<CmpInst>::operands(this),
3394 setPredicate((Predicate)predicate);
3399 CmpInst::Create(OtherOps Op, unsigned short predicate,
3400 Value *S1, Value *S2,
3401 const Twine &Name, Instruction *InsertBefore) {
3402 if (Op == Instruction::ICmp) {
3404 return new ICmpInst(InsertBefore, CmpInst::Predicate(predicate),
3407 return new ICmpInst(CmpInst::Predicate(predicate),
3412 return new FCmpInst(InsertBefore, CmpInst::Predicate(predicate),
3415 return new FCmpInst(CmpInst::Predicate(predicate),
3420 CmpInst::Create(OtherOps Op, unsigned short predicate, Value *S1, Value *S2,
3421 const Twine &Name, BasicBlock *InsertAtEnd) {
3422 if (Op == Instruction::ICmp) {
3423 return new ICmpInst(*InsertAtEnd, CmpInst::Predicate(predicate),
3426 return new FCmpInst(*InsertAtEnd, CmpInst::Predicate(predicate),
3430 void CmpInst::swapOperands() {
3431 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
3434 cast<FCmpInst>(this)->swapOperands();
3437 bool CmpInst::isCommutative() const {
3438 if (const ICmpInst *IC = dyn_cast<ICmpInst>(this))
3439 return IC->isCommutative();
3440 return cast<FCmpInst>(this)->isCommutative();
3443 bool CmpInst::isEquality() const {
3444 if (const ICmpInst *IC = dyn_cast<ICmpInst>(this))
3445 return IC->isEquality();
3446 return cast<FCmpInst>(this)->isEquality();
3450 CmpInst::Predicate CmpInst::getInversePredicate(Predicate pred) {
3452 default: llvm_unreachable("Unknown cmp predicate!");
3453 case ICMP_EQ: return ICMP_NE;
3454 case ICMP_NE: return ICMP_EQ;
3455 case ICMP_UGT: return ICMP_ULE;
3456 case ICMP_ULT: return ICMP_UGE;
3457 case ICMP_UGE: return ICMP_ULT;
3458 case ICMP_ULE: return ICMP_UGT;
3459 case ICMP_SGT: return ICMP_SLE;
3460 case ICMP_SLT: return ICMP_SGE;
3461 case ICMP_SGE: return ICMP_SLT;
3462 case ICMP_SLE: return ICMP_SGT;
3464 case FCMP_OEQ: return FCMP_UNE;
3465 case FCMP_ONE: return FCMP_UEQ;
3466 case FCMP_OGT: return FCMP_ULE;
3467 case FCMP_OLT: return FCMP_UGE;
3468 case FCMP_OGE: return FCMP_ULT;
3469 case FCMP_OLE: return FCMP_UGT;
3470 case FCMP_UEQ: return FCMP_ONE;
3471 case FCMP_UNE: return FCMP_OEQ;
3472 case FCMP_UGT: return FCMP_OLE;
3473 case FCMP_ULT: return FCMP_OGE;
3474 case FCMP_UGE: return FCMP_OLT;
3475 case FCMP_ULE: return FCMP_OGT;
3476 case FCMP_ORD: return FCMP_UNO;
3477 case FCMP_UNO: return FCMP_ORD;
3478 case FCMP_TRUE: return FCMP_FALSE;
3479 case FCMP_FALSE: return FCMP_TRUE;
3483 ICmpInst::Predicate ICmpInst::getSignedPredicate(Predicate pred) {
3485 default: llvm_unreachable("Unknown icmp predicate!");
3486 case ICMP_EQ: case ICMP_NE:
3487 case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE:
3489 case ICMP_UGT: return ICMP_SGT;
3490 case ICMP_ULT: return ICMP_SLT;
3491 case ICMP_UGE: return ICMP_SGE;
3492 case ICMP_ULE: return ICMP_SLE;
3496 ICmpInst::Predicate ICmpInst::getUnsignedPredicate(Predicate pred) {
3498 default: llvm_unreachable("Unknown icmp predicate!");
3499 case ICMP_EQ: case ICMP_NE:
3500 case ICMP_UGT: case ICMP_ULT: case ICMP_UGE: case ICMP_ULE:
3502 case ICMP_SGT: return ICMP_UGT;
3503 case ICMP_SLT: return ICMP_ULT;
3504 case ICMP_SGE: return ICMP_UGE;
3505 case ICMP_SLE: return ICMP_ULE;
3509 /// Initialize a set of values that all satisfy the condition with C.
3512 ICmpInst::makeConstantRange(Predicate pred, const APInt &C) {
3515 uint32_t BitWidth = C.getBitWidth();
3517 default: llvm_unreachable("Invalid ICmp opcode to ConstantRange ctor!");
3518 case ICmpInst::ICMP_EQ: ++Upper; break;
3519 case ICmpInst::ICMP_NE: ++Lower; break;
3520 case ICmpInst::ICMP_ULT:
3521 Lower = APInt::getMinValue(BitWidth);
3522 // Check for an empty-set condition.
3524 return ConstantRange(BitWidth, /*isFullSet=*/false);
3526 case ICmpInst::ICMP_SLT:
3527 Lower = APInt::getSignedMinValue(BitWidth);
3528 // Check for an empty-set condition.
3530 return ConstantRange(BitWidth, /*isFullSet=*/false);
3532 case ICmpInst::ICMP_UGT:
3533 ++Lower; Upper = APInt::getMinValue(BitWidth); // Min = Next(Max)
3534 // Check for an empty-set condition.
3536 return ConstantRange(BitWidth, /*isFullSet=*/false);
3538 case ICmpInst::ICMP_SGT:
3539 ++Lower; Upper = APInt::getSignedMinValue(BitWidth); // Min = Next(Max)
3540 // Check for an empty-set condition.
3542 return ConstantRange(BitWidth, /*isFullSet=*/false);
3544 case ICmpInst::ICMP_ULE:
3545 Lower = APInt::getMinValue(BitWidth); ++Upper;
3546 // Check for a full-set condition.
3548 return ConstantRange(BitWidth, /*isFullSet=*/true);
3550 case ICmpInst::ICMP_SLE:
3551 Lower = APInt::getSignedMinValue(BitWidth); ++Upper;
3552 // Check for a full-set condition.
3554 return ConstantRange(BitWidth, /*isFullSet=*/true);
3556 case ICmpInst::ICMP_UGE:
3557 Upper = APInt::getMinValue(BitWidth); // Min = Next(Max)
3558 // Check for a full-set condition.
3560 return ConstantRange(BitWidth, /*isFullSet=*/true);
3562 case ICmpInst::ICMP_SGE:
3563 Upper = APInt::getSignedMinValue(BitWidth); // Min = Next(Max)
3564 // Check for a full-set condition.
3566 return ConstantRange(BitWidth, /*isFullSet=*/true);
3569 return ConstantRange(Lower, Upper);
3572 CmpInst::Predicate CmpInst::getSwappedPredicate(Predicate pred) {
3574 default: llvm_unreachable("Unknown cmp predicate!");
3575 case ICMP_EQ: case ICMP_NE:
3577 case ICMP_SGT: return ICMP_SLT;
3578 case ICMP_SLT: return ICMP_SGT;
3579 case ICMP_SGE: return ICMP_SLE;
3580 case ICMP_SLE: return ICMP_SGE;
3581 case ICMP_UGT: return ICMP_ULT;
3582 case ICMP_ULT: return ICMP_UGT;
3583 case ICMP_UGE: return ICMP_ULE;
3584 case ICMP_ULE: return ICMP_UGE;
3586 case FCMP_FALSE: case FCMP_TRUE:
3587 case FCMP_OEQ: case FCMP_ONE:
3588 case FCMP_UEQ: case FCMP_UNE:
3589 case FCMP_ORD: case FCMP_UNO:
3591 case FCMP_OGT: return FCMP_OLT;
3592 case FCMP_OLT: return FCMP_OGT;
3593 case FCMP_OGE: return FCMP_OLE;
3594 case FCMP_OLE: return FCMP_OGE;
3595 case FCMP_UGT: return FCMP_ULT;
3596 case FCMP_ULT: return FCMP_UGT;
3597 case FCMP_UGE: return FCMP_ULE;
3598 case FCMP_ULE: return FCMP_UGE;
3602 CmpInst::Predicate CmpInst::getSignedPredicate(Predicate pred) {
3603 assert(CmpInst::isUnsigned(pred) && "Call only with signed predicates!");
3607 llvm_unreachable("Unknown predicate!");
3608 case CmpInst::ICMP_ULT:
3609 return CmpInst::ICMP_SLT;
3610 case CmpInst::ICMP_ULE:
3611 return CmpInst::ICMP_SLE;
3612 case CmpInst::ICMP_UGT:
3613 return CmpInst::ICMP_SGT;
3614 case CmpInst::ICMP_UGE:
3615 return CmpInst::ICMP_SGE;
3619 bool CmpInst::isUnsigned(unsigned short predicate) {
3620 switch (predicate) {
3621 default: return false;
3622 case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_ULE: case ICmpInst::ICMP_UGT:
3623 case ICmpInst::ICMP_UGE: return true;
3627 bool CmpInst::isSigned(unsigned short predicate) {
3628 switch (predicate) {
3629 default: return false;
3630 case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_SLE: case ICmpInst::ICMP_SGT:
3631 case ICmpInst::ICMP_SGE: return true;
3635 bool CmpInst::isOrdered(unsigned short predicate) {
3636 switch (predicate) {
3637 default: return false;
3638 case FCmpInst::FCMP_OEQ: case FCmpInst::FCMP_ONE: case FCmpInst::FCMP_OGT:
3639 case FCmpInst::FCMP_OLT: case FCmpInst::FCMP_OGE: case FCmpInst::FCMP_OLE:
3640 case FCmpInst::FCMP_ORD: return true;
3644 bool CmpInst::isUnordered(unsigned short predicate) {
3645 switch (predicate) {
3646 default: return false;
3647 case FCmpInst::FCMP_UEQ: case FCmpInst::FCMP_UNE: case FCmpInst::FCMP_UGT:
3648 case FCmpInst::FCMP_ULT: case FCmpInst::FCMP_UGE: case FCmpInst::FCMP_ULE:
3649 case FCmpInst::FCMP_UNO: return true;
3653 bool CmpInst::isTrueWhenEqual(unsigned short predicate) {
3655 default: return false;
3656 case ICMP_EQ: case ICMP_UGE: case ICMP_ULE: case ICMP_SGE: case ICMP_SLE:
3657 case FCMP_TRUE: case FCMP_UEQ: case FCMP_UGE: case FCMP_ULE: return true;
3661 bool CmpInst::isFalseWhenEqual(unsigned short predicate) {
3663 case ICMP_NE: case ICMP_UGT: case ICMP_ULT: case ICMP_SGT: case ICMP_SLT:
3664 case FCMP_FALSE: case FCMP_ONE: case FCMP_OGT: case FCMP_OLT: return true;
3665 default: return false;
3670 //===----------------------------------------------------------------------===//
3671 // SwitchInst Implementation
3672 //===----------------------------------------------------------------------===//
3674 void SwitchInst::init(Value *Value, BasicBlock *Default, unsigned NumReserved) {
3675 assert(Value && Default && NumReserved);
3676 ReservedSpace = NumReserved;
3677 setNumHungOffUseOperands(2);
3678 allocHungoffUses(ReservedSpace);
3684 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
3685 /// switch on and a default destination. The number of additional cases can
3686 /// be specified here to make memory allocation more efficient. This
3687 /// constructor can also autoinsert before another instruction.
3688 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
3689 Instruction *InsertBefore)
3690 : TerminatorInst(Type::getVoidTy(Value->getContext()), Instruction::Switch,
3691 nullptr, 0, InsertBefore) {
3692 init(Value, Default, 2+NumCases*2);
3695 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
3696 /// switch on and a default destination. The number of additional cases can
3697 /// be specified here to make memory allocation more efficient. This
3698 /// constructor also autoinserts at the end of the specified BasicBlock.
3699 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
3700 BasicBlock *InsertAtEnd)
3701 : TerminatorInst(Type::getVoidTy(Value->getContext()), Instruction::Switch,
3702 nullptr, 0, InsertAtEnd) {
3703 init(Value, Default, 2+NumCases*2);
3706 SwitchInst::SwitchInst(const SwitchInst &SI)
3707 : TerminatorInst(SI.getType(), Instruction::Switch, nullptr, 0) {
3708 init(SI.getCondition(), SI.getDefaultDest(), SI.getNumOperands());
3709 setNumHungOffUseOperands(SI.getNumOperands());
3710 Use *OL = getOperandList();
3711 const Use *InOL = SI.getOperandList();
3712 for (unsigned i = 2, E = SI.getNumOperands(); i != E; i += 2) {
3714 OL[i+1] = InOL[i+1];
3716 SubclassOptionalData = SI.SubclassOptionalData;
3720 /// addCase - Add an entry to the switch instruction...
3722 void SwitchInst::addCase(ConstantInt *OnVal, BasicBlock *Dest) {
3723 unsigned NewCaseIdx = getNumCases();
3724 unsigned OpNo = getNumOperands();
3725 if (OpNo+2 > ReservedSpace)
3726 growOperands(); // Get more space!
3727 // Initialize some new operands.
3728 assert(OpNo+1 < ReservedSpace && "Growing didn't work!");
3729 setNumHungOffUseOperands(OpNo+2);
3730 CaseIt Case(this, NewCaseIdx);
3731 Case.setValue(OnVal);
3732 Case.setSuccessor(Dest);
3735 /// removeCase - This method removes the specified case and its successor
3736 /// from the switch instruction.
3737 void SwitchInst::removeCase(CaseIt i) {
3738 unsigned idx = i.getCaseIndex();
3740 assert(2 + idx*2 < getNumOperands() && "Case index out of range!!!");
3742 unsigned NumOps = getNumOperands();
3743 Use *OL = getOperandList();
3745 // Overwrite this case with the end of the list.
3746 if (2 + (idx + 1) * 2 != NumOps) {
3747 OL[2 + idx * 2] = OL[NumOps - 2];
3748 OL[2 + idx * 2 + 1] = OL[NumOps - 1];
3751 // Nuke the last value.
3752 OL[NumOps-2].set(nullptr);
3753 OL[NumOps-2+1].set(nullptr);
3754 setNumHungOffUseOperands(NumOps-2);
3757 /// growOperands - grow operands - This grows the operand list in response
3758 /// to a push_back style of operation. This grows the number of ops by 3 times.
3760 void SwitchInst::growOperands() {
3761 unsigned e = getNumOperands();
3762 unsigned NumOps = e*3;
3764 ReservedSpace = NumOps;
3765 growHungoffUses(ReservedSpace);
3769 BasicBlock *SwitchInst::getSuccessorV(unsigned idx) const {
3770 return getSuccessor(idx);
3772 unsigned SwitchInst::getNumSuccessorsV() const {
3773 return getNumSuccessors();
3775 void SwitchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
3776 setSuccessor(idx, B);
3779 //===----------------------------------------------------------------------===//
3780 // IndirectBrInst Implementation
3781 //===----------------------------------------------------------------------===//
3783 void IndirectBrInst::init(Value *Address, unsigned NumDests) {
3784 assert(Address && Address->getType()->isPointerTy() &&
3785 "Address of indirectbr must be a pointer");
3786 ReservedSpace = 1+NumDests;
3787 setNumHungOffUseOperands(1);
3788 allocHungoffUses(ReservedSpace);
3794 /// growOperands - grow operands - This grows the operand list in response
3795 /// to a push_back style of operation. This grows the number of ops by 2 times.
3797 void IndirectBrInst::growOperands() {
3798 unsigned e = getNumOperands();
3799 unsigned NumOps = e*2;
3801 ReservedSpace = NumOps;
3802 growHungoffUses(ReservedSpace);
3805 IndirectBrInst::IndirectBrInst(Value *Address, unsigned NumCases,
3806 Instruction *InsertBefore)
3807 : TerminatorInst(Type::getVoidTy(Address->getContext()),Instruction::IndirectBr,
3808 nullptr, 0, InsertBefore) {
3809 init(Address, NumCases);
3812 IndirectBrInst::IndirectBrInst(Value *Address, unsigned NumCases,
3813 BasicBlock *InsertAtEnd)
3814 : TerminatorInst(Type::getVoidTy(Address->getContext()),Instruction::IndirectBr,
3815 nullptr, 0, InsertAtEnd) {
3816 init(Address, NumCases);
3819 IndirectBrInst::IndirectBrInst(const IndirectBrInst &IBI)
3820 : TerminatorInst(Type::getVoidTy(IBI.getContext()), Instruction::IndirectBr,
3821 nullptr, IBI.getNumOperands()) {
3822 allocHungoffUses(IBI.getNumOperands());
3823 Use *OL = getOperandList();
3824 const Use *InOL = IBI.getOperandList();
3825 for (unsigned i = 0, E = IBI.getNumOperands(); i != E; ++i)
3827 SubclassOptionalData = IBI.SubclassOptionalData;
3830 /// addDestination - Add a destination.
3832 void IndirectBrInst::addDestination(BasicBlock *DestBB) {
3833 unsigned OpNo = getNumOperands();
3834 if (OpNo+1 > ReservedSpace)
3835 growOperands(); // Get more space!
3836 // Initialize some new operands.
3837 assert(OpNo < ReservedSpace && "Growing didn't work!");
3838 setNumHungOffUseOperands(OpNo+1);
3839 getOperandList()[OpNo] = DestBB;
3842 /// removeDestination - This method removes the specified successor from the
3843 /// indirectbr instruction.
3844 void IndirectBrInst::removeDestination(unsigned idx) {
3845 assert(idx < getNumOperands()-1 && "Successor index out of range!");
3847 unsigned NumOps = getNumOperands();
3848 Use *OL = getOperandList();
3850 // Replace this value with the last one.
3851 OL[idx+1] = OL[NumOps-1];
3853 // Nuke the last value.
3854 OL[NumOps-1].set(nullptr);
3855 setNumHungOffUseOperands(NumOps-1);
3858 BasicBlock *IndirectBrInst::getSuccessorV(unsigned idx) const {
3859 return getSuccessor(idx);
3861 unsigned IndirectBrInst::getNumSuccessorsV() const {
3862 return getNumSuccessors();
3864 void IndirectBrInst::setSuccessorV(unsigned idx, BasicBlock *B) {
3865 setSuccessor(idx, B);
3868 //===----------------------------------------------------------------------===//
3869 // cloneImpl() implementations
3870 //===----------------------------------------------------------------------===//
3872 // Define these methods here so vtables don't get emitted into every translation
3873 // unit that uses these classes.
3875 GetElementPtrInst *GetElementPtrInst::cloneImpl() const {
3876 return new (getNumOperands()) GetElementPtrInst(*this);
3879 BinaryOperator *BinaryOperator::cloneImpl() const {
3880 return Create(getOpcode(), Op<0>(), Op<1>());
3883 FCmpInst *FCmpInst::cloneImpl() const {
3884 return new FCmpInst(getPredicate(), Op<0>(), Op<1>());
3887 ICmpInst *ICmpInst::cloneImpl() const {
3888 return new ICmpInst(getPredicate(), Op<0>(), Op<1>());
3891 ExtractValueInst *ExtractValueInst::cloneImpl() const {
3892 return new ExtractValueInst(*this);
3895 InsertValueInst *InsertValueInst::cloneImpl() const {
3896 return new InsertValueInst(*this);
3899 AllocaInst *AllocaInst::cloneImpl() const {
3900 AllocaInst *Result = new AllocaInst(getAllocatedType(),
3901 (Value *)getOperand(0), getAlignment());
3902 Result->setUsedWithInAlloca(isUsedWithInAlloca());
3906 LoadInst *LoadInst::cloneImpl() const {
3907 return new LoadInst(getOperand(0), Twine(), isVolatile(),
3908 getAlignment(), getOrdering(), getSynchScope());
3911 StoreInst *StoreInst::cloneImpl() const {
3912 return new StoreInst(getOperand(0), getOperand(1), isVolatile(),
3913 getAlignment(), getOrdering(), getSynchScope());
3917 AtomicCmpXchgInst *AtomicCmpXchgInst::cloneImpl() const {
3918 AtomicCmpXchgInst *Result =
3919 new AtomicCmpXchgInst(getOperand(0), getOperand(1), getOperand(2),
3920 getSuccessOrdering(), getFailureOrdering(),
3922 Result->setVolatile(isVolatile());
3923 Result->setWeak(isWeak());
3927 AtomicRMWInst *AtomicRMWInst::cloneImpl() const {
3928 AtomicRMWInst *Result =
3929 new AtomicRMWInst(getOperation(),getOperand(0), getOperand(1),
3930 getOrdering(), getSynchScope());
3931 Result->setVolatile(isVolatile());
3935 FenceInst *FenceInst::cloneImpl() const {
3936 return new FenceInst(getContext(), getOrdering(), getSynchScope());
3939 TruncInst *TruncInst::cloneImpl() const {
3940 return new TruncInst(getOperand(0), getType());
3943 ZExtInst *ZExtInst::cloneImpl() const {
3944 return new ZExtInst(getOperand(0), getType());
3947 SExtInst *SExtInst::cloneImpl() const {
3948 return new SExtInst(getOperand(0), getType());
3951 FPTruncInst *FPTruncInst::cloneImpl() const {
3952 return new FPTruncInst(getOperand(0), getType());
3955 FPExtInst *FPExtInst::cloneImpl() const {
3956 return new FPExtInst(getOperand(0), getType());
3959 UIToFPInst *UIToFPInst::cloneImpl() const {
3960 return new UIToFPInst(getOperand(0), getType());
3963 SIToFPInst *SIToFPInst::cloneImpl() const {
3964 return new SIToFPInst(getOperand(0), getType());
3967 FPToUIInst *FPToUIInst::cloneImpl() const {
3968 return new FPToUIInst(getOperand(0), getType());
3971 FPToSIInst *FPToSIInst::cloneImpl() const {
3972 return new FPToSIInst(getOperand(0), getType());
3975 PtrToIntInst *PtrToIntInst::cloneImpl() const {
3976 return new PtrToIntInst(getOperand(0), getType());
3979 IntToPtrInst *IntToPtrInst::cloneImpl() const {
3980 return new IntToPtrInst(getOperand(0), getType());
3983 BitCastInst *BitCastInst::cloneImpl() const {
3984 return new BitCastInst(getOperand(0), getType());
3987 AddrSpaceCastInst *AddrSpaceCastInst::cloneImpl() const {
3988 return new AddrSpaceCastInst(getOperand(0), getType());
3991 CallInst *CallInst::cloneImpl() const {
3992 return new(getNumOperands()) CallInst(*this);
3995 SelectInst *SelectInst::cloneImpl() const {
3996 return SelectInst::Create(getOperand(0), getOperand(1), getOperand(2));
3999 VAArgInst *VAArgInst::cloneImpl() const {
4000 return new VAArgInst(getOperand(0), getType());
4003 ExtractElementInst *ExtractElementInst::cloneImpl() const {
4004 return ExtractElementInst::Create(getOperand(0), getOperand(1));
4007 InsertElementInst *InsertElementInst::cloneImpl() const {
4008 return InsertElementInst::Create(getOperand(0), getOperand(1), getOperand(2));
4011 ShuffleVectorInst *ShuffleVectorInst::cloneImpl() const {
4012 return new ShuffleVectorInst(getOperand(0), getOperand(1), getOperand(2));
4015 PHINode *PHINode::cloneImpl() const { return new PHINode(*this); }
4017 LandingPadInst *LandingPadInst::cloneImpl() const {
4018 return new LandingPadInst(*this);
4021 ReturnInst *ReturnInst::cloneImpl() const {
4022 return new(getNumOperands()) ReturnInst(*this);
4025 BranchInst *BranchInst::cloneImpl() const {
4026 return new(getNumOperands()) BranchInst(*this);
4029 SwitchInst *SwitchInst::cloneImpl() const { return new SwitchInst(*this); }
4031 IndirectBrInst *IndirectBrInst::cloneImpl() const {
4032 return new IndirectBrInst(*this);
4035 InvokeInst *InvokeInst::cloneImpl() const {
4036 return new(getNumOperands()) InvokeInst(*this);
4039 ResumeInst *ResumeInst::cloneImpl() const { return new (1) ResumeInst(*this); }
4041 CleanupEndPadInst *CleanupEndPadInst::cloneImpl() const {
4042 return new (getNumOperands()) CleanupEndPadInst(*this);
4045 CleanupReturnInst *CleanupReturnInst::cloneImpl() const {
4046 return new (getNumOperands()) CleanupReturnInst(*this);
4049 CatchEndPadInst *CatchEndPadInst::cloneImpl() const {
4050 return new (getNumOperands()) CatchEndPadInst(*this);
4053 CatchReturnInst *CatchReturnInst::cloneImpl() const {
4054 return new (getNumOperands()) CatchReturnInst(*this);
4057 CatchPadInst *CatchPadInst::cloneImpl() const {
4058 return new (getNumOperands()) CatchPadInst(*this);
4061 TerminatePadInst *TerminatePadInst::cloneImpl() const {
4062 return new (getNumOperands()) TerminatePadInst(*this);
4065 CleanupPadInst *CleanupPadInst::cloneImpl() const {
4066 return new (getNumOperands()) CleanupPadInst(*this);
4069 UnreachableInst *UnreachableInst::cloneImpl() const {
4070 LLVMContext &Context = getContext();
4071 return new UnreachableInst(Context);