1e8d8bef9SDimitry Andric //===-- HexagonVectorCombine.cpp ------------------------------------------===// 2e8d8bef9SDimitry Andric // 3e8d8bef9SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4e8d8bef9SDimitry Andric // See https://llvm.org/LICENSE.txt for license information. 5e8d8bef9SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6e8d8bef9SDimitry Andric // 7e8d8bef9SDimitry Andric //===----------------------------------------------------------------------===// 8e8d8bef9SDimitry Andric // HexagonVectorCombine is a utility class implementing a variety of functions 9e8d8bef9SDimitry Andric // that assist in vector-based optimizations. 10e8d8bef9SDimitry Andric // 11e8d8bef9SDimitry Andric // AlignVectors: replace unaligned vector loads and stores with aligned ones. 1206c3fb27SDimitry Andric // HvxIdioms: recognize various opportunities to generate HVX intrinsic code. 13e8d8bef9SDimitry Andric //===----------------------------------------------------------------------===// 14e8d8bef9SDimitry Andric 15e8d8bef9SDimitry Andric #include "llvm/ADT/APInt.h" 16e8d8bef9SDimitry Andric #include "llvm/ADT/ArrayRef.h" 17e8d8bef9SDimitry Andric #include "llvm/ADT/DenseMap.h" 18e8d8bef9SDimitry Andric #include "llvm/ADT/STLExtras.h" 19e8d8bef9SDimitry Andric #include "llvm/ADT/SmallVector.h" 20e8d8bef9SDimitry Andric #include "llvm/Analysis/AliasAnalysis.h" 21e8d8bef9SDimitry Andric #include "llvm/Analysis/AssumptionCache.h" 22bdd1243dSDimitry Andric #include "llvm/Analysis/InstSimplifyFolder.h" 23e8d8bef9SDimitry Andric #include "llvm/Analysis/InstructionSimplify.h" 2406c3fb27SDimitry Andric #include "llvm/Analysis/ScalarEvolution.h" 25e8d8bef9SDimitry Andric #include "llvm/Analysis/TargetLibraryInfo.h" 26e8d8bef9SDimitry Andric #include "llvm/Analysis/ValueTracking.h" 27fe6060f1SDimitry Andric #include "llvm/Analysis/VectorUtils.h" 28e8d8bef9SDimitry Andric #include "llvm/CodeGen/TargetPassConfig.h" 29bdd1243dSDimitry Andric #include "llvm/CodeGen/ValueTypes.h" 30e8d8bef9SDimitry Andric #include "llvm/IR/Dominators.h" 31e8d8bef9SDimitry Andric #include "llvm/IR/IRBuilder.h" 32e8d8bef9SDimitry Andric #include "llvm/IR/IntrinsicInst.h" 33e8d8bef9SDimitry Andric #include "llvm/IR/Intrinsics.h" 34e8d8bef9SDimitry Andric #include "llvm/IR/IntrinsicsHexagon.h" 35fe6060f1SDimitry Andric #include "llvm/IR/Metadata.h" 36bdd1243dSDimitry Andric #include "llvm/IR/PatternMatch.h" 37e8d8bef9SDimitry Andric #include "llvm/InitializePasses.h" 38e8d8bef9SDimitry Andric #include "llvm/Pass.h" 3906c3fb27SDimitry Andric #include "llvm/Support/CommandLine.h" 40e8d8bef9SDimitry Andric #include "llvm/Support/KnownBits.h" 41e8d8bef9SDimitry Andric #include "llvm/Support/MathExtras.h" 42e8d8bef9SDimitry Andric #include "llvm/Support/raw_ostream.h" 43e8d8bef9SDimitry Andric #include "llvm/Target/TargetMachine.h" 44bdd1243dSDimitry Andric #include "llvm/Transforms/Utils/Local.h" 45e8d8bef9SDimitry Andric 46e8d8bef9SDimitry Andric #include "HexagonSubtarget.h" 47e8d8bef9SDimitry Andric #include "HexagonTargetMachine.h" 48e8d8bef9SDimitry Andric 49e8d8bef9SDimitry Andric #include <algorithm> 50e8d8bef9SDimitry Andric #include <deque> 51e8d8bef9SDimitry Andric #include <map> 52bdd1243dSDimitry Andric #include <optional> 53e8d8bef9SDimitry Andric #include <set> 54e8d8bef9SDimitry Andric #include <utility> 55e8d8bef9SDimitry Andric #include <vector> 56e8d8bef9SDimitry Andric 57e8d8bef9SDimitry Andric #define DEBUG_TYPE "hexagon-vc" 58e8d8bef9SDimitry Andric 59e8d8bef9SDimitry Andric using namespace llvm; 60e8d8bef9SDimitry Andric 61e8d8bef9SDimitry Andric namespace { 6206c3fb27SDimitry Andric cl::opt<bool> DumpModule("hvc-dump-module", cl::Hidden); 6306c3fb27SDimitry Andric cl::opt<bool> VAEnabled("hvc-va", cl::Hidden, cl::init(true)); // Align 6406c3fb27SDimitry Andric cl::opt<bool> VIEnabled("hvc-vi", cl::Hidden, cl::init(true)); // Idioms 6506c3fb27SDimitry Andric cl::opt<bool> VADoFullStores("hvc-va-full-stores", cl::Hidden); 6606c3fb27SDimitry Andric 6706c3fb27SDimitry Andric cl::opt<unsigned> VAGroupCountLimit("hvc-va-group-count-limit", cl::Hidden, 6806c3fb27SDimitry Andric cl::init(~0)); 6906c3fb27SDimitry Andric cl::opt<unsigned> VAGroupSizeLimit("hvc-va-group-size-limit", cl::Hidden, 7006c3fb27SDimitry Andric cl::init(~0)); 7106c3fb27SDimitry Andric 72e8d8bef9SDimitry Andric class HexagonVectorCombine { 73e8d8bef9SDimitry Andric public: 74e8d8bef9SDimitry Andric HexagonVectorCombine(Function &F_, AliasAnalysis &AA_, AssumptionCache &AC_, 7506c3fb27SDimitry Andric DominatorTree &DT_, ScalarEvolution &SE_, 7606c3fb27SDimitry Andric TargetLibraryInfo &TLI_, const TargetMachine &TM_) 77*0fca6ea1SDimitry Andric : F(F_), DL(F.getDataLayout()), AA(AA_), AC(AC_), DT(DT_), 7806c3fb27SDimitry Andric SE(SE_), TLI(TLI_), 79e8d8bef9SDimitry Andric HST(static_cast<const HexagonSubtarget &>(*TM_.getSubtargetImpl(F))) {} 80e8d8bef9SDimitry Andric 81e8d8bef9SDimitry Andric bool run(); 82e8d8bef9SDimitry Andric 83e8d8bef9SDimitry Andric // Common integer type. 84bdd1243dSDimitry Andric IntegerType *getIntTy(unsigned Width = 32) const; 85e8d8bef9SDimitry Andric // Byte type: either scalar (when Length = 0), or vector with given 86e8d8bef9SDimitry Andric // element count. 87e8d8bef9SDimitry Andric Type *getByteTy(int ElemCount = 0) const; 88e8d8bef9SDimitry Andric // Boolean type: either scalar (when Length = 0), or vector with given 89e8d8bef9SDimitry Andric // element count. 90e8d8bef9SDimitry Andric Type *getBoolTy(int ElemCount = 0) const; 91e8d8bef9SDimitry Andric // Create a ConstantInt of type returned by getIntTy with the value Val. 92bdd1243dSDimitry Andric ConstantInt *getConstInt(int Val, unsigned Width = 32) const; 93e8d8bef9SDimitry Andric // Get the integer value of V, if it exists. 94bdd1243dSDimitry Andric std::optional<APInt> getIntValue(const Value *Val) const; 9506c3fb27SDimitry Andric // Is Val a constant 0, or a vector of 0s? 96e8d8bef9SDimitry Andric bool isZero(const Value *Val) const; 9706c3fb27SDimitry Andric // Is Val an undef value? 98e8d8bef9SDimitry Andric bool isUndef(const Value *Val) const; 9906c3fb27SDimitry Andric // Is Val a scalar (i1 true) or a vector of (i1 true)? 10006c3fb27SDimitry Andric bool isTrue(const Value *Val) const; 10106c3fb27SDimitry Andric // Is Val a scalar (i1 false) or a vector of (i1 false)? 10206c3fb27SDimitry Andric bool isFalse(const Value *Val) const; 103e8d8bef9SDimitry Andric 104bdd1243dSDimitry Andric // Get HVX vector type with the given element type. 105bdd1243dSDimitry Andric VectorType *getHvxTy(Type *ElemTy, bool Pair = false) const; 106bdd1243dSDimitry Andric 107bdd1243dSDimitry Andric enum SizeKind { 108bdd1243dSDimitry Andric Store, // Store size 109bdd1243dSDimitry Andric Alloc, // Alloc size 110bdd1243dSDimitry Andric }; 111bdd1243dSDimitry Andric int getSizeOf(const Value *Val, SizeKind Kind = Store) const; 112bdd1243dSDimitry Andric int getSizeOf(const Type *Ty, SizeKind Kind = Store) const; 113e8d8bef9SDimitry Andric int getTypeAlignment(Type *Ty) const; 114bdd1243dSDimitry Andric size_t length(Value *Val) const; 115bdd1243dSDimitry Andric size_t length(Type *Ty) const; 116e8d8bef9SDimitry Andric 117e8d8bef9SDimitry Andric Constant *getNullValue(Type *Ty) const; 118e8d8bef9SDimitry Andric Constant *getFullValue(Type *Ty) const; 119bdd1243dSDimitry Andric Constant *getConstSplat(Type *Ty, int Val) const; 120e8d8bef9SDimitry Andric 121bdd1243dSDimitry Andric Value *simplify(Value *Val) const; 122bdd1243dSDimitry Andric 123bdd1243dSDimitry Andric Value *insertb(IRBuilderBase &Builder, Value *Dest, Value *Src, int Start, 124e8d8bef9SDimitry Andric int Length, int Where) const; 125bdd1243dSDimitry Andric Value *vlalignb(IRBuilderBase &Builder, Value *Lo, Value *Hi, 126bdd1243dSDimitry Andric Value *Amt) const; 127bdd1243dSDimitry Andric Value *vralignb(IRBuilderBase &Builder, Value *Lo, Value *Hi, 128bdd1243dSDimitry Andric Value *Amt) const; 129bdd1243dSDimitry Andric Value *concat(IRBuilderBase &Builder, ArrayRef<Value *> Vecs) const; 130bdd1243dSDimitry Andric Value *vresize(IRBuilderBase &Builder, Value *Val, int NewSize, 131e8d8bef9SDimitry Andric Value *Pad) const; 132bdd1243dSDimitry Andric Value *rescale(IRBuilderBase &Builder, Value *Mask, Type *FromTy, 133e8d8bef9SDimitry Andric Type *ToTy) const; 134bdd1243dSDimitry Andric Value *vlsb(IRBuilderBase &Builder, Value *Val) const; 135bdd1243dSDimitry Andric Value *vbytes(IRBuilderBase &Builder, Value *Val) const; 136bdd1243dSDimitry Andric Value *subvector(IRBuilderBase &Builder, Value *Val, unsigned Start, 137bdd1243dSDimitry Andric unsigned Length) const; 138bdd1243dSDimitry Andric Value *sublo(IRBuilderBase &Builder, Value *Val) const; 139bdd1243dSDimitry Andric Value *subhi(IRBuilderBase &Builder, Value *Val) const; 140bdd1243dSDimitry Andric Value *vdeal(IRBuilderBase &Builder, Value *Val0, Value *Val1) const; 141bdd1243dSDimitry Andric Value *vshuff(IRBuilderBase &Builder, Value *Val0, Value *Val1) const; 142e8d8bef9SDimitry Andric 143bdd1243dSDimitry Andric Value *createHvxIntrinsic(IRBuilderBase &Builder, Intrinsic::ID IntID, 144bdd1243dSDimitry Andric Type *RetTy, ArrayRef<Value *> Args, 14506c3fb27SDimitry Andric ArrayRef<Type *> ArgTys = std::nullopt, 14606c3fb27SDimitry Andric ArrayRef<Value *> MDSources = std::nullopt) const; 147bdd1243dSDimitry Andric SmallVector<Value *> splitVectorElements(IRBuilderBase &Builder, Value *Vec, 148bdd1243dSDimitry Andric unsigned ToWidth) const; 149bdd1243dSDimitry Andric Value *joinVectorElements(IRBuilderBase &Builder, ArrayRef<Value *> Values, 150bdd1243dSDimitry Andric VectorType *ToType) const; 151e8d8bef9SDimitry Andric 152bdd1243dSDimitry Andric std::optional<int> calculatePointerDifference(Value *Ptr0, Value *Ptr1) const; 153bdd1243dSDimitry Andric 154bdd1243dSDimitry Andric unsigned getNumSignificantBits(const Value *V, 155bdd1243dSDimitry Andric const Instruction *CtxI = nullptr) const; 156bdd1243dSDimitry Andric KnownBits getKnownBits(const Value *V, 157bdd1243dSDimitry Andric const Instruction *CtxI = nullptr) const; 158e8d8bef9SDimitry Andric 15906c3fb27SDimitry Andric bool isSafeToClone(const Instruction &In) const; 16006c3fb27SDimitry Andric 161e8d8bef9SDimitry Andric template <typename T = std::vector<Instruction *>> 162e8d8bef9SDimitry Andric bool isSafeToMoveBeforeInBB(const Instruction &In, 163e8d8bef9SDimitry Andric BasicBlock::const_iterator To, 164bdd1243dSDimitry Andric const T &IgnoreInsts = {}) const; 165bdd1243dSDimitry Andric 166bdd1243dSDimitry Andric // This function is only used for assertions at the moment. 167bdd1243dSDimitry Andric [[maybe_unused]] bool isByteVecTy(Type *Ty) const; 168e8d8bef9SDimitry Andric 169e8d8bef9SDimitry Andric Function &F; 170e8d8bef9SDimitry Andric const DataLayout &DL; 171e8d8bef9SDimitry Andric AliasAnalysis &AA; 172e8d8bef9SDimitry Andric AssumptionCache &AC; 173e8d8bef9SDimitry Andric DominatorTree &DT; 17406c3fb27SDimitry Andric ScalarEvolution &SE; 175e8d8bef9SDimitry Andric TargetLibraryInfo &TLI; 176e8d8bef9SDimitry Andric const HexagonSubtarget &HST; 177e8d8bef9SDimitry Andric 178e8d8bef9SDimitry Andric private: 179bdd1243dSDimitry Andric Value *getElementRange(IRBuilderBase &Builder, Value *Lo, Value *Hi, 180bdd1243dSDimitry Andric int Start, int Length) const; 181e8d8bef9SDimitry Andric }; 182e8d8bef9SDimitry Andric 183e8d8bef9SDimitry Andric class AlignVectors { 18406c3fb27SDimitry Andric // This code tries to replace unaligned vector loads/stores with aligned 18506c3fb27SDimitry Andric // ones. 18606c3fb27SDimitry Andric // Consider unaligned load: 18706c3fb27SDimitry Andric // %v = original_load %some_addr, align <bad> 18806c3fb27SDimitry Andric // %user = %v 18906c3fb27SDimitry Andric // It will generate 19006c3fb27SDimitry Andric // = load ..., align <good> 19106c3fb27SDimitry Andric // = load ..., align <good> 19206c3fb27SDimitry Andric // = valign 19306c3fb27SDimitry Andric // etc. 19406c3fb27SDimitry Andric // %synthesize = combine/shuffle the loaded data so that it looks 19506c3fb27SDimitry Andric // exactly like what "original_load" has loaded. 19606c3fb27SDimitry Andric // %user = %synthesize 19706c3fb27SDimitry Andric // Similarly for stores. 198e8d8bef9SDimitry Andric public: 199bdd1243dSDimitry Andric AlignVectors(const HexagonVectorCombine &HVC_) : HVC(HVC_) {} 200e8d8bef9SDimitry Andric 201e8d8bef9SDimitry Andric bool run(); 202e8d8bef9SDimitry Andric 203e8d8bef9SDimitry Andric private: 204e8d8bef9SDimitry Andric using InstList = std::vector<Instruction *>; 20506c3fb27SDimitry Andric using InstMap = DenseMap<Instruction *, Instruction *>; 206e8d8bef9SDimitry Andric 207e8d8bef9SDimitry Andric struct AddrInfo { 208e8d8bef9SDimitry Andric AddrInfo(const AddrInfo &) = default; 209e8d8bef9SDimitry Andric AddrInfo(const HexagonVectorCombine &HVC, Instruction *I, Value *A, Type *T, 210e8d8bef9SDimitry Andric Align H) 211e8d8bef9SDimitry Andric : Inst(I), Addr(A), ValTy(T), HaveAlign(H), 212e8d8bef9SDimitry Andric NeedAlign(HVC.getTypeAlignment(ValTy)) {} 2136246ae0bSDimitry Andric AddrInfo &operator=(const AddrInfo &) = default; 214e8d8bef9SDimitry Andric 215e8d8bef9SDimitry Andric // XXX: add Size member? 216e8d8bef9SDimitry Andric Instruction *Inst; 217e8d8bef9SDimitry Andric Value *Addr; 218e8d8bef9SDimitry Andric Type *ValTy; 219e8d8bef9SDimitry Andric Align HaveAlign; 220e8d8bef9SDimitry Andric Align NeedAlign; 221e8d8bef9SDimitry Andric int Offset = 0; // Offset (in bytes) from the first member of the 222e8d8bef9SDimitry Andric // containing AddrList. 223e8d8bef9SDimitry Andric }; 224e8d8bef9SDimitry Andric using AddrList = std::vector<AddrInfo>; 225e8d8bef9SDimitry Andric 226e8d8bef9SDimitry Andric struct InstrLess { 227e8d8bef9SDimitry Andric bool operator()(const Instruction *A, const Instruction *B) const { 228e8d8bef9SDimitry Andric return A->comesBefore(B); 229e8d8bef9SDimitry Andric } 230e8d8bef9SDimitry Andric }; 231e8d8bef9SDimitry Andric using DepList = std::set<Instruction *, InstrLess>; 232e8d8bef9SDimitry Andric 233e8d8bef9SDimitry Andric struct MoveGroup { 234e8d8bef9SDimitry Andric MoveGroup(const AddrInfo &AI, Instruction *B, bool Hvx, bool Load) 23506c3fb27SDimitry Andric : Base(B), Main{AI.Inst}, Clones{}, IsHvx(Hvx), IsLoad(Load) {} 23606c3fb27SDimitry Andric MoveGroup() = default; 237e8d8bef9SDimitry Andric Instruction *Base; // Base instruction of the parent address group. 238e8d8bef9SDimitry Andric InstList Main; // Main group of instructions. 239e8d8bef9SDimitry Andric InstList Deps; // List of dependencies. 24006c3fb27SDimitry Andric InstMap Clones; // Map from original Deps to cloned ones. 241e8d8bef9SDimitry Andric bool IsHvx; // Is this group of HVX instructions? 242e8d8bef9SDimitry Andric bool IsLoad; // Is this a load group? 243e8d8bef9SDimitry Andric }; 244e8d8bef9SDimitry Andric using MoveList = std::vector<MoveGroup>; 245e8d8bef9SDimitry Andric 246e8d8bef9SDimitry Andric struct ByteSpan { 24706c3fb27SDimitry Andric // A representation of "interesting" bytes within a given span of memory. 24806c3fb27SDimitry Andric // These bytes are those that are loaded or stored, and they don't have 24906c3fb27SDimitry Andric // to cover the entire span of memory. 25006c3fb27SDimitry Andric // 25106c3fb27SDimitry Andric // The representation works by picking a contiguous sequence of bytes 25206c3fb27SDimitry Andric // from somewhere within a llvm::Value, and placing it at a given offset 25306c3fb27SDimitry Andric // within the span. 25406c3fb27SDimitry Andric // 25506c3fb27SDimitry Andric // The sequence of bytes from llvm:Value is represented by Segment. 25606c3fb27SDimitry Andric // Block is Segment, plus where it goes in the span. 25706c3fb27SDimitry Andric // 25806c3fb27SDimitry Andric // An important feature of ByteSpan is being able to make a "section", 25906c3fb27SDimitry Andric // i.e. creating another ByteSpan corresponding to a range of offsets 26006c3fb27SDimitry Andric // relative to the source span. 26106c3fb27SDimitry Andric 262e8d8bef9SDimitry Andric struct Segment { 263fe6060f1SDimitry Andric // Segment of a Value: 'Len' bytes starting at byte 'Begin'. 264e8d8bef9SDimitry Andric Segment(Value *Val, int Begin, int Len) 265e8d8bef9SDimitry Andric : Val(Val), Start(Begin), Size(Len) {} 266e8d8bef9SDimitry Andric Segment(const Segment &Seg) = default; 2676246ae0bSDimitry Andric Segment &operator=(const Segment &Seg) = default; 268fe6060f1SDimitry Andric Value *Val; // Value representable as a sequence of bytes. 269fe6060f1SDimitry Andric int Start; // First byte of the value that belongs to the segment. 270fe6060f1SDimitry Andric int Size; // Number of bytes in the segment. 271e8d8bef9SDimitry Andric }; 272e8d8bef9SDimitry Andric 273e8d8bef9SDimitry Andric struct Block { 274e8d8bef9SDimitry Andric Block(Value *Val, int Len, int Pos) : Seg(Val, 0, Len), Pos(Pos) {} 275e8d8bef9SDimitry Andric Block(Value *Val, int Off, int Len, int Pos) 276e8d8bef9SDimitry Andric : Seg(Val, Off, Len), Pos(Pos) {} 277e8d8bef9SDimitry Andric Block(const Block &Blk) = default; 2786246ae0bSDimitry Andric Block &operator=(const Block &Blk) = default; 279fe6060f1SDimitry Andric Segment Seg; // Value segment. 28006c3fb27SDimitry Andric int Pos; // Position (offset) of the block in the span. 281e8d8bef9SDimitry Andric }; 282e8d8bef9SDimitry Andric 283e8d8bef9SDimitry Andric int extent() const; 284e8d8bef9SDimitry Andric ByteSpan section(int Start, int Length) const; 285e8d8bef9SDimitry Andric ByteSpan &shift(int Offset); 286fe6060f1SDimitry Andric SmallVector<Value *, 8> values() const; 287e8d8bef9SDimitry Andric 288e8d8bef9SDimitry Andric int size() const { return Blocks.size(); } 289e8d8bef9SDimitry Andric Block &operator[](int i) { return Blocks[i]; } 29006c3fb27SDimitry Andric const Block &operator[](int i) const { return Blocks[i]; } 291e8d8bef9SDimitry Andric 292e8d8bef9SDimitry Andric std::vector<Block> Blocks; 293e8d8bef9SDimitry Andric 294e8d8bef9SDimitry Andric using iterator = decltype(Blocks)::iterator; 295e8d8bef9SDimitry Andric iterator begin() { return Blocks.begin(); } 296e8d8bef9SDimitry Andric iterator end() { return Blocks.end(); } 297e8d8bef9SDimitry Andric using const_iterator = decltype(Blocks)::const_iterator; 298e8d8bef9SDimitry Andric const_iterator begin() const { return Blocks.begin(); } 299e8d8bef9SDimitry Andric const_iterator end() const { return Blocks.end(); } 300e8d8bef9SDimitry Andric }; 301e8d8bef9SDimitry Andric 302e8d8bef9SDimitry Andric Align getAlignFromValue(const Value *V) const; 303bdd1243dSDimitry Andric std::optional<AddrInfo> getAddrInfo(Instruction &In) const; 304e8d8bef9SDimitry Andric bool isHvx(const AddrInfo &AI) const; 305bdd1243dSDimitry Andric // This function is only used for assertions at the moment. 306bdd1243dSDimitry Andric [[maybe_unused]] bool isSectorTy(Type *Ty) const; 307e8d8bef9SDimitry Andric 308e8d8bef9SDimitry Andric Value *getPayload(Value *Val) const; 309e8d8bef9SDimitry Andric Value *getMask(Value *Val) const; 310e8d8bef9SDimitry Andric Value *getPassThrough(Value *Val) const; 311e8d8bef9SDimitry Andric 312bdd1243dSDimitry Andric Value *createAdjustedPointer(IRBuilderBase &Builder, Value *Ptr, Type *ValTy, 31306c3fb27SDimitry Andric int Adjust, 31406c3fb27SDimitry Andric const InstMap &CloneMap = InstMap()) const; 315bdd1243dSDimitry Andric Value *createAlignedPointer(IRBuilderBase &Builder, Value *Ptr, Type *ValTy, 31606c3fb27SDimitry Andric int Alignment, 31706c3fb27SDimitry Andric const InstMap &CloneMap = InstMap()) const; 31806c3fb27SDimitry Andric 31906c3fb27SDimitry Andric Value *createLoad(IRBuilderBase &Builder, Type *ValTy, Value *Ptr, 32006c3fb27SDimitry Andric Value *Predicate, int Alignment, Value *Mask, 32106c3fb27SDimitry Andric Value *PassThru, 32206c3fb27SDimitry Andric ArrayRef<Value *> MDSources = std::nullopt) const; 32306c3fb27SDimitry Andric Value *createSimpleLoad(IRBuilderBase &Builder, Type *ValTy, Value *Ptr, 32406c3fb27SDimitry Andric int Alignment, 32506c3fb27SDimitry Andric ArrayRef<Value *> MDSources = std::nullopt) const; 32606c3fb27SDimitry Andric 32706c3fb27SDimitry Andric Value *createStore(IRBuilderBase &Builder, Value *Val, Value *Ptr, 32806c3fb27SDimitry Andric Value *Predicate, int Alignment, Value *Mask, 32906c3fb27SDimitry Andric ArrayRef<Value *> MDSources = std ::nullopt) const; 33006c3fb27SDimitry Andric Value *createSimpleStore(IRBuilderBase &Builder, Value *Val, Value *Ptr, 33106c3fb27SDimitry Andric int Alignment, 33206c3fb27SDimitry Andric ArrayRef<Value *> MDSources = std ::nullopt) const; 33306c3fb27SDimitry Andric 33406c3fb27SDimitry Andric Value *createPredicatedLoad(IRBuilderBase &Builder, Type *ValTy, Value *Ptr, 33506c3fb27SDimitry Andric Value *Predicate, int Alignment, 33606c3fb27SDimitry Andric ArrayRef<Value *> MDSources = std::nullopt) const; 33706c3fb27SDimitry Andric Value * 33806c3fb27SDimitry Andric createPredicatedStore(IRBuilderBase &Builder, Value *Val, Value *Ptr, 33906c3fb27SDimitry Andric Value *Predicate, int Alignment, 34006c3fb27SDimitry Andric ArrayRef<Value *> MDSources = std::nullopt) const; 341e8d8bef9SDimitry Andric 342bdd1243dSDimitry Andric DepList getUpwardDeps(Instruction *In, Instruction *Base) const; 343e8d8bef9SDimitry Andric bool createAddressGroups(); 344e8d8bef9SDimitry Andric MoveList createLoadGroups(const AddrList &Group) const; 345e8d8bef9SDimitry Andric MoveList createStoreGroups(const AddrList &Group) const; 34606c3fb27SDimitry Andric bool moveTogether(MoveGroup &Move) const; 34706c3fb27SDimitry Andric template <typename T> InstMap cloneBefore(Instruction *To, T &&Insts) const; 34806c3fb27SDimitry Andric 349bdd1243dSDimitry Andric void realignLoadGroup(IRBuilderBase &Builder, const ByteSpan &VSpan, 350bdd1243dSDimitry Andric int ScLen, Value *AlignVal, Value *AlignAddr) const; 351bdd1243dSDimitry Andric void realignStoreGroup(IRBuilderBase &Builder, const ByteSpan &VSpan, 352bdd1243dSDimitry Andric int ScLen, Value *AlignVal, Value *AlignAddr) const; 353e8d8bef9SDimitry Andric bool realignGroup(const MoveGroup &Move) const; 354e8d8bef9SDimitry Andric 35506c3fb27SDimitry Andric Value *makeTestIfUnaligned(IRBuilderBase &Builder, Value *AlignVal, 35606c3fb27SDimitry Andric int Alignment) const; 35706c3fb27SDimitry Andric 358e8d8bef9SDimitry Andric friend raw_ostream &operator<<(raw_ostream &OS, const AddrInfo &AI); 359e8d8bef9SDimitry Andric friend raw_ostream &operator<<(raw_ostream &OS, const MoveGroup &MG); 360bdd1243dSDimitry Andric friend raw_ostream &operator<<(raw_ostream &OS, const ByteSpan::Block &B); 361e8d8bef9SDimitry Andric friend raw_ostream &operator<<(raw_ostream &OS, const ByteSpan &BS); 362e8d8bef9SDimitry Andric 363e8d8bef9SDimitry Andric std::map<Instruction *, AddrList> AddrGroups; 364bdd1243dSDimitry Andric const HexagonVectorCombine &HVC; 365e8d8bef9SDimitry Andric }; 366e8d8bef9SDimitry Andric 367e8d8bef9SDimitry Andric LLVM_ATTRIBUTE_UNUSED 368e8d8bef9SDimitry Andric raw_ostream &operator<<(raw_ostream &OS, const AlignVectors::AddrInfo &AI) { 369e8d8bef9SDimitry Andric OS << "Inst: " << AI.Inst << " " << *AI.Inst << '\n'; 370e8d8bef9SDimitry Andric OS << "Addr: " << *AI.Addr << '\n'; 371e8d8bef9SDimitry Andric OS << "Type: " << *AI.ValTy << '\n'; 372e8d8bef9SDimitry Andric OS << "HaveAlign: " << AI.HaveAlign.value() << '\n'; 373e8d8bef9SDimitry Andric OS << "NeedAlign: " << AI.NeedAlign.value() << '\n'; 374e8d8bef9SDimitry Andric OS << "Offset: " << AI.Offset; 375e8d8bef9SDimitry Andric return OS; 376e8d8bef9SDimitry Andric } 377e8d8bef9SDimitry Andric 378e8d8bef9SDimitry Andric LLVM_ATTRIBUTE_UNUSED 379e8d8bef9SDimitry Andric raw_ostream &operator<<(raw_ostream &OS, const AlignVectors::MoveGroup &MG) { 38006c3fb27SDimitry Andric OS << "IsLoad:" << (MG.IsLoad ? "yes" : "no"); 38106c3fb27SDimitry Andric OS << ", IsHvx:" << (MG.IsHvx ? "yes" : "no") << '\n'; 382e8d8bef9SDimitry Andric OS << "Main\n"; 383e8d8bef9SDimitry Andric for (Instruction *I : MG.Main) 384e8d8bef9SDimitry Andric OS << " " << *I << '\n'; 385e8d8bef9SDimitry Andric OS << "Deps\n"; 386e8d8bef9SDimitry Andric for (Instruction *I : MG.Deps) 387e8d8bef9SDimitry Andric OS << " " << *I << '\n'; 38806c3fb27SDimitry Andric OS << "Clones\n"; 38906c3fb27SDimitry Andric for (auto [K, V] : MG.Clones) { 39006c3fb27SDimitry Andric OS << " "; 39106c3fb27SDimitry Andric K->printAsOperand(OS, false); 39206c3fb27SDimitry Andric OS << "\t-> " << *V << '\n'; 39306c3fb27SDimitry Andric } 394e8d8bef9SDimitry Andric return OS; 395e8d8bef9SDimitry Andric } 396e8d8bef9SDimitry Andric 397e8d8bef9SDimitry Andric LLVM_ATTRIBUTE_UNUSED 398bdd1243dSDimitry Andric raw_ostream &operator<<(raw_ostream &OS, 399bdd1243dSDimitry Andric const AlignVectors::ByteSpan::Block &B) { 40006c3fb27SDimitry Andric OS << " @" << B.Pos << " [" << B.Seg.Start << ',' << B.Seg.Size << "] "; 40106c3fb27SDimitry Andric if (B.Seg.Val == reinterpret_cast<const Value *>(&B)) { 40206c3fb27SDimitry Andric OS << "(self:" << B.Seg.Val << ')'; 40306c3fb27SDimitry Andric } else if (B.Seg.Val != nullptr) { 40406c3fb27SDimitry Andric OS << *B.Seg.Val; 40506c3fb27SDimitry Andric } else { 40606c3fb27SDimitry Andric OS << "(null)"; 40706c3fb27SDimitry Andric } 408bdd1243dSDimitry Andric return OS; 409bdd1243dSDimitry Andric } 410bdd1243dSDimitry Andric 411bdd1243dSDimitry Andric LLVM_ATTRIBUTE_UNUSED 412e8d8bef9SDimitry Andric raw_ostream &operator<<(raw_ostream &OS, const AlignVectors::ByteSpan &BS) { 413e8d8bef9SDimitry Andric OS << "ByteSpan[size=" << BS.size() << ", extent=" << BS.extent() << '\n'; 414bdd1243dSDimitry Andric for (const AlignVectors::ByteSpan::Block &B : BS) 415bdd1243dSDimitry Andric OS << B << '\n'; 416e8d8bef9SDimitry Andric OS << ']'; 417e8d8bef9SDimitry Andric return OS; 418e8d8bef9SDimitry Andric } 419e8d8bef9SDimitry Andric 420bdd1243dSDimitry Andric class HvxIdioms { 421bdd1243dSDimitry Andric public: 422bdd1243dSDimitry Andric HvxIdioms(const HexagonVectorCombine &HVC_) : HVC(HVC_) { 423bdd1243dSDimitry Andric auto *Int32Ty = HVC.getIntTy(32); 424bdd1243dSDimitry Andric HvxI32Ty = HVC.getHvxTy(Int32Ty, /*Pair=*/false); 425bdd1243dSDimitry Andric HvxP32Ty = HVC.getHvxTy(Int32Ty, /*Pair=*/true); 426bdd1243dSDimitry Andric } 427bdd1243dSDimitry Andric 428bdd1243dSDimitry Andric bool run(); 429bdd1243dSDimitry Andric 430bdd1243dSDimitry Andric private: 431bdd1243dSDimitry Andric enum Signedness { Positive, Signed, Unsigned }; 432bdd1243dSDimitry Andric 433bdd1243dSDimitry Andric // Value + sign 434bdd1243dSDimitry Andric // This is to keep track of whether the value should be treated as signed 435bdd1243dSDimitry Andric // or unsigned, or is known to be positive. 436bdd1243dSDimitry Andric struct SValue { 437bdd1243dSDimitry Andric Value *Val; 438bdd1243dSDimitry Andric Signedness Sgn; 439bdd1243dSDimitry Andric }; 440bdd1243dSDimitry Andric 441bdd1243dSDimitry Andric struct FxpOp { 442bdd1243dSDimitry Andric unsigned Opcode; 443bdd1243dSDimitry Andric unsigned Frac; // Number of fraction bits 444bdd1243dSDimitry Andric SValue X, Y; 445bdd1243dSDimitry Andric // If present, add 1 << RoundAt before shift: 446bdd1243dSDimitry Andric std::optional<unsigned> RoundAt; 447bdd1243dSDimitry Andric VectorType *ResTy; 448bdd1243dSDimitry Andric }; 449bdd1243dSDimitry Andric 450bdd1243dSDimitry Andric auto getNumSignificantBits(Value *V, Instruction *In) const 451bdd1243dSDimitry Andric -> std::pair<unsigned, Signedness>; 452bdd1243dSDimitry Andric auto canonSgn(SValue X, SValue Y) const -> std::pair<SValue, SValue>; 453bdd1243dSDimitry Andric 454bdd1243dSDimitry Andric auto matchFxpMul(Instruction &In) const -> std::optional<FxpOp>; 455bdd1243dSDimitry Andric auto processFxpMul(Instruction &In, const FxpOp &Op) const -> Value *; 456bdd1243dSDimitry Andric 457bdd1243dSDimitry Andric auto processFxpMulChopped(IRBuilderBase &Builder, Instruction &In, 458bdd1243dSDimitry Andric const FxpOp &Op) const -> Value *; 459bdd1243dSDimitry Andric auto createMulQ15(IRBuilderBase &Builder, SValue X, SValue Y, 460bdd1243dSDimitry Andric bool Rounding) const -> Value *; 461bdd1243dSDimitry Andric auto createMulQ31(IRBuilderBase &Builder, SValue X, SValue Y, 462bdd1243dSDimitry Andric bool Rounding) const -> Value *; 463bdd1243dSDimitry Andric // Return {Result, Carry}, where Carry is a vector predicate. 464bdd1243dSDimitry Andric auto createAddCarry(IRBuilderBase &Builder, Value *X, Value *Y, 465bdd1243dSDimitry Andric Value *CarryIn = nullptr) const 466bdd1243dSDimitry Andric -> std::pair<Value *, Value *>; 467bdd1243dSDimitry Andric auto createMul16(IRBuilderBase &Builder, SValue X, SValue Y) const -> Value *; 468bdd1243dSDimitry Andric auto createMulH16(IRBuilderBase &Builder, SValue X, SValue Y) const 469bdd1243dSDimitry Andric -> Value *; 470bdd1243dSDimitry Andric auto createMul32(IRBuilderBase &Builder, SValue X, SValue Y) const 471bdd1243dSDimitry Andric -> std::pair<Value *, Value *>; 472bdd1243dSDimitry Andric auto createAddLong(IRBuilderBase &Builder, ArrayRef<Value *> WordX, 473bdd1243dSDimitry Andric ArrayRef<Value *> WordY) const -> SmallVector<Value *>; 474bdd1243dSDimitry Andric auto createMulLong(IRBuilderBase &Builder, ArrayRef<Value *> WordX, 475bdd1243dSDimitry Andric Signedness SgnX, ArrayRef<Value *> WordY, 476bdd1243dSDimitry Andric Signedness SgnY) const -> SmallVector<Value *>; 477bdd1243dSDimitry Andric 478bdd1243dSDimitry Andric VectorType *HvxI32Ty; 479bdd1243dSDimitry Andric VectorType *HvxP32Ty; 480bdd1243dSDimitry Andric const HexagonVectorCombine &HVC; 481bdd1243dSDimitry Andric 482bdd1243dSDimitry Andric friend raw_ostream &operator<<(raw_ostream &, const FxpOp &); 483bdd1243dSDimitry Andric }; 484bdd1243dSDimitry Andric 485bdd1243dSDimitry Andric [[maybe_unused]] raw_ostream &operator<<(raw_ostream &OS, 486bdd1243dSDimitry Andric const HvxIdioms::FxpOp &Op) { 487bdd1243dSDimitry Andric static const char *SgnNames[] = {"Positive", "Signed", "Unsigned"}; 488bdd1243dSDimitry Andric OS << Instruction::getOpcodeName(Op.Opcode) << '.' << Op.Frac; 489bdd1243dSDimitry Andric if (Op.RoundAt.has_value()) { 490bdd1243dSDimitry Andric if (Op.Frac != 0 && *Op.RoundAt == Op.Frac - 1) { 491bdd1243dSDimitry Andric OS << ":rnd"; 492bdd1243dSDimitry Andric } else { 493bdd1243dSDimitry Andric OS << " + 1<<" << *Op.RoundAt; 494bdd1243dSDimitry Andric } 495bdd1243dSDimitry Andric } 496bdd1243dSDimitry Andric OS << "\n X:(" << SgnNames[Op.X.Sgn] << ") " << *Op.X.Val << "\n" 497bdd1243dSDimitry Andric << " Y:(" << SgnNames[Op.Y.Sgn] << ") " << *Op.Y.Val; 498bdd1243dSDimitry Andric return OS; 499bdd1243dSDimitry Andric } 500bdd1243dSDimitry Andric 501e8d8bef9SDimitry Andric } // namespace 502e8d8bef9SDimitry Andric 503e8d8bef9SDimitry Andric namespace { 504e8d8bef9SDimitry Andric 505e8d8bef9SDimitry Andric template <typename T> T *getIfUnordered(T *MaybeT) { 506e8d8bef9SDimitry Andric return MaybeT && MaybeT->isUnordered() ? MaybeT : nullptr; 507e8d8bef9SDimitry Andric } 508e8d8bef9SDimitry Andric template <typename T> T *isCandidate(Instruction *In) { 509e8d8bef9SDimitry Andric return dyn_cast<T>(In); 510e8d8bef9SDimitry Andric } 511e8d8bef9SDimitry Andric template <> LoadInst *isCandidate<LoadInst>(Instruction *In) { 512e8d8bef9SDimitry Andric return getIfUnordered(dyn_cast<LoadInst>(In)); 513e8d8bef9SDimitry Andric } 514e8d8bef9SDimitry Andric template <> StoreInst *isCandidate<StoreInst>(Instruction *In) { 515e8d8bef9SDimitry Andric return getIfUnordered(dyn_cast<StoreInst>(In)); 516e8d8bef9SDimitry Andric } 517e8d8bef9SDimitry Andric 518fe6060f1SDimitry Andric #if !defined(_MSC_VER) || _MSC_VER >= 1926 519fe6060f1SDimitry Andric // VS2017 and some versions of VS2019 have trouble compiling this: 520e8d8bef9SDimitry Andric // error C2976: 'std::map': too few template arguments 521fe6060f1SDimitry Andric // VS 2019 16.x is known to work, except for 16.4/16.5 (MSC_VER 1924/1925) 522e8d8bef9SDimitry Andric template <typename Pred, typename... Ts> 523e8d8bef9SDimitry Andric void erase_if(std::map<Ts...> &map, Pred p) 524e8d8bef9SDimitry Andric #else 525e8d8bef9SDimitry Andric template <typename Pred, typename T, typename U> 526e8d8bef9SDimitry Andric void erase_if(std::map<T, U> &map, Pred p) 527e8d8bef9SDimitry Andric #endif 528e8d8bef9SDimitry Andric { 529e8d8bef9SDimitry Andric for (auto i = map.begin(), e = map.end(); i != e;) { 530e8d8bef9SDimitry Andric if (p(*i)) 531e8d8bef9SDimitry Andric i = map.erase(i); 532e8d8bef9SDimitry Andric else 533e8d8bef9SDimitry Andric i = std::next(i); 534e8d8bef9SDimitry Andric } 535e8d8bef9SDimitry Andric } 536e8d8bef9SDimitry Andric 537e8d8bef9SDimitry Andric // Forward other erase_ifs to the LLVM implementations. 538e8d8bef9SDimitry Andric template <typename Pred, typename T> void erase_if(T &&container, Pred p) { 539e8d8bef9SDimitry Andric llvm::erase_if(std::forward<T>(container), p); 540e8d8bef9SDimitry Andric } 541e8d8bef9SDimitry Andric 542e8d8bef9SDimitry Andric } // namespace 543e8d8bef9SDimitry Andric 544e8d8bef9SDimitry Andric // --- Begin AlignVectors 545e8d8bef9SDimitry Andric 54606c3fb27SDimitry Andric // For brevity, only consider loads. We identify a group of loads where we 54706c3fb27SDimitry Andric // know the relative differences between their addresses, so we know how they 54806c3fb27SDimitry Andric // are laid out in memory (relative to one another). These loads can overlap, 54906c3fb27SDimitry Andric // can be shorter or longer than the desired vector length. 55006c3fb27SDimitry Andric // Ultimately we want to generate a sequence of aligned loads that will load 55106c3fb27SDimitry Andric // every byte that the original loads loaded, and have the program use these 55206c3fb27SDimitry Andric // loaded values instead of the original loads. 55306c3fb27SDimitry Andric // We consider the contiguous memory area spanned by all these loads. 55406c3fb27SDimitry Andric // 55506c3fb27SDimitry Andric // Let's say that a single aligned vector load can load 16 bytes at a time. 55606c3fb27SDimitry Andric // If the program wanted to use a byte at offset 13 from the beginning of the 55706c3fb27SDimitry Andric // original span, it will be a byte at offset 13+x in the aligned data for 55806c3fb27SDimitry Andric // some x>=0. This may happen to be in the first aligned load, or in the load 55906c3fb27SDimitry Andric // following it. Since we generally don't know what the that alignment value 56006c3fb27SDimitry Andric // is at compile time, we proactively do valigns on the aligned loads, so that 56106c3fb27SDimitry Andric // byte that was at offset 13 is still at offset 13 after the valigns. 56206c3fb27SDimitry Andric // 56306c3fb27SDimitry Andric // This will be the starting point for making the rest of the program use the 56406c3fb27SDimitry Andric // data loaded by the new loads. 56506c3fb27SDimitry Andric // For each original load, and its users: 56606c3fb27SDimitry Andric // %v = load ... 56706c3fb27SDimitry Andric // ... = %v 56806c3fb27SDimitry Andric // ... = %v 56906c3fb27SDimitry Andric // we create 57006c3fb27SDimitry Andric // %new_v = extract/combine/shuffle data from loaded/valigned vectors so 57106c3fb27SDimitry Andric // it contains the same value as %v did before 57206c3fb27SDimitry Andric // then replace all users of %v with %new_v. 57306c3fb27SDimitry Andric // ... = %new_v 57406c3fb27SDimitry Andric // ... = %new_v 57506c3fb27SDimitry Andric 576e8d8bef9SDimitry Andric auto AlignVectors::ByteSpan::extent() const -> int { 577e8d8bef9SDimitry Andric if (size() == 0) 578e8d8bef9SDimitry Andric return 0; 579e8d8bef9SDimitry Andric int Min = Blocks[0].Pos; 580e8d8bef9SDimitry Andric int Max = Blocks[0].Pos + Blocks[0].Seg.Size; 581e8d8bef9SDimitry Andric for (int i = 1, e = size(); i != e; ++i) { 582e8d8bef9SDimitry Andric Min = std::min(Min, Blocks[i].Pos); 583e8d8bef9SDimitry Andric Max = std::max(Max, Blocks[i].Pos + Blocks[i].Seg.Size); 584e8d8bef9SDimitry Andric } 585e8d8bef9SDimitry Andric return Max - Min; 586e8d8bef9SDimitry Andric } 587e8d8bef9SDimitry Andric 588e8d8bef9SDimitry Andric auto AlignVectors::ByteSpan::section(int Start, int Length) const -> ByteSpan { 589e8d8bef9SDimitry Andric ByteSpan Section; 590e8d8bef9SDimitry Andric for (const ByteSpan::Block &B : Blocks) { 591e8d8bef9SDimitry Andric int L = std::max(B.Pos, Start); // Left end. 592e8d8bef9SDimitry Andric int R = std::min(B.Pos + B.Seg.Size, Start + Length); // Right end+1. 593e8d8bef9SDimitry Andric if (L < R) { 594e8d8bef9SDimitry Andric // How much to chop off the beginning of the segment: 595e8d8bef9SDimitry Andric int Off = L > B.Pos ? L - B.Pos : 0; 596e8d8bef9SDimitry Andric Section.Blocks.emplace_back(B.Seg.Val, B.Seg.Start + Off, R - L, L); 597e8d8bef9SDimitry Andric } 598e8d8bef9SDimitry Andric } 599e8d8bef9SDimitry Andric return Section; 600e8d8bef9SDimitry Andric } 601e8d8bef9SDimitry Andric 602e8d8bef9SDimitry Andric auto AlignVectors::ByteSpan::shift(int Offset) -> ByteSpan & { 603e8d8bef9SDimitry Andric for (Block &B : Blocks) 604e8d8bef9SDimitry Andric B.Pos += Offset; 605e8d8bef9SDimitry Andric return *this; 606e8d8bef9SDimitry Andric } 607e8d8bef9SDimitry Andric 608fe6060f1SDimitry Andric auto AlignVectors::ByteSpan::values() const -> SmallVector<Value *, 8> { 609fe6060f1SDimitry Andric SmallVector<Value *, 8> Values(Blocks.size()); 610fe6060f1SDimitry Andric for (int i = 0, e = Blocks.size(); i != e; ++i) 611fe6060f1SDimitry Andric Values[i] = Blocks[i].Seg.Val; 612fe6060f1SDimitry Andric return Values; 613fe6060f1SDimitry Andric } 614fe6060f1SDimitry Andric 615e8d8bef9SDimitry Andric auto AlignVectors::getAlignFromValue(const Value *V) const -> Align { 616e8d8bef9SDimitry Andric const auto *C = dyn_cast<ConstantInt>(V); 617e8d8bef9SDimitry Andric assert(C && "Alignment must be a compile-time constant integer"); 618e8d8bef9SDimitry Andric return C->getAlignValue(); 619e8d8bef9SDimitry Andric } 620e8d8bef9SDimitry Andric 621bdd1243dSDimitry Andric auto AlignVectors::getAddrInfo(Instruction &In) const 622bdd1243dSDimitry Andric -> std::optional<AddrInfo> { 623e8d8bef9SDimitry Andric if (auto *L = isCandidate<LoadInst>(&In)) 624e8d8bef9SDimitry Andric return AddrInfo(HVC, L, L->getPointerOperand(), L->getType(), 625e8d8bef9SDimitry Andric L->getAlign()); 626e8d8bef9SDimitry Andric if (auto *S = isCandidate<StoreInst>(&In)) 627e8d8bef9SDimitry Andric return AddrInfo(HVC, S, S->getPointerOperand(), 628e8d8bef9SDimitry Andric S->getValueOperand()->getType(), S->getAlign()); 629e8d8bef9SDimitry Andric if (auto *II = isCandidate<IntrinsicInst>(&In)) { 630e8d8bef9SDimitry Andric Intrinsic::ID ID = II->getIntrinsicID(); 631e8d8bef9SDimitry Andric switch (ID) { 632e8d8bef9SDimitry Andric case Intrinsic::masked_load: 633e8d8bef9SDimitry Andric return AddrInfo(HVC, II, II->getArgOperand(0), II->getType(), 634e8d8bef9SDimitry Andric getAlignFromValue(II->getArgOperand(1))); 635e8d8bef9SDimitry Andric case Intrinsic::masked_store: 636e8d8bef9SDimitry Andric return AddrInfo(HVC, II, II->getArgOperand(1), 637e8d8bef9SDimitry Andric II->getArgOperand(0)->getType(), 638e8d8bef9SDimitry Andric getAlignFromValue(II->getArgOperand(2))); 639e8d8bef9SDimitry Andric } 640e8d8bef9SDimitry Andric } 641bdd1243dSDimitry Andric return std::nullopt; 642e8d8bef9SDimitry Andric } 643e8d8bef9SDimitry Andric 644e8d8bef9SDimitry Andric auto AlignVectors::isHvx(const AddrInfo &AI) const -> bool { 645e8d8bef9SDimitry Andric return HVC.HST.isTypeForHVX(AI.ValTy); 646e8d8bef9SDimitry Andric } 647e8d8bef9SDimitry Andric 648e8d8bef9SDimitry Andric auto AlignVectors::getPayload(Value *Val) const -> Value * { 649e8d8bef9SDimitry Andric if (auto *In = dyn_cast<Instruction>(Val)) { 650e8d8bef9SDimitry Andric Intrinsic::ID ID = 0; 651e8d8bef9SDimitry Andric if (auto *II = dyn_cast<IntrinsicInst>(In)) 652e8d8bef9SDimitry Andric ID = II->getIntrinsicID(); 653e8d8bef9SDimitry Andric if (isa<StoreInst>(In) || ID == Intrinsic::masked_store) 654e8d8bef9SDimitry Andric return In->getOperand(0); 655e8d8bef9SDimitry Andric } 656e8d8bef9SDimitry Andric return Val; 657e8d8bef9SDimitry Andric } 658e8d8bef9SDimitry Andric 659e8d8bef9SDimitry Andric auto AlignVectors::getMask(Value *Val) const -> Value * { 660e8d8bef9SDimitry Andric if (auto *II = dyn_cast<IntrinsicInst>(Val)) { 661e8d8bef9SDimitry Andric switch (II->getIntrinsicID()) { 662e8d8bef9SDimitry Andric case Intrinsic::masked_load: 663e8d8bef9SDimitry Andric return II->getArgOperand(2); 664e8d8bef9SDimitry Andric case Intrinsic::masked_store: 665e8d8bef9SDimitry Andric return II->getArgOperand(3); 666e8d8bef9SDimitry Andric } 667e8d8bef9SDimitry Andric } 668e8d8bef9SDimitry Andric 669e8d8bef9SDimitry Andric Type *ValTy = getPayload(Val)->getType(); 670bdd1243dSDimitry Andric if (auto *VecTy = dyn_cast<VectorType>(ValTy)) 671bdd1243dSDimitry Andric return HVC.getFullValue(HVC.getBoolTy(HVC.length(VecTy))); 672e8d8bef9SDimitry Andric return HVC.getFullValue(HVC.getBoolTy()); 673e8d8bef9SDimitry Andric } 674e8d8bef9SDimitry Andric 675e8d8bef9SDimitry Andric auto AlignVectors::getPassThrough(Value *Val) const -> Value * { 676e8d8bef9SDimitry Andric if (auto *II = dyn_cast<IntrinsicInst>(Val)) { 677e8d8bef9SDimitry Andric if (II->getIntrinsicID() == Intrinsic::masked_load) 678e8d8bef9SDimitry Andric return II->getArgOperand(3); 679e8d8bef9SDimitry Andric } 680e8d8bef9SDimitry Andric return UndefValue::get(getPayload(Val)->getType()); 681e8d8bef9SDimitry Andric } 682e8d8bef9SDimitry Andric 683bdd1243dSDimitry Andric auto AlignVectors::createAdjustedPointer(IRBuilderBase &Builder, Value *Ptr, 68406c3fb27SDimitry Andric Type *ValTy, int Adjust, 68506c3fb27SDimitry Andric const InstMap &CloneMap) const 686e8d8bef9SDimitry Andric -> Value * { 68706c3fb27SDimitry Andric if (auto *I = dyn_cast<Instruction>(Ptr)) 68806c3fb27SDimitry Andric if (Instruction *New = CloneMap.lookup(I)) 68906c3fb27SDimitry Andric Ptr = New; 6907a6dacacSDimitry Andric return Builder.CreatePtrAdd(Ptr, HVC.getConstInt(Adjust), "gep"); 691e8d8bef9SDimitry Andric } 692e8d8bef9SDimitry Andric 693bdd1243dSDimitry Andric auto AlignVectors::createAlignedPointer(IRBuilderBase &Builder, Value *Ptr, 69406c3fb27SDimitry Andric Type *ValTy, int Alignment, 69506c3fb27SDimitry Andric const InstMap &CloneMap) const 696e8d8bef9SDimitry Andric -> Value * { 69706c3fb27SDimitry Andric auto remap = [&](Value *V) -> Value * { 69806c3fb27SDimitry Andric if (auto *I = dyn_cast<Instruction>(V)) { 69906c3fb27SDimitry Andric for (auto [Old, New] : CloneMap) 70006c3fb27SDimitry Andric I->replaceUsesOfWith(Old, New); 70106c3fb27SDimitry Andric return I; 70206c3fb27SDimitry Andric } 70306c3fb27SDimitry Andric return V; 70406c3fb27SDimitry Andric }; 70506c3fb27SDimitry Andric Value *AsInt = Builder.CreatePtrToInt(Ptr, HVC.getIntTy(), "pti"); 706e8d8bef9SDimitry Andric Value *Mask = HVC.getConstInt(-Alignment); 70706c3fb27SDimitry Andric Value *And = Builder.CreateAnd(remap(AsInt), Mask, "and"); 7085f757f3fSDimitry Andric return Builder.CreateIntToPtr( 7095f757f3fSDimitry Andric And, PointerType::getUnqual(ValTy->getContext()), "itp"); 710e8d8bef9SDimitry Andric } 711e8d8bef9SDimitry Andric 71206c3fb27SDimitry Andric auto AlignVectors::createLoad(IRBuilderBase &Builder, Type *ValTy, Value *Ptr, 71306c3fb27SDimitry Andric Value *Predicate, int Alignment, Value *Mask, 71406c3fb27SDimitry Andric Value *PassThru, 71506c3fb27SDimitry Andric ArrayRef<Value *> MDSources) const -> Value * { 71606c3fb27SDimitry Andric bool HvxHasPredLoad = HVC.HST.useHVXV62Ops(); 71706c3fb27SDimitry Andric // Predicate is nullptr if not creating predicated load 71806c3fb27SDimitry Andric if (Predicate) { 71906c3fb27SDimitry Andric assert(!Predicate->getType()->isVectorTy() && 72006c3fb27SDimitry Andric "Expectning scalar predicate"); 72106c3fb27SDimitry Andric if (HVC.isFalse(Predicate)) 72206c3fb27SDimitry Andric return UndefValue::get(ValTy); 72306c3fb27SDimitry Andric if (!HVC.isTrue(Predicate) && HvxHasPredLoad) { 72406c3fb27SDimitry Andric Value *Load = createPredicatedLoad(Builder, ValTy, Ptr, Predicate, 72506c3fb27SDimitry Andric Alignment, MDSources); 72606c3fb27SDimitry Andric return Builder.CreateSelect(Mask, Load, PassThru); 72706c3fb27SDimitry Andric } 72806c3fb27SDimitry Andric // Predicate == true here. 72906c3fb27SDimitry Andric } 730e8d8bef9SDimitry Andric assert(!HVC.isUndef(Mask)); // Should this be allowed? 731e8d8bef9SDimitry Andric if (HVC.isZero(Mask)) 732e8d8bef9SDimitry Andric return PassThru; 73306c3fb27SDimitry Andric if (HVC.isTrue(Mask)) 73406c3fb27SDimitry Andric return createSimpleLoad(Builder, ValTy, Ptr, Alignment, MDSources); 73506c3fb27SDimitry Andric 73606c3fb27SDimitry Andric Instruction *Load = Builder.CreateMaskedLoad(ValTy, Ptr, Align(Alignment), 73706c3fb27SDimitry Andric Mask, PassThru, "mld"); 73806c3fb27SDimitry Andric propagateMetadata(Load, MDSources); 73906c3fb27SDimitry Andric return Load; 740e8d8bef9SDimitry Andric } 741e8d8bef9SDimitry Andric 74206c3fb27SDimitry Andric auto AlignVectors::createSimpleLoad(IRBuilderBase &Builder, Type *ValTy, 743e8d8bef9SDimitry Andric Value *Ptr, int Alignment, 74406c3fb27SDimitry Andric ArrayRef<Value *> MDSources) const 74506c3fb27SDimitry Andric -> Value * { 74606c3fb27SDimitry Andric Instruction *Load = 74706c3fb27SDimitry Andric Builder.CreateAlignedLoad(ValTy, Ptr, Align(Alignment), "ald"); 74806c3fb27SDimitry Andric propagateMetadata(Load, MDSources); 74906c3fb27SDimitry Andric return Load; 75006c3fb27SDimitry Andric } 75106c3fb27SDimitry Andric 75206c3fb27SDimitry Andric auto AlignVectors::createPredicatedLoad(IRBuilderBase &Builder, Type *ValTy, 75306c3fb27SDimitry Andric Value *Ptr, Value *Predicate, 75406c3fb27SDimitry Andric int Alignment, 75506c3fb27SDimitry Andric ArrayRef<Value *> MDSources) const 75606c3fb27SDimitry Andric -> Value * { 75706c3fb27SDimitry Andric assert(HVC.HST.isTypeForHVX(ValTy) && 75806c3fb27SDimitry Andric "Predicates 'scalar' vector loads not yet supported"); 75906c3fb27SDimitry Andric assert(Predicate); 76006c3fb27SDimitry Andric assert(!Predicate->getType()->isVectorTy() && "Expectning scalar predicate"); 76106c3fb27SDimitry Andric assert(HVC.getSizeOf(ValTy, HVC.Alloc) % Alignment == 0); 76206c3fb27SDimitry Andric if (HVC.isFalse(Predicate)) 76306c3fb27SDimitry Andric return UndefValue::get(ValTy); 76406c3fb27SDimitry Andric if (HVC.isTrue(Predicate)) 76506c3fb27SDimitry Andric return createSimpleLoad(Builder, ValTy, Ptr, Alignment, MDSources); 76606c3fb27SDimitry Andric 76706c3fb27SDimitry Andric auto V6_vL32b_pred_ai = HVC.HST.getIntrinsicId(Hexagon::V6_vL32b_pred_ai); 76806c3fb27SDimitry Andric // FIXME: This may not put the offset from Ptr into the vmem offset. 76906c3fb27SDimitry Andric return HVC.createHvxIntrinsic(Builder, V6_vL32b_pred_ai, ValTy, 77006c3fb27SDimitry Andric {Predicate, Ptr, HVC.getConstInt(0)}, 77106c3fb27SDimitry Andric std::nullopt, MDSources); 77206c3fb27SDimitry Andric } 77306c3fb27SDimitry Andric 77406c3fb27SDimitry Andric auto AlignVectors::createStore(IRBuilderBase &Builder, Value *Val, Value *Ptr, 77506c3fb27SDimitry Andric Value *Predicate, int Alignment, Value *Mask, 77606c3fb27SDimitry Andric ArrayRef<Value *> MDSources) const -> Value * { 777e8d8bef9SDimitry Andric if (HVC.isZero(Mask) || HVC.isUndef(Val) || HVC.isUndef(Mask)) 778e8d8bef9SDimitry Andric return UndefValue::get(Val->getType()); 77906c3fb27SDimitry Andric assert(!Predicate || (!Predicate->getType()->isVectorTy() && 78006c3fb27SDimitry Andric "Expectning scalar predicate")); 78106c3fb27SDimitry Andric if (Predicate) { 78206c3fb27SDimitry Andric if (HVC.isFalse(Predicate)) 78306c3fb27SDimitry Andric return UndefValue::get(Val->getType()); 78406c3fb27SDimitry Andric if (HVC.isTrue(Predicate)) 78506c3fb27SDimitry Andric Predicate = nullptr; 78606c3fb27SDimitry Andric } 78706c3fb27SDimitry Andric // Here both Predicate and Mask are true or unknown. 78806c3fb27SDimitry Andric 78906c3fb27SDimitry Andric if (HVC.isTrue(Mask)) { 79006c3fb27SDimitry Andric if (Predicate) { // Predicate unknown 79106c3fb27SDimitry Andric return createPredicatedStore(Builder, Val, Ptr, Predicate, Alignment, 79206c3fb27SDimitry Andric MDSources); 79306c3fb27SDimitry Andric } 79406c3fb27SDimitry Andric // Predicate is true: 79506c3fb27SDimitry Andric return createSimpleStore(Builder, Val, Ptr, Alignment, MDSources); 79606c3fb27SDimitry Andric } 79706c3fb27SDimitry Andric 79806c3fb27SDimitry Andric // Mask is unknown 79906c3fb27SDimitry Andric if (!Predicate) { 80006c3fb27SDimitry Andric Instruction *Store = 80106c3fb27SDimitry Andric Builder.CreateMaskedStore(Val, Ptr, Align(Alignment), Mask); 80206c3fb27SDimitry Andric propagateMetadata(Store, MDSources); 80306c3fb27SDimitry Andric return Store; 80406c3fb27SDimitry Andric } 80506c3fb27SDimitry Andric 80606c3fb27SDimitry Andric // Both Predicate and Mask are unknown. 80706c3fb27SDimitry Andric // Emulate masked store with predicated-load + mux + predicated-store. 80806c3fb27SDimitry Andric Value *PredLoad = createPredicatedLoad(Builder, Val->getType(), Ptr, 80906c3fb27SDimitry Andric Predicate, Alignment, MDSources); 81006c3fb27SDimitry Andric Value *Mux = Builder.CreateSelect(Mask, Val, PredLoad); 81106c3fb27SDimitry Andric return createPredicatedStore(Builder, Mux, Ptr, Predicate, Alignment, 81206c3fb27SDimitry Andric MDSources); 81306c3fb27SDimitry Andric } 81406c3fb27SDimitry Andric 81506c3fb27SDimitry Andric auto AlignVectors::createSimpleStore(IRBuilderBase &Builder, Value *Val, 81606c3fb27SDimitry Andric Value *Ptr, int Alignment, 81706c3fb27SDimitry Andric ArrayRef<Value *> MDSources) const 81806c3fb27SDimitry Andric -> Value * { 81906c3fb27SDimitry Andric Instruction *Store = Builder.CreateAlignedStore(Val, Ptr, Align(Alignment)); 82006c3fb27SDimitry Andric propagateMetadata(Store, MDSources); 82106c3fb27SDimitry Andric return Store; 82206c3fb27SDimitry Andric } 82306c3fb27SDimitry Andric 82406c3fb27SDimitry Andric auto AlignVectors::createPredicatedStore(IRBuilderBase &Builder, Value *Val, 82506c3fb27SDimitry Andric Value *Ptr, Value *Predicate, 82606c3fb27SDimitry Andric int Alignment, 82706c3fb27SDimitry Andric ArrayRef<Value *> MDSources) const 82806c3fb27SDimitry Andric -> Value * { 82906c3fb27SDimitry Andric assert(HVC.HST.isTypeForHVX(Val->getType()) && 83006c3fb27SDimitry Andric "Predicates 'scalar' vector stores not yet supported"); 83106c3fb27SDimitry Andric assert(Predicate); 83206c3fb27SDimitry Andric if (HVC.isFalse(Predicate)) 83306c3fb27SDimitry Andric return UndefValue::get(Val->getType()); 83406c3fb27SDimitry Andric if (HVC.isTrue(Predicate)) 83506c3fb27SDimitry Andric return createSimpleStore(Builder, Val, Ptr, Alignment, MDSources); 83606c3fb27SDimitry Andric 83706c3fb27SDimitry Andric assert(HVC.getSizeOf(Val, HVC.Alloc) % Alignment == 0); 83806c3fb27SDimitry Andric auto V6_vS32b_pred_ai = HVC.HST.getIntrinsicId(Hexagon::V6_vS32b_pred_ai); 83906c3fb27SDimitry Andric // FIXME: This may not put the offset from Ptr into the vmem offset. 84006c3fb27SDimitry Andric return HVC.createHvxIntrinsic(Builder, V6_vS32b_pred_ai, nullptr, 84106c3fb27SDimitry Andric {Predicate, Ptr, HVC.getConstInt(0), Val}, 84206c3fb27SDimitry Andric std::nullopt, MDSources); 843e8d8bef9SDimitry Andric } 844e8d8bef9SDimitry Andric 845bdd1243dSDimitry Andric auto AlignVectors::getUpwardDeps(Instruction *In, Instruction *Base) const 846bdd1243dSDimitry Andric -> DepList { 847bdd1243dSDimitry Andric BasicBlock *Parent = Base->getParent(); 848bdd1243dSDimitry Andric assert(In->getParent() == Parent && 849bdd1243dSDimitry Andric "Base and In should be in the same block"); 850bdd1243dSDimitry Andric assert(Base->comesBefore(In) && "Base should come before In"); 851bdd1243dSDimitry Andric 852bdd1243dSDimitry Andric DepList Deps; 853bdd1243dSDimitry Andric std::deque<Instruction *> WorkQ = {In}; 854bdd1243dSDimitry Andric while (!WorkQ.empty()) { 855bdd1243dSDimitry Andric Instruction *D = WorkQ.front(); 856bdd1243dSDimitry Andric WorkQ.pop_front(); 85706c3fb27SDimitry Andric if (D != In) 858bdd1243dSDimitry Andric Deps.insert(D); 859bdd1243dSDimitry Andric for (Value *Op : D->operands()) { 860bdd1243dSDimitry Andric if (auto *I = dyn_cast<Instruction>(Op)) { 861bdd1243dSDimitry Andric if (I->getParent() == Parent && Base->comesBefore(I)) 862bdd1243dSDimitry Andric WorkQ.push_back(I); 863bdd1243dSDimitry Andric } 864bdd1243dSDimitry Andric } 865bdd1243dSDimitry Andric } 866bdd1243dSDimitry Andric return Deps; 867bdd1243dSDimitry Andric } 868bdd1243dSDimitry Andric 869e8d8bef9SDimitry Andric auto AlignVectors::createAddressGroups() -> bool { 870e8d8bef9SDimitry Andric // An address group created here may contain instructions spanning 871e8d8bef9SDimitry Andric // multiple basic blocks. 872e8d8bef9SDimitry Andric AddrList WorkStack; 873e8d8bef9SDimitry Andric 874e8d8bef9SDimitry Andric auto findBaseAndOffset = [&](AddrInfo &AI) -> std::pair<Instruction *, int> { 875e8d8bef9SDimitry Andric for (AddrInfo &W : WorkStack) { 876e8d8bef9SDimitry Andric if (auto D = HVC.calculatePointerDifference(AI.Addr, W.Addr)) 877e8d8bef9SDimitry Andric return std::make_pair(W.Inst, *D); 878e8d8bef9SDimitry Andric } 879e8d8bef9SDimitry Andric return std::make_pair(nullptr, 0); 880e8d8bef9SDimitry Andric }; 881e8d8bef9SDimitry Andric 882e8d8bef9SDimitry Andric auto traverseBlock = [&](DomTreeNode *DomN, auto Visit) -> void { 883e8d8bef9SDimitry Andric BasicBlock &Block = *DomN->getBlock(); 884e8d8bef9SDimitry Andric for (Instruction &I : Block) { 885e8d8bef9SDimitry Andric auto AI = this->getAddrInfo(I); // Use this-> for gcc6. 886e8d8bef9SDimitry Andric if (!AI) 887e8d8bef9SDimitry Andric continue; 888e8d8bef9SDimitry Andric auto F = findBaseAndOffset(*AI); 889e8d8bef9SDimitry Andric Instruction *GroupInst; 890e8d8bef9SDimitry Andric if (Instruction *BI = F.first) { 891e8d8bef9SDimitry Andric AI->Offset = F.second; 892e8d8bef9SDimitry Andric GroupInst = BI; 893e8d8bef9SDimitry Andric } else { 894e8d8bef9SDimitry Andric WorkStack.push_back(*AI); 895e8d8bef9SDimitry Andric GroupInst = AI->Inst; 896e8d8bef9SDimitry Andric } 897e8d8bef9SDimitry Andric AddrGroups[GroupInst].push_back(*AI); 898e8d8bef9SDimitry Andric } 899e8d8bef9SDimitry Andric 900e8d8bef9SDimitry Andric for (DomTreeNode *C : DomN->children()) 901e8d8bef9SDimitry Andric Visit(C, Visit); 902e8d8bef9SDimitry Andric 903e8d8bef9SDimitry Andric while (!WorkStack.empty() && WorkStack.back().Inst->getParent() == &Block) 904e8d8bef9SDimitry Andric WorkStack.pop_back(); 905e8d8bef9SDimitry Andric }; 906e8d8bef9SDimitry Andric 907e8d8bef9SDimitry Andric traverseBlock(HVC.DT.getRootNode(), traverseBlock); 908e8d8bef9SDimitry Andric assert(WorkStack.empty()); 909e8d8bef9SDimitry Andric 910e8d8bef9SDimitry Andric // AddrGroups are formed. 911e8d8bef9SDimitry Andric 912e8d8bef9SDimitry Andric // Remove groups of size 1. 913e8d8bef9SDimitry Andric erase_if(AddrGroups, [](auto &G) { return G.second.size() == 1; }); 914e8d8bef9SDimitry Andric // Remove groups that don't use HVX types. 915e8d8bef9SDimitry Andric erase_if(AddrGroups, [&](auto &G) { 9160eae32dcSDimitry Andric return llvm::none_of( 917e8d8bef9SDimitry Andric G.second, [&](auto &I) { return HVC.HST.isTypeForHVX(I.ValTy); }); 918e8d8bef9SDimitry Andric }); 919e8d8bef9SDimitry Andric 920e8d8bef9SDimitry Andric return !AddrGroups.empty(); 921e8d8bef9SDimitry Andric } 922e8d8bef9SDimitry Andric 923e8d8bef9SDimitry Andric auto AlignVectors::createLoadGroups(const AddrList &Group) const -> MoveList { 924e8d8bef9SDimitry Andric // Form load groups. 925e8d8bef9SDimitry Andric // To avoid complications with moving code across basic blocks, only form 926e8d8bef9SDimitry Andric // groups that are contained within a single basic block. 92706c3fb27SDimitry Andric unsigned SizeLimit = VAGroupSizeLimit; 92806c3fb27SDimitry Andric if (SizeLimit == 0) 92906c3fb27SDimitry Andric return {}; 930e8d8bef9SDimitry Andric 931e8d8bef9SDimitry Andric auto tryAddTo = [&](const AddrInfo &Info, MoveGroup &Move) { 932e8d8bef9SDimitry Andric assert(!Move.Main.empty() && "Move group should have non-empty Main"); 93306c3fb27SDimitry Andric if (Move.Main.size() >= SizeLimit) 93406c3fb27SDimitry Andric return false; 935e8d8bef9SDimitry Andric // Don't mix HVX and non-HVX instructions. 936e8d8bef9SDimitry Andric if (Move.IsHvx != isHvx(Info)) 937e8d8bef9SDimitry Andric return false; 938e8d8bef9SDimitry Andric // Leading instruction in the load group. 939e8d8bef9SDimitry Andric Instruction *Base = Move.Main.front(); 940e8d8bef9SDimitry Andric if (Base->getParent() != Info.Inst->getParent()) 941e8d8bef9SDimitry Andric return false; 94206c3fb27SDimitry Andric // Check if it's safe to move the load. 94306c3fb27SDimitry Andric if (!HVC.isSafeToMoveBeforeInBB(*Info.Inst, Base->getIterator())) 94406c3fb27SDimitry Andric return false; 94506c3fb27SDimitry Andric // And if it's safe to clone the dependencies. 94606c3fb27SDimitry Andric auto isSafeToCopyAtBase = [&](const Instruction *I) { 94706c3fb27SDimitry Andric return HVC.isSafeToMoveBeforeInBB(*I, Base->getIterator()) && 94806c3fb27SDimitry Andric HVC.isSafeToClone(*I); 949e8d8bef9SDimitry Andric }; 950e8d8bef9SDimitry Andric DepList Deps = getUpwardDeps(Info.Inst, Base); 95106c3fb27SDimitry Andric if (!llvm::all_of(Deps, isSafeToCopyAtBase)) 952e8d8bef9SDimitry Andric return false; 953e8d8bef9SDimitry Andric 954e8d8bef9SDimitry Andric Move.Main.push_back(Info.Inst); 955e8d8bef9SDimitry Andric llvm::append_range(Move.Deps, Deps); 956e8d8bef9SDimitry Andric return true; 957e8d8bef9SDimitry Andric }; 958e8d8bef9SDimitry Andric 959e8d8bef9SDimitry Andric MoveList LoadGroups; 960e8d8bef9SDimitry Andric 961e8d8bef9SDimitry Andric for (const AddrInfo &Info : Group) { 962e8d8bef9SDimitry Andric if (!Info.Inst->mayReadFromMemory()) 963e8d8bef9SDimitry Andric continue; 964e8d8bef9SDimitry Andric if (LoadGroups.empty() || !tryAddTo(Info, LoadGroups.back())) 965e8d8bef9SDimitry Andric LoadGroups.emplace_back(Info, Group.front().Inst, isHvx(Info), true); 966e8d8bef9SDimitry Andric } 967e8d8bef9SDimitry Andric 968e8d8bef9SDimitry Andric // Erase singleton groups. 969e8d8bef9SDimitry Andric erase_if(LoadGroups, [](const MoveGroup &G) { return G.Main.size() <= 1; }); 97006c3fb27SDimitry Andric 97106c3fb27SDimitry Andric // Erase HVX groups on targets < HvxV62 (due to lack of predicated loads). 97206c3fb27SDimitry Andric if (!HVC.HST.useHVXV62Ops()) 97306c3fb27SDimitry Andric erase_if(LoadGroups, [](const MoveGroup &G) { return G.IsHvx; }); 97406c3fb27SDimitry Andric 975e8d8bef9SDimitry Andric return LoadGroups; 976e8d8bef9SDimitry Andric } 977e8d8bef9SDimitry Andric 978e8d8bef9SDimitry Andric auto AlignVectors::createStoreGroups(const AddrList &Group) const -> MoveList { 979e8d8bef9SDimitry Andric // Form store groups. 980e8d8bef9SDimitry Andric // To avoid complications with moving code across basic blocks, only form 981e8d8bef9SDimitry Andric // groups that are contained within a single basic block. 98206c3fb27SDimitry Andric unsigned SizeLimit = VAGroupSizeLimit; 98306c3fb27SDimitry Andric if (SizeLimit == 0) 98406c3fb27SDimitry Andric return {}; 985e8d8bef9SDimitry Andric 986e8d8bef9SDimitry Andric auto tryAddTo = [&](const AddrInfo &Info, MoveGroup &Move) { 987e8d8bef9SDimitry Andric assert(!Move.Main.empty() && "Move group should have non-empty Main"); 98806c3fb27SDimitry Andric if (Move.Main.size() >= SizeLimit) 98906c3fb27SDimitry Andric return false; 990e8d8bef9SDimitry Andric // For stores with return values we'd have to collect downward depenencies. 991e8d8bef9SDimitry Andric // There are no such stores that we handle at the moment, so omit that. 992e8d8bef9SDimitry Andric assert(Info.Inst->getType()->isVoidTy() && 993e8d8bef9SDimitry Andric "Not handling stores with return values"); 994e8d8bef9SDimitry Andric // Don't mix HVX and non-HVX instructions. 995e8d8bef9SDimitry Andric if (Move.IsHvx != isHvx(Info)) 996e8d8bef9SDimitry Andric return false; 997e8d8bef9SDimitry Andric // For stores we need to be careful whether it's safe to move them. 998e8d8bef9SDimitry Andric // Stores that are otherwise safe to move together may not appear safe 999e8d8bef9SDimitry Andric // to move over one another (i.e. isSafeToMoveBefore may return false). 1000e8d8bef9SDimitry Andric Instruction *Base = Move.Main.front(); 1001e8d8bef9SDimitry Andric if (Base->getParent() != Info.Inst->getParent()) 1002e8d8bef9SDimitry Andric return false; 1003e8d8bef9SDimitry Andric if (!HVC.isSafeToMoveBeforeInBB(*Info.Inst, Base->getIterator(), Move.Main)) 1004e8d8bef9SDimitry Andric return false; 1005e8d8bef9SDimitry Andric Move.Main.push_back(Info.Inst); 1006e8d8bef9SDimitry Andric return true; 1007e8d8bef9SDimitry Andric }; 1008e8d8bef9SDimitry Andric 1009e8d8bef9SDimitry Andric MoveList StoreGroups; 1010e8d8bef9SDimitry Andric 1011e8d8bef9SDimitry Andric for (auto I = Group.rbegin(), E = Group.rend(); I != E; ++I) { 1012e8d8bef9SDimitry Andric const AddrInfo &Info = *I; 1013e8d8bef9SDimitry Andric if (!Info.Inst->mayWriteToMemory()) 1014e8d8bef9SDimitry Andric continue; 1015e8d8bef9SDimitry Andric if (StoreGroups.empty() || !tryAddTo(Info, StoreGroups.back())) 1016e8d8bef9SDimitry Andric StoreGroups.emplace_back(Info, Group.front().Inst, isHvx(Info), false); 1017e8d8bef9SDimitry Andric } 1018e8d8bef9SDimitry Andric 1019e8d8bef9SDimitry Andric // Erase singleton groups. 1020e8d8bef9SDimitry Andric erase_if(StoreGroups, [](const MoveGroup &G) { return G.Main.size() <= 1; }); 102106c3fb27SDimitry Andric 102206c3fb27SDimitry Andric // Erase HVX groups on targets < HvxV62 (due to lack of predicated loads). 102306c3fb27SDimitry Andric if (!HVC.HST.useHVXV62Ops()) 102406c3fb27SDimitry Andric erase_if(StoreGroups, [](const MoveGroup &G) { return G.IsHvx; }); 102506c3fb27SDimitry Andric 102606c3fb27SDimitry Andric // Erase groups where every store is a full HVX vector. The reason is that 102706c3fb27SDimitry Andric // aligning predicated stores generates complex code that may be less 102806c3fb27SDimitry Andric // efficient than a sequence of unaligned vector stores. 102906c3fb27SDimitry Andric if (!VADoFullStores) { 103006c3fb27SDimitry Andric erase_if(StoreGroups, [this](const MoveGroup &G) { 103106c3fb27SDimitry Andric return G.IsHvx && llvm::all_of(G.Main, [this](Instruction *S) { 103206c3fb27SDimitry Andric auto MaybeInfo = this->getAddrInfo(*S); 103306c3fb27SDimitry Andric assert(MaybeInfo.has_value()); 103406c3fb27SDimitry Andric return HVC.HST.isHVXVectorType( 103506c3fb27SDimitry Andric EVT::getEVT(MaybeInfo->ValTy, false)); 103606c3fb27SDimitry Andric }); 103706c3fb27SDimitry Andric }); 103806c3fb27SDimitry Andric } 103906c3fb27SDimitry Andric 1040e8d8bef9SDimitry Andric return StoreGroups; 1041e8d8bef9SDimitry Andric } 1042e8d8bef9SDimitry Andric 104306c3fb27SDimitry Andric auto AlignVectors::moveTogether(MoveGroup &Move) const -> bool { 104406c3fb27SDimitry Andric // Move all instructions to be adjacent. 1045e8d8bef9SDimitry Andric assert(!Move.Main.empty() && "Move group should have non-empty Main"); 1046e8d8bef9SDimitry Andric Instruction *Where = Move.Main.front(); 1047e8d8bef9SDimitry Andric 1048e8d8bef9SDimitry Andric if (Move.IsLoad) { 104906c3fb27SDimitry Andric // Move all the loads (and dependencies) to where the first load is. 105006c3fb27SDimitry Andric // Clone all deps to before Where, keeping order. 105106c3fb27SDimitry Andric Move.Clones = cloneBefore(Where, Move.Deps); 1052e8d8bef9SDimitry Andric // Move all main instructions to after Where, keeping order. 1053e8d8bef9SDimitry Andric ArrayRef<Instruction *> Main(Move.Main); 105406c3fb27SDimitry Andric for (Instruction *M : Main) { 105506c3fb27SDimitry Andric if (M != Where) 1056e8d8bef9SDimitry Andric M->moveAfter(Where); 105706c3fb27SDimitry Andric for (auto [Old, New] : Move.Clones) 105806c3fb27SDimitry Andric M->replaceUsesOfWith(Old, New); 1059e8d8bef9SDimitry Andric Where = M; 1060e8d8bef9SDimitry Andric } 106106c3fb27SDimitry Andric // Replace Deps with the clones. 106206c3fb27SDimitry Andric for (int i = 0, e = Move.Deps.size(); i != e; ++i) 106306c3fb27SDimitry Andric Move.Deps[i] = Move.Clones[Move.Deps[i]]; 1064e8d8bef9SDimitry Andric } else { 106506c3fb27SDimitry Andric // Move all the stores to where the last store is. 1066e8d8bef9SDimitry Andric // NOTE: Deps are empty for "store" groups. If they need to be 1067e8d8bef9SDimitry Andric // non-empty, decide on the order. 1068e8d8bef9SDimitry Andric assert(Move.Deps.empty()); 1069e8d8bef9SDimitry Andric // Move all main instructions to before Where, inverting order. 1070e8d8bef9SDimitry Andric ArrayRef<Instruction *> Main(Move.Main); 1071e8d8bef9SDimitry Andric for (Instruction *M : Main.drop_front(1)) { 1072e8d8bef9SDimitry Andric M->moveBefore(Where); 1073e8d8bef9SDimitry Andric Where = M; 1074e8d8bef9SDimitry Andric } 1075e8d8bef9SDimitry Andric } 1076e8d8bef9SDimitry Andric 1077e8d8bef9SDimitry Andric return Move.Main.size() + Move.Deps.size() > 1; 1078e8d8bef9SDimitry Andric } 1079e8d8bef9SDimitry Andric 108006c3fb27SDimitry Andric template <typename T> 108106c3fb27SDimitry Andric auto AlignVectors::cloneBefore(Instruction *To, T &&Insts) const -> InstMap { 108206c3fb27SDimitry Andric InstMap Map; 108306c3fb27SDimitry Andric 108406c3fb27SDimitry Andric for (Instruction *I : Insts) { 108506c3fb27SDimitry Andric assert(HVC.isSafeToClone(*I)); 108606c3fb27SDimitry Andric Instruction *C = I->clone(); 108706c3fb27SDimitry Andric C->setName(Twine("c.") + I->getName() + "."); 108806c3fb27SDimitry Andric C->insertBefore(To); 108906c3fb27SDimitry Andric 109006c3fb27SDimitry Andric for (auto [Old, New] : Map) 109106c3fb27SDimitry Andric C->replaceUsesOfWith(Old, New); 109206c3fb27SDimitry Andric Map.insert(std::make_pair(I, C)); 109306c3fb27SDimitry Andric } 109406c3fb27SDimitry Andric return Map; 109506c3fb27SDimitry Andric } 109606c3fb27SDimitry Andric 1097bdd1243dSDimitry Andric auto AlignVectors::realignLoadGroup(IRBuilderBase &Builder, 1098bdd1243dSDimitry Andric const ByteSpan &VSpan, int ScLen, 1099bdd1243dSDimitry Andric Value *AlignVal, Value *AlignAddr) const 1100bdd1243dSDimitry Andric -> void { 110106c3fb27SDimitry Andric LLVM_DEBUG(dbgs() << __func__ << "\n"); 110206c3fb27SDimitry Andric 1103bdd1243dSDimitry Andric Type *SecTy = HVC.getByteTy(ScLen); 1104bdd1243dSDimitry Andric int NumSectors = (VSpan.extent() + ScLen - 1) / ScLen; 1105bdd1243dSDimitry Andric bool DoAlign = !HVC.isZero(AlignVal); 1106bdd1243dSDimitry Andric BasicBlock::iterator BasePos = Builder.GetInsertPoint(); 1107bdd1243dSDimitry Andric BasicBlock *BaseBlock = Builder.GetInsertBlock(); 1108bdd1243dSDimitry Andric 1109bdd1243dSDimitry Andric ByteSpan ASpan; 1110bdd1243dSDimitry Andric auto *True = HVC.getFullValue(HVC.getBoolTy(ScLen)); 1111bdd1243dSDimitry Andric auto *Undef = UndefValue::get(SecTy); 1112bdd1243dSDimitry Andric 111306c3fb27SDimitry Andric // Created load does not have to be "Instruction" (e.g. "undef"). 111406c3fb27SDimitry Andric SmallVector<Value *> Loads(NumSectors + DoAlign, nullptr); 1115bdd1243dSDimitry Andric 1116bdd1243dSDimitry Andric // We could create all of the aligned loads, and generate the valigns 1117bdd1243dSDimitry Andric // at the location of the first load, but for large load groups, this 1118bdd1243dSDimitry Andric // could create highly suboptimal code (there have been groups of 140+ 1119bdd1243dSDimitry Andric // loads in real code). 1120bdd1243dSDimitry Andric // Instead, place the loads/valigns as close to the users as possible. 1121bdd1243dSDimitry Andric // In any case we need to have a mapping from the blocks of VSpan (the 1122bdd1243dSDimitry Andric // span covered by the pre-existing loads) to ASpan (the span covered 1123bdd1243dSDimitry Andric // by the aligned loads). There is a small problem, though: ASpan needs 112406c3fb27SDimitry Andric // to have pointers to the loads/valigns, but we don't have these loads 112506c3fb27SDimitry Andric // because we don't know where to put them yet. We find out by creating 112606c3fb27SDimitry Andric // a section of ASpan that corresponds to values (blocks) from VSpan, 112706c3fb27SDimitry Andric // and checking where the new load should be placed. We need to attach 112806c3fb27SDimitry Andric // this location information to each block in ASpan somehow, so we put 112906c3fb27SDimitry Andric // distincts values for Seg.Val in each ASpan.Blocks[i], and use a map 113006c3fb27SDimitry Andric // to store the location for each Seg.Val. 113106c3fb27SDimitry Andric // The distinct values happen to be Blocks[i].Seg.Val = &Blocks[i], 113206c3fb27SDimitry Andric // which helps with printing ByteSpans without crashing when printing 113306c3fb27SDimitry Andric // Segments with these temporary identifiers in place of Val. 1134bdd1243dSDimitry Andric 1135bdd1243dSDimitry Andric // Populate the blocks first, to avoid reallocations of the vector 1136bdd1243dSDimitry Andric // interfering with generating the placeholder addresses. 1137bdd1243dSDimitry Andric for (int Index = 0; Index != NumSectors; ++Index) 1138bdd1243dSDimitry Andric ASpan.Blocks.emplace_back(nullptr, ScLen, Index * ScLen); 1139bdd1243dSDimitry Andric for (int Index = 0; Index != NumSectors; ++Index) { 1140bdd1243dSDimitry Andric ASpan.Blocks[Index].Seg.Val = 1141bdd1243dSDimitry Andric reinterpret_cast<Value *>(&ASpan.Blocks[Index]); 1142bdd1243dSDimitry Andric } 1143bdd1243dSDimitry Andric 1144bdd1243dSDimitry Andric // Multiple values from VSpan can map to the same value in ASpan. Since we 1145bdd1243dSDimitry Andric // try to create loads lazily, we need to find the earliest use for each 1146bdd1243dSDimitry Andric // value from ASpan. 1147bdd1243dSDimitry Andric DenseMap<void *, Instruction *> EarliestUser; 1148bdd1243dSDimitry Andric auto isEarlier = [](Instruction *A, Instruction *B) { 1149bdd1243dSDimitry Andric if (B == nullptr) 1150bdd1243dSDimitry Andric return true; 1151bdd1243dSDimitry Andric if (A == nullptr) 1152bdd1243dSDimitry Andric return false; 1153bdd1243dSDimitry Andric assert(A->getParent() == B->getParent()); 1154bdd1243dSDimitry Andric return A->comesBefore(B); 1155bdd1243dSDimitry Andric }; 1156bdd1243dSDimitry Andric auto earliestUser = [&](const auto &Uses) { 1157bdd1243dSDimitry Andric Instruction *User = nullptr; 1158bdd1243dSDimitry Andric for (const Use &U : Uses) { 1159bdd1243dSDimitry Andric auto *I = dyn_cast<Instruction>(U.getUser()); 1160bdd1243dSDimitry Andric assert(I != nullptr && "Load used in a non-instruction?"); 116106c3fb27SDimitry Andric // Make sure we only consider users in this block, but we need 1162bdd1243dSDimitry Andric // to remember if there were users outside the block too. This is 116306c3fb27SDimitry Andric // because if no users are found, aligned loads will not be created. 1164bdd1243dSDimitry Andric if (I->getParent() == BaseBlock) { 1165bdd1243dSDimitry Andric if (!isa<PHINode>(I)) 1166bdd1243dSDimitry Andric User = std::min(User, I, isEarlier); 1167bdd1243dSDimitry Andric } else { 1168bdd1243dSDimitry Andric User = std::min(User, BaseBlock->getTerminator(), isEarlier); 1169bdd1243dSDimitry Andric } 1170bdd1243dSDimitry Andric } 1171bdd1243dSDimitry Andric return User; 1172bdd1243dSDimitry Andric }; 1173bdd1243dSDimitry Andric 1174bdd1243dSDimitry Andric for (const ByteSpan::Block &B : VSpan) { 1175bdd1243dSDimitry Andric ByteSpan ASection = ASpan.section(B.Pos, B.Seg.Size); 1176bdd1243dSDimitry Andric for (const ByteSpan::Block &S : ASection) { 1177bdd1243dSDimitry Andric EarliestUser[S.Seg.Val] = std::min( 1178bdd1243dSDimitry Andric EarliestUser[S.Seg.Val], earliestUser(B.Seg.Val->uses()), isEarlier); 1179bdd1243dSDimitry Andric } 1180bdd1243dSDimitry Andric } 1181bdd1243dSDimitry Andric 118206c3fb27SDimitry Andric LLVM_DEBUG({ 118306c3fb27SDimitry Andric dbgs() << "ASpan:\n" << ASpan << '\n'; 118406c3fb27SDimitry Andric dbgs() << "Earliest users of ASpan:\n"; 118506c3fb27SDimitry Andric for (auto &[Val, User] : EarliestUser) { 118606c3fb27SDimitry Andric dbgs() << Val << "\n ->" << *User << '\n'; 118706c3fb27SDimitry Andric } 118806c3fb27SDimitry Andric }); 118906c3fb27SDimitry Andric 1190bdd1243dSDimitry Andric auto createLoad = [&](IRBuilderBase &Builder, const ByteSpan &VSpan, 119106c3fb27SDimitry Andric int Index, bool MakePred) { 1192bdd1243dSDimitry Andric Value *Ptr = 1193bdd1243dSDimitry Andric createAdjustedPointer(Builder, AlignAddr, SecTy, Index * ScLen); 119406c3fb27SDimitry Andric Value *Predicate = 119506c3fb27SDimitry Andric MakePred ? makeTestIfUnaligned(Builder, AlignVal, ScLen) : nullptr; 119606c3fb27SDimitry Andric 1197bdd1243dSDimitry Andric // If vector shifting is potentially needed, accumulate metadata 1198bdd1243dSDimitry Andric // from source sections of twice the load width. 1199bdd1243dSDimitry Andric int Start = (Index - DoAlign) * ScLen; 1200bdd1243dSDimitry Andric int Width = (1 + DoAlign) * ScLen; 120106c3fb27SDimitry Andric return this->createLoad(Builder, SecTy, Ptr, Predicate, ScLen, True, Undef, 1202bdd1243dSDimitry Andric VSpan.section(Start, Width).values()); 1203bdd1243dSDimitry Andric }; 1204bdd1243dSDimitry Andric 1205bdd1243dSDimitry Andric auto moveBefore = [this](Instruction *In, Instruction *To) { 1206bdd1243dSDimitry Andric // Move In and its upward dependencies to before To. 1207bdd1243dSDimitry Andric assert(In->getParent() == To->getParent()); 1208bdd1243dSDimitry Andric DepList Deps = getUpwardDeps(In, To); 120906c3fb27SDimitry Andric In->moveBefore(To); 1210bdd1243dSDimitry Andric // DepList is sorted with respect to positions in the basic block. 121106c3fb27SDimitry Andric InstMap Map = cloneBefore(In, Deps); 121206c3fb27SDimitry Andric for (auto [Old, New] : Map) 121306c3fb27SDimitry Andric In->replaceUsesOfWith(Old, New); 1214bdd1243dSDimitry Andric }; 1215bdd1243dSDimitry Andric 1216bdd1243dSDimitry Andric // Generate necessary loads at appropriate locations. 121706c3fb27SDimitry Andric LLVM_DEBUG(dbgs() << "Creating loads for ASpan sectors\n"); 1218bdd1243dSDimitry Andric for (int Index = 0; Index != NumSectors + 1; ++Index) { 1219bdd1243dSDimitry Andric // In ASpan, each block will be either a single aligned load, or a 1220bdd1243dSDimitry Andric // valign of a pair of loads. In the latter case, an aligned load j 1221bdd1243dSDimitry Andric // will belong to the current valign, and the one in the previous 1222bdd1243dSDimitry Andric // block (for j > 0). 122306c3fb27SDimitry Andric // Place the load at a location which will dominate the valign, assuming 122406c3fb27SDimitry Andric // the valign will be placed right before the earliest user. 1225bdd1243dSDimitry Andric Instruction *PrevAt = 1226bdd1243dSDimitry Andric DoAlign && Index > 0 ? EarliestUser[&ASpan[Index - 1]] : nullptr; 1227bdd1243dSDimitry Andric Instruction *ThisAt = 1228bdd1243dSDimitry Andric Index < NumSectors ? EarliestUser[&ASpan[Index]] : nullptr; 1229bdd1243dSDimitry Andric if (auto *Where = std::min(PrevAt, ThisAt, isEarlier)) { 1230bdd1243dSDimitry Andric Builder.SetInsertPoint(Where); 123106c3fb27SDimitry Andric Loads[Index] = 123206c3fb27SDimitry Andric createLoad(Builder, VSpan, Index, DoAlign && Index == NumSectors); 123306c3fb27SDimitry Andric // We know it's safe to put the load at BasePos, but we'd prefer to put 123406c3fb27SDimitry Andric // it at "Where". To see if the load is safe to be placed at Where, put 123506c3fb27SDimitry Andric // it there first and then check if it's safe to move it to BasePos. 123606c3fb27SDimitry Andric // If not, then the load needs to be placed at BasePos. 1237bdd1243dSDimitry Andric // We can't do this check proactively because we need the load to exist 1238bdd1243dSDimitry Andric // in order to check legality. 123906c3fb27SDimitry Andric if (auto *Load = dyn_cast<Instruction>(Loads[Index])) { 124006c3fb27SDimitry Andric if (!HVC.isSafeToMoveBeforeInBB(*Load, BasePos)) 124106c3fb27SDimitry Andric moveBefore(Load, &*BasePos); 124206c3fb27SDimitry Andric } 124306c3fb27SDimitry Andric LLVM_DEBUG(dbgs() << "Loads[" << Index << "]:" << *Loads[Index] << '\n'); 1244bdd1243dSDimitry Andric } 1245bdd1243dSDimitry Andric } 124606c3fb27SDimitry Andric 1247bdd1243dSDimitry Andric // Generate valigns if needed, and fill in proper values in ASpan 124806c3fb27SDimitry Andric LLVM_DEBUG(dbgs() << "Creating values for ASpan sectors\n"); 1249bdd1243dSDimitry Andric for (int Index = 0; Index != NumSectors; ++Index) { 1250bdd1243dSDimitry Andric ASpan[Index].Seg.Val = nullptr; 1251bdd1243dSDimitry Andric if (auto *Where = EarliestUser[&ASpan[Index]]) { 1252bdd1243dSDimitry Andric Builder.SetInsertPoint(Where); 1253bdd1243dSDimitry Andric Value *Val = Loads[Index]; 1254bdd1243dSDimitry Andric assert(Val != nullptr); 1255bdd1243dSDimitry Andric if (DoAlign) { 1256bdd1243dSDimitry Andric Value *NextLoad = Loads[Index + 1]; 1257bdd1243dSDimitry Andric assert(NextLoad != nullptr); 1258bdd1243dSDimitry Andric Val = HVC.vralignb(Builder, Val, NextLoad, AlignVal); 1259bdd1243dSDimitry Andric } 1260bdd1243dSDimitry Andric ASpan[Index].Seg.Val = Val; 126106c3fb27SDimitry Andric LLVM_DEBUG(dbgs() << "ASpan[" << Index << "]:" << *Val << '\n'); 1262bdd1243dSDimitry Andric } 1263bdd1243dSDimitry Andric } 1264bdd1243dSDimitry Andric 1265bdd1243dSDimitry Andric for (const ByteSpan::Block &B : VSpan) { 1266bdd1243dSDimitry Andric ByteSpan ASection = ASpan.section(B.Pos, B.Seg.Size).shift(-B.Pos); 1267bdd1243dSDimitry Andric Value *Accum = UndefValue::get(HVC.getByteTy(B.Seg.Size)); 1268bdd1243dSDimitry Andric Builder.SetInsertPoint(cast<Instruction>(B.Seg.Val)); 1269bdd1243dSDimitry Andric 127006c3fb27SDimitry Andric // We're generating a reduction, where each instruction depends on 127106c3fb27SDimitry Andric // the previous one, so we need to order them according to the position 127206c3fb27SDimitry Andric // of their inputs in the code. 127306c3fb27SDimitry Andric std::vector<ByteSpan::Block *> ABlocks; 1274bdd1243dSDimitry Andric for (ByteSpan::Block &S : ASection) { 127506c3fb27SDimitry Andric if (S.Seg.Val != nullptr) 127606c3fb27SDimitry Andric ABlocks.push_back(&S); 127706c3fb27SDimitry Andric } 127806c3fb27SDimitry Andric llvm::sort(ABlocks, 127906c3fb27SDimitry Andric [&](const ByteSpan::Block *A, const ByteSpan::Block *B) { 128006c3fb27SDimitry Andric return isEarlier(cast<Instruction>(A->Seg.Val), 128106c3fb27SDimitry Andric cast<Instruction>(B->Seg.Val)); 128206c3fb27SDimitry Andric }); 128306c3fb27SDimitry Andric for (ByteSpan::Block *S : ABlocks) { 1284bdd1243dSDimitry Andric // The processing of the data loaded by the aligned loads 1285bdd1243dSDimitry Andric // needs to be inserted after the data is available. 128606c3fb27SDimitry Andric Instruction *SegI = cast<Instruction>(S->Seg.Val); 1287bdd1243dSDimitry Andric Builder.SetInsertPoint(&*std::next(SegI->getIterator())); 128806c3fb27SDimitry Andric Value *Pay = HVC.vbytes(Builder, getPayload(S->Seg.Val)); 128906c3fb27SDimitry Andric Accum = 129006c3fb27SDimitry Andric HVC.insertb(Builder, Accum, Pay, S->Seg.Start, S->Seg.Size, S->Pos); 1291bdd1243dSDimitry Andric } 1292bdd1243dSDimitry Andric // Instead of casting everything to bytes for the vselect, cast to the 1293bdd1243dSDimitry Andric // original value type. This will avoid complications with casting masks. 1294bdd1243dSDimitry Andric // For example, in cases when the original mask applied to i32, it could 1295bdd1243dSDimitry Andric // be converted to a mask applicable to i8 via pred_typecast intrinsic, 1296bdd1243dSDimitry Andric // but if the mask is not exactly of HVX length, extra handling would be 1297bdd1243dSDimitry Andric // needed to make it work. 1298bdd1243dSDimitry Andric Type *ValTy = getPayload(B.Seg.Val)->getType(); 129906c3fb27SDimitry Andric Value *Cast = Builder.CreateBitCast(Accum, ValTy, "cst"); 1300bdd1243dSDimitry Andric Value *Sel = Builder.CreateSelect(getMask(B.Seg.Val), Cast, 130106c3fb27SDimitry Andric getPassThrough(B.Seg.Val), "sel"); 1302bdd1243dSDimitry Andric B.Seg.Val->replaceAllUsesWith(Sel); 1303bdd1243dSDimitry Andric } 1304bdd1243dSDimitry Andric } 1305bdd1243dSDimitry Andric 1306bdd1243dSDimitry Andric auto AlignVectors::realignStoreGroup(IRBuilderBase &Builder, 1307bdd1243dSDimitry Andric const ByteSpan &VSpan, int ScLen, 1308bdd1243dSDimitry Andric Value *AlignVal, Value *AlignAddr) const 1309bdd1243dSDimitry Andric -> void { 131006c3fb27SDimitry Andric LLVM_DEBUG(dbgs() << __func__ << "\n"); 131106c3fb27SDimitry Andric 1312bdd1243dSDimitry Andric Type *SecTy = HVC.getByteTy(ScLen); 1313bdd1243dSDimitry Andric int NumSectors = (VSpan.extent() + ScLen - 1) / ScLen; 1314bdd1243dSDimitry Andric bool DoAlign = !HVC.isZero(AlignVal); 1315bdd1243dSDimitry Andric 1316bdd1243dSDimitry Andric // Stores. 1317bdd1243dSDimitry Andric ByteSpan ASpanV, ASpanM; 1318bdd1243dSDimitry Andric 1319bdd1243dSDimitry Andric // Return a vector value corresponding to the input value Val: 1320bdd1243dSDimitry Andric // either <1 x Val> for scalar Val, or Val itself for vector Val. 1321bdd1243dSDimitry Andric auto MakeVec = [](IRBuilderBase &Builder, Value *Val) -> Value * { 1322bdd1243dSDimitry Andric Type *Ty = Val->getType(); 1323bdd1243dSDimitry Andric if (Ty->isVectorTy()) 1324bdd1243dSDimitry Andric return Val; 1325bdd1243dSDimitry Andric auto *VecTy = VectorType::get(Ty, 1, /*Scalable=*/false); 132606c3fb27SDimitry Andric return Builder.CreateBitCast(Val, VecTy, "cst"); 1327bdd1243dSDimitry Andric }; 1328bdd1243dSDimitry Andric 1329bdd1243dSDimitry Andric // Create an extra "undef" sector at the beginning and at the end. 1330bdd1243dSDimitry Andric // They will be used as the left/right filler in the vlalign step. 133106c3fb27SDimitry Andric for (int Index = (DoAlign ? -1 : 0); Index != NumSectors + DoAlign; ++Index) { 1332bdd1243dSDimitry Andric // For stores, the size of each section is an aligned vector length. 1333bdd1243dSDimitry Andric // Adjust the store offsets relative to the section start offset. 133406c3fb27SDimitry Andric ByteSpan VSection = 133506c3fb27SDimitry Andric VSpan.section(Index * ScLen, ScLen).shift(-Index * ScLen); 133606c3fb27SDimitry Andric Value *Undef = UndefValue::get(SecTy); 133706c3fb27SDimitry Andric Value *Zero = HVC.getNullValue(SecTy); 133806c3fb27SDimitry Andric Value *AccumV = Undef; 133906c3fb27SDimitry Andric Value *AccumM = Zero; 1340bdd1243dSDimitry Andric for (ByteSpan::Block &S : VSection) { 1341bdd1243dSDimitry Andric Value *Pay = getPayload(S.Seg.Val); 1342bdd1243dSDimitry Andric Value *Mask = HVC.rescale(Builder, MakeVec(Builder, getMask(S.Seg.Val)), 1343bdd1243dSDimitry Andric Pay->getType(), HVC.getByteTy()); 134406c3fb27SDimitry Andric Value *PartM = HVC.insertb(Builder, Zero, HVC.vbytes(Builder, Mask), 1345bdd1243dSDimitry Andric S.Seg.Start, S.Seg.Size, S.Pos); 134606c3fb27SDimitry Andric AccumM = Builder.CreateOr(AccumM, PartM); 134706c3fb27SDimitry Andric 134806c3fb27SDimitry Andric Value *PartV = HVC.insertb(Builder, Undef, HVC.vbytes(Builder, Pay), 1349bdd1243dSDimitry Andric S.Seg.Start, S.Seg.Size, S.Pos); 135006c3fb27SDimitry Andric 135106c3fb27SDimitry Andric AccumV = Builder.CreateSelect( 135206c3fb27SDimitry Andric Builder.CreateICmp(CmpInst::ICMP_NE, PartM, Zero), PartV, AccumV); 1353bdd1243dSDimitry Andric } 135406c3fb27SDimitry Andric ASpanV.Blocks.emplace_back(AccumV, ScLen, Index * ScLen); 135506c3fb27SDimitry Andric ASpanM.Blocks.emplace_back(AccumM, ScLen, Index * ScLen); 1356bdd1243dSDimitry Andric } 1357bdd1243dSDimitry Andric 135806c3fb27SDimitry Andric LLVM_DEBUG({ 135906c3fb27SDimitry Andric dbgs() << "ASpanV before vlalign:\n" << ASpanV << '\n'; 136006c3fb27SDimitry Andric dbgs() << "ASpanM before vlalign:\n" << ASpanM << '\n'; 136106c3fb27SDimitry Andric }); 136206c3fb27SDimitry Andric 1363bdd1243dSDimitry Andric // vlalign 1364bdd1243dSDimitry Andric if (DoAlign) { 136506c3fb27SDimitry Andric for (int Index = 1; Index != NumSectors + 2; ++Index) { 136606c3fb27SDimitry Andric Value *PrevV = ASpanV[Index - 1].Seg.Val, *ThisV = ASpanV[Index].Seg.Val; 136706c3fb27SDimitry Andric Value *PrevM = ASpanM[Index - 1].Seg.Val, *ThisM = ASpanM[Index].Seg.Val; 1368bdd1243dSDimitry Andric assert(isSectorTy(PrevV->getType()) && isSectorTy(PrevM->getType())); 136906c3fb27SDimitry Andric ASpanV[Index - 1].Seg.Val = HVC.vlalignb(Builder, PrevV, ThisV, AlignVal); 137006c3fb27SDimitry Andric ASpanM[Index - 1].Seg.Val = HVC.vlalignb(Builder, PrevM, ThisM, AlignVal); 1371bdd1243dSDimitry Andric } 1372bdd1243dSDimitry Andric } 1373bdd1243dSDimitry Andric 137406c3fb27SDimitry Andric LLVM_DEBUG({ 137506c3fb27SDimitry Andric dbgs() << "ASpanV after vlalign:\n" << ASpanV << '\n'; 137606c3fb27SDimitry Andric dbgs() << "ASpanM after vlalign:\n" << ASpanM << '\n'; 137706c3fb27SDimitry Andric }); 137806c3fb27SDimitry Andric 137906c3fb27SDimitry Andric auto createStore = [&](IRBuilderBase &Builder, const ByteSpan &ASpanV, 138006c3fb27SDimitry Andric const ByteSpan &ASpanM, int Index, bool MakePred) { 138106c3fb27SDimitry Andric Value *Val = ASpanV[Index].Seg.Val; 138206c3fb27SDimitry Andric Value *Mask = ASpanM[Index].Seg.Val; // bytes 138306c3fb27SDimitry Andric if (HVC.isUndef(Val) || HVC.isZero(Mask)) 138406c3fb27SDimitry Andric return; 138506c3fb27SDimitry Andric Value *Ptr = 138606c3fb27SDimitry Andric createAdjustedPointer(Builder, AlignAddr, SecTy, Index * ScLen); 138706c3fb27SDimitry Andric Value *Predicate = 138806c3fb27SDimitry Andric MakePred ? makeTestIfUnaligned(Builder, AlignVal, ScLen) : nullptr; 138906c3fb27SDimitry Andric 1390bdd1243dSDimitry Andric // If vector shifting is potentially needed, accumulate metadata 1391bdd1243dSDimitry Andric // from source sections of twice the store width. 139206c3fb27SDimitry Andric int Start = (Index - DoAlign) * ScLen; 1393bdd1243dSDimitry Andric int Width = (1 + DoAlign) * ScLen; 139406c3fb27SDimitry Andric this->createStore(Builder, Val, Ptr, Predicate, ScLen, 139506c3fb27SDimitry Andric HVC.vlsb(Builder, Mask), 1396bdd1243dSDimitry Andric VSpan.section(Start, Width).values()); 139706c3fb27SDimitry Andric }; 139806c3fb27SDimitry Andric 139906c3fb27SDimitry Andric for (int Index = 0; Index != NumSectors + DoAlign; ++Index) { 140006c3fb27SDimitry Andric createStore(Builder, ASpanV, ASpanM, Index, DoAlign && Index == NumSectors); 1401bdd1243dSDimitry Andric } 1402bdd1243dSDimitry Andric } 1403bdd1243dSDimitry Andric 1404e8d8bef9SDimitry Andric auto AlignVectors::realignGroup(const MoveGroup &Move) const -> bool { 140506c3fb27SDimitry Andric LLVM_DEBUG(dbgs() << "Realigning group:\n" << Move << '\n'); 140606c3fb27SDimitry Andric 1407e8d8bef9SDimitry Andric // TODO: Needs support for masked loads/stores of "scalar" vectors. 1408e8d8bef9SDimitry Andric if (!Move.IsHvx) 1409e8d8bef9SDimitry Andric return false; 1410e8d8bef9SDimitry Andric 1411e8d8bef9SDimitry Andric // Return the element with the maximum alignment from Range, 1412e8d8bef9SDimitry Andric // where GetValue obtains the value to compare from an element. 1413e8d8bef9SDimitry Andric auto getMaxOf = [](auto Range, auto GetValue) { 1414*0fca6ea1SDimitry Andric return *llvm::max_element(Range, [&GetValue](auto &A, auto &B) { 1415*0fca6ea1SDimitry Andric return GetValue(A) < GetValue(B); 1416*0fca6ea1SDimitry Andric }); 1417e8d8bef9SDimitry Andric }; 1418e8d8bef9SDimitry Andric 1419e8d8bef9SDimitry Andric const AddrList &BaseInfos = AddrGroups.at(Move.Base); 1420e8d8bef9SDimitry Andric 1421e8d8bef9SDimitry Andric // Conceptually, there is a vector of N bytes covering the addresses 1422e8d8bef9SDimitry Andric // starting from the minimum offset (i.e. Base.Addr+Start). This vector 1423e8d8bef9SDimitry Andric // represents a contiguous memory region that spans all accessed memory 1424e8d8bef9SDimitry Andric // locations. 1425e8d8bef9SDimitry Andric // The correspondence between loaded or stored values will be expressed 1426e8d8bef9SDimitry Andric // in terms of this vector. For example, the 0th element of the vector 1427e8d8bef9SDimitry Andric // from the Base address info will start at byte Start from the beginning 1428e8d8bef9SDimitry Andric // of this conceptual vector. 1429e8d8bef9SDimitry Andric // 1430e8d8bef9SDimitry Andric // This vector will be loaded/stored starting at the nearest down-aligned 1431e8d8bef9SDimitry Andric // address and the amount od the down-alignment will be AlignVal: 1432e8d8bef9SDimitry Andric // valign(load_vector(align_down(Base+Start)), AlignVal) 1433e8d8bef9SDimitry Andric 1434e8d8bef9SDimitry Andric std::set<Instruction *> TestSet(Move.Main.begin(), Move.Main.end()); 1435e8d8bef9SDimitry Andric AddrList MoveInfos; 1436e8d8bef9SDimitry Andric llvm::copy_if( 1437e8d8bef9SDimitry Andric BaseInfos, std::back_inserter(MoveInfos), 1438e8d8bef9SDimitry Andric [&TestSet](const AddrInfo &AI) { return TestSet.count(AI.Inst); }); 1439e8d8bef9SDimitry Andric 1440e8d8bef9SDimitry Andric // Maximum alignment present in the whole address group. 1441e8d8bef9SDimitry Andric const AddrInfo &WithMaxAlign = 144204eeddc0SDimitry Andric getMaxOf(MoveInfos, [](const AddrInfo &AI) { return AI.HaveAlign; }); 1443e8d8bef9SDimitry Andric Align MaxGiven = WithMaxAlign.HaveAlign; 1444e8d8bef9SDimitry Andric 1445e8d8bef9SDimitry Andric // Minimum alignment present in the move address group. 1446e8d8bef9SDimitry Andric const AddrInfo &WithMinOffset = 1447e8d8bef9SDimitry Andric getMaxOf(MoveInfos, [](const AddrInfo &AI) { return -AI.Offset; }); 1448e8d8bef9SDimitry Andric 1449e8d8bef9SDimitry Andric const AddrInfo &WithMaxNeeded = 1450e8d8bef9SDimitry Andric getMaxOf(MoveInfos, [](const AddrInfo &AI) { return AI.NeedAlign; }); 1451e8d8bef9SDimitry Andric Align MinNeeded = WithMaxNeeded.NeedAlign; 1452e8d8bef9SDimitry Andric 1453bdd1243dSDimitry Andric // Set the builder's insertion point right before the load group, or 1454bdd1243dSDimitry Andric // immediately after the store group. (Instructions in a store group are 1455bdd1243dSDimitry Andric // listed in reverse order.) 1456bdd1243dSDimitry Andric Instruction *InsertAt = Move.Main.front(); 1457bdd1243dSDimitry Andric if (!Move.IsLoad) { 1458bdd1243dSDimitry Andric // There should be a terminator (which store isn't, but check anyways). 1459bdd1243dSDimitry Andric assert(InsertAt->getIterator() != InsertAt->getParent()->end()); 1460bdd1243dSDimitry Andric InsertAt = &*std::next(InsertAt->getIterator()); 1461bdd1243dSDimitry Andric } 1462bdd1243dSDimitry Andric 1463bdd1243dSDimitry Andric IRBuilder Builder(InsertAt->getParent(), InsertAt->getIterator(), 1464bdd1243dSDimitry Andric InstSimplifyFolder(HVC.DL)); 1465e8d8bef9SDimitry Andric Value *AlignAddr = nullptr; // Actual aligned address. 1466e8d8bef9SDimitry Andric Value *AlignVal = nullptr; // Right-shift amount (for valign). 1467e8d8bef9SDimitry Andric 1468e8d8bef9SDimitry Andric if (MinNeeded <= MaxGiven) { 1469e8d8bef9SDimitry Andric int Start = WithMinOffset.Offset; 1470e8d8bef9SDimitry Andric int OffAtMax = WithMaxAlign.Offset; 1471e8d8bef9SDimitry Andric // Shift the offset of the maximally aligned instruction (OffAtMax) 1472e8d8bef9SDimitry Andric // back by just enough multiples of the required alignment to cover the 1473e8d8bef9SDimitry Andric // distance from Start to OffAtMax. 1474e8d8bef9SDimitry Andric // Calculate the address adjustment amount based on the address with the 1475e8d8bef9SDimitry Andric // maximum alignment. This is to allow a simple gep instruction instead 1476e8d8bef9SDimitry Andric // of potential bitcasts to i8*. 1477e8d8bef9SDimitry Andric int Adjust = -alignTo(OffAtMax - Start, MinNeeded.value()); 1478e8d8bef9SDimitry Andric AlignAddr = createAdjustedPointer(Builder, WithMaxAlign.Addr, 147906c3fb27SDimitry Andric WithMaxAlign.ValTy, Adjust, Move.Clones); 1480e8d8bef9SDimitry Andric int Diff = Start - (OffAtMax + Adjust); 1481e8d8bef9SDimitry Andric AlignVal = HVC.getConstInt(Diff); 1482e8d8bef9SDimitry Andric assert(Diff >= 0); 1483e8d8bef9SDimitry Andric assert(static_cast<decltype(MinNeeded.value())>(Diff) < MinNeeded.value()); 1484e8d8bef9SDimitry Andric } else { 1485e8d8bef9SDimitry Andric // WithMinOffset is the lowest address in the group, 1486e8d8bef9SDimitry Andric // WithMinOffset.Addr = Base+Start. 1487e8d8bef9SDimitry Andric // Align instructions for both HVX (V6_valign) and scalar (S2_valignrb) 1488e8d8bef9SDimitry Andric // mask off unnecessary bits, so it's ok to just the original pointer as 1489e8d8bef9SDimitry Andric // the alignment amount. 1490e8d8bef9SDimitry Andric // Do an explicit down-alignment of the address to avoid creating an 1491e8d8bef9SDimitry Andric // aligned instruction with an address that is not really aligned. 149206c3fb27SDimitry Andric AlignAddr = 149306c3fb27SDimitry Andric createAlignedPointer(Builder, WithMinOffset.Addr, WithMinOffset.ValTy, 149406c3fb27SDimitry Andric MinNeeded.value(), Move.Clones); 149506c3fb27SDimitry Andric AlignVal = 149606c3fb27SDimitry Andric Builder.CreatePtrToInt(WithMinOffset.Addr, HVC.getIntTy(), "pti"); 149706c3fb27SDimitry Andric if (auto *I = dyn_cast<Instruction>(AlignVal)) { 149806c3fb27SDimitry Andric for (auto [Old, New] : Move.Clones) 149906c3fb27SDimitry Andric I->replaceUsesOfWith(Old, New); 150006c3fb27SDimitry Andric } 1501e8d8bef9SDimitry Andric } 1502e8d8bef9SDimitry Andric 1503e8d8bef9SDimitry Andric ByteSpan VSpan; 1504e8d8bef9SDimitry Andric for (const AddrInfo &AI : MoveInfos) { 1505e8d8bef9SDimitry Andric VSpan.Blocks.emplace_back(AI.Inst, HVC.getSizeOf(AI.ValTy), 1506e8d8bef9SDimitry Andric AI.Offset - WithMinOffset.Offset); 1507e8d8bef9SDimitry Andric } 1508e8d8bef9SDimitry Andric 1509e8d8bef9SDimitry Andric // The aligned loads/stores will use blocks that are either scalars, 1510e8d8bef9SDimitry Andric // or HVX vectors. Let "sector" be the unified term for such a block. 1511e8d8bef9SDimitry Andric // blend(scalar, vector) -> sector... 1512e8d8bef9SDimitry Andric int ScLen = Move.IsHvx ? HVC.HST.getVectorLength() 1513e8d8bef9SDimitry Andric : std::max<int>(MinNeeded.value(), 4); 1514e8d8bef9SDimitry Andric assert(!Move.IsHvx || ScLen == 64 || ScLen == 128); 1515e8d8bef9SDimitry Andric assert(Move.IsHvx || ScLen == 4 || ScLen == 8); 1516e8d8bef9SDimitry Andric 151706c3fb27SDimitry Andric LLVM_DEBUG({ 151806c3fb27SDimitry Andric dbgs() << "ScLen: " << ScLen << "\n"; 151906c3fb27SDimitry Andric dbgs() << "AlignVal:" << *AlignVal << "\n"; 152006c3fb27SDimitry Andric dbgs() << "AlignAddr:" << *AlignAddr << "\n"; 152106c3fb27SDimitry Andric dbgs() << "VSpan:\n" << VSpan << '\n'; 152206c3fb27SDimitry Andric }); 152306c3fb27SDimitry Andric 1524bdd1243dSDimitry Andric if (Move.IsLoad) 1525bdd1243dSDimitry Andric realignLoadGroup(Builder, VSpan, ScLen, AlignVal, AlignAddr); 1526bdd1243dSDimitry Andric else 1527bdd1243dSDimitry Andric realignStoreGroup(Builder, VSpan, ScLen, AlignVal, AlignAddr); 1528e8d8bef9SDimitry Andric 1529e8d8bef9SDimitry Andric for (auto *Inst : Move.Main) 1530e8d8bef9SDimitry Andric Inst->eraseFromParent(); 1531e8d8bef9SDimitry Andric 1532e8d8bef9SDimitry Andric return true; 1533e8d8bef9SDimitry Andric } 1534e8d8bef9SDimitry Andric 153506c3fb27SDimitry Andric auto AlignVectors::makeTestIfUnaligned(IRBuilderBase &Builder, Value *AlignVal, 153606c3fb27SDimitry Andric int Alignment) const -> Value * { 153706c3fb27SDimitry Andric auto *AlignTy = AlignVal->getType(); 153806c3fb27SDimitry Andric Value *And = Builder.CreateAnd( 153906c3fb27SDimitry Andric AlignVal, ConstantInt::get(AlignTy, Alignment - 1), "and"); 154006c3fb27SDimitry Andric Value *Zero = ConstantInt::get(AlignTy, 0); 154106c3fb27SDimitry Andric return Builder.CreateICmpNE(And, Zero, "isz"); 154206c3fb27SDimitry Andric } 154306c3fb27SDimitry Andric 1544bdd1243dSDimitry Andric auto AlignVectors::isSectorTy(Type *Ty) const -> bool { 1545bdd1243dSDimitry Andric if (!HVC.isByteVecTy(Ty)) 1546bdd1243dSDimitry Andric return false; 1547bdd1243dSDimitry Andric int Size = HVC.getSizeOf(Ty); 1548bdd1243dSDimitry Andric if (HVC.HST.isTypeForHVX(Ty)) 1549bdd1243dSDimitry Andric return Size == static_cast<int>(HVC.HST.getVectorLength()); 1550bdd1243dSDimitry Andric return Size == 4 || Size == 8; 1551bdd1243dSDimitry Andric } 1552bdd1243dSDimitry Andric 1553e8d8bef9SDimitry Andric auto AlignVectors::run() -> bool { 155406c3fb27SDimitry Andric LLVM_DEBUG(dbgs() << "Running HVC::AlignVectors on " << HVC.F.getName() 155506c3fb27SDimitry Andric << '\n'); 1556e8d8bef9SDimitry Andric if (!createAddressGroups()) 1557e8d8bef9SDimitry Andric return false; 1558e8d8bef9SDimitry Andric 155906c3fb27SDimitry Andric LLVM_DEBUG({ 156006c3fb27SDimitry Andric dbgs() << "Address groups(" << AddrGroups.size() << "):\n"; 156106c3fb27SDimitry Andric for (auto &[In, AL] : AddrGroups) { 156206c3fb27SDimitry Andric for (const AddrInfo &AI : AL) 156306c3fb27SDimitry Andric dbgs() << "---\n" << AI << '\n'; 156406c3fb27SDimitry Andric } 156506c3fb27SDimitry Andric }); 156606c3fb27SDimitry Andric 1567e8d8bef9SDimitry Andric bool Changed = false; 1568e8d8bef9SDimitry Andric MoveList LoadGroups, StoreGroups; 1569e8d8bef9SDimitry Andric 1570e8d8bef9SDimitry Andric for (auto &G : AddrGroups) { 1571e8d8bef9SDimitry Andric llvm::append_range(LoadGroups, createLoadGroups(G.second)); 1572e8d8bef9SDimitry Andric llvm::append_range(StoreGroups, createStoreGroups(G.second)); 1573e8d8bef9SDimitry Andric } 1574e8d8bef9SDimitry Andric 157506c3fb27SDimitry Andric LLVM_DEBUG({ 157606c3fb27SDimitry Andric dbgs() << "\nLoad groups(" << LoadGroups.size() << "):\n"; 157706c3fb27SDimitry Andric for (const MoveGroup &G : LoadGroups) 157806c3fb27SDimitry Andric dbgs() << G << "\n"; 157906c3fb27SDimitry Andric dbgs() << "Store groups(" << StoreGroups.size() << "):\n"; 158006c3fb27SDimitry Andric for (const MoveGroup &G : StoreGroups) 158106c3fb27SDimitry Andric dbgs() << G << "\n"; 158206c3fb27SDimitry Andric }); 158306c3fb27SDimitry Andric 158406c3fb27SDimitry Andric // Cumulative limit on the number of groups. 158506c3fb27SDimitry Andric unsigned CountLimit = VAGroupCountLimit; 158606c3fb27SDimitry Andric if (CountLimit == 0) 158706c3fb27SDimitry Andric return false; 158806c3fb27SDimitry Andric 158906c3fb27SDimitry Andric if (LoadGroups.size() > CountLimit) { 159006c3fb27SDimitry Andric LoadGroups.resize(CountLimit); 159106c3fb27SDimitry Andric StoreGroups.clear(); 159206c3fb27SDimitry Andric } else { 159306c3fb27SDimitry Andric unsigned StoreLimit = CountLimit - LoadGroups.size(); 159406c3fb27SDimitry Andric if (StoreGroups.size() > StoreLimit) 159506c3fb27SDimitry Andric StoreGroups.resize(StoreLimit); 159606c3fb27SDimitry Andric } 159706c3fb27SDimitry Andric 1598e8d8bef9SDimitry Andric for (auto &M : LoadGroups) 159906c3fb27SDimitry Andric Changed |= moveTogether(M); 1600e8d8bef9SDimitry Andric for (auto &M : StoreGroups) 160106c3fb27SDimitry Andric Changed |= moveTogether(M); 160206c3fb27SDimitry Andric 160306c3fb27SDimitry Andric LLVM_DEBUG(dbgs() << "After moveTogether:\n" << HVC.F); 1604e8d8bef9SDimitry Andric 1605e8d8bef9SDimitry Andric for (auto &M : LoadGroups) 1606e8d8bef9SDimitry Andric Changed |= realignGroup(M); 1607e8d8bef9SDimitry Andric for (auto &M : StoreGroups) 1608e8d8bef9SDimitry Andric Changed |= realignGroup(M); 1609e8d8bef9SDimitry Andric 1610e8d8bef9SDimitry Andric return Changed; 1611e8d8bef9SDimitry Andric } 1612e8d8bef9SDimitry Andric 1613e8d8bef9SDimitry Andric // --- End AlignVectors 1614e8d8bef9SDimitry Andric 1615bdd1243dSDimitry Andric // --- Begin HvxIdioms 1616bdd1243dSDimitry Andric 1617bdd1243dSDimitry Andric auto HvxIdioms::getNumSignificantBits(Value *V, Instruction *In) const 1618bdd1243dSDimitry Andric -> std::pair<unsigned, Signedness> { 1619bdd1243dSDimitry Andric unsigned Bits = HVC.getNumSignificantBits(V, In); 1620bdd1243dSDimitry Andric // The significant bits are calculated including the sign bit. This may 1621bdd1243dSDimitry Andric // add an extra bit for zero-extended values, e.g. (zext i32 to i64) may 1622bdd1243dSDimitry Andric // result in 33 significant bits. To avoid extra words, skip the extra 1623bdd1243dSDimitry Andric // sign bit, but keep information that the value is to be treated as 1624bdd1243dSDimitry Andric // unsigned. 1625bdd1243dSDimitry Andric KnownBits Known = HVC.getKnownBits(V, In); 1626bdd1243dSDimitry Andric Signedness Sign = Signed; 1627bdd1243dSDimitry Andric unsigned NumToTest = 0; // Number of bits used in test for unsignedness. 1628bdd1243dSDimitry Andric if (isPowerOf2_32(Bits)) 1629bdd1243dSDimitry Andric NumToTest = Bits; 1630bdd1243dSDimitry Andric else if (Bits > 1 && isPowerOf2_32(Bits - 1)) 1631bdd1243dSDimitry Andric NumToTest = Bits - 1; 1632bdd1243dSDimitry Andric 1633bdd1243dSDimitry Andric if (NumToTest != 0 && Known.Zero.ashr(NumToTest).isAllOnes()) { 1634bdd1243dSDimitry Andric Sign = Unsigned; 1635bdd1243dSDimitry Andric Bits = NumToTest; 1636bdd1243dSDimitry Andric } 1637bdd1243dSDimitry Andric 1638bdd1243dSDimitry Andric // If the top bit of the nearest power-of-2 is zero, this value is 1639bdd1243dSDimitry Andric // positive. It could be treated as either signed or unsigned. 1640bdd1243dSDimitry Andric if (unsigned Pow2 = PowerOf2Ceil(Bits); Pow2 != Bits) { 1641bdd1243dSDimitry Andric if (Known.Zero.ashr(Pow2 - 1).isAllOnes()) 1642bdd1243dSDimitry Andric Sign = Positive; 1643bdd1243dSDimitry Andric } 1644bdd1243dSDimitry Andric return {Bits, Sign}; 1645bdd1243dSDimitry Andric } 1646bdd1243dSDimitry Andric 1647bdd1243dSDimitry Andric auto HvxIdioms::canonSgn(SValue X, SValue Y) const 1648bdd1243dSDimitry Andric -> std::pair<SValue, SValue> { 1649bdd1243dSDimitry Andric // Canonicalize the signedness of X and Y, so that the result is one of: 1650bdd1243dSDimitry Andric // S, S 1651bdd1243dSDimitry Andric // U/P, S 1652bdd1243dSDimitry Andric // U/P, U/P 1653bdd1243dSDimitry Andric if (X.Sgn == Signed && Y.Sgn != Signed) 1654bdd1243dSDimitry Andric std::swap(X, Y); 1655bdd1243dSDimitry Andric return {X, Y}; 1656bdd1243dSDimitry Andric } 1657bdd1243dSDimitry Andric 1658bdd1243dSDimitry Andric // Match 1659bdd1243dSDimitry Andric // (X * Y) [>> N], or 1660bdd1243dSDimitry Andric // ((X * Y) + (1 << M)) >> N 1661bdd1243dSDimitry Andric auto HvxIdioms::matchFxpMul(Instruction &In) const -> std::optional<FxpOp> { 1662bdd1243dSDimitry Andric using namespace PatternMatch; 1663bdd1243dSDimitry Andric auto *Ty = In.getType(); 1664bdd1243dSDimitry Andric 1665bdd1243dSDimitry Andric if (!Ty->isVectorTy() || !Ty->getScalarType()->isIntegerTy()) 1666bdd1243dSDimitry Andric return std::nullopt; 1667bdd1243dSDimitry Andric 1668bdd1243dSDimitry Andric unsigned Width = cast<IntegerType>(Ty->getScalarType())->getBitWidth(); 1669bdd1243dSDimitry Andric 1670bdd1243dSDimitry Andric FxpOp Op; 1671bdd1243dSDimitry Andric Value *Exp = &In; 1672bdd1243dSDimitry Andric 1673bdd1243dSDimitry Andric // Fixed-point multiplication is always shifted right (except when the 1674bdd1243dSDimitry Andric // fraction is 0 bits). 1675bdd1243dSDimitry Andric auto m_Shr = [](auto &&V, auto &&S) { 1676bdd1243dSDimitry Andric return m_CombineOr(m_LShr(V, S), m_AShr(V, S)); 1677bdd1243dSDimitry Andric }; 1678bdd1243dSDimitry Andric 1679bdd1243dSDimitry Andric const APInt *Qn = nullptr; 1680bdd1243dSDimitry Andric if (Value * T; match(Exp, m_Shr(m_Value(T), m_APInt(Qn)))) { 1681bdd1243dSDimitry Andric Op.Frac = Qn->getZExtValue(); 1682bdd1243dSDimitry Andric Exp = T; 1683bdd1243dSDimitry Andric } else { 1684bdd1243dSDimitry Andric Op.Frac = 0; 1685bdd1243dSDimitry Andric } 1686bdd1243dSDimitry Andric 1687bdd1243dSDimitry Andric if (Op.Frac > Width) 1688bdd1243dSDimitry Andric return std::nullopt; 1689bdd1243dSDimitry Andric 1690bdd1243dSDimitry Andric // Check if there is rounding added. 1691bdd1243dSDimitry Andric const APInt *C = nullptr; 1692bdd1243dSDimitry Andric if (Value * T; Op.Frac > 0 && match(Exp, m_Add(m_Value(T), m_APInt(C)))) { 1693bdd1243dSDimitry Andric uint64_t CV = C->getZExtValue(); 1694bdd1243dSDimitry Andric if (CV != 0 && !isPowerOf2_64(CV)) 1695bdd1243dSDimitry Andric return std::nullopt; 1696bdd1243dSDimitry Andric if (CV != 0) 1697bdd1243dSDimitry Andric Op.RoundAt = Log2_64(CV); 1698bdd1243dSDimitry Andric Exp = T; 1699bdd1243dSDimitry Andric } 1700bdd1243dSDimitry Andric 1701bdd1243dSDimitry Andric // Check if the rest is a multiplication. 1702bdd1243dSDimitry Andric if (match(Exp, m_Mul(m_Value(Op.X.Val), m_Value(Op.Y.Val)))) { 1703bdd1243dSDimitry Andric Op.Opcode = Instruction::Mul; 1704bdd1243dSDimitry Andric // FIXME: The information below is recomputed. 1705bdd1243dSDimitry Andric Op.X.Sgn = getNumSignificantBits(Op.X.Val, &In).second; 1706bdd1243dSDimitry Andric Op.Y.Sgn = getNumSignificantBits(Op.Y.Val, &In).second; 1707bdd1243dSDimitry Andric Op.ResTy = cast<VectorType>(Ty); 1708bdd1243dSDimitry Andric return Op; 1709bdd1243dSDimitry Andric } 1710bdd1243dSDimitry Andric 1711bdd1243dSDimitry Andric return std::nullopt; 1712bdd1243dSDimitry Andric } 1713bdd1243dSDimitry Andric 1714bdd1243dSDimitry Andric auto HvxIdioms::processFxpMul(Instruction &In, const FxpOp &Op) const 1715bdd1243dSDimitry Andric -> Value * { 1716bdd1243dSDimitry Andric assert(Op.X.Val->getType() == Op.Y.Val->getType()); 1717bdd1243dSDimitry Andric 1718bdd1243dSDimitry Andric auto *VecTy = dyn_cast<VectorType>(Op.X.Val->getType()); 1719bdd1243dSDimitry Andric if (VecTy == nullptr) 1720bdd1243dSDimitry Andric return nullptr; 1721bdd1243dSDimitry Andric auto *ElemTy = cast<IntegerType>(VecTy->getElementType()); 1722bdd1243dSDimitry Andric unsigned ElemWidth = ElemTy->getBitWidth(); 1723bdd1243dSDimitry Andric 1724bdd1243dSDimitry Andric // TODO: This can be relaxed after legalization is done pre-isel. 1725bdd1243dSDimitry Andric if ((HVC.length(VecTy) * ElemWidth) % (8 * HVC.HST.getVectorLength()) != 0) 1726bdd1243dSDimitry Andric return nullptr; 1727bdd1243dSDimitry Andric 1728bdd1243dSDimitry Andric // There are no special intrinsics that should be used for multiplying 1729bdd1243dSDimitry Andric // signed 8-bit values, so just skip them. Normal codegen should handle 1730bdd1243dSDimitry Andric // this just fine. 1731bdd1243dSDimitry Andric if (ElemWidth <= 8) 1732bdd1243dSDimitry Andric return nullptr; 1733bdd1243dSDimitry Andric // Similarly, if this is just a multiplication that can be handled without 1734bdd1243dSDimitry Andric // intervention, then leave it alone. 1735bdd1243dSDimitry Andric if (ElemWidth <= 32 && Op.Frac == 0) 1736bdd1243dSDimitry Andric return nullptr; 1737bdd1243dSDimitry Andric 1738bdd1243dSDimitry Andric auto [BitsX, SignX] = getNumSignificantBits(Op.X.Val, &In); 1739bdd1243dSDimitry Andric auto [BitsY, SignY] = getNumSignificantBits(Op.Y.Val, &In); 1740bdd1243dSDimitry Andric 1741bdd1243dSDimitry Andric // TODO: Add multiplication of vectors by scalar registers (up to 4 bytes). 1742bdd1243dSDimitry Andric 1743bdd1243dSDimitry Andric Value *X = Op.X.Val, *Y = Op.Y.Val; 1744bdd1243dSDimitry Andric IRBuilder Builder(In.getParent(), In.getIterator(), 1745bdd1243dSDimitry Andric InstSimplifyFolder(HVC.DL)); 1746bdd1243dSDimitry Andric 1747bdd1243dSDimitry Andric auto roundUpWidth = [](unsigned Width) -> unsigned { 1748bdd1243dSDimitry Andric if (Width <= 32 && !isPowerOf2_32(Width)) { 1749bdd1243dSDimitry Andric // If the element width is not a power of 2, round it up 1750bdd1243dSDimitry Andric // to the next one. Do this for widths not exceeding 32. 1751bdd1243dSDimitry Andric return PowerOf2Ceil(Width); 1752bdd1243dSDimitry Andric } 1753bdd1243dSDimitry Andric if (Width > 32 && Width % 32 != 0) { 1754bdd1243dSDimitry Andric // For wider elements, round it up to the multiple of 32. 1755bdd1243dSDimitry Andric return alignTo(Width, 32u); 1756bdd1243dSDimitry Andric } 1757bdd1243dSDimitry Andric return Width; 1758bdd1243dSDimitry Andric }; 1759bdd1243dSDimitry Andric 1760bdd1243dSDimitry Andric BitsX = roundUpWidth(BitsX); 1761bdd1243dSDimitry Andric BitsY = roundUpWidth(BitsY); 1762bdd1243dSDimitry Andric 1763bdd1243dSDimitry Andric // For elementwise multiplication vectors must have the same lengths, so 1764bdd1243dSDimitry Andric // resize the elements of both inputs to the same width, the max of the 1765bdd1243dSDimitry Andric // calculated significant bits. 1766bdd1243dSDimitry Andric unsigned Width = std::max(BitsX, BitsY); 1767bdd1243dSDimitry Andric 1768bdd1243dSDimitry Andric auto *ResizeTy = VectorType::get(HVC.getIntTy(Width), VecTy); 1769bdd1243dSDimitry Andric if (Width < ElemWidth) { 177006c3fb27SDimitry Andric X = Builder.CreateTrunc(X, ResizeTy, "trn"); 177106c3fb27SDimitry Andric Y = Builder.CreateTrunc(Y, ResizeTy, "trn"); 1772bdd1243dSDimitry Andric } else if (Width > ElemWidth) { 177306c3fb27SDimitry Andric X = SignX == Signed ? Builder.CreateSExt(X, ResizeTy, "sxt") 177406c3fb27SDimitry Andric : Builder.CreateZExt(X, ResizeTy, "zxt"); 177506c3fb27SDimitry Andric Y = SignY == Signed ? Builder.CreateSExt(Y, ResizeTy, "sxt") 177606c3fb27SDimitry Andric : Builder.CreateZExt(Y, ResizeTy, "zxt"); 1777bdd1243dSDimitry Andric }; 1778bdd1243dSDimitry Andric 1779bdd1243dSDimitry Andric assert(X->getType() == Y->getType() && X->getType() == ResizeTy); 1780bdd1243dSDimitry Andric 1781bdd1243dSDimitry Andric unsigned VecLen = HVC.length(ResizeTy); 1782bdd1243dSDimitry Andric unsigned ChopLen = (8 * HVC.HST.getVectorLength()) / std::min(Width, 32u); 1783bdd1243dSDimitry Andric 1784bdd1243dSDimitry Andric SmallVector<Value *> Results; 1785bdd1243dSDimitry Andric FxpOp ChopOp = Op; 1786bdd1243dSDimitry Andric ChopOp.ResTy = VectorType::get(Op.ResTy->getElementType(), ChopLen, false); 1787bdd1243dSDimitry Andric 1788bdd1243dSDimitry Andric for (unsigned V = 0; V != VecLen / ChopLen; ++V) { 1789bdd1243dSDimitry Andric ChopOp.X.Val = HVC.subvector(Builder, X, V * ChopLen, ChopLen); 1790bdd1243dSDimitry Andric ChopOp.Y.Val = HVC.subvector(Builder, Y, V * ChopLen, ChopLen); 1791bdd1243dSDimitry Andric Results.push_back(processFxpMulChopped(Builder, In, ChopOp)); 1792bdd1243dSDimitry Andric if (Results.back() == nullptr) 1793bdd1243dSDimitry Andric break; 1794bdd1243dSDimitry Andric } 1795bdd1243dSDimitry Andric 1796bdd1243dSDimitry Andric if (Results.empty() || Results.back() == nullptr) 1797bdd1243dSDimitry Andric return nullptr; 1798bdd1243dSDimitry Andric 1799bdd1243dSDimitry Andric Value *Cat = HVC.concat(Builder, Results); 1800bdd1243dSDimitry Andric Value *Ext = SignX == Signed || SignY == Signed 180106c3fb27SDimitry Andric ? Builder.CreateSExt(Cat, VecTy, "sxt") 180206c3fb27SDimitry Andric : Builder.CreateZExt(Cat, VecTy, "zxt"); 1803bdd1243dSDimitry Andric return Ext; 1804bdd1243dSDimitry Andric } 1805bdd1243dSDimitry Andric 1806bdd1243dSDimitry Andric auto HvxIdioms::processFxpMulChopped(IRBuilderBase &Builder, Instruction &In, 1807bdd1243dSDimitry Andric const FxpOp &Op) const -> Value * { 1808bdd1243dSDimitry Andric assert(Op.X.Val->getType() == Op.Y.Val->getType()); 1809bdd1243dSDimitry Andric auto *InpTy = cast<VectorType>(Op.X.Val->getType()); 1810bdd1243dSDimitry Andric unsigned Width = InpTy->getScalarSizeInBits(); 1811bdd1243dSDimitry Andric bool Rounding = Op.RoundAt.has_value(); 1812bdd1243dSDimitry Andric 1813bdd1243dSDimitry Andric if (!Op.RoundAt || *Op.RoundAt == Op.Frac - 1) { 1814bdd1243dSDimitry Andric // The fixed-point intrinsics do signed multiplication. 1815bdd1243dSDimitry Andric if (Width == Op.Frac + 1 && Op.X.Sgn != Unsigned && Op.Y.Sgn != Unsigned) { 1816bdd1243dSDimitry Andric Value *QMul = nullptr; 1817bdd1243dSDimitry Andric if (Width == 16) { 1818bdd1243dSDimitry Andric QMul = createMulQ15(Builder, Op.X, Op.Y, Rounding); 1819bdd1243dSDimitry Andric } else if (Width == 32) { 1820bdd1243dSDimitry Andric QMul = createMulQ31(Builder, Op.X, Op.Y, Rounding); 1821bdd1243dSDimitry Andric } 1822bdd1243dSDimitry Andric if (QMul != nullptr) 1823bdd1243dSDimitry Andric return QMul; 1824bdd1243dSDimitry Andric } 1825bdd1243dSDimitry Andric } 1826bdd1243dSDimitry Andric 1827bdd1243dSDimitry Andric assert(Width >= 32 || isPowerOf2_32(Width)); // Width <= 32 => Width is 2^n 1828bdd1243dSDimitry Andric assert(Width < 32 || Width % 32 == 0); // Width > 32 => Width is 32*k 1829bdd1243dSDimitry Andric 1830bdd1243dSDimitry Andric // If Width < 32, then it should really be 16. 1831bdd1243dSDimitry Andric if (Width < 32) { 1832bdd1243dSDimitry Andric if (Width < 16) 1833bdd1243dSDimitry Andric return nullptr; 1834bdd1243dSDimitry Andric // Getting here with Op.Frac == 0 isn't wrong, but suboptimal: here we 1835bdd1243dSDimitry Andric // generate a full precision products, which is unnecessary if there is 1836bdd1243dSDimitry Andric // no shift. 1837bdd1243dSDimitry Andric assert(Width == 16); 1838bdd1243dSDimitry Andric assert(Op.Frac != 0 && "Unshifted mul should have been skipped"); 1839bdd1243dSDimitry Andric if (Op.Frac == 16) { 1840bdd1243dSDimitry Andric // Multiply high 1841bdd1243dSDimitry Andric if (Value *MulH = createMulH16(Builder, Op.X, Op.Y)) 1842bdd1243dSDimitry Andric return MulH; 1843bdd1243dSDimitry Andric } 1844bdd1243dSDimitry Andric // Do full-precision multiply and shift. 1845bdd1243dSDimitry Andric Value *Prod32 = createMul16(Builder, Op.X, Op.Y); 1846bdd1243dSDimitry Andric if (Rounding) { 1847bdd1243dSDimitry Andric Value *RoundVal = HVC.getConstSplat(Prod32->getType(), 1 << *Op.RoundAt); 184806c3fb27SDimitry Andric Prod32 = Builder.CreateAdd(Prod32, RoundVal, "add"); 1849bdd1243dSDimitry Andric } 1850bdd1243dSDimitry Andric 1851bdd1243dSDimitry Andric Value *ShiftAmt = HVC.getConstSplat(Prod32->getType(), Op.Frac); 1852bdd1243dSDimitry Andric Value *Shifted = Op.X.Sgn == Signed || Op.Y.Sgn == Signed 185306c3fb27SDimitry Andric ? Builder.CreateAShr(Prod32, ShiftAmt, "asr") 185406c3fb27SDimitry Andric : Builder.CreateLShr(Prod32, ShiftAmt, "lsr"); 185506c3fb27SDimitry Andric return Builder.CreateTrunc(Shifted, InpTy, "trn"); 1856bdd1243dSDimitry Andric } 1857bdd1243dSDimitry Andric 1858bdd1243dSDimitry Andric // Width >= 32 1859bdd1243dSDimitry Andric 1860bdd1243dSDimitry Andric // Break up the arguments Op.X and Op.Y into vectors of smaller widths 1861bdd1243dSDimitry Andric // in preparation of doing the multiplication by 32-bit parts. 1862bdd1243dSDimitry Andric auto WordX = HVC.splitVectorElements(Builder, Op.X.Val, /*ToWidth=*/32); 1863bdd1243dSDimitry Andric auto WordY = HVC.splitVectorElements(Builder, Op.Y.Val, /*ToWidth=*/32); 1864bdd1243dSDimitry Andric auto WordP = createMulLong(Builder, WordX, Op.X.Sgn, WordY, Op.Y.Sgn); 1865bdd1243dSDimitry Andric 1866bdd1243dSDimitry Andric auto *HvxWordTy = cast<VectorType>(WordP.front()->getType()); 1867bdd1243dSDimitry Andric 1868bdd1243dSDimitry Andric // Add the optional rounding to the proper word. 1869bdd1243dSDimitry Andric if (Op.RoundAt.has_value()) { 1870bdd1243dSDimitry Andric Value *Zero = HVC.getNullValue(WordX[0]->getType()); 1871bdd1243dSDimitry Andric SmallVector<Value *> RoundV(WordP.size(), Zero); 1872bdd1243dSDimitry Andric RoundV[*Op.RoundAt / 32] = 1873bdd1243dSDimitry Andric HVC.getConstSplat(HvxWordTy, 1 << (*Op.RoundAt % 32)); 1874bdd1243dSDimitry Andric WordP = createAddLong(Builder, WordP, RoundV); 1875bdd1243dSDimitry Andric } 1876bdd1243dSDimitry Andric 1877bdd1243dSDimitry Andric // createRightShiftLong? 1878bdd1243dSDimitry Andric 1879bdd1243dSDimitry Andric // Shift all products right by Op.Frac. 1880bdd1243dSDimitry Andric unsigned SkipWords = Op.Frac / 32; 1881bdd1243dSDimitry Andric Constant *ShiftAmt = HVC.getConstSplat(HvxWordTy, Op.Frac % 32); 1882bdd1243dSDimitry Andric 1883bdd1243dSDimitry Andric for (int Dst = 0, End = WordP.size() - SkipWords; Dst != End; ++Dst) { 1884bdd1243dSDimitry Andric int Src = Dst + SkipWords; 1885bdd1243dSDimitry Andric Value *Lo = WordP[Src]; 1886bdd1243dSDimitry Andric if (Src + 1 < End) { 1887bdd1243dSDimitry Andric Value *Hi = WordP[Src + 1]; 1888bdd1243dSDimitry Andric WordP[Dst] = Builder.CreateIntrinsic(HvxWordTy, Intrinsic::fshr, 188906c3fb27SDimitry Andric {Hi, Lo, ShiftAmt}, 189006c3fb27SDimitry Andric /*FMFSource*/ nullptr, "int"); 1891bdd1243dSDimitry Andric } else { 1892bdd1243dSDimitry Andric // The shift of the most significant word. 189306c3fb27SDimitry Andric WordP[Dst] = Builder.CreateAShr(Lo, ShiftAmt, "asr"); 1894bdd1243dSDimitry Andric } 1895bdd1243dSDimitry Andric } 1896bdd1243dSDimitry Andric if (SkipWords != 0) 1897bdd1243dSDimitry Andric WordP.resize(WordP.size() - SkipWords); 1898bdd1243dSDimitry Andric 1899bdd1243dSDimitry Andric return HVC.joinVectorElements(Builder, WordP, Op.ResTy); 1900bdd1243dSDimitry Andric } 1901bdd1243dSDimitry Andric 1902bdd1243dSDimitry Andric auto HvxIdioms::createMulQ15(IRBuilderBase &Builder, SValue X, SValue Y, 1903bdd1243dSDimitry Andric bool Rounding) const -> Value * { 1904bdd1243dSDimitry Andric assert(X.Val->getType() == Y.Val->getType()); 1905bdd1243dSDimitry Andric assert(X.Val->getType()->getScalarType() == HVC.getIntTy(16)); 1906bdd1243dSDimitry Andric assert(HVC.HST.isHVXVectorType(EVT::getEVT(X.Val->getType(), false))); 1907bdd1243dSDimitry Andric 1908bdd1243dSDimitry Andric // There is no non-rounding intrinsic for i16. 1909bdd1243dSDimitry Andric if (!Rounding || X.Sgn == Unsigned || Y.Sgn == Unsigned) 1910bdd1243dSDimitry Andric return nullptr; 1911bdd1243dSDimitry Andric 1912bdd1243dSDimitry Andric auto V6_vmpyhvsrs = HVC.HST.getIntrinsicId(Hexagon::V6_vmpyhvsrs); 1913bdd1243dSDimitry Andric return HVC.createHvxIntrinsic(Builder, V6_vmpyhvsrs, X.Val->getType(), 1914bdd1243dSDimitry Andric {X.Val, Y.Val}); 1915bdd1243dSDimitry Andric } 1916bdd1243dSDimitry Andric 1917bdd1243dSDimitry Andric auto HvxIdioms::createMulQ31(IRBuilderBase &Builder, SValue X, SValue Y, 1918bdd1243dSDimitry Andric bool Rounding) const -> Value * { 1919bdd1243dSDimitry Andric Type *InpTy = X.Val->getType(); 1920bdd1243dSDimitry Andric assert(InpTy == Y.Val->getType()); 1921bdd1243dSDimitry Andric assert(InpTy->getScalarType() == HVC.getIntTy(32)); 1922bdd1243dSDimitry Andric assert(HVC.HST.isHVXVectorType(EVT::getEVT(InpTy, false))); 1923bdd1243dSDimitry Andric 1924bdd1243dSDimitry Andric if (X.Sgn == Unsigned || Y.Sgn == Unsigned) 1925bdd1243dSDimitry Andric return nullptr; 1926bdd1243dSDimitry Andric 1927bdd1243dSDimitry Andric auto V6_vmpyewuh = HVC.HST.getIntrinsicId(Hexagon::V6_vmpyewuh); 1928bdd1243dSDimitry Andric auto V6_vmpyo_acc = Rounding 1929bdd1243dSDimitry Andric ? HVC.HST.getIntrinsicId(Hexagon::V6_vmpyowh_rnd_sacc) 1930bdd1243dSDimitry Andric : HVC.HST.getIntrinsicId(Hexagon::V6_vmpyowh_sacc); 1931bdd1243dSDimitry Andric Value *V1 = 1932bdd1243dSDimitry Andric HVC.createHvxIntrinsic(Builder, V6_vmpyewuh, InpTy, {X.Val, Y.Val}); 1933bdd1243dSDimitry Andric return HVC.createHvxIntrinsic(Builder, V6_vmpyo_acc, InpTy, 1934bdd1243dSDimitry Andric {V1, X.Val, Y.Val}); 1935bdd1243dSDimitry Andric } 1936bdd1243dSDimitry Andric 1937bdd1243dSDimitry Andric auto HvxIdioms::createAddCarry(IRBuilderBase &Builder, Value *X, Value *Y, 1938bdd1243dSDimitry Andric Value *CarryIn) const 1939bdd1243dSDimitry Andric -> std::pair<Value *, Value *> { 1940bdd1243dSDimitry Andric assert(X->getType() == Y->getType()); 1941bdd1243dSDimitry Andric auto VecTy = cast<VectorType>(X->getType()); 1942bdd1243dSDimitry Andric if (VecTy == HvxI32Ty && HVC.HST.useHVXV62Ops()) { 1943bdd1243dSDimitry Andric SmallVector<Value *> Args = {X, Y}; 1944bdd1243dSDimitry Andric Intrinsic::ID AddCarry; 1945bdd1243dSDimitry Andric if (CarryIn == nullptr && HVC.HST.useHVXV66Ops()) { 1946bdd1243dSDimitry Andric AddCarry = HVC.HST.getIntrinsicId(Hexagon::V6_vaddcarryo); 1947bdd1243dSDimitry Andric } else { 1948bdd1243dSDimitry Andric AddCarry = HVC.HST.getIntrinsicId(Hexagon::V6_vaddcarry); 1949bdd1243dSDimitry Andric if (CarryIn == nullptr) 1950bdd1243dSDimitry Andric CarryIn = HVC.getNullValue(HVC.getBoolTy(HVC.length(VecTy))); 1951bdd1243dSDimitry Andric Args.push_back(CarryIn); 1952bdd1243dSDimitry Andric } 1953bdd1243dSDimitry Andric Value *Ret = HVC.createHvxIntrinsic(Builder, AddCarry, 1954bdd1243dSDimitry Andric /*RetTy=*/nullptr, Args); 195506c3fb27SDimitry Andric Value *Result = Builder.CreateExtractValue(Ret, {0}, "ext"); 195606c3fb27SDimitry Andric Value *CarryOut = Builder.CreateExtractValue(Ret, {1}, "ext"); 1957bdd1243dSDimitry Andric return {Result, CarryOut}; 1958bdd1243dSDimitry Andric } 1959bdd1243dSDimitry Andric 1960bdd1243dSDimitry Andric // In other cases, do a regular add, and unsigned compare-less-than. 1961bdd1243dSDimitry Andric // The carry-out can originate in two places: adding the carry-in or adding 1962bdd1243dSDimitry Andric // the two input values. 1963bdd1243dSDimitry Andric Value *Result1 = X; // Result1 = X + CarryIn 1964bdd1243dSDimitry Andric if (CarryIn != nullptr) { 1965bdd1243dSDimitry Andric unsigned Width = VecTy->getScalarSizeInBits(); 1966bdd1243dSDimitry Andric uint32_t Mask = 1; 1967bdd1243dSDimitry Andric if (Width < 32) { 1968bdd1243dSDimitry Andric for (unsigned i = 0, e = 32 / Width; i != e; ++i) 1969bdd1243dSDimitry Andric Mask = (Mask << Width) | 1; 1970bdd1243dSDimitry Andric } 1971bdd1243dSDimitry Andric auto V6_vandqrt = HVC.HST.getIntrinsicId(Hexagon::V6_vandqrt); 1972bdd1243dSDimitry Andric Value *ValueIn = 1973bdd1243dSDimitry Andric HVC.createHvxIntrinsic(Builder, V6_vandqrt, /*RetTy=*/nullptr, 1974bdd1243dSDimitry Andric {CarryIn, HVC.getConstInt(Mask)}); 197506c3fb27SDimitry Andric Result1 = Builder.CreateAdd(X, ValueIn, "add"); 1976bdd1243dSDimitry Andric } 1977bdd1243dSDimitry Andric 197806c3fb27SDimitry Andric Value *CarryOut1 = Builder.CreateCmp(CmpInst::ICMP_ULT, Result1, X, "cmp"); 197906c3fb27SDimitry Andric Value *Result2 = Builder.CreateAdd(Result1, Y, "add"); 198006c3fb27SDimitry Andric Value *CarryOut2 = Builder.CreateCmp(CmpInst::ICMP_ULT, Result2, Y, "cmp"); 198106c3fb27SDimitry Andric return {Result2, Builder.CreateOr(CarryOut1, CarryOut2, "orb")}; 1982bdd1243dSDimitry Andric } 1983bdd1243dSDimitry Andric 1984bdd1243dSDimitry Andric auto HvxIdioms::createMul16(IRBuilderBase &Builder, SValue X, SValue Y) const 1985bdd1243dSDimitry Andric -> Value * { 1986bdd1243dSDimitry Andric Intrinsic::ID V6_vmpyh = 0; 1987bdd1243dSDimitry Andric std::tie(X, Y) = canonSgn(X, Y); 1988bdd1243dSDimitry Andric 1989bdd1243dSDimitry Andric if (X.Sgn == Signed) { 1990bdd1243dSDimitry Andric V6_vmpyh = HVC.HST.getIntrinsicId(Hexagon::V6_vmpyhv); 1991bdd1243dSDimitry Andric } else if (Y.Sgn == Signed) { 1992bdd1243dSDimitry Andric // In vmpyhus the second operand is unsigned 1993bdd1243dSDimitry Andric V6_vmpyh = HVC.HST.getIntrinsicId(Hexagon::V6_vmpyhus); 1994bdd1243dSDimitry Andric } else { 1995bdd1243dSDimitry Andric V6_vmpyh = HVC.HST.getIntrinsicId(Hexagon::V6_vmpyuhv); 1996bdd1243dSDimitry Andric } 1997bdd1243dSDimitry Andric 1998bdd1243dSDimitry Andric // i16*i16 -> i32 / interleaved 1999bdd1243dSDimitry Andric Value *P = 2000bdd1243dSDimitry Andric HVC.createHvxIntrinsic(Builder, V6_vmpyh, HvxP32Ty, {Y.Val, X.Val}); 2001bdd1243dSDimitry Andric // Deinterleave 2002bdd1243dSDimitry Andric return HVC.vshuff(Builder, HVC.sublo(Builder, P), HVC.subhi(Builder, P)); 2003bdd1243dSDimitry Andric } 2004bdd1243dSDimitry Andric 2005bdd1243dSDimitry Andric auto HvxIdioms::createMulH16(IRBuilderBase &Builder, SValue X, SValue Y) const 2006bdd1243dSDimitry Andric -> Value * { 2007bdd1243dSDimitry Andric Type *HvxI16Ty = HVC.getHvxTy(HVC.getIntTy(16), /*Pair=*/false); 2008bdd1243dSDimitry Andric 2009bdd1243dSDimitry Andric if (HVC.HST.useHVXV69Ops()) { 2010bdd1243dSDimitry Andric if (X.Sgn != Signed && Y.Sgn != Signed) { 2011bdd1243dSDimitry Andric auto V6_vmpyuhvs = HVC.HST.getIntrinsicId(Hexagon::V6_vmpyuhvs); 2012bdd1243dSDimitry Andric return HVC.createHvxIntrinsic(Builder, V6_vmpyuhvs, HvxI16Ty, 2013bdd1243dSDimitry Andric {X.Val, Y.Val}); 2014bdd1243dSDimitry Andric } 2015bdd1243dSDimitry Andric } 2016bdd1243dSDimitry Andric 2017bdd1243dSDimitry Andric Type *HvxP16Ty = HVC.getHvxTy(HVC.getIntTy(16), /*Pair=*/true); 201806c3fb27SDimitry Andric Value *Pair16 = 201906c3fb27SDimitry Andric Builder.CreateBitCast(createMul16(Builder, X, Y), HvxP16Ty, "cst"); 2020bdd1243dSDimitry Andric unsigned Len = HVC.length(HvxP16Ty) / 2; 2021bdd1243dSDimitry Andric 2022bdd1243dSDimitry Andric SmallVector<int, 128> PickOdd(Len); 2023bdd1243dSDimitry Andric for (int i = 0; i != static_cast<int>(Len); ++i) 2024bdd1243dSDimitry Andric PickOdd[i] = 2 * i + 1; 2025bdd1243dSDimitry Andric 202606c3fb27SDimitry Andric return Builder.CreateShuffleVector( 202706c3fb27SDimitry Andric HVC.sublo(Builder, Pair16), HVC.subhi(Builder, Pair16), PickOdd, "shf"); 2028bdd1243dSDimitry Andric } 2029bdd1243dSDimitry Andric 2030bdd1243dSDimitry Andric auto HvxIdioms::createMul32(IRBuilderBase &Builder, SValue X, SValue Y) const 2031bdd1243dSDimitry Andric -> std::pair<Value *, Value *> { 2032bdd1243dSDimitry Andric assert(X.Val->getType() == Y.Val->getType()); 2033bdd1243dSDimitry Andric assert(X.Val->getType() == HvxI32Ty); 2034bdd1243dSDimitry Andric 2035bdd1243dSDimitry Andric Intrinsic::ID V6_vmpy_parts; 2036bdd1243dSDimitry Andric std::tie(X, Y) = canonSgn(X, Y); 2037bdd1243dSDimitry Andric 2038bdd1243dSDimitry Andric if (X.Sgn == Signed) { 2039bdd1243dSDimitry Andric V6_vmpy_parts = Intrinsic::hexagon_V6_vmpyss_parts; 2040bdd1243dSDimitry Andric } else if (Y.Sgn == Signed) { 2041bdd1243dSDimitry Andric V6_vmpy_parts = Intrinsic::hexagon_V6_vmpyus_parts; 2042bdd1243dSDimitry Andric } else { 2043bdd1243dSDimitry Andric V6_vmpy_parts = Intrinsic::hexagon_V6_vmpyuu_parts; 2044bdd1243dSDimitry Andric } 2045bdd1243dSDimitry Andric 2046bdd1243dSDimitry Andric Value *Parts = HVC.createHvxIntrinsic(Builder, V6_vmpy_parts, nullptr, 2047bdd1243dSDimitry Andric {X.Val, Y.Val}, {HvxI32Ty}); 204806c3fb27SDimitry Andric Value *Hi = Builder.CreateExtractValue(Parts, {0}, "ext"); 204906c3fb27SDimitry Andric Value *Lo = Builder.CreateExtractValue(Parts, {1}, "ext"); 2050bdd1243dSDimitry Andric return {Lo, Hi}; 2051bdd1243dSDimitry Andric } 2052bdd1243dSDimitry Andric 2053bdd1243dSDimitry Andric auto HvxIdioms::createAddLong(IRBuilderBase &Builder, ArrayRef<Value *> WordX, 2054bdd1243dSDimitry Andric ArrayRef<Value *> WordY) const 2055bdd1243dSDimitry Andric -> SmallVector<Value *> { 2056bdd1243dSDimitry Andric assert(WordX.size() == WordY.size()); 2057bdd1243dSDimitry Andric unsigned Idx = 0, Length = WordX.size(); 2058bdd1243dSDimitry Andric SmallVector<Value *> Sum(Length); 2059bdd1243dSDimitry Andric 2060bdd1243dSDimitry Andric while (Idx != Length) { 2061bdd1243dSDimitry Andric if (HVC.isZero(WordX[Idx])) 2062bdd1243dSDimitry Andric Sum[Idx] = WordY[Idx]; 2063bdd1243dSDimitry Andric else if (HVC.isZero(WordY[Idx])) 2064bdd1243dSDimitry Andric Sum[Idx] = WordX[Idx]; 2065bdd1243dSDimitry Andric else 2066bdd1243dSDimitry Andric break; 2067bdd1243dSDimitry Andric ++Idx; 2068bdd1243dSDimitry Andric } 2069bdd1243dSDimitry Andric 2070bdd1243dSDimitry Andric Value *Carry = nullptr; 2071bdd1243dSDimitry Andric for (; Idx != Length; ++Idx) { 2072bdd1243dSDimitry Andric std::tie(Sum[Idx], Carry) = 2073bdd1243dSDimitry Andric createAddCarry(Builder, WordX[Idx], WordY[Idx], Carry); 2074bdd1243dSDimitry Andric } 2075bdd1243dSDimitry Andric 2076bdd1243dSDimitry Andric // This drops the final carry beyond the highest word. 2077bdd1243dSDimitry Andric return Sum; 2078bdd1243dSDimitry Andric } 2079bdd1243dSDimitry Andric 2080bdd1243dSDimitry Andric auto HvxIdioms::createMulLong(IRBuilderBase &Builder, ArrayRef<Value *> WordX, 2081bdd1243dSDimitry Andric Signedness SgnX, ArrayRef<Value *> WordY, 2082bdd1243dSDimitry Andric Signedness SgnY) const -> SmallVector<Value *> { 2083bdd1243dSDimitry Andric SmallVector<SmallVector<Value *>> Products(WordX.size() + WordY.size()); 2084bdd1243dSDimitry Andric 2085bdd1243dSDimitry Andric // WordX[i] * WordY[j] produces words i+j and i+j+1 of the results, 2086bdd1243dSDimitry Andric // that is halves 2(i+j), 2(i+j)+1, 2(i+j)+2, 2(i+j)+3. 2087bdd1243dSDimitry Andric for (int i = 0, e = WordX.size(); i != e; ++i) { 2088bdd1243dSDimitry Andric for (int j = 0, f = WordY.size(); j != f; ++j) { 2089bdd1243dSDimitry Andric // Check the 4 halves that this multiplication can generate. 2090bdd1243dSDimitry Andric Signedness SX = (i + 1 == e) ? SgnX : Unsigned; 2091bdd1243dSDimitry Andric Signedness SY = (j + 1 == f) ? SgnY : Unsigned; 2092bdd1243dSDimitry Andric auto [Lo, Hi] = createMul32(Builder, {WordX[i], SX}, {WordY[j], SY}); 2093bdd1243dSDimitry Andric Products[i + j + 0].push_back(Lo); 2094bdd1243dSDimitry Andric Products[i + j + 1].push_back(Hi); 2095bdd1243dSDimitry Andric } 2096bdd1243dSDimitry Andric } 2097bdd1243dSDimitry Andric 2098bdd1243dSDimitry Andric Value *Zero = HVC.getNullValue(WordX[0]->getType()); 2099bdd1243dSDimitry Andric 2100bdd1243dSDimitry Andric auto pop_back_or_zero = [Zero](auto &Vector) -> Value * { 2101bdd1243dSDimitry Andric if (Vector.empty()) 2102bdd1243dSDimitry Andric return Zero; 2103bdd1243dSDimitry Andric auto Last = Vector.back(); 2104bdd1243dSDimitry Andric Vector.pop_back(); 2105bdd1243dSDimitry Andric return Last; 2106bdd1243dSDimitry Andric }; 2107bdd1243dSDimitry Andric 2108bdd1243dSDimitry Andric for (int i = 0, e = Products.size(); i != e; ++i) { 2109bdd1243dSDimitry Andric while (Products[i].size() > 1) { 2110bdd1243dSDimitry Andric Value *Carry = nullptr; // no carry-in 2111bdd1243dSDimitry Andric for (int j = i; j != e; ++j) { 2112bdd1243dSDimitry Andric auto &ProdJ = Products[j]; 2113bdd1243dSDimitry Andric auto [Sum, CarryOut] = createAddCarry(Builder, pop_back_or_zero(ProdJ), 2114bdd1243dSDimitry Andric pop_back_or_zero(ProdJ), Carry); 2115bdd1243dSDimitry Andric ProdJ.insert(ProdJ.begin(), Sum); 2116bdd1243dSDimitry Andric Carry = CarryOut; 2117bdd1243dSDimitry Andric } 2118bdd1243dSDimitry Andric } 2119bdd1243dSDimitry Andric } 2120bdd1243dSDimitry Andric 2121bdd1243dSDimitry Andric SmallVector<Value *> WordP; 2122bdd1243dSDimitry Andric for (auto &P : Products) { 2123bdd1243dSDimitry Andric assert(P.size() == 1 && "Should have been added together"); 2124bdd1243dSDimitry Andric WordP.push_back(P.front()); 2125bdd1243dSDimitry Andric } 2126bdd1243dSDimitry Andric 2127bdd1243dSDimitry Andric return WordP; 2128bdd1243dSDimitry Andric } 2129bdd1243dSDimitry Andric 2130bdd1243dSDimitry Andric auto HvxIdioms::run() -> bool { 2131bdd1243dSDimitry Andric bool Changed = false; 2132bdd1243dSDimitry Andric 2133bdd1243dSDimitry Andric for (BasicBlock &B : HVC.F) { 2134bdd1243dSDimitry Andric for (auto It = B.rbegin(); It != B.rend(); ++It) { 2135bdd1243dSDimitry Andric if (auto Fxm = matchFxpMul(*It)) { 2136bdd1243dSDimitry Andric Value *New = processFxpMul(*It, *Fxm); 2137bdd1243dSDimitry Andric // Always report "changed" for now. 2138bdd1243dSDimitry Andric Changed = true; 2139bdd1243dSDimitry Andric if (!New) 2140bdd1243dSDimitry Andric continue; 2141bdd1243dSDimitry Andric bool StartOver = !isa<Instruction>(New); 2142bdd1243dSDimitry Andric It->replaceAllUsesWith(New); 2143bdd1243dSDimitry Andric RecursivelyDeleteTriviallyDeadInstructions(&*It, &HVC.TLI); 2144bdd1243dSDimitry Andric It = StartOver ? B.rbegin() 2145bdd1243dSDimitry Andric : cast<Instruction>(New)->getReverseIterator(); 2146bdd1243dSDimitry Andric Changed = true; 2147bdd1243dSDimitry Andric } 2148bdd1243dSDimitry Andric } 2149bdd1243dSDimitry Andric } 2150bdd1243dSDimitry Andric 2151bdd1243dSDimitry Andric return Changed; 2152bdd1243dSDimitry Andric } 2153bdd1243dSDimitry Andric 2154bdd1243dSDimitry Andric // --- End HvxIdioms 2155bdd1243dSDimitry Andric 2156e8d8bef9SDimitry Andric auto HexagonVectorCombine::run() -> bool { 215706c3fb27SDimitry Andric if (DumpModule) 215806c3fb27SDimitry Andric dbgs() << "Module before HexagonVectorCombine\n" << *F.getParent(); 2159e8d8bef9SDimitry Andric 2160bdd1243dSDimitry Andric bool Changed = false; 216106c3fb27SDimitry Andric if (HST.useHVXOps()) { 216206c3fb27SDimitry Andric if (VAEnabled) 2163bdd1243dSDimitry Andric Changed |= AlignVectors(*this).run(); 216406c3fb27SDimitry Andric if (VIEnabled) 2165bdd1243dSDimitry Andric Changed |= HvxIdioms(*this).run(); 216606c3fb27SDimitry Andric } 2167bdd1243dSDimitry Andric 216806c3fb27SDimitry Andric if (DumpModule) { 216906c3fb27SDimitry Andric dbgs() << "Module " << (Changed ? "(modified)" : "(unchanged)") 217006c3fb27SDimitry Andric << " after HexagonVectorCombine\n" 217106c3fb27SDimitry Andric << *F.getParent(); 217206c3fb27SDimitry Andric } 2173e8d8bef9SDimitry Andric return Changed; 2174e8d8bef9SDimitry Andric } 2175e8d8bef9SDimitry Andric 2176bdd1243dSDimitry Andric auto HexagonVectorCombine::getIntTy(unsigned Width) const -> IntegerType * { 2177bdd1243dSDimitry Andric return IntegerType::get(F.getContext(), Width); 2178e8d8bef9SDimitry Andric } 2179e8d8bef9SDimitry Andric 2180e8d8bef9SDimitry Andric auto HexagonVectorCombine::getByteTy(int ElemCount) const -> Type * { 2181e8d8bef9SDimitry Andric assert(ElemCount >= 0); 2182e8d8bef9SDimitry Andric IntegerType *ByteTy = Type::getInt8Ty(F.getContext()); 2183e8d8bef9SDimitry Andric if (ElemCount == 0) 2184e8d8bef9SDimitry Andric return ByteTy; 2185bdd1243dSDimitry Andric return VectorType::get(ByteTy, ElemCount, /*Scalable=*/false); 2186e8d8bef9SDimitry Andric } 2187e8d8bef9SDimitry Andric 2188e8d8bef9SDimitry Andric auto HexagonVectorCombine::getBoolTy(int ElemCount) const -> Type * { 2189e8d8bef9SDimitry Andric assert(ElemCount >= 0); 2190e8d8bef9SDimitry Andric IntegerType *BoolTy = Type::getInt1Ty(F.getContext()); 2191e8d8bef9SDimitry Andric if (ElemCount == 0) 2192e8d8bef9SDimitry Andric return BoolTy; 2193bdd1243dSDimitry Andric return VectorType::get(BoolTy, ElemCount, /*Scalable=*/false); 2194e8d8bef9SDimitry Andric } 2195e8d8bef9SDimitry Andric 2196bdd1243dSDimitry Andric auto HexagonVectorCombine::getConstInt(int Val, unsigned Width) const 2197bdd1243dSDimitry Andric -> ConstantInt * { 2198bdd1243dSDimitry Andric return ConstantInt::getSigned(getIntTy(Width), Val); 2199e8d8bef9SDimitry Andric } 2200e8d8bef9SDimitry Andric 2201e8d8bef9SDimitry Andric auto HexagonVectorCombine::isZero(const Value *Val) const -> bool { 2202e8d8bef9SDimitry Andric if (auto *C = dyn_cast<Constant>(Val)) 2203e8d8bef9SDimitry Andric return C->isZeroValue(); 2204e8d8bef9SDimitry Andric return false; 2205e8d8bef9SDimitry Andric } 2206e8d8bef9SDimitry Andric 2207e8d8bef9SDimitry Andric auto HexagonVectorCombine::getIntValue(const Value *Val) const 2208bdd1243dSDimitry Andric -> std::optional<APInt> { 2209e8d8bef9SDimitry Andric if (auto *CI = dyn_cast<ConstantInt>(Val)) 2210e8d8bef9SDimitry Andric return CI->getValue(); 2211bdd1243dSDimitry Andric return std::nullopt; 2212e8d8bef9SDimitry Andric } 2213e8d8bef9SDimitry Andric 2214e8d8bef9SDimitry Andric auto HexagonVectorCombine::isUndef(const Value *Val) const -> bool { 2215e8d8bef9SDimitry Andric return isa<UndefValue>(Val); 2216e8d8bef9SDimitry Andric } 2217e8d8bef9SDimitry Andric 221806c3fb27SDimitry Andric auto HexagonVectorCombine::isTrue(const Value *Val) const -> bool { 221906c3fb27SDimitry Andric return Val == ConstantInt::getTrue(Val->getType()); 222006c3fb27SDimitry Andric } 222106c3fb27SDimitry Andric 222206c3fb27SDimitry Andric auto HexagonVectorCombine::isFalse(const Value *Val) const -> bool { 222306c3fb27SDimitry Andric return isZero(Val); 222406c3fb27SDimitry Andric } 222506c3fb27SDimitry Andric 2226bdd1243dSDimitry Andric auto HexagonVectorCombine::getHvxTy(Type *ElemTy, bool Pair) const 2227bdd1243dSDimitry Andric -> VectorType * { 2228bdd1243dSDimitry Andric EVT ETy = EVT::getEVT(ElemTy, false); 2229bdd1243dSDimitry Andric assert(ETy.isSimple() && "Invalid HVX element type"); 2230bdd1243dSDimitry Andric // Do not allow boolean types here: they don't have a fixed length. 2231bdd1243dSDimitry Andric assert(HST.isHVXElementType(ETy.getSimpleVT(), /*IncludeBool=*/false) && 2232bdd1243dSDimitry Andric "Invalid HVX element type"); 2233bdd1243dSDimitry Andric unsigned HwLen = HST.getVectorLength(); 2234bdd1243dSDimitry Andric unsigned NumElems = (8 * HwLen) / ETy.getSizeInBits(); 2235bdd1243dSDimitry Andric return VectorType::get(ElemTy, Pair ? 2 * NumElems : NumElems, 2236bdd1243dSDimitry Andric /*Scalable=*/false); 2237e8d8bef9SDimitry Andric } 2238e8d8bef9SDimitry Andric 2239bdd1243dSDimitry Andric auto HexagonVectorCombine::getSizeOf(const Value *Val, SizeKind Kind) const 2240bdd1243dSDimitry Andric -> int { 2241bdd1243dSDimitry Andric return getSizeOf(Val->getType(), Kind); 2242e8d8bef9SDimitry Andric } 2243e8d8bef9SDimitry Andric 2244bdd1243dSDimitry Andric auto HexagonVectorCombine::getSizeOf(const Type *Ty, SizeKind Kind) const 2245bdd1243dSDimitry Andric -> int { 2246bdd1243dSDimitry Andric auto *NcTy = const_cast<Type *>(Ty); 2247bdd1243dSDimitry Andric switch (Kind) { 2248bdd1243dSDimitry Andric case Store: 2249bdd1243dSDimitry Andric return DL.getTypeStoreSize(NcTy).getFixedValue(); 2250bdd1243dSDimitry Andric case Alloc: 2251bdd1243dSDimitry Andric return DL.getTypeAllocSize(NcTy).getFixedValue(); 2252bdd1243dSDimitry Andric } 2253bdd1243dSDimitry Andric llvm_unreachable("Unhandled SizeKind enum"); 2254349cc55cSDimitry Andric } 2255349cc55cSDimitry Andric 2256e8d8bef9SDimitry Andric auto HexagonVectorCombine::getTypeAlignment(Type *Ty) const -> int { 2257e8d8bef9SDimitry Andric // The actual type may be shorter than the HVX vector, so determine 2258e8d8bef9SDimitry Andric // the alignment based on subtarget info. 2259e8d8bef9SDimitry Andric if (HST.isTypeForHVX(Ty)) 2260e8d8bef9SDimitry Andric return HST.getVectorLength(); 2261e8d8bef9SDimitry Andric return DL.getABITypeAlign(Ty).value(); 2262e8d8bef9SDimitry Andric } 2263e8d8bef9SDimitry Andric 2264bdd1243dSDimitry Andric auto HexagonVectorCombine::length(Value *Val) const -> size_t { 2265bdd1243dSDimitry Andric return length(Val->getType()); 2266bdd1243dSDimitry Andric } 2267bdd1243dSDimitry Andric 2268bdd1243dSDimitry Andric auto HexagonVectorCombine::length(Type *Ty) const -> size_t { 2269bdd1243dSDimitry Andric auto *VecTy = dyn_cast<VectorType>(Ty); 2270bdd1243dSDimitry Andric assert(VecTy && "Must be a vector type"); 2271bdd1243dSDimitry Andric return VecTy->getElementCount().getFixedValue(); 2272bdd1243dSDimitry Andric } 2273bdd1243dSDimitry Andric 2274e8d8bef9SDimitry Andric auto HexagonVectorCombine::getNullValue(Type *Ty) const -> Constant * { 2275e8d8bef9SDimitry Andric assert(Ty->isIntOrIntVectorTy()); 2276e8d8bef9SDimitry Andric auto Zero = ConstantInt::get(Ty->getScalarType(), 0); 2277e8d8bef9SDimitry Andric if (auto *VecTy = dyn_cast<VectorType>(Ty)) 2278e8d8bef9SDimitry Andric return ConstantVector::getSplat(VecTy->getElementCount(), Zero); 2279e8d8bef9SDimitry Andric return Zero; 2280e8d8bef9SDimitry Andric } 2281e8d8bef9SDimitry Andric 2282e8d8bef9SDimitry Andric auto HexagonVectorCombine::getFullValue(Type *Ty) const -> Constant * { 2283e8d8bef9SDimitry Andric assert(Ty->isIntOrIntVectorTy()); 2284e8d8bef9SDimitry Andric auto Minus1 = ConstantInt::get(Ty->getScalarType(), -1); 2285e8d8bef9SDimitry Andric if (auto *VecTy = dyn_cast<VectorType>(Ty)) 2286e8d8bef9SDimitry Andric return ConstantVector::getSplat(VecTy->getElementCount(), Minus1); 2287e8d8bef9SDimitry Andric return Minus1; 2288e8d8bef9SDimitry Andric } 2289e8d8bef9SDimitry Andric 2290bdd1243dSDimitry Andric auto HexagonVectorCombine::getConstSplat(Type *Ty, int Val) const 2291bdd1243dSDimitry Andric -> Constant * { 2292bdd1243dSDimitry Andric assert(Ty->isVectorTy()); 2293bdd1243dSDimitry Andric auto VecTy = cast<VectorType>(Ty); 2294bdd1243dSDimitry Andric Type *ElemTy = VecTy->getElementType(); 2295bdd1243dSDimitry Andric // Add support for floats if needed. 2296bdd1243dSDimitry Andric auto *Splat = ConstantVector::getSplat(VecTy->getElementCount(), 2297bdd1243dSDimitry Andric ConstantInt::get(ElemTy, Val)); 2298bdd1243dSDimitry Andric return Splat; 2299bdd1243dSDimitry Andric } 2300bdd1243dSDimitry Andric 2301bdd1243dSDimitry Andric auto HexagonVectorCombine::simplify(Value *V) const -> Value * { 2302bdd1243dSDimitry Andric if (auto *In = dyn_cast<Instruction>(V)) { 2303bdd1243dSDimitry Andric SimplifyQuery Q(DL, &TLI, &DT, &AC, In); 2304bdd1243dSDimitry Andric return simplifyInstruction(In, Q); 2305bdd1243dSDimitry Andric } 2306bdd1243dSDimitry Andric return nullptr; 2307bdd1243dSDimitry Andric } 2308bdd1243dSDimitry Andric 2309e8d8bef9SDimitry Andric // Insert bytes [Start..Start+Length) of Src into Dst at byte Where. 2310bdd1243dSDimitry Andric auto HexagonVectorCombine::insertb(IRBuilderBase &Builder, Value *Dst, 2311bdd1243dSDimitry Andric Value *Src, int Start, int Length, 2312bdd1243dSDimitry Andric int Where) const -> Value * { 2313e8d8bef9SDimitry Andric assert(isByteVecTy(Dst->getType()) && isByteVecTy(Src->getType())); 2314e8d8bef9SDimitry Andric int SrcLen = getSizeOf(Src); 2315e8d8bef9SDimitry Andric int DstLen = getSizeOf(Dst); 2316e8d8bef9SDimitry Andric assert(0 <= Start && Start + Length <= SrcLen); 2317e8d8bef9SDimitry Andric assert(0 <= Where && Where + Length <= DstLen); 2318e8d8bef9SDimitry Andric 2319e8d8bef9SDimitry Andric int P2Len = PowerOf2Ceil(SrcLen | DstLen); 2320e8d8bef9SDimitry Andric auto *Undef = UndefValue::get(getByteTy()); 2321e8d8bef9SDimitry Andric Value *P2Src = vresize(Builder, Src, P2Len, Undef); 2322e8d8bef9SDimitry Andric Value *P2Dst = vresize(Builder, Dst, P2Len, Undef); 2323e8d8bef9SDimitry Andric 2324e8d8bef9SDimitry Andric SmallVector<int, 256> SMask(P2Len); 2325e8d8bef9SDimitry Andric for (int i = 0; i != P2Len; ++i) { 2326e8d8bef9SDimitry Andric // If i is in [Where, Where+Length), pick Src[Start+(i-Where)]. 2327e8d8bef9SDimitry Andric // Otherwise, pick Dst[i]; 2328e8d8bef9SDimitry Andric SMask[i] = 2329e8d8bef9SDimitry Andric (Where <= i && i < Where + Length) ? P2Len + Start + (i - Where) : i; 2330e8d8bef9SDimitry Andric } 2331e8d8bef9SDimitry Andric 233206c3fb27SDimitry Andric Value *P2Insert = Builder.CreateShuffleVector(P2Dst, P2Src, SMask, "shf"); 2333e8d8bef9SDimitry Andric return vresize(Builder, P2Insert, DstLen, Undef); 2334e8d8bef9SDimitry Andric } 2335e8d8bef9SDimitry Andric 2336bdd1243dSDimitry Andric auto HexagonVectorCombine::vlalignb(IRBuilderBase &Builder, Value *Lo, 2337bdd1243dSDimitry Andric Value *Hi, Value *Amt) const -> Value * { 2338e8d8bef9SDimitry Andric assert(Lo->getType() == Hi->getType() && "Argument type mismatch"); 2339e8d8bef9SDimitry Andric if (isZero(Amt)) 2340e8d8bef9SDimitry Andric return Hi; 2341e8d8bef9SDimitry Andric int VecLen = getSizeOf(Hi); 2342e8d8bef9SDimitry Andric if (auto IntAmt = getIntValue(Amt)) 2343e8d8bef9SDimitry Andric return getElementRange(Builder, Lo, Hi, VecLen - IntAmt->getSExtValue(), 2344e8d8bef9SDimitry Andric VecLen); 2345e8d8bef9SDimitry Andric 2346e8d8bef9SDimitry Andric if (HST.isTypeForHVX(Hi->getType())) { 2347bdd1243dSDimitry Andric assert(static_cast<unsigned>(VecLen) == HST.getVectorLength() && 2348bdd1243dSDimitry Andric "Expecting an exact HVX type"); 2349bdd1243dSDimitry Andric return createHvxIntrinsic(Builder, HST.getIntrinsicId(Hexagon::V6_vlalignb), 2350bdd1243dSDimitry Andric Hi->getType(), {Hi, Lo, Amt}); 2351e8d8bef9SDimitry Andric } 2352e8d8bef9SDimitry Andric 2353e8d8bef9SDimitry Andric if (VecLen == 4) { 2354e8d8bef9SDimitry Andric Value *Pair = concat(Builder, {Lo, Hi}); 235506c3fb27SDimitry Andric Value *Shift = 235606c3fb27SDimitry Andric Builder.CreateLShr(Builder.CreateShl(Pair, Amt, "shl"), 32, "lsr"); 235706c3fb27SDimitry Andric Value *Trunc = 235806c3fb27SDimitry Andric Builder.CreateTrunc(Shift, Type::getInt32Ty(F.getContext()), "trn"); 235906c3fb27SDimitry Andric return Builder.CreateBitCast(Trunc, Hi->getType(), "cst"); 2360e8d8bef9SDimitry Andric } 2361e8d8bef9SDimitry Andric if (VecLen == 8) { 236206c3fb27SDimitry Andric Value *Sub = Builder.CreateSub(getConstInt(VecLen), Amt, "sub"); 2363e8d8bef9SDimitry Andric return vralignb(Builder, Lo, Hi, Sub); 2364e8d8bef9SDimitry Andric } 2365e8d8bef9SDimitry Andric llvm_unreachable("Unexpected vector length"); 2366e8d8bef9SDimitry Andric } 2367e8d8bef9SDimitry Andric 2368bdd1243dSDimitry Andric auto HexagonVectorCombine::vralignb(IRBuilderBase &Builder, Value *Lo, 2369bdd1243dSDimitry Andric Value *Hi, Value *Amt) const -> Value * { 2370e8d8bef9SDimitry Andric assert(Lo->getType() == Hi->getType() && "Argument type mismatch"); 2371e8d8bef9SDimitry Andric if (isZero(Amt)) 2372e8d8bef9SDimitry Andric return Lo; 2373e8d8bef9SDimitry Andric int VecLen = getSizeOf(Lo); 2374e8d8bef9SDimitry Andric if (auto IntAmt = getIntValue(Amt)) 2375e8d8bef9SDimitry Andric return getElementRange(Builder, Lo, Hi, IntAmt->getSExtValue(), VecLen); 2376e8d8bef9SDimitry Andric 2377e8d8bef9SDimitry Andric if (HST.isTypeForHVX(Lo->getType())) { 2378bdd1243dSDimitry Andric assert(static_cast<unsigned>(VecLen) == HST.getVectorLength() && 2379bdd1243dSDimitry Andric "Expecting an exact HVX type"); 2380bdd1243dSDimitry Andric return createHvxIntrinsic(Builder, HST.getIntrinsicId(Hexagon::V6_valignb), 2381bdd1243dSDimitry Andric Lo->getType(), {Hi, Lo, Amt}); 2382e8d8bef9SDimitry Andric } 2383e8d8bef9SDimitry Andric 2384e8d8bef9SDimitry Andric if (VecLen == 4) { 2385e8d8bef9SDimitry Andric Value *Pair = concat(Builder, {Lo, Hi}); 238606c3fb27SDimitry Andric Value *Shift = Builder.CreateLShr(Pair, Amt, "lsr"); 238706c3fb27SDimitry Andric Value *Trunc = 238806c3fb27SDimitry Andric Builder.CreateTrunc(Shift, Type::getInt32Ty(F.getContext()), "trn"); 238906c3fb27SDimitry Andric return Builder.CreateBitCast(Trunc, Lo->getType(), "cst"); 2390e8d8bef9SDimitry Andric } 2391e8d8bef9SDimitry Andric if (VecLen == 8) { 2392e8d8bef9SDimitry Andric Type *Int64Ty = Type::getInt64Ty(F.getContext()); 239306c3fb27SDimitry Andric Value *Lo64 = Builder.CreateBitCast(Lo, Int64Ty, "cst"); 239406c3fb27SDimitry Andric Value *Hi64 = Builder.CreateBitCast(Hi, Int64Ty, "cst"); 2395e8d8bef9SDimitry Andric Function *FI = Intrinsic::getDeclaration(F.getParent(), 2396e8d8bef9SDimitry Andric Intrinsic::hexagon_S2_valignrb); 239706c3fb27SDimitry Andric Value *Call = Builder.CreateCall(FI, {Hi64, Lo64, Amt}, "cup"); 239806c3fb27SDimitry Andric return Builder.CreateBitCast(Call, Lo->getType(), "cst"); 2399e8d8bef9SDimitry Andric } 2400e8d8bef9SDimitry Andric llvm_unreachable("Unexpected vector length"); 2401e8d8bef9SDimitry Andric } 2402e8d8bef9SDimitry Andric 2403e8d8bef9SDimitry Andric // Concatenates a sequence of vectors of the same type. 2404bdd1243dSDimitry Andric auto HexagonVectorCombine::concat(IRBuilderBase &Builder, 2405e8d8bef9SDimitry Andric ArrayRef<Value *> Vecs) const -> Value * { 2406e8d8bef9SDimitry Andric assert(!Vecs.empty()); 2407e8d8bef9SDimitry Andric SmallVector<int, 256> SMask; 2408e8d8bef9SDimitry Andric std::vector<Value *> Work[2]; 2409e8d8bef9SDimitry Andric int ThisW = 0, OtherW = 1; 2410e8d8bef9SDimitry Andric 2411e8d8bef9SDimitry Andric Work[ThisW].assign(Vecs.begin(), Vecs.end()); 2412e8d8bef9SDimitry Andric while (Work[ThisW].size() > 1) { 2413e8d8bef9SDimitry Andric auto *Ty = cast<VectorType>(Work[ThisW].front()->getType()); 2414bdd1243dSDimitry Andric SMask.resize(length(Ty) * 2); 2415e8d8bef9SDimitry Andric std::iota(SMask.begin(), SMask.end(), 0); 2416e8d8bef9SDimitry Andric 2417e8d8bef9SDimitry Andric Work[OtherW].clear(); 2418e8d8bef9SDimitry Andric if (Work[ThisW].size() % 2 != 0) 2419e8d8bef9SDimitry Andric Work[ThisW].push_back(UndefValue::get(Ty)); 2420e8d8bef9SDimitry Andric for (int i = 0, e = Work[ThisW].size(); i < e; i += 2) { 242106c3fb27SDimitry Andric Value *Joined = Builder.CreateShuffleVector( 242206c3fb27SDimitry Andric Work[ThisW][i], Work[ThisW][i + 1], SMask, "shf"); 2423e8d8bef9SDimitry Andric Work[OtherW].push_back(Joined); 2424e8d8bef9SDimitry Andric } 2425e8d8bef9SDimitry Andric std::swap(ThisW, OtherW); 2426e8d8bef9SDimitry Andric } 2427e8d8bef9SDimitry Andric 2428e8d8bef9SDimitry Andric // Since there may have been some undefs appended to make shuffle operands 2429e8d8bef9SDimitry Andric // have the same type, perform the last shuffle to only pick the original 2430e8d8bef9SDimitry Andric // elements. 2431bdd1243dSDimitry Andric SMask.resize(Vecs.size() * length(Vecs.front()->getType())); 2432e8d8bef9SDimitry Andric std::iota(SMask.begin(), SMask.end(), 0); 2433bdd1243dSDimitry Andric Value *Total = Work[ThisW].front(); 243406c3fb27SDimitry Andric return Builder.CreateShuffleVector(Total, SMask, "shf"); 2435e8d8bef9SDimitry Andric } 2436e8d8bef9SDimitry Andric 2437bdd1243dSDimitry Andric auto HexagonVectorCombine::vresize(IRBuilderBase &Builder, Value *Val, 2438e8d8bef9SDimitry Andric int NewSize, Value *Pad) const -> Value * { 2439e8d8bef9SDimitry Andric assert(isa<VectorType>(Val->getType())); 2440e8d8bef9SDimitry Andric auto *ValTy = cast<VectorType>(Val->getType()); 2441e8d8bef9SDimitry Andric assert(ValTy->getElementType() == Pad->getType()); 2442e8d8bef9SDimitry Andric 2443bdd1243dSDimitry Andric int CurSize = length(ValTy); 2444e8d8bef9SDimitry Andric if (CurSize == NewSize) 2445e8d8bef9SDimitry Andric return Val; 2446e8d8bef9SDimitry Andric // Truncate? 2447e8d8bef9SDimitry Andric if (CurSize > NewSize) 2448bdd1243dSDimitry Andric return getElementRange(Builder, Val, /*Ignored*/ Val, 0, NewSize); 2449e8d8bef9SDimitry Andric // Extend. 2450e8d8bef9SDimitry Andric SmallVector<int, 128> SMask(NewSize); 2451e8d8bef9SDimitry Andric std::iota(SMask.begin(), SMask.begin() + CurSize, 0); 2452e8d8bef9SDimitry Andric std::fill(SMask.begin() + CurSize, SMask.end(), CurSize); 245306c3fb27SDimitry Andric Value *PadVec = Builder.CreateVectorSplat(CurSize, Pad, "spt"); 245406c3fb27SDimitry Andric return Builder.CreateShuffleVector(Val, PadVec, SMask, "shf"); 2455e8d8bef9SDimitry Andric } 2456e8d8bef9SDimitry Andric 2457bdd1243dSDimitry Andric auto HexagonVectorCombine::rescale(IRBuilderBase &Builder, Value *Mask, 2458e8d8bef9SDimitry Andric Type *FromTy, Type *ToTy) const -> Value * { 2459e8d8bef9SDimitry Andric // Mask is a vector <N x i1>, where each element corresponds to an 2460e8d8bef9SDimitry Andric // element of FromTy. Remap it so that each element will correspond 2461e8d8bef9SDimitry Andric // to an element of ToTy. 2462e8d8bef9SDimitry Andric assert(isa<VectorType>(Mask->getType())); 2463e8d8bef9SDimitry Andric 2464e8d8bef9SDimitry Andric Type *FromSTy = FromTy->getScalarType(); 2465e8d8bef9SDimitry Andric Type *ToSTy = ToTy->getScalarType(); 2466e8d8bef9SDimitry Andric if (FromSTy == ToSTy) 2467e8d8bef9SDimitry Andric return Mask; 2468e8d8bef9SDimitry Andric 2469e8d8bef9SDimitry Andric int FromSize = getSizeOf(FromSTy); 2470e8d8bef9SDimitry Andric int ToSize = getSizeOf(ToSTy); 2471e8d8bef9SDimitry Andric assert(FromSize % ToSize == 0 || ToSize % FromSize == 0); 2472e8d8bef9SDimitry Andric 2473e8d8bef9SDimitry Andric auto *MaskTy = cast<VectorType>(Mask->getType()); 2474bdd1243dSDimitry Andric int FromCount = length(MaskTy); 2475e8d8bef9SDimitry Andric int ToCount = (FromCount * FromSize) / ToSize; 2476e8d8bef9SDimitry Andric assert((FromCount * FromSize) % ToSize == 0); 2477e8d8bef9SDimitry Andric 2478bdd1243dSDimitry Andric auto *FromITy = getIntTy(FromSize * 8); 2479bdd1243dSDimitry Andric auto *ToITy = getIntTy(ToSize * 8); 248004eeddc0SDimitry Andric 2481e8d8bef9SDimitry Andric // Mask <N x i1> -> sext to <N x FromTy> -> bitcast to <M x ToTy> -> 2482e8d8bef9SDimitry Andric // -> trunc to <M x i1>. 2483e8d8bef9SDimitry Andric Value *Ext = Builder.CreateSExt( 248406c3fb27SDimitry Andric Mask, VectorType::get(FromITy, FromCount, /*Scalable=*/false), "sxt"); 2485e8d8bef9SDimitry Andric Value *Cast = Builder.CreateBitCast( 248606c3fb27SDimitry Andric Ext, VectorType::get(ToITy, ToCount, /*Scalable=*/false), "cst"); 2487e8d8bef9SDimitry Andric return Builder.CreateTrunc( 248806c3fb27SDimitry Andric Cast, VectorType::get(getBoolTy(), ToCount, /*Scalable=*/false), "trn"); 2489e8d8bef9SDimitry Andric } 2490e8d8bef9SDimitry Andric 2491e8d8bef9SDimitry Andric // Bitcast to bytes, and return least significant bits. 2492bdd1243dSDimitry Andric auto HexagonVectorCombine::vlsb(IRBuilderBase &Builder, Value *Val) const 2493e8d8bef9SDimitry Andric -> Value * { 2494e8d8bef9SDimitry Andric Type *ScalarTy = Val->getType()->getScalarType(); 2495e8d8bef9SDimitry Andric if (ScalarTy == getBoolTy()) 2496e8d8bef9SDimitry Andric return Val; 2497e8d8bef9SDimitry Andric 2498e8d8bef9SDimitry Andric Value *Bytes = vbytes(Builder, Val); 2499e8d8bef9SDimitry Andric if (auto *VecTy = dyn_cast<VectorType>(Bytes->getType())) 250006c3fb27SDimitry Andric return Builder.CreateTrunc(Bytes, getBoolTy(getSizeOf(VecTy)), "trn"); 2501e8d8bef9SDimitry Andric // If Bytes is a scalar (i.e. Val was a scalar byte), return i1, not 2502e8d8bef9SDimitry Andric // <1 x i1>. 250306c3fb27SDimitry Andric return Builder.CreateTrunc(Bytes, getBoolTy(), "trn"); 2504e8d8bef9SDimitry Andric } 2505e8d8bef9SDimitry Andric 2506e8d8bef9SDimitry Andric // Bitcast to bytes for non-bool. For bool, convert i1 -> i8. 2507bdd1243dSDimitry Andric auto HexagonVectorCombine::vbytes(IRBuilderBase &Builder, Value *Val) const 2508e8d8bef9SDimitry Andric -> Value * { 2509e8d8bef9SDimitry Andric Type *ScalarTy = Val->getType()->getScalarType(); 2510e8d8bef9SDimitry Andric if (ScalarTy == getByteTy()) 2511e8d8bef9SDimitry Andric return Val; 2512e8d8bef9SDimitry Andric 2513e8d8bef9SDimitry Andric if (ScalarTy != getBoolTy()) 251406c3fb27SDimitry Andric return Builder.CreateBitCast(Val, getByteTy(getSizeOf(Val)), "cst"); 2515e8d8bef9SDimitry Andric // For bool, return a sext from i1 to i8. 2516e8d8bef9SDimitry Andric if (auto *VecTy = dyn_cast<VectorType>(Val->getType())) 251706c3fb27SDimitry Andric return Builder.CreateSExt(Val, VectorType::get(getByteTy(), VecTy), "sxt"); 251806c3fb27SDimitry Andric return Builder.CreateSExt(Val, getByteTy(), "sxt"); 2519e8d8bef9SDimitry Andric } 2520e8d8bef9SDimitry Andric 2521bdd1243dSDimitry Andric auto HexagonVectorCombine::subvector(IRBuilderBase &Builder, Value *Val, 2522bdd1243dSDimitry Andric unsigned Start, unsigned Length) const 2523e8d8bef9SDimitry Andric -> Value * { 2524bdd1243dSDimitry Andric assert(Start + Length <= length(Val)); 2525bdd1243dSDimitry Andric return getElementRange(Builder, Val, /*Ignored*/ Val, Start, Length); 2526e8d8bef9SDimitry Andric } 2527e8d8bef9SDimitry Andric 2528bdd1243dSDimitry Andric auto HexagonVectorCombine::sublo(IRBuilderBase &Builder, Value *Val) const 2529bdd1243dSDimitry Andric -> Value * { 2530bdd1243dSDimitry Andric size_t Len = length(Val); 2531bdd1243dSDimitry Andric assert(Len % 2 == 0 && "Length should be even"); 2532bdd1243dSDimitry Andric return subvector(Builder, Val, 0, Len / 2); 2533bdd1243dSDimitry Andric } 2534bdd1243dSDimitry Andric 2535bdd1243dSDimitry Andric auto HexagonVectorCombine::subhi(IRBuilderBase &Builder, Value *Val) const 2536bdd1243dSDimitry Andric -> Value * { 2537bdd1243dSDimitry Andric size_t Len = length(Val); 2538bdd1243dSDimitry Andric assert(Len % 2 == 0 && "Length should be even"); 2539bdd1243dSDimitry Andric return subvector(Builder, Val, Len / 2, Len / 2); 2540bdd1243dSDimitry Andric } 2541bdd1243dSDimitry Andric 2542bdd1243dSDimitry Andric auto HexagonVectorCombine::vdeal(IRBuilderBase &Builder, Value *Val0, 2543bdd1243dSDimitry Andric Value *Val1) const -> Value * { 2544bdd1243dSDimitry Andric assert(Val0->getType() == Val1->getType()); 2545bdd1243dSDimitry Andric int Len = length(Val0); 2546bdd1243dSDimitry Andric SmallVector<int, 128> Mask(2 * Len); 2547bdd1243dSDimitry Andric 2548bdd1243dSDimitry Andric for (int i = 0; i != Len; ++i) { 2549bdd1243dSDimitry Andric Mask[i] = 2 * i; // Even 2550bdd1243dSDimitry Andric Mask[i + Len] = 2 * i + 1; // Odd 2551bdd1243dSDimitry Andric } 255206c3fb27SDimitry Andric return Builder.CreateShuffleVector(Val0, Val1, Mask, "shf"); 2553bdd1243dSDimitry Andric } 2554bdd1243dSDimitry Andric 2555bdd1243dSDimitry Andric auto HexagonVectorCombine::vshuff(IRBuilderBase &Builder, Value *Val0, 2556bdd1243dSDimitry Andric Value *Val1) const -> Value * { // 2557bdd1243dSDimitry Andric assert(Val0->getType() == Val1->getType()); 2558bdd1243dSDimitry Andric int Len = length(Val0); 2559bdd1243dSDimitry Andric SmallVector<int, 128> Mask(2 * Len); 2560bdd1243dSDimitry Andric 2561bdd1243dSDimitry Andric for (int i = 0; i != Len; ++i) { 2562bdd1243dSDimitry Andric Mask[2 * i + 0] = i; // Val0 2563bdd1243dSDimitry Andric Mask[2 * i + 1] = i + Len; // Val1 2564bdd1243dSDimitry Andric } 256506c3fb27SDimitry Andric return Builder.CreateShuffleVector(Val0, Val1, Mask, "shf"); 2566bdd1243dSDimitry Andric } 2567bdd1243dSDimitry Andric 2568bdd1243dSDimitry Andric auto HexagonVectorCombine::createHvxIntrinsic(IRBuilderBase &Builder, 2569bdd1243dSDimitry Andric Intrinsic::ID IntID, Type *RetTy, 2570bdd1243dSDimitry Andric ArrayRef<Value *> Args, 257106c3fb27SDimitry Andric ArrayRef<Type *> ArgTys, 257206c3fb27SDimitry Andric ArrayRef<Value *> MDSources) const 2573bdd1243dSDimitry Andric -> Value * { 2574bdd1243dSDimitry Andric auto getCast = [&](IRBuilderBase &Builder, Value *Val, 2575e8d8bef9SDimitry Andric Type *DestTy) -> Value * { 2576e8d8bef9SDimitry Andric Type *SrcTy = Val->getType(); 2577e8d8bef9SDimitry Andric if (SrcTy == DestTy) 2578e8d8bef9SDimitry Andric return Val; 2579bdd1243dSDimitry Andric 2580e8d8bef9SDimitry Andric // Non-HVX type. It should be a scalar, and it should already have 2581e8d8bef9SDimitry Andric // a valid type. 2582bdd1243dSDimitry Andric assert(HST.isTypeForHVX(SrcTy, /*IncludeBool=*/true)); 2583bdd1243dSDimitry Andric 2584bdd1243dSDimitry Andric Type *BoolTy = Type::getInt1Ty(F.getContext()); 2585bdd1243dSDimitry Andric if (cast<VectorType>(SrcTy)->getElementType() != BoolTy) 258606c3fb27SDimitry Andric return Builder.CreateBitCast(Val, DestTy, "cst"); 2587bdd1243dSDimitry Andric 2588bdd1243dSDimitry Andric // Predicate HVX vector. 2589bdd1243dSDimitry Andric unsigned HwLen = HST.getVectorLength(); 2590bdd1243dSDimitry Andric Intrinsic::ID TC = HwLen == 64 ? Intrinsic::hexagon_V6_pred_typecast 2591bdd1243dSDimitry Andric : Intrinsic::hexagon_V6_pred_typecast_128B; 2592bdd1243dSDimitry Andric Function *FI = 2593bdd1243dSDimitry Andric Intrinsic::getDeclaration(F.getParent(), TC, {DestTy, Val->getType()}); 259406c3fb27SDimitry Andric return Builder.CreateCall(FI, {Val}, "cup"); 2595e8d8bef9SDimitry Andric }; 2596e8d8bef9SDimitry Andric 2597bdd1243dSDimitry Andric Function *IntrFn = Intrinsic::getDeclaration(F.getParent(), IntID, ArgTys); 2598bdd1243dSDimitry Andric FunctionType *IntrTy = IntrFn->getFunctionType(); 2599bdd1243dSDimitry Andric 2600bdd1243dSDimitry Andric SmallVector<Value *, 4> IntrArgs; 2601bdd1243dSDimitry Andric for (int i = 0, e = Args.size(); i != e; ++i) { 2602bdd1243dSDimitry Andric Value *A = Args[i]; 2603bdd1243dSDimitry Andric Type *T = IntrTy->getParamType(i); 2604bdd1243dSDimitry Andric if (A->getType() != T) { 2605bdd1243dSDimitry Andric IntrArgs.push_back(getCast(Builder, A, T)); 2606bdd1243dSDimitry Andric } else { 2607bdd1243dSDimitry Andric IntrArgs.push_back(A); 2608bdd1243dSDimitry Andric } 2609bdd1243dSDimitry Andric } 261006c3fb27SDimitry Andric StringRef MaybeName = !IntrTy->getReturnType()->isVoidTy() ? "cup" : ""; 261106c3fb27SDimitry Andric CallInst *Call = Builder.CreateCall(IntrFn, IntrArgs, MaybeName); 261206c3fb27SDimitry Andric 261306c3fb27SDimitry Andric MemoryEffects ME = Call->getAttributes().getMemoryEffects(); 261406c3fb27SDimitry Andric if (!ME.doesNotAccessMemory() && !ME.onlyAccessesInaccessibleMem()) 261506c3fb27SDimitry Andric propagateMetadata(Call, MDSources); 2616e8d8bef9SDimitry Andric 2617e8d8bef9SDimitry Andric Type *CallTy = Call->getType(); 2618bdd1243dSDimitry Andric if (RetTy == nullptr || CallTy == RetTy) 2619e8d8bef9SDimitry Andric return Call; 2620e8d8bef9SDimitry Andric // Scalar types should have RetTy matching the call return type. 2621bdd1243dSDimitry Andric assert(HST.isTypeForHVX(CallTy, /*IncludeBool=*/true)); 2622e8d8bef9SDimitry Andric return getCast(Builder, Call, RetTy); 2623bdd1243dSDimitry Andric } 2624bdd1243dSDimitry Andric 2625bdd1243dSDimitry Andric auto HexagonVectorCombine::splitVectorElements(IRBuilderBase &Builder, 2626bdd1243dSDimitry Andric Value *Vec, 2627bdd1243dSDimitry Andric unsigned ToWidth) const 2628bdd1243dSDimitry Andric -> SmallVector<Value *> { 2629bdd1243dSDimitry Andric // Break a vector of wide elements into a series of vectors with narrow 2630bdd1243dSDimitry Andric // elements: 2631bdd1243dSDimitry Andric // (...c0:b0:a0, ...c1:b1:a1, ...c2:b2:a2, ...) 2632bdd1243dSDimitry Andric // --> 2633bdd1243dSDimitry Andric // (a0, a1, a2, ...) // lowest "ToWidth" bits 2634bdd1243dSDimitry Andric // (b0, b1, b2, ...) // the next lowest... 2635bdd1243dSDimitry Andric // (c0, c1, c2, ...) // ... 2636bdd1243dSDimitry Andric // ... 2637bdd1243dSDimitry Andric // 2638bdd1243dSDimitry Andric // The number of elements in each resulting vector is the same as 2639bdd1243dSDimitry Andric // in the original vector. 2640bdd1243dSDimitry Andric 2641bdd1243dSDimitry Andric auto *VecTy = cast<VectorType>(Vec->getType()); 2642bdd1243dSDimitry Andric assert(VecTy->getElementType()->isIntegerTy()); 2643bdd1243dSDimitry Andric unsigned FromWidth = VecTy->getScalarSizeInBits(); 2644bdd1243dSDimitry Andric assert(isPowerOf2_32(ToWidth) && isPowerOf2_32(FromWidth)); 2645bdd1243dSDimitry Andric assert(ToWidth <= FromWidth && "Breaking up into wider elements?"); 2646bdd1243dSDimitry Andric unsigned NumResults = FromWidth / ToWidth; 2647bdd1243dSDimitry Andric 2648bdd1243dSDimitry Andric SmallVector<Value *> Results(NumResults); 2649bdd1243dSDimitry Andric Results[0] = Vec; 2650bdd1243dSDimitry Andric unsigned Length = length(VecTy); 2651bdd1243dSDimitry Andric 2652bdd1243dSDimitry Andric // Do it by splitting in half, since those operations correspond to deal 2653bdd1243dSDimitry Andric // instructions. 2654bdd1243dSDimitry Andric auto splitInHalf = [&](unsigned Begin, unsigned End, auto splitFunc) -> void { 2655bdd1243dSDimitry Andric // Take V = Results[Begin], split it in L, H. 2656bdd1243dSDimitry Andric // Store Results[Begin] = L, Results[(Begin+End)/2] = H 2657bdd1243dSDimitry Andric // Call itself recursively split(Begin, Half), split(Half+1, End) 2658bdd1243dSDimitry Andric if (Begin + 1 == End) 2659bdd1243dSDimitry Andric return; 2660bdd1243dSDimitry Andric 2661bdd1243dSDimitry Andric Value *Val = Results[Begin]; 2662bdd1243dSDimitry Andric unsigned Width = Val->getType()->getScalarSizeInBits(); 2663bdd1243dSDimitry Andric 2664bdd1243dSDimitry Andric auto *VTy = VectorType::get(getIntTy(Width / 2), 2 * Length, false); 266506c3fb27SDimitry Andric Value *VVal = Builder.CreateBitCast(Val, VTy, "cst"); 2666bdd1243dSDimitry Andric 2667bdd1243dSDimitry Andric Value *Res = vdeal(Builder, sublo(Builder, VVal), subhi(Builder, VVal)); 2668bdd1243dSDimitry Andric 2669bdd1243dSDimitry Andric unsigned Half = (Begin + End) / 2; 2670bdd1243dSDimitry Andric Results[Begin] = sublo(Builder, Res); 2671bdd1243dSDimitry Andric Results[Half] = subhi(Builder, Res); 2672bdd1243dSDimitry Andric 2673bdd1243dSDimitry Andric splitFunc(Begin, Half, splitFunc); 2674bdd1243dSDimitry Andric splitFunc(Half, End, splitFunc); 2675bdd1243dSDimitry Andric }; 2676bdd1243dSDimitry Andric 2677bdd1243dSDimitry Andric splitInHalf(0, NumResults, splitInHalf); 2678bdd1243dSDimitry Andric return Results; 2679bdd1243dSDimitry Andric } 2680bdd1243dSDimitry Andric 2681bdd1243dSDimitry Andric auto HexagonVectorCombine::joinVectorElements(IRBuilderBase &Builder, 2682bdd1243dSDimitry Andric ArrayRef<Value *> Values, 2683bdd1243dSDimitry Andric VectorType *ToType) const 2684bdd1243dSDimitry Andric -> Value * { 2685bdd1243dSDimitry Andric assert(ToType->getElementType()->isIntegerTy()); 2686bdd1243dSDimitry Andric 2687bdd1243dSDimitry Andric // If the list of values does not have power-of-2 elements, append copies 2688bdd1243dSDimitry Andric // of the sign bit to it, to make the size be 2^n. 2689bdd1243dSDimitry Andric // The reason for this is that the values will be joined in pairs, because 2690bdd1243dSDimitry Andric // otherwise the shuffles will result in convoluted code. With pairwise 2691bdd1243dSDimitry Andric // joins, the shuffles will hopefully be folded into a perfect shuffle. 2692bdd1243dSDimitry Andric // The output will need to be sign-extended to a type with element width 2693bdd1243dSDimitry Andric // being a power-of-2 anyways. 2694bdd1243dSDimitry Andric SmallVector<Value *> Inputs(Values.begin(), Values.end()); 2695bdd1243dSDimitry Andric 2696bdd1243dSDimitry Andric unsigned ToWidth = ToType->getScalarSizeInBits(); 2697bdd1243dSDimitry Andric unsigned Width = Inputs.front()->getType()->getScalarSizeInBits(); 2698bdd1243dSDimitry Andric assert(Width <= ToWidth); 2699bdd1243dSDimitry Andric assert(isPowerOf2_32(Width) && isPowerOf2_32(ToWidth)); 2700bdd1243dSDimitry Andric unsigned Length = length(Inputs.front()->getType()); 2701bdd1243dSDimitry Andric 2702bdd1243dSDimitry Andric unsigned NeedInputs = ToWidth / Width; 2703bdd1243dSDimitry Andric if (Inputs.size() != NeedInputs) { 2704bdd1243dSDimitry Andric // Having too many inputs is ok: drop the high bits (usual wrap-around). 2705bdd1243dSDimitry Andric // If there are too few, fill them with the sign bit. 2706bdd1243dSDimitry Andric Value *Last = Inputs.back(); 270706c3fb27SDimitry Andric Value *Sign = Builder.CreateAShr( 270806c3fb27SDimitry Andric Last, getConstSplat(Last->getType(), Width - 1), "asr"); 2709bdd1243dSDimitry Andric Inputs.resize(NeedInputs, Sign); 2710bdd1243dSDimitry Andric } 2711bdd1243dSDimitry Andric 2712bdd1243dSDimitry Andric while (Inputs.size() > 1) { 2713bdd1243dSDimitry Andric Width *= 2; 2714bdd1243dSDimitry Andric auto *VTy = VectorType::get(getIntTy(Width), Length, false); 2715bdd1243dSDimitry Andric for (int i = 0, e = Inputs.size(); i < e; i += 2) { 2716bdd1243dSDimitry Andric Value *Res = vshuff(Builder, Inputs[i], Inputs[i + 1]); 271706c3fb27SDimitry Andric Inputs[i / 2] = Builder.CreateBitCast(Res, VTy, "cst"); 2718bdd1243dSDimitry Andric } 2719bdd1243dSDimitry Andric Inputs.resize(Inputs.size() / 2); 2720bdd1243dSDimitry Andric } 2721bdd1243dSDimitry Andric 2722bdd1243dSDimitry Andric assert(Inputs.front()->getType() == ToType); 2723bdd1243dSDimitry Andric return Inputs.front(); 2724e8d8bef9SDimitry Andric } 2725e8d8bef9SDimitry Andric 2726e8d8bef9SDimitry Andric auto HexagonVectorCombine::calculatePointerDifference(Value *Ptr0, 2727e8d8bef9SDimitry Andric Value *Ptr1) const 2728bdd1243dSDimitry Andric -> std::optional<int> { 272906c3fb27SDimitry Andric // Try SCEV first. 273006c3fb27SDimitry Andric const SCEV *Scev0 = SE.getSCEV(Ptr0); 273106c3fb27SDimitry Andric const SCEV *Scev1 = SE.getSCEV(Ptr1); 273206c3fb27SDimitry Andric const SCEV *ScevDiff = SE.getMinusSCEV(Scev0, Scev1); 273306c3fb27SDimitry Andric if (auto *Const = dyn_cast<SCEVConstant>(ScevDiff)) { 273406c3fb27SDimitry Andric APInt V = Const->getAPInt(); 273506c3fb27SDimitry Andric if (V.isSignedIntN(8 * sizeof(int))) 273606c3fb27SDimitry Andric return static_cast<int>(V.getSExtValue()); 273706c3fb27SDimitry Andric } 273806c3fb27SDimitry Andric 2739e8d8bef9SDimitry Andric struct Builder : IRBuilder<> { 2740bdd1243dSDimitry Andric Builder(BasicBlock *B) : IRBuilder<>(B->getTerminator()) {} 2741e8d8bef9SDimitry Andric ~Builder() { 2742e8d8bef9SDimitry Andric for (Instruction *I : llvm::reverse(ToErase)) 2743e8d8bef9SDimitry Andric I->eraseFromParent(); 2744e8d8bef9SDimitry Andric } 2745e8d8bef9SDimitry Andric SmallVector<Instruction *, 8> ToErase; 2746e8d8bef9SDimitry Andric }; 2747e8d8bef9SDimitry Andric 2748e8d8bef9SDimitry Andric #define CallBuilder(B, F) \ 2749e8d8bef9SDimitry Andric [&](auto &B_) { \ 2750e8d8bef9SDimitry Andric Value *V = B_.F; \ 2751e8d8bef9SDimitry Andric if (auto *I = dyn_cast<Instruction>(V)) \ 2752e8d8bef9SDimitry Andric B_.ToErase.push_back(I); \ 2753e8d8bef9SDimitry Andric return V; \ 2754e8d8bef9SDimitry Andric }(B) 2755e8d8bef9SDimitry Andric 2756bdd1243dSDimitry Andric auto Simplify = [this](Value *V) { 2757bdd1243dSDimitry Andric if (Value *S = simplify(V)) 2758e8d8bef9SDimitry Andric return S; 2759e8d8bef9SDimitry Andric return V; 2760e8d8bef9SDimitry Andric }; 2761e8d8bef9SDimitry Andric 2762e8d8bef9SDimitry Andric auto StripBitCast = [](Value *V) { 2763e8d8bef9SDimitry Andric while (auto *C = dyn_cast<BitCastInst>(V)) 2764e8d8bef9SDimitry Andric V = C->getOperand(0); 2765e8d8bef9SDimitry Andric return V; 2766e8d8bef9SDimitry Andric }; 2767e8d8bef9SDimitry Andric 2768e8d8bef9SDimitry Andric Ptr0 = StripBitCast(Ptr0); 2769e8d8bef9SDimitry Andric Ptr1 = StripBitCast(Ptr1); 2770e8d8bef9SDimitry Andric if (!isa<GetElementPtrInst>(Ptr0) || !isa<GetElementPtrInst>(Ptr1)) 2771bdd1243dSDimitry Andric return std::nullopt; 2772e8d8bef9SDimitry Andric 2773e8d8bef9SDimitry Andric auto *Gep0 = cast<GetElementPtrInst>(Ptr0); 2774e8d8bef9SDimitry Andric auto *Gep1 = cast<GetElementPtrInst>(Ptr1); 2775e8d8bef9SDimitry Andric if (Gep0->getPointerOperand() != Gep1->getPointerOperand()) 2776bdd1243dSDimitry Andric return std::nullopt; 2777bdd1243dSDimitry Andric if (Gep0->getSourceElementType() != Gep1->getSourceElementType()) 2778bdd1243dSDimitry Andric return std::nullopt; 2779e8d8bef9SDimitry Andric 2780e8d8bef9SDimitry Andric Builder B(Gep0->getParent()); 2781bdd1243dSDimitry Andric int Scale = getSizeOf(Gep0->getSourceElementType(), Alloc); 2782e8d8bef9SDimitry Andric 2783e8d8bef9SDimitry Andric // FIXME: for now only check GEPs with a single index. 2784e8d8bef9SDimitry Andric if (Gep0->getNumOperands() != 2 || Gep1->getNumOperands() != 2) 2785bdd1243dSDimitry Andric return std::nullopt; 2786e8d8bef9SDimitry Andric 2787e8d8bef9SDimitry Andric Value *Idx0 = Gep0->getOperand(1); 2788e8d8bef9SDimitry Andric Value *Idx1 = Gep1->getOperand(1); 2789e8d8bef9SDimitry Andric 2790e8d8bef9SDimitry Andric // First, try to simplify the subtraction directly. 2791e8d8bef9SDimitry Andric if (auto *Diff = dyn_cast<ConstantInt>( 2792e8d8bef9SDimitry Andric Simplify(CallBuilder(B, CreateSub(Idx0, Idx1))))) 2793e8d8bef9SDimitry Andric return Diff->getSExtValue() * Scale; 2794e8d8bef9SDimitry Andric 2795bdd1243dSDimitry Andric KnownBits Known0 = getKnownBits(Idx0, Gep0); 2796bdd1243dSDimitry Andric KnownBits Known1 = getKnownBits(Idx1, Gep1); 2797e8d8bef9SDimitry Andric APInt Unknown = ~(Known0.Zero | Known0.One) | ~(Known1.Zero | Known1.One); 2798349cc55cSDimitry Andric if (Unknown.isAllOnes()) 2799bdd1243dSDimitry Andric return std::nullopt; 2800e8d8bef9SDimitry Andric 2801e8d8bef9SDimitry Andric Value *MaskU = ConstantInt::get(Idx0->getType(), Unknown); 2802e8d8bef9SDimitry Andric Value *AndU0 = Simplify(CallBuilder(B, CreateAnd(Idx0, MaskU))); 2803e8d8bef9SDimitry Andric Value *AndU1 = Simplify(CallBuilder(B, CreateAnd(Idx1, MaskU))); 2804e8d8bef9SDimitry Andric Value *SubU = Simplify(CallBuilder(B, CreateSub(AndU0, AndU1))); 2805e8d8bef9SDimitry Andric int Diff0 = 0; 2806e8d8bef9SDimitry Andric if (auto *C = dyn_cast<ConstantInt>(SubU)) { 2807e8d8bef9SDimitry Andric Diff0 = C->getSExtValue(); 2808e8d8bef9SDimitry Andric } else { 2809bdd1243dSDimitry Andric return std::nullopt; 2810e8d8bef9SDimitry Andric } 2811e8d8bef9SDimitry Andric 2812e8d8bef9SDimitry Andric Value *MaskK = ConstantInt::get(MaskU->getType(), ~Unknown); 2813e8d8bef9SDimitry Andric Value *AndK0 = Simplify(CallBuilder(B, CreateAnd(Idx0, MaskK))); 2814e8d8bef9SDimitry Andric Value *AndK1 = Simplify(CallBuilder(B, CreateAnd(Idx1, MaskK))); 2815e8d8bef9SDimitry Andric Value *SubK = Simplify(CallBuilder(B, CreateSub(AndK0, AndK1))); 2816e8d8bef9SDimitry Andric int Diff1 = 0; 2817e8d8bef9SDimitry Andric if (auto *C = dyn_cast<ConstantInt>(SubK)) { 2818e8d8bef9SDimitry Andric Diff1 = C->getSExtValue(); 2819e8d8bef9SDimitry Andric } else { 2820bdd1243dSDimitry Andric return std::nullopt; 2821e8d8bef9SDimitry Andric } 2822e8d8bef9SDimitry Andric 2823e8d8bef9SDimitry Andric return (Diff0 + Diff1) * Scale; 2824e8d8bef9SDimitry Andric 2825e8d8bef9SDimitry Andric #undef CallBuilder 2826e8d8bef9SDimitry Andric } 2827e8d8bef9SDimitry Andric 2828bdd1243dSDimitry Andric auto HexagonVectorCombine::getNumSignificantBits(const Value *V, 2829bdd1243dSDimitry Andric const Instruction *CtxI) const 2830bdd1243dSDimitry Andric -> unsigned { 2831bdd1243dSDimitry Andric return ComputeMaxSignificantBits(V, DL, /*Depth=*/0, &AC, CtxI, &DT); 2832bdd1243dSDimitry Andric } 2833bdd1243dSDimitry Andric 2834bdd1243dSDimitry Andric auto HexagonVectorCombine::getKnownBits(const Value *V, 2835bdd1243dSDimitry Andric const Instruction *CtxI) const 2836bdd1243dSDimitry Andric -> KnownBits { 283706c3fb27SDimitry Andric return computeKnownBits(V, DL, /*Depth=*/0, &AC, CtxI, &DT); 283806c3fb27SDimitry Andric } 283906c3fb27SDimitry Andric 284006c3fb27SDimitry Andric auto HexagonVectorCombine::isSafeToClone(const Instruction &In) const -> bool { 284106c3fb27SDimitry Andric if (In.mayHaveSideEffects() || In.isAtomic() || In.isVolatile() || 284206c3fb27SDimitry Andric In.isFenceLike() || In.mayReadOrWriteMemory()) { 284306c3fb27SDimitry Andric return false; 284406c3fb27SDimitry Andric } 284506c3fb27SDimitry Andric if (isa<CallBase>(In) || isa<AllocaInst>(In)) 284606c3fb27SDimitry Andric return false; 284706c3fb27SDimitry Andric return true; 2848bdd1243dSDimitry Andric } 2849bdd1243dSDimitry Andric 2850e8d8bef9SDimitry Andric template <typename T> 2851e8d8bef9SDimitry Andric auto HexagonVectorCombine::isSafeToMoveBeforeInBB(const Instruction &In, 2852e8d8bef9SDimitry Andric BasicBlock::const_iterator To, 2853bdd1243dSDimitry Andric const T &IgnoreInsts) const 2854e8d8bef9SDimitry Andric -> bool { 2855bdd1243dSDimitry Andric auto getLocOrNone = 2856bdd1243dSDimitry Andric [this](const Instruction &I) -> std::optional<MemoryLocation> { 2857e8d8bef9SDimitry Andric if (const auto *II = dyn_cast<IntrinsicInst>(&I)) { 2858e8d8bef9SDimitry Andric switch (II->getIntrinsicID()) { 2859e8d8bef9SDimitry Andric case Intrinsic::masked_load: 2860e8d8bef9SDimitry Andric return MemoryLocation::getForArgument(II, 0, TLI); 2861e8d8bef9SDimitry Andric case Intrinsic::masked_store: 2862e8d8bef9SDimitry Andric return MemoryLocation::getForArgument(II, 1, TLI); 2863e8d8bef9SDimitry Andric } 2864e8d8bef9SDimitry Andric } 2865e8d8bef9SDimitry Andric return MemoryLocation::getOrNone(&I); 2866e8d8bef9SDimitry Andric }; 2867e8d8bef9SDimitry Andric 2868e8d8bef9SDimitry Andric // The source and the destination must be in the same basic block. 2869e8d8bef9SDimitry Andric const BasicBlock &Block = *In.getParent(); 2870e8d8bef9SDimitry Andric assert(Block.begin() == To || Block.end() == To || To->getParent() == &Block); 2871e8d8bef9SDimitry Andric // No PHIs. 2872e8d8bef9SDimitry Andric if (isa<PHINode>(In) || (To != Block.end() && isa<PHINode>(*To))) 2873e8d8bef9SDimitry Andric return false; 2874e8d8bef9SDimitry Andric 287581ad6265SDimitry Andric if (!mayHaveNonDefUseDependency(In)) 2876e8d8bef9SDimitry Andric return true; 2877e8d8bef9SDimitry Andric bool MayWrite = In.mayWriteToMemory(); 2878e8d8bef9SDimitry Andric auto MaybeLoc = getLocOrNone(In); 2879e8d8bef9SDimitry Andric 2880e8d8bef9SDimitry Andric auto From = In.getIterator(); 2881e8d8bef9SDimitry Andric if (From == To) 2882e8d8bef9SDimitry Andric return true; 2883e8d8bef9SDimitry Andric bool MoveUp = (To != Block.end() && To->comesBefore(&In)); 2884e8d8bef9SDimitry Andric auto Range = 2885e8d8bef9SDimitry Andric MoveUp ? std::make_pair(To, From) : std::make_pair(std::next(From), To); 2886e8d8bef9SDimitry Andric for (auto It = Range.first; It != Range.second; ++It) { 2887e8d8bef9SDimitry Andric const Instruction &I = *It; 2888bdd1243dSDimitry Andric if (llvm::is_contained(IgnoreInsts, &I)) 2889e8d8bef9SDimitry Andric continue; 2890fe6060f1SDimitry Andric // assume intrinsic can be ignored 2891fe6060f1SDimitry Andric if (auto *II = dyn_cast<IntrinsicInst>(&I)) { 2892fe6060f1SDimitry Andric if (II->getIntrinsicID() == Intrinsic::assume) 2893fe6060f1SDimitry Andric continue; 2894fe6060f1SDimitry Andric } 2895e8d8bef9SDimitry Andric // Parts based on isSafeToMoveBefore from CoveMoverUtils.cpp. 2896e8d8bef9SDimitry Andric if (I.mayThrow()) 2897e8d8bef9SDimitry Andric return false; 2898e8d8bef9SDimitry Andric if (auto *CB = dyn_cast<CallBase>(&I)) { 2899e8d8bef9SDimitry Andric if (!CB->hasFnAttr(Attribute::WillReturn)) 2900e8d8bef9SDimitry Andric return false; 2901e8d8bef9SDimitry Andric if (!CB->hasFnAttr(Attribute::NoSync)) 2902e8d8bef9SDimitry Andric return false; 2903e8d8bef9SDimitry Andric } 2904e8d8bef9SDimitry Andric if (I.mayReadOrWriteMemory()) { 2905e8d8bef9SDimitry Andric auto MaybeLocI = getLocOrNone(I); 2906e8d8bef9SDimitry Andric if (MayWrite || I.mayWriteToMemory()) { 2907e8d8bef9SDimitry Andric if (!MaybeLoc || !MaybeLocI) 2908e8d8bef9SDimitry Andric return false; 2909e8d8bef9SDimitry Andric if (!AA.isNoAlias(*MaybeLoc, *MaybeLocI)) 2910e8d8bef9SDimitry Andric return false; 2911e8d8bef9SDimitry Andric } 2912e8d8bef9SDimitry Andric } 2913e8d8bef9SDimitry Andric } 2914e8d8bef9SDimitry Andric return true; 2915e8d8bef9SDimitry Andric } 2916e8d8bef9SDimitry Andric 2917e8d8bef9SDimitry Andric auto HexagonVectorCombine::isByteVecTy(Type *Ty) const -> bool { 2918e8d8bef9SDimitry Andric if (auto *VecTy = dyn_cast<VectorType>(Ty)) 2919e8d8bef9SDimitry Andric return VecTy->getElementType() == getByteTy(); 2920e8d8bef9SDimitry Andric return false; 2921e8d8bef9SDimitry Andric } 2922e8d8bef9SDimitry Andric 2923bdd1243dSDimitry Andric auto HexagonVectorCombine::getElementRange(IRBuilderBase &Builder, Value *Lo, 2924e8d8bef9SDimitry Andric Value *Hi, int Start, 2925e8d8bef9SDimitry Andric int Length) const -> Value * { 2926bdd1243dSDimitry Andric assert(0 <= Start && size_t(Start + Length) < length(Lo) + length(Hi)); 2927e8d8bef9SDimitry Andric SmallVector<int, 128> SMask(Length); 2928e8d8bef9SDimitry Andric std::iota(SMask.begin(), SMask.end(), Start); 292906c3fb27SDimitry Andric return Builder.CreateShuffleVector(Lo, Hi, SMask, "shf"); 2930e8d8bef9SDimitry Andric } 2931e8d8bef9SDimitry Andric 2932e8d8bef9SDimitry Andric // Pass management. 2933e8d8bef9SDimitry Andric 2934e8d8bef9SDimitry Andric namespace llvm { 2935e8d8bef9SDimitry Andric void initializeHexagonVectorCombineLegacyPass(PassRegistry &); 2936e8d8bef9SDimitry Andric FunctionPass *createHexagonVectorCombineLegacyPass(); 2937e8d8bef9SDimitry Andric } // namespace llvm 2938e8d8bef9SDimitry Andric 2939e8d8bef9SDimitry Andric namespace { 2940e8d8bef9SDimitry Andric class HexagonVectorCombineLegacy : public FunctionPass { 2941e8d8bef9SDimitry Andric public: 2942e8d8bef9SDimitry Andric static char ID; 2943e8d8bef9SDimitry Andric 2944e8d8bef9SDimitry Andric HexagonVectorCombineLegacy() : FunctionPass(ID) {} 2945e8d8bef9SDimitry Andric 2946e8d8bef9SDimitry Andric StringRef getPassName() const override { return "Hexagon Vector Combine"; } 2947e8d8bef9SDimitry Andric 2948e8d8bef9SDimitry Andric void getAnalysisUsage(AnalysisUsage &AU) const override { 2949e8d8bef9SDimitry Andric AU.setPreservesCFG(); 2950e8d8bef9SDimitry Andric AU.addRequired<AAResultsWrapperPass>(); 2951e8d8bef9SDimitry Andric AU.addRequired<AssumptionCacheTracker>(); 2952e8d8bef9SDimitry Andric AU.addRequired<DominatorTreeWrapperPass>(); 295306c3fb27SDimitry Andric AU.addRequired<ScalarEvolutionWrapperPass>(); 2954e8d8bef9SDimitry Andric AU.addRequired<TargetLibraryInfoWrapperPass>(); 2955e8d8bef9SDimitry Andric AU.addRequired<TargetPassConfig>(); 2956e8d8bef9SDimitry Andric FunctionPass::getAnalysisUsage(AU); 2957e8d8bef9SDimitry Andric } 2958e8d8bef9SDimitry Andric 2959e8d8bef9SDimitry Andric bool runOnFunction(Function &F) override { 2960fe6060f1SDimitry Andric if (skipFunction(F)) 2961fe6060f1SDimitry Andric return false; 2962e8d8bef9SDimitry Andric AliasAnalysis &AA = getAnalysis<AAResultsWrapperPass>().getAAResults(); 2963e8d8bef9SDimitry Andric AssumptionCache &AC = 2964e8d8bef9SDimitry Andric getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F); 2965e8d8bef9SDimitry Andric DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 296606c3fb27SDimitry Andric ScalarEvolution &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE(); 2967e8d8bef9SDimitry Andric TargetLibraryInfo &TLI = 2968e8d8bef9SDimitry Andric getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F); 2969e8d8bef9SDimitry Andric auto &TM = getAnalysis<TargetPassConfig>().getTM<HexagonTargetMachine>(); 297006c3fb27SDimitry Andric HexagonVectorCombine HVC(F, AA, AC, DT, SE, TLI, TM); 2971e8d8bef9SDimitry Andric return HVC.run(); 2972e8d8bef9SDimitry Andric } 2973e8d8bef9SDimitry Andric }; 2974e8d8bef9SDimitry Andric } // namespace 2975e8d8bef9SDimitry Andric 2976e8d8bef9SDimitry Andric char HexagonVectorCombineLegacy::ID = 0; 2977e8d8bef9SDimitry Andric 2978e8d8bef9SDimitry Andric INITIALIZE_PASS_BEGIN(HexagonVectorCombineLegacy, DEBUG_TYPE, 2979e8d8bef9SDimitry Andric "Hexagon Vector Combine", false, false) 2980e8d8bef9SDimitry Andric INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass) 2981e8d8bef9SDimitry Andric INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 2982e8d8bef9SDimitry Andric INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 298306c3fb27SDimitry Andric INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass) 2984e8d8bef9SDimitry Andric INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 2985e8d8bef9SDimitry Andric INITIALIZE_PASS_DEPENDENCY(TargetPassConfig) 2986e8d8bef9SDimitry Andric INITIALIZE_PASS_END(HexagonVectorCombineLegacy, DEBUG_TYPE, 2987e8d8bef9SDimitry Andric "Hexagon Vector Combine", false, false) 2988e8d8bef9SDimitry Andric 2989e8d8bef9SDimitry Andric FunctionPass *llvm::createHexagonVectorCombineLegacyPass() { 2990e8d8bef9SDimitry Andric return new HexagonVectorCombineLegacy(); 2991e8d8bef9SDimitry Andric } 2992