#define BBV_NAME "bb-vectorize"
#define DEBUG_TYPE BBV_NAME
#include "llvm/Constants.h"
#include "llvm/DerivedTypes.h"
#include "llvm/Function.h"
#include "llvm/Instructions.h"
#include "llvm/IntrinsicInst.h"
#include "llvm/Intrinsics.h"
#include "llvm/LLVMContext.h"
#include "llvm/Pass.h"
#include "llvm/Type.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/DenseSet.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/Analysis/AliasAnalysis.h"
#include "llvm/Analysis/AliasSetTracker.h"
#include "llvm/Analysis/ScalarEvolution.h"
#include "llvm/Analysis/ScalarEvolutionExpressions.h"
#include "llvm/Analysis/ValueTracking.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/ValueHandle.h"
#include "llvm/Target/TargetData.h"
#include "llvm/Transforms/Vectorize.h"
#include <algorithm>
#include <map>
using namespace llvm;
static cl::opt<unsigned>
ReqChainDepth("bb-vectorize-req-chain-depth", cl::init(6), cl::Hidden,
cl::desc("The required chain depth for vectorization"));
static cl::opt<unsigned>
SearchLimit("bb-vectorize-search-limit", cl::init(400), cl::Hidden,
cl::desc("The maximum search distance for instruction pairs"));
static cl::opt<bool>
SplatBreaksChain("bb-vectorize-splat-breaks-chain", cl::init(false), cl::Hidden,
cl::desc("Replicating one element to a pair breaks the chain"));
static cl::opt<unsigned>
VectorBits("bb-vectorize-vector-bits", cl::init(128), cl::Hidden,
cl::desc("The size of the native vector registers"));
static cl::opt<unsigned>
MaxIter("bb-vectorize-max-iter", cl::init(0), cl::Hidden,
cl::desc("The maximum number of pairing iterations"));
static cl::opt<unsigned>
MaxInsts("bb-vectorize-max-instr-per-group", cl::init(500), cl::Hidden,
cl::desc("The maximum number of pairable instructions per group"));
static cl::opt<unsigned>
MaxCandPairsForCycleCheck("bb-vectorize-max-cycle-check-pairs", cl::init(200),
cl::Hidden, cl::desc("The maximum number of candidate pairs with which to use"
" a full cycle check"));
static cl::opt<bool>
NoInts("bb-vectorize-no-ints", cl::init(false), cl::Hidden,
cl::desc("Don't try to vectorize integer values"));
static cl::opt<bool>
NoFloats("bb-vectorize-no-floats", cl::init(false), cl::Hidden,
cl::desc("Don't try to vectorize floating-point values"));
static cl::opt<bool>
NoCasts("bb-vectorize-no-casts", cl::init(false), cl::Hidden,
cl::desc("Don't try to vectorize casting (conversion) operations"));
static cl::opt<bool>
NoMath("bb-vectorize-no-math", cl::init(false), cl::Hidden,
cl::desc("Don't try to vectorize floating-point math intrinsics"));
static cl::opt<bool>
NoFMA("bb-vectorize-no-fma", cl::init(false), cl::Hidden,
cl::desc("Don't try to vectorize the fused-multiply-add intrinsic"));
static cl::opt<bool>
NoMemOps("bb-vectorize-no-mem-ops", cl::init(false), cl::Hidden,
cl::desc("Don't try to vectorize loads and stores"));
static cl::opt<bool>
AlignedOnly("bb-vectorize-aligned-only", cl::init(false), cl::Hidden,
cl::desc("Only generate aligned loads and stores"));
static cl::opt<bool>
NoMemOpBoost("bb-vectorize-no-mem-op-boost",
cl::init(false), cl::Hidden,
cl::desc("Don't boost the chain-depth contribution of loads and stores"));
static cl::opt<bool>
FastDep("bb-vectorize-fast-dep", cl::init(false), cl::Hidden,
cl::desc("Use a fast instruction dependency analysis"));
#ifndef NDEBUG
static cl::opt<bool>
DebugInstructionExamination("bb-vectorize-debug-instruction-examination",
cl::init(false), cl::Hidden,
cl::desc("When debugging is enabled, output information on the"
" instruction-examination process"));
static cl::opt<bool>
DebugCandidateSelection("bb-vectorize-debug-candidate-selection",
cl::init(false), cl::Hidden,
cl::desc("When debugging is enabled, output information on the"
" candidate-selection process"));
static cl::opt<bool>
DebugPairSelection("bb-vectorize-debug-pair-selection",
cl::init(false), cl::Hidden,
cl::desc("When debugging is enabled, output information on the"
" pair-selection process"));
static cl::opt<bool>
DebugCycleCheck("bb-vectorize-debug-cycle-check",
cl::init(false), cl::Hidden,
cl::desc("When debugging is enabled, output information on the"
" cycle-checking process"));
#endif
STATISTIC(NumFusedOps, "Number of operations fused by bb-vectorize");
namespace {
struct BBVectorize : public BasicBlockPass {
static char ID; BBVectorize() : BasicBlockPass(ID) {
initializeBBVectorizePass(*PassRegistry::getPassRegistry());
}
typedef std::pair<Value *, Value *> ValuePair;
typedef std::pair<ValuePair, size_t> ValuePairWithDepth;
typedef std::pair<ValuePair, ValuePair> VPPair; typedef std::pair<std::multimap<Value *, Value *>::iterator,
std::multimap<Value *, Value *>::iterator> VPIteratorPair;
typedef std::pair<std::multimap<ValuePair, ValuePair>::iterator,
std::multimap<ValuePair, ValuePair>::iterator>
VPPIteratorPair;
AliasAnalysis *AA;
ScalarEvolution *SE;
TargetData *TD;
bool vectorizePairs(BasicBlock &BB);
bool getCandidatePairs(BasicBlock &BB,
BasicBlock::iterator &Start,
std::multimap<Value *, Value *> &CandidatePairs,
std::vector<Value *> &PairableInsts);
void computeConnectedPairs(std::multimap<Value *, Value *> &CandidatePairs,
std::vector<Value *> &PairableInsts,
std::multimap<ValuePair, ValuePair> &ConnectedPairs);
void buildDepMap(BasicBlock &BB,
std::multimap<Value *, Value *> &CandidatePairs,
std::vector<Value *> &PairableInsts,
DenseSet<ValuePair> &PairableInstUsers);
void choosePairs(std::multimap<Value *, Value *> &CandidatePairs,
std::vector<Value *> &PairableInsts,
std::multimap<ValuePair, ValuePair> &ConnectedPairs,
DenseSet<ValuePair> &PairableInstUsers,
DenseMap<Value *, Value *>& ChosenPairs);
void fuseChosenPairs(BasicBlock &BB,
std::vector<Value *> &PairableInsts,
DenseMap<Value *, Value *>& ChosenPairs);
bool isInstVectorizable(Instruction *I, bool &IsSimpleLoadStore);
bool areInstsCompatible(Instruction *I, Instruction *J,
bool IsSimpleLoadStore);
bool trackUsesOfI(DenseSet<Value *> &Users,
AliasSetTracker &WriteSet, Instruction *I,
Instruction *J, bool UpdateUsers = true,
std::multimap<Value *, Value *> *LoadMoveSet = 0);
void computePairsConnectedTo(
std::multimap<Value *, Value *> &CandidatePairs,
std::vector<Value *> &PairableInsts,
std::multimap<ValuePair, ValuePair> &ConnectedPairs,
ValuePair P);
bool pairsConflict(ValuePair P, ValuePair Q,
DenseSet<ValuePair> &PairableInstUsers,
std::multimap<ValuePair, ValuePair> *PairableInstUserMap = 0);
bool pairWillFormCycle(ValuePair P,
std::multimap<ValuePair, ValuePair> &PairableInstUsers,
DenseSet<ValuePair> &CurrentPairs);
void pruneTreeFor(
std::multimap<Value *, Value *> &CandidatePairs,
std::vector<Value *> &PairableInsts,
std::multimap<ValuePair, ValuePair> &ConnectedPairs,
DenseSet<ValuePair> &PairableInstUsers,
std::multimap<ValuePair, ValuePair> &PairableInstUserMap,
DenseMap<Value *, Value *> &ChosenPairs,
DenseMap<ValuePair, size_t> &Tree,
DenseSet<ValuePair> &PrunedTree, ValuePair J,
bool UseCycleCheck);
void buildInitialTreeFor(
std::multimap<Value *, Value *> &CandidatePairs,
std::vector<Value *> &PairableInsts,
std::multimap<ValuePair, ValuePair> &ConnectedPairs,
DenseSet<ValuePair> &PairableInstUsers,
DenseMap<Value *, Value *> &ChosenPairs,
DenseMap<ValuePair, size_t> &Tree, ValuePair J);
void findBestTreeFor(
std::multimap<Value *, Value *> &CandidatePairs,
std::vector<Value *> &PairableInsts,
std::multimap<ValuePair, ValuePair> &ConnectedPairs,
DenseSet<ValuePair> &PairableInstUsers,
std::multimap<ValuePair, ValuePair> &PairableInstUserMap,
DenseMap<Value *, Value *> &ChosenPairs,
DenseSet<ValuePair> &BestTree, size_t &BestMaxDepth,
size_t &BestEffSize, VPIteratorPair ChoiceRange,
bool UseCycleCheck);
Value *getReplacementPointerInput(LLVMContext& Context, Instruction *I,
Instruction *J, unsigned o, bool &FlipMemInputs);
void fillNewShuffleMask(LLVMContext& Context, Instruction *J,
unsigned NumElem, unsigned MaskOffset, unsigned NumInElem,
unsigned IdxOffset, std::vector<Constant*> &Mask);
Value *getReplacementShuffleMask(LLVMContext& Context, Instruction *I,
Instruction *J);
Value *getReplacementInput(LLVMContext& Context, Instruction *I,
Instruction *J, unsigned o, bool FlipMemInputs);
void getReplacementInputsForPair(LLVMContext& Context, Instruction *I,
Instruction *J, SmallVector<Value *, 3> &ReplacedOperands,
bool &FlipMemInputs);
void replaceOutputsOfPair(LLVMContext& Context, Instruction *I,
Instruction *J, Instruction *K,
Instruction *&InsertionPt, Instruction *&K1,
Instruction *&K2, bool &FlipMemInputs);
void collectPairLoadMoveSet(BasicBlock &BB,
DenseMap<Value *, Value *> &ChosenPairs,
std::multimap<Value *, Value *> &LoadMoveSet,
Instruction *I);
void collectLoadMoveSet(BasicBlock &BB,
std::vector<Value *> &PairableInsts,
DenseMap<Value *, Value *> &ChosenPairs,
std::multimap<Value *, Value *> &LoadMoveSet);
bool canMoveUsesOfIAfterJ(BasicBlock &BB,
std::multimap<Value *, Value *> &LoadMoveSet,
Instruction *I, Instruction *J);
void moveUsesOfIAfterJ(BasicBlock &BB,
std::multimap<Value *, Value *> &LoadMoveSet,
Instruction *&InsertionPt,
Instruction *I, Instruction *J);
virtual bool runOnBasicBlock(BasicBlock &BB) {
AA = &getAnalysis<AliasAnalysis>();
SE = &getAnalysis<ScalarEvolution>();
TD = getAnalysisIfAvailable<TargetData>();
bool changed = false;
for (unsigned v = 2, n = 1; v <= VectorBits && (!MaxIter || n <= MaxIter);
v *= 2, ++n) {
DEBUG(dbgs() << "BBV: fusing loop #" << n <<
" for " << BB.getName() << " in " <<
BB.getParent()->getName() << "...\n");
if (vectorizePairs(BB))
changed = true;
else
break;
}
DEBUG(dbgs() << "BBV: done!\n");
return changed;
}
virtual void getAnalysisUsage(AnalysisUsage &AU) const {
BasicBlockPass::getAnalysisUsage(AU);
AU.addRequired<AliasAnalysis>();
AU.addRequired<ScalarEvolution>();
AU.addPreserved<AliasAnalysis>();
AU.addPreserved<ScalarEvolution>();
AU.setPreservesCFG();
}
static inline VectorType *getVecTypeForPair(Type *ElemTy) {
if (VectorType *VTy = dyn_cast<VectorType>(ElemTy)) {
unsigned numElem = VTy->getNumElements();
return VectorType::get(ElemTy->getScalarType(), numElem*2);
}
return VectorType::get(ElemTy, 2);
}
static inline size_t getDepthFactor(Value *V) {
if (isa<InsertElementInst>(V) || isa<ExtractElementInst>(V))
return 0;
if (!NoMemOpBoost && (isa<LoadInst>(V) || isa<StoreInst>(V)))
return ReqChainDepth/2;
return 1;
}
bool getPairPtrInfo(Instruction *I, Instruction *J,
Value *&IPtr, Value *&JPtr, unsigned &IAlignment, unsigned &JAlignment,
int64_t &OffsetInElmts) {
OffsetInElmts = 0;
if (isa<LoadInst>(I)) {
IPtr = cast<LoadInst>(I)->getPointerOperand();
JPtr = cast<LoadInst>(J)->getPointerOperand();
IAlignment = cast<LoadInst>(I)->getAlignment();
JAlignment = cast<LoadInst>(J)->getAlignment();
} else {
IPtr = cast<StoreInst>(I)->getPointerOperand();
JPtr = cast<StoreInst>(J)->getPointerOperand();
IAlignment = cast<StoreInst>(I)->getAlignment();
JAlignment = cast<StoreInst>(J)->getAlignment();
}
const SCEV *IPtrSCEV = SE->getSCEV(IPtr);
const SCEV *JPtrSCEV = SE->getSCEV(JPtr);
const SCEV *OffsetSCEV = SE->getMinusSCEV(JPtrSCEV, IPtrSCEV);
if (const SCEVConstant *ConstOffSCEV =
dyn_cast<SCEVConstant>(OffsetSCEV)) {
ConstantInt *IntOff = ConstOffSCEV->getValue();
int64_t Offset = IntOff->getSExtValue();
Type *VTy = cast<PointerType>(IPtr->getType())->getElementType();
int64_t VTyTSS = (int64_t) TD->getTypeStoreSize(VTy);
assert(VTy == cast<PointerType>(JPtr->getType())->getElementType());
OffsetInElmts = Offset/VTyTSS;
return (abs64(Offset) % VTyTSS) == 0;
}
return false;
}
bool isVectorizableIntrinsic(CallInst* I) {
Function *F = I->getCalledFunction();
if (!F) return false;
unsigned IID = F->getIntrinsicID();
if (!IID) return false;
switch(IID) {
default:
return false;
case Intrinsic::sqrt:
case Intrinsic::powi:
case Intrinsic::sin:
case Intrinsic::cos:
case Intrinsic::log:
case Intrinsic::log2:
case Intrinsic::log10:
case Intrinsic::exp:
case Intrinsic::exp2:
case Intrinsic::pow:
return !NoMath;
case Intrinsic::fma:
return !NoFMA;
}
}
template <typename V>
bool isSecondInIteratorPair(V J, std::pair<
typename std::multimap<V, V>::iterator,
typename std::multimap<V, V>::iterator> PairRange) {
for (typename std::multimap<V, V>::iterator K = PairRange.first;
K != PairRange.second; ++K)
if (K->second == J) return true;
return false;
}
};
bool BBVectorize::vectorizePairs(BasicBlock &BB) {
bool ShouldContinue;
BasicBlock::iterator Start = BB.getFirstInsertionPt();
std::vector<Value *> AllPairableInsts;
DenseMap<Value *, Value *> AllChosenPairs;
do {
std::vector<Value *> PairableInsts;
std::multimap<Value *, Value *> CandidatePairs;
ShouldContinue = getCandidatePairs(BB, Start, CandidatePairs,
PairableInsts);
if (PairableInsts.empty()) continue;
std::multimap<ValuePair, ValuePair> ConnectedPairs;
computeConnectedPairs(CandidatePairs, PairableInsts, ConnectedPairs);
if (ConnectedPairs.empty()) continue;
DenseSet<ValuePair> PairableInstUsers;
buildDepMap(BB, CandidatePairs, PairableInsts, PairableInstUsers);
DenseMap<Value *, Value *> ChosenPairs;
choosePairs(CandidatePairs, PairableInsts, ConnectedPairs,
PairableInstUsers, ChosenPairs);
if (ChosenPairs.empty()) continue;
AllPairableInsts.insert(AllPairableInsts.end(), PairableInsts.begin(),
PairableInsts.end());
AllChosenPairs.insert(ChosenPairs.begin(), ChosenPairs.end());
} while (ShouldContinue);
if (AllChosenPairs.empty()) return false;
NumFusedOps += AllChosenPairs.size();
fuseChosenPairs(BB, AllPairableInsts, AllChosenPairs);
return true;
}
bool BBVectorize::isInstVectorizable(Instruction *I,
bool &IsSimpleLoadStore) {
IsSimpleLoadStore = false;
if (CallInst *C = dyn_cast<CallInst>(I)) {
if (!isVectorizableIntrinsic(C))
return false;
} else if (LoadInst *L = dyn_cast<LoadInst>(I)) {
IsSimpleLoadStore = L->isSimple();
if (!IsSimpleLoadStore || NoMemOps)
return false;
} else if (StoreInst *S = dyn_cast<StoreInst>(I)) {
IsSimpleLoadStore = S->isSimple();
if (!IsSimpleLoadStore || NoMemOps)
return false;
} else if (CastInst *C = dyn_cast<CastInst>(I)) {
if (NoCasts)
return false;
Type *SrcTy = C->getSrcTy();
if (!SrcTy->isSingleValueType() || SrcTy->isPointerTy())
return false;
Type *DestTy = C->getDestTy();
if (!DestTy->isSingleValueType() || DestTy->isPointerTy())
return false;
} else if (!(I->isBinaryOp() || isa<ShuffleVectorInst>(I) ||
isa<ExtractElementInst>(I) || isa<InsertElementInst>(I))) {
return false;
}
if (TD == 0 && IsSimpleLoadStore)
return false;
Type *T1, *T2;
if (isa<StoreInst>(I)) {
Value *IVal = cast<StoreInst>(I)->getValueOperand();
T1 = IVal->getType();
} else {
T1 = I->getType();
}
if (I->isCast())
T2 = cast<CastInst>(I)->getSrcTy();
else
T2 = T1;
if (!(VectorType::isValidElementType(T1) || T1->isVectorTy()) ||
!(VectorType::isValidElementType(T2) || T2->isVectorTy()))
return false;
if (NoInts && (T1->isIntOrIntVectorTy() || T2->isIntOrIntVectorTy()))
return false;
if (NoFloats && (T1->isFPOrFPVectorTy() || T2->isFPOrFPVectorTy()))
return false;
if (T1->getPrimitiveSizeInBits() > VectorBits/2 ||
T2->getPrimitiveSizeInBits() > VectorBits/2)
return false;
return true;
}
bool BBVectorize::areInstsCompatible(Instruction *I, Instruction *J,
bool IsSimpleLoadStore) {
DEBUG(if (DebugInstructionExamination) dbgs() << "BBV: looking at " << *I <<
" <-> " << *J << "\n");
LoadInst *LI, *LJ;
StoreInst *SI, *SJ;
if ((LI = dyn_cast<LoadInst>(I)) && (LJ = dyn_cast<LoadInst>(J))) {
if (I->getType() != J->getType())
return false;
if (LI->getPointerOperand()->getType() !=
LJ->getPointerOperand()->getType() ||
LI->isVolatile() != LJ->isVolatile() ||
LI->getOrdering() != LJ->getOrdering() ||
LI->getSynchScope() != LJ->getSynchScope())
return false;
} else if ((SI = dyn_cast<StoreInst>(I)) && (SJ = dyn_cast<StoreInst>(J))) {
if (SI->getValueOperand()->getType() !=
SJ->getValueOperand()->getType() ||
SI->getPointerOperand()->getType() !=
SJ->getPointerOperand()->getType() ||
SI->isVolatile() != SJ->isVolatile() ||
SI->getOrdering() != SJ->getOrdering() ||
SI->getSynchScope() != SJ->getSynchScope())
return false;
} else if (!J->isSameOperationAs(I)) {
return false;
}
if (IsSimpleLoadStore) {
Value *IPtr, *JPtr;
unsigned IAlignment, JAlignment;
int64_t OffsetInElmts = 0;
if (getPairPtrInfo(I, J, IPtr, JPtr, IAlignment, JAlignment,
OffsetInElmts) && abs64(OffsetInElmts) == 1) {
if (AlignedOnly) {
Type *aType = isa<StoreInst>(I) ?
cast<StoreInst>(I)->getValueOperand()->getType() : I->getType();
unsigned BottomAlignment = IAlignment;
if (OffsetInElmts < 0) BottomAlignment = JAlignment;
Type *VType = getVecTypeForPair(aType);
unsigned VecAlignment = TD->getPrefTypeAlignment(VType);
if (BottomAlignment < VecAlignment)
return false;
}
} else {
return false;
}
} else if (isa<ShuffleVectorInst>(I)) {
return isa<Constant>(I->getOperand(2)) &&
isa<Constant>(J->getOperand(2));
}
return true;
}
bool BBVectorize::trackUsesOfI(DenseSet<Value *> &Users,
AliasSetTracker &WriteSet, Instruction *I,
Instruction *J, bool UpdateUsers,
std::multimap<Value *, Value *> *LoadMoveSet) {
bool UsesI = false;
if (Users.count(J))
UsesI = true;
if (!UsesI)
for (User::op_iterator JU = J->op_begin(), JE = J->op_end();
JU != JE; ++JU) {
Value *V = *JU;
if (I == V || Users.count(V)) {
UsesI = true;
break;
}
}
if (!UsesI && J->mayReadFromMemory()) {
if (LoadMoveSet) {
VPIteratorPair JPairRange = LoadMoveSet->equal_range(J);
UsesI = isSecondInIteratorPair<Value*>(I, JPairRange);
} else {
for (AliasSetTracker::iterator W = WriteSet.begin(),
WE = WriteSet.end(); W != WE; ++W) {
if (W->aliasesUnknownInst(J, *AA)) {
UsesI = true;
break;
}
}
}
}
if (UsesI && UpdateUsers) {
if (J->mayWriteToMemory()) WriteSet.add(J);
Users.insert(J);
}
return UsesI;
}
bool BBVectorize::getCandidatePairs(BasicBlock &BB,
BasicBlock::iterator &Start,
std::multimap<Value *, Value *> &CandidatePairs,
std::vector<Value *> &PairableInsts) {
BasicBlock::iterator E = BB.end();
if (Start == E) return false;
bool ShouldContinue = false, IAfterStart = false;
for (BasicBlock::iterator I = Start++; I != E; ++I) {
if (I == Start) IAfterStart = true;
bool IsSimpleLoadStore;
if (!isInstVectorizable(I, IsSimpleLoadStore)) continue;
DenseSet<Value *> Users;
AliasSetTracker WriteSet(*AA);
bool JAfterStart = IAfterStart;
BasicBlock::iterator J = llvm::next(I);
for (unsigned ss = 0; J != E && ss <= SearchLimit; ++J, ++ss) {
if (J == Start) JAfterStart = true;
bool UsesI = trackUsesOfI(Users, WriteSet, I, J, !FastDep);
if (FastDep) {
if (UsesI) break;
} else {
if (UsesI) continue;
}
if (!areInstsCompatible(I, J, IsSimpleLoadStore)) continue;
if (!PairableInsts.size() ||
PairableInsts[PairableInsts.size()-1] != I) {
PairableInsts.push_back(I);
}
CandidatePairs.insert(ValuePair(I, J));
if (JAfterStart) {
Start = llvm::next(J);
IAfterStart = JAfterStart = false;
}
DEBUG(if (DebugCandidateSelection) dbgs() << "BBV: candidate pair "
<< *I << " <-> " << *J << "\n");
if (PairableInsts.size() >= MaxInsts) {
ShouldContinue = true;
break;
}
}
if (ShouldContinue)
break;
}
DEBUG(dbgs() << "BBV: found " << PairableInsts.size()
<< " instructions with candidate pairs\n");
return ShouldContinue;
}
void BBVectorize::computePairsConnectedTo(
std::multimap<Value *, Value *> &CandidatePairs,
std::vector<Value *> &PairableInsts,
std::multimap<ValuePair, ValuePair> &ConnectedPairs,
ValuePair P) {
for (Value::use_iterator I = P.first->use_begin(),
E = P.first->use_end(); I != E; ++I) {
VPIteratorPair IPairRange = CandidatePairs.equal_range(*I);
for (Value::use_iterator J = P.second->use_begin(),
E2 = P.second->use_end(); J != E2; ++J) {
VPIteratorPair JPairRange = CandidatePairs.equal_range(*J);
if (isSecondInIteratorPair<Value*>(*J, IPairRange))
ConnectedPairs.insert(VPPair(P, ValuePair(*I, *J)));
if (isSecondInIteratorPair<Value*>(*I, JPairRange))
ConnectedPairs.insert(VPPair(P, ValuePair(*J, *I)));
}
if (SplatBreaksChain) continue;
for (Value::use_iterator J = P.first->use_begin(); J != E; ++J) {
if (isSecondInIteratorPair<Value*>(*J, IPairRange))
ConnectedPairs.insert(VPPair(P, ValuePair(*I, *J)));
}
}
if (SplatBreaksChain) return;
for (Value::use_iterator I = P.second->use_begin(),
E = P.second->use_end(); I != E; ++I) {
VPIteratorPair IPairRange = CandidatePairs.equal_range(*I);
for (Value::use_iterator J = P.second->use_begin(); J != E; ++J) {
if (isSecondInIteratorPair<Value*>(*J, IPairRange))
ConnectedPairs.insert(VPPair(P, ValuePair(*I, *J)));
}
}
}
void BBVectorize::computeConnectedPairs(
std::multimap<Value *, Value *> &CandidatePairs,
std::vector<Value *> &PairableInsts,
std::multimap<ValuePair, ValuePair> &ConnectedPairs) {
for (std::vector<Value *>::iterator PI = PairableInsts.begin(),
PE = PairableInsts.end(); PI != PE; ++PI) {
VPIteratorPair choiceRange = CandidatePairs.equal_range(*PI);
for (std::multimap<Value *, Value *>::iterator P = choiceRange.first;
P != choiceRange.second; ++P)
computePairsConnectedTo(CandidatePairs, PairableInsts,
ConnectedPairs, *P);
}
DEBUG(dbgs() << "BBV: found " << ConnectedPairs.size()
<< " pair connections.\n");
}
void BBVectorize::buildDepMap(
BasicBlock &BB,
std::multimap<Value *, Value *> &CandidatePairs,
std::vector<Value *> &PairableInsts,
DenseSet<ValuePair> &PairableInstUsers) {
DenseSet<Value *> IsInPair;
for (std::multimap<Value *, Value *>::iterator C = CandidatePairs.begin(),
E = CandidatePairs.end(); C != E; ++C) {
IsInPair.insert(C->first);
IsInPair.insert(C->second);
}
BasicBlock::iterator E = BB.end();
for (BasicBlock::iterator I = BB.getFirstInsertionPt(); I != E; ++I) {
if (IsInPair.find(I) == IsInPair.end()) continue;
DenseSet<Value *> Users;
AliasSetTracker WriteSet(*AA);
for (BasicBlock::iterator J = llvm::next(I); J != E; ++J)
(void) trackUsesOfI(Users, WriteSet, I, J);
for (DenseSet<Value *>::iterator U = Users.begin(), E = Users.end();
U != E; ++U)
PairableInstUsers.insert(ValuePair(I, *U));
}
}
bool BBVectorize::pairsConflict(ValuePair P, ValuePair Q,
DenseSet<ValuePair> &PairableInstUsers,
std::multimap<ValuePair, ValuePair> *PairableInstUserMap) {
bool QUsesP = PairableInstUsers.count(ValuePair(P.first, Q.first)) ||
PairableInstUsers.count(ValuePair(P.first, Q.second)) ||
PairableInstUsers.count(ValuePair(P.second, Q.first)) ||
PairableInstUsers.count(ValuePair(P.second, Q.second));
bool PUsesQ = PairableInstUsers.count(ValuePair(Q.first, P.first)) ||
PairableInstUsers.count(ValuePair(Q.first, P.second)) ||
PairableInstUsers.count(ValuePair(Q.second, P.first)) ||
PairableInstUsers.count(ValuePair(Q.second, P.second));
if (PairableInstUserMap) {
if (PUsesQ) {
VPPIteratorPair QPairRange = PairableInstUserMap->equal_range(Q);
if (!isSecondInIteratorPair(P, QPairRange))
PairableInstUserMap->insert(VPPair(Q, P));
}
if (QUsesP) {
VPPIteratorPair PPairRange = PairableInstUserMap->equal_range(P);
if (!isSecondInIteratorPair(Q, PPairRange))
PairableInstUserMap->insert(VPPair(P, Q));
}
}
return (QUsesP && PUsesQ);
}
bool BBVectorize::pairWillFormCycle(ValuePair P,
std::multimap<ValuePair, ValuePair> &PairableInstUserMap,
DenseSet<ValuePair> &CurrentPairs) {
DEBUG(if (DebugCycleCheck)
dbgs() << "BBV: starting cycle check for : " << *P.first << " <-> "
<< *P.second << "\n");
DenseSet<ValuePair> Visited;
SmallVector<ValuePair, 32> Q;
Q.push_back(P);
do {
ValuePair QTop = Q.pop_back_val();
Visited.insert(QTop);
DEBUG(if (DebugCycleCheck)
dbgs() << "BBV: cycle check visiting: " << *QTop.first << " <-> "
<< *QTop.second << "\n");
VPPIteratorPair QPairRange = PairableInstUserMap.equal_range(QTop);
for (std::multimap<ValuePair, ValuePair>::iterator C = QPairRange.first;
C != QPairRange.second; ++C) {
if (C->second == P) {
DEBUG(dbgs()
<< "BBV: rejected to prevent non-trivial cycle formation: "
<< *C->first.first << " <-> " << *C->first.second << "\n");
return true;
}
if (CurrentPairs.count(C->second) && !Visited.count(C->second))
Q.push_back(C->second);
}
} while (!Q.empty());
return false;
}
void BBVectorize::buildInitialTreeFor(
std::multimap<Value *, Value *> &CandidatePairs,
std::vector<Value *> &PairableInsts,
std::multimap<ValuePair, ValuePair> &ConnectedPairs,
DenseSet<ValuePair> &PairableInstUsers,
DenseMap<Value *, Value *> &ChosenPairs,
DenseMap<ValuePair, size_t> &Tree, ValuePair J) {
SmallVector<ValuePairWithDepth, 32> Q;
Q.push_back(ValuePairWithDepth(J, getDepthFactor(J.first)));
do {
ValuePairWithDepth QTop = Q.back();
bool MoreChildren = false;
size_t MaxChildDepth = QTop.second;
VPPIteratorPair qtRange = ConnectedPairs.equal_range(QTop.first);
for (std::multimap<ValuePair, ValuePair>::iterator k = qtRange.first;
k != qtRange.second; ++k) {
bool IsStillCand = false;
VPIteratorPair checkRange =
CandidatePairs.equal_range(k->second.first);
for (std::multimap<Value *, Value *>::iterator m = checkRange.first;
m != checkRange.second; ++m) {
if (m->second == k->second.second) {
IsStillCand = true;
break;
}
}
if (IsStillCand) {
DenseMap<ValuePair, size_t>::iterator C = Tree.find(k->second);
if (C == Tree.end()) {
size_t d = getDepthFactor(k->second.first);
Q.push_back(ValuePairWithDepth(k->second, QTop.second+d));
MoreChildren = true;
} else {
MaxChildDepth = std::max(MaxChildDepth, C->second);
}
}
}
if (!MoreChildren) {
Tree.insert(ValuePairWithDepth(QTop.first, MaxChildDepth));
Q.pop_back();
}
} while (!Q.empty());
}
void BBVectorize::pruneTreeFor(
std::multimap<Value *, Value *> &CandidatePairs,
std::vector<Value *> &PairableInsts,
std::multimap<ValuePair, ValuePair> &ConnectedPairs,
DenseSet<ValuePair> &PairableInstUsers,
std::multimap<ValuePair, ValuePair> &PairableInstUserMap,
DenseMap<Value *, Value *> &ChosenPairs,
DenseMap<ValuePair, size_t> &Tree,
DenseSet<ValuePair> &PrunedTree, ValuePair J,
bool UseCycleCheck) {
SmallVector<ValuePairWithDepth, 32> Q;
Q.push_back(ValuePairWithDepth(J, getDepthFactor(J.first)));
do {
ValuePairWithDepth QTop = Q.pop_back_val();
PrunedTree.insert(QTop.first);
DenseMap<ValuePair, size_t> BestChilden;
VPPIteratorPair QTopRange = ConnectedPairs.equal_range(QTop.first);
for (std::multimap<ValuePair, ValuePair>::iterator K = QTopRange.first;
K != QTopRange.second; ++K) {
DenseMap<ValuePair, size_t>::iterator C = Tree.find(K->second);
if (C == Tree.end()) continue;
DenseSet<ValuePair> CurrentPairs;
bool CanAdd = true;
for (DenseMap<ValuePair, size_t>::iterator C2
= BestChilden.begin(), E2 = BestChilden.end();
C2 != E2; ++C2) {
if (C2->first.first == C->first.first ||
C2->first.first == C->first.second ||
C2->first.second == C->first.first ||
C2->first.second == C->first.second ||
pairsConflict(C2->first, C->first, PairableInstUsers,
UseCycleCheck ? &PairableInstUserMap : 0)) {
if (C2->second >= C->second) {
CanAdd = false;
break;
}
CurrentPairs.insert(C2->first);
}
}
if (!CanAdd) continue;
for (DenseSet<ValuePair>::iterator T = PrunedTree.begin(),
E2 = PrunedTree.end(); T != E2; ++T) {
if (T->first == C->first.first ||
T->first == C->first.second ||
T->second == C->first.first ||
T->second == C->first.second ||
pairsConflict(*T, C->first, PairableInstUsers,
UseCycleCheck ? &PairableInstUserMap : 0)) {
CanAdd = false;
break;
}
CurrentPairs.insert(*T);
}
if (!CanAdd) continue;
for (SmallVector<ValuePairWithDepth, 32>::iterator C2 = Q.begin(),
E2 = Q.end(); C2 != E2; ++C2) {
if (C2->first.first == C->first.first ||
C2->first.first == C->first.second ||
C2->first.second == C->first.first ||
C2->first.second == C->first.second ||
pairsConflict(C2->first, C->first, PairableInstUsers,
UseCycleCheck ? &PairableInstUserMap : 0)) {
CanAdd = false;
break;
}
CurrentPairs.insert(C2->first);
}
if (!CanAdd) continue;
for (DenseMap<Value *, Value *>::iterator C2 =
ChosenPairs.begin(), E2 = ChosenPairs.end();
C2 != E2; ++C2) {
if (pairsConflict(*C2, C->first, PairableInstUsers,
UseCycleCheck ? &PairableInstUserMap : 0)) {
CanAdd = false;
break;
}
CurrentPairs.insert(*C2);
}
if (!CanAdd) continue;
if (UseCycleCheck &&
pairWillFormCycle(C->first, PairableInstUserMap, CurrentPairs))
continue;
for (DenseMap<ValuePair, size_t>::iterator C2
= BestChilden.begin(); C2 != BestChilden.end();) {
if (C2->first.first == C->first.first ||
C2->first.first == C->first.second ||
C2->first.second == C->first.first ||
C2->first.second == C->first.second ||
pairsConflict(C2->first, C->first, PairableInstUsers))
BestChilden.erase(C2++);
else
++C2;
}
BestChilden.insert(ValuePairWithDepth(C->first, C->second));
}
for (DenseMap<ValuePair, size_t>::iterator C
= BestChilden.begin(), E2 = BestChilden.end();
C != E2; ++C) {
size_t DepthF = getDepthFactor(C->first.first);
Q.push_back(ValuePairWithDepth(C->first, QTop.second+DepthF));
}
} while (!Q.empty());
}
void BBVectorize::findBestTreeFor(
std::multimap<Value *, Value *> &CandidatePairs,
std::vector<Value *> &PairableInsts,
std::multimap<ValuePair, ValuePair> &ConnectedPairs,
DenseSet<ValuePair> &PairableInstUsers,
std::multimap<ValuePair, ValuePair> &PairableInstUserMap,
DenseMap<Value *, Value *> &ChosenPairs,
DenseSet<ValuePair> &BestTree, size_t &BestMaxDepth,
size_t &BestEffSize, VPIteratorPair ChoiceRange,
bool UseCycleCheck) {
for (std::multimap<Value *, Value *>::iterator J = ChoiceRange.first;
J != ChoiceRange.second; ++J) {
DenseSet<ValuePair> ChosenPairSet;
bool DoesConflict = false;
for (DenseMap<Value *, Value *>::iterator C = ChosenPairs.begin(),
E = ChosenPairs.end(); C != E; ++C) {
if (pairsConflict(*C, *J, PairableInstUsers,
UseCycleCheck ? &PairableInstUserMap : 0)) {
DoesConflict = true;
break;
}
ChosenPairSet.insert(*C);
}
if (DoesConflict) continue;
if (UseCycleCheck &&
pairWillFormCycle(*J, PairableInstUserMap, ChosenPairSet))
continue;
DenseMap<ValuePair, size_t> Tree;
buildInitialTreeFor(CandidatePairs, PairableInsts, ConnectedPairs,
PairableInstUsers, ChosenPairs, Tree, *J);
size_t MaxDepth = Tree.lookup(*J);
DEBUG(if (DebugPairSelection) dbgs() << "BBV: found Tree for pair {"
<< *J->first << " <-> " << *J->second << "} of depth " <<
MaxDepth << " and size " << Tree.size() << "\n");
DenseSet<ValuePair> PrunedTree;
pruneTreeFor(CandidatePairs, PairableInsts, ConnectedPairs,
PairableInstUsers, PairableInstUserMap, ChosenPairs, Tree,
PrunedTree, *J, UseCycleCheck);
size_t EffSize = 0;
for (DenseSet<ValuePair>::iterator S = PrunedTree.begin(),
E = PrunedTree.end(); S != E; ++S)
EffSize += getDepthFactor(S->first);
DEBUG(if (DebugPairSelection)
dbgs() << "BBV: found pruned Tree for pair {"
<< *J->first << " <-> " << *J->second << "} of depth " <<
MaxDepth << " and size " << PrunedTree.size() <<
" (effective size: " << EffSize << ")\n");
if (MaxDepth >= ReqChainDepth && EffSize > BestEffSize) {
BestMaxDepth = MaxDepth;
BestEffSize = EffSize;
BestTree = PrunedTree;
}
}
}
void BBVectorize::choosePairs(
std::multimap<Value *, Value *> &CandidatePairs,
std::vector<Value *> &PairableInsts,
std::multimap<ValuePair, ValuePair> &ConnectedPairs,
DenseSet<ValuePair> &PairableInstUsers,
DenseMap<Value *, Value *>& ChosenPairs) {
bool UseCycleCheck = CandidatePairs.size() <= MaxCandPairsForCycleCheck;
std::multimap<ValuePair, ValuePair> PairableInstUserMap;
for (std::vector<Value *>::iterator I = PairableInsts.begin(),
E = PairableInsts.end(); I != E; ++I) {
size_t NumChoices = CandidatePairs.count(*I);
if (!NumChoices) continue;
VPIteratorPair ChoiceRange = CandidatePairs.equal_range(*I);
size_t BestMaxDepth = 0, BestEffSize = 0;
DenseSet<ValuePair> BestTree;
findBestTreeFor(CandidatePairs, PairableInsts, ConnectedPairs,
PairableInstUsers, PairableInstUserMap, ChosenPairs,
BestTree, BestMaxDepth, BestEffSize, ChoiceRange,
UseCycleCheck);
DEBUG(if (BestTree.size() > 0)
dbgs() << "BBV: selected pairs in the best tree for: "
<< *cast<Instruction>(*I) << "\n");
for (DenseSet<ValuePair>::iterator S = BestTree.begin(),
SE2 = BestTree.end(); S != SE2; ++S) {
ChosenPairs.insert(ValuePair(S->first, S->second));
DEBUG(dbgs() << "BBV: selected pair: " << *S->first << " <-> " <<
*S->second << "\n");
for (std::multimap<Value *, Value *>::iterator K =
CandidatePairs.begin(); K != CandidatePairs.end();) {
if (K->first == S->first || K->second == S->first ||
K->second == S->second || K->first == S->second) {
if (!(K->first == S->first && K->second == S->second))
CandidatePairs.erase(K++);
else
++K;
} else {
++K;
}
}
}
}
DEBUG(dbgs() << "BBV: selected " << ChosenPairs.size() << " pairs.\n");
}
std::string getReplacementName(Instruction *I, bool IsInput, unsigned o,
unsigned n = 0) {
if (!I->hasName())
return "";
return (I->getName() + (IsInput ? ".v.i" : ".v.r") + utostr(o) +
(n > 0 ? "." + utostr(n) : "")).str();
}
Value *BBVectorize::getReplacementPointerInput(LLVMContext& Context,
Instruction *I, Instruction *J, unsigned o,
bool &FlipMemInputs) {
Value *IPtr, *JPtr;
unsigned IAlignment, JAlignment;
int64_t OffsetInElmts;
(void) getPairPtrInfo(I, J, IPtr, JPtr, IAlignment, JAlignment,
OffsetInElmts);
Value *VPtr;
if (OffsetInElmts > 0) {
VPtr = IPtr;
} else {
FlipMemInputs = true;
VPtr = JPtr;
}
Type *ArgType = cast<PointerType>(IPtr->getType())->getElementType();
Type *VArgType = getVecTypeForPair(ArgType);
Type *VArgPtrType = PointerType::get(VArgType,
cast<PointerType>(IPtr->getType())->getAddressSpace());
return new BitCastInst(VPtr, VArgPtrType, getReplacementName(I, true, o),
FlipMemInputs ? J : I);
}
void BBVectorize::fillNewShuffleMask(LLVMContext& Context, Instruction *J,
unsigned NumElem, unsigned MaskOffset, unsigned NumInElem,
unsigned IdxOffset, std::vector<Constant*> &Mask) {
for (unsigned v = 0; v < NumElem/2; ++v) {
int m = cast<ShuffleVectorInst>(J)->getMaskValue(v);
if (m < 0) {
Mask[v+MaskOffset] = UndefValue::get(Type::getInt32Ty(Context));
} else {
unsigned mm = m + (int) IdxOffset;
if (m >= (int) NumInElem)
mm += (int) NumInElem;
Mask[v+MaskOffset] =
ConstantInt::get(Type::getInt32Ty(Context), mm);
}
}
}
Value *BBVectorize::getReplacementShuffleMask(LLVMContext& Context,
Instruction *I, Instruction *J) {
Type *ArgType = I->getType();
Type *VArgType = getVecTypeForPair(ArgType);
unsigned NumElem = cast<VectorType>(VArgType)->getNumElements();
std::vector<Constant*> Mask(NumElem);
Type *OpType = I->getOperand(0)->getType();
unsigned NumInElem = cast<VectorType>(OpType)->getNumElements();
fillNewShuffleMask(Context, I, NumElem, 0, NumInElem, 0, Mask);
fillNewShuffleMask(Context, J, NumElem, NumElem/2, NumInElem, NumInElem,
Mask);
return ConstantVector::get(Mask);
}
Value *BBVectorize::getReplacementInput(LLVMContext& Context, Instruction *I,
Instruction *J, unsigned o, bool FlipMemInputs) {
Value *CV0 = ConstantInt::get(Type::getInt32Ty(Context), 0);
Value *CV1 = ConstantInt::get(Type::getInt32Ty(Context), 1);
Type *ArgType = I->getOperand(o)->getType();
VectorType *VArgType = getVecTypeForPair(ArgType);
Instruction *L = I, *H = J;
if (FlipMemInputs) {
L = J;
H = I;
}
if (ArgType->isVectorTy()) {
unsigned numElem = cast<VectorType>(VArgType)->getNumElements();
std::vector<Constant*> Mask(numElem);
for (unsigned v = 0; v < numElem; ++v)
Mask[v] = ConstantInt::get(Type::getInt32Ty(Context), v);
Instruction *BV = new ShuffleVectorInst(L->getOperand(o),
H->getOperand(o),
ConstantVector::get(Mask),
getReplacementName(I, true, o));
BV->insertBefore(J);
return BV;
}
ExtractElementInst *LEE
= dyn_cast<ExtractElementInst>(L->getOperand(o));
ExtractElementInst *HEE
= dyn_cast<ExtractElementInst>(H->getOperand(o));
if (LEE && HEE &&
LEE->getOperand(0)->getType() == HEE->getOperand(0)->getType()) {
VectorType *EEType = cast<VectorType>(LEE->getOperand(0)->getType());
unsigned LowIndx = cast<ConstantInt>(LEE->getOperand(1))->getZExtValue();
unsigned HighIndx = cast<ConstantInt>(HEE->getOperand(1))->getZExtValue();
if (LEE->getOperand(0) == HEE->getOperand(0)) {
if (LowIndx == 0 && HighIndx == 1)
return LEE->getOperand(0);
std::vector<Constant*> Mask(2);
Mask[0] = ConstantInt::get(Type::getInt32Ty(Context), LowIndx);
Mask[1] = ConstantInt::get(Type::getInt32Ty(Context), HighIndx);
Instruction *BV = new ShuffleVectorInst(LEE->getOperand(0),
UndefValue::get(EEType),
ConstantVector::get(Mask),
getReplacementName(I, true, o));
BV->insertBefore(J);
return BV;
}
std::vector<Constant*> Mask(2);
HighIndx += EEType->getNumElements();
Mask[0] = ConstantInt::get(Type::getInt32Ty(Context), LowIndx);
Mask[1] = ConstantInt::get(Type::getInt32Ty(Context), HighIndx);
Instruction *BV = new ShuffleVectorInst(LEE->getOperand(0),
HEE->getOperand(0),
ConstantVector::get(Mask),
getReplacementName(I, true, o));
BV->insertBefore(J);
return BV;
}
Instruction *BV1 = InsertElementInst::Create(
UndefValue::get(VArgType),
L->getOperand(o), CV0,
getReplacementName(I, true, o, 1));
BV1->insertBefore(I);
Instruction *BV2 = InsertElementInst::Create(BV1, H->getOperand(o),
CV1,
getReplacementName(I, true, o, 2));
BV2->insertBefore(J);
return BV2;
}
void BBVectorize::getReplacementInputsForPair(LLVMContext& Context,
Instruction *I, Instruction *J,
SmallVector<Value *, 3> &ReplacedOperands,
bool &FlipMemInputs) {
FlipMemInputs = false;
unsigned NumOperands = I->getNumOperands();
for (unsigned p = 0, o = NumOperands-1; p < NumOperands; ++p, --o) {
if (isa<LoadInst>(I) || (o == 1 && isa<StoreInst>(I))) {
ReplacedOperands[o] = getReplacementPointerInput(Context, I, J, o,
FlipMemInputs);
continue;
} else if (isa<CallInst>(I) && o == NumOperands-1) {
Function *F = cast<CallInst>(I)->getCalledFunction();
unsigned IID = F->getIntrinsicID();
BasicBlock &BB = *I->getParent();
Module *M = BB.getParent()->getParent();
Type *ArgType = I->getType();
Type *VArgType = getVecTypeForPair(ArgType);
ReplacedOperands[o] = Intrinsic::getDeclaration(M,
(Intrinsic::ID) IID, VArgType);
continue;
} else if (isa<ShuffleVectorInst>(I) && o == NumOperands-1) {
ReplacedOperands[o] = getReplacementShuffleMask(Context, I, J);
continue;
}
ReplacedOperands[o] =
getReplacementInput(Context, I, J, o, FlipMemInputs);
}
}
void BBVectorize::replaceOutputsOfPair(LLVMContext& Context, Instruction *I,
Instruction *J, Instruction *K,
Instruction *&InsertionPt,
Instruction *&K1, Instruction *&K2,
bool &FlipMemInputs) {
Value *CV0 = ConstantInt::get(Type::getInt32Ty(Context), 0);
Value *CV1 = ConstantInt::get(Type::getInt32Ty(Context), 1);
if (isa<StoreInst>(I)) {
AA->replaceWithNewValue(I, K);
AA->replaceWithNewValue(J, K);
} else {
Type *IType = I->getType();
Type *VType = getVecTypeForPair(IType);
if (IType->isVectorTy()) {
unsigned numElem = cast<VectorType>(IType)->getNumElements();
std::vector<Constant*> Mask1(numElem), Mask2(numElem);
for (unsigned v = 0; v < numElem; ++v) {
Mask1[v] = ConstantInt::get(Type::getInt32Ty(Context), v);
Mask2[v] = ConstantInt::get(Type::getInt32Ty(Context), numElem+v);
}
K1 = new ShuffleVectorInst(K, UndefValue::get(VType),
ConstantVector::get(
FlipMemInputs ? Mask2 : Mask1),
getReplacementName(K, false, 1));
K2 = new ShuffleVectorInst(K, UndefValue::get(VType),
ConstantVector::get(
FlipMemInputs ? Mask1 : Mask2),
getReplacementName(K, false, 2));
} else {
K1 = ExtractElementInst::Create(K, FlipMemInputs ? CV1 : CV0,
getReplacementName(K, false, 1));
K2 = ExtractElementInst::Create(K, FlipMemInputs ? CV0 : CV1,
getReplacementName(K, false, 2));
}
K1->insertAfter(K);
K2->insertAfter(K1);
InsertionPt = K2;
}
}
bool BBVectorize::canMoveUsesOfIAfterJ(BasicBlock &BB,
std::multimap<Value *, Value *> &LoadMoveSet,
Instruction *I, Instruction *J) {
BasicBlock::iterator L = llvm::next(BasicBlock::iterator(I));
DenseSet<Value *> Users;
AliasSetTracker WriteSet(*AA);
for (; cast<Instruction>(L) != J; ++L)
(void) trackUsesOfI(Users, WriteSet, I, L, true, &LoadMoveSet);
assert(cast<Instruction>(L) == J &&
"Tracking has not proceeded far enough to check for dependencies");
return !trackUsesOfI(Users, WriteSet, I, J, true, &LoadMoveSet);
}
void BBVectorize::moveUsesOfIAfterJ(BasicBlock &BB,
std::multimap<Value *, Value *> &LoadMoveSet,
Instruction *&InsertionPt,
Instruction *I, Instruction *J) {
BasicBlock::iterator L = llvm::next(BasicBlock::iterator(I));
DenseSet<Value *> Users;
AliasSetTracker WriteSet(*AA);
for (; cast<Instruction>(L) != J;) {
if (trackUsesOfI(Users, WriteSet, I, L, true, &LoadMoveSet)) {
Instruction *InstToMove = L; ++L;
DEBUG(dbgs() << "BBV: moving: " << *InstToMove <<
" to after " << *InsertionPt << "\n");
InstToMove->removeFromParent();
InstToMove->insertAfter(InsertionPt);
InsertionPt = InstToMove;
} else {
++L;
}
}
}
void BBVectorize::collectPairLoadMoveSet(BasicBlock &BB,
DenseMap<Value *, Value *> &ChosenPairs,
std::multimap<Value *, Value *> &LoadMoveSet,
Instruction *I) {
BasicBlock::iterator L = llvm::next(BasicBlock::iterator(I));
DenseSet<Value *> Users;
AliasSetTracker WriteSet(*AA);
for (BasicBlock::iterator E = BB.end(); cast<Instruction>(L) != E; ++L) {
if (trackUsesOfI(Users, WriteSet, I, L)) {
if (L->mayReadFromMemory())
LoadMoveSet.insert(ValuePair(L, I));
}
}
}
void BBVectorize::collectLoadMoveSet(BasicBlock &BB,
std::vector<Value *> &PairableInsts,
DenseMap<Value *, Value *> &ChosenPairs,
std::multimap<Value *, Value *> &LoadMoveSet) {
for (std::vector<Value *>::iterator PI = PairableInsts.begin(),
PIE = PairableInsts.end(); PI != PIE; ++PI) {
DenseMap<Value *, Value *>::iterator P = ChosenPairs.find(*PI);
if (P == ChosenPairs.end()) continue;
Instruction *I = cast<Instruction>(P->first);
collectPairLoadMoveSet(BB, ChosenPairs, LoadMoveSet, I);
}
}
void BBVectorize::fuseChosenPairs(BasicBlock &BB,
std::vector<Value *> &PairableInsts,
DenseMap<Value *, Value *> &ChosenPairs) {
LLVMContext& Context = BB.getContext();
std::vector<ValuePair> FlippedPairs;
FlippedPairs.reserve(ChosenPairs.size());
for (DenseMap<Value *, Value *>::iterator P = ChosenPairs.begin(),
E = ChosenPairs.end(); P != E; ++P)
FlippedPairs.push_back(ValuePair(P->second, P->first));
for (std::vector<ValuePair>::iterator P = FlippedPairs.begin(),
E = FlippedPairs.end(); P != E; ++P)
ChosenPairs.insert(*P);
std::multimap<Value *, Value *> LoadMoveSet;
collectLoadMoveSet(BB, PairableInsts, ChosenPairs, LoadMoveSet);
DEBUG(dbgs() << "BBV: initial: \n" << BB << "\n");
for (BasicBlock::iterator PI = BB.getFirstInsertionPt(); PI != BB.end();) {
DenseMap<Value *, Value *>::iterator P = ChosenPairs.find(PI);
if (P == ChosenPairs.end()) {
++PI;
continue;
}
if (getDepthFactor(P->first) == 0) {
--NumFusedOps;
++PI;
continue;
}
Instruction *I = cast<Instruction>(P->first),
*J = cast<Instruction>(P->second);
DEBUG(dbgs() << "BBV: fusing: " << *I <<
" <-> " << *J << "\n");
DenseMap<Value *, Value *>::iterator FP = ChosenPairs.find(P->second);
assert(FP != ChosenPairs.end() && "Flipped pair not found in list");
ChosenPairs.erase(FP);
ChosenPairs.erase(P);
if (!canMoveUsesOfIAfterJ(BB, LoadMoveSet, I, J)) {
DEBUG(dbgs() << "BBV: fusion of: " << *I <<
" <-> " << *J <<
" aborted because of non-trivial dependency cycle\n");
--NumFusedOps;
++PI;
continue;
}
bool FlipMemInputs;
unsigned NumOperands = I->getNumOperands();
SmallVector<Value *, 3> ReplacedOperands(NumOperands);
getReplacementInputsForPair(Context, I, J, ReplacedOperands,
FlipMemInputs);
Instruction *K = I->clone();
if (I->hasName()) K->takeName(I);
if (!isa<StoreInst>(K))
K->mutateType(getVecTypeForPair(I->getType()));
for (unsigned o = 0; o < NumOperands; ++o)
K->setOperand(o, ReplacedOperands[o]);
if (FlipMemInputs) {
if (isa<StoreInst>(K))
cast<StoreInst>(K)->setAlignment(cast<StoreInst>(J)->getAlignment());
else
cast<LoadInst>(K)->setAlignment(cast<LoadInst>(J)->getAlignment());
}
K->insertAfter(J);
Instruction *InsertionPt = K;
Instruction *K1 = 0, *K2 = 0;
replaceOutputsOfPair(Context, I, J, K, InsertionPt, K1, K2,
FlipMemInputs);
moveUsesOfIAfterJ(BB, LoadMoveSet, InsertionPt, I, J);
if (!isa<StoreInst>(I)) {
I->replaceAllUsesWith(K1);
J->replaceAllUsesWith(K2);
AA->replaceWithNewValue(I, K1);
AA->replaceWithNewValue(J, K2);
}
if (I->mayReadFromMemory()) {
std::vector<ValuePair> NewSetMembers;
VPIteratorPair IPairRange = LoadMoveSet.equal_range(I);
VPIteratorPair JPairRange = LoadMoveSet.equal_range(J);
for (std::multimap<Value *, Value *>::iterator N = IPairRange.first;
N != IPairRange.second; ++N)
NewSetMembers.push_back(ValuePair(K, N->second));
for (std::multimap<Value *, Value *>::iterator N = JPairRange.first;
N != JPairRange.second; ++N)
NewSetMembers.push_back(ValuePair(K, N->second));
for (std::vector<ValuePair>::iterator A = NewSetMembers.begin(),
AE = NewSetMembers.end(); A != AE; ++A)
LoadMoveSet.insert(*A);
}
PI = llvm::next(BasicBlock::iterator(I));
if (cast<Instruction>(PI) == J)
++PI;
SE->forgetValue(I);
SE->forgetValue(J);
I->eraseFromParent();
J->eraseFromParent();
}
DEBUG(dbgs() << "BBV: final: \n" << BB << "\n");
}
}
char BBVectorize::ID = 0;
static const char bb_vectorize_name[] = "Basic-Block Vectorization";
INITIALIZE_PASS_BEGIN(BBVectorize, BBV_NAME, bb_vectorize_name, false, false)
INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
INITIALIZE_PASS_END(BBVectorize, BBV_NAME, bb_vectorize_name, false, false)
BasicBlockPass *llvm::createBBVectorizePass() {
return new BBVectorize();
}