#define DEBUG_TYPE "sroa"
#include "llvm/Transforms/Scalar.h"
#include "llvm/Constants.h"
#include "llvm/DIBuilder.h"
#include "llvm/DebugInfo.h"
#include "llvm/DerivedTypes.h"
#include "llvm/Function.h"
#include "llvm/IRBuilder.h"
#include "llvm/Instructions.h"
#include "llvm/IntrinsicInst.h"
#include "llvm/LLVMContext.h"
#include "llvm/Module.h"
#include "llvm/Operator.h"
#include "llvm/Pass.h"
#include "llvm/ADT/SetVector.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/Analysis/Dominators.h"
#include "llvm/Analysis/Loads.h"
#include "llvm/Analysis/ValueTracking.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/GetElementPtrTypeIterator.h"
#include "llvm/Support/InstVisitor.h"
#include "llvm/Support/MathExtras.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Target/TargetData.h"
#include "llvm/Transforms/Utils/Local.h"
#include "llvm/Transforms/Utils/PromoteMemToReg.h"
#include "llvm/Transforms/Utils/SSAUpdater.h"
using namespace llvm;
STATISTIC(NumAllocasAnalyzed, "Number of allocas analyzed for replacement");
STATISTIC(NumNewAllocas, "Number of new, smaller allocas introduced");
STATISTIC(NumPromoted, "Number of allocas promoted to SSA values");
STATISTIC(NumLoadsSpeculated, "Number of loads speculated to allow promotion");
STATISTIC(NumDeleted, "Number of instructions deleted");
STATISTIC(NumVectorized, "Number of vectorized aggregates");
static cl::opt<bool>
ForceSSAUpdater("force-ssa-updater", cl::init(false), cl::Hidden);
namespace {
class AllocaPartitioning {
public:
struct ByteRange {
uint64_t BeginOffset;
uint64_t EndOffset;
ByteRange() : BeginOffset(), EndOffset() {}
ByteRange(uint64_t BeginOffset, uint64_t EndOffset)
: BeginOffset(BeginOffset), EndOffset(EndOffset) {}
bool operator<(const ByteRange &RHS) const {
if (BeginOffset < RHS.BeginOffset) return true;
if (BeginOffset > RHS.BeginOffset) return false;
if (EndOffset > RHS.EndOffset) return true;
return false;
}
friend bool operator<(const ByteRange &LHS, uint64_t RHSOffset) {
return LHS.BeginOffset < RHSOffset;
}
friend LLVM_ATTRIBUTE_UNUSED bool operator<(uint64_t LHSOffset,
const ByteRange &RHS) {
return LHSOffset < RHS.BeginOffset;
}
bool operator==(const ByteRange &RHS) const {
return BeginOffset == RHS.BeginOffset && EndOffset == RHS.EndOffset;
}
bool operator!=(const ByteRange &RHS) const { return !operator==(RHS); }
};
struct Partition : public ByteRange {
bool IsSplittable;
Partition() : ByteRange(), IsSplittable() {}
Partition(uint64_t BeginOffset, uint64_t EndOffset, bool IsSplittable)
: ByteRange(BeginOffset, EndOffset), IsSplittable(IsSplittable) {}
};
struct PartitionUse : public ByteRange {
Use* U;
PartitionUse() : ByteRange(), U() {}
PartitionUse(uint64_t BeginOffset, uint64_t EndOffset, Use *U)
: ByteRange(BeginOffset, EndOffset), U(U) {}
};
AllocaPartitioning(const TargetData &TD, AllocaInst &AI);
bool isEscaped() const { return PointerEscapingInstr; }
typedef SmallVectorImpl<Partition>::iterator iterator;
iterator begin() { return Partitions.begin(); }
iterator end() { return Partitions.end(); }
typedef SmallVectorImpl<Partition>::const_iterator const_iterator;
const_iterator begin() const { return Partitions.begin(); }
const_iterator end() const { return Partitions.end(); }
typedef SmallVectorImpl<PartitionUse>::iterator use_iterator;
use_iterator use_begin(unsigned Idx) { return Uses[Idx].begin(); }
use_iterator use_begin(const_iterator I) { return Uses[I - begin()].begin(); }
use_iterator use_end(unsigned Idx) { return Uses[Idx].end(); }
use_iterator use_end(const_iterator I) { return Uses[I - begin()].end(); }
void use_push_back(unsigned Idx, const PartitionUse &PU) {
Uses[Idx].push_back(PU);
}
void use_push_back(const_iterator I, const PartitionUse &PU) {
Uses[I - begin()].push_back(PU);
}
void use_erase(unsigned Idx, use_iterator UI) { Uses[Idx].erase(UI); }
void use_erase(const_iterator I, use_iterator UI) {
Uses[I - begin()].erase(UI);
}
typedef SmallVectorImpl<PartitionUse>::const_iterator const_use_iterator;
const_use_iterator use_begin(unsigned Idx) const { return Uses[Idx].begin(); }
const_use_iterator use_begin(const_iterator I) const {
return Uses[I - begin()].begin();
}
const_use_iterator use_end(unsigned Idx) const { return Uses[Idx].end(); }
const_use_iterator use_end(const_iterator I) const {
return Uses[I - begin()].end();
}
typedef SmallVectorImpl<Instruction *>::const_iterator dead_user_iterator;
dead_user_iterator dead_user_begin() const { return DeadUsers.begin(); }
dead_user_iterator dead_user_end() const { return DeadUsers.end(); }
typedef SmallVectorImpl<Use *>::const_iterator dead_op_iterator;
dead_op_iterator dead_op_begin() const { return DeadOperands.begin(); }
dead_op_iterator dead_op_end() const { return DeadOperands.end(); }
struct MemTransferOffsets {
uint64_t DestBegin, DestEnd;
uint64_t SourceBegin, SourceEnd;
bool IsSplittable;
};
MemTransferOffsets getMemTransferOffsets(MemTransferInst &II) const {
return MemTransferInstData.lookup(&II);
}
iterator findPartitionForPHIOrSelectOperand(Use *U) {
SmallDenseMap<Use *, std::pair<unsigned, unsigned> >::const_iterator MapIt
= PHIOrSelectOpMap.find(U);
if (MapIt == PHIOrSelectOpMap.end())
return end();
return begin() + MapIt->second.first;
}
use_iterator findPartitionUseForPHIOrSelectOperand(Use *U) {
SmallDenseMap<Use *, std::pair<unsigned, unsigned> >::const_iterator MapIt
= PHIOrSelectOpMap.find(U);
assert(MapIt != PHIOrSelectOpMap.end());
return Uses[MapIt->second.first].begin() + MapIt->second.second;
}
Type *getCommonType(iterator I) const;
#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
void print(raw_ostream &OS, const_iterator I, StringRef Indent = " ") const;
void printUsers(raw_ostream &OS, const_iterator I,
StringRef Indent = " ") const;
void print(raw_ostream &OS) const;
void LLVM_ATTRIBUTE_NOINLINE LLVM_ATTRIBUTE_USED dump(const_iterator I) const;
void LLVM_ATTRIBUTE_NOINLINE LLVM_ATTRIBUTE_USED dump() const;
#endif
private:
template <typename DerivedT, typename RetT = void> class BuilderBase;
class PartitionBuilder;
friend class AllocaPartitioning::PartitionBuilder;
class UseBuilder;
friend class AllocaPartitioning::UseBuilder;
#ifndef NDEBUG
AllocaInst &AI;
#endif
Instruction *PointerEscapingInstr;
SmallVector<Partition, 8> Partitions;
SmallVector<SmallVector<PartitionUse, 2>, 8> Uses;
SmallVector<Instruction *, 8> DeadUsers;
SmallVector<Use *, 8> DeadOperands;
SmallDenseMap<MemTransferInst *, MemTransferOffsets, 4> MemTransferInstData;
SmallDenseMap<Instruction *, std::pair<uint64_t, bool> > PHIOrSelectSizes;
SmallDenseMap<Use *, std::pair<unsigned, unsigned>, 4> PHIOrSelectOpMap;
void splitAndMergePartitions();
};
}
template <typename DerivedT, typename RetT>
class AllocaPartitioning::BuilderBase
: public InstVisitor<DerivedT, RetT> {
public:
BuilderBase(const TargetData &TD, AllocaInst &AI, AllocaPartitioning &P)
: TD(TD),
AllocSize(TD.getTypeAllocSize(AI.getAllocatedType())),
P(P) {
enqueueUsers(AI, 0);
}
protected:
const TargetData &TD;
const uint64_t AllocSize;
AllocaPartitioning &P;
SmallPtrSet<Use *, 8> VisitedUses;
struct OffsetUse {
Use *U;
int64_t Offset;
};
SmallVector<OffsetUse, 8> Queue;
Use *U;
int64_t Offset;
void enqueueUsers(Instruction &I, int64_t UserOffset) {
for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
UI != UE; ++UI) {
if (VisitedUses.insert(&UI.getUse())) {
OffsetUse OU = { &UI.getUse(), UserOffset };
Queue.push_back(OU);
}
}
}
bool computeConstantGEPOffset(GetElementPtrInst &GEPI, int64_t &GEPOffset) {
GEPOffset = Offset;
for (gep_type_iterator GTI = gep_type_begin(GEPI), GTE = gep_type_end(GEPI);
GTI != GTE; ++GTI) {
ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand());
if (!OpC)
return false;
if (OpC->isZero())
continue;
if (StructType *STy = dyn_cast<StructType>(*GTI)) {
unsigned ElementIdx = OpC->getZExtValue();
const StructLayout *SL = TD.getStructLayout(STy);
uint64_t ElementOffset = SL->getElementOffset(ElementIdx);
if (ElementOffset > INT64_MAX ||
(GEPOffset >= 0 &&
((uint64_t)GEPOffset + ElementOffset) > INT64_MAX)) {
DEBUG(dbgs() << "WARNING: Encountered a cumulative offset exceeding "
<< "what can be represented in an int64_t!\n"
<< " alloca: " << P.AI << "\n");
return false;
}
if (GEPOffset < 0)
GEPOffset = ElementOffset + (uint64_t)-GEPOffset;
else
GEPOffset += ElementOffset;
continue;
}
APInt Index = OpC->getValue().sextOrTrunc(TD.getPointerSizeInBits());
Index *= APInt(Index.getBitWidth(),
TD.getTypeAllocSize(GTI.getIndexedType()));
Index += APInt(Index.getBitWidth(), (uint64_t)GEPOffset,
true);
if (!Index.isSignedIntN(sizeof(GEPOffset) * 8)) {
DEBUG(dbgs() << "WARNING: Encountered a cumulative offset exceeding "
<< "what can be represented in an int64_t!\n"
<< " alloca: " << P.AI << "\n");
return false;
}
GEPOffset = Index.getSExtValue();
}
return true;
}
Value *foldSelectInst(SelectInst &SI) {
if (ConstantInt *CI = dyn_cast<ConstantInt>(SI.getCondition()))
return SI.getOperand(1+CI->isZero());
if (SI.getOperand(1) == SI.getOperand(2)) {
assert(*U == SI.getOperand(1));
return SI.getOperand(1);
}
return 0;
}
};
class AllocaPartitioning::PartitionBuilder
: public BuilderBase<PartitionBuilder, bool> {
friend class InstVisitor<PartitionBuilder, bool>;
SmallDenseMap<Instruction *, unsigned> MemTransferPartitionMap;
public:
PartitionBuilder(const TargetData &TD, AllocaInst &AI, AllocaPartitioning &P)
: BuilderBase<PartitionBuilder, bool>(TD, AI, P) {}
bool operator()() {
for (unsigned Idx = 0; Idx < Queue.size(); ++Idx) {
U = Queue[Idx].U;
Offset = Queue[Idx].Offset;
if (!visit(cast<Instruction>(U->getUser())))
return false;
}
return true;
}
private:
bool markAsEscaping(Instruction &I) {
P.PointerEscapingInstr = &I;
return false;
}
void insertUse(Instruction &I, int64_t Offset, uint64_t Size,
bool IsSplittable = false) {
if (Size == 0 ||
(Offset >= 0 && (uint64_t)Offset >= AllocSize) ||
(Offset < 0 && (uint64_t)-Offset >= Size)) {
DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte use @" << Offset
<< " which starts past the end of the " << AllocSize
<< " byte alloca:\n"
<< " alloca: " << P.AI << "\n"
<< " use: " << I << "\n");
return;
}
if (Offset < 0) {
DEBUG(dbgs() << "WARNING: Clamping a " << Size << " byte use @" << Offset
<< " to start at the beginning of the alloca:\n"
<< " alloca: " << P.AI << "\n"
<< " use: " << I << "\n");
Size -= (uint64_t)-Offset;
Offset = 0;
}
uint64_t BeginOffset = Offset, EndOffset = BeginOffset + Size;
assert(AllocSize >= BeginOffset); if (Size > AllocSize - BeginOffset) {
DEBUG(dbgs() << "WARNING: Clamping a " << Size << " byte use @" << Offset
<< " to remain within the " << AllocSize << " byte alloca:\n"
<< " alloca: " << P.AI << "\n"
<< " use: " << I << "\n");
EndOffset = AllocSize;
}
if (!P.Partitions.empty() &&
P.Partitions.back().BeginOffset == BeginOffset &&
P.Partitions.back().EndOffset == EndOffset) {
P.Partitions.back().IsSplittable &= IsSplittable;
return;
}
Partition New(BeginOffset, EndOffset, IsSplittable);
P.Partitions.push_back(New);
}
bool handleLoadOrStore(Type *Ty, Instruction &I, int64_t Offset) {
uint64_t Size = TD.getTypeStoreSize(Ty);
if (Offset < 0 || (uint64_t)Offset >= AllocSize ||
Size > (AllocSize - (uint64_t)Offset)) {
DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte "
<< (isa<LoadInst>(I) ? "load" : "store") << " @" << Offset
<< " which extends past the end of the " << AllocSize
<< " byte alloca:\n"
<< " alloca: " << P.AI << "\n"
<< " use: " << I << "\n");
return true;
}
insertUse(I, Offset, Size);
return true;
}
bool visitBitCastInst(BitCastInst &BC) {
enqueueUsers(BC, Offset);
return true;
}
bool visitGetElementPtrInst(GetElementPtrInst &GEPI) {
int64_t GEPOffset;
if (!computeConstantGEPOffset(GEPI, GEPOffset))
return markAsEscaping(GEPI);
enqueueUsers(GEPI, GEPOffset);
return true;
}
bool visitLoadInst(LoadInst &LI) {
assert((!LI.isSimple() || LI.getType()->isSingleValueType()) &&
"All simple FCA loads should have been pre-split");
return handleLoadOrStore(LI.getType(), LI, Offset);
}
bool visitStoreInst(StoreInst &SI) {
Value *ValOp = SI.getValueOperand();
if (ValOp == *U)
return markAsEscaping(SI);
assert((!SI.isSimple() || ValOp->getType()->isSingleValueType()) &&
"All simple FCA stores should have been pre-split");
return handleLoadOrStore(ValOp->getType(), SI, Offset);
}
bool visitMemSetInst(MemSetInst &II) {
assert(II.getRawDest() == *U && "Pointer use is not the destination?");
ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
uint64_t Size = Length ? Length->getZExtValue() : AllocSize - Offset;
insertUse(II, Offset, Size, Length);
return true;
}
bool visitMemTransferInst(MemTransferInst &II) {
ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
uint64_t Size = Length ? Length->getZExtValue() : AllocSize - Offset;
if (!Size)
return true;
MemTransferOffsets &Offsets = P.MemTransferInstData[&II];
Offsets.IsSplittable = Length;
if (*U != II.getRawDest()) {
assert(*U == II.getRawSource());
Offsets.SourceBegin = Offset;
Offsets.SourceEnd = Offset + Size;
} else {
Offsets.DestBegin = Offset;
Offsets.DestEnd = Offset + Size;
}
insertUse(II, Offset, Size, Offsets.IsSplittable);
unsigned NewIdx = P.Partitions.size() - 1;
SmallDenseMap<Instruction *, unsigned>::const_iterator PMI;
bool Inserted = false;
llvm::tie(PMI, Inserted)
= MemTransferPartitionMap.insert(std::make_pair(&II, NewIdx));
if (Offsets.IsSplittable &&
(!Inserted || II.getRawSource() == II.getRawDest())) {
Offsets.IsSplittable = false;
P.Partitions[PMI->second].IsSplittable = false;
P.Partitions[NewIdx].IsSplittable = false;
}
return true;
}
bool visitIntrinsicInst(IntrinsicInst &II) {
if (II.getIntrinsicID() == Intrinsic::lifetime_start ||
II.getIntrinsicID() == Intrinsic::lifetime_end) {
ConstantInt *Length = cast<ConstantInt>(II.getArgOperand(0));
uint64_t Size = std::min(AllocSize - Offset, Length->getLimitedValue());
insertUse(II, Offset, Size, true);
return true;
}
return markAsEscaping(II);
}
Instruction *hasUnsafePHIOrSelectUse(Instruction *Root, uint64_t &Size) {
SmallPtrSet<Instruction *, 4> Visited;
SmallVector<std::pair<Instruction *, Instruction *>, 4> Uses;
Visited.insert(Root);
Uses.push_back(std::make_pair(cast<Instruction>(*U), Root));
Size = 0;
do {
Instruction *I, *UsedI;
llvm::tie(UsedI, I) = Uses.pop_back_val();
if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Size = std::max(Size, TD.getTypeStoreSize(LI->getType()));
continue;
}
if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Value *Op = SI->getOperand(0);
if (Op == UsedI)
return SI;
Size = std::max(Size, TD.getTypeStoreSize(Op->getType()));
continue;
}
if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) {
if (!GEP->hasAllZeroIndices())
return GEP;
} else if (!isa<BitCastInst>(I) && !isa<PHINode>(I) &&
!isa<SelectInst>(I)) {
return I;
}
for (Value::use_iterator UI = I->use_begin(), UE = I->use_end(); UI != UE;
++UI)
if (Visited.insert(cast<Instruction>(*UI)))
Uses.push_back(std::make_pair(I, cast<Instruction>(*UI)));
} while (!Uses.empty());
return 0;
}
bool visitPHINode(PHINode &PN) {
std::pair<uint64_t, bool> &PHIInfo = P.PHIOrSelectSizes[&PN];
if (PHIInfo.first) {
PHIInfo.second = true;
insertUse(PN, Offset, PHIInfo.first);
return true;
}
if (Instruction *EscapingI = hasUnsafePHIOrSelectUse(&PN, PHIInfo.first))
return markAsEscaping(*EscapingI);
insertUse(PN, Offset, PHIInfo.first);
return true;
}
bool visitSelectInst(SelectInst &SI) {
if (Value *Result = foldSelectInst(SI)) {
if (Result == *U)
enqueueUsers(SI, Offset);
return true;
}
std::pair<uint64_t, bool> &SelectInfo = P.PHIOrSelectSizes[&SI];
if (SelectInfo.first) {
SelectInfo.second = true;
insertUse(SI, Offset, SelectInfo.first);
return true;
}
if (Instruction *EscapingI = hasUnsafePHIOrSelectUse(&SI, SelectInfo.first))
return markAsEscaping(*EscapingI);
insertUse(SI, Offset, SelectInfo.first);
return true;
}
bool visitInstruction(Instruction &I) { return markAsEscaping(I); }
};
class AllocaPartitioning::UseBuilder : public BuilderBase<UseBuilder> {
friend class InstVisitor<UseBuilder>;
SmallPtrSet<Instruction *, 4> VisitedDeadInsts;
public:
UseBuilder(const TargetData &TD, AllocaInst &AI, AllocaPartitioning &P)
: BuilderBase<UseBuilder>(TD, AI, P) {}
void operator()() {
for (unsigned Idx = 0; Idx < Queue.size(); ++Idx) {
U = Queue[Idx].U;
Offset = Queue[Idx].Offset;
this->visit(cast<Instruction>(U->getUser()));
}
}
private:
void markAsDead(Instruction &I) {
if (VisitedDeadInsts.insert(&I))
P.DeadUsers.push_back(&I);
}
void insertUse(Instruction &User, int64_t Offset, uint64_t Size) {
if (Size == 0 || (uint64_t)Offset >= AllocSize ||
(Offset < 0 && (uint64_t)-Offset >= Size))
return markAsDead(User);
if (Offset < 0) {
Size -= (uint64_t)-Offset;
Offset = 0;
}
uint64_t BeginOffset = Offset, EndOffset = BeginOffset + Size;
assert(AllocSize >= BeginOffset); if (Size > AllocSize - BeginOffset)
EndOffset = AllocSize;
iterator B = std::lower_bound(P.begin(), P.end(), BeginOffset);
if (B != P.begin() && llvm::prior(B)->EndOffset > BeginOffset)
B = llvm::prior(B);
for (iterator I = B, E = P.end(); I != E && I->BeginOffset < EndOffset;
++I) {
PartitionUse NewPU(std::max(I->BeginOffset, BeginOffset),
std::min(I->EndOffset, EndOffset), U);
P.use_push_back(I, NewPU);
if (isa<PHINode>(U->getUser()) || isa<SelectInst>(U->getUser()))
P.PHIOrSelectOpMap[U]
= std::make_pair(I - P.begin(), P.Uses[I - P.begin()].size() - 1);
}
}
void handleLoadOrStore(Type *Ty, Instruction &I, int64_t Offset) {
uint64_t Size = TD.getTypeStoreSize(Ty);
if (Offset < 0 || (uint64_t)Offset >= AllocSize ||
Size > (AllocSize - (uint64_t)Offset))
return markAsDead(I);
insertUse(I, Offset, Size);
}
void visitBitCastInst(BitCastInst &BC) {
if (BC.use_empty())
return markAsDead(BC);
enqueueUsers(BC, Offset);
}
void visitGetElementPtrInst(GetElementPtrInst &GEPI) {
if (GEPI.use_empty())
return markAsDead(GEPI);
int64_t GEPOffset;
if (!computeConstantGEPOffset(GEPI, GEPOffset))
llvm_unreachable("Unable to compute constant offset for use");
enqueueUsers(GEPI, GEPOffset);
}
void visitLoadInst(LoadInst &LI) {
handleLoadOrStore(LI.getType(), LI, Offset);
}
void visitStoreInst(StoreInst &SI) {
handleLoadOrStore(SI.getOperand(0)->getType(), SI, Offset);
}
void visitMemSetInst(MemSetInst &II) {
ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
uint64_t Size = Length ? Length->getZExtValue() : AllocSize - Offset;
insertUse(II, Offset, Size);
}
void visitMemTransferInst(MemTransferInst &II) {
ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
uint64_t Size = Length ? Length->getZExtValue() : AllocSize - Offset;
insertUse(II, Offset, Size);
}
void visitIntrinsicInst(IntrinsicInst &II) {
assert(II.getIntrinsicID() == Intrinsic::lifetime_start ||
II.getIntrinsicID() == Intrinsic::lifetime_end);
ConstantInt *Length = cast<ConstantInt>(II.getArgOperand(0));
insertUse(II, Offset,
std::min(AllocSize - Offset, Length->getLimitedValue()));
}
void insertPHIOrSelect(Instruction &User, uint64_t Offset) {
uint64_t Size = P.PHIOrSelectSizes.lookup(&User).first;
if (Offset >= AllocSize) {
P.DeadOperands.push_back(U);
return;
}
insertUse(User, Offset, Size);
}
void visitPHINode(PHINode &PN) {
if (PN.use_empty())
return markAsDead(PN);
insertPHIOrSelect(PN, Offset);
}
void visitSelectInst(SelectInst &SI) {
if (SI.use_empty())
return markAsDead(SI);
if (Value *Result = foldSelectInst(SI)) {
if (Result == *U)
enqueueUsers(SI, Offset);
else
P.DeadOperands.push_back(U);
return;
}
insertPHIOrSelect(SI, Offset);
}
void visitInstruction(Instruction &I) {
llvm_unreachable("Unhandled instruction in use builder.");
}
};
void AllocaPartitioning::splitAndMergePartitions() {
size_t NumDeadPartitions = 0;
uint64_t SplitEndOffset = 0ull;
Partition New(0ull, 0ull, false);
for (unsigned i = 0, j = i, e = Partitions.size(); i != e; i = j) {
++j;
if (!Partitions[i].IsSplittable || New.BeginOffset == New.EndOffset) {
assert(New.BeginOffset == New.EndOffset);
New = Partitions[i];
} else {
assert(New.IsSplittable);
New.EndOffset = std::max(New.EndOffset, Partitions[i].EndOffset);
}
assert(New.BeginOffset != New.EndOffset);
while (j != e && New.EndOffset > Partitions[j].BeginOffset) {
if (New.IsSplittable && !Partitions[j].IsSplittable)
break;
if (New.IsSplittable == Partitions[j].IsSplittable) {
New.EndOffset = std::max(New.EndOffset, Partitions[j].EndOffset);
} else {
assert(!New.IsSplittable);
assert(Partitions[j].IsSplittable);
SplitEndOffset = std::max(SplitEndOffset, Partitions[j].EndOffset);
}
Partitions[j].BeginOffset = Partitions[j].EndOffset = UINT64_MAX;
++NumDeadPartitions;
++j;
}
if (j != e && New.IsSplittable) {
SplitEndOffset = std::max(SplitEndOffset, New.EndOffset);
New.EndOffset = std::min(New.EndOffset, Partitions[j].BeginOffset);
}
if (New != Partitions[i]) {
if (New.BeginOffset != New.EndOffset)
Partitions.push_back(New);
Partitions[i].BeginOffset = Partitions[i].EndOffset = UINT64_MAX;
++NumDeadPartitions;
}
New.BeginOffset = New.EndOffset;
if (!New.IsSplittable) {
New.EndOffset = std::max(New.EndOffset, SplitEndOffset);
if (j != e && !Partitions[j].IsSplittable)
New.EndOffset = std::min(New.EndOffset, Partitions[j].BeginOffset);
New.IsSplittable = true;
if (New.BeginOffset < New.EndOffset &&
(j == e || !Partitions[j].IsSplittable ||
New.EndOffset < Partitions[j].BeginOffset)) {
Partitions.push_back(New);
New.BeginOffset = New.EndOffset = 0ull;
}
}
}
std::sort(Partitions.begin(), Partitions.end());
if (NumDeadPartitions) {
assert(Partitions.back().BeginOffset == UINT64_MAX);
assert(Partitions.back().EndOffset == UINT64_MAX);
assert((ptrdiff_t)NumDeadPartitions ==
std::count(Partitions.begin(), Partitions.end(), Partitions.back()));
}
Partitions.erase(Partitions.end() - NumDeadPartitions, Partitions.end());
}
AllocaPartitioning::AllocaPartitioning(const TargetData &TD, AllocaInst &AI)
:
#ifndef NDEBUG
AI(AI),
#endif
PointerEscapingInstr(0) {
PartitionBuilder PB(TD, AI, *this);
if (!PB())
return;
if (Partitions.size() > 1) {
std::sort(Partitions.begin(), Partitions.end());
for (iterator I = Partitions.begin(), J = I, E = Partitions.end(); I != E;
I = J) {
++J;
while (J != E && *I == *J) {
I->IsSplittable &= J->IsSplittable;
++J;
}
}
Partitions.erase(std::unique(Partitions.begin(), Partitions.end()),
Partitions.end());
splitAndMergePartitions();
}
Uses.resize(Partitions.size());
UseBuilder UB(TD, AI, *this);
UB();
}
Type *AllocaPartitioning::getCommonType(iterator I) const {
Type *Ty = 0;
for (const_use_iterator UI = use_begin(I), UE = use_end(I); UI != UE; ++UI) {
if (isa<IntrinsicInst>(*UI->U->getUser()))
continue;
if (UI->BeginOffset != I->BeginOffset || UI->EndOffset != I->EndOffset)
continue;
Type *UserTy = 0;
if (LoadInst *LI = dyn_cast<LoadInst>(UI->U->getUser())) {
UserTy = LI->getType();
} else if (StoreInst *SI = dyn_cast<StoreInst>(UI->U->getUser())) {
UserTy = SI->getValueOperand()->getType();
}
if (Ty && Ty != UserTy)
return 0;
Ty = UserTy;
}
return Ty;
}
#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
void AllocaPartitioning::print(raw_ostream &OS, const_iterator I,
StringRef Indent) const {
OS << Indent << "partition #" << (I - begin())
<< " [" << I->BeginOffset << "," << I->EndOffset << ")"
<< (I->IsSplittable ? " (splittable)" : "")
<< (Uses[I - begin()].empty() ? " (zero uses)" : "")
<< "\n";
}
void AllocaPartitioning::printUsers(raw_ostream &OS, const_iterator I,
StringRef Indent) const {
for (const_use_iterator UI = use_begin(I), UE = use_end(I);
UI != UE; ++UI) {
OS << Indent << " [" << UI->BeginOffset << "," << UI->EndOffset << ") "
<< "used by: " << *UI->U->getUser() << "\n";
if (MemTransferInst *II = dyn_cast<MemTransferInst>(UI->U->getUser())) {
const MemTransferOffsets &MTO = MemTransferInstData.lookup(II);
bool IsDest;
if (!MTO.IsSplittable)
IsDest = UI->BeginOffset == MTO.DestBegin;
else
IsDest = MTO.DestBegin != 0u;
OS << Indent << " (original " << (IsDest ? "dest" : "source") << ": "
<< "[" << (IsDest ? MTO.DestBegin : MTO.SourceBegin)
<< "," << (IsDest ? MTO.DestEnd : MTO.SourceEnd) << ")\n";
}
}
}
void AllocaPartitioning::print(raw_ostream &OS) const {
if (PointerEscapingInstr) {
OS << "No partitioning for alloca: " << AI << "\n"
<< " A pointer to this alloca escaped by:\n"
<< " " << *PointerEscapingInstr << "\n";
return;
}
OS << "Partitioning of alloca: " << AI << "\n";
unsigned Num = 0;
for (const_iterator I = begin(), E = end(); I != E; ++I, ++Num) {
print(OS, I);
printUsers(OS, I);
}
}
void AllocaPartitioning::dump(const_iterator I) const { print(dbgs(), I); }
void AllocaPartitioning::dump() const { print(dbgs()); }
#endif // !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
namespace {
class AllocaPromoter : public LoadAndStorePromoter {
AllocaInst &AI;
DIBuilder &DIB;
SmallVector<DbgDeclareInst *, 4> DDIs;
SmallVector<DbgValueInst *, 4> DVIs;
public:
AllocaPromoter(const SmallVectorImpl<Instruction*> &Insts, SSAUpdater &S,
AllocaInst &AI, DIBuilder &DIB)
: LoadAndStorePromoter(Insts, S), AI(AI), DIB(DIB) {}
void run(const SmallVectorImpl<Instruction*> &Insts) {
if (MDNode *DebugNode = MDNode::getIfExists(AI.getContext(), &AI)) {
for (Value::use_iterator UI = DebugNode->use_begin(),
UE = DebugNode->use_end();
UI != UE; ++UI)
if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(*UI))
DDIs.push_back(DDI);
else if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(*UI))
DVIs.push_back(DVI);
}
LoadAndStorePromoter::run(Insts);
AI.eraseFromParent();
while (!DDIs.empty())
DDIs.pop_back_val()->eraseFromParent();
while (!DVIs.empty())
DVIs.pop_back_val()->eraseFromParent();
}
virtual bool isInstInList(Instruction *I,
const SmallVectorImpl<Instruction*> &Insts) const {
if (LoadInst *LI = dyn_cast<LoadInst>(I))
return LI->getOperand(0) == &AI;
return cast<StoreInst>(I)->getPointerOperand() == &AI;
}
virtual void updateDebugInfo(Instruction *Inst) const {
for (SmallVector<DbgDeclareInst *, 4>::const_iterator I = DDIs.begin(),
E = DDIs.end(); I != E; ++I) {
DbgDeclareInst *DDI = *I;
if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
ConvertDebugDeclareToDebugValue(DDI, SI, DIB);
else if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
ConvertDebugDeclareToDebugValue(DDI, LI, DIB);
}
for (SmallVector<DbgValueInst *, 4>::const_iterator I = DVIs.begin(),
E = DVIs.end(); I != E; ++I) {
DbgValueInst *DVI = *I;
Value *Arg = NULL;
if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
if (ZExtInst *ZExt = dyn_cast<ZExtInst>(SI->getOperand(0)))
Arg = dyn_cast<Argument>(ZExt->getOperand(0));
if (SExtInst *SExt = dyn_cast<SExtInst>(SI->getOperand(0)))
Arg = dyn_cast<Argument>(SExt->getOperand(0));
if (!Arg)
Arg = SI->getOperand(0);
} else if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
Arg = LI->getOperand(0);
} else {
continue;
}
Instruction *DbgVal =
DIB.insertDbgValueIntrinsic(Arg, 0, DIVariable(DVI->getVariable()),
Inst);
DbgVal->setDebugLoc(DVI->getDebugLoc());
}
}
};
}
namespace {
class SROA : public FunctionPass {
const bool RequiresDomTree;
LLVMContext *C;
const TargetData *TD;
DominatorTree *DT;
SetVector<AllocaInst *, SmallVector<AllocaInst *, 16> > Worklist;
SmallVector<Instruction *, 8> DeadInsts;
SmallPtrSet<Instruction *, 4> DeadSplitInsts;
std::vector<AllocaInst *> PromotableAllocas;
public:
SROA(bool RequiresDomTree = true)
: FunctionPass(ID), RequiresDomTree(RequiresDomTree),
C(0), TD(0), DT(0) {
initializeSROAPass(*PassRegistry::getPassRegistry());
}
bool runOnFunction(Function &F);
void getAnalysisUsage(AnalysisUsage &AU) const;
const char *getPassName() const { return "SROA"; }
static char ID;
private:
friend class PHIOrSelectSpeculator;
friend class AllocaPartitionRewriter;
friend class AllocaPartitionVectorRewriter;
bool rewriteAllocaPartition(AllocaInst &AI,
AllocaPartitioning &P,
AllocaPartitioning::iterator PI);
bool splitAlloca(AllocaInst &AI, AllocaPartitioning &P);
bool runOnAlloca(AllocaInst &AI);
void deleteDeadInstructions(SmallPtrSet<AllocaInst *, 4> &DeletedAllocas);
bool promoteAllocas(Function &F);
};
}
char SROA::ID = 0;
FunctionPass *llvm::createSROAPass(bool RequiresDomTree) {
return new SROA(RequiresDomTree);
}
INITIALIZE_PASS_BEGIN(SROA, "sroa", "Scalar Replacement Of Aggregates",
false, false)
INITIALIZE_PASS_DEPENDENCY(DominatorTree)
INITIALIZE_PASS_END(SROA, "sroa", "Scalar Replacement Of Aggregates",
false, false)
static bool accumulateGEPOffsets(const TargetData &TD, GEPOperator &GEP,
APInt &Offset) {
APInt GEPOffset(Offset.getBitWidth(), 0);
for (gep_type_iterator GTI = gep_type_begin(GEP), GTE = gep_type_end(GEP);
GTI != GTE; ++GTI) {
ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand());
if (!OpC)
return false;
if (OpC->isZero()) continue;
if (StructType *STy = dyn_cast<StructType>(*GTI)) {
unsigned ElementIdx = OpC->getZExtValue();
const StructLayout *SL = TD.getStructLayout(STy);
GEPOffset += APInt(Offset.getBitWidth(),
SL->getElementOffset(ElementIdx));
continue;
}
APInt TypeSize(Offset.getBitWidth(),
TD.getTypeAllocSize(GTI.getIndexedType()));
if (VectorType *VTy = dyn_cast<VectorType>(*GTI)) {
assert((VTy->getScalarSizeInBits() % 8) == 0 &&
"vector element size is not a multiple of 8, cannot GEP over it");
TypeSize = VTy->getScalarSizeInBits() / 8;
}
GEPOffset += OpC->getValue().sextOrTrunc(Offset.getBitWidth()) * TypeSize;
}
Offset = GEPOffset;
return true;
}
static Value *buildGEP(IRBuilder<> &IRB, Value *BasePtr,
SmallVectorImpl<Value *> &Indices,
const Twine &Prefix) {
if (Indices.empty())
return BasePtr;
if (Indices.size() == 1 && cast<ConstantInt>(Indices.back())->isZero())
return BasePtr;
return IRB.CreateInBoundsGEP(BasePtr, Indices, Prefix + ".idx");
}
static Value *getNaturalGEPWithType(IRBuilder<> &IRB, const TargetData &TD,
Value *BasePtr, Type *Ty, Type *TargetTy,
SmallVectorImpl<Value *> &Indices,
const Twine &Prefix) {
if (Ty == TargetTy)
return buildGEP(IRB, BasePtr, Indices, Prefix);
unsigned NumLayers = 0;
Type *ElementTy = Ty;
do {
if (ElementTy->isPointerTy())
break;
if (SequentialType *SeqTy = dyn_cast<SequentialType>(ElementTy)) {
ElementTy = SeqTy->getElementType();
Indices.push_back(IRB.getInt(APInt(TD.getPointerSizeInBits(), 0)));
} else if (StructType *STy = dyn_cast<StructType>(ElementTy)) {
ElementTy = *STy->element_begin();
Indices.push_back(IRB.getInt32(0));
} else {
break;
}
++NumLayers;
} while (ElementTy != TargetTy);
if (ElementTy != TargetTy)
Indices.erase(Indices.end() - NumLayers, Indices.end());
return buildGEP(IRB, BasePtr, Indices, Prefix);
}
static Value *getNaturalGEPRecursively(IRBuilder<> &IRB, const TargetData &TD,
Value *Ptr, Type *Ty, APInt &Offset,
Type *TargetTy,
SmallVectorImpl<Value *> &Indices,
const Twine &Prefix) {
if (Offset == 0)
return getNaturalGEPWithType(IRB, TD, Ptr, Ty, TargetTy, Indices, Prefix);
if (Ty->isPointerTy())
return 0;
if (VectorType *VecTy = dyn_cast<VectorType>(Ty)) {
unsigned ElementSizeInBits = VecTy->getScalarSizeInBits();
if (ElementSizeInBits % 8)
return 0; APInt ElementSize(Offset.getBitWidth(), ElementSizeInBits / 8);
APInt NumSkippedElements = Offset.udiv(ElementSize);
if (NumSkippedElements.ugt(VecTy->getNumElements()))
return 0;
Offset -= NumSkippedElements * ElementSize;
Indices.push_back(IRB.getInt(NumSkippedElements));
return getNaturalGEPRecursively(IRB, TD, Ptr, VecTy->getElementType(),
Offset, TargetTy, Indices, Prefix);
}
if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
Type *ElementTy = ArrTy->getElementType();
APInt ElementSize(Offset.getBitWidth(), TD.getTypeAllocSize(ElementTy));
APInt NumSkippedElements = Offset.udiv(ElementSize);
if (NumSkippedElements.ugt(ArrTy->getNumElements()))
return 0;
Offset -= NumSkippedElements * ElementSize;
Indices.push_back(IRB.getInt(NumSkippedElements));
return getNaturalGEPRecursively(IRB, TD, Ptr, ElementTy, Offset, TargetTy,
Indices, Prefix);
}
StructType *STy = dyn_cast<StructType>(Ty);
if (!STy)
return 0;
const StructLayout *SL = TD.getStructLayout(STy);
uint64_t StructOffset = Offset.getZExtValue();
if (StructOffset >= SL->getSizeInBytes())
return 0;
unsigned Index = SL->getElementContainingOffset(StructOffset);
Offset -= APInt(Offset.getBitWidth(), SL->getElementOffset(Index));
Type *ElementTy = STy->getElementType(Index);
if (Offset.uge(TD.getTypeAllocSize(ElementTy)))
return 0;
Indices.push_back(IRB.getInt32(Index));
return getNaturalGEPRecursively(IRB, TD, Ptr, ElementTy, Offset, TargetTy,
Indices, Prefix);
}
static Value *getNaturalGEPWithOffset(IRBuilder<> &IRB, const TargetData &TD,
Value *Ptr, APInt Offset, Type *TargetTy,
SmallVectorImpl<Value *> &Indices,
const Twine &Prefix) {
PointerType *Ty = cast<PointerType>(Ptr->getType());
if (Ty == IRB.getInt8PtrTy() && TargetTy->isIntegerTy(8))
return 0;
Type *ElementTy = Ty->getElementType();
if (!ElementTy->isSized())
return 0; APInt ElementSize(Offset.getBitWidth(), TD.getTypeAllocSize(ElementTy));
if (ElementSize == 0)
return 0; APInt NumSkippedElements = Offset.udiv(ElementSize);
Offset -= NumSkippedElements * ElementSize;
Indices.push_back(IRB.getInt(NumSkippedElements));
return getNaturalGEPRecursively(IRB, TD, Ptr, ElementTy, Offset, TargetTy,
Indices, Prefix);
}
static Value *getAdjustedPtr(IRBuilder<> &IRB, const TargetData &TD,
Value *Ptr, APInt Offset, Type *PointerTy,
const Twine &Prefix) {
SmallPtrSet<Value *, 4> Visited;
Visited.insert(Ptr);
SmallVector<Value *, 4> Indices;
Value *OffsetPtr = 0;
Value *Int8Ptr = 0;
APInt Int8PtrOffset(Offset.getBitWidth(), 0);
Type *TargetTy = PointerTy->getPointerElementType();
do {
while (GEPOperator *GEP = dyn_cast<GEPOperator>(Ptr)) {
APInt GEPOffset(Offset.getBitWidth(), 0);
if (!accumulateGEPOffsets(TD, *GEP, GEPOffset))
break;
Offset += GEPOffset;
Ptr = GEP->getPointerOperand();
if (!Visited.insert(Ptr))
break;
}
Indices.clear();
if (Value *P = getNaturalGEPWithOffset(IRB, TD, Ptr, Offset, TargetTy,
Indices, Prefix)) {
if (P->getType() == PointerTy) {
if (OffsetPtr && OffsetPtr->use_empty())
if (Instruction *I = dyn_cast<Instruction>(OffsetPtr))
I->eraseFromParent();
return P;
}
if (!OffsetPtr) {
OffsetPtr = P;
}
}
if (Ptr->getType()->isIntegerTy(8)) {
Int8Ptr = Ptr;
Int8PtrOffset = Offset;
}
if (Operator::getOpcode(Ptr) == Instruction::BitCast) {
Ptr = cast<Operator>(Ptr)->getOperand(0);
} else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(Ptr)) {
if (GA->mayBeOverridden())
break;
Ptr = GA->getAliasee();
} else {
break;
}
assert(Ptr->getType()->isPointerTy() && "Unexpected operand type!");
} while (Visited.insert(Ptr));
if (!OffsetPtr) {
if (!Int8Ptr) {
Int8Ptr = IRB.CreateBitCast(Ptr, IRB.getInt8PtrTy(),
Prefix + ".raw_cast");
Int8PtrOffset = Offset;
}
OffsetPtr = Int8PtrOffset == 0 ? Int8Ptr :
IRB.CreateInBoundsGEP(Int8Ptr, IRB.getInt(Int8PtrOffset),
Prefix + ".raw_idx");
}
Ptr = OffsetPtr;
if (Ptr->getType() != PointerTy)
Ptr = IRB.CreateBitCast(Ptr, PointerTy, Prefix + ".cast");
return Ptr;
}
static bool isVectorPromotionViable(const TargetData &TD,
Type *AllocaTy,
AllocaPartitioning &P,
uint64_t PartitionBeginOffset,
uint64_t PartitionEndOffset,
AllocaPartitioning::const_use_iterator I,
AllocaPartitioning::const_use_iterator E) {
VectorType *Ty = dyn_cast<VectorType>(AllocaTy);
if (!Ty)
return false;
uint64_t VecSize = TD.getTypeSizeInBits(Ty);
uint64_t ElementSize = Ty->getScalarSizeInBits();
if (ElementSize % 8)
return false;
assert((VecSize % 8) == 0 && "vector size not a multiple of element size?");
VecSize /= 8;
ElementSize /= 8;
for (; I != E; ++I) {
uint64_t BeginOffset = I->BeginOffset - PartitionBeginOffset;
uint64_t BeginIndex = BeginOffset / ElementSize;
if (BeginIndex * ElementSize != BeginOffset ||
BeginIndex >= Ty->getNumElements())
return false;
uint64_t EndOffset = I->EndOffset - PartitionBeginOffset;
uint64_t EndIndex = EndOffset / ElementSize;
if (EndIndex * ElementSize != EndOffset ||
EndIndex > Ty->getNumElements())
return false;
if ((EndOffset - BeginOffset) != ElementSize &&
(EndOffset - BeginOffset) != VecSize)
return false;
if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I->U->getUser())) {
if (MI->isVolatile())
return false;
if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(I->U->getUser())) {
const AllocaPartitioning::MemTransferOffsets &MTO
= P.getMemTransferOffsets(*MTI);
if (!MTO.IsSplittable)
return false;
}
} else if (I->U->get()->getType()->getPointerElementType()->isStructTy()) {
return false;
} else if (!isa<LoadInst>(I->U->getUser()) &&
!isa<StoreInst>(I->U->getUser())) {
return false;
}
}
return true;
}
static bool isIntegerPromotionViable(const TargetData &TD,
Type *AllocaTy,
AllocaPartitioning &P,
AllocaPartitioning::const_use_iterator I,
AllocaPartitioning::const_use_iterator E) {
IntegerType *Ty = dyn_cast<IntegerType>(AllocaTy);
if (!Ty)
return false;
bool WholeAllocaOp = false;
for (; I != E; ++I) {
if (LoadInst *LI = dyn_cast<LoadInst>(I->U->getUser())) {
if (LI->isVolatile() || !LI->getType()->isIntegerTy())
return false;
if (LI->getType() == Ty)
WholeAllocaOp = true;
} else if (StoreInst *SI = dyn_cast<StoreInst>(I->U->getUser())) {
if (SI->isVolatile() || !SI->getValueOperand()->getType()->isIntegerTy())
return false;
if (SI->getValueOperand()->getType() == Ty)
WholeAllocaOp = true;
} else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I->U->getUser())) {
if (MI->isVolatile())
return false;
if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(I->U->getUser())) {
const AllocaPartitioning::MemTransferOffsets &MTO
= P.getMemTransferOffsets(*MTI);
if (!MTO.IsSplittable)
return false;
}
} else {
return false;
}
}
return WholeAllocaOp;
}
namespace {
class PHIOrSelectSpeculator : public InstVisitor<PHIOrSelectSpeculator> {
friend class llvm::InstVisitor<PHIOrSelectSpeculator>;
const TargetData &TD;
AllocaPartitioning &P;
SROA &Pass;
public:
PHIOrSelectSpeculator(const TargetData &TD, AllocaPartitioning &P, SROA &Pass)
: TD(TD), P(P), Pass(Pass) {}
void visitUsers(AllocaPartitioning::const_use_iterator I,
AllocaPartitioning::const_use_iterator E) {
for (; I != E; ++I)
visit(cast<Instruction>(I->U->getUser()));
}
private:
void visitInstruction(Instruction &I) {}
bool isSafePHIToSpeculate(PHINode &PN, SmallVectorImpl<LoadInst *> &Loads) {
BasicBlock *BB = PN.getParent();
unsigned MaxAlign = 0;
for (Value::use_iterator UI = PN.use_begin(), UE = PN.use_end();
UI != UE; ++UI) {
LoadInst *LI = dyn_cast<LoadInst>(*UI);
if (LI == 0 || !LI->isSimple()) return false;
if (LI->getParent() != BB) return false;
for (BasicBlock::iterator BBI = &PN; &*BBI != LI; ++BBI)
if (BBI->mayWriteToMemory())
return false;
MaxAlign = std::max(MaxAlign, LI->getAlignment());
Loads.push_back(LI);
}
for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num;
++Idx) {
TerminatorInst *TI = PN.getIncomingBlock(Idx)->getTerminator();
Value *InVal = PN.getIncomingValue(Idx);
if (TI == InVal || TI->mayHaveSideEffects())
return false;
if (TI->getNumSuccessors() == 1)
continue;
if (InVal->isDereferenceablePointer() ||
isSafeToLoadUnconditionally(InVal, TI, MaxAlign, &TD))
continue;
return false;
}
return true;
}
void visitPHINode(PHINode &PN) {
DEBUG(dbgs() << " original: " << PN << "\n");
SmallVector<LoadInst *, 4> Loads;
if (!isSafePHIToSpeculate(PN, Loads))
return;
assert(!Loads.empty());
Type *LoadTy = cast<PointerType>(PN.getType())->getElementType();
IRBuilder<> PHIBuilder(&PN);
PHINode *NewPN = PHIBuilder.CreatePHI(LoadTy, PN.getNumIncomingValues(),
PN.getName() + ".sroa.speculated");
LoadInst *SomeLoad = cast<LoadInst>(Loads.back());
MDNode *TBAATag = SomeLoad->getMetadata(LLVMContext::MD_tbaa);
unsigned Align = SomeLoad->getAlignment();
do {
LoadInst *LI = Loads.pop_back_val();
LI->replaceAllUsesWith(NewPN);
Pass.DeadInsts.push_back(LI);
} while (!Loads.empty());
for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) {
BasicBlock *Pred = PN.getIncomingBlock(Idx);
TerminatorInst *TI = Pred->getTerminator();
Use *InUse = &PN.getOperandUse(PN.getOperandNumForIncomingValue(Idx));
Value *InVal = PN.getIncomingValue(Idx);
IRBuilder<> PredBuilder(TI);
LoadInst *Load
= PredBuilder.CreateLoad(InVal, (PN.getName() + ".sroa.speculate.load." +
Pred->getName()));
++NumLoadsSpeculated;
Load->setAlignment(Align);
if (TBAATag)
Load->setMetadata(LLVMContext::MD_tbaa, TBAATag);
NewPN->addIncoming(Load, Pred);
Instruction *Ptr = dyn_cast<Instruction>(InVal);
if (!Ptr)
continue;
AllocaPartitioning::iterator PI
= P.findPartitionForPHIOrSelectOperand(InUse);
if (PI == P.end())
continue;
AllocaPartitioning::use_iterator UI
= P.findPartitionUseForPHIOrSelectOperand(InUse);
assert(isa<PHINode>(*UI->U->getUser()));
UI->U = &Load->getOperandUse(Load->getPointerOperandIndex());
}
DEBUG(dbgs() << " speculated to: " << *NewPN << "\n");
}
bool isSafeSelectToSpeculate(SelectInst &SI,
SmallVectorImpl<LoadInst *> &Loads) {
Value *TValue = SI.getTrueValue();
Value *FValue = SI.getFalseValue();
bool TDerefable = TValue->isDereferenceablePointer();
bool FDerefable = FValue->isDereferenceablePointer();
for (Value::use_iterator UI = SI.use_begin(), UE = SI.use_end();
UI != UE; ++UI) {
LoadInst *LI = dyn_cast<LoadInst>(*UI);
if (LI == 0 || !LI->isSimple()) return false;
if (!TDerefable && !isSafeToLoadUnconditionally(TValue, LI,
LI->getAlignment(), &TD))
return false;
if (!FDerefable && !isSafeToLoadUnconditionally(FValue, LI,
LI->getAlignment(), &TD))
return false;
Loads.push_back(LI);
}
return true;
}
void visitSelectInst(SelectInst &SI) {
DEBUG(dbgs() << " original: " << SI << "\n");
IRBuilder<> IRB(&SI);
SmallVector<LoadInst *, 4> Loads;
if (!isSafeSelectToSpeculate(SI, Loads))
return;
Use *Ops[2] = { &SI.getOperandUse(1), &SI.getOperandUse(2) };
AllocaPartitioning::iterator PIs[2];
AllocaPartitioning::PartitionUse PUs[2];
for (unsigned i = 0, e = 2; i != e; ++i) {
PIs[i] = P.findPartitionForPHIOrSelectOperand(Ops[i]);
if (PIs[i] != P.end()) {
AllocaPartitioning::use_iterator UI
= P.findPartitionUseForPHIOrSelectOperand(Ops[i]);
PUs[i] = *UI;
P.use_erase(PIs[i], UI);
}
}
Value *TV = SI.getTrueValue();
Value *FV = SI.getFalseValue();
while (!Loads.empty()) {
LoadInst *LI = Loads.pop_back_val();
IRB.SetInsertPoint(LI);
LoadInst *TL =
IRB.CreateLoad(TV, LI->getName() + ".sroa.speculate.load.true");
LoadInst *FL =
IRB.CreateLoad(FV, LI->getName() + ".sroa.speculate.load.false");
NumLoadsSpeculated += 2;
TL->setAlignment(LI->getAlignment());
FL->setAlignment(LI->getAlignment());
if (MDNode *Tag = LI->getMetadata(LLVMContext::MD_tbaa)) {
TL->setMetadata(LLVMContext::MD_tbaa, Tag);
FL->setMetadata(LLVMContext::MD_tbaa, Tag);
}
Value *V = IRB.CreateSelect(SI.getCondition(), TL, FL,
LI->getName() + ".sroa.speculated");
LoadInst *Loads[2] = { TL, FL };
for (unsigned i = 0, e = 2; i != e; ++i) {
if (PIs[i] != P.end()) {
Use *LoadUse = &Loads[i]->getOperandUse(0);
assert(PUs[i].U->get() == LoadUse->get());
PUs[i].U = LoadUse;
P.use_push_back(PIs[i], PUs[i]);
}
}
DEBUG(dbgs() << " speculated to: " << *V << "\n");
LI->replaceAllUsesWith(V);
Pass.DeadInsts.push_back(LI);
}
}
};
class AllocaPartitionRewriter : public InstVisitor<AllocaPartitionRewriter,
bool> {
friend class llvm::InstVisitor<AllocaPartitionRewriter, bool>;
const TargetData &TD;
AllocaPartitioning &P;
SROA &Pass;
AllocaInst &OldAI, &NewAI;
const uint64_t NewAllocaBeginOffset, NewAllocaEndOffset;
VectorType *VecTy;
Type *ElementTy;
uint64_t ElementSize;
IntegerType *IntPromotionTy;
uint64_t BeginOffset, EndOffset;
Use *OldUse;
Instruction *OldPtr;
std::string NamePrefix;
public:
AllocaPartitionRewriter(const TargetData &TD, AllocaPartitioning &P,
AllocaPartitioning::iterator PI,
SROA &Pass, AllocaInst &OldAI, AllocaInst &NewAI,
uint64_t NewBeginOffset, uint64_t NewEndOffset)
: TD(TD), P(P), Pass(Pass),
OldAI(OldAI), NewAI(NewAI),
NewAllocaBeginOffset(NewBeginOffset),
NewAllocaEndOffset(NewEndOffset),
VecTy(), ElementTy(), ElementSize(), IntPromotionTy(),
BeginOffset(), EndOffset() {
}
bool visitUsers(AllocaPartitioning::const_use_iterator I,
AllocaPartitioning::const_use_iterator E) {
if (isVectorPromotionViable(TD, NewAI.getAllocatedType(), P,
NewAllocaBeginOffset, NewAllocaEndOffset,
I, E)) {
++NumVectorized;
VecTy = cast<VectorType>(NewAI.getAllocatedType());
ElementTy = VecTy->getElementType();
assert((VecTy->getScalarSizeInBits() % 8) == 0 &&
"Only multiple-of-8 sized vector elements are viable");
ElementSize = VecTy->getScalarSizeInBits() / 8;
} else if (isIntegerPromotionViable(TD, NewAI.getAllocatedType(),
P, I, E)) {
IntPromotionTy = cast<IntegerType>(NewAI.getAllocatedType());
}
bool CanSROA = true;
for (; I != E; ++I) {
BeginOffset = I->BeginOffset;
EndOffset = I->EndOffset;
OldUse = I->U;
OldPtr = cast<Instruction>(I->U->get());
NamePrefix = (Twine(NewAI.getName()) + "." + Twine(BeginOffset)).str();
CanSROA &= visit(cast<Instruction>(I->U->getUser()));
}
if (VecTy) {
assert(CanSROA);
VecTy = 0;
ElementTy = 0;
ElementSize = 0;
}
return CanSROA;
}
private:
bool visitInstruction(Instruction &I) {
DEBUG(dbgs() << " !!!! Cannot rewrite: " << I << "\n");
llvm_unreachable("No rewrite rule for this instruction!");
}
Twine getName(const Twine &Suffix) {
return NamePrefix + Suffix;
}
Value *getAdjustedAllocaPtr(IRBuilder<> &IRB, Type *PointerTy) {
assert(BeginOffset >= NewAllocaBeginOffset);
APInt Offset(TD.getPointerSizeInBits(), BeginOffset - NewAllocaBeginOffset);
return getAdjustedPtr(IRB, TD, &NewAI, Offset, PointerTy, getName(""));
}
unsigned getAdjustedAlign(uint64_t Offset) {
unsigned NewAIAlign = NewAI.getAlignment();
if (!NewAIAlign)
NewAIAlign = TD.getABITypeAlignment(NewAI.getAllocatedType());
return MinAlign(NewAIAlign, Offset);
}
unsigned getAdjustedAlign() {
return getAdjustedAlign(BeginOffset - NewAllocaBeginOffset);
}
bool isTypeAlignSufficient(Type *Ty) {
return TD.getABITypeAlignment(Ty) >= getAdjustedAlign();
}
ConstantInt *getIndex(IRBuilder<> &IRB, uint64_t Offset) {
assert(VecTy && "Can only call getIndex when rewriting a vector");
uint64_t RelOffset = Offset - NewAllocaBeginOffset;
assert(RelOffset / ElementSize < UINT32_MAX && "Index out of bounds");
uint32_t Index = RelOffset / ElementSize;
assert(Index * ElementSize == RelOffset);
return IRB.getInt32(Index);
}
Value *extractInteger(IRBuilder<> &IRB, IntegerType *TargetTy,
uint64_t Offset) {
assert(IntPromotionTy && "Alloca is not an integer we can extract from");
Value *V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
getName(".load"));
assert(Offset >= NewAllocaBeginOffset && "Out of bounds offset");
uint64_t RelOffset = Offset - NewAllocaBeginOffset;
if (RelOffset)
V = IRB.CreateLShr(V, RelOffset*8, getName(".shift"));
if (TargetTy != IntPromotionTy) {
assert(TargetTy->getBitWidth() < IntPromotionTy->getBitWidth() &&
"Cannot extract to a larger integer!");
V = IRB.CreateTrunc(V, TargetTy, getName(".trunc"));
}
return V;
}
StoreInst *insertInteger(IRBuilder<> &IRB, Value *V, uint64_t Offset) {
IntegerType *Ty = cast<IntegerType>(V->getType());
if (Ty == IntPromotionTy)
return IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment());
assert(Ty->getBitWidth() < IntPromotionTy->getBitWidth() &&
"Cannot insert a larger integer!");
V = IRB.CreateZExt(V, IntPromotionTy, getName(".ext"));
assert(Offset >= NewAllocaBeginOffset && "Out of bounds offset");
uint64_t RelOffset = Offset - NewAllocaBeginOffset;
if (RelOffset)
V = IRB.CreateShl(V, RelOffset*8, getName(".shift"));
APInt Mask = ~Ty->getMask().zext(IntPromotionTy->getBitWidth())
.shl(RelOffset*8);
Value *Old = IRB.CreateAnd(IRB.CreateAlignedLoad(&NewAI,
NewAI.getAlignment(),
getName(".oldload")),
Mask, getName(".mask"));
return IRB.CreateAlignedStore(IRB.CreateOr(Old, V, getName(".insert")),
&NewAI, NewAI.getAlignment());
}
void deleteIfTriviallyDead(Value *V) {
Instruction *I = cast<Instruction>(V);
if (isInstructionTriviallyDead(I))
Pass.DeadInsts.push_back(I);
}
Value *getValueCast(IRBuilder<> &IRB, Value *V, Type *Ty) {
if (V->getType()->isIntegerTy() && Ty->isPointerTy())
return IRB.CreateIntToPtr(V, Ty);
if (V->getType()->isPointerTy() && Ty->isIntegerTy())
return IRB.CreatePtrToInt(V, Ty);
return IRB.CreateBitCast(V, Ty);
}
bool rewriteVectorizedLoadInst(IRBuilder<> &IRB, LoadInst &LI, Value *OldOp) {
Value *Result;
if (LI.getType() == VecTy->getElementType() ||
BeginOffset > NewAllocaBeginOffset || EndOffset < NewAllocaEndOffset) {
Result = IRB.CreateExtractElement(
IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), getName(".load")),
getIndex(IRB, BeginOffset), getName(".extract"));
} else {
Result = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
getName(".load"));
}
if (Result->getType() != LI.getType())
Result = getValueCast(IRB, Result, LI.getType());
LI.replaceAllUsesWith(Result);
Pass.DeadInsts.push_back(&LI);
DEBUG(dbgs() << " to: " << *Result << "\n");
return true;
}
bool rewriteIntegerLoad(IRBuilder<> &IRB, LoadInst &LI) {
assert(!LI.isVolatile());
Value *Result = extractInteger(IRB, cast<IntegerType>(LI.getType()),
BeginOffset);
LI.replaceAllUsesWith(Result);
Pass.DeadInsts.push_back(&LI);
DEBUG(dbgs() << " to: " << *Result << "\n");
return true;
}
bool visitLoadInst(LoadInst &LI) {
DEBUG(dbgs() << " original: " << LI << "\n");
Value *OldOp = LI.getOperand(0);
assert(OldOp == OldPtr);
IRBuilder<> IRB(&LI);
if (VecTy)
return rewriteVectorizedLoadInst(IRB, LI, OldOp);
if (IntPromotionTy)
return rewriteIntegerLoad(IRB, LI);
Value *NewPtr = getAdjustedAllocaPtr(IRB,
LI.getPointerOperand()->getType());
LI.setOperand(0, NewPtr);
if (LI.getAlignment() || !isTypeAlignSufficient(LI.getType()))
LI.setAlignment(getAdjustedAlign());
DEBUG(dbgs() << " to: " << LI << "\n");
deleteIfTriviallyDead(OldOp);
return NewPtr == &NewAI && !LI.isVolatile();
}
bool rewriteVectorizedStoreInst(IRBuilder<> &IRB, StoreInst &SI,
Value *OldOp) {
Value *V = SI.getValueOperand();
if (V->getType() == ElementTy ||
BeginOffset > NewAllocaBeginOffset || EndOffset < NewAllocaEndOffset) {
if (V->getType() != ElementTy)
V = getValueCast(IRB, V, ElementTy);
LoadInst *LI = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
getName(".load"));
V = IRB.CreateInsertElement(LI, V, getIndex(IRB, BeginOffset),
getName(".insert"));
} else if (V->getType() != VecTy) {
V = getValueCast(IRB, V, VecTy);
}
StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment());
Pass.DeadInsts.push_back(&SI);
(void)Store;
DEBUG(dbgs() << " to: " << *Store << "\n");
return true;
}
bool rewriteIntegerStore(IRBuilder<> &IRB, StoreInst &SI) {
assert(!SI.isVolatile());
StoreInst *Store = insertInteger(IRB, SI.getValueOperand(), BeginOffset);
Pass.DeadInsts.push_back(&SI);
(void)Store;
DEBUG(dbgs() << " to: " << *Store << "\n");
return true;
}
bool visitStoreInst(StoreInst &SI) {
DEBUG(dbgs() << " original: " << SI << "\n");
Value *OldOp = SI.getOperand(1);
assert(OldOp == OldPtr);
IRBuilder<> IRB(&SI);
if (VecTy)
return rewriteVectorizedStoreInst(IRB, SI, OldOp);
if (IntPromotionTy)
return rewriteIntegerStore(IRB, SI);
Value *NewPtr = getAdjustedAllocaPtr(IRB,
SI.getPointerOperand()->getType());
SI.setOperand(1, NewPtr);
if (SI.getAlignment() ||
!isTypeAlignSufficient(SI.getValueOperand()->getType()))
SI.setAlignment(getAdjustedAlign());
if (SI.getAlignment())
SI.setAlignment(MinAlign(NewAI.getAlignment(),
BeginOffset - NewAllocaBeginOffset));
DEBUG(dbgs() << " to: " << SI << "\n");
deleteIfTriviallyDead(OldOp);
return NewPtr == &NewAI && !SI.isVolatile();
}
bool visitMemSetInst(MemSetInst &II) {
DEBUG(dbgs() << " original: " << II << "\n");
IRBuilder<> IRB(&II);
assert(II.getRawDest() == OldPtr);
if (!isa<Constant>(II.getLength())) {
II.setDest(getAdjustedAllocaPtr(IRB, II.getRawDest()->getType()));
Type *CstTy = II.getAlignmentCst()->getType();
II.setAlignment(ConstantInt::get(CstTy, getAdjustedAlign()));
deleteIfTriviallyDead(OldPtr);
return false;
}
if (Pass.DeadSplitInsts.insert(&II))
Pass.DeadInsts.push_back(&II);
Type *AllocaTy = NewAI.getAllocatedType();
Type *ScalarTy = AllocaTy->getScalarType();
if (!VecTy && (BeginOffset != NewAllocaBeginOffset ||
EndOffset != NewAllocaEndOffset ||
!AllocaTy->isSingleValueType() ||
!TD.isLegalInteger(TD.getTypeSizeInBits(ScalarTy)))) {
Type *SizeTy = II.getLength()->getType();
Constant *Size = ConstantInt::get(SizeTy, EndOffset - BeginOffset);
CallInst *New
= IRB.CreateMemSet(getAdjustedAllocaPtr(IRB,
II.getRawDest()->getType()),
II.getValue(), Size, getAdjustedAlign(),
II.isVolatile());
(void)New;
DEBUG(dbgs() << " to: " << *New << "\n");
return false;
}
Value *V = II.getValue();
IntegerType *VTy = cast<IntegerType>(V->getType());
Type *IntTy = Type::getIntNTy(VTy->getContext(),
TD.getTypeSizeInBits(ScalarTy));
if (TD.getTypeSizeInBits(ScalarTy) > VTy->getBitWidth())
V = IRB.CreateMul(IRB.CreateZExt(V, IntTy, getName(".zext")),
ConstantExpr::getUDiv(
Constant::getAllOnesValue(IntTy),
ConstantExpr::getZExt(
Constant::getAllOnesValue(V->getType()),
IntTy)),
getName(".isplat"));
if (V->getType() != ScalarTy) {
if (ScalarTy->isPointerTy())
V = IRB.CreateIntToPtr(V, ScalarTy);
else if (ScalarTy->isPrimitiveType() || ScalarTy->isVectorTy())
V = IRB.CreateBitCast(V, ScalarTy);
else if (ScalarTy->isIntegerTy())
llvm_unreachable("Computed different integer types with equal widths");
else
llvm_unreachable("Invalid scalar type");
}
if (VecTy && (BeginOffset > NewAllocaBeginOffset ||
EndOffset < NewAllocaEndOffset)) {
StoreInst *Store = IRB.CreateAlignedStore(
IRB.CreateInsertElement(IRB.CreateAlignedLoad(&NewAI,
NewAI.getAlignment(),
getName(".load")),
V, getIndex(IRB, BeginOffset),
getName(".insert")),
&NewAI, NewAI.getAlignment());
(void)Store;
DEBUG(dbgs() << " to: " << *Store << "\n");
return true;
}
if (VectorType *VecTy = dyn_cast<VectorType>(AllocaTy)) {
VectorType *SplatSourceTy = VectorType::get(V->getType(), 1);
V = IRB.CreateShuffleVector(
IRB.CreateInsertElement(UndefValue::get(SplatSourceTy), V,
IRB.getInt32(0), getName(".vsplat.insert")),
UndefValue::get(SplatSourceTy),
ConstantVector::getSplat(VecTy->getNumElements(), IRB.getInt32(0)),
getName(".vsplat.shuffle"));
assert(V->getType() == VecTy);
}
Value *New = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment(),
II.isVolatile());
(void)New;
DEBUG(dbgs() << " to: " << *New << "\n");
return !II.isVolatile();
}
bool visitMemTransferInst(MemTransferInst &II) {
DEBUG(dbgs() << " original: " << II << "\n");
IRBuilder<> IRB(&II);
assert(II.getRawSource() == OldPtr || II.getRawDest() == OldPtr);
bool IsDest = II.getRawDest() == OldPtr;
const AllocaPartitioning::MemTransferOffsets &MTO
= P.getMemTransferOffsets(II);
unsigned IntPtrWidth = TD.getPointerSizeInBits();
APInt RelOffset(IntPtrWidth, BeginOffset - (IsDest ? MTO.DestBegin
: MTO.SourceBegin));
unsigned Align = II.getAlignment();
if (Align > 1)
Align = MinAlign(RelOffset.zextOrTrunc(64).getZExtValue(),
MinAlign(II.getAlignment(), getAdjustedAlign()));
if (!MTO.IsSplittable) {
Value *OldOp = IsDest ? II.getRawDest() : II.getRawSource();
if (IsDest)
II.setDest(getAdjustedAllocaPtr(IRB, II.getRawDest()->getType()));
else
II.setSource(getAdjustedAllocaPtr(IRB, II.getRawSource()->getType()));
Type *CstTy = II.getAlignmentCst()->getType();
II.setAlignment(ConstantInt::get(CstTy, Align));
DEBUG(dbgs() << " to: " << II << "\n");
deleteIfTriviallyDead(OldOp);
return false;
}
bool EmitMemCpy
= !VecTy && (BeginOffset != NewAllocaBeginOffset ||
EndOffset != NewAllocaEndOffset ||
!NewAI.getAllocatedType()->isSingleValueType());
if (EmitMemCpy && &OldAI == &NewAI) {
uint64_t OrigBegin = IsDest ? MTO.DestBegin : MTO.SourceBegin;
uint64_t OrigEnd = IsDest ? MTO.DestEnd : MTO.SourceEnd;
assert(BeginOffset == OrigBegin);
(void)OrigBegin;
if (EndOffset != OrigEnd)
II.setLength(ConstantInt::get(II.getLength()->getType(),
EndOffset - BeginOffset));
return false;
}
if (Pass.DeadSplitInsts.insert(&II))
Pass.DeadInsts.push_back(&II);
bool IsVectorElement = VecTy && (BeginOffset > NewAllocaBeginOffset ||
EndOffset < NewAllocaEndOffset);
Type *OtherPtrTy = IsDest ? II.getRawSource()->getType()
: II.getRawDest()->getType();
if (!EmitMemCpy)
OtherPtrTy = IsVectorElement ? VecTy->getElementType()->getPointerTo()
: NewAI.getType();
Value *OtherPtr = IsDest ? II.getRawSource() : II.getRawDest();
OtherPtr = getAdjustedPtr(IRB, TD, OtherPtr, RelOffset, OtherPtrTy,
getName("." + OtherPtr->getName()));
if (AllocaInst *AI
= dyn_cast<AllocaInst>(OtherPtr->stripInBoundsOffsets()))
Pass.Worklist.insert(AI);
if (EmitMemCpy) {
Value *OurPtr
= getAdjustedAllocaPtr(IRB, IsDest ? II.getRawDest()->getType()
: II.getRawSource()->getType());
Type *SizeTy = II.getLength()->getType();
Constant *Size = ConstantInt::get(SizeTy, EndOffset - BeginOffset);
CallInst *New = IRB.CreateMemCpy(IsDest ? OurPtr : OtherPtr,
IsDest ? OtherPtr : OurPtr,
Size, Align, II.isVolatile());
(void)New;
DEBUG(dbgs() << " to: " << *New << "\n");
return false;
}
Value *SrcPtr = OtherPtr;
Value *DstPtr = &NewAI;
if (!IsDest)
std::swap(SrcPtr, DstPtr);
Value *Src;
if (IsVectorElement && !IsDest) {
Src = IRB.CreateExtractElement(
IRB.CreateAlignedLoad(SrcPtr, Align, getName(".copyload")),
getIndex(IRB, BeginOffset),
getName(".copyextract"));
} else {
Src = IRB.CreateAlignedLoad(SrcPtr, Align, II.isVolatile(),
getName(".copyload"));
}
if (IsVectorElement && IsDest) {
Src = IRB.CreateInsertElement(
IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), getName(".load")),
Src, getIndex(IRB, BeginOffset),
getName(".insert"));
}
StoreInst *Store = cast<StoreInst>(
IRB.CreateAlignedStore(Src, DstPtr, Align, II.isVolatile()));
(void)Store;
DEBUG(dbgs() << " to: " << *Store << "\n");
return !II.isVolatile();
}
bool visitIntrinsicInst(IntrinsicInst &II) {
assert(II.getIntrinsicID() == Intrinsic::lifetime_start ||
II.getIntrinsicID() == Intrinsic::lifetime_end);
DEBUG(dbgs() << " original: " << II << "\n");
IRBuilder<> IRB(&II);
assert(II.getArgOperand(1) == OldPtr);
if (Pass.DeadSplitInsts.insert(&II))
Pass.DeadInsts.push_back(&II);
ConstantInt *Size
= ConstantInt::get(cast<IntegerType>(II.getArgOperand(0)->getType()),
EndOffset - BeginOffset);
Value *Ptr = getAdjustedAllocaPtr(IRB, II.getArgOperand(1)->getType());
Value *New;
if (II.getIntrinsicID() == Intrinsic::lifetime_start)
New = IRB.CreateLifetimeStart(Ptr, Size);
else
New = IRB.CreateLifetimeEnd(Ptr, Size);
DEBUG(dbgs() << " to: " << *New << "\n");
return true;
}
bool visitPHINode(PHINode &PN) {
DEBUG(dbgs() << " original: " << PN << "\n");
IRBuilder<> PtrBuilder(cast<Instruction>(OldPtr));
Value *NewPtr = getAdjustedAllocaPtr(PtrBuilder, OldPtr->getType());
User::op_iterator OI = PN.op_begin(), OE = PN.op_end();
for (; OI != OE; ++OI)
if (*OI == OldPtr)
*OI = NewPtr;
DEBUG(dbgs() << " to: " << PN << "\n");
deleteIfTriviallyDead(OldPtr);
return false;
}
bool visitSelectInst(SelectInst &SI) {
DEBUG(dbgs() << " original: " << SI << "\n");
IRBuilder<> IRB(&SI);
bool IsTrueVal = SI.getTrueValue() == OldPtr;
if (IsTrueVal)
assert(SI.getFalseValue() != OldPtr && "Pointer is both operands!");
else
assert(SI.getFalseValue() == OldPtr && "Pointer isn't an operand!");
Value *NewPtr = getAdjustedAllocaPtr(IRB, OldPtr->getType());
SI.setOperand(IsTrueVal ? 1 : 2, NewPtr);
DEBUG(dbgs() << " to: " << SI << "\n");
deleteIfTriviallyDead(OldPtr);
return false;
}
};
}
namespace {
class AggLoadStoreRewriter : public InstVisitor<AggLoadStoreRewriter, bool> {
friend class llvm::InstVisitor<AggLoadStoreRewriter, bool>;
const TargetData &TD;
SmallVector<Use *, 8> Queue;
SmallPtrSet<User *, 8> Visited;
Use *U;
public:
AggLoadStoreRewriter(const TargetData &TD) : TD(TD) {}
bool rewrite(Instruction &I) {
DEBUG(dbgs() << " Rewriting FCA loads and stores...\n");
enqueueUsers(I);
bool Changed = false;
while (!Queue.empty()) {
U = Queue.pop_back_val();
Changed |= visit(cast<Instruction>(U->getUser()));
}
return Changed;
}
private:
void enqueueUsers(Instruction &I) {
for (Value::use_iterator UI = I.use_begin(), UE = I.use_end(); UI != UE;
++UI)
if (Visited.insert(*UI))
Queue.push_back(&UI.getUse());
}
bool visitInstruction(Instruction &I) { return false; }
template <typename Derived>
class OpSplitter {
protected:
IRBuilder<> IRB;
SmallVector<unsigned, 4> Indices;
SmallVector<Value *, 4> GEPIndices;
Value *Ptr;
OpSplitter(Instruction *InsertionPoint, Value *Ptr)
: IRB(InsertionPoint), GEPIndices(1, IRB.getInt32(0)), Ptr(Ptr) {}
public:
void emitSplitOps(Type *Ty, Value *&Agg, const Twine &Name) {
if (Ty->isSingleValueType())
return static_cast<Derived *>(this)->emitFunc(Ty, Agg, Name);
if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
unsigned OldSize = Indices.size();
(void)OldSize;
for (unsigned Idx = 0, Size = ATy->getNumElements(); Idx != Size;
++Idx) {
assert(Indices.size() == OldSize && "Did not return to the old size");
Indices.push_back(Idx);
GEPIndices.push_back(IRB.getInt32(Idx));
emitSplitOps(ATy->getElementType(), Agg, Name + "." + Twine(Idx));
GEPIndices.pop_back();
Indices.pop_back();
}
return;
}
if (StructType *STy = dyn_cast<StructType>(Ty)) {
unsigned OldSize = Indices.size();
(void)OldSize;
for (unsigned Idx = 0, Size = STy->getNumElements(); Idx != Size;
++Idx) {
assert(Indices.size() == OldSize && "Did not return to the old size");
Indices.push_back(Idx);
GEPIndices.push_back(IRB.getInt32(Idx));
emitSplitOps(STy->getElementType(Idx), Agg, Name + "." + Twine(Idx));
GEPIndices.pop_back();
Indices.pop_back();
}
return;
}
llvm_unreachable("Only arrays and structs are aggregate loadable types");
}
};
struct LoadOpSplitter : public OpSplitter<LoadOpSplitter> {
LoadOpSplitter(Instruction *InsertionPoint, Value *Ptr)
: OpSplitter<LoadOpSplitter>(InsertionPoint, Ptr) {}
void emitFunc(Type *Ty, Value *&Agg, const Twine &Name) {
assert(Ty->isSingleValueType());
Value *Load = IRB.CreateLoad(IRB.CreateInBoundsGEP(Ptr, GEPIndices,
Name + ".gep"),
Name + ".load");
Agg = IRB.CreateInsertValue(Agg, Load, Indices, Name + ".insert");
DEBUG(dbgs() << " to: " << *Load << "\n");
}
};
bool visitLoadInst(LoadInst &LI) {
assert(LI.getPointerOperand() == *U);
if (!LI.isSimple() || LI.getType()->isSingleValueType())
return false;
DEBUG(dbgs() << " original: " << LI << "\n");
LoadOpSplitter Splitter(&LI, *U);
Value *V = UndefValue::get(LI.getType());
Splitter.emitSplitOps(LI.getType(), V, LI.getName() + ".fca");
LI.replaceAllUsesWith(V);
LI.eraseFromParent();
return true;
}
struct StoreOpSplitter : public OpSplitter<StoreOpSplitter> {
StoreOpSplitter(Instruction *InsertionPoint, Value *Ptr)
: OpSplitter<StoreOpSplitter>(InsertionPoint, Ptr) {}
void emitFunc(Type *Ty, Value *&Agg, const Twine &Name) {
assert(Ty->isSingleValueType());
Value *Store = IRB.CreateStore(
IRB.CreateExtractValue(Agg, Indices, Name + ".extract"),
IRB.CreateInBoundsGEP(Ptr, GEPIndices, Name + ".gep"));
(void)Store;
DEBUG(dbgs() << " to: " << *Store << "\n");
}
};
bool visitStoreInst(StoreInst &SI) {
if (!SI.isSimple() || SI.getPointerOperand() != *U)
return false;
Value *V = SI.getValueOperand();
if (V->getType()->isSingleValueType())
return false;
DEBUG(dbgs() << " original: " << SI << "\n");
StoreOpSplitter Splitter(&SI, *U);
Splitter.emitSplitOps(V->getType(), V, V->getName() + ".fca");
SI.eraseFromParent();
return true;
}
bool visitBitCastInst(BitCastInst &BC) {
enqueueUsers(BC);
return false;
}
bool visitGetElementPtrInst(GetElementPtrInst &GEPI) {
enqueueUsers(GEPI);
return false;
}
bool visitPHINode(PHINode &PN) {
enqueueUsers(PN);
return false;
}
bool visitSelectInst(SelectInst &SI) {
enqueueUsers(SI);
return false;
}
};
}
static Type *getTypePartition(const TargetData &TD, Type *Ty,
uint64_t Offset, uint64_t Size) {
if (Offset == 0 && TD.getTypeAllocSize(Ty) == Size)
return Ty;
if (SequentialType *SeqTy = dyn_cast<SequentialType>(Ty)) {
if (SeqTy->isPointerTy())
return 0;
Type *ElementTy = SeqTy->getElementType();
uint64_t ElementSize = TD.getTypeAllocSize(ElementTy);
uint64_t NumSkippedElements = Offset / ElementSize;
if (ArrayType *ArrTy = dyn_cast<ArrayType>(SeqTy))
if (NumSkippedElements >= ArrTy->getNumElements())
return 0;
if (VectorType *VecTy = dyn_cast<VectorType>(SeqTy))
if (NumSkippedElements >= VecTy->getNumElements())
return 0;
Offset -= NumSkippedElements * ElementSize;
if (Offset > 0 || Size < ElementSize) {
if ((Offset + Size) > ElementSize)
return 0;
return getTypePartition(TD, ElementTy, Offset, Size);
}
assert(Offset == 0);
if (Size == ElementSize)
return ElementTy;
assert(Size > ElementSize);
uint64_t NumElements = Size / ElementSize;
if (NumElements * ElementSize != Size)
return 0;
return ArrayType::get(ElementTy, NumElements);
}
StructType *STy = dyn_cast<StructType>(Ty);
if (!STy)
return 0;
const StructLayout *SL = TD.getStructLayout(STy);
if (Offset >= SL->getSizeInBytes())
return 0;
uint64_t EndOffset = Offset + Size;
if (EndOffset > SL->getSizeInBytes())
return 0;
unsigned Index = SL->getElementContainingOffset(Offset);
Offset -= SL->getElementOffset(Index);
Type *ElementTy = STy->getElementType(Index);
uint64_t ElementSize = TD.getTypeAllocSize(ElementTy);
if (Offset >= ElementSize)
return 0;
if (Offset > 0 || Size < ElementSize) {
if ((Offset + Size) > ElementSize)
return 0;
return getTypePartition(TD, ElementTy, Offset, Size);
}
assert(Offset == 0);
if (Size == ElementSize)
return ElementTy;
StructType::element_iterator EI = STy->element_begin() + Index,
EE = STy->element_end();
if (EndOffset < SL->getSizeInBytes()) {
unsigned EndIndex = SL->getElementContainingOffset(EndOffset);
if (Index == EndIndex)
return 0;
if (SL->getElementOffset(EndIndex) != EndOffset)
return 0;
assert(Index < EndIndex);
EE = STy->element_begin() + EndIndex;
}
SmallVector<Type *, 4> ElementTys;
do {
ElementTys.push_back(*EI++);
} while (EI != EE);
StructType *SubTy = StructType::get(STy->getContext(), ElementTys,
STy->isPacked());
const StructLayout *SubSL = TD.getStructLayout(SubTy);
if (Size != SubSL->getSizeInBytes())
return 0;
return SubTy;
}
bool SROA::rewriteAllocaPartition(AllocaInst &AI,
AllocaPartitioning &P,
AllocaPartitioning::iterator PI) {
uint64_t AllocaSize = PI->EndOffset - PI->BeginOffset;
if (P.use_begin(PI) == P.use_end(PI))
return false;
DEBUG(dbgs() << "Speculating PHIs and selects in partition "
<< "[" << PI->BeginOffset << "," << PI->EndOffset << ")\n");
PHIOrSelectSpeculator Speculator(*TD, P, *this);
DEBUG(dbgs() << " speculating ");
DEBUG(P.print(dbgs(), PI, ""));
Speculator.visitUsers(P.use_begin(PI), P.use_end(PI));
Type *AllocaTy = 0;
if (Type *PartitionTy = P.getCommonType(PI))
if (TD->getTypeAllocSize(PartitionTy) >= AllocaSize)
AllocaTy = PartitionTy;
if (!AllocaTy)
if (Type *PartitionTy = getTypePartition(*TD, AI.getAllocatedType(),
PI->BeginOffset, AllocaSize))
AllocaTy = PartitionTy;
if ((!AllocaTy ||
(AllocaTy->isArrayTy() &&
AllocaTy->getArrayElementType()->isIntegerTy())) &&
TD->isLegalInteger(AllocaSize * 8))
AllocaTy = Type::getIntNTy(*C, AllocaSize * 8);
if (!AllocaTy)
AllocaTy = ArrayType::get(Type::getInt8Ty(*C), AllocaSize);
assert(TD->getTypeAllocSize(AllocaTy) >= AllocaSize);
AllocaInst *NewAI;
if (AllocaTy == AI.getAllocatedType()) {
assert(PI->BeginOffset == 0 &&
"Non-zero begin offset but same alloca type");
assert(PI == P.begin() && "Begin offset is zero on later partition");
NewAI = &AI;
} else {
unsigned Alignment = AI.getAlignment();
if (!Alignment) {
Alignment = TD->getABITypeAlignment(AI.getAllocatedType());
}
Alignment = MinAlign(Alignment, PI->BeginOffset);
if (Alignment <= TD->getABITypeAlignment(AllocaTy))
Alignment = 0;
NewAI = new AllocaInst(AllocaTy, 0, Alignment,
AI.getName() + ".sroa." + Twine(PI - P.begin()),
&AI);
++NumNewAllocas;
}
DEBUG(dbgs() << "Rewriting alloca partition "
<< "[" << PI->BeginOffset << "," << PI->EndOffset << ") to: "
<< *NewAI << "\n");
AllocaPartitionRewriter Rewriter(*TD, P, PI, *this, AI, *NewAI,
PI->BeginOffset, PI->EndOffset);
DEBUG(dbgs() << " rewriting ");
DEBUG(P.print(dbgs(), PI, ""));
if (Rewriter.visitUsers(P.use_begin(PI), P.use_end(PI))) {
DEBUG(dbgs() << " and queuing for promotion\n");
PromotableAllocas.push_back(NewAI);
} else if (NewAI != &AI) {
Worklist.insert(NewAI);
}
return true;
}
bool SROA::splitAlloca(AllocaInst &AI, AllocaPartitioning &P) {
bool Changed = false;
for (AllocaPartitioning::iterator PI = P.begin(), PE = P.end(); PI != PE;
++PI)
Changed |= rewriteAllocaPartition(AI, P, PI);
return Changed;
}
bool SROA::runOnAlloca(AllocaInst &AI) {
DEBUG(dbgs() << "SROA alloca: " << AI << "\n");
++NumAllocasAnalyzed;
if (AI.use_empty()) {
AI.eraseFromParent();
return true;
}
if (AI.isArrayAllocation() || !AI.getAllocatedType()->isSized() ||
TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
return false;
if (!AI.getAllocatedType()->isAggregateType() && isAllocaPromotable(&AI)) {
DEBUG(dbgs() << " Trivially scalar type, queuing for promotion...\n");
PromotableAllocas.push_back(&AI);
return false;
}
bool Changed = false;
AggLoadStoreRewriter AggRewriter(*TD);
Changed |= AggRewriter.rewrite(AI);
AllocaPartitioning P(*TD, AI);
DEBUG(P.print(dbgs()));
if (P.isEscaped())
return Changed;
if (P.begin() == P.end())
return Changed;
for (AllocaPartitioning::dead_user_iterator DI = P.dead_user_begin(),
DE = P.dead_user_end();
DI != DE; ++DI) {
Changed = true;
(*DI)->replaceAllUsesWith(UndefValue::get((*DI)->getType()));
DeadInsts.push_back(*DI);
}
for (AllocaPartitioning::dead_op_iterator DO = P.dead_op_begin(),
DE = P.dead_op_end();
DO != DE; ++DO) {
Value *OldV = **DO;
**DO = UndefValue::get(OldV->getType());
if (Instruction *OldI = dyn_cast<Instruction>(OldV))
if (isInstructionTriviallyDead(OldI)) {
Changed = true;
DeadInsts.push_back(OldI);
}
}
return splitAlloca(AI, P) || Changed;
}
void SROA::deleteDeadInstructions(SmallPtrSet<AllocaInst*, 4> &DeletedAllocas) {
DeadSplitInsts.clear();
while (!DeadInsts.empty()) {
Instruction *I = DeadInsts.pop_back_val();
DEBUG(dbgs() << "Deleting dead instruction: " << *I << "\n");
for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI)
if (Instruction *U = dyn_cast<Instruction>(*OI)) {
*OI = 0;
if (isInstructionTriviallyDead(U))
DeadInsts.push_back(U);
}
if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
DeletedAllocas.insert(AI);
++NumDeleted;
I->eraseFromParent();
}
}
bool SROA::promoteAllocas(Function &F) {
if (PromotableAllocas.empty())
return false;
NumPromoted += PromotableAllocas.size();
if (DT && !ForceSSAUpdater) {
DEBUG(dbgs() << "Promoting allocas with mem2reg...\n");
PromoteMemToReg(PromotableAllocas, *DT);
PromotableAllocas.clear();
return true;
}
DEBUG(dbgs() << "Promoting allocas with SSAUpdater...\n");
SSAUpdater SSA;
DIBuilder DIB(*F.getParent());
SmallVector<Instruction*, 64> Insts;
for (unsigned Idx = 0, Size = PromotableAllocas.size(); Idx != Size; ++Idx) {
AllocaInst *AI = PromotableAllocas[Idx];
for (Value::use_iterator UI = AI->use_begin(), UE = AI->use_end();
UI != UE;) {
Instruction *I = cast<Instruction>(*UI++);
if (isa<BitCastInst>(I) || isa<GetElementPtrInst>(I)) {
assert(onlyUsedByLifetimeMarkers(I) &&
"Found a bitcast used outside of a lifetime marker.");
while (!I->use_empty())
cast<Instruction>(*I->use_begin())->eraseFromParent();
I->eraseFromParent();
continue;
}
if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
assert(II->getIntrinsicID() == Intrinsic::lifetime_start ||
II->getIntrinsicID() == Intrinsic::lifetime_end);
II->eraseFromParent();
continue;
}
Insts.push_back(I);
}
AllocaPromoter(Insts, SSA, *AI, DIB).run(Insts);
Insts.clear();
}
PromotableAllocas.clear();
return true;
}
namespace {
class IsAllocaInSet {
typedef SmallPtrSet<AllocaInst *, 4> SetType;
const SetType &Set;
public:
IsAllocaInSet(const SetType &Set) : Set(Set) {}
bool operator()(AllocaInst *AI) { return Set.count(AI); }
};
}
bool SROA::runOnFunction(Function &F) {
DEBUG(dbgs() << "SROA function: " << F.getName() << "\n");
C = &F.getContext();
TD = getAnalysisIfAvailable<TargetData>();
if (!TD) {
DEBUG(dbgs() << " Skipping SROA -- no target data!\n");
return false;
}
DT = getAnalysisIfAvailable<DominatorTree>();
BasicBlock &EntryBB = F.getEntryBlock();
for (BasicBlock::iterator I = EntryBB.begin(), E = llvm::prior(EntryBB.end());
I != E; ++I)
if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
Worklist.insert(AI);
bool Changed = false;
SmallPtrSet<AllocaInst *, 4> DeletedAllocas;
while (!Worklist.empty()) {
Changed |= runOnAlloca(*Worklist.pop_back_val());
deleteDeadInstructions(DeletedAllocas);
if (!DeletedAllocas.empty()) {
PromotableAllocas.erase(std::remove_if(PromotableAllocas.begin(),
PromotableAllocas.end(),
IsAllocaInSet(DeletedAllocas)),
PromotableAllocas.end());
DeletedAllocas.clear();
}
}
Changed |= promoteAllocas(F);
return Changed;
}
void SROA::getAnalysisUsage(AnalysisUsage &AU) const {
if (RequiresDomTree)
AU.addRequired<DominatorTree>();
AU.setPreservesCFG();
}