#include "InstCombineInternal.h"
#include "llvm/ADT/MapVector.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/Analysis/AliasAnalysis.h"
#include "llvm/Analysis/Loads.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/DebugInfoMetadata.h"
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/PatternMatch.h"
#include "llvm/Transforms/InstCombine/InstCombiner.h"
#include "llvm/Transforms/Utils/Local.h"
using namespace llvm;
using namespace PatternMatch;
#define DEBUG_TYPE "instcombine"
STATISTIC(NumDeadStore, "Number of dead stores eliminated");
STATISTIC(NumGlobalCopies, "Number of allocas copied from constant global");
static bool
isOnlyCopiedFromConstantMemory(AAResults *AA,
Value *V, MemTransferInst *&TheCopy,
SmallVectorImpl<Instruction *> &ToDelete) {
SmallVector<std::pair<Value *, bool>, 35> ValuesToInspect;
ValuesToInspect.emplace_back(V, false);
while (!ValuesToInspect.empty()) {
auto ValuePair = ValuesToInspect.pop_back_val();
const bool IsOffset = ValuePair.second;
for (auto &U : ValuePair.first->uses()) {
auto *I = cast<Instruction>(U.getUser());
if (auto *LI = dyn_cast<LoadInst>(I)) {
if (!LI->isSimple()) return false;
continue;
}
if (isa<BitCastInst>(I) || isa<AddrSpaceCastInst>(I)) {
ValuesToInspect.emplace_back(I, IsOffset);
continue;
}
if (auto *GEP = dyn_cast<GetElementPtrInst>(I)) {
ValuesToInspect.emplace_back(I, IsOffset || !GEP->hasAllZeroIndices());
continue;
}
if (auto *Call = dyn_cast<CallBase>(I)) {
if (Call->isCallee(&U))
continue;
unsigned DataOpNo = Call->getDataOperandNo(&U);
bool IsArgOperand = Call->isArgOperand(&U);
if (IsArgOperand && Call->isInAllocaArgument(DataOpNo))
return false;
if (Call->onlyReadsMemory() &&
(Call->use_empty() || Call->doesNotCapture(DataOpNo)))
continue;
if (IsArgOperand && Call->isByValArgument(DataOpNo))
continue;
}
if (I->isLifetimeStartOrEnd()) {
assert(I->use_empty() && "Lifetime markers have no result to use!");
ToDelete.push_back(I);
continue;
}
MemTransferInst *MI = dyn_cast<MemTransferInst>(I);
if (!MI)
return false;
if (U.getOperandNo() == 1) {
if (MI->isVolatile()) return false;
continue;
}
if (TheCopy) return false;
if (IsOffset) return false;
if (U.getOperandNo() != 0) return false;
if (!AA->pointsToConstantMemory(MI->getSource()))
return false;
TheCopy = MI;
}
}
return true;
}
static MemTransferInst *
isOnlyCopiedFromConstantMemory(AAResults *AA,
AllocaInst *AI,
SmallVectorImpl<Instruction *> &ToDelete) {
MemTransferInst *TheCopy = nullptr;
if (isOnlyCopiedFromConstantMemory(AA, AI, TheCopy, ToDelete))
return TheCopy;
return nullptr;
}
static bool isDereferenceableForAllocaSize(const Value *V, const AllocaInst *AI,
const DataLayout &DL) {
if (AI->isArrayAllocation())
return false;
uint64_t AllocaSize = DL.getTypeStoreSize(AI->getAllocatedType());
if (!AllocaSize)
return false;
return isDereferenceableAndAlignedPointer(V, AI->getAlign(),
APInt(64, AllocaSize), DL);
}
static Instruction *simplifyAllocaArraySize(InstCombinerImpl &IC,
AllocaInst &AI) {
if (!AI.isArrayAllocation()) {
if (AI.getArraySize()->getType()->isIntegerTy(32))
return nullptr;
return IC.replaceOperand(AI, 0, IC.Builder.getInt32(1));
}
if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
if (C->getValue().getActiveBits() <= 64) {
Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
AllocaInst *New = IC.Builder.CreateAlloca(NewTy, AI.getAddressSpace(),
nullptr, AI.getName());
New->setAlignment(AI.getAlign());
BasicBlock::iterator It(New);
while (isa<AllocaInst>(*It) || isa<DbgInfoIntrinsic>(*It))
++It;
Type *IdxTy = IC.getDataLayout().getIntPtrType(AI.getType());
Value *NullIdx = Constant::getNullValue(IdxTy);
Value *Idx[2] = {NullIdx, NullIdx};
Instruction *GEP = GetElementPtrInst::CreateInBounds(
NewTy, New, Idx, New->getName() + ".sub");
IC.InsertNewInstBefore(GEP, *It);
return IC.replaceInstUsesWith(AI, GEP);
}
}
if (isa<UndefValue>(AI.getArraySize()))
return IC.replaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Type *IntPtrTy = IC.getDataLayout().getIntPtrType(AI.getType());
if (AI.getArraySize()->getType() != IntPtrTy) {
Value *V = IC.Builder.CreateIntCast(AI.getArraySize(), IntPtrTy, false);
return IC.replaceOperand(AI, 0, V);
}
return nullptr;
}
namespace {
class PointerReplacer {
public:
PointerReplacer(InstCombinerImpl &IC) : IC(IC) {}
bool collectUsers(Instruction &I);
void replacePointer(Instruction &I, Value *V);
private:
void replace(Instruction *I);
Value *getReplacement(Value *I);
SmallSetVector<Instruction *, 4> Worklist;
MapVector<Value *, Value *> WorkMap;
InstCombinerImpl &IC;
};
}
bool PointerReplacer::collectUsers(Instruction &I) {
for (auto U : I.users()) {
auto *Inst = cast<Instruction>(&*U);
if (auto *Load = dyn_cast<LoadInst>(Inst)) {
if (Load->isVolatile())
return false;
Worklist.insert(Load);
} else if (isa<GetElementPtrInst>(Inst) || isa<BitCastInst>(Inst)) {
Worklist.insert(Inst);
if (!collectUsers(*Inst))
return false;
} else if (auto *MI = dyn_cast<MemTransferInst>(Inst)) {
if (MI->isVolatile())
return false;
Worklist.insert(Inst);
} else if (Inst->isLifetimeStartOrEnd()) {
continue;
} else {
LLVM_DEBUG(dbgs() << "Cannot handle pointer user: " << *U << '\n');
return false;
}
}
return true;
}
Value *PointerReplacer::getReplacement(Value *V) { return WorkMap.lookup(V); }
void PointerReplacer::replace(Instruction *I) {
if (getReplacement(I))
return;
if (auto *LT = dyn_cast<LoadInst>(I)) {
auto *V = getReplacement(LT->getPointerOperand());
assert(V && "Operand not replaced");
auto *NewI = new LoadInst(LT->getType(), V, "", LT->isVolatile(),
LT->getAlign(), LT->getOrdering(),
LT->getSyncScopeID());
NewI->takeName(LT);
copyMetadataForLoad(*NewI, *LT);
IC.InsertNewInstWith(NewI, *LT);
IC.replaceInstUsesWith(*LT, NewI);
WorkMap[LT] = NewI;
} else if (auto *GEP = dyn_cast<GetElementPtrInst>(I)) {
auto *V = getReplacement(GEP->getPointerOperand());
assert(V && "Operand not replaced");
SmallVector<Value *, 8> Indices;
Indices.append(GEP->idx_begin(), GEP->idx_end());
auto *NewI =
GetElementPtrInst::Create(GEP->getSourceElementType(), V, Indices);
IC.InsertNewInstWith(NewI, *GEP);
NewI->takeName(GEP);
WorkMap[GEP] = NewI;
} else if (auto *BC = dyn_cast<BitCastInst>(I)) {
auto *V = getReplacement(BC->getOperand(0));
assert(V && "Operand not replaced");
auto *NewT = PointerType::getWithSamePointeeType(
cast<PointerType>(BC->getType()),
V->getType()->getPointerAddressSpace());
auto *NewI = new BitCastInst(V, NewT);
IC.InsertNewInstWith(NewI, *BC);
NewI->takeName(BC);
WorkMap[BC] = NewI;
} else if (auto *MemCpy = dyn_cast<MemTransferInst>(I)) {
auto *SrcV = getReplacement(MemCpy->getRawSource());
if (!SrcV) {
assert(getReplacement(MemCpy->getRawDest()) &&
"destination not in replace list");
return;
}
IC.Builder.SetInsertPoint(MemCpy);
auto *NewI = IC.Builder.CreateMemTransferInst(
MemCpy->getIntrinsicID(), MemCpy->getRawDest(), MemCpy->getDestAlign(),
SrcV, MemCpy->getSourceAlign(), MemCpy->getLength(),
MemCpy->isVolatile());
AAMDNodes AAMD = MemCpy->getAAMetadata();
if (AAMD)
NewI->setAAMetadata(AAMD);
IC.eraseInstFromFunction(*MemCpy);
WorkMap[MemCpy] = NewI;
} else {
llvm_unreachable("should never reach here");
}
}
void PointerReplacer::replacePointer(Instruction &I, Value *V) {
#ifndef NDEBUG
auto *PT = cast<PointerType>(I.getType());
auto *NT = cast<PointerType>(V->getType());
assert(PT != NT && PT->hasSameElementTypeAs(NT) && "Invalid usage");
#endif
WorkMap[&I] = V;
for (Instruction *Workitem : Worklist)
replace(Workitem);
}
Instruction *InstCombinerImpl::visitAllocaInst(AllocaInst &AI) {
if (auto *I = simplifyAllocaArraySize(*this, AI))
return I;
if (AI.getAllocatedType()->isSized()) {
if (DL.getTypeAllocSize(AI.getAllocatedType()).getKnownMinSize() == 0) {
if (AI.isArrayAllocation())
return replaceOperand(AI, 0,
ConstantInt::get(AI.getArraySize()->getType(), 1));
BasicBlock &EntryBlock = AI.getParent()->getParent()->getEntryBlock();
Instruction *FirstInst = EntryBlock.getFirstNonPHIOrDbg();
if (FirstInst != &AI) {
AllocaInst *EntryAI = dyn_cast<AllocaInst>(FirstInst);
if (!EntryAI || !EntryAI->getAllocatedType()->isSized() ||
DL.getTypeAllocSize(EntryAI->getAllocatedType())
.getKnownMinSize() != 0) {
AI.moveBefore(FirstInst);
return &AI;
}
const Align MaxAlign = std::max(EntryAI->getAlign(), AI.getAlign());
EntryAI->setAlignment(MaxAlign);
if (AI.getType() != EntryAI->getType())
return new BitCastInst(EntryAI, AI.getType());
return replaceInstUsesWith(AI, EntryAI);
}
}
}
SmallVector<Instruction *, 4> ToDelete;
if (MemTransferInst *Copy = isOnlyCopiedFromConstantMemory(AA, &AI, ToDelete)) {
Value *TheSrc = Copy->getSource();
Align AllocaAlign = AI.getAlign();
Align SourceAlign = getOrEnforceKnownAlignment(
TheSrc, AllocaAlign, DL, &AI, &AC, &DT);
if (AllocaAlign <= SourceAlign &&
isDereferenceableForAllocaSize(TheSrc, &AI, DL) &&
!isa<Instruction>(TheSrc)) {
LLVM_DEBUG(dbgs() << "Found alloca equal to global: " << AI << '\n');
LLVM_DEBUG(dbgs() << " memcpy = " << *Copy << '\n');
unsigned SrcAddrSpace = TheSrc->getType()->getPointerAddressSpace();
auto *DestTy = PointerType::get(AI.getAllocatedType(), SrcAddrSpace);
if (AI.getType()->getAddressSpace() == SrcAddrSpace) {
for (Instruction *Delete : ToDelete)
eraseInstFromFunction(*Delete);
Value *Cast = Builder.CreateBitCast(TheSrc, DestTy);
Instruction *NewI = replaceInstUsesWith(AI, Cast);
eraseInstFromFunction(*Copy);
++NumGlobalCopies;
return NewI;
}
PointerReplacer PtrReplacer(*this);
if (PtrReplacer.collectUsers(AI)) {
for (Instruction *Delete : ToDelete)
eraseInstFromFunction(*Delete);
Value *Cast = Builder.CreateBitCast(TheSrc, DestTy);
PtrReplacer.replacePointer(AI, Cast);
++NumGlobalCopies;
}
}
}
return visitAllocSite(AI);
}
static bool isSupportedAtomicType(Type *Ty) {
return Ty->isIntOrPtrTy() || Ty->isFloatingPointTy();
}
LoadInst *InstCombinerImpl::combineLoadToNewType(LoadInst &LI, Type *NewTy,
const Twine &Suffix) {
assert((!LI.isAtomic() || isSupportedAtomicType(NewTy)) &&
"can't fold an atomic load to requested type");
Value *Ptr = LI.getPointerOperand();
unsigned AS = LI.getPointerAddressSpace();
Type *NewPtrTy = NewTy->getPointerTo(AS);
Value *NewPtr = nullptr;
if (!(match(Ptr, m_BitCast(m_Value(NewPtr))) &&
NewPtr->getType() == NewPtrTy))
NewPtr = Builder.CreateBitCast(Ptr, NewPtrTy);
LoadInst *NewLoad = Builder.CreateAlignedLoad(
NewTy, NewPtr, LI.getAlign(), LI.isVolatile(), LI.getName() + Suffix);
NewLoad->setAtomic(LI.getOrdering(), LI.getSyncScopeID());
copyMetadataForLoad(*NewLoad, LI);
return NewLoad;
}
static StoreInst *combineStoreToNewValue(InstCombinerImpl &IC, StoreInst &SI,
Value *V) {
assert((!SI.isAtomic() || isSupportedAtomicType(V->getType())) &&
"can't fold an atomic store of requested type");
Value *Ptr = SI.getPointerOperand();
unsigned AS = SI.getPointerAddressSpace();
SmallVector<std::pair<unsigned, MDNode *>, 8> MD;
SI.getAllMetadata(MD);
StoreInst *NewStore = IC.Builder.CreateAlignedStore(
V, IC.Builder.CreateBitCast(Ptr, V->getType()->getPointerTo(AS)),
SI.getAlign(), SI.isVolatile());
NewStore->setAtomic(SI.getOrdering(), SI.getSyncScopeID());
for (const auto &MDPair : MD) {
unsigned ID = MDPair.first;
MDNode *N = MDPair.second;
switch (ID) {
case LLVMContext::MD_dbg:
case LLVMContext::MD_tbaa:
case LLVMContext::MD_prof:
case LLVMContext::MD_fpmath:
case LLVMContext::MD_tbaa_struct:
case LLVMContext::MD_alias_scope:
case LLVMContext::MD_noalias:
case LLVMContext::MD_nontemporal:
case LLVMContext::MD_mem_parallel_loop_access:
case LLVMContext::MD_access_group:
NewStore->setMetadata(ID, N);
break;
case LLVMContext::MD_invariant_load:
case LLVMContext::MD_nonnull:
case LLVMContext::MD_noundef:
case LLVMContext::MD_range:
case LLVMContext::MD_align:
case LLVMContext::MD_dereferenceable:
case LLVMContext::MD_dereferenceable_or_null:
break;
}
}
return NewStore;
}
static bool isMinMaxWithLoads(Value *V, Type *&LoadTy) {
assert(V->getType()->isPointerTy() && "Expected pointer type.");
V = InstCombiner::peekThroughBitcast(V);
CmpInst::Predicate Pred;
Instruction *L1;
Instruction *L2;
Value *LHS;
Value *RHS;
if (!match(V, m_Select(m_Cmp(Pred, m_Instruction(L1), m_Instruction(L2)),
m_Value(LHS), m_Value(RHS))))
return false;
LoadTy = L1->getType();
return (match(L1, m_Load(m_Specific(LHS))) &&
match(L2, m_Load(m_Specific(RHS)))) ||
(match(L1, m_Load(m_Specific(RHS))) &&
match(L2, m_Load(m_Specific(LHS))));
}
static Instruction *combineLoadToOperationType(InstCombinerImpl &IC,
LoadInst &LI) {
if (!LI.isUnordered())
return nullptr;
if (LI.use_empty())
return nullptr;
if (LI.getPointerOperand()->isSwiftError())
return nullptr;
const DataLayout &DL = IC.getDataLayout();
if (LI.hasOneUse()) {
if (auto *BC = dyn_cast<BitCastInst>(LI.user_back())) {
assert(!LI.getType()->isX86_AMXTy() &&
"load from x86_amx* should not happen!");
if (BC->getType()->isX86_AMXTy())
return nullptr;
}
if (auto* CI = dyn_cast<CastInst>(LI.user_back()))
if (CI->isNoopCast(DL) && LI.getType()->isPtrOrPtrVectorTy() ==
CI->getDestTy()->isPtrOrPtrVectorTy())
if (!LI.isAtomic() || isSupportedAtomicType(CI->getDestTy())) {
LoadInst *NewLoad = IC.combineLoadToNewType(LI, CI->getDestTy());
CI->replaceAllUsesWith(NewLoad);
IC.eraseInstFromFunction(*CI);
return &LI;
}
}
return nullptr;
}
static Instruction *unpackLoadToAggregate(InstCombinerImpl &IC, LoadInst &LI) {
if (!LI.isSimple())
return nullptr;
Type *T = LI.getType();
if (!T->isAggregateType())
return nullptr;
StringRef Name = LI.getName();
if (auto *ST = dyn_cast<StructType>(T)) {
auto NumElements = ST->getNumElements();
if (NumElements == 1) {
LoadInst *NewLoad = IC.combineLoadToNewType(LI, ST->getTypeAtIndex(0U),
".unpack");
NewLoad->setAAMetadata(LI.getAAMetadata());
return IC.replaceInstUsesWith(LI, IC.Builder.CreateInsertValue(
UndefValue::get(T), NewLoad, 0, Name));
}
const DataLayout &DL = IC.getDataLayout();
auto *SL = DL.getStructLayout(ST);
if (SL->hasPadding())
return nullptr;
const auto Align = LI.getAlign();
auto *Addr = LI.getPointerOperand();
auto *IdxType = Type::getInt32Ty(T->getContext());
auto *Zero = ConstantInt::get(IdxType, 0);
Value *V = UndefValue::get(T);
for (unsigned i = 0; i < NumElements; i++) {
Value *Indices[2] = {
Zero,
ConstantInt::get(IdxType, i),
};
auto *Ptr = IC.Builder.CreateInBoundsGEP(ST, Addr, makeArrayRef(Indices),
Name + ".elt");
auto *L = IC.Builder.CreateAlignedLoad(
ST->getElementType(i), Ptr,
commonAlignment(Align, SL->getElementOffset(i)), Name + ".unpack");
L->setAAMetadata(LI.getAAMetadata());
V = IC.Builder.CreateInsertValue(V, L, i);
}
V->setName(Name);
return IC.replaceInstUsesWith(LI, V);
}
if (auto *AT = dyn_cast<ArrayType>(T)) {
auto *ET = AT->getElementType();
auto NumElements = AT->getNumElements();
if (NumElements == 1) {
LoadInst *NewLoad = IC.combineLoadToNewType(LI, ET, ".unpack");
NewLoad->setAAMetadata(LI.getAAMetadata());
return IC.replaceInstUsesWith(LI, IC.Builder.CreateInsertValue(
UndefValue::get(T), NewLoad, 0, Name));
}
if (NumElements > IC.MaxArraySizeForCombine)
return nullptr;
const DataLayout &DL = IC.getDataLayout();
auto EltSize = DL.getTypeAllocSize(ET);
const auto Align = LI.getAlign();
auto *Addr = LI.getPointerOperand();
auto *IdxType = Type::getInt64Ty(T->getContext());
auto *Zero = ConstantInt::get(IdxType, 0);
Value *V = UndefValue::get(T);
uint64_t Offset = 0;
for (uint64_t i = 0; i < NumElements; i++) {
Value *Indices[2] = {
Zero,
ConstantInt::get(IdxType, i),
};
auto *Ptr = IC.Builder.CreateInBoundsGEP(AT, Addr, makeArrayRef(Indices),
Name + ".elt");
auto *L = IC.Builder.CreateAlignedLoad(AT->getElementType(), Ptr,
commonAlignment(Align, Offset),
Name + ".unpack");
L->setAAMetadata(LI.getAAMetadata());
V = IC.Builder.CreateInsertValue(V, L, i);
Offset += EltSize;
}
V->setName(Name);
return IC.replaceInstUsesWith(LI, V);
}
return nullptr;
}
static bool isObjectSizeLessThanOrEq(Value *V, uint64_t MaxSize,
const DataLayout &DL) {
SmallPtrSet<Value *, 4> Visited;
SmallVector<Value *, 4> Worklist(1, V);
do {
Value *P = Worklist.pop_back_val();
P = P->stripPointerCasts();
if (!Visited.insert(P).second)
continue;
if (SelectInst *SI = dyn_cast<SelectInst>(P)) {
Worklist.push_back(SI->getTrueValue());
Worklist.push_back(SI->getFalseValue());
continue;
}
if (PHINode *PN = dyn_cast<PHINode>(P)) {
append_range(Worklist, PN->incoming_values());
continue;
}
if (GlobalAlias *GA = dyn_cast<GlobalAlias>(P)) {
if (GA->isInterposable())
return false;
Worklist.push_back(GA->getAliasee());
continue;
}
if (AllocaInst *AI = dyn_cast<AllocaInst>(P)) {
if (!AI->getAllocatedType()->isSized())
return false;
ConstantInt *CS = dyn_cast<ConstantInt>(AI->getArraySize());
if (!CS)
return false;
uint64_t TypeSize = DL.getTypeAllocSize(AI->getAllocatedType());
if ((CS->getValue().zext(128) * APInt(128, TypeSize)).ugt(MaxSize))
return false;
continue;
}
if (GlobalVariable *GV = dyn_cast<GlobalVariable>(P)) {
if (!GV->hasDefinitiveInitializer() || !GV->isConstant())
return false;
uint64_t InitSize = DL.getTypeAllocSize(GV->getValueType());
if (InitSize > MaxSize)
return false;
continue;
}
return false;
} while (!Worklist.empty());
return true;
}
static bool canReplaceGEPIdxWithZero(InstCombinerImpl &IC,
GetElementPtrInst *GEPI, Instruction *MemI,
unsigned &Idx) {
if (GEPI->getNumOperands() < 2)
return false;
auto FirstNZIdx = [](const GetElementPtrInst *GEPI) {
unsigned I = 1;
for (unsigned IE = GEPI->getNumOperands(); I != IE; ++I) {
Value *V = GEPI->getOperand(I);
if (const ConstantInt *CI = dyn_cast<ConstantInt>(V))
if (CI->isZero())
continue;
break;
}
return I;
};
Idx = FirstNZIdx(GEPI);
if (Idx == GEPI->getNumOperands())
return false;
if (isa<Constant>(GEPI->getOperand(Idx)))
return false;
SmallVector<Value *, 4> Ops(GEPI->idx_begin(), GEPI->idx_begin() + Idx);
Type *SourceElementType = GEPI->getSourceElementType();
if (isa<ScalableVectorType>(SourceElementType))
return false;
Type *AllocTy = GetElementPtrInst::getIndexedType(SourceElementType, Ops);
if (!AllocTy || !AllocTy->isSized())
return false;
const DataLayout &DL = IC.getDataLayout();
uint64_t TyAllocSize = DL.getTypeAllocSize(AllocTy).getFixedSize();
auto IsAllNonNegative = [&]() {
for (unsigned i = Idx+1, e = GEPI->getNumOperands(); i != e; ++i) {
KnownBits Known = IC.computeKnownBits(GEPI->getOperand(i), 0, MemI);
if (Known.isNonNegative())
continue;
return false;
}
return true;
};
if (Idx+1 != GEPI->getNumOperands() && !GEPI->isInBounds())
return false;
return isObjectSizeLessThanOrEq(GEPI->getOperand(0), TyAllocSize, DL) &&
IsAllNonNegative();
}
template <typename T>
static Instruction *replaceGEPIdxWithZero(InstCombinerImpl &IC, Value *Ptr,
T &MemI) {
if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Ptr)) {
unsigned Idx;
if (canReplaceGEPIdxWithZero(IC, GEPI, &MemI, Idx)) {
Instruction *NewGEPI = GEPI->clone();
NewGEPI->setOperand(Idx,
ConstantInt::get(GEPI->getOperand(Idx)->getType(), 0));
NewGEPI->insertBefore(GEPI);
MemI.setOperand(MemI.getPointerOperandIndex(), NewGEPI);
return NewGEPI;
}
}
return nullptr;
}
static bool canSimplifyNullStoreOrGEP(StoreInst &SI) {
if (NullPointerIsDefined(SI.getFunction(), SI.getPointerAddressSpace()))
return false;
auto *Ptr = SI.getPointerOperand();
if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Ptr))
Ptr = GEPI->getOperand(0);
return (isa<ConstantPointerNull>(Ptr) &&
!NullPointerIsDefined(SI.getFunction(), SI.getPointerAddressSpace()));
}
static bool canSimplifyNullLoadOrGEP(LoadInst &LI, Value *Op) {
if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
const Value *GEPI0 = GEPI->getOperand(0);
if (isa<ConstantPointerNull>(GEPI0) &&
!NullPointerIsDefined(LI.getFunction(), GEPI->getPointerAddressSpace()))
return true;
}
if (isa<UndefValue>(Op) ||
(isa<ConstantPointerNull>(Op) &&
!NullPointerIsDefined(LI.getFunction(), LI.getPointerAddressSpace())))
return true;
return false;
}
Instruction *InstCombinerImpl::visitLoadInst(LoadInst &LI) {
Value *Op = LI.getOperand(0);
if (Instruction *Res = combineLoadToOperationType(*this, LI))
return Res;
Align KnownAlign = getOrEnforceKnownAlignment(
Op, DL.getPrefTypeAlign(LI.getType()), DL, &LI, &AC, &DT);
if (KnownAlign > LI.getAlign())
LI.setAlignment(KnownAlign);
if (Instruction *NewGEPI = replaceGEPIdxWithZero(*this, Op, LI)) {
Worklist.push(NewGEPI);
return &LI;
}
if (Instruction *Res = unpackLoadToAggregate(*this, LI))
return Res;
bool IsLoadCSE = false;
if (Value *AvailableVal = FindAvailableLoadedValue(&LI, *AA, &IsLoadCSE)) {
if (IsLoadCSE)
combineMetadataForCSE(cast<LoadInst>(AvailableVal), &LI, false);
return replaceInstUsesWith(
LI, Builder.CreateBitOrPointerCast(AvailableVal, LI.getType(),
LI.getName() + ".cast"));
}
if (!LI.isUnordered()) return nullptr;
if (canSimplifyNullLoadOrGEP(LI, Op)) {
StoreInst *SI = new StoreInst(PoisonValue::get(LI.getType()),
Constant::getNullValue(Op->getType()), &LI);
SI->setDebugLoc(LI.getDebugLoc());
return replaceInstUsesWith(LI, PoisonValue::get(LI.getType()));
}
if (Op->hasOneUse()) {
if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
Align Alignment = LI.getAlign();
if (isSafeToLoadUnconditionally(SI->getOperand(1), LI.getType(),
Alignment, DL, SI) &&
isSafeToLoadUnconditionally(SI->getOperand(2), LI.getType(),
Alignment, DL, SI)) {
LoadInst *V1 =
Builder.CreateLoad(LI.getType(), SI->getOperand(1),
SI->getOperand(1)->getName() + ".val");
LoadInst *V2 =
Builder.CreateLoad(LI.getType(), SI->getOperand(2),
SI->getOperand(2)->getName() + ".val");
assert(LI.isUnordered() && "implied by above");
V1->setAlignment(Alignment);
V1->setAtomic(LI.getOrdering(), LI.getSyncScopeID());
V2->setAlignment(Alignment);
V2->setAtomic(LI.getOrdering(), LI.getSyncScopeID());
return SelectInst::Create(SI->getCondition(), V1, V2);
}
if (isa<ConstantPointerNull>(SI->getOperand(1)) &&
!NullPointerIsDefined(SI->getFunction(),
LI.getPointerAddressSpace()))
return replaceOperand(LI, 0, SI->getOperand(2));
if (isa<ConstantPointerNull>(SI->getOperand(2)) &&
!NullPointerIsDefined(SI->getFunction(),
LI.getPointerAddressSpace()))
return replaceOperand(LI, 0, SI->getOperand(1));
}
}
return nullptr;
}
static Value *likeBitCastFromVector(InstCombinerImpl &IC, Value *V) {
Value *U = nullptr;
while (auto *IV = dyn_cast<InsertValueInst>(V)) {
auto *E = dyn_cast<ExtractElementInst>(IV->getInsertedValueOperand());
if (!E)
return nullptr;
auto *W = E->getVectorOperand();
if (!U)
U = W;
else if (U != W)
return nullptr;
auto *CI = dyn_cast<ConstantInt>(E->getIndexOperand());
if (!CI || IV->getNumIndices() != 1 || CI->getZExtValue() != *IV->idx_begin())
return nullptr;
V = IV->getAggregateOperand();
}
if (!match(V, m_Undef()) || !U)
return nullptr;
auto *UT = cast<VectorType>(U->getType());
auto *VT = V->getType();
const auto &DL = IC.getDataLayout();
if (DL.getTypeStoreSizeInBits(UT) != DL.getTypeStoreSizeInBits(VT)) {
return nullptr;
}
if (auto *AT = dyn_cast<ArrayType>(VT)) {
if (AT->getNumElements() != cast<FixedVectorType>(UT)->getNumElements())
return nullptr;
} else {
auto *ST = cast<StructType>(VT);
if (ST->getNumElements() != cast<FixedVectorType>(UT)->getNumElements())
return nullptr;
for (const auto *EltT : ST->elements()) {
if (EltT != UT->getElementType())
return nullptr;
}
}
return U;
}
static bool combineStoreToValueType(InstCombinerImpl &IC, StoreInst &SI) {
if (!SI.isUnordered())
return false;
if (SI.getPointerOperand()->isSwiftError())
return false;
Value *V = SI.getValueOperand();
if (auto *BC = dyn_cast<BitCastInst>(V)) {
assert(!BC->getType()->isX86_AMXTy() &&
"store to x86_amx* should not happen!");
V = BC->getOperand(0);
if (V->getType()->isX86_AMXTy())
return false;
if (!SI.isAtomic() || isSupportedAtomicType(V->getType())) {
combineStoreToNewValue(IC, SI, V);
return true;
}
}
if (Value *U = likeBitCastFromVector(IC, V))
if (!SI.isAtomic() || isSupportedAtomicType(U->getType())) {
combineStoreToNewValue(IC, SI, U);
return true;
}
return false;
}
static bool unpackStoreToAggregate(InstCombinerImpl &IC, StoreInst &SI) {
if (!SI.isSimple())
return false;
Value *V = SI.getValueOperand();
Type *T = V->getType();
if (!T->isAggregateType())
return false;
if (auto *ST = dyn_cast<StructType>(T)) {
unsigned Count = ST->getNumElements();
if (Count == 1) {
V = IC.Builder.CreateExtractValue(V, 0);
combineStoreToNewValue(IC, SI, V);
return true;
}
const DataLayout &DL = IC.getDataLayout();
auto *SL = DL.getStructLayout(ST);
if (SL->hasPadding())
return false;
const auto Align = SI.getAlign();
SmallString<16> EltName = V->getName();
EltName += ".elt";
auto *Addr = SI.getPointerOperand();
SmallString<16> AddrName = Addr->getName();
AddrName += ".repack";
auto *IdxType = Type::getInt32Ty(ST->getContext());
auto *Zero = ConstantInt::get(IdxType, 0);
for (unsigned i = 0; i < Count; i++) {
Value *Indices[2] = {
Zero,
ConstantInt::get(IdxType, i),
};
auto *Ptr = IC.Builder.CreateInBoundsGEP(ST, Addr, makeArrayRef(Indices),
AddrName);
auto *Val = IC.Builder.CreateExtractValue(V, i, EltName);
auto EltAlign = commonAlignment(Align, SL->getElementOffset(i));
llvm::Instruction *NS = IC.Builder.CreateAlignedStore(Val, Ptr, EltAlign);
NS->setAAMetadata(SI.getAAMetadata());
}
return true;
}
if (auto *AT = dyn_cast<ArrayType>(T)) {
auto NumElements = AT->getNumElements();
if (NumElements == 1) {
V = IC.Builder.CreateExtractValue(V, 0);
combineStoreToNewValue(IC, SI, V);
return true;
}
if (NumElements > IC.MaxArraySizeForCombine)
return false;
const DataLayout &DL = IC.getDataLayout();
auto EltSize = DL.getTypeAllocSize(AT->getElementType());
const auto Align = SI.getAlign();
SmallString<16> EltName = V->getName();
EltName += ".elt";
auto *Addr = SI.getPointerOperand();
SmallString<16> AddrName = Addr->getName();
AddrName += ".repack";
auto *IdxType = Type::getInt64Ty(T->getContext());
auto *Zero = ConstantInt::get(IdxType, 0);
uint64_t Offset = 0;
for (uint64_t i = 0; i < NumElements; i++) {
Value *Indices[2] = {
Zero,
ConstantInt::get(IdxType, i),
};
auto *Ptr = IC.Builder.CreateInBoundsGEP(AT, Addr, makeArrayRef(Indices),
AddrName);
auto *Val = IC.Builder.CreateExtractValue(V, i, EltName);
auto EltAlign = commonAlignment(Align, Offset);
Instruction *NS = IC.Builder.CreateAlignedStore(Val, Ptr, EltAlign);
NS->setAAMetadata(SI.getAAMetadata());
Offset += EltSize;
}
return true;
}
return false;
}
static bool equivalentAddressValues(Value *A, Value *B) {
if (A == B) return true;
if (isa<BinaryOperator>(A) ||
isa<CastInst>(A) ||
isa<PHINode>(A) ||
isa<GetElementPtrInst>(A))
if (Instruction *BI = dyn_cast<Instruction>(B))
if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
return true;
return false;
}
static bool removeBitcastsFromLoadStoreOnMinMax(InstCombinerImpl &IC,
StoreInst &SI) {
if (!match(SI.getPointerOperand(), m_BitCast(m_Value())))
return false;
Value *LoadAddr;
if (!match(SI.getValueOperand(), m_Load(m_BitCast(m_Value(LoadAddr)))))
return false;
auto *LI = cast<LoadInst>(SI.getValueOperand());
if (!LI->getType()->isIntegerTy())
return false;
Type *CmpLoadTy;
if (!isMinMaxWithLoads(LoadAddr, CmpLoadTy))
return false;
if (LI->getType() == CmpLoadTy)
return false;
const auto &DL = IC.getDataLayout();
if (DL.getTypeStoreSizeInBits(LI->getType()) !=
DL.getTypeStoreSizeInBits(CmpLoadTy))
return false;
if (!all_of(LI->users(), [LI, LoadAddr](User *U) {
auto *SI = dyn_cast<StoreInst>(U);
return SI && SI->getPointerOperand() != LI &&
InstCombiner::peekThroughBitcast(SI->getPointerOperand()) !=
LoadAddr &&
!SI->getPointerOperand()->isSwiftError();
}))
return false;
IC.Builder.SetInsertPoint(LI);
LoadInst *NewLI = IC.combineLoadToNewType(*LI, CmpLoadTy);
for (auto *UI : LI->users()) {
auto *USI = cast<StoreInst>(UI);
IC.Builder.SetInsertPoint(USI);
combineStoreToNewValue(IC, *USI, NewLI);
}
IC.replaceInstUsesWith(*LI, PoisonValue::get(LI->getType()));
IC.eraseInstFromFunction(*LI);
return true;
}
Instruction *InstCombinerImpl::visitStoreInst(StoreInst &SI) {
Value *Val = SI.getOperand(0);
Value *Ptr = SI.getOperand(1);
if (combineStoreToValueType(*this, SI))
return eraseInstFromFunction(SI);
const Align KnownAlign = getOrEnforceKnownAlignment(
Ptr, DL.getPrefTypeAlign(Val->getType()), DL, &SI, &AC, &DT);
if (KnownAlign > SI.getAlign())
SI.setAlignment(KnownAlign);
if (unpackStoreToAggregate(*this, SI))
return eraseInstFromFunction(SI);
if (removeBitcastsFromLoadStoreOnMinMax(*this, SI))
return eraseInstFromFunction(SI);
if (Instruction *NewGEPI = replaceGEPIdxWithZero(*this, Ptr, SI)) {
Worklist.push(NewGEPI);
return &SI;
}
if (!SI.isUnordered()) return nullptr;
if (Ptr->hasOneUse()) {
if (isa<AllocaInst>(Ptr))
return eraseInstFromFunction(SI);
if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
if (isa<AllocaInst>(GEP->getOperand(0))) {
if (GEP->getOperand(0)->hasOneUse())
return eraseInstFromFunction(SI);
}
}
}
if (AA->pointsToConstantMemory(Ptr))
return eraseInstFromFunction(SI);
BasicBlock::iterator BBI(SI);
for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
--ScanInsts) {
--BBI;
if (BBI->isDebugOrPseudoInst() ||
(isa<BitCastInst>(BBI) && BBI->getType()->isPointerTy())) {
ScanInsts++;
continue;
}
if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
if (PrevSI->isUnordered() &&
equivalentAddressValues(PrevSI->getOperand(1), SI.getOperand(1)) &&
PrevSI->getValueOperand()->getType() ==
SI.getValueOperand()->getType()) {
++NumDeadStore;
Worklist.push(&SI);
eraseInstFromFunction(*PrevSI);
return nullptr;
}
break;
}
if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr)) {
assert(SI.isUnordered() && "can't eliminate ordering operation");
return eraseInstFromFunction(SI);
}
break;
}
if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory() || BBI->mayThrow())
break;
}
if (canSimplifyNullStoreOrGEP(SI)) {
if (!isa<PoisonValue>(Val))
return replaceOperand(SI, 0, PoisonValue::get(Val->getType()));
return nullptr; }
if (isa<UndefValue>(Val))
return eraseInstFromFunction(SI);
return nullptr;
}
bool InstCombinerImpl::mergeStoreIntoSuccessor(StoreInst &SI) {
if (!SI.isUnordered())
return false;
BasicBlock *StoreBB = SI.getParent();
BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
if (!DestBB->hasNPredecessors(2))
return false;
pred_iterator PredIter = pred_begin(DestBB);
if (*PredIter == StoreBB)
++PredIter;
BasicBlock *OtherBB = *PredIter;
if (StoreBB == DestBB || OtherBB == DestBB)
return false;
BasicBlock::iterator BBI(OtherBB->getTerminator());
BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
if (!OtherBr || BBI == OtherBB->begin())
return false;
StoreInst *OtherStore = nullptr;
if (OtherBr->isUnconditional()) {
--BBI;
while (BBI->isDebugOrPseudoInst() ||
(isa<BitCastInst>(BBI) && BBI->getType()->isPointerTy())) {
if (BBI==OtherBB->begin())
return false;
--BBI;
}
OtherStore = dyn_cast<StoreInst>(BBI);
if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1) ||
!SI.isSameOperationAs(OtherStore))
return false;
} else {
if (OtherBr->getSuccessor(0) != StoreBB &&
OtherBr->getSuccessor(1) != StoreBB)
return false;
for (;; --BBI) {
if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
if (OtherStore->getOperand(1) != SI.getOperand(1) ||
!SI.isSameOperationAs(OtherStore))
return false;
break;
}
if (BBI->mayReadFromMemory() || BBI->mayThrow() ||
BBI->mayWriteToMemory() || BBI == OtherBB->begin())
return false;
}
for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
if (I->mayReadFromMemory() || I->mayThrow() || I->mayWriteToMemory())
return false;
}
}
Value *MergedVal = OtherStore->getOperand(0);
DebugLoc MergedLoc = DILocation::getMergedLocation(SI.getDebugLoc(),
OtherStore->getDebugLoc());
if (MergedVal != SI.getOperand(0)) {
PHINode *PN = PHINode::Create(MergedVal->getType(), 2, "storemerge");
PN->addIncoming(SI.getOperand(0), SI.getParent());
PN->addIncoming(OtherStore->getOperand(0), OtherBB);
MergedVal = InsertNewInstBefore(PN, DestBB->front());
PN->setDebugLoc(MergedLoc);
}
BBI = DestBB->getFirstInsertionPt();
StoreInst *NewSI =
new StoreInst(MergedVal, SI.getOperand(1), SI.isVolatile(), SI.getAlign(),
SI.getOrdering(), SI.getSyncScopeID());
InsertNewInstBefore(NewSI, *BBI);
NewSI->setDebugLoc(MergedLoc);
AAMDNodes AATags = SI.getAAMetadata();
if (AATags)
NewSI->setAAMetadata(AATags.merge(OtherStore->getAAMetadata()));
eraseInstFromFunction(SI);
eraseInstFromFunction(*OtherStore);
return true;
}