#include "llvm/IR/Instructions.h"
#include "LLVMContextImpl.h"
#include "llvm/ADT/None.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/Twine.h"
#include "llvm/IR/Attributes.h"
#include "llvm/IR/BasicBlock.h"
#include "llvm/IR/Constant.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/InstrTypes.h"
#include "llvm/IR/Instruction.h"
#include "llvm/IR/Intrinsics.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/MDBuilder.h"
#include "llvm/IR/Metadata.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Operator.h"
#include "llvm/IR/Type.h"
#include "llvm/IR/Value.h"
#include "llvm/Support/AtomicOrdering.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/MathExtras.h"
#include "llvm/Support/TypeSize.h"
#include <algorithm>
#include <cassert>
#include <cstdint>
#include <vector>
using namespace llvm;
static cl::opt<bool> DisableI2pP2iOpt(
"disable-i2p-p2i-opt", cl::init(false),
cl::desc("Disables inttoptr/ptrtoint roundtrip optimization"));
Optional<TypeSize>
AllocaInst::getAllocationSizeInBits(const DataLayout &DL) const {
TypeSize Size = DL.getTypeAllocSizeInBits(getAllocatedType());
if (isArrayAllocation()) {
auto *C = dyn_cast<ConstantInt>(getArraySize());
if (!C)
return None;
assert(!Size.isScalable() && "Array elements cannot have a scalable size");
Size *= C->getZExtValue();
}
return Size;
}
const char *SelectInst::areInvalidOperands(Value *Op0, Value *Op1, Value *Op2) {
if (Op1->getType() != Op2->getType())
return "both values to select must have same type";
if (Op1->getType()->isTokenTy())
return "select values cannot have token type";
if (VectorType *VT = dyn_cast<VectorType>(Op0->getType())) {
if (VT->getElementType() != Type::getInt1Ty(Op0->getContext()))
return "vector select condition element type must be i1";
VectorType *ET = dyn_cast<VectorType>(Op1->getType());
if (!ET)
return "selected values for vector select must be vectors";
if (ET->getElementCount() != VT->getElementCount())
return "vector select requires selected vectors to have "
"the same vector length as select condition";
} else if (Op0->getType() != Type::getInt1Ty(Op0->getContext())) {
return "select condition must be i1 or <n x i1>";
}
return nullptr;
}
PHINode::PHINode(const PHINode &PN)
: Instruction(PN.getType(), Instruction::PHI, nullptr, PN.getNumOperands()),
ReservedSpace(PN.getNumOperands()) {
allocHungoffUses(PN.getNumOperands());
std::copy(PN.op_begin(), PN.op_end(), op_begin());
std::copy(PN.block_begin(), PN.block_end(), block_begin());
SubclassOptionalData = PN.SubclassOptionalData;
}
Value *PHINode::removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty) {
Value *Removed = getIncomingValue(Idx);
std::copy(op_begin() + Idx + 1, op_end(), op_begin() + Idx);
std::copy(block_begin() + Idx + 1, block_end(), block_begin() + Idx);
Op<-1>().set(nullptr);
setNumHungOffUseOperands(getNumOperands() - 1);
if (getNumOperands() == 0 && DeletePHIIfEmpty) {
replaceAllUsesWith(PoisonValue::get(getType()));
eraseFromParent();
}
return Removed;
}
void PHINode::growOperands() {
unsigned e = getNumOperands();
unsigned NumOps = e + e / 2;
if (NumOps < 2) NumOps = 2;
ReservedSpace = NumOps;
growHungoffUses(ReservedSpace, true);
}
Value *PHINode::hasConstantValue() const {
Value *ConstantValue = getIncomingValue(0);
for (unsigned i = 1, e = getNumIncomingValues(); i != e; ++i)
if (getIncomingValue(i) != ConstantValue && getIncomingValue(i) != this) {
if (ConstantValue != this)
return nullptr; ConstantValue = getIncomingValue(i);
}
if (ConstantValue == this)
return UndefValue::get(getType());
return ConstantValue;
}
bool PHINode::hasConstantOrUndefValue() const {
Value *ConstantValue = nullptr;
for (unsigned i = 0, e = getNumIncomingValues(); i != e; ++i) {
Value *Incoming = getIncomingValue(i);
if (Incoming != this && !isa<UndefValue>(Incoming)) {
if (ConstantValue && ConstantValue != Incoming)
return false;
ConstantValue = Incoming;
}
}
return true;
}
LandingPadInst::LandingPadInst(Type *RetTy, unsigned NumReservedValues,
const Twine &NameStr, Instruction *InsertBefore)
: Instruction(RetTy, Instruction::LandingPad, nullptr, 0, InsertBefore) {
init(NumReservedValues, NameStr);
}
LandingPadInst::LandingPadInst(Type *RetTy, unsigned NumReservedValues,
const Twine &NameStr, BasicBlock *InsertAtEnd)
: Instruction(RetTy, Instruction::LandingPad, nullptr, 0, InsertAtEnd) {
init(NumReservedValues, NameStr);
}
LandingPadInst::LandingPadInst(const LandingPadInst &LP)
: Instruction(LP.getType(), Instruction::LandingPad, nullptr,
LP.getNumOperands()),
ReservedSpace(LP.getNumOperands()) {
allocHungoffUses(LP.getNumOperands());
Use *OL = getOperandList();
const Use *InOL = LP.getOperandList();
for (unsigned I = 0, E = ReservedSpace; I != E; ++I)
OL[I] = InOL[I];
setCleanup(LP.isCleanup());
}
LandingPadInst *LandingPadInst::Create(Type *RetTy, unsigned NumReservedClauses,
const Twine &NameStr,
Instruction *InsertBefore) {
return new LandingPadInst(RetTy, NumReservedClauses, NameStr, InsertBefore);
}
LandingPadInst *LandingPadInst::Create(Type *RetTy, unsigned NumReservedClauses,
const Twine &NameStr,
BasicBlock *InsertAtEnd) {
return new LandingPadInst(RetTy, NumReservedClauses, NameStr, InsertAtEnd);
}
void LandingPadInst::init(unsigned NumReservedValues, const Twine &NameStr) {
ReservedSpace = NumReservedValues;
setNumHungOffUseOperands(0);
allocHungoffUses(ReservedSpace);
setName(NameStr);
setCleanup(false);
}
void LandingPadInst::growOperands(unsigned Size) {
unsigned e = getNumOperands();
if (ReservedSpace >= e + Size) return;
ReservedSpace = (std::max(e, 1U) + Size / 2) * 2;
growHungoffUses(ReservedSpace);
}
void LandingPadInst::addClause(Constant *Val) {
unsigned OpNo = getNumOperands();
growOperands(1);
assert(OpNo < ReservedSpace && "Growing didn't work!");
setNumHungOffUseOperands(getNumOperands() + 1);
getOperandList()[OpNo] = Val;
}
CallBase *CallBase::Create(CallBase *CB, ArrayRef<OperandBundleDef> Bundles,
Instruction *InsertPt) {
switch (CB->getOpcode()) {
case Instruction::Call:
return CallInst::Create(cast<CallInst>(CB), Bundles, InsertPt);
case Instruction::Invoke:
return InvokeInst::Create(cast<InvokeInst>(CB), Bundles, InsertPt);
case Instruction::CallBr:
return CallBrInst::Create(cast<CallBrInst>(CB), Bundles, InsertPt);
default:
llvm_unreachable("Unknown CallBase sub-class!");
}
}
CallBase *CallBase::Create(CallBase *CI, OperandBundleDef OpB,
Instruction *InsertPt) {
SmallVector<OperandBundleDef, 2> OpDefs;
for (unsigned i = 0, e = CI->getNumOperandBundles(); i < e; ++i) {
auto ChildOB = CI->getOperandBundleAt(i);
if (ChildOB.getTagName() != OpB.getTag())
OpDefs.emplace_back(ChildOB);
}
OpDefs.emplace_back(OpB);
return CallBase::Create(CI, OpDefs, InsertPt);
}
Function *CallBase::getCaller() { return getParent()->getParent(); }
unsigned CallBase::getNumSubclassExtraOperandsDynamic() const {
assert(getOpcode() == Instruction::CallBr && "Unexpected opcode!");
return cast<CallBrInst>(this)->getNumIndirectDests() + 1;
}
bool CallBase::isIndirectCall() const {
const Value *V = getCalledOperand();
if (isa<Function>(V) || isa<Constant>(V))
return false;
return !isInlineAsm();
}
bool CallBase::isMustTailCall() const {
if (auto *CI = dyn_cast<CallInst>(this))
return CI->isMustTailCall();
return false;
}
bool CallBase::isTailCall() const {
if (auto *CI = dyn_cast<CallInst>(this))
return CI->isTailCall();
return false;
}
Intrinsic::ID CallBase::getIntrinsicID() const {
if (auto *F = getCalledFunction())
return F->getIntrinsicID();
return Intrinsic::not_intrinsic;
}
bool CallBase::isReturnNonNull() const {
if (hasRetAttr(Attribute::NonNull))
return true;
if (getRetDereferenceableBytes() > 0 &&
!NullPointerIsDefined(getCaller(), getType()->getPointerAddressSpace()))
return true;
return false;
}
Value *CallBase::getArgOperandWithAttribute(Attribute::AttrKind Kind) const {
unsigned Index;
if (Attrs.hasAttrSomewhere(Kind, &Index))
return getArgOperand(Index - AttributeList::FirstArgIndex);
if (const Function *F = getCalledFunction())
if (F->getAttributes().hasAttrSomewhere(Kind, &Index))
return getArgOperand(Index - AttributeList::FirstArgIndex);
return nullptr;
}
bool CallBase::paramHasAttr(unsigned ArgNo, Attribute::AttrKind Kind) const {
assert(ArgNo < arg_size() && "Param index out of bounds!");
if (Attrs.hasParamAttr(ArgNo, Kind))
return true;
if (const Function *F = getCalledFunction())
return F->getAttributes().hasParamAttr(ArgNo, Kind);
return false;
}
bool CallBase::hasFnAttrOnCalledFunction(Attribute::AttrKind Kind) const {
Value *V = getCalledOperand();
if (auto *CE = dyn_cast<ConstantExpr>(V))
if (CE->getOpcode() == BitCast)
V = CE->getOperand(0);
if (auto *F = dyn_cast<Function>(V))
return F->getAttributes().hasFnAttr(Kind);
return false;
}
bool CallBase::hasFnAttrOnCalledFunction(StringRef Kind) const {
Value *V = getCalledOperand();
if (auto *CE = dyn_cast<ConstantExpr>(V))
if (CE->getOpcode() == BitCast)
V = CE->getOperand(0);
if (auto *F = dyn_cast<Function>(V))
return F->getAttributes().hasFnAttr(Kind);
return false;
}
template <typename AK>
Attribute CallBase::getFnAttrOnCalledFunction(AK Kind) const {
if (isFnAttrDisallowedByOpBundle(Kind))
return Attribute();
Value *V = getCalledOperand();
if (auto *CE = dyn_cast<ConstantExpr>(V))
if (CE->getOpcode() == BitCast)
V = CE->getOperand(0);
if (auto *F = dyn_cast<Function>(V))
return F->getAttributes().getFnAttr(Kind);
return Attribute();
}
template Attribute
CallBase::getFnAttrOnCalledFunction(Attribute::AttrKind Kind) const;
template Attribute CallBase::getFnAttrOnCalledFunction(StringRef Kind) const;
void CallBase::getOperandBundlesAsDefs(
SmallVectorImpl<OperandBundleDef> &Defs) const {
for (unsigned i = 0, e = getNumOperandBundles(); i != e; ++i)
Defs.emplace_back(getOperandBundleAt(i));
}
CallBase::op_iterator
CallBase::populateBundleOperandInfos(ArrayRef<OperandBundleDef> Bundles,
const unsigned BeginIndex) {
auto It = op_begin() + BeginIndex;
for (auto &B : Bundles)
It = std::copy(B.input_begin(), B.input_end(), It);
auto *ContextImpl = getContext().pImpl;
auto BI = Bundles.begin();
unsigned CurrentIndex = BeginIndex;
for (auto &BOI : bundle_op_infos()) {
assert(BI != Bundles.end() && "Incorrect allocation?");
BOI.Tag = ContextImpl->getOrInsertBundleTag(BI->getTag());
BOI.Begin = CurrentIndex;
BOI.End = CurrentIndex + BI->input_size();
CurrentIndex = BOI.End;
BI++;
}
assert(BI == Bundles.end() && "Incorrect allocation?");
return It;
}
CallBase::BundleOpInfo &CallBase::getBundleOpInfoForOperand(unsigned OpIdx) {
if (bundle_op_info_end() - bundle_op_info_begin() < 8) {
for (auto &BOI : bundle_op_infos())
if (BOI.Begin <= OpIdx && OpIdx < BOI.End)
return BOI;
llvm_unreachable("Did not find operand bundle for operand!");
}
assert(OpIdx >= arg_size() && "the Idx is not in the operand bundles");
assert(bundle_op_info_end() - bundle_op_info_begin() > 0 &&
OpIdx < std::prev(bundle_op_info_end())->End &&
"The Idx isn't in the operand bundle");
constexpr unsigned NumberScaling = 1024;
bundle_op_iterator Begin = bundle_op_info_begin();
bundle_op_iterator End = bundle_op_info_end();
bundle_op_iterator Current = Begin;
while (Begin != End) {
unsigned ScaledOperandPerBundle =
NumberScaling * (std::prev(End)->End - Begin->Begin) / (End - Begin);
Current = Begin + (((OpIdx - Begin->Begin) * NumberScaling) /
ScaledOperandPerBundle);
if (Current >= End)
Current = std::prev(End);
assert(Current < End && Current >= Begin &&
"the operand bundle doesn't cover every value in the range");
if (OpIdx >= Current->Begin && OpIdx < Current->End)
break;
if (OpIdx >= Current->End)
Begin = Current + 1;
else
End = Current;
}
assert(OpIdx >= Current->Begin && OpIdx < Current->End &&
"the operand bundle doesn't cover every value in the range");
return *Current;
}
CallBase *CallBase::addOperandBundle(CallBase *CB, uint32_t ID,
OperandBundleDef OB,
Instruction *InsertPt) {
if (CB->getOperandBundle(ID))
return CB;
SmallVector<OperandBundleDef, 1> Bundles;
CB->getOperandBundlesAsDefs(Bundles);
Bundles.push_back(OB);
return Create(CB, Bundles, InsertPt);
}
CallBase *CallBase::removeOperandBundle(CallBase *CB, uint32_t ID,
Instruction *InsertPt) {
SmallVector<OperandBundleDef, 1> Bundles;
bool CreateNew = false;
for (unsigned I = 0, E = CB->getNumOperandBundles(); I != E; ++I) {
auto Bundle = CB->getOperandBundleAt(I);
if (Bundle.getTagID() == ID) {
CreateNew = true;
continue;
}
Bundles.emplace_back(Bundle);
}
return CreateNew ? Create(CB, Bundles, InsertPt) : CB;
}
bool CallBase::hasReadingOperandBundles() const {
return hasOperandBundlesOtherThan(LLVMContext::OB_ptrauth) &&
getIntrinsicID() != Intrinsic::assume;
}
void CallInst::init(FunctionType *FTy, Value *Func, ArrayRef<Value *> Args,
ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr) {
this->FTy = FTy;
assert(getNumOperands() == Args.size() + CountBundleInputs(Bundles) + 1 &&
"NumOperands not set up?");
#ifndef NDEBUG
assert((Args.size() == FTy->getNumParams() ||
(FTy->isVarArg() && Args.size() > FTy->getNumParams())) &&
"Calling a function with bad signature!");
for (unsigned i = 0; i != Args.size(); ++i)
assert((i >= FTy->getNumParams() ||
FTy->getParamType(i) == Args[i]->getType()) &&
"Calling a function with a bad signature!");
#endif
llvm::copy(Args, op_begin());
setCalledOperand(Func);
auto It = populateBundleOperandInfos(Bundles, Args.size());
(void)It;
assert(It + 1 == op_end() && "Should add up!");
setName(NameStr);
}
void CallInst::init(FunctionType *FTy, Value *Func, const Twine &NameStr) {
this->FTy = FTy;
assert(getNumOperands() == 1 && "NumOperands not set up?");
setCalledOperand(Func);
assert(FTy->getNumParams() == 0 && "Calling a function with bad signature");
setName(NameStr);
}
CallInst::CallInst(FunctionType *Ty, Value *Func, const Twine &Name,
Instruction *InsertBefore)
: CallBase(Ty->getReturnType(), Instruction::Call,
OperandTraits<CallBase>::op_end(this) - 1, 1, InsertBefore) {
init(Ty, Func, Name);
}
CallInst::CallInst(FunctionType *Ty, Value *Func, const Twine &Name,
BasicBlock *InsertAtEnd)
: CallBase(Ty->getReturnType(), Instruction::Call,
OperandTraits<CallBase>::op_end(this) - 1, 1, InsertAtEnd) {
init(Ty, Func, Name);
}
CallInst::CallInst(const CallInst &CI)
: CallBase(CI.Attrs, CI.FTy, CI.getType(), Instruction::Call,
OperandTraits<CallBase>::op_end(this) - CI.getNumOperands(),
CI.getNumOperands()) {
setTailCallKind(CI.getTailCallKind());
setCallingConv(CI.getCallingConv());
std::copy(CI.op_begin(), CI.op_end(), op_begin());
std::copy(CI.bundle_op_info_begin(), CI.bundle_op_info_end(),
bundle_op_info_begin());
SubclassOptionalData = CI.SubclassOptionalData;
}
CallInst *CallInst::Create(CallInst *CI, ArrayRef<OperandBundleDef> OpB,
Instruction *InsertPt) {
std::vector<Value *> Args(CI->arg_begin(), CI->arg_end());
auto *NewCI = CallInst::Create(CI->getFunctionType(), CI->getCalledOperand(),
Args, OpB, CI->getName(), InsertPt);
NewCI->setTailCallKind(CI->getTailCallKind());
NewCI->setCallingConv(CI->getCallingConv());
NewCI->SubclassOptionalData = CI->SubclassOptionalData;
NewCI->setAttributes(CI->getAttributes());
NewCI->setDebugLoc(CI->getDebugLoc());
return NewCI;
}
void CallInst::updateProfWeight(uint64_t S, uint64_t T) {
auto *ProfileData = getMetadata(LLVMContext::MD_prof);
if (ProfileData == nullptr)
return;
auto *ProfDataName = dyn_cast<MDString>(ProfileData->getOperand(0));
if (!ProfDataName || (!ProfDataName->getString().equals("branch_weights") &&
!ProfDataName->getString().equals("VP")))
return;
if (T == 0) {
LLVM_DEBUG(dbgs() << "Attempting to update profile weights will result in "
"div by 0. Ignoring. Likely the function "
<< getParent()->getParent()->getName()
<< " has 0 entry count, and contains call instructions "
"with non-zero prof info.");
return;
}
MDBuilder MDB(getContext());
SmallVector<Metadata *, 3> Vals;
Vals.push_back(ProfileData->getOperand(0));
APInt APS(128, S), APT(128, T);
if (ProfDataName->getString().equals("branch_weights") &&
ProfileData->getNumOperands() > 0) {
APInt Val(128, mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(1))
->getValue()
.getZExtValue());
Val *= APS;
Vals.push_back(MDB.createConstant(
ConstantInt::get(Type::getInt32Ty(getContext()),
Val.udiv(APT).getLimitedValue(UINT32_MAX))));
} else if (ProfDataName->getString().equals("VP"))
for (unsigned i = 1; i < ProfileData->getNumOperands(); i += 2) {
Vals.push_back(ProfileData->getOperand(i));
uint64_t Count =
mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(i + 1))
->getValue()
.getZExtValue();
if (Count == NOMORE_ICP_MAGICNUM) {
Vals.push_back(ProfileData->getOperand(i + 1));
continue;
}
APInt Val(128, Count);
Val *= APS;
Vals.push_back(MDB.createConstant(
ConstantInt::get(Type::getInt64Ty(getContext()),
Val.udiv(APT).getLimitedValue())));
}
setMetadata(LLVMContext::MD_prof, MDNode::get(getContext(), Vals));
}
static bool IsConstantOne(Value *val) {
assert(val && "IsConstantOne does not work with nullptr val");
const ConstantInt *CVal = dyn_cast<ConstantInt>(val);
return CVal && CVal->isOne();
}
static Instruction *createMalloc(Instruction *InsertBefore,
BasicBlock *InsertAtEnd, Type *IntPtrTy,
Type *AllocTy, Value *AllocSize,
Value *ArraySize,
ArrayRef<OperandBundleDef> OpB,
Function *MallocF, const Twine &Name) {
assert(((!InsertBefore && InsertAtEnd) || (InsertBefore && !InsertAtEnd)) &&
"createMalloc needs either InsertBefore or InsertAtEnd");
if (!ArraySize)
ArraySize = ConstantInt::get(IntPtrTy, 1);
else if (ArraySize->getType() != IntPtrTy) {
if (InsertBefore)
ArraySize = CastInst::CreateIntegerCast(ArraySize, IntPtrTy, false,
"", InsertBefore);
else
ArraySize = CastInst::CreateIntegerCast(ArraySize, IntPtrTy, false,
"", InsertAtEnd);
}
if (!IsConstantOne(ArraySize)) {
if (IsConstantOne(AllocSize)) {
AllocSize = ArraySize; } else if (Constant *CO = dyn_cast<Constant>(ArraySize)) {
Constant *Scale = ConstantExpr::getIntegerCast(CO, IntPtrTy,
false );
AllocSize = ConstantExpr::getMul(Scale, cast<Constant>(AllocSize));
} else {
if (InsertBefore)
AllocSize = BinaryOperator::CreateMul(ArraySize, AllocSize,
"mallocsize", InsertBefore);
else
AllocSize = BinaryOperator::CreateMul(ArraySize, AllocSize,
"mallocsize", InsertAtEnd);
}
}
assert(AllocSize->getType() == IntPtrTy && "malloc arg is wrong size");
BasicBlock *BB = InsertBefore ? InsertBefore->getParent() : InsertAtEnd;
Module *M = BB->getParent()->getParent();
Type *BPTy = Type::getInt8PtrTy(BB->getContext());
FunctionCallee MallocFunc = MallocF;
if (!MallocFunc)
MallocFunc = M->getOrInsertFunction("malloc", BPTy, IntPtrTy);
PointerType *AllocPtrType = PointerType::getUnqual(AllocTy);
CallInst *MCall = nullptr;
Instruction *Result = nullptr;
if (InsertBefore) {
MCall = CallInst::Create(MallocFunc, AllocSize, OpB, "malloccall",
InsertBefore);
Result = MCall;
if (Result->getType() != AllocPtrType)
Result = new BitCastInst(MCall, AllocPtrType, Name, InsertBefore);
} else {
MCall = CallInst::Create(MallocFunc, AllocSize, OpB, "malloccall");
Result = MCall;
if (Result->getType() != AllocPtrType) {
InsertAtEnd->getInstList().push_back(MCall);
Result = new BitCastInst(MCall, AllocPtrType, Name);
}
}
MCall->setTailCall();
if (Function *F = dyn_cast<Function>(MallocFunc.getCallee())) {
MCall->setCallingConv(F->getCallingConv());
if (!F->returnDoesNotAlias())
F->setReturnDoesNotAlias();
}
assert(!MCall->getType()->isVoidTy() && "Malloc has void return type");
return Result;
}
Instruction *CallInst::CreateMalloc(Instruction *InsertBefore,
Type *IntPtrTy, Type *AllocTy,
Value *AllocSize, Value *ArraySize,
Function *MallocF,
const Twine &Name) {
return createMalloc(InsertBefore, nullptr, IntPtrTy, AllocTy, AllocSize,
ArraySize, None, MallocF, Name);
}
Instruction *CallInst::CreateMalloc(Instruction *InsertBefore,
Type *IntPtrTy, Type *AllocTy,
Value *AllocSize, Value *ArraySize,
ArrayRef<OperandBundleDef> OpB,
Function *MallocF,
const Twine &Name) {
return createMalloc(InsertBefore, nullptr, IntPtrTy, AllocTy, AllocSize,
ArraySize, OpB, MallocF, Name);
}
Instruction *CallInst::CreateMalloc(BasicBlock *InsertAtEnd,
Type *IntPtrTy, Type *AllocTy,
Value *AllocSize, Value *ArraySize,
Function *MallocF, const Twine &Name) {
return createMalloc(nullptr, InsertAtEnd, IntPtrTy, AllocTy, AllocSize,
ArraySize, None, MallocF, Name);
}
Instruction *CallInst::CreateMalloc(BasicBlock *InsertAtEnd,
Type *IntPtrTy, Type *AllocTy,
Value *AllocSize, Value *ArraySize,
ArrayRef<OperandBundleDef> OpB,
Function *MallocF, const Twine &Name) {
return createMalloc(nullptr, InsertAtEnd, IntPtrTy, AllocTy, AllocSize,
ArraySize, OpB, MallocF, Name);
}
static Instruction *createFree(Value *Source,
ArrayRef<OperandBundleDef> Bundles,
Instruction *InsertBefore,
BasicBlock *InsertAtEnd) {
assert(((!InsertBefore && InsertAtEnd) || (InsertBefore && !InsertAtEnd)) &&
"createFree needs either InsertBefore or InsertAtEnd");
assert(Source->getType()->isPointerTy() &&
"Can not free something of nonpointer type!");
BasicBlock *BB = InsertBefore ? InsertBefore->getParent() : InsertAtEnd;
Module *M = BB->getParent()->getParent();
Type *VoidTy = Type::getVoidTy(M->getContext());
Type *IntPtrTy = Type::getInt8PtrTy(M->getContext());
FunctionCallee FreeFunc = M->getOrInsertFunction("free", VoidTy, IntPtrTy);
CallInst *Result = nullptr;
Value *PtrCast = Source;
if (InsertBefore) {
if (Source->getType() != IntPtrTy)
PtrCast = new BitCastInst(Source, IntPtrTy, "", InsertBefore);
Result = CallInst::Create(FreeFunc, PtrCast, Bundles, "", InsertBefore);
} else {
if (Source->getType() != IntPtrTy)
PtrCast = new BitCastInst(Source, IntPtrTy, "", InsertAtEnd);
Result = CallInst::Create(FreeFunc, PtrCast, Bundles, "");
}
Result->setTailCall();
if (Function *F = dyn_cast<Function>(FreeFunc.getCallee()))
Result->setCallingConv(F->getCallingConv());
return Result;
}
Instruction *CallInst::CreateFree(Value *Source, Instruction *InsertBefore) {
return createFree(Source, None, InsertBefore, nullptr);
}
Instruction *CallInst::CreateFree(Value *Source,
ArrayRef<OperandBundleDef> Bundles,
Instruction *InsertBefore) {
return createFree(Source, Bundles, InsertBefore, nullptr);
}
Instruction *CallInst::CreateFree(Value *Source, BasicBlock *InsertAtEnd) {
Instruction *FreeCall = createFree(Source, None, nullptr, InsertAtEnd);
assert(FreeCall && "CreateFree did not create a CallInst");
return FreeCall;
}
Instruction *CallInst::CreateFree(Value *Source,
ArrayRef<OperandBundleDef> Bundles,
BasicBlock *InsertAtEnd) {
Instruction *FreeCall = createFree(Source, Bundles, nullptr, InsertAtEnd);
assert(FreeCall && "CreateFree did not create a CallInst");
return FreeCall;
}
void InvokeInst::init(FunctionType *FTy, Value *Fn, BasicBlock *IfNormal,
BasicBlock *IfException, ArrayRef<Value *> Args,
ArrayRef<OperandBundleDef> Bundles,
const Twine &NameStr) {
this->FTy = FTy;
assert((int)getNumOperands() ==
ComputeNumOperands(Args.size(), CountBundleInputs(Bundles)) &&
"NumOperands not set up?");
#ifndef NDEBUG
assert(((Args.size() == FTy->getNumParams()) ||
(FTy->isVarArg() && Args.size() > FTy->getNumParams())) &&
"Invoking a function with bad signature");
for (unsigned i = 0, e = Args.size(); i != e; i++)
assert((i >= FTy->getNumParams() ||
FTy->getParamType(i) == Args[i]->getType()) &&
"Invoking a function with a bad signature!");
#endif
llvm::copy(Args, op_begin());
setNormalDest(IfNormal);
setUnwindDest(IfException);
setCalledOperand(Fn);
auto It = populateBundleOperandInfos(Bundles, Args.size());
(void)It;
assert(It + 3 == op_end() && "Should add up!");
setName(NameStr);
}
InvokeInst::InvokeInst(const InvokeInst &II)
: CallBase(II.Attrs, II.FTy, II.getType(), Instruction::Invoke,
OperandTraits<CallBase>::op_end(this) - II.getNumOperands(),
II.getNumOperands()) {
setCallingConv(II.getCallingConv());
std::copy(II.op_begin(), II.op_end(), op_begin());
std::copy(II.bundle_op_info_begin(), II.bundle_op_info_end(),
bundle_op_info_begin());
SubclassOptionalData = II.SubclassOptionalData;
}
InvokeInst *InvokeInst::Create(InvokeInst *II, ArrayRef<OperandBundleDef> OpB,
Instruction *InsertPt) {
std::vector<Value *> Args(II->arg_begin(), II->arg_end());
auto *NewII = InvokeInst::Create(
II->getFunctionType(), II->getCalledOperand(), II->getNormalDest(),
II->getUnwindDest(), Args, OpB, II->getName(), InsertPt);
NewII->setCallingConv(II->getCallingConv());
NewII->SubclassOptionalData = II->SubclassOptionalData;
NewII->setAttributes(II->getAttributes());
NewII->setDebugLoc(II->getDebugLoc());
return NewII;
}
LandingPadInst *InvokeInst::getLandingPadInst() const {
return cast<LandingPadInst>(getUnwindDest()->getFirstNonPHI());
}
void CallBrInst::init(FunctionType *FTy, Value *Fn, BasicBlock *Fallthrough,
ArrayRef<BasicBlock *> IndirectDests,
ArrayRef<Value *> Args,
ArrayRef<OperandBundleDef> Bundles,
const Twine &NameStr) {
this->FTy = FTy;
assert((int)getNumOperands() ==
ComputeNumOperands(Args.size(), IndirectDests.size(),
CountBundleInputs(Bundles)) &&
"NumOperands not set up?");
#ifndef NDEBUG
assert(((Args.size() == FTy->getNumParams()) ||
(FTy->isVarArg() && Args.size() > FTy->getNumParams())) &&
"Calling a function with bad signature");
for (unsigned i = 0, e = Args.size(); i != e; i++)
assert((i >= FTy->getNumParams() ||
FTy->getParamType(i) == Args[i]->getType()) &&
"Calling a function with a bad signature!");
#endif
std::copy(Args.begin(), Args.end(), op_begin());
NumIndirectDests = IndirectDests.size();
setDefaultDest(Fallthrough);
for (unsigned i = 0; i != NumIndirectDests; ++i)
setIndirectDest(i, IndirectDests[i]);
setCalledOperand(Fn);
auto It = populateBundleOperandInfos(Bundles, Args.size());
(void)It;
assert(It + 2 + IndirectDests.size() == op_end() && "Should add up!");
setName(NameStr);
}
BlockAddress *
CallBrInst::getBlockAddressForIndirectDest(unsigned DestNo) const {
return BlockAddress::get(const_cast<Function *>(getFunction()),
getIndirectDest(DestNo));
}
CallBrInst::CallBrInst(const CallBrInst &CBI)
: CallBase(CBI.Attrs, CBI.FTy, CBI.getType(), Instruction::CallBr,
OperandTraits<CallBase>::op_end(this) - CBI.getNumOperands(),
CBI.getNumOperands()) {
setCallingConv(CBI.getCallingConv());
std::copy(CBI.op_begin(), CBI.op_end(), op_begin());
std::copy(CBI.bundle_op_info_begin(), CBI.bundle_op_info_end(),
bundle_op_info_begin());
SubclassOptionalData = CBI.SubclassOptionalData;
NumIndirectDests = CBI.NumIndirectDests;
}
CallBrInst *CallBrInst::Create(CallBrInst *CBI, ArrayRef<OperandBundleDef> OpB,
Instruction *InsertPt) {
std::vector<Value *> Args(CBI->arg_begin(), CBI->arg_end());
auto *NewCBI = CallBrInst::Create(
CBI->getFunctionType(), CBI->getCalledOperand(), CBI->getDefaultDest(),
CBI->getIndirectDests(), Args, OpB, CBI->getName(), InsertPt);
NewCBI->setCallingConv(CBI->getCallingConv());
NewCBI->SubclassOptionalData = CBI->SubclassOptionalData;
NewCBI->setAttributes(CBI->getAttributes());
NewCBI->setDebugLoc(CBI->getDebugLoc());
NewCBI->NumIndirectDests = CBI->NumIndirectDests;
return NewCBI;
}
ReturnInst::ReturnInst(const ReturnInst &RI)
: Instruction(Type::getVoidTy(RI.getContext()), Instruction::Ret,
OperandTraits<ReturnInst>::op_end(this) - RI.getNumOperands(),
RI.getNumOperands()) {
if (RI.getNumOperands())
Op<0>() = RI.Op<0>();
SubclassOptionalData = RI.SubclassOptionalData;
}
ReturnInst::ReturnInst(LLVMContext &C, Value *retVal, Instruction *InsertBefore)
: Instruction(Type::getVoidTy(C), Instruction::Ret,
OperandTraits<ReturnInst>::op_end(this) - !!retVal, !!retVal,
InsertBefore) {
if (retVal)
Op<0>() = retVal;
}
ReturnInst::ReturnInst(LLVMContext &C, Value *retVal, BasicBlock *InsertAtEnd)
: Instruction(Type::getVoidTy(C), Instruction::Ret,
OperandTraits<ReturnInst>::op_end(this) - !!retVal, !!retVal,
InsertAtEnd) {
if (retVal)
Op<0>() = retVal;
}
ReturnInst::ReturnInst(LLVMContext &Context, BasicBlock *InsertAtEnd)
: Instruction(Type::getVoidTy(Context), Instruction::Ret,
OperandTraits<ReturnInst>::op_end(this), 0, InsertAtEnd) {}
ResumeInst::ResumeInst(const ResumeInst &RI)
: Instruction(Type::getVoidTy(RI.getContext()), Instruction::Resume,
OperandTraits<ResumeInst>::op_begin(this), 1) {
Op<0>() = RI.Op<0>();
}
ResumeInst::ResumeInst(Value *Exn, Instruction *InsertBefore)
: Instruction(Type::getVoidTy(Exn->getContext()), Instruction::Resume,
OperandTraits<ResumeInst>::op_begin(this), 1, InsertBefore) {
Op<0>() = Exn;
}
ResumeInst::ResumeInst(Value *Exn, BasicBlock *InsertAtEnd)
: Instruction(Type::getVoidTy(Exn->getContext()), Instruction::Resume,
OperandTraits<ResumeInst>::op_begin(this), 1, InsertAtEnd) {
Op<0>() = Exn;
}
CleanupReturnInst::CleanupReturnInst(const CleanupReturnInst &CRI)
: Instruction(CRI.getType(), Instruction::CleanupRet,
OperandTraits<CleanupReturnInst>::op_end(this) -
CRI.getNumOperands(),
CRI.getNumOperands()) {
setSubclassData<Instruction::OpaqueField>(
CRI.getSubclassData<Instruction::OpaqueField>());
Op<0>() = CRI.Op<0>();
if (CRI.hasUnwindDest())
Op<1>() = CRI.Op<1>();
}
void CleanupReturnInst::init(Value *CleanupPad, BasicBlock *UnwindBB) {
if (UnwindBB)
setSubclassData<UnwindDestField>(true);
Op<0>() = CleanupPad;
if (UnwindBB)
Op<1>() = UnwindBB;
}
CleanupReturnInst::CleanupReturnInst(Value *CleanupPad, BasicBlock *UnwindBB,
unsigned Values, Instruction *InsertBefore)
: Instruction(Type::getVoidTy(CleanupPad->getContext()),
Instruction::CleanupRet,
OperandTraits<CleanupReturnInst>::op_end(this) - Values,
Values, InsertBefore) {
init(CleanupPad, UnwindBB);
}
CleanupReturnInst::CleanupReturnInst(Value *CleanupPad, BasicBlock *UnwindBB,
unsigned Values, BasicBlock *InsertAtEnd)
: Instruction(Type::getVoidTy(CleanupPad->getContext()),
Instruction::CleanupRet,
OperandTraits<CleanupReturnInst>::op_end(this) - Values,
Values, InsertAtEnd) {
init(CleanupPad, UnwindBB);
}
void CatchReturnInst::init(Value *CatchPad, BasicBlock *BB) {
Op<0>() = CatchPad;
Op<1>() = BB;
}
CatchReturnInst::CatchReturnInst(const CatchReturnInst &CRI)
: Instruction(Type::getVoidTy(CRI.getContext()), Instruction::CatchRet,
OperandTraits<CatchReturnInst>::op_begin(this), 2) {
Op<0>() = CRI.Op<0>();
Op<1>() = CRI.Op<1>();
}
CatchReturnInst::CatchReturnInst(Value *CatchPad, BasicBlock *BB,
Instruction *InsertBefore)
: Instruction(Type::getVoidTy(BB->getContext()), Instruction::CatchRet,
OperandTraits<CatchReturnInst>::op_begin(this), 2,
InsertBefore) {
init(CatchPad, BB);
}
CatchReturnInst::CatchReturnInst(Value *CatchPad, BasicBlock *BB,
BasicBlock *InsertAtEnd)
: Instruction(Type::getVoidTy(BB->getContext()), Instruction::CatchRet,
OperandTraits<CatchReturnInst>::op_begin(this), 2,
InsertAtEnd) {
init(CatchPad, BB);
}
CatchSwitchInst::CatchSwitchInst(Value *ParentPad, BasicBlock *UnwindDest,
unsigned NumReservedValues,
const Twine &NameStr,
Instruction *InsertBefore)
: Instruction(ParentPad->getType(), Instruction::CatchSwitch, nullptr, 0,
InsertBefore) {
if (UnwindDest)
++NumReservedValues;
init(ParentPad, UnwindDest, NumReservedValues + 1);
setName(NameStr);
}
CatchSwitchInst::CatchSwitchInst(Value *ParentPad, BasicBlock *UnwindDest,
unsigned NumReservedValues,
const Twine &NameStr, BasicBlock *InsertAtEnd)
: Instruction(ParentPad->getType(), Instruction::CatchSwitch, nullptr, 0,
InsertAtEnd) {
if (UnwindDest)
++NumReservedValues;
init(ParentPad, UnwindDest, NumReservedValues + 1);
setName(NameStr);
}
CatchSwitchInst::CatchSwitchInst(const CatchSwitchInst &CSI)
: Instruction(CSI.getType(), Instruction::CatchSwitch, nullptr,
CSI.getNumOperands()) {
init(CSI.getParentPad(), CSI.getUnwindDest(), CSI.getNumOperands());
setNumHungOffUseOperands(ReservedSpace);
Use *OL = getOperandList();
const Use *InOL = CSI.getOperandList();
for (unsigned I = 1, E = ReservedSpace; I != E; ++I)
OL[I] = InOL[I];
}
void CatchSwitchInst::init(Value *ParentPad, BasicBlock *UnwindDest,
unsigned NumReservedValues) {
assert(ParentPad && NumReservedValues);
ReservedSpace = NumReservedValues;
setNumHungOffUseOperands(UnwindDest ? 2 : 1);
allocHungoffUses(ReservedSpace);
Op<0>() = ParentPad;
if (UnwindDest) {
setSubclassData<UnwindDestField>(true);
setUnwindDest(UnwindDest);
}
}
void CatchSwitchInst::growOperands(unsigned Size) {
unsigned NumOperands = getNumOperands();
assert(NumOperands >= 1);
if (ReservedSpace >= NumOperands + Size)
return;
ReservedSpace = (NumOperands + Size / 2) * 2;
growHungoffUses(ReservedSpace);
}
void CatchSwitchInst::addHandler(BasicBlock *Handler) {
unsigned OpNo = getNumOperands();
growOperands(1);
assert(OpNo < ReservedSpace && "Growing didn't work!");
setNumHungOffUseOperands(getNumOperands() + 1);
getOperandList()[OpNo] = Handler;
}
void CatchSwitchInst::removeHandler(handler_iterator HI) {
Use *EndDst = op_end() - 1;
for (Use *CurDst = HI.getCurrent(); CurDst != EndDst; ++CurDst)
*CurDst = *(CurDst + 1);
*EndDst = nullptr;
setNumHungOffUseOperands(getNumOperands() - 1);
}
void FuncletPadInst::init(Value *ParentPad, ArrayRef<Value *> Args,
const Twine &NameStr) {
assert(getNumOperands() == 1 + Args.size() && "NumOperands not set up?");
llvm::copy(Args, op_begin());
setParentPad(ParentPad);
setName(NameStr);
}
FuncletPadInst::FuncletPadInst(const FuncletPadInst &FPI)
: Instruction(FPI.getType(), FPI.getOpcode(),
OperandTraits<FuncletPadInst>::op_end(this) -
FPI.getNumOperands(),
FPI.getNumOperands()) {
std::copy(FPI.op_begin(), FPI.op_end(), op_begin());
setParentPad(FPI.getParentPad());
}
FuncletPadInst::FuncletPadInst(Instruction::FuncletPadOps Op, Value *ParentPad,
ArrayRef<Value *> Args, unsigned Values,
const Twine &NameStr, Instruction *InsertBefore)
: Instruction(ParentPad->getType(), Op,
OperandTraits<FuncletPadInst>::op_end(this) - Values, Values,
InsertBefore) {
init(ParentPad, Args, NameStr);
}
FuncletPadInst::FuncletPadInst(Instruction::FuncletPadOps Op, Value *ParentPad,
ArrayRef<Value *> Args, unsigned Values,
const Twine &NameStr, BasicBlock *InsertAtEnd)
: Instruction(ParentPad->getType(), Op,
OperandTraits<FuncletPadInst>::op_end(this) - Values, Values,
InsertAtEnd) {
init(ParentPad, Args, NameStr);
}
UnreachableInst::UnreachableInst(LLVMContext &Context,
Instruction *InsertBefore)
: Instruction(Type::getVoidTy(Context), Instruction::Unreachable, nullptr,
0, InsertBefore) {}
UnreachableInst::UnreachableInst(LLVMContext &Context, BasicBlock *InsertAtEnd)
: Instruction(Type::getVoidTy(Context), Instruction::Unreachable, nullptr,
0, InsertAtEnd) {}
void BranchInst::AssertOK() {
if (isConditional())
assert(getCondition()->getType()->isIntegerTy(1) &&
"May only branch on boolean predicates!");
}
BranchInst::BranchInst(BasicBlock *IfTrue, Instruction *InsertBefore)
: Instruction(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
OperandTraits<BranchInst>::op_end(this) - 1, 1,
InsertBefore) {
assert(IfTrue && "Branch destination may not be null!");
Op<-1>() = IfTrue;
}
BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
Instruction *InsertBefore)
: Instruction(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
OperandTraits<BranchInst>::op_end(this) - 3, 3,
InsertBefore) {
Op<-3>() = Cond;
Op<-2>() = IfFalse;
Op<-1>() = IfTrue;
#ifndef NDEBUG
AssertOK();
#endif
}
BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *InsertAtEnd)
: Instruction(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
OperandTraits<BranchInst>::op_end(this) - 1, 1, InsertAtEnd) {
assert(IfTrue && "Branch destination may not be null!");
Op<-1>() = IfTrue;
}
BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
BasicBlock *InsertAtEnd)
: Instruction(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
OperandTraits<BranchInst>::op_end(this) - 3, 3, InsertAtEnd) {
Op<-3>() = Cond;
Op<-2>() = IfFalse;
Op<-1>() = IfTrue;
#ifndef NDEBUG
AssertOK();
#endif
}
BranchInst::BranchInst(const BranchInst &BI)
: Instruction(Type::getVoidTy(BI.getContext()), Instruction::Br,
OperandTraits<BranchInst>::op_end(this) - BI.getNumOperands(),
BI.getNumOperands()) {
if (BI.getNumOperands() != 1) {
assert(BI.getNumOperands() == 3 && "BR can have 1 or 3 operands!");
Op<-3>() = BI.Op<-3>();
Op<-2>() = BI.Op<-2>();
}
Op<-1>() = BI.Op<-1>();
SubclassOptionalData = BI.SubclassOptionalData;
}
void BranchInst::swapSuccessors() {
assert(isConditional() &&
"Cannot swap successors of an unconditional branch");
Op<-1>().swap(Op<-2>());
swapProfMetadata();
}
static Value *getAISize(LLVMContext &Context, Value *Amt) {
if (!Amt)
Amt = ConstantInt::get(Type::getInt32Ty(Context), 1);
else {
assert(!isa<BasicBlock>(Amt) &&
"Passed basic block into allocation size parameter! Use other ctor");
assert(Amt->getType()->isIntegerTy() &&
"Allocation array size is not an integer!");
}
return Amt;
}
static Align computeAllocaDefaultAlign(Type *Ty, BasicBlock *BB) {
assert(BB && "Insertion BB cannot be null when alignment not provided!");
assert(BB->getParent() &&
"BB must be in a Function when alignment not provided!");
const DataLayout &DL = BB->getModule()->getDataLayout();
return DL.getPrefTypeAlign(Ty);
}
static Align computeAllocaDefaultAlign(Type *Ty, Instruction *I) {
assert(I && "Insertion position cannot be null when alignment not provided!");
return computeAllocaDefaultAlign(Ty, I->getParent());
}
AllocaInst::AllocaInst(Type *Ty, unsigned AddrSpace, const Twine &Name,
Instruction *InsertBefore)
: AllocaInst(Ty, AddrSpace, nullptr, Name, InsertBefore) {}
AllocaInst::AllocaInst(Type *Ty, unsigned AddrSpace, const Twine &Name,
BasicBlock *InsertAtEnd)
: AllocaInst(Ty, AddrSpace, nullptr, Name, InsertAtEnd) {}
AllocaInst::AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize,
const Twine &Name, Instruction *InsertBefore)
: AllocaInst(Ty, AddrSpace, ArraySize,
computeAllocaDefaultAlign(Ty, InsertBefore), Name,
InsertBefore) {}
AllocaInst::AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize,
const Twine &Name, BasicBlock *InsertAtEnd)
: AllocaInst(Ty, AddrSpace, ArraySize,
computeAllocaDefaultAlign(Ty, InsertAtEnd), Name,
InsertAtEnd) {}
AllocaInst::AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize,
Align Align, const Twine &Name,
Instruction *InsertBefore)
: UnaryInstruction(PointerType::get(Ty, AddrSpace), Alloca,
getAISize(Ty->getContext(), ArraySize), InsertBefore),
AllocatedType(Ty) {
setAlignment(Align);
assert(!Ty->isVoidTy() && "Cannot allocate void!");
setName(Name);
}
AllocaInst::AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize,
Align Align, const Twine &Name, BasicBlock *InsertAtEnd)
: UnaryInstruction(PointerType::get(Ty, AddrSpace), Alloca,
getAISize(Ty->getContext(), ArraySize), InsertAtEnd),
AllocatedType(Ty) {
setAlignment(Align);
assert(!Ty->isVoidTy() && "Cannot allocate void!");
setName(Name);
}
bool AllocaInst::isArrayAllocation() const {
if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(0)))
return !CI->isOne();
return true;
}
bool AllocaInst::isStaticAlloca() const {
if (!isa<ConstantInt>(getArraySize())) return false;
const BasicBlock *Parent = getParent();
return Parent == &Parent->getParent()->front() && !isUsedWithInAlloca();
}
void LoadInst::AssertOK() {
assert(getOperand(0)->getType()->isPointerTy() &&
"Ptr must have pointer type.");
}
static Align computeLoadStoreDefaultAlign(Type *Ty, BasicBlock *BB) {
assert(BB && "Insertion BB cannot be null when alignment not provided!");
assert(BB->getParent() &&
"BB must be in a Function when alignment not provided!");
const DataLayout &DL = BB->getModule()->getDataLayout();
return DL.getABITypeAlign(Ty);
}
static Align computeLoadStoreDefaultAlign(Type *Ty, Instruction *I) {
assert(I && "Insertion position cannot be null when alignment not provided!");
return computeLoadStoreDefaultAlign(Ty, I->getParent());
}
LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name,
Instruction *InsertBef)
: LoadInst(Ty, Ptr, Name, false, InsertBef) {}
LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name,
BasicBlock *InsertAE)
: LoadInst(Ty, Ptr, Name, false, InsertAE) {}
LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name, bool isVolatile,
Instruction *InsertBef)
: LoadInst(Ty, Ptr, Name, isVolatile,
computeLoadStoreDefaultAlign(Ty, InsertBef), InsertBef) {}
LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name, bool isVolatile,
BasicBlock *InsertAE)
: LoadInst(Ty, Ptr, Name, isVolatile,
computeLoadStoreDefaultAlign(Ty, InsertAE), InsertAE) {}
LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name, bool isVolatile,
Align Align, Instruction *InsertBef)
: LoadInst(Ty, Ptr, Name, isVolatile, Align, AtomicOrdering::NotAtomic,
SyncScope::System, InsertBef) {}
LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name, bool isVolatile,
Align Align, BasicBlock *InsertAE)
: LoadInst(Ty, Ptr, Name, isVolatile, Align, AtomicOrdering::NotAtomic,
SyncScope::System, InsertAE) {}
LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name, bool isVolatile,
Align Align, AtomicOrdering Order, SyncScope::ID SSID,
Instruction *InsertBef)
: UnaryInstruction(Ty, Load, Ptr, InsertBef) {
assert(cast<PointerType>(Ptr->getType())->isOpaqueOrPointeeTypeMatches(Ty));
setVolatile(isVolatile);
setAlignment(Align);
setAtomic(Order, SSID);
AssertOK();
setName(Name);
}
LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name, bool isVolatile,
Align Align, AtomicOrdering Order, SyncScope::ID SSID,
BasicBlock *InsertAE)
: UnaryInstruction(Ty, Load, Ptr, InsertAE) {
assert(cast<PointerType>(Ptr->getType())->isOpaqueOrPointeeTypeMatches(Ty));
setVolatile(isVolatile);
setAlignment(Align);
setAtomic(Order, SSID);
AssertOK();
setName(Name);
}
void StoreInst::AssertOK() {
assert(getOperand(0) && getOperand(1) && "Both operands must be non-null!");
assert(getOperand(1)->getType()->isPointerTy() &&
"Ptr must have pointer type!");
assert(cast<PointerType>(getOperand(1)->getType())
->isOpaqueOrPointeeTypeMatches(getOperand(0)->getType()) &&
"Ptr must be a pointer to Val type!");
}
StoreInst::StoreInst(Value *val, Value *addr, Instruction *InsertBefore)
: StoreInst(val, addr, false, InsertBefore) {}
StoreInst::StoreInst(Value *val, Value *addr, BasicBlock *InsertAtEnd)
: StoreInst(val, addr, false, InsertAtEnd) {}
StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
Instruction *InsertBefore)
: StoreInst(val, addr, isVolatile,
computeLoadStoreDefaultAlign(val->getType(), InsertBefore),
InsertBefore) {}
StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
BasicBlock *InsertAtEnd)
: StoreInst(val, addr, isVolatile,
computeLoadStoreDefaultAlign(val->getType(), InsertAtEnd),
InsertAtEnd) {}
StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile, Align Align,
Instruction *InsertBefore)
: StoreInst(val, addr, isVolatile, Align, AtomicOrdering::NotAtomic,
SyncScope::System, InsertBefore) {}
StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile, Align Align,
BasicBlock *InsertAtEnd)
: StoreInst(val, addr, isVolatile, Align, AtomicOrdering::NotAtomic,
SyncScope::System, InsertAtEnd) {}
StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile, Align Align,
AtomicOrdering Order, SyncScope::ID SSID,
Instruction *InsertBefore)
: Instruction(Type::getVoidTy(val->getContext()), Store,
OperandTraits<StoreInst>::op_begin(this),
OperandTraits<StoreInst>::operands(this), InsertBefore) {
Op<0>() = val;
Op<1>() = addr;
setVolatile(isVolatile);
setAlignment(Align);
setAtomic(Order, SSID);
AssertOK();
}
StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile, Align Align,
AtomicOrdering Order, SyncScope::ID SSID,
BasicBlock *InsertAtEnd)
: Instruction(Type::getVoidTy(val->getContext()), Store,
OperandTraits<StoreInst>::op_begin(this),
OperandTraits<StoreInst>::operands(this), InsertAtEnd) {
Op<0>() = val;
Op<1>() = addr;
setVolatile(isVolatile);
setAlignment(Align);
setAtomic(Order, SSID);
AssertOK();
}
void AtomicCmpXchgInst::Init(Value *Ptr, Value *Cmp, Value *NewVal,
Align Alignment, AtomicOrdering SuccessOrdering,
AtomicOrdering FailureOrdering,
SyncScope::ID SSID) {
Op<0>() = Ptr;
Op<1>() = Cmp;
Op<2>() = NewVal;
setSuccessOrdering(SuccessOrdering);
setFailureOrdering(FailureOrdering);
setSyncScopeID(SSID);
setAlignment(Alignment);
assert(getOperand(0) && getOperand(1) && getOperand(2) &&
"All operands must be non-null!");
assert(getOperand(0)->getType()->isPointerTy() &&
"Ptr must have pointer type!");
assert(cast<PointerType>(getOperand(0)->getType())
->isOpaqueOrPointeeTypeMatches(getOperand(1)->getType()) &&
"Ptr must be a pointer to Cmp type!");
assert(cast<PointerType>(getOperand(0)->getType())
->isOpaqueOrPointeeTypeMatches(getOperand(2)->getType()) &&
"Ptr must be a pointer to NewVal type!");
assert(getOperand(1)->getType() == getOperand(2)->getType() &&
"Cmp type and NewVal type must be same!");
}
AtomicCmpXchgInst::AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal,
Align Alignment,
AtomicOrdering SuccessOrdering,
AtomicOrdering FailureOrdering,
SyncScope::ID SSID,
Instruction *InsertBefore)
: Instruction(
StructType::get(Cmp->getType(), Type::getInt1Ty(Cmp->getContext())),
AtomicCmpXchg, OperandTraits<AtomicCmpXchgInst>::op_begin(this),
OperandTraits<AtomicCmpXchgInst>::operands(this), InsertBefore) {
Init(Ptr, Cmp, NewVal, Alignment, SuccessOrdering, FailureOrdering, SSID);
}
AtomicCmpXchgInst::AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal,
Align Alignment,
AtomicOrdering SuccessOrdering,
AtomicOrdering FailureOrdering,
SyncScope::ID SSID,
BasicBlock *InsertAtEnd)
: Instruction(
StructType::get(Cmp->getType(), Type::getInt1Ty(Cmp->getContext())),
AtomicCmpXchg, OperandTraits<AtomicCmpXchgInst>::op_begin(this),
OperandTraits<AtomicCmpXchgInst>::operands(this), InsertAtEnd) {
Init(Ptr, Cmp, NewVal, Alignment, SuccessOrdering, FailureOrdering, SSID);
}
void AtomicRMWInst::Init(BinOp Operation, Value *Ptr, Value *Val,
Align Alignment, AtomicOrdering Ordering,
SyncScope::ID SSID) {
assert(Ordering != AtomicOrdering::NotAtomic &&
"atomicrmw instructions can only be atomic.");
assert(Ordering != AtomicOrdering::Unordered &&
"atomicrmw instructions cannot be unordered.");
Op<0>() = Ptr;
Op<1>() = Val;
setOperation(Operation);
setOrdering(Ordering);
setSyncScopeID(SSID);
setAlignment(Alignment);
assert(getOperand(0) && getOperand(1) &&
"All operands must be non-null!");
assert(getOperand(0)->getType()->isPointerTy() &&
"Ptr must have pointer type!");
assert(cast<PointerType>(getOperand(0)->getType())
->isOpaqueOrPointeeTypeMatches(getOperand(1)->getType()) &&
"Ptr must be a pointer to Val type!");
assert(Ordering != AtomicOrdering::NotAtomic &&
"AtomicRMW instructions must be atomic!");
}
AtomicRMWInst::AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val,
Align Alignment, AtomicOrdering Ordering,
SyncScope::ID SSID, Instruction *InsertBefore)
: Instruction(Val->getType(), AtomicRMW,
OperandTraits<AtomicRMWInst>::op_begin(this),
OperandTraits<AtomicRMWInst>::operands(this), InsertBefore) {
Init(Operation, Ptr, Val, Alignment, Ordering, SSID);
}
AtomicRMWInst::AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val,
Align Alignment, AtomicOrdering Ordering,
SyncScope::ID SSID, BasicBlock *InsertAtEnd)
: Instruction(Val->getType(), AtomicRMW,
OperandTraits<AtomicRMWInst>::op_begin(this),
OperandTraits<AtomicRMWInst>::operands(this), InsertAtEnd) {
Init(Operation, Ptr, Val, Alignment, Ordering, SSID);
}
StringRef AtomicRMWInst::getOperationName(BinOp Op) {
switch (Op) {
case AtomicRMWInst::Xchg:
return "xchg";
case AtomicRMWInst::Add:
return "add";
case AtomicRMWInst::Sub:
return "sub";
case AtomicRMWInst::And:
return "and";
case AtomicRMWInst::Nand:
return "nand";
case AtomicRMWInst::Or:
return "or";
case AtomicRMWInst::Xor:
return "xor";
case AtomicRMWInst::Max:
return "max";
case AtomicRMWInst::Min:
return "min";
case AtomicRMWInst::UMax:
return "umax";
case AtomicRMWInst::UMin:
return "umin";
case AtomicRMWInst::FAdd:
return "fadd";
case AtomicRMWInst::FSub:
return "fsub";
case AtomicRMWInst::FMax:
return "fmax";
case AtomicRMWInst::FMin:
return "fmin";
case AtomicRMWInst::BAD_BINOP:
return "<invalid operation>";
}
llvm_unreachable("invalid atomicrmw operation");
}
FenceInst::FenceInst(LLVMContext &C, AtomicOrdering Ordering,
SyncScope::ID SSID,
Instruction *InsertBefore)
: Instruction(Type::getVoidTy(C), Fence, nullptr, 0, InsertBefore) {
setOrdering(Ordering);
setSyncScopeID(SSID);
}
FenceInst::FenceInst(LLVMContext &C, AtomicOrdering Ordering,
SyncScope::ID SSID,
BasicBlock *InsertAtEnd)
: Instruction(Type::getVoidTy(C), Fence, nullptr, 0, InsertAtEnd) {
setOrdering(Ordering);
setSyncScopeID(SSID);
}
void GetElementPtrInst::init(Value *Ptr, ArrayRef<Value *> IdxList,
const Twine &Name) {
assert(getNumOperands() == 1 + IdxList.size() &&
"NumOperands not initialized?");
Op<0>() = Ptr;
llvm::copy(IdxList, op_begin() + 1);
setName(Name);
}
GetElementPtrInst::GetElementPtrInst(const GetElementPtrInst &GEPI)
: Instruction(GEPI.getType(), GetElementPtr,
OperandTraits<GetElementPtrInst>::op_end(this) -
GEPI.getNumOperands(),
GEPI.getNumOperands()),
SourceElementType(GEPI.SourceElementType),
ResultElementType(GEPI.ResultElementType) {
std::copy(GEPI.op_begin(), GEPI.op_end(), op_begin());
SubclassOptionalData = GEPI.SubclassOptionalData;
}
Type *GetElementPtrInst::getTypeAtIndex(Type *Ty, Value *Idx) {
if (auto *Struct = dyn_cast<StructType>(Ty)) {
if (!Struct->indexValid(Idx))
return nullptr;
return Struct->getTypeAtIndex(Idx);
}
if (!Idx->getType()->isIntOrIntVectorTy())
return nullptr;
if (auto *Array = dyn_cast<ArrayType>(Ty))
return Array->getElementType();
if (auto *Vector = dyn_cast<VectorType>(Ty))
return Vector->getElementType();
return nullptr;
}
Type *GetElementPtrInst::getTypeAtIndex(Type *Ty, uint64_t Idx) {
if (auto *Struct = dyn_cast<StructType>(Ty)) {
if (Idx >= Struct->getNumElements())
return nullptr;
return Struct->getElementType(Idx);
}
if (auto *Array = dyn_cast<ArrayType>(Ty))
return Array->getElementType();
if (auto *Vector = dyn_cast<VectorType>(Ty))
return Vector->getElementType();
return nullptr;
}
template <typename IndexTy>
static Type *getIndexedTypeInternal(Type *Ty, ArrayRef<IndexTy> IdxList) {
if (IdxList.empty())
return Ty;
for (IndexTy V : IdxList.slice(1)) {
Ty = GetElementPtrInst::getTypeAtIndex(Ty, V);
if (!Ty)
return Ty;
}
return Ty;
}
Type *GetElementPtrInst::getIndexedType(Type *Ty, ArrayRef<Value *> IdxList) {
return getIndexedTypeInternal(Ty, IdxList);
}
Type *GetElementPtrInst::getIndexedType(Type *Ty,
ArrayRef<Constant *> IdxList) {
return getIndexedTypeInternal(Ty, IdxList);
}
Type *GetElementPtrInst::getIndexedType(Type *Ty, ArrayRef<uint64_t> IdxList) {
return getIndexedTypeInternal(Ty, IdxList);
}
bool GetElementPtrInst::hasAllZeroIndices() const {
for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(i))) {
if (!CI->isZero()) return false;
} else {
return false;
}
}
return true;
}
bool GetElementPtrInst::hasAllConstantIndices() const {
for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
if (!isa<ConstantInt>(getOperand(i)))
return false;
}
return true;
}
void GetElementPtrInst::setIsInBounds(bool B) {
cast<GEPOperator>(this)->setIsInBounds(B);
}
bool GetElementPtrInst::isInBounds() const {
return cast<GEPOperator>(this)->isInBounds();
}
bool GetElementPtrInst::accumulateConstantOffset(const DataLayout &DL,
APInt &Offset) const {
return cast<GEPOperator>(this)->accumulateConstantOffset(DL, Offset);
}
bool GetElementPtrInst::collectOffset(
const DataLayout &DL, unsigned BitWidth,
MapVector<Value *, APInt> &VariableOffsets,
APInt &ConstantOffset) const {
return cast<GEPOperator>(this)->collectOffset(DL, BitWidth, VariableOffsets,
ConstantOffset);
}
ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
const Twine &Name,
Instruction *InsertBef)
: Instruction(cast<VectorType>(Val->getType())->getElementType(),
ExtractElement,
OperandTraits<ExtractElementInst>::op_begin(this),
2, InsertBef) {
assert(isValidOperands(Val, Index) &&
"Invalid extractelement instruction operands!");
Op<0>() = Val;
Op<1>() = Index;
setName(Name);
}
ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
const Twine &Name,
BasicBlock *InsertAE)
: Instruction(cast<VectorType>(Val->getType())->getElementType(),
ExtractElement,
OperandTraits<ExtractElementInst>::op_begin(this),
2, InsertAE) {
assert(isValidOperands(Val, Index) &&
"Invalid extractelement instruction operands!");
Op<0>() = Val;
Op<1>() = Index;
setName(Name);
}
bool ExtractElementInst::isValidOperands(const Value *Val, const Value *Index) {
if (!Val->getType()->isVectorTy() || !Index->getType()->isIntegerTy())
return false;
return true;
}
InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
const Twine &Name,
Instruction *InsertBef)
: Instruction(Vec->getType(), InsertElement,
OperandTraits<InsertElementInst>::op_begin(this),
3, InsertBef) {
assert(isValidOperands(Vec, Elt, Index) &&
"Invalid insertelement instruction operands!");
Op<0>() = Vec;
Op<1>() = Elt;
Op<2>() = Index;
setName(Name);
}
InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
const Twine &Name,
BasicBlock *InsertAE)
: Instruction(Vec->getType(), InsertElement,
OperandTraits<InsertElementInst>::op_begin(this),
3, InsertAE) {
assert(isValidOperands(Vec, Elt, Index) &&
"Invalid insertelement instruction operands!");
Op<0>() = Vec;
Op<1>() = Elt;
Op<2>() = Index;
setName(Name);
}
bool InsertElementInst::isValidOperands(const Value *Vec, const Value *Elt,
const Value *Index) {
if (!Vec->getType()->isVectorTy())
return false;
if (Elt->getType() != cast<VectorType>(Vec->getType())->getElementType())
return false;
if (!Index->getType()->isIntegerTy())
return false; return true;
}
static Value *createPlaceholderForShuffleVector(Value *V) {
assert(V && "Cannot create placeholder of nullptr V");
return PoisonValue::get(V->getType());
}
ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *Mask, const Twine &Name,
Instruction *InsertBefore)
: ShuffleVectorInst(V1, createPlaceholderForShuffleVector(V1), Mask, Name,
InsertBefore) {}
ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *Mask, const Twine &Name,
BasicBlock *InsertAtEnd)
: ShuffleVectorInst(V1, createPlaceholderForShuffleVector(V1), Mask, Name,
InsertAtEnd) {}
ShuffleVectorInst::ShuffleVectorInst(Value *V1, ArrayRef<int> Mask,
const Twine &Name,
Instruction *InsertBefore)
: ShuffleVectorInst(V1, createPlaceholderForShuffleVector(V1), Mask, Name,
InsertBefore) {}
ShuffleVectorInst::ShuffleVectorInst(Value *V1, ArrayRef<int> Mask,
const Twine &Name, BasicBlock *InsertAtEnd)
: ShuffleVectorInst(V1, createPlaceholderForShuffleVector(V1), Mask, Name,
InsertAtEnd) {}
ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
const Twine &Name,
Instruction *InsertBefore)
: Instruction(
VectorType::get(cast<VectorType>(V1->getType())->getElementType(),
cast<VectorType>(Mask->getType())->getElementCount()),
ShuffleVector, OperandTraits<ShuffleVectorInst>::op_begin(this),
OperandTraits<ShuffleVectorInst>::operands(this), InsertBefore) {
assert(isValidOperands(V1, V2, Mask) &&
"Invalid shuffle vector instruction operands!");
Op<0>() = V1;
Op<1>() = V2;
SmallVector<int, 16> MaskArr;
getShuffleMask(cast<Constant>(Mask), MaskArr);
setShuffleMask(MaskArr);
setName(Name);
}
ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
const Twine &Name, BasicBlock *InsertAtEnd)
: Instruction(
VectorType::get(cast<VectorType>(V1->getType())->getElementType(),
cast<VectorType>(Mask->getType())->getElementCount()),
ShuffleVector, OperandTraits<ShuffleVectorInst>::op_begin(this),
OperandTraits<ShuffleVectorInst>::operands(this), InsertAtEnd) {
assert(isValidOperands(V1, V2, Mask) &&
"Invalid shuffle vector instruction operands!");
Op<0>() = V1;
Op<1>() = V2;
SmallVector<int, 16> MaskArr;
getShuffleMask(cast<Constant>(Mask), MaskArr);
setShuffleMask(MaskArr);
setName(Name);
}
ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, ArrayRef<int> Mask,
const Twine &Name,
Instruction *InsertBefore)
: Instruction(
VectorType::get(cast<VectorType>(V1->getType())->getElementType(),
Mask.size(), isa<ScalableVectorType>(V1->getType())),
ShuffleVector, OperandTraits<ShuffleVectorInst>::op_begin(this),
OperandTraits<ShuffleVectorInst>::operands(this), InsertBefore) {
assert(isValidOperands(V1, V2, Mask) &&
"Invalid shuffle vector instruction operands!");
Op<0>() = V1;
Op<1>() = V2;
setShuffleMask(Mask);
setName(Name);
}
ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, ArrayRef<int> Mask,
const Twine &Name, BasicBlock *InsertAtEnd)
: Instruction(
VectorType::get(cast<VectorType>(V1->getType())->getElementType(),
Mask.size(), isa<ScalableVectorType>(V1->getType())),
ShuffleVector, OperandTraits<ShuffleVectorInst>::op_begin(this),
OperandTraits<ShuffleVectorInst>::operands(this), InsertAtEnd) {
assert(isValidOperands(V1, V2, Mask) &&
"Invalid shuffle vector instruction operands!");
Op<0>() = V1;
Op<1>() = V2;
setShuffleMask(Mask);
setName(Name);
}
void ShuffleVectorInst::commute() {
int NumOpElts = cast<FixedVectorType>(Op<0>()->getType())->getNumElements();
int NumMaskElts = ShuffleMask.size();
SmallVector<int, 16> NewMask(NumMaskElts);
for (int i = 0; i != NumMaskElts; ++i) {
int MaskElt = getMaskValue(i);
if (MaskElt == UndefMaskElem) {
NewMask[i] = UndefMaskElem;
continue;
}
assert(MaskElt >= 0 && MaskElt < 2 * NumOpElts && "Out-of-range mask");
MaskElt = (MaskElt < NumOpElts) ? MaskElt + NumOpElts : MaskElt - NumOpElts;
NewMask[i] = MaskElt;
}
setShuffleMask(NewMask);
Op<0>().swap(Op<1>());
}
bool ShuffleVectorInst::isValidOperands(const Value *V1, const Value *V2,
ArrayRef<int> Mask) {
if (!isa<VectorType>(V1->getType()) || V1->getType() != V2->getType())
return false;
int V1Size =
cast<VectorType>(V1->getType())->getElementCount().getKnownMinValue();
for (int Elem : Mask)
if (Elem != UndefMaskElem && Elem >= V1Size * 2)
return false;
if (isa<ScalableVectorType>(V1->getType()))
if ((Mask[0] != 0 && Mask[0] != UndefMaskElem) || !is_splat(Mask))
return false;
return true;
}
bool ShuffleVectorInst::isValidOperands(const Value *V1, const Value *V2,
const Value *Mask) {
if (!V1->getType()->isVectorTy() || V1->getType() != V2->getType())
return false;
auto *MaskTy = dyn_cast<VectorType>(Mask->getType());
if (!MaskTy || !MaskTy->getElementType()->isIntegerTy(32) ||
isa<ScalableVectorType>(MaskTy) != isa<ScalableVectorType>(V1->getType()))
return false;
if (isa<UndefValue>(Mask) || isa<ConstantAggregateZero>(Mask))
return true;
if (const auto *MV = dyn_cast<ConstantVector>(Mask)) {
unsigned V1Size = cast<FixedVectorType>(V1->getType())->getNumElements();
for (Value *Op : MV->operands()) {
if (auto *CI = dyn_cast<ConstantInt>(Op)) {
if (CI->uge(V1Size*2))
return false;
} else if (!isa<UndefValue>(Op)) {
return false;
}
}
return true;
}
if (const auto *CDS = dyn_cast<ConstantDataSequential>(Mask)) {
unsigned V1Size = cast<FixedVectorType>(V1->getType())->getNumElements();
for (unsigned i = 0, e = cast<FixedVectorType>(MaskTy)->getNumElements();
i != e; ++i)
if (CDS->getElementAsInteger(i) >= V1Size*2)
return false;
return true;
}
return false;
}
void ShuffleVectorInst::getShuffleMask(const Constant *Mask,
SmallVectorImpl<int> &Result) {
ElementCount EC = cast<VectorType>(Mask->getType())->getElementCount();
if (isa<ConstantAggregateZero>(Mask)) {
Result.resize(EC.getKnownMinValue(), 0);
return;
}
Result.reserve(EC.getKnownMinValue());
if (EC.isScalable()) {
assert((isa<ConstantAggregateZero>(Mask) || isa<UndefValue>(Mask)) &&
"Scalable vector shuffle mask must be undef or zeroinitializer");
int MaskVal = isa<UndefValue>(Mask) ? -1 : 0;
for (unsigned I = 0; I < EC.getKnownMinValue(); ++I)
Result.emplace_back(MaskVal);
return;
}
unsigned NumElts = EC.getKnownMinValue();
if (auto *CDS = dyn_cast<ConstantDataSequential>(Mask)) {
for (unsigned i = 0; i != NumElts; ++i)
Result.push_back(CDS->getElementAsInteger(i));
return;
}
for (unsigned i = 0; i != NumElts; ++i) {
Constant *C = Mask->getAggregateElement(i);
Result.push_back(isa<UndefValue>(C) ? -1 :
cast<ConstantInt>(C)->getZExtValue());
}
}
void ShuffleVectorInst::setShuffleMask(ArrayRef<int> Mask) {
ShuffleMask.assign(Mask.begin(), Mask.end());
ShuffleMaskForBitcode = convertShuffleMaskForBitcode(Mask, getType());
}
Constant *ShuffleVectorInst::convertShuffleMaskForBitcode(ArrayRef<int> Mask,
Type *ResultTy) {
Type *Int32Ty = Type::getInt32Ty(ResultTy->getContext());
if (isa<ScalableVectorType>(ResultTy)) {
assert(is_splat(Mask) && "Unexpected shuffle");
Type *VecTy = VectorType::get(Int32Ty, Mask.size(), true);
if (Mask[0] == 0)
return Constant::getNullValue(VecTy);
return UndefValue::get(VecTy);
}
SmallVector<Constant *, 16> MaskConst;
for (int Elem : Mask) {
if (Elem == UndefMaskElem)
MaskConst.push_back(UndefValue::get(Int32Ty));
else
MaskConst.push_back(ConstantInt::get(Int32Ty, Elem));
}
return ConstantVector::get(MaskConst);
}
static bool isSingleSourceMaskImpl(ArrayRef<int> Mask, int NumOpElts) {
assert(!Mask.empty() && "Shuffle mask must contain elements");
bool UsesLHS = false;
bool UsesRHS = false;
for (int I : Mask) {
if (I == -1)
continue;
assert(I >= 0 && I < (NumOpElts * 2) &&
"Out-of-bounds shuffle mask element");
UsesLHS |= (I < NumOpElts);
UsesRHS |= (I >= NumOpElts);
if (UsesLHS && UsesRHS)
return false;
}
return UsesLHS || UsesRHS;
}
bool ShuffleVectorInst::isSingleSourceMask(ArrayRef<int> Mask) {
return isSingleSourceMaskImpl(Mask, Mask.size());
}
static bool isIdentityMaskImpl(ArrayRef<int> Mask, int NumOpElts) {
if (!isSingleSourceMaskImpl(Mask, NumOpElts))
return false;
for (int i = 0, NumMaskElts = Mask.size(); i < NumMaskElts; ++i) {
if (Mask[i] == -1)
continue;
if (Mask[i] != i && Mask[i] != (NumOpElts + i))
return false;
}
return true;
}
bool ShuffleVectorInst::isIdentityMask(ArrayRef<int> Mask) {
return isIdentityMaskImpl(Mask, Mask.size());
}
bool ShuffleVectorInst::isReverseMask(ArrayRef<int> Mask) {
if (!isSingleSourceMask(Mask))
return false;
int NumElts = Mask.size();
if (NumElts < 2)
return false;
for (int i = 0; i < NumElts; ++i) {
if (Mask[i] == -1)
continue;
if (Mask[i] != (NumElts - 1 - i) && Mask[i] != (NumElts + NumElts - 1 - i))
return false;
}
return true;
}
bool ShuffleVectorInst::isZeroEltSplatMask(ArrayRef<int> Mask) {
if (!isSingleSourceMask(Mask))
return false;
for (int i = 0, NumElts = Mask.size(); i < NumElts; ++i) {
if (Mask[i] == -1)
continue;
if (Mask[i] != 0 && Mask[i] != NumElts)
return false;
}
return true;
}
bool ShuffleVectorInst::isSelectMask(ArrayRef<int> Mask) {
if (isSingleSourceMask(Mask))
return false;
for (int i = 0, NumElts = Mask.size(); i < NumElts; ++i) {
if (Mask[i] == -1)
continue;
if (Mask[i] != i && Mask[i] != (NumElts + i))
return false;
}
return true;
}
bool ShuffleVectorInst::isTransposeMask(ArrayRef<int> Mask) {
int NumElts = Mask.size();
if (NumElts < 2 || !isPowerOf2_32(NumElts))
return false;
if (Mask[0] != 0 && Mask[0] != 1)
return false;
if ((Mask[1] - Mask[0]) != NumElts)
return false;
for (int i = 2; i < NumElts; ++i) {
int MaskEltVal = Mask[i];
if (MaskEltVal == -1)
return false;
int MaskEltPrevVal = Mask[i - 2];
if (MaskEltVal - MaskEltPrevVal != 2)
return false;
}
return true;
}
bool ShuffleVectorInst::isExtractSubvectorMask(ArrayRef<int> Mask,
int NumSrcElts, int &Index) {
if (!isSingleSourceMaskImpl(Mask, NumSrcElts))
return false;
if (NumSrcElts <= (int)Mask.size())
return false;
int SubIndex = -1;
for (int i = 0, e = Mask.size(); i != e; ++i) {
int M = Mask[i];
if (M < 0)
continue;
int Offset = (M % NumSrcElts) - i;
if (0 <= SubIndex && SubIndex != Offset)
return false;
SubIndex = Offset;
}
if (0 <= SubIndex && SubIndex + (int)Mask.size() <= NumSrcElts) {
Index = SubIndex;
return true;
}
return false;
}
bool ShuffleVectorInst::isInsertSubvectorMask(ArrayRef<int> Mask,
int NumSrcElts, int &NumSubElts,
int &Index) {
int NumMaskElts = Mask.size();
if (NumMaskElts < NumSrcElts)
return false;
if (isSingleSourceMaskImpl(Mask, NumSrcElts))
return false;
APInt UndefElts = APInt::getZero(NumMaskElts);
APInt Src0Elts = APInt::getZero(NumMaskElts);
APInt Src1Elts = APInt::getZero(NumMaskElts);
bool Src0Identity = true;
bool Src1Identity = true;
for (int i = 0; i != NumMaskElts; ++i) {
int M = Mask[i];
if (M < 0) {
UndefElts.setBit(i);
continue;
}
if (M < NumSrcElts) {
Src0Elts.setBit(i);
Src0Identity &= (M == i);
continue;
}
Src1Elts.setBit(i);
Src1Identity &= (M == (i + NumSrcElts));
}
assert((Src0Elts | Src1Elts | UndefElts).isAllOnes() &&
"unknown shuffle elements");
assert(!Src0Elts.isZero() && !Src1Elts.isZero() &&
"2-source shuffle not found");
int Src0Lo = Src0Elts.countTrailingZeros();
int Src1Lo = Src1Elts.countTrailingZeros();
int Src0Hi = NumMaskElts - Src0Elts.countLeadingZeros();
int Src1Hi = NumMaskElts - Src1Elts.countLeadingZeros();
if (Src0Identity) {
int NumSub1Elts = Src1Hi - Src1Lo;
ArrayRef<int> Sub1Mask = Mask.slice(Src1Lo, NumSub1Elts);
if (isIdentityMaskImpl(Sub1Mask, NumSrcElts)) {
NumSubElts = NumSub1Elts;
Index = Src1Lo;
return true;
}
}
if (Src1Identity) {
int NumSub0Elts = Src0Hi - Src0Lo;
ArrayRef<int> Sub0Mask = Mask.slice(Src0Lo, NumSub0Elts);
if (isIdentityMaskImpl(Sub0Mask, NumSrcElts)) {
NumSubElts = NumSub0Elts;
Index = Src0Lo;
return true;
}
}
return false;
}
bool ShuffleVectorInst::isIdentityWithPadding() const {
if (isa<UndefValue>(Op<2>()))
return false;
if (isa<ScalableVectorType>(getType()))
return false;
int NumOpElts = cast<FixedVectorType>(Op<0>()->getType())->getNumElements();
int NumMaskElts = cast<FixedVectorType>(getType())->getNumElements();
if (NumMaskElts <= NumOpElts)
return false;
ArrayRef<int> Mask = getShuffleMask();
if (!isIdentityMaskImpl(Mask, NumOpElts))
return false;
for (int i = NumOpElts; i < NumMaskElts; ++i)
if (Mask[i] != -1)
return false;
return true;
}
bool ShuffleVectorInst::isIdentityWithExtract() const {
if (isa<UndefValue>(Op<2>()))
return false;
if (isa<ScalableVectorType>(getType()))
return false;
int NumOpElts = cast<FixedVectorType>(Op<0>()->getType())->getNumElements();
int NumMaskElts = cast<FixedVectorType>(getType())->getNumElements();
if (NumMaskElts >= NumOpElts)
return false;
return isIdentityMaskImpl(getShuffleMask(), NumOpElts);
}
bool ShuffleVectorInst::isConcat() const {
if (isa<UndefValue>(Op<0>()) || isa<UndefValue>(Op<1>()) ||
isa<UndefValue>(Op<2>()))
return false;
if (isa<ScalableVectorType>(getType()))
return false;
int NumOpElts = cast<FixedVectorType>(Op<0>()->getType())->getNumElements();
int NumMaskElts = cast<FixedVectorType>(getType())->getNumElements();
if (NumMaskElts != NumOpElts * 2)
return false;
return isIdentityMaskImpl(getShuffleMask(), NumMaskElts);
}
static bool isReplicationMaskWithParams(ArrayRef<int> Mask,
int ReplicationFactor, int VF) {
assert(Mask.size() == (unsigned)ReplicationFactor * VF &&
"Unexpected mask size.");
for (int CurrElt : seq(0, VF)) {
ArrayRef<int> CurrSubMask = Mask.take_front(ReplicationFactor);
assert(CurrSubMask.size() == (unsigned)ReplicationFactor &&
"Run out of mask?");
Mask = Mask.drop_front(ReplicationFactor);
if (!all_of(CurrSubMask, [CurrElt](int MaskElt) {
return MaskElt == UndefMaskElem || MaskElt == CurrElt;
}))
return false;
}
assert(Mask.empty() && "Did not consume the whole mask?");
return true;
}
bool ShuffleVectorInst::isReplicationMask(ArrayRef<int> Mask,
int &ReplicationFactor, int &VF) {
if (none_of(Mask, [](int MaskElt) { return MaskElt == UndefMaskElem; })) {
ReplicationFactor =
Mask.take_while([](int MaskElt) { return MaskElt == 0; }).size();
if (ReplicationFactor == 0 || Mask.size() % ReplicationFactor != 0)
return false;
VF = Mask.size() / ReplicationFactor;
return isReplicationMaskWithParams(Mask, ReplicationFactor, VF);
}
int Largest = -1;
for (int MaskElt : Mask) {
if (MaskElt == UndefMaskElem)
continue;
if (MaskElt < Largest)
return false;
Largest = std::max(Largest, MaskElt);
}
for (int PossibleReplicationFactor :
reverse(seq_inclusive<unsigned>(1, Mask.size()))) {
if (Mask.size() % PossibleReplicationFactor != 0)
continue;
int PossibleVF = Mask.size() / PossibleReplicationFactor;
if (!isReplicationMaskWithParams(Mask, PossibleReplicationFactor,
PossibleVF))
continue;
ReplicationFactor = PossibleReplicationFactor;
VF = PossibleVF;
return true;
}
return false;
}
bool ShuffleVectorInst::isReplicationMask(int &ReplicationFactor,
int &VF) const {
if (isa<ScalableVectorType>(getType()))
return false;
VF = cast<FixedVectorType>(Op<0>()->getType())->getNumElements();
if (ShuffleMask.size() % VF != 0)
return false;
ReplicationFactor = ShuffleMask.size() / VF;
return isReplicationMaskWithParams(ShuffleMask, ReplicationFactor, VF);
}
void InsertValueInst::init(Value *Agg, Value *Val, ArrayRef<unsigned> Idxs,
const Twine &Name) {
assert(getNumOperands() == 2 && "NumOperands not initialized?");
assert(!Idxs.empty() && "InsertValueInst must have at least one index");
assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs) ==
Val->getType() && "Inserted value must match indexed type!");
Op<0>() = Agg;
Op<1>() = Val;
Indices.append(Idxs.begin(), Idxs.end());
setName(Name);
}
InsertValueInst::InsertValueInst(const InsertValueInst &IVI)
: Instruction(IVI.getType(), InsertValue,
OperandTraits<InsertValueInst>::op_begin(this), 2),
Indices(IVI.Indices) {
Op<0>() = IVI.getOperand(0);
Op<1>() = IVI.getOperand(1);
SubclassOptionalData = IVI.SubclassOptionalData;
}
void ExtractValueInst::init(ArrayRef<unsigned> Idxs, const Twine &Name) {
assert(getNumOperands() == 1 && "NumOperands not initialized?");
assert(!Idxs.empty() && "ExtractValueInst must have at least one index");
Indices.append(Idxs.begin(), Idxs.end());
setName(Name);
}
ExtractValueInst::ExtractValueInst(const ExtractValueInst &EVI)
: UnaryInstruction(EVI.getType(), ExtractValue, EVI.getOperand(0)),
Indices(EVI.Indices) {
SubclassOptionalData = EVI.SubclassOptionalData;
}
Type *ExtractValueInst::getIndexedType(Type *Agg,
ArrayRef<unsigned> Idxs) {
for (unsigned Index : Idxs) {
if (ArrayType *AT = dyn_cast<ArrayType>(Agg)) {
if (Index >= AT->getNumElements())
return nullptr;
Agg = AT->getElementType();
} else if (StructType *ST = dyn_cast<StructType>(Agg)) {
if (Index >= ST->getNumElements())
return nullptr;
Agg = ST->getElementType(Index);
} else {
return nullptr;
}
}
return const_cast<Type*>(Agg);
}
UnaryOperator::UnaryOperator(UnaryOps iType, Value *S,
Type *Ty, const Twine &Name,
Instruction *InsertBefore)
: UnaryInstruction(Ty, iType, S, InsertBefore) {
Op<0>() = S;
setName(Name);
AssertOK();
}
UnaryOperator::UnaryOperator(UnaryOps iType, Value *S,
Type *Ty, const Twine &Name,
BasicBlock *InsertAtEnd)
: UnaryInstruction(Ty, iType, S, InsertAtEnd) {
Op<0>() = S;
setName(Name);
AssertOK();
}
UnaryOperator *UnaryOperator::Create(UnaryOps Op, Value *S,
const Twine &Name,
Instruction *InsertBefore) {
return new UnaryOperator(Op, S, S->getType(), Name, InsertBefore);
}
UnaryOperator *UnaryOperator::Create(UnaryOps Op, Value *S,
const Twine &Name,
BasicBlock *InsertAtEnd) {
UnaryOperator *Res = Create(Op, S, Name);
InsertAtEnd->getInstList().push_back(Res);
return Res;
}
void UnaryOperator::AssertOK() {
Value *LHS = getOperand(0);
(void)LHS; #ifndef NDEBUG
switch (getOpcode()) {
case FNeg:
assert(getType() == LHS->getType() &&
"Unary operation should return same type as operand!");
assert(getType()->isFPOrFPVectorTy() &&
"Tried to create a floating-point operation on a "
"non-floating-point type!");
break;
default: llvm_unreachable("Invalid opcode provided");
}
#endif
}
BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
Type *Ty, const Twine &Name,
Instruction *InsertBefore)
: Instruction(Ty, iType,
OperandTraits<BinaryOperator>::op_begin(this),
OperandTraits<BinaryOperator>::operands(this),
InsertBefore) {
Op<0>() = S1;
Op<1>() = S2;
setName(Name);
AssertOK();
}
BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
Type *Ty, const Twine &Name,
BasicBlock *InsertAtEnd)
: Instruction(Ty, iType,
OperandTraits<BinaryOperator>::op_begin(this),
OperandTraits<BinaryOperator>::operands(this),
InsertAtEnd) {
Op<0>() = S1;
Op<1>() = S2;
setName(Name);
AssertOK();
}
void BinaryOperator::AssertOK() {
Value *LHS = getOperand(0), *RHS = getOperand(1);
(void)LHS; (void)RHS; assert(LHS->getType() == RHS->getType() &&
"Binary operator operand types must match!");
#ifndef NDEBUG
switch (getOpcode()) {
case Add: case Sub:
case Mul:
assert(getType() == LHS->getType() &&
"Arithmetic operation should return same type as operands!");
assert(getType()->isIntOrIntVectorTy() &&
"Tried to create an integer operation on a non-integer type!");
break;
case FAdd: case FSub:
case FMul:
assert(getType() == LHS->getType() &&
"Arithmetic operation should return same type as operands!");
assert(getType()->isFPOrFPVectorTy() &&
"Tried to create a floating-point operation on a "
"non-floating-point type!");
break;
case UDiv:
case SDiv:
assert(getType() == LHS->getType() &&
"Arithmetic operation should return same type as operands!");
assert(getType()->isIntOrIntVectorTy() &&
"Incorrect operand type (not integer) for S/UDIV");
break;
case FDiv:
assert(getType() == LHS->getType() &&
"Arithmetic operation should return same type as operands!");
assert(getType()->isFPOrFPVectorTy() &&
"Incorrect operand type (not floating point) for FDIV");
break;
case URem:
case SRem:
assert(getType() == LHS->getType() &&
"Arithmetic operation should return same type as operands!");
assert(getType()->isIntOrIntVectorTy() &&
"Incorrect operand type (not integer) for S/UREM");
break;
case FRem:
assert(getType() == LHS->getType() &&
"Arithmetic operation should return same type as operands!");
assert(getType()->isFPOrFPVectorTy() &&
"Incorrect operand type (not floating point) for FREM");
break;
case Shl:
case LShr:
case AShr:
assert(getType() == LHS->getType() &&
"Shift operation should return same type as operands!");
assert(getType()->isIntOrIntVectorTy() &&
"Tried to create a shift operation on a non-integral type!");
break;
case And: case Or:
case Xor:
assert(getType() == LHS->getType() &&
"Logical operation should return same type as operands!");
assert(getType()->isIntOrIntVectorTy() &&
"Tried to create a logical operation on a non-integral type!");
break;
default: llvm_unreachable("Invalid opcode provided");
}
#endif
}
BinaryOperator *BinaryOperator::Create(BinaryOps Op, Value *S1, Value *S2,
const Twine &Name,
Instruction *InsertBefore) {
assert(S1->getType() == S2->getType() &&
"Cannot create binary operator with two operands of differing type!");
return new BinaryOperator(Op, S1, S2, S1->getType(), Name, InsertBefore);
}
BinaryOperator *BinaryOperator::Create(BinaryOps Op, Value *S1, Value *S2,
const Twine &Name,
BasicBlock *InsertAtEnd) {
BinaryOperator *Res = Create(Op, S1, S2, Name);
InsertAtEnd->getInstList().push_back(Res);
return Res;
}
BinaryOperator *BinaryOperator::CreateNeg(Value *Op, const Twine &Name,
Instruction *InsertBefore) {
Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
return new BinaryOperator(Instruction::Sub,
zero, Op,
Op->getType(), Name, InsertBefore);
}
BinaryOperator *BinaryOperator::CreateNeg(Value *Op, const Twine &Name,
BasicBlock *InsertAtEnd) {
Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
return new BinaryOperator(Instruction::Sub,
zero, Op,
Op->getType(), Name, InsertAtEnd);
}
BinaryOperator *BinaryOperator::CreateNSWNeg(Value *Op, const Twine &Name,
Instruction *InsertBefore) {
Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
return BinaryOperator::CreateNSWSub(zero, Op, Name, InsertBefore);
}
BinaryOperator *BinaryOperator::CreateNSWNeg(Value *Op, const Twine &Name,
BasicBlock *InsertAtEnd) {
Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
return BinaryOperator::CreateNSWSub(zero, Op, Name, InsertAtEnd);
}
BinaryOperator *BinaryOperator::CreateNUWNeg(Value *Op, const Twine &Name,
Instruction *InsertBefore) {
Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
return BinaryOperator::CreateNUWSub(zero, Op, Name, InsertBefore);
}
BinaryOperator *BinaryOperator::CreateNUWNeg(Value *Op, const Twine &Name,
BasicBlock *InsertAtEnd) {
Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
return BinaryOperator::CreateNUWSub(zero, Op, Name, InsertAtEnd);
}
BinaryOperator *BinaryOperator::CreateNot(Value *Op, const Twine &Name,
Instruction *InsertBefore) {
Constant *C = Constant::getAllOnesValue(Op->getType());
return new BinaryOperator(Instruction::Xor, Op, C,
Op->getType(), Name, InsertBefore);
}
BinaryOperator *BinaryOperator::CreateNot(Value *Op, const Twine &Name,
BasicBlock *InsertAtEnd) {
Constant *AllOnes = Constant::getAllOnesValue(Op->getType());
return new BinaryOperator(Instruction::Xor, Op, AllOnes,
Op->getType(), Name, InsertAtEnd);
}
bool BinaryOperator::swapOperands() {
if (!isCommutative())
return true; Op<0>().swap(Op<1>());
return false;
}
float FPMathOperator::getFPAccuracy() const {
const MDNode *MD =
cast<Instruction>(this)->getMetadata(LLVMContext::MD_fpmath);
if (!MD)
return 0.0;
ConstantFP *Accuracy = mdconst::extract<ConstantFP>(MD->getOperand(0));
return Accuracy->getValueAPF().convertToFloat();
}
bool CastInst::isIntegerCast() const {
switch (getOpcode()) {
default: return false;
case Instruction::ZExt:
case Instruction::SExt:
case Instruction::Trunc:
return true;
case Instruction::BitCast:
return getOperand(0)->getType()->isIntegerTy() &&
getType()->isIntegerTy();
}
}
bool CastInst::isLosslessCast() const {
if (getOpcode() != Instruction::BitCast)
return false;
Type *SrcTy = getOperand(0)->getType();
Type *DstTy = getType();
if (SrcTy == DstTy)
return true;
if (SrcTy->isPointerTy())
return DstTy->isPointerTy();
return false; }
bool CastInst::isNoopCast(Instruction::CastOps Opcode,
Type *SrcTy,
Type *DestTy,
const DataLayout &DL) {
assert(castIsValid(Opcode, SrcTy, DestTy) && "method precondition");
switch (Opcode) {
default: llvm_unreachable("Invalid CastOp");
case Instruction::Trunc:
case Instruction::ZExt:
case Instruction::SExt:
case Instruction::FPTrunc:
case Instruction::FPExt:
case Instruction::UIToFP:
case Instruction::SIToFP:
case Instruction::FPToUI:
case Instruction::FPToSI:
case Instruction::AddrSpaceCast:
return false;
case Instruction::BitCast:
return true; case Instruction::PtrToInt:
return DL.getIntPtrType(SrcTy)->getScalarSizeInBits() ==
DestTy->getScalarSizeInBits();
case Instruction::IntToPtr:
return DL.getIntPtrType(DestTy)->getScalarSizeInBits() ==
SrcTy->getScalarSizeInBits();
}
}
bool CastInst::isNoopCast(const DataLayout &DL) const {
return isNoopCast(getOpcode(), getOperand(0)->getType(), getType(), DL);
}
unsigned CastInst::isEliminableCastPair(
Instruction::CastOps firstOp, Instruction::CastOps secondOp,
Type *SrcTy, Type *MidTy, Type *DstTy, Type *SrcIntPtrTy, Type *MidIntPtrTy,
Type *DstIntPtrTy) {
const unsigned numCastOps =
Instruction::CastOpsEnd - Instruction::CastOpsBegin;
static const uint8_t CastResults[numCastOps][numCastOps] = {
{ 1, 0, 0,99,99, 0, 0,99,99,99, 0, 3, 0}, { 8, 1, 9,99,99, 2,17,99,99,99, 2, 3, 0}, { 8, 0, 1,99,99, 0, 2,99,99,99, 0, 3, 0}, { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3, 0}, { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3, 0}, { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4, 0}, { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4, 0}, { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4, 0}, { 99,99,99, 2, 2,99,99, 8, 2,99,99, 4, 0}, { 1, 0, 0,99,99, 0, 0,99,99,99, 7, 3, 0}, { 99,99,99,99,99,99,99,99,99,11,99,15, 0}, { 5, 5, 5, 6, 6, 5, 5, 6, 6,16, 5, 1,14}, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,13,12}, };
bool IsFirstBitcast = (firstOp == Instruction::BitCast);
bool IsSecondBitcast = (secondOp == Instruction::BitCast);
bool AreBothBitcasts = IsFirstBitcast && IsSecondBitcast;
if ((IsFirstBitcast && isa<VectorType>(SrcTy) != isa<VectorType>(MidTy)) ||
(IsSecondBitcast && isa<VectorType>(MidTy) != isa<VectorType>(DstTy)))
if (!AreBothBitcasts)
return 0;
int ElimCase = CastResults[firstOp-Instruction::CastOpsBegin]
[secondOp-Instruction::CastOpsBegin];
switch (ElimCase) {
case 0:
return 0;
case 1:
return firstOp;
case 2:
return secondOp;
case 3:
if (!SrcTy->isVectorTy() && DstTy->isIntegerTy())
return firstOp;
return 0;
case 4:
if (DstTy->isFloatingPointTy())
return firstOp;
return 0;
case 5:
if (SrcTy->isIntegerTy())
return secondOp;
return 0;
case 6:
if (SrcTy->isFloatingPointTy())
return secondOp;
return 0;
case 7: {
if (DisableI2pP2iOpt)
return 0;
if (SrcTy->getPointerAddressSpace() != DstTy->getPointerAddressSpace())
return 0;
unsigned MidSize = MidTy->getScalarSizeInBits();
if (MidSize == 64)
return Instruction::BitCast;
if (!SrcIntPtrTy || DstIntPtrTy != SrcIntPtrTy)
return 0;
unsigned PtrSize = SrcIntPtrTy->getScalarSizeInBits();
if (MidSize >= PtrSize)
return Instruction::BitCast;
return 0;
}
case 8: {
unsigned SrcSize = SrcTy->getScalarSizeInBits();
unsigned DstSize = DstTy->getScalarSizeInBits();
if (SrcTy == DstTy)
return Instruction::BitCast;
if (SrcSize < DstSize)
return firstOp;
if (SrcSize > DstSize)
return secondOp;
return 0;
}
case 9:
return Instruction::ZExt;
case 11: {
if (!MidIntPtrTy)
return 0;
unsigned PtrSize = MidIntPtrTy->getScalarSizeInBits();
unsigned SrcSize = SrcTy->getScalarSizeInBits();
unsigned DstSize = DstTy->getScalarSizeInBits();
if (SrcSize <= PtrSize && SrcSize == DstSize)
return Instruction::BitCast;
return 0;
}
case 12:
if (SrcTy->getPointerAddressSpace() != DstTy->getPointerAddressSpace())
return Instruction::AddrSpaceCast;
return Instruction::BitCast;
case 13:
assert(
SrcTy->isPtrOrPtrVectorTy() &&
MidTy->isPtrOrPtrVectorTy() &&
DstTy->isPtrOrPtrVectorTy() &&
SrcTy->getPointerAddressSpace() != MidTy->getPointerAddressSpace() &&
MidTy->getPointerAddressSpace() == DstTy->getPointerAddressSpace() &&
"Illegal addrspacecast, bitcast sequence!");
return firstOp;
case 14: {
PointerType *SrcPtrTy = cast<PointerType>(SrcTy->getScalarType());
PointerType *DstPtrTy = cast<PointerType>(DstTy->getScalarType());
if (SrcPtrTy->hasSameElementTypeAs(DstPtrTy))
return Instruction::AddrSpaceCast;
return 0;
}
case 15:
assert(
SrcTy->isIntOrIntVectorTy() &&
MidTy->isPtrOrPtrVectorTy() &&
DstTy->isPtrOrPtrVectorTy() &&
MidTy->getPointerAddressSpace() == DstTy->getPointerAddressSpace() &&
"Illegal inttoptr, bitcast sequence!");
return firstOp;
case 16:
assert(
SrcTy->isPtrOrPtrVectorTy() &&
MidTy->isPtrOrPtrVectorTy() &&
DstTy->isIntOrIntVectorTy() &&
SrcTy->getPointerAddressSpace() == MidTy->getPointerAddressSpace() &&
"Illegal bitcast, ptrtoint sequence!");
return secondOp;
case 17:
return Instruction::UIToFP;
case 99:
llvm_unreachable("Invalid Cast Combination");
default:
llvm_unreachable("Error in CastResults table!!!");
}
}
CastInst *CastInst::Create(Instruction::CastOps op, Value *S, Type *Ty,
const Twine &Name, Instruction *InsertBefore) {
assert(castIsValid(op, S, Ty) && "Invalid cast!");
switch (op) {
case Trunc: return new TruncInst (S, Ty, Name, InsertBefore);
case ZExt: return new ZExtInst (S, Ty, Name, InsertBefore);
case SExt: return new SExtInst (S, Ty, Name, InsertBefore);
case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertBefore);
case FPExt: return new FPExtInst (S, Ty, Name, InsertBefore);
case UIToFP: return new UIToFPInst (S, Ty, Name, InsertBefore);
case SIToFP: return new SIToFPInst (S, Ty, Name, InsertBefore);
case FPToUI: return new FPToUIInst (S, Ty, Name, InsertBefore);
case FPToSI: return new FPToSIInst (S, Ty, Name, InsertBefore);
case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertBefore);
case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertBefore);
case BitCast: return new BitCastInst (S, Ty, Name, InsertBefore);
case AddrSpaceCast: return new AddrSpaceCastInst (S, Ty, Name, InsertBefore);
default: llvm_unreachable("Invalid opcode provided");
}
}
CastInst *CastInst::Create(Instruction::CastOps op, Value *S, Type *Ty,
const Twine &Name, BasicBlock *InsertAtEnd) {
assert(castIsValid(op, S, Ty) && "Invalid cast!");
switch (op) {
case Trunc: return new TruncInst (S, Ty, Name, InsertAtEnd);
case ZExt: return new ZExtInst (S, Ty, Name, InsertAtEnd);
case SExt: return new SExtInst (S, Ty, Name, InsertAtEnd);
case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertAtEnd);
case FPExt: return new FPExtInst (S, Ty, Name, InsertAtEnd);
case UIToFP: return new UIToFPInst (S, Ty, Name, InsertAtEnd);
case SIToFP: return new SIToFPInst (S, Ty, Name, InsertAtEnd);
case FPToUI: return new FPToUIInst (S, Ty, Name, InsertAtEnd);
case FPToSI: return new FPToSIInst (S, Ty, Name, InsertAtEnd);
case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertAtEnd);
case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertAtEnd);
case BitCast: return new BitCastInst (S, Ty, Name, InsertAtEnd);
case AddrSpaceCast: return new AddrSpaceCastInst (S, Ty, Name, InsertAtEnd);
default: llvm_unreachable("Invalid opcode provided");
}
}
CastInst *CastInst::CreateZExtOrBitCast(Value *S, Type *Ty,
const Twine &Name,
Instruction *InsertBefore) {
if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
return Create(Instruction::ZExt, S, Ty, Name, InsertBefore);
}
CastInst *CastInst::CreateZExtOrBitCast(Value *S, Type *Ty,
const Twine &Name,
BasicBlock *InsertAtEnd) {
if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
return Create(Instruction::ZExt, S, Ty, Name, InsertAtEnd);
}
CastInst *CastInst::CreateSExtOrBitCast(Value *S, Type *Ty,
const Twine &Name,
Instruction *InsertBefore) {
if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
return Create(Instruction::SExt, S, Ty, Name, InsertBefore);
}
CastInst *CastInst::CreateSExtOrBitCast(Value *S, Type *Ty,
const Twine &Name,
BasicBlock *InsertAtEnd) {
if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
return Create(Instruction::SExt, S, Ty, Name, InsertAtEnd);
}
CastInst *CastInst::CreateTruncOrBitCast(Value *S, Type *Ty,
const Twine &Name,
Instruction *InsertBefore) {
if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
return Create(Instruction::Trunc, S, Ty, Name, InsertBefore);
}
CastInst *CastInst::CreateTruncOrBitCast(Value *S, Type *Ty,
const Twine &Name,
BasicBlock *InsertAtEnd) {
if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
return Create(Instruction::Trunc, S, Ty, Name, InsertAtEnd);
}
CastInst *CastInst::CreatePointerCast(Value *S, Type *Ty,
const Twine &Name,
BasicBlock *InsertAtEnd) {
assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
assert((Ty->isIntOrIntVectorTy() || Ty->isPtrOrPtrVectorTy()) &&
"Invalid cast");
assert(Ty->isVectorTy() == S->getType()->isVectorTy() && "Invalid cast");
assert((!Ty->isVectorTy() ||
cast<VectorType>(Ty)->getElementCount() ==
cast<VectorType>(S->getType())->getElementCount()) &&
"Invalid cast");
if (Ty->isIntOrIntVectorTy())
return Create(Instruction::PtrToInt, S, Ty, Name, InsertAtEnd);
return CreatePointerBitCastOrAddrSpaceCast(S, Ty, Name, InsertAtEnd);
}
CastInst *CastInst::CreatePointerCast(Value *S, Type *Ty,
const Twine &Name,
Instruction *InsertBefore) {
assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
assert((Ty->isIntOrIntVectorTy() || Ty->isPtrOrPtrVectorTy()) &&
"Invalid cast");
assert(Ty->isVectorTy() == S->getType()->isVectorTy() && "Invalid cast");
assert((!Ty->isVectorTy() ||
cast<VectorType>(Ty)->getElementCount() ==
cast<VectorType>(S->getType())->getElementCount()) &&
"Invalid cast");
if (Ty->isIntOrIntVectorTy())
return Create(Instruction::PtrToInt, S, Ty, Name, InsertBefore);
return CreatePointerBitCastOrAddrSpaceCast(S, Ty, Name, InsertBefore);
}
CastInst *CastInst::CreatePointerBitCastOrAddrSpaceCast(
Value *S, Type *Ty,
const Twine &Name,
BasicBlock *InsertAtEnd) {
assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
assert(Ty->isPtrOrPtrVectorTy() && "Invalid cast");
if (S->getType()->getPointerAddressSpace() != Ty->getPointerAddressSpace())
return Create(Instruction::AddrSpaceCast, S, Ty, Name, InsertAtEnd);
return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
}
CastInst *CastInst::CreatePointerBitCastOrAddrSpaceCast(
Value *S, Type *Ty,
const Twine &Name,
Instruction *InsertBefore) {
assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
assert(Ty->isPtrOrPtrVectorTy() && "Invalid cast");
if (S->getType()->getPointerAddressSpace() != Ty->getPointerAddressSpace())
return Create(Instruction::AddrSpaceCast, S, Ty, Name, InsertBefore);
return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
}
CastInst *CastInst::CreateBitOrPointerCast(Value *S, Type *Ty,
const Twine &Name,
Instruction *InsertBefore) {
if (S->getType()->isPointerTy() && Ty->isIntegerTy())
return Create(Instruction::PtrToInt, S, Ty, Name, InsertBefore);
if (S->getType()->isIntegerTy() && Ty->isPointerTy())
return Create(Instruction::IntToPtr, S, Ty, Name, InsertBefore);
return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
}
CastInst *CastInst::CreateIntegerCast(Value *C, Type *Ty,
bool isSigned, const Twine &Name,
Instruction *InsertBefore) {
assert(C->getType()->isIntOrIntVectorTy() && Ty->isIntOrIntVectorTy() &&
"Invalid integer cast");
unsigned SrcBits = C->getType()->getScalarSizeInBits();
unsigned DstBits = Ty->getScalarSizeInBits();
Instruction::CastOps opcode =
(SrcBits == DstBits ? Instruction::BitCast :
(SrcBits > DstBits ? Instruction::Trunc :
(isSigned ? Instruction::SExt : Instruction::ZExt)));
return Create(opcode, C, Ty, Name, InsertBefore);
}
CastInst *CastInst::CreateIntegerCast(Value *C, Type *Ty,
bool isSigned, const Twine &Name,
BasicBlock *InsertAtEnd) {
assert(C->getType()->isIntOrIntVectorTy() && Ty->isIntOrIntVectorTy() &&
"Invalid cast");
unsigned SrcBits = C->getType()->getScalarSizeInBits();
unsigned DstBits = Ty->getScalarSizeInBits();
Instruction::CastOps opcode =
(SrcBits == DstBits ? Instruction::BitCast :
(SrcBits > DstBits ? Instruction::Trunc :
(isSigned ? Instruction::SExt : Instruction::ZExt)));
return Create(opcode, C, Ty, Name, InsertAtEnd);
}
CastInst *CastInst::CreateFPCast(Value *C, Type *Ty,
const Twine &Name,
Instruction *InsertBefore) {
assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
"Invalid cast");
unsigned SrcBits = C->getType()->getScalarSizeInBits();
unsigned DstBits = Ty->getScalarSizeInBits();
Instruction::CastOps opcode =
(SrcBits == DstBits ? Instruction::BitCast :
(SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
return Create(opcode, C, Ty, Name, InsertBefore);
}
CastInst *CastInst::CreateFPCast(Value *C, Type *Ty,
const Twine &Name,
BasicBlock *InsertAtEnd) {
assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
"Invalid cast");
unsigned SrcBits = C->getType()->getScalarSizeInBits();
unsigned DstBits = Ty->getScalarSizeInBits();
Instruction::CastOps opcode =
(SrcBits == DstBits ? Instruction::BitCast :
(SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
return Create(opcode, C, Ty, Name, InsertAtEnd);
}
bool CastInst::isBitCastable(Type *SrcTy, Type *DestTy) {
if (!SrcTy->isFirstClassType() || !DestTy->isFirstClassType())
return false;
if (SrcTy == DestTy)
return true;
if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy)) {
if (VectorType *DestVecTy = dyn_cast<VectorType>(DestTy)) {
if (SrcVecTy->getElementCount() == DestVecTy->getElementCount()) {
SrcTy = SrcVecTy->getElementType();
DestTy = DestVecTy->getElementType();
}
}
}
if (PointerType *DestPtrTy = dyn_cast<PointerType>(DestTy)) {
if (PointerType *SrcPtrTy = dyn_cast<PointerType>(SrcTy)) {
return SrcPtrTy->getAddressSpace() == DestPtrTy->getAddressSpace();
}
}
TypeSize SrcBits = SrcTy->getPrimitiveSizeInBits(); TypeSize DestBits = DestTy->getPrimitiveSizeInBits();
if (SrcBits.getKnownMinSize() == 0 || DestBits.getKnownMinSize() == 0)
return false;
if (SrcBits != DestBits)
return false;
if (DestTy->isX86_MMXTy() || SrcTy->isX86_MMXTy())
return false;
return true;
}
bool CastInst::isBitOrNoopPointerCastable(Type *SrcTy, Type *DestTy,
const DataLayout &DL) {
if (auto *PtrTy = dyn_cast<PointerType>(SrcTy))
if (auto *IntTy = dyn_cast<IntegerType>(DestTy))
return (IntTy->getBitWidth() == DL.getPointerTypeSizeInBits(PtrTy) &&
!DL.isNonIntegralPointerType(PtrTy));
if (auto *PtrTy = dyn_cast<PointerType>(DestTy))
if (auto *IntTy = dyn_cast<IntegerType>(SrcTy))
return (IntTy->getBitWidth() == DL.getPointerTypeSizeInBits(PtrTy) &&
!DL.isNonIntegralPointerType(PtrTy));
return isBitCastable(SrcTy, DestTy);
}
Instruction::CastOps
CastInst::getCastOpcode(
const Value *Src, bool SrcIsSigned, Type *DestTy, bool DestIsSigned) {
Type *SrcTy = Src->getType();
assert(SrcTy->isFirstClassType() && DestTy->isFirstClassType() &&
"Only first class types are castable!");
if (SrcTy == DestTy)
return BitCast;
if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy))
if (VectorType *DestVecTy = dyn_cast<VectorType>(DestTy))
if (SrcVecTy->getElementCount() == DestVecTy->getElementCount()) {
SrcTy = SrcVecTy->getElementType();
DestTy = DestVecTy->getElementType();
}
unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); unsigned DestBits = DestTy->getPrimitiveSizeInBits();
if (DestTy->isIntegerTy()) { if (SrcTy->isIntegerTy()) { if (DestBits < SrcBits)
return Trunc; else if (DestBits > SrcBits) { if (SrcIsSigned)
return SExt; else
return ZExt; } else {
return BitCast; }
} else if (SrcTy->isFloatingPointTy()) { if (DestIsSigned)
return FPToSI; else
return FPToUI; } else if (SrcTy->isVectorTy()) {
assert(DestBits == SrcBits &&
"Casting vector to integer of different width");
return BitCast; } else {
assert(SrcTy->isPointerTy() &&
"Casting from a value that is not first-class type");
return PtrToInt; }
} else if (DestTy->isFloatingPointTy()) { if (SrcTy->isIntegerTy()) { if (SrcIsSigned)
return SIToFP; else
return UIToFP; } else if (SrcTy->isFloatingPointTy()) { if (DestBits < SrcBits) {
return FPTrunc; } else if (DestBits > SrcBits) {
return FPExt; } else {
return BitCast; }
} else if (SrcTy->isVectorTy()) {
assert(DestBits == SrcBits &&
"Casting vector to floating point of different width");
return BitCast; }
llvm_unreachable("Casting pointer or non-first class to float");
} else if (DestTy->isVectorTy()) {
assert(DestBits == SrcBits &&
"Illegal cast to vector (wrong type or size)");
return BitCast;
} else if (DestTy->isPointerTy()) {
if (SrcTy->isPointerTy()) {
if (DestTy->getPointerAddressSpace() != SrcTy->getPointerAddressSpace())
return AddrSpaceCast;
return BitCast; } else if (SrcTy->isIntegerTy()) {
return IntToPtr; }
llvm_unreachable("Casting pointer to other than pointer or int");
} else if (DestTy->isX86_MMXTy()) {
if (SrcTy->isVectorTy()) {
assert(DestBits == SrcBits && "Casting vector of wrong width to X86_MMX");
return BitCast; }
llvm_unreachable("Illegal cast to X86_MMX");
}
llvm_unreachable("Casting to type that is not first-class");
}
bool
CastInst::castIsValid(Instruction::CastOps op, Type *SrcTy, Type *DstTy) {
if (!SrcTy->isFirstClassType() || !DstTy->isFirstClassType() ||
SrcTy->isAggregateType() || DstTy->isAggregateType())
return false;
bool SrcIsVec = isa<VectorType>(SrcTy);
bool DstIsVec = isa<VectorType>(DstTy);
unsigned SrcScalarBitSize = SrcTy->getScalarSizeInBits();
unsigned DstScalarBitSize = DstTy->getScalarSizeInBits();
ElementCount SrcEC = SrcIsVec ? cast<VectorType>(SrcTy)->getElementCount()
: ElementCount::getFixed(0);
ElementCount DstEC = DstIsVec ? cast<VectorType>(DstTy)->getElementCount()
: ElementCount::getFixed(0);
switch (op) {
default: return false; case Instruction::Trunc:
return SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy() &&
SrcEC == DstEC && SrcScalarBitSize > DstScalarBitSize;
case Instruction::ZExt:
return SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy() &&
SrcEC == DstEC && SrcScalarBitSize < DstScalarBitSize;
case Instruction::SExt:
return SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy() &&
SrcEC == DstEC && SrcScalarBitSize < DstScalarBitSize;
case Instruction::FPTrunc:
return SrcTy->isFPOrFPVectorTy() && DstTy->isFPOrFPVectorTy() &&
SrcEC == DstEC && SrcScalarBitSize > DstScalarBitSize;
case Instruction::FPExt:
return SrcTy->isFPOrFPVectorTy() && DstTy->isFPOrFPVectorTy() &&
SrcEC == DstEC && SrcScalarBitSize < DstScalarBitSize;
case Instruction::UIToFP:
case Instruction::SIToFP:
return SrcTy->isIntOrIntVectorTy() && DstTy->isFPOrFPVectorTy() &&
SrcEC == DstEC;
case Instruction::FPToUI:
case Instruction::FPToSI:
return SrcTy->isFPOrFPVectorTy() && DstTy->isIntOrIntVectorTy() &&
SrcEC == DstEC;
case Instruction::PtrToInt:
if (SrcEC != DstEC)
return false;
return SrcTy->isPtrOrPtrVectorTy() && DstTy->isIntOrIntVectorTy();
case Instruction::IntToPtr:
if (SrcEC != DstEC)
return false;
return SrcTy->isIntOrIntVectorTy() && DstTy->isPtrOrPtrVectorTy();
case Instruction::BitCast: {
PointerType *SrcPtrTy = dyn_cast<PointerType>(SrcTy->getScalarType());
PointerType *DstPtrTy = dyn_cast<PointerType>(DstTy->getScalarType());
if (!SrcPtrTy != !DstPtrTy)
return false;
if (!SrcPtrTy)
return SrcTy->getPrimitiveSizeInBits() == DstTy->getPrimitiveSizeInBits();
if (SrcPtrTy->getAddressSpace() != DstPtrTy->getAddressSpace())
return false;
if (SrcIsVec && DstIsVec)
return SrcEC == DstEC;
if (SrcIsVec)
return SrcEC == ElementCount::getFixed(1);
if (DstIsVec)
return DstEC == ElementCount::getFixed(1);
return true;
}
case Instruction::AddrSpaceCast: {
PointerType *SrcPtrTy = dyn_cast<PointerType>(SrcTy->getScalarType());
if (!SrcPtrTy)
return false;
PointerType *DstPtrTy = dyn_cast<PointerType>(DstTy->getScalarType());
if (!DstPtrTy)
return false;
if (SrcPtrTy->getAddressSpace() == DstPtrTy->getAddressSpace())
return false;
return SrcEC == DstEC;
}
}
}
TruncInst::TruncInst(
Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
) : CastInst(Ty, Trunc, S, Name, InsertBefore) {
assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
}
TruncInst::TruncInst(
Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
) : CastInst(Ty, Trunc, S, Name, InsertAtEnd) {
assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
}
ZExtInst::ZExtInst(
Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
) : CastInst(Ty, ZExt, S, Name, InsertBefore) {
assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
}
ZExtInst::ZExtInst(
Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
) : CastInst(Ty, ZExt, S, Name, InsertAtEnd) {
assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
}
SExtInst::SExtInst(
Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
) : CastInst(Ty, SExt, S, Name, InsertBefore) {
assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
}
SExtInst::SExtInst(
Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
) : CastInst(Ty, SExt, S, Name, InsertAtEnd) {
assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
}
FPTruncInst::FPTruncInst(
Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
) : CastInst(Ty, FPTrunc, S, Name, InsertBefore) {
assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
}
FPTruncInst::FPTruncInst(
Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
) : CastInst(Ty, FPTrunc, S, Name, InsertAtEnd) {
assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
}
FPExtInst::FPExtInst(
Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
) : CastInst(Ty, FPExt, S, Name, InsertBefore) {
assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
}
FPExtInst::FPExtInst(
Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
) : CastInst(Ty, FPExt, S, Name, InsertAtEnd) {
assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
}
UIToFPInst::UIToFPInst(
Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
) : CastInst(Ty, UIToFP, S, Name, InsertBefore) {
assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
}
UIToFPInst::UIToFPInst(
Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
) : CastInst(Ty, UIToFP, S, Name, InsertAtEnd) {
assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
}
SIToFPInst::SIToFPInst(
Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
) : CastInst(Ty, SIToFP, S, Name, InsertBefore) {
assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
}
SIToFPInst::SIToFPInst(
Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
) : CastInst(Ty, SIToFP, S, Name, InsertAtEnd) {
assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
}
FPToUIInst::FPToUIInst(
Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
) : CastInst(Ty, FPToUI, S, Name, InsertBefore) {
assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
}
FPToUIInst::FPToUIInst(
Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
) : CastInst(Ty, FPToUI, S, Name, InsertAtEnd) {
assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
}
FPToSIInst::FPToSIInst(
Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
) : CastInst(Ty, FPToSI, S, Name, InsertBefore) {
assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
}
FPToSIInst::FPToSIInst(
Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
) : CastInst(Ty, FPToSI, S, Name, InsertAtEnd) {
assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
}
PtrToIntInst::PtrToIntInst(
Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
) : CastInst(Ty, PtrToInt, S, Name, InsertBefore) {
assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
}
PtrToIntInst::PtrToIntInst(
Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
) : CastInst(Ty, PtrToInt, S, Name, InsertAtEnd) {
assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
}
IntToPtrInst::IntToPtrInst(
Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
) : CastInst(Ty, IntToPtr, S, Name, InsertBefore) {
assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
}
IntToPtrInst::IntToPtrInst(
Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
) : CastInst(Ty, IntToPtr, S, Name, InsertAtEnd) {
assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
}
BitCastInst::BitCastInst(
Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
) : CastInst(Ty, BitCast, S, Name, InsertBefore) {
assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
}
BitCastInst::BitCastInst(
Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
) : CastInst(Ty, BitCast, S, Name, InsertAtEnd) {
assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
}
AddrSpaceCastInst::AddrSpaceCastInst(
Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
) : CastInst(Ty, AddrSpaceCast, S, Name, InsertBefore) {
assert(castIsValid(getOpcode(), S, Ty) && "Illegal AddrSpaceCast");
}
AddrSpaceCastInst::AddrSpaceCastInst(
Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
) : CastInst(Ty, AddrSpaceCast, S, Name, InsertAtEnd) {
assert(castIsValid(getOpcode(), S, Ty) && "Illegal AddrSpaceCast");
}
CmpInst::CmpInst(Type *ty, OtherOps op, Predicate predicate, Value *LHS,
Value *RHS, const Twine &Name, Instruction *InsertBefore,
Instruction *FlagsSource)
: Instruction(ty, op,
OperandTraits<CmpInst>::op_begin(this),
OperandTraits<CmpInst>::operands(this),
InsertBefore) {
Op<0>() = LHS;
Op<1>() = RHS;
setPredicate((Predicate)predicate);
setName(Name);
if (FlagsSource)
copyIRFlags(FlagsSource);
}
CmpInst::CmpInst(Type *ty, OtherOps op, Predicate predicate, Value *LHS,
Value *RHS, const Twine &Name, BasicBlock *InsertAtEnd)
: Instruction(ty, op,
OperandTraits<CmpInst>::op_begin(this),
OperandTraits<CmpInst>::operands(this),
InsertAtEnd) {
Op<0>() = LHS;
Op<1>() = RHS;
setPredicate((Predicate)predicate);
setName(Name);
}
CmpInst *
CmpInst::Create(OtherOps Op, Predicate predicate, Value *S1, Value *S2,
const Twine &Name, Instruction *InsertBefore) {
if (Op == Instruction::ICmp) {
if (InsertBefore)
return new ICmpInst(InsertBefore, CmpInst::Predicate(predicate),
S1, S2, Name);
else
return new ICmpInst(CmpInst::Predicate(predicate),
S1, S2, Name);
}
if (InsertBefore)
return new FCmpInst(InsertBefore, CmpInst::Predicate(predicate),
S1, S2, Name);
else
return new FCmpInst(CmpInst::Predicate(predicate),
S1, S2, Name);
}
CmpInst *
CmpInst::Create(OtherOps Op, Predicate predicate, Value *S1, Value *S2,
const Twine &Name, BasicBlock *InsertAtEnd) {
if (Op == Instruction::ICmp) {
return new ICmpInst(*InsertAtEnd, CmpInst::Predicate(predicate),
S1, S2, Name);
}
return new FCmpInst(*InsertAtEnd, CmpInst::Predicate(predicate),
S1, S2, Name);
}
void CmpInst::swapOperands() {
if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
IC->swapOperands();
else
cast<FCmpInst>(this)->swapOperands();
}
bool CmpInst::isCommutative() const {
if (const ICmpInst *IC = dyn_cast<ICmpInst>(this))
return IC->isCommutative();
return cast<FCmpInst>(this)->isCommutative();
}
bool CmpInst::isEquality(Predicate P) {
if (ICmpInst::isIntPredicate(P))
return ICmpInst::isEquality(P);
if (FCmpInst::isFPPredicate(P))
return FCmpInst::isEquality(P);
llvm_unreachable("Unsupported predicate kind");
}
CmpInst::Predicate CmpInst::getInversePredicate(Predicate pred) {
switch (pred) {
default: llvm_unreachable("Unknown cmp predicate!");
case ICMP_EQ: return ICMP_NE;
case ICMP_NE: return ICMP_EQ;
case ICMP_UGT: return ICMP_ULE;
case ICMP_ULT: return ICMP_UGE;
case ICMP_UGE: return ICMP_ULT;
case ICMP_ULE: return ICMP_UGT;
case ICMP_SGT: return ICMP_SLE;
case ICMP_SLT: return ICMP_SGE;
case ICMP_SGE: return ICMP_SLT;
case ICMP_SLE: return ICMP_SGT;
case FCMP_OEQ: return FCMP_UNE;
case FCMP_ONE: return FCMP_UEQ;
case FCMP_OGT: return FCMP_ULE;
case FCMP_OLT: return FCMP_UGE;
case FCMP_OGE: return FCMP_ULT;
case FCMP_OLE: return FCMP_UGT;
case FCMP_UEQ: return FCMP_ONE;
case FCMP_UNE: return FCMP_OEQ;
case FCMP_UGT: return FCMP_OLE;
case FCMP_ULT: return FCMP_OGE;
case FCMP_UGE: return FCMP_OLT;
case FCMP_ULE: return FCMP_OGT;
case FCMP_ORD: return FCMP_UNO;
case FCMP_UNO: return FCMP_ORD;
case FCMP_TRUE: return FCMP_FALSE;
case FCMP_FALSE: return FCMP_TRUE;
}
}
StringRef CmpInst::getPredicateName(Predicate Pred) {
switch (Pred) {
default: return "unknown";
case FCmpInst::FCMP_FALSE: return "false";
case FCmpInst::FCMP_OEQ: return "oeq";
case FCmpInst::FCMP_OGT: return "ogt";
case FCmpInst::FCMP_OGE: return "oge";
case FCmpInst::FCMP_OLT: return "olt";
case FCmpInst::FCMP_OLE: return "ole";
case FCmpInst::FCMP_ONE: return "one";
case FCmpInst::FCMP_ORD: return "ord";
case FCmpInst::FCMP_UNO: return "uno";
case FCmpInst::FCMP_UEQ: return "ueq";
case FCmpInst::FCMP_UGT: return "ugt";
case FCmpInst::FCMP_UGE: return "uge";
case FCmpInst::FCMP_ULT: return "ult";
case FCmpInst::FCMP_ULE: return "ule";
case FCmpInst::FCMP_UNE: return "une";
case FCmpInst::FCMP_TRUE: return "true";
case ICmpInst::ICMP_EQ: return "eq";
case ICmpInst::ICMP_NE: return "ne";
case ICmpInst::ICMP_SGT: return "sgt";
case ICmpInst::ICMP_SGE: return "sge";
case ICmpInst::ICMP_SLT: return "slt";
case ICmpInst::ICMP_SLE: return "sle";
case ICmpInst::ICMP_UGT: return "ugt";
case ICmpInst::ICMP_UGE: return "uge";
case ICmpInst::ICMP_ULT: return "ult";
case ICmpInst::ICMP_ULE: return "ule";
}
}
ICmpInst::Predicate ICmpInst::getSignedPredicate(Predicate pred) {
switch (pred) {
default: llvm_unreachable("Unknown icmp predicate!");
case ICMP_EQ: case ICMP_NE:
case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE:
return pred;
case ICMP_UGT: return ICMP_SGT;
case ICMP_ULT: return ICMP_SLT;
case ICMP_UGE: return ICMP_SGE;
case ICMP_ULE: return ICMP_SLE;
}
}
ICmpInst::Predicate ICmpInst::getUnsignedPredicate(Predicate pred) {
switch (pred) {
default: llvm_unreachable("Unknown icmp predicate!");
case ICMP_EQ: case ICMP_NE:
case ICMP_UGT: case ICMP_ULT: case ICMP_UGE: case ICMP_ULE:
return pred;
case ICMP_SGT: return ICMP_UGT;
case ICMP_SLT: return ICMP_ULT;
case ICMP_SGE: return ICMP_UGE;
case ICMP_SLE: return ICMP_ULE;
}
}
CmpInst::Predicate CmpInst::getSwappedPredicate(Predicate pred) {
switch (pred) {
default: llvm_unreachable("Unknown cmp predicate!");
case ICMP_EQ: case ICMP_NE:
return pred;
case ICMP_SGT: return ICMP_SLT;
case ICMP_SLT: return ICMP_SGT;
case ICMP_SGE: return ICMP_SLE;
case ICMP_SLE: return ICMP_SGE;
case ICMP_UGT: return ICMP_ULT;
case ICMP_ULT: return ICMP_UGT;
case ICMP_UGE: return ICMP_ULE;
case ICMP_ULE: return ICMP_UGE;
case FCMP_FALSE: case FCMP_TRUE:
case FCMP_OEQ: case FCMP_ONE:
case FCMP_UEQ: case FCMP_UNE:
case FCMP_ORD: case FCMP_UNO:
return pred;
case FCMP_OGT: return FCMP_OLT;
case FCMP_OLT: return FCMP_OGT;
case FCMP_OGE: return FCMP_OLE;
case FCMP_OLE: return FCMP_OGE;
case FCMP_UGT: return FCMP_ULT;
case FCMP_ULT: return FCMP_UGT;
case FCMP_UGE: return FCMP_ULE;
case FCMP_ULE: return FCMP_UGE;
}
}
bool CmpInst::isNonStrictPredicate(Predicate pred) {
switch (pred) {
case ICMP_SGE:
case ICMP_SLE:
case ICMP_UGE:
case ICMP_ULE:
case FCMP_OGE:
case FCMP_OLE:
case FCMP_UGE:
case FCMP_ULE:
return true;
default:
return false;
}
}
bool CmpInst::isStrictPredicate(Predicate pred) {
switch (pred) {
case ICMP_SGT:
case ICMP_SLT:
case ICMP_UGT:
case ICMP_ULT:
case FCMP_OGT:
case FCMP_OLT:
case FCMP_UGT:
case FCMP_ULT:
return true;
default:
return false;
}
}
CmpInst::Predicate CmpInst::getStrictPredicate(Predicate pred) {
switch (pred) {
case ICMP_SGE:
return ICMP_SGT;
case ICMP_SLE:
return ICMP_SLT;
case ICMP_UGE:
return ICMP_UGT;
case ICMP_ULE:
return ICMP_ULT;
case FCMP_OGE:
return FCMP_OGT;
case FCMP_OLE:
return FCMP_OLT;
case FCMP_UGE:
return FCMP_UGT;
case FCMP_ULE:
return FCMP_ULT;
default:
return pred;
}
}
CmpInst::Predicate CmpInst::getNonStrictPredicate(Predicate pred) {
switch (pred) {
case ICMP_SGT:
return ICMP_SGE;
case ICMP_SLT:
return ICMP_SLE;
case ICMP_UGT:
return ICMP_UGE;
case ICMP_ULT:
return ICMP_ULE;
case FCMP_OGT:
return FCMP_OGE;
case FCMP_OLT:
return FCMP_OLE;
case FCMP_UGT:
return FCMP_UGE;
case FCMP_ULT:
return FCMP_ULE;
default:
return pred;
}
}
CmpInst::Predicate CmpInst::getFlippedStrictnessPredicate(Predicate pred) {
assert(CmpInst::isRelational(pred) && "Call only with relational predicate!");
if (isStrictPredicate(pred))
return getNonStrictPredicate(pred);
if (isNonStrictPredicate(pred))
return getStrictPredicate(pred);
llvm_unreachable("Unknown predicate!");
}
CmpInst::Predicate CmpInst::getSignedPredicate(Predicate pred) {
assert(CmpInst::isUnsigned(pred) && "Call only with unsigned predicates!");
switch (pred) {
default:
llvm_unreachable("Unknown predicate!");
case CmpInst::ICMP_ULT:
return CmpInst::ICMP_SLT;
case CmpInst::ICMP_ULE:
return CmpInst::ICMP_SLE;
case CmpInst::ICMP_UGT:
return CmpInst::ICMP_SGT;
case CmpInst::ICMP_UGE:
return CmpInst::ICMP_SGE;
}
}
CmpInst::Predicate CmpInst::getUnsignedPredicate(Predicate pred) {
assert(CmpInst::isSigned(pred) && "Call only with signed predicates!");
switch (pred) {
default:
llvm_unreachable("Unknown predicate!");
case CmpInst::ICMP_SLT:
return CmpInst::ICMP_ULT;
case CmpInst::ICMP_SLE:
return CmpInst::ICMP_ULE;
case CmpInst::ICMP_SGT:
return CmpInst::ICMP_UGT;
case CmpInst::ICMP_SGE:
return CmpInst::ICMP_UGE;
}
}
bool CmpInst::isUnsigned(Predicate predicate) {
switch (predicate) {
default: return false;
case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_ULE: case ICmpInst::ICMP_UGT:
case ICmpInst::ICMP_UGE: return true;
}
}
bool CmpInst::isSigned(Predicate predicate) {
switch (predicate) {
default: return false;
case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_SLE: case ICmpInst::ICMP_SGT:
case ICmpInst::ICMP_SGE: return true;
}
}
bool ICmpInst::compare(const APInt &LHS, const APInt &RHS,
ICmpInst::Predicate Pred) {
assert(ICmpInst::isIntPredicate(Pred) && "Only for integer predicates!");
switch (Pred) {
case ICmpInst::Predicate::ICMP_EQ:
return LHS.eq(RHS);
case ICmpInst::Predicate::ICMP_NE:
return LHS.ne(RHS);
case ICmpInst::Predicate::ICMP_UGT:
return LHS.ugt(RHS);
case ICmpInst::Predicate::ICMP_UGE:
return LHS.uge(RHS);
case ICmpInst::Predicate::ICMP_ULT:
return LHS.ult(RHS);
case ICmpInst::Predicate::ICMP_ULE:
return LHS.ule(RHS);
case ICmpInst::Predicate::ICMP_SGT:
return LHS.sgt(RHS);
case ICmpInst::Predicate::ICMP_SGE:
return LHS.sge(RHS);
case ICmpInst::Predicate::ICMP_SLT:
return LHS.slt(RHS);
case ICmpInst::Predicate::ICMP_SLE:
return LHS.sle(RHS);
default:
llvm_unreachable("Unexpected non-integer predicate.");
};
}
bool FCmpInst::compare(const APFloat &LHS, const APFloat &RHS,
FCmpInst::Predicate Pred) {
APFloat::cmpResult R = LHS.compare(RHS);
switch (Pred) {
default:
llvm_unreachable("Invalid FCmp Predicate");
case FCmpInst::FCMP_FALSE:
return false;
case FCmpInst::FCMP_TRUE:
return true;
case FCmpInst::FCMP_UNO:
return R == APFloat::cmpUnordered;
case FCmpInst::FCMP_ORD:
return R != APFloat::cmpUnordered;
case FCmpInst::FCMP_UEQ:
return R == APFloat::cmpUnordered || R == APFloat::cmpEqual;
case FCmpInst::FCMP_OEQ:
return R == APFloat::cmpEqual;
case FCmpInst::FCMP_UNE:
return R != APFloat::cmpEqual;
case FCmpInst::FCMP_ONE:
return R == APFloat::cmpLessThan || R == APFloat::cmpGreaterThan;
case FCmpInst::FCMP_ULT:
return R == APFloat::cmpUnordered || R == APFloat::cmpLessThan;
case FCmpInst::FCMP_OLT:
return R == APFloat::cmpLessThan;
case FCmpInst::FCMP_UGT:
return R == APFloat::cmpUnordered || R == APFloat::cmpGreaterThan;
case FCmpInst::FCMP_OGT:
return R == APFloat::cmpGreaterThan;
case FCmpInst::FCMP_ULE:
return R != APFloat::cmpGreaterThan;
case FCmpInst::FCMP_OLE:
return R == APFloat::cmpLessThan || R == APFloat::cmpEqual;
case FCmpInst::FCMP_UGE:
return R != APFloat::cmpLessThan;
case FCmpInst::FCMP_OGE:
return R == APFloat::cmpGreaterThan || R == APFloat::cmpEqual;
}
}
CmpInst::Predicate CmpInst::getFlippedSignednessPredicate(Predicate pred) {
assert(CmpInst::isRelational(pred) &&
"Call only with non-equality predicates!");
if (isSigned(pred))
return getUnsignedPredicate(pred);
if (isUnsigned(pred))
return getSignedPredicate(pred);
llvm_unreachable("Unknown predicate!");
}
bool CmpInst::isOrdered(Predicate predicate) {
switch (predicate) {
default: return false;
case FCmpInst::FCMP_OEQ: case FCmpInst::FCMP_ONE: case FCmpInst::FCMP_OGT:
case FCmpInst::FCMP_OLT: case FCmpInst::FCMP_OGE: case FCmpInst::FCMP_OLE:
case FCmpInst::FCMP_ORD: return true;
}
}
bool CmpInst::isUnordered(Predicate predicate) {
switch (predicate) {
default: return false;
case FCmpInst::FCMP_UEQ: case FCmpInst::FCMP_UNE: case FCmpInst::FCMP_UGT:
case FCmpInst::FCMP_ULT: case FCmpInst::FCMP_UGE: case FCmpInst::FCMP_ULE:
case FCmpInst::FCMP_UNO: return true;
}
}
bool CmpInst::isTrueWhenEqual(Predicate predicate) {
switch(predicate) {
default: return false;
case ICMP_EQ: case ICMP_UGE: case ICMP_ULE: case ICMP_SGE: case ICMP_SLE:
case FCMP_TRUE: case FCMP_UEQ: case FCMP_UGE: case FCMP_ULE: return true;
}
}
bool CmpInst::isFalseWhenEqual(Predicate predicate) {
switch(predicate) {
case ICMP_NE: case ICMP_UGT: case ICMP_ULT: case ICMP_SGT: case ICMP_SLT:
case FCMP_FALSE: case FCMP_ONE: case FCMP_OGT: case FCMP_OLT: return true;
default: return false;
}
}
bool CmpInst::isImpliedTrueByMatchingCmp(Predicate Pred1, Predicate Pred2) {
if (Pred1 == Pred2)
return true;
switch (Pred1) {
default:
break;
case ICMP_EQ:
return Pred2 == ICMP_UGE || Pred2 == ICMP_ULE || Pred2 == ICMP_SGE ||
Pred2 == ICMP_SLE;
case ICMP_UGT: return Pred2 == ICMP_NE || Pred2 == ICMP_UGE;
case ICMP_ULT: return Pred2 == ICMP_NE || Pred2 == ICMP_ULE;
case ICMP_SGT: return Pred2 == ICMP_NE || Pred2 == ICMP_SGE;
case ICMP_SLT: return Pred2 == ICMP_NE || Pred2 == ICMP_SLE;
}
return false;
}
bool CmpInst::isImpliedFalseByMatchingCmp(Predicate Pred1, Predicate Pred2) {
return isImpliedTrueByMatchingCmp(Pred1, getInversePredicate(Pred2));
}
void SwitchInst::init(Value *Value, BasicBlock *Default, unsigned NumReserved) {
assert(Value && Default && NumReserved);
ReservedSpace = NumReserved;
setNumHungOffUseOperands(2);
allocHungoffUses(ReservedSpace);
Op<0>() = Value;
Op<1>() = Default;
}
SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
Instruction *InsertBefore)
: Instruction(Type::getVoidTy(Value->getContext()), Instruction::Switch,
nullptr, 0, InsertBefore) {
init(Value, Default, 2+NumCases*2);
}
SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
BasicBlock *InsertAtEnd)
: Instruction(Type::getVoidTy(Value->getContext()), Instruction::Switch,
nullptr, 0, InsertAtEnd) {
init(Value, Default, 2+NumCases*2);
}
SwitchInst::SwitchInst(const SwitchInst &SI)
: Instruction(SI.getType(), Instruction::Switch, nullptr, 0) {
init(SI.getCondition(), SI.getDefaultDest(), SI.getNumOperands());
setNumHungOffUseOperands(SI.getNumOperands());
Use *OL = getOperandList();
const Use *InOL = SI.getOperandList();
for (unsigned i = 2, E = SI.getNumOperands(); i != E; i += 2) {
OL[i] = InOL[i];
OL[i+1] = InOL[i+1];
}
SubclassOptionalData = SI.SubclassOptionalData;
}
void SwitchInst::addCase(ConstantInt *OnVal, BasicBlock *Dest) {
unsigned NewCaseIdx = getNumCases();
unsigned OpNo = getNumOperands();
if (OpNo+2 > ReservedSpace)
growOperands(); assert(OpNo+1 < ReservedSpace && "Growing didn't work!");
setNumHungOffUseOperands(OpNo+2);
CaseHandle Case(this, NewCaseIdx);
Case.setValue(OnVal);
Case.setSuccessor(Dest);
}
SwitchInst::CaseIt SwitchInst::removeCase(CaseIt I) {
unsigned idx = I->getCaseIndex();
assert(2 + idx*2 < getNumOperands() && "Case index out of range!!!");
unsigned NumOps = getNumOperands();
Use *OL = getOperandList();
if (2 + (idx + 1) * 2 != NumOps) {
OL[2 + idx * 2] = OL[NumOps - 2];
OL[2 + idx * 2 + 1] = OL[NumOps - 1];
}
OL[NumOps-2].set(nullptr);
OL[NumOps-2+1].set(nullptr);
setNumHungOffUseOperands(NumOps-2);
return CaseIt(this, idx);
}
void SwitchInst::growOperands() {
unsigned e = getNumOperands();
unsigned NumOps = e*3;
ReservedSpace = NumOps;
growHungoffUses(ReservedSpace);
}
MDNode *
SwitchInstProfUpdateWrapper::getProfBranchWeightsMD(const SwitchInst &SI) {
if (MDNode *ProfileData = SI.getMetadata(LLVMContext::MD_prof))
if (auto *MDName = dyn_cast<MDString>(ProfileData->getOperand(0)))
if (MDName->getString() == "branch_weights")
return ProfileData;
return nullptr;
}
MDNode *SwitchInstProfUpdateWrapper::buildProfBranchWeightsMD() {
assert(Changed && "called only if metadata has changed");
if (!Weights)
return nullptr;
assert(SI.getNumSuccessors() == Weights->size() &&
"num of prof branch_weights must accord with num of successors");
bool AllZeroes = all_of(Weights.value(), [](uint32_t W) { return W == 0; });
if (AllZeroes || Weights.value().size() < 2)
return nullptr;
return MDBuilder(SI.getParent()->getContext()).createBranchWeights(*Weights);
}
void SwitchInstProfUpdateWrapper::init() {
MDNode *ProfileData = getProfBranchWeightsMD(SI);
if (!ProfileData)
return;
if (ProfileData->getNumOperands() != SI.getNumSuccessors() + 1) {
llvm_unreachable("number of prof branch_weights metadata operands does "
"not correspond to number of succesors");
}
SmallVector<uint32_t, 8> Weights;
for (unsigned CI = 1, CE = SI.getNumSuccessors(); CI <= CE; ++CI) {
ConstantInt *C = mdconst::extract<ConstantInt>(ProfileData->getOperand(CI));
uint32_t CW = C->getValue().getZExtValue();
Weights.push_back(CW);
}
this->Weights = std::move(Weights);
}
SwitchInst::CaseIt
SwitchInstProfUpdateWrapper::removeCase(SwitchInst::CaseIt I) {
if (Weights) {
assert(SI.getNumSuccessors() == Weights->size() &&
"num of prof branch_weights must accord with num of successors");
Changed = true;
Weights.value()[I->getCaseIndex() + 1] = Weights.value().back();
Weights.value().pop_back();
}
return SI.removeCase(I);
}
void SwitchInstProfUpdateWrapper::addCase(
ConstantInt *OnVal, BasicBlock *Dest,
SwitchInstProfUpdateWrapper::CaseWeightOpt W) {
SI.addCase(OnVal, Dest);
if (!Weights && W && *W) {
Changed = true;
Weights = SmallVector<uint32_t, 8>(SI.getNumSuccessors(), 0);
Weights.value()[SI.getNumSuccessors() - 1] = *W;
} else if (Weights) {
Changed = true;
Weights.value().push_back(W.value_or(0));
}
if (Weights)
assert(SI.getNumSuccessors() == Weights->size() &&
"num of prof branch_weights must accord with num of successors");
}
SymbolTableList<Instruction>::iterator
SwitchInstProfUpdateWrapper::eraseFromParent() {
Changed = false;
if (Weights)
Weights->resize(0);
return SI.eraseFromParent();
}
SwitchInstProfUpdateWrapper::CaseWeightOpt
SwitchInstProfUpdateWrapper::getSuccessorWeight(unsigned idx) {
if (!Weights)
return None;
return (*Weights)[idx];
}
void SwitchInstProfUpdateWrapper::setSuccessorWeight(
unsigned idx, SwitchInstProfUpdateWrapper::CaseWeightOpt W) {
if (!W)
return;
if (!Weights && *W)
Weights = SmallVector<uint32_t, 8>(SI.getNumSuccessors(), 0);
if (Weights) {
auto &OldW = (*Weights)[idx];
if (*W != OldW) {
Changed = true;
OldW = *W;
}
}
}
SwitchInstProfUpdateWrapper::CaseWeightOpt
SwitchInstProfUpdateWrapper::getSuccessorWeight(const SwitchInst &SI,
unsigned idx) {
if (MDNode *ProfileData = getProfBranchWeightsMD(SI))
if (ProfileData->getNumOperands() == SI.getNumSuccessors() + 1)
return mdconst::extract<ConstantInt>(ProfileData->getOperand(idx + 1))
->getValue()
.getZExtValue();
return None;
}
void IndirectBrInst::init(Value *Address, unsigned NumDests) {
assert(Address && Address->getType()->isPointerTy() &&
"Address of indirectbr must be a pointer");
ReservedSpace = 1+NumDests;
setNumHungOffUseOperands(1);
allocHungoffUses(ReservedSpace);
Op<0>() = Address;
}
void IndirectBrInst::growOperands() {
unsigned e = getNumOperands();
unsigned NumOps = e*2;
ReservedSpace = NumOps;
growHungoffUses(ReservedSpace);
}
IndirectBrInst::IndirectBrInst(Value *Address, unsigned NumCases,
Instruction *InsertBefore)
: Instruction(Type::getVoidTy(Address->getContext()),
Instruction::IndirectBr, nullptr, 0, InsertBefore) {
init(Address, NumCases);
}
IndirectBrInst::IndirectBrInst(Value *Address, unsigned NumCases,
BasicBlock *InsertAtEnd)
: Instruction(Type::getVoidTy(Address->getContext()),
Instruction::IndirectBr, nullptr, 0, InsertAtEnd) {
init(Address, NumCases);
}
IndirectBrInst::IndirectBrInst(const IndirectBrInst &IBI)
: Instruction(Type::getVoidTy(IBI.getContext()), Instruction::IndirectBr,
nullptr, IBI.getNumOperands()) {
allocHungoffUses(IBI.getNumOperands());
Use *OL = getOperandList();
const Use *InOL = IBI.getOperandList();
for (unsigned i = 0, E = IBI.getNumOperands(); i != E; ++i)
OL[i] = InOL[i];
SubclassOptionalData = IBI.SubclassOptionalData;
}
void IndirectBrInst::addDestination(BasicBlock *DestBB) {
unsigned OpNo = getNumOperands();
if (OpNo+1 > ReservedSpace)
growOperands(); assert(OpNo < ReservedSpace && "Growing didn't work!");
setNumHungOffUseOperands(OpNo+1);
getOperandList()[OpNo] = DestBB;
}
void IndirectBrInst::removeDestination(unsigned idx) {
assert(idx < getNumOperands()-1 && "Successor index out of range!");
unsigned NumOps = getNumOperands();
Use *OL = getOperandList();
OL[idx+1] = OL[NumOps-1];
OL[NumOps-1].set(nullptr);
setNumHungOffUseOperands(NumOps-1);
}
FreezeInst::FreezeInst(Value *S,
const Twine &Name, Instruction *InsertBefore)
: UnaryInstruction(S->getType(), Freeze, S, InsertBefore) {
setName(Name);
}
FreezeInst::FreezeInst(Value *S,
const Twine &Name, BasicBlock *InsertAtEnd)
: UnaryInstruction(S->getType(), Freeze, S, InsertAtEnd) {
setName(Name);
}
GetElementPtrInst *GetElementPtrInst::cloneImpl() const {
return new (getNumOperands()) GetElementPtrInst(*this);
}
UnaryOperator *UnaryOperator::cloneImpl() const {
return Create(getOpcode(), Op<0>());
}
BinaryOperator *BinaryOperator::cloneImpl() const {
return Create(getOpcode(), Op<0>(), Op<1>());
}
FCmpInst *FCmpInst::cloneImpl() const {
return new FCmpInst(getPredicate(), Op<0>(), Op<1>());
}
ICmpInst *ICmpInst::cloneImpl() const {
return new ICmpInst(getPredicate(), Op<0>(), Op<1>());
}
ExtractValueInst *ExtractValueInst::cloneImpl() const {
return new ExtractValueInst(*this);
}
InsertValueInst *InsertValueInst::cloneImpl() const {
return new InsertValueInst(*this);
}
AllocaInst *AllocaInst::cloneImpl() const {
AllocaInst *Result =
new AllocaInst(getAllocatedType(), getType()->getAddressSpace(),
getOperand(0), getAlign());
Result->setUsedWithInAlloca(isUsedWithInAlloca());
Result->setSwiftError(isSwiftError());
return Result;
}
LoadInst *LoadInst::cloneImpl() const {
return new LoadInst(getType(), getOperand(0), Twine(), isVolatile(),
getAlign(), getOrdering(), getSyncScopeID());
}
StoreInst *StoreInst::cloneImpl() const {
return new StoreInst(getOperand(0), getOperand(1), isVolatile(), getAlign(),
getOrdering(), getSyncScopeID());
}
AtomicCmpXchgInst *AtomicCmpXchgInst::cloneImpl() const {
AtomicCmpXchgInst *Result = new AtomicCmpXchgInst(
getOperand(0), getOperand(1), getOperand(2), getAlign(),
getSuccessOrdering(), getFailureOrdering(), getSyncScopeID());
Result->setVolatile(isVolatile());
Result->setWeak(isWeak());
return Result;
}
AtomicRMWInst *AtomicRMWInst::cloneImpl() const {
AtomicRMWInst *Result =
new AtomicRMWInst(getOperation(), getOperand(0), getOperand(1),
getAlign(), getOrdering(), getSyncScopeID());
Result->setVolatile(isVolatile());
return Result;
}
FenceInst *FenceInst::cloneImpl() const {
return new FenceInst(getContext(), getOrdering(), getSyncScopeID());
}
TruncInst *TruncInst::cloneImpl() const {
return new TruncInst(getOperand(0), getType());
}
ZExtInst *ZExtInst::cloneImpl() const {
return new ZExtInst(getOperand(0), getType());
}
SExtInst *SExtInst::cloneImpl() const {
return new SExtInst(getOperand(0), getType());
}
FPTruncInst *FPTruncInst::cloneImpl() const {
return new FPTruncInst(getOperand(0), getType());
}
FPExtInst *FPExtInst::cloneImpl() const {
return new FPExtInst(getOperand(0), getType());
}
UIToFPInst *UIToFPInst::cloneImpl() const {
return new UIToFPInst(getOperand(0), getType());
}
SIToFPInst *SIToFPInst::cloneImpl() const {
return new SIToFPInst(getOperand(0), getType());
}
FPToUIInst *FPToUIInst::cloneImpl() const {
return new FPToUIInst(getOperand(0), getType());
}
FPToSIInst *FPToSIInst::cloneImpl() const {
return new FPToSIInst(getOperand(0), getType());
}
PtrToIntInst *PtrToIntInst::cloneImpl() const {
return new PtrToIntInst(getOperand(0), getType());
}
IntToPtrInst *IntToPtrInst::cloneImpl() const {
return new IntToPtrInst(getOperand(0), getType());
}
BitCastInst *BitCastInst::cloneImpl() const {
return new BitCastInst(getOperand(0), getType());
}
AddrSpaceCastInst *AddrSpaceCastInst::cloneImpl() const {
return new AddrSpaceCastInst(getOperand(0), getType());
}
CallInst *CallInst::cloneImpl() const {
if (hasOperandBundles()) {
unsigned DescriptorBytes = getNumOperandBundles() * sizeof(BundleOpInfo);
return new(getNumOperands(), DescriptorBytes) CallInst(*this);
}
return new(getNumOperands()) CallInst(*this);
}
SelectInst *SelectInst::cloneImpl() const {
return SelectInst::Create(getOperand(0), getOperand(1), getOperand(2));
}
VAArgInst *VAArgInst::cloneImpl() const {
return new VAArgInst(getOperand(0), getType());
}
ExtractElementInst *ExtractElementInst::cloneImpl() const {
return ExtractElementInst::Create(getOperand(0), getOperand(1));
}
InsertElementInst *InsertElementInst::cloneImpl() const {
return InsertElementInst::Create(getOperand(0), getOperand(1), getOperand(2));
}
ShuffleVectorInst *ShuffleVectorInst::cloneImpl() const {
return new ShuffleVectorInst(getOperand(0), getOperand(1), getShuffleMask());
}
PHINode *PHINode::cloneImpl() const { return new PHINode(*this); }
LandingPadInst *LandingPadInst::cloneImpl() const {
return new LandingPadInst(*this);
}
ReturnInst *ReturnInst::cloneImpl() const {
return new(getNumOperands()) ReturnInst(*this);
}
BranchInst *BranchInst::cloneImpl() const {
return new(getNumOperands()) BranchInst(*this);
}
SwitchInst *SwitchInst::cloneImpl() const { return new SwitchInst(*this); }
IndirectBrInst *IndirectBrInst::cloneImpl() const {
return new IndirectBrInst(*this);
}
InvokeInst *InvokeInst::cloneImpl() const {
if (hasOperandBundles()) {
unsigned DescriptorBytes = getNumOperandBundles() * sizeof(BundleOpInfo);
return new(getNumOperands(), DescriptorBytes) InvokeInst(*this);
}
return new(getNumOperands()) InvokeInst(*this);
}
CallBrInst *CallBrInst::cloneImpl() const {
if (hasOperandBundles()) {
unsigned DescriptorBytes = getNumOperandBundles() * sizeof(BundleOpInfo);
return new (getNumOperands(), DescriptorBytes) CallBrInst(*this);
}
return new (getNumOperands()) CallBrInst(*this);
}
ResumeInst *ResumeInst::cloneImpl() const { return new (1) ResumeInst(*this); }
CleanupReturnInst *CleanupReturnInst::cloneImpl() const {
return new (getNumOperands()) CleanupReturnInst(*this);
}
CatchReturnInst *CatchReturnInst::cloneImpl() const {
return new (getNumOperands()) CatchReturnInst(*this);
}
CatchSwitchInst *CatchSwitchInst::cloneImpl() const {
return new CatchSwitchInst(*this);
}
FuncletPadInst *FuncletPadInst::cloneImpl() const {
return new (getNumOperands()) FuncletPadInst(*this);
}
UnreachableInst *UnreachableInst::cloneImpl() const {
LLVMContext &Context = getContext();
return new UnreachableInst(Context);
}
FreezeInst *FreezeInst::cloneImpl() const {
return new FreezeInst(getOperand(0));
}