xref: /llvm-project/llvm/lib/Target/Hexagon/HexagonVectorCombine.cpp (revision 9422a8d94c0f038b78427f58b31c1200aed7524c)
1 //===-- HexagonVectorCombine.cpp ------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 // HexagonVectorCombine is a utility class implementing a variety of functions
9 // that assist in vector-based optimizations.
10 //
11 // AlignVectors: replace unaligned vector loads and stores with aligned ones.
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/ADT/APInt.h"
15 #include "llvm/ADT/ArrayRef.h"
16 #include "llvm/ADT/DenseMap.h"
17 #include "llvm/ADT/None.h"
18 #include "llvm/ADT/Optional.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/ADT/SmallVector.h"
21 #include "llvm/Analysis/AliasAnalysis.h"
22 #include "llvm/Analysis/AssumptionCache.h"
23 #include "llvm/Analysis/InstSimplifyFolder.h"
24 #include "llvm/Analysis/InstructionSimplify.h"
25 #include "llvm/Analysis/TargetLibraryInfo.h"
26 #include "llvm/Analysis/ValueTracking.h"
27 #include "llvm/Analysis/VectorUtils.h"
28 #include "llvm/CodeGen/TargetPassConfig.h"
29 #include "llvm/CodeGen/ValueTypes.h"
30 #include "llvm/IR/Dominators.h"
31 #include "llvm/IR/IRBuilder.h"
32 #include "llvm/IR/IntrinsicInst.h"
33 #include "llvm/IR/Intrinsics.h"
34 #include "llvm/IR/IntrinsicsHexagon.h"
35 #include "llvm/IR/Metadata.h"
36 #include "llvm/IR/PatternMatch.h"
37 #include "llvm/InitializePasses.h"
38 #include "llvm/Pass.h"
39 #include "llvm/Support/KnownBits.h"
40 #include "llvm/Support/MathExtras.h"
41 #include "llvm/Support/raw_ostream.h"
42 #include "llvm/Target/TargetMachine.h"
43 #include "llvm/Transforms/Utils/Local.h"
44 
45 #include "HexagonSubtarget.h"
46 #include "HexagonTargetMachine.h"
47 
48 #include <algorithm>
49 #include <deque>
50 #include <map>
51 #include <optional>
52 #include <set>
53 #include <utility>
54 #include <vector>
55 
56 #define DEBUG_TYPE "hexagon-vc"
57 
58 using namespace llvm;
59 
60 namespace {
61 class HexagonVectorCombine {
62 public:
63   HexagonVectorCombine(Function &F_, AliasAnalysis &AA_, AssumptionCache &AC_,
64                        DominatorTree &DT_, TargetLibraryInfo &TLI_,
65                        const TargetMachine &TM_)
66       : F(F_), DL(F.getParent()->getDataLayout()), AA(AA_), AC(AC_), DT(DT_),
67         TLI(TLI_),
68         HST(static_cast<const HexagonSubtarget &>(*TM_.getSubtargetImpl(F))) {}
69 
70   bool run();
71 
72   // Common integer type.
73   IntegerType *getIntTy(unsigned Width = 32) const;
74   // Byte type: either scalar (when Length = 0), or vector with given
75   // element count.
76   Type *getByteTy(int ElemCount = 0) const;
77   // Boolean type: either scalar (when Length = 0), or vector with given
78   // element count.
79   Type *getBoolTy(int ElemCount = 0) const;
80   // Create a ConstantInt of type returned by getIntTy with the value Val.
81   ConstantInt *getConstInt(int Val) const;
82   // Get the integer value of V, if it exists.
83   std::optional<APInt> getIntValue(const Value *Val) const;
84   // Is V a constant 0, or a vector of 0s?
85   bool isZero(const Value *Val) const;
86   // Is V an undef value?
87   bool isUndef(const Value *Val) const;
88 
89   // Get HVX vector type with the given element type.
90   VectorType *getHvxTy(Type *ElemTy, bool Pair = false) const;
91 
92   enum SizeKind {
93     Store, // Store size
94     Alloc, // Alloc size
95   };
96   int getSizeOf(const Value *Val, SizeKind Kind = Store) const;
97   int getSizeOf(const Type *Ty, SizeKind Kind = Store) const;
98   int getTypeAlignment(Type *Ty) const;
99   size_t length(Value *Val) const;
100   size_t length(Type *Ty) const;
101 
102   Constant *getNullValue(Type *Ty) const;
103   Constant *getFullValue(Type *Ty) const;
104   Constant *getConstSplat(Type *Ty, int Val) const;
105 
106   Value *simplify(Value *Val) const;
107 
108   Value *insertb(IRBuilderBase &Builder, Value *Dest, Value *Src, int Start,
109                  int Length, int Where) const;
110   Value *vlalignb(IRBuilderBase &Builder, Value *Lo, Value *Hi,
111                   Value *Amt) const;
112   Value *vralignb(IRBuilderBase &Builder, Value *Lo, Value *Hi,
113                   Value *Amt) const;
114   Value *concat(IRBuilderBase &Builder, ArrayRef<Value *> Vecs) const;
115   Value *vresize(IRBuilderBase &Builder, Value *Val, int NewSize,
116                  Value *Pad) const;
117   Value *rescale(IRBuilderBase &Builder, Value *Mask, Type *FromTy,
118                  Type *ToTy) const;
119   Value *vlsb(IRBuilderBase &Builder, Value *Val) const;
120   Value *vbytes(IRBuilderBase &Builder, Value *Val) const;
121   Value *subvector(IRBuilderBase &Builder, Value *Val, unsigned Start,
122                    unsigned Length) const;
123   Value *sublo(IRBuilderBase &Builder, Value *Val) const;
124   Value *subhi(IRBuilderBase &Builder, Value *Val) const;
125   Value *vdeal(IRBuilderBase &Builder, Value *Val0, Value *Val1) const;
126   Value *vshuff(IRBuilderBase &Builder, Value *Val0, Value *Val1) const;
127 
128   Value *createHvxIntrinsic(IRBuilderBase &Builder, Intrinsic::ID IntID,
129                             Type *RetTy, ArrayRef<Value *> Args,
130                             ArrayRef<Type *> ArgTys = None) const;
131   SmallVector<Value *> splitVectorElements(IRBuilderBase &Builder, Value *Vec,
132                                            unsigned ToWidth) const;
133   Value *joinVectorElements(IRBuilderBase &Builder, ArrayRef<Value *> Values,
134                             VectorType *ToType) const;
135 
136   std::optional<int> calculatePointerDifference(Value *Ptr0, Value *Ptr1) const;
137 
138   unsigned getNumSignificantBits(const Value *V,
139                                  const Instruction *CtxI = nullptr) const;
140   KnownBits getKnownBits(const Value *V,
141                          const Instruction *CtxI = nullptr) const;
142 
143   template <typename T = std::vector<Instruction *>>
144   bool isSafeToMoveBeforeInBB(const Instruction &In,
145                               BasicBlock::const_iterator To,
146                               const T &Ignore = {}) const;
147 
148   // This function is only used for assertions at the moment.
149   [[maybe_unused]] bool isByteVecTy(Type *Ty) const;
150 
151   Function &F;
152   const DataLayout &DL;
153   AliasAnalysis &AA;
154   AssumptionCache &AC;
155   DominatorTree &DT;
156   TargetLibraryInfo &TLI;
157   const HexagonSubtarget &HST;
158 
159 private:
160   Value *getElementRange(IRBuilderBase &Builder, Value *Lo, Value *Hi,
161                          int Start, int Length) const;
162 };
163 
164 class AlignVectors {
165 public:
166   AlignVectors(const HexagonVectorCombine &HVC_) : HVC(HVC_) {}
167 
168   bool run();
169 
170 private:
171   using InstList = std::vector<Instruction *>;
172 
173   struct Segment {
174     void *Data;
175     int Start;
176     int Size;
177   };
178 
179   struct AddrInfo {
180     AddrInfo(const AddrInfo &) = default;
181     AddrInfo(const HexagonVectorCombine &HVC, Instruction *I, Value *A, Type *T,
182              Align H)
183         : Inst(I), Addr(A), ValTy(T), HaveAlign(H),
184           NeedAlign(HVC.getTypeAlignment(ValTy)) {}
185     AddrInfo &operator=(const AddrInfo &) = default;
186 
187     // XXX: add Size member?
188     Instruction *Inst;
189     Value *Addr;
190     Type *ValTy;
191     Align HaveAlign;
192     Align NeedAlign;
193     int Offset = 0; // Offset (in bytes) from the first member of the
194                     // containing AddrList.
195   };
196   using AddrList = std::vector<AddrInfo>;
197 
198   struct InstrLess {
199     bool operator()(const Instruction *A, const Instruction *B) const {
200       return A->comesBefore(B);
201     }
202   };
203   using DepList = std::set<Instruction *, InstrLess>;
204 
205   struct MoveGroup {
206     MoveGroup(const AddrInfo &AI, Instruction *B, bool Hvx, bool Load)
207         : Base(B), Main{AI.Inst}, IsHvx(Hvx), IsLoad(Load) {}
208     Instruction *Base; // Base instruction of the parent address group.
209     InstList Main;     // Main group of instructions.
210     InstList Deps;     // List of dependencies.
211     bool IsHvx;        // Is this group of HVX instructions?
212     bool IsLoad;       // Is this a load group?
213   };
214   using MoveList = std::vector<MoveGroup>;
215 
216   struct ByteSpan {
217     struct Segment {
218       // Segment of a Value: 'Len' bytes starting at byte 'Begin'.
219       Segment(Value *Val, int Begin, int Len)
220           : Val(Val), Start(Begin), Size(Len) {}
221       Segment(const Segment &Seg) = default;
222       Segment &operator=(const Segment &Seg) = default;
223       Value *Val; // Value representable as a sequence of bytes.
224       int Start;  // First byte of the value that belongs to the segment.
225       int Size;   // Number of bytes in the segment.
226     };
227 
228     struct Block {
229       Block(Value *Val, int Len, int Pos) : Seg(Val, 0, Len), Pos(Pos) {}
230       Block(Value *Val, int Off, int Len, int Pos)
231           : Seg(Val, Off, Len), Pos(Pos) {}
232       Block(const Block &Blk) = default;
233       Block &operator=(const Block &Blk) = default;
234       Segment Seg; // Value segment.
235       int Pos;     // Position (offset) of the segment in the Block.
236     };
237 
238     int extent() const;
239     ByteSpan section(int Start, int Length) const;
240     ByteSpan &shift(int Offset);
241     SmallVector<Value *, 8> values() const;
242 
243     int size() const { return Blocks.size(); }
244     Block &operator[](int i) { return Blocks[i]; }
245 
246     std::vector<Block> Blocks;
247 
248     using iterator = decltype(Blocks)::iterator;
249     iterator begin() { return Blocks.begin(); }
250     iterator end() { return Blocks.end(); }
251     using const_iterator = decltype(Blocks)::const_iterator;
252     const_iterator begin() const { return Blocks.begin(); }
253     const_iterator end() const { return Blocks.end(); }
254   };
255 
256   Align getAlignFromValue(const Value *V) const;
257   std::optional<MemoryLocation> getLocation(const Instruction &In) const;
258   std::optional<AddrInfo> getAddrInfo(Instruction &In) const;
259   bool isHvx(const AddrInfo &AI) const;
260   // This function is only used for assertions at the moment.
261   [[maybe_unused]] bool isSectorTy(Type *Ty) const;
262 
263   Value *getPayload(Value *Val) const;
264   Value *getMask(Value *Val) const;
265   Value *getPassThrough(Value *Val) const;
266 
267   Value *createAdjustedPointer(IRBuilderBase &Builder, Value *Ptr, Type *ValTy,
268                                int Adjust) const;
269   Value *createAlignedPointer(IRBuilderBase &Builder, Value *Ptr, Type *ValTy,
270                               int Alignment) const;
271   Value *createAlignedLoad(IRBuilderBase &Builder, Type *ValTy, Value *Ptr,
272                            int Alignment, Value *Mask, Value *PassThru) const;
273   Value *createAlignedStore(IRBuilderBase &Builder, Value *Val, Value *Ptr,
274                             int Alignment, Value *Mask) const;
275 
276   bool createAddressGroups();
277   MoveList createLoadGroups(const AddrList &Group) const;
278   MoveList createStoreGroups(const AddrList &Group) const;
279   bool move(const MoveGroup &Move) const;
280   bool realignGroup(const MoveGroup &Move) const;
281 
282   friend raw_ostream &operator<<(raw_ostream &OS, const AddrInfo &AI);
283   friend raw_ostream &operator<<(raw_ostream &OS, const MoveGroup &MG);
284   friend raw_ostream &operator<<(raw_ostream &OS, const ByteSpan &BS);
285 
286   std::map<Instruction *, AddrList> AddrGroups;
287   const HexagonVectorCombine &HVC;
288 };
289 
290 LLVM_ATTRIBUTE_UNUSED
291 raw_ostream &operator<<(raw_ostream &OS, const AlignVectors::AddrInfo &AI) {
292   OS << "Inst: " << AI.Inst << "  " << *AI.Inst << '\n';
293   OS << "Addr: " << *AI.Addr << '\n';
294   OS << "Type: " << *AI.ValTy << '\n';
295   OS << "HaveAlign: " << AI.HaveAlign.value() << '\n';
296   OS << "NeedAlign: " << AI.NeedAlign.value() << '\n';
297   OS << "Offset: " << AI.Offset;
298   return OS;
299 }
300 
301 LLVM_ATTRIBUTE_UNUSED
302 raw_ostream &operator<<(raw_ostream &OS, const AlignVectors::MoveGroup &MG) {
303   OS << "Main\n";
304   for (Instruction *I : MG.Main)
305     OS << "  " << *I << '\n';
306   OS << "Deps\n";
307   for (Instruction *I : MG.Deps)
308     OS << "  " << *I << '\n';
309   return OS;
310 }
311 
312 LLVM_ATTRIBUTE_UNUSED
313 raw_ostream &operator<<(raw_ostream &OS, const AlignVectors::ByteSpan &BS) {
314   OS << "ByteSpan[size=" << BS.size() << ", extent=" << BS.extent() << '\n';
315   for (const AlignVectors::ByteSpan::Block &B : BS) {
316     OS << "  @" << B.Pos << " [" << B.Seg.Start << ',' << B.Seg.Size << "] "
317        << *B.Seg.Val << '\n';
318   }
319   OS << ']';
320   return OS;
321 }
322 
323 class HvxIdioms {
324 public:
325   HvxIdioms(const HexagonVectorCombine &HVC_) : HVC(HVC_) {
326     auto *Int32Ty = HVC.getIntTy(32);
327     HvxI32Ty = HVC.getHvxTy(Int32Ty, /*Pair=*/false);
328     HvxP32Ty = HVC.getHvxTy(Int32Ty, /*Pair=*/true);
329   }
330 
331   bool run();
332 
333 private:
334   struct FxpOp {
335     unsigned Opcode;
336     unsigned Frac; // Number of fraction bits
337     Value *X, *Y;
338     // If present, add 1 << RoundAt before shift:
339     std::optional<unsigned> RoundAt;
340   };
341 
342   // Value + sign
343   // This is to distinguish multiplications: s*s, s*u, u*s, u*u.
344   struct SValue {
345     Value *Val;
346     bool Signed;
347   };
348 
349   std::optional<FxpOp> matchFxpMul(Instruction &In) const;
350   Value *processFxpMul(Instruction &In, const FxpOp &Op) const;
351 
352   Value *processFxpMulChopped(IRBuilderBase &Builder, Instruction &In,
353                               const FxpOp &Op) const;
354   Value *createMulQ15(IRBuilderBase &Builder, Value *X, Value *Y,
355                       bool Rounding) const;
356   Value *createMulQ31(IRBuilderBase &Builder, Value *X, Value *Y,
357                       bool Rounding) const;
358   std::pair<Value *, Value *> createMul32(IRBuilderBase &Builder, SValue X,
359                                           SValue Y) const;
360 
361   VectorType *HvxI32Ty;
362   VectorType *HvxP32Ty;
363   const HexagonVectorCombine &HVC;
364 
365   friend raw_ostream &operator<<(raw_ostream &, const FxpOp &);
366 };
367 
368 [[maybe_unused]] raw_ostream &operator<<(raw_ostream &OS,
369                                          const HvxIdioms::FxpOp &Op) {
370   OS << Instruction::getOpcodeName(Op.Opcode) << '.' << Op.Frac;
371   if (Op.RoundAt.has_value()) {
372     if (Op.Frac != 0 && Op.RoundAt.value() == Op.Frac - 1) {
373       OS << ":rnd";
374     } else {
375       OS << " + 1<<" << Op.RoundAt.value();
376     }
377   }
378   OS << "\n  X:" << *Op.X << "\n  Y:" << *Op.Y;
379   return OS;
380 }
381 
382 } // namespace
383 
384 namespace {
385 
386 template <typename T> T *getIfUnordered(T *MaybeT) {
387   return MaybeT && MaybeT->isUnordered() ? MaybeT : nullptr;
388 }
389 template <typename T> T *isCandidate(Instruction *In) {
390   return dyn_cast<T>(In);
391 }
392 template <> LoadInst *isCandidate<LoadInst>(Instruction *In) {
393   return getIfUnordered(dyn_cast<LoadInst>(In));
394 }
395 template <> StoreInst *isCandidate<StoreInst>(Instruction *In) {
396   return getIfUnordered(dyn_cast<StoreInst>(In));
397 }
398 
399 #if !defined(_MSC_VER) || _MSC_VER >= 1926
400 // VS2017 and some versions of VS2019 have trouble compiling this:
401 // error C2976: 'std::map': too few template arguments
402 // VS 2019 16.x is known to work, except for 16.4/16.5 (MSC_VER 1924/1925)
403 template <typename Pred, typename... Ts>
404 void erase_if(std::map<Ts...> &map, Pred p)
405 #else
406 template <typename Pred, typename T, typename U>
407 void erase_if(std::map<T, U> &map, Pred p)
408 #endif
409 {
410   for (auto i = map.begin(), e = map.end(); i != e;) {
411     if (p(*i))
412       i = map.erase(i);
413     else
414       i = std::next(i);
415   }
416 }
417 
418 // Forward other erase_ifs to the LLVM implementations.
419 template <typename Pred, typename T> void erase_if(T &&container, Pred p) {
420   llvm::erase_if(std::forward<T>(container), p);
421 }
422 
423 } // namespace
424 
425 // --- Begin AlignVectors
426 
427 auto AlignVectors::ByteSpan::extent() const -> int {
428   if (size() == 0)
429     return 0;
430   int Min = Blocks[0].Pos;
431   int Max = Blocks[0].Pos + Blocks[0].Seg.Size;
432   for (int i = 1, e = size(); i != e; ++i) {
433     Min = std::min(Min, Blocks[i].Pos);
434     Max = std::max(Max, Blocks[i].Pos + Blocks[i].Seg.Size);
435   }
436   return Max - Min;
437 }
438 
439 auto AlignVectors::ByteSpan::section(int Start, int Length) const -> ByteSpan {
440   ByteSpan Section;
441   for (const ByteSpan::Block &B : Blocks) {
442     int L = std::max(B.Pos, Start);                       // Left end.
443     int R = std::min(B.Pos + B.Seg.Size, Start + Length); // Right end+1.
444     if (L < R) {
445       // How much to chop off the beginning of the segment:
446       int Off = L > B.Pos ? L - B.Pos : 0;
447       Section.Blocks.emplace_back(B.Seg.Val, B.Seg.Start + Off, R - L, L);
448     }
449   }
450   return Section;
451 }
452 
453 auto AlignVectors::ByteSpan::shift(int Offset) -> ByteSpan & {
454   for (Block &B : Blocks)
455     B.Pos += Offset;
456   return *this;
457 }
458 
459 auto AlignVectors::ByteSpan::values() const -> SmallVector<Value *, 8> {
460   SmallVector<Value *, 8> Values(Blocks.size());
461   for (int i = 0, e = Blocks.size(); i != e; ++i)
462     Values[i] = Blocks[i].Seg.Val;
463   return Values;
464 }
465 
466 auto AlignVectors::getAlignFromValue(const Value *V) const -> Align {
467   const auto *C = dyn_cast<ConstantInt>(V);
468   assert(C && "Alignment must be a compile-time constant integer");
469   return C->getAlignValue();
470 }
471 
472 auto AlignVectors::getAddrInfo(Instruction &In) const
473     -> std::optional<AddrInfo> {
474   if (auto *L = isCandidate<LoadInst>(&In))
475     return AddrInfo(HVC, L, L->getPointerOperand(), L->getType(),
476                     L->getAlign());
477   if (auto *S = isCandidate<StoreInst>(&In))
478     return AddrInfo(HVC, S, S->getPointerOperand(),
479                     S->getValueOperand()->getType(), S->getAlign());
480   if (auto *II = isCandidate<IntrinsicInst>(&In)) {
481     Intrinsic::ID ID = II->getIntrinsicID();
482     switch (ID) {
483     case Intrinsic::masked_load:
484       return AddrInfo(HVC, II, II->getArgOperand(0), II->getType(),
485                       getAlignFromValue(II->getArgOperand(1)));
486     case Intrinsic::masked_store:
487       return AddrInfo(HVC, II, II->getArgOperand(1),
488                       II->getArgOperand(0)->getType(),
489                       getAlignFromValue(II->getArgOperand(2)));
490     }
491   }
492   return std::nullopt;
493 }
494 
495 auto AlignVectors::isHvx(const AddrInfo &AI) const -> bool {
496   return HVC.HST.isTypeForHVX(AI.ValTy);
497 }
498 
499 auto AlignVectors::getPayload(Value *Val) const -> Value * {
500   if (auto *In = dyn_cast<Instruction>(Val)) {
501     Intrinsic::ID ID = 0;
502     if (auto *II = dyn_cast<IntrinsicInst>(In))
503       ID = II->getIntrinsicID();
504     if (isa<StoreInst>(In) || ID == Intrinsic::masked_store)
505       return In->getOperand(0);
506   }
507   return Val;
508 }
509 
510 auto AlignVectors::getMask(Value *Val) const -> Value * {
511   if (auto *II = dyn_cast<IntrinsicInst>(Val)) {
512     switch (II->getIntrinsicID()) {
513     case Intrinsic::masked_load:
514       return II->getArgOperand(2);
515     case Intrinsic::masked_store:
516       return II->getArgOperand(3);
517     }
518   }
519 
520   Type *ValTy = getPayload(Val)->getType();
521   if (auto *VecTy = dyn_cast<VectorType>(ValTy))
522     return HVC.getFullValue(HVC.getBoolTy(HVC.length(VecTy)));
523   return HVC.getFullValue(HVC.getBoolTy());
524 }
525 
526 auto AlignVectors::getPassThrough(Value *Val) const -> Value * {
527   if (auto *II = dyn_cast<IntrinsicInst>(Val)) {
528     if (II->getIntrinsicID() == Intrinsic::masked_load)
529       return II->getArgOperand(3);
530   }
531   return UndefValue::get(getPayload(Val)->getType());
532 }
533 
534 auto AlignVectors::createAdjustedPointer(IRBuilderBase &Builder, Value *Ptr,
535                                          Type *ValTy, int Adjust) const
536     -> Value * {
537   // The adjustment is in bytes, but if it's a multiple of the type size,
538   // we don't need to do pointer casts.
539   auto *PtrTy = cast<PointerType>(Ptr->getType());
540   if (!PtrTy->isOpaque()) {
541     Type *ElemTy = PtrTy->getNonOpaquePointerElementType();
542     int ElemSize = HVC.getSizeOf(ElemTy, HVC.Alloc);
543     if (Adjust % ElemSize == 0 && Adjust != 0) {
544       Value *Tmp0 =
545           Builder.CreateGEP(ElemTy, Ptr, HVC.getConstInt(Adjust / ElemSize));
546       return Builder.CreatePointerCast(Tmp0, ValTy->getPointerTo());
547     }
548   }
549 
550   PointerType *CharPtrTy = Type::getInt8PtrTy(HVC.F.getContext());
551   Value *Tmp0 = Builder.CreatePointerCast(Ptr, CharPtrTy);
552   Value *Tmp1 = Builder.CreateGEP(Type::getInt8Ty(HVC.F.getContext()), Tmp0,
553                                   HVC.getConstInt(Adjust));
554   return Builder.CreatePointerCast(Tmp1, ValTy->getPointerTo());
555 }
556 
557 auto AlignVectors::createAlignedPointer(IRBuilderBase &Builder, Value *Ptr,
558                                         Type *ValTy, int Alignment) const
559     -> Value * {
560   Value *AsInt = Builder.CreatePtrToInt(Ptr, HVC.getIntTy());
561   Value *Mask = HVC.getConstInt(-Alignment);
562   Value *And = Builder.CreateAnd(AsInt, Mask);
563   return Builder.CreateIntToPtr(And, ValTy->getPointerTo());
564 }
565 
566 auto AlignVectors::createAlignedLoad(IRBuilderBase &Builder, Type *ValTy,
567                                      Value *Ptr, int Alignment, Value *Mask,
568                                      Value *PassThru) const -> Value * {
569   assert(!HVC.isUndef(Mask)); // Should this be allowed?
570   if (HVC.isZero(Mask))
571     return PassThru;
572   if (Mask == ConstantInt::getTrue(Mask->getType()))
573     return Builder.CreateAlignedLoad(ValTy, Ptr, Align(Alignment));
574   return Builder.CreateMaskedLoad(ValTy, Ptr, Align(Alignment), Mask, PassThru);
575 }
576 
577 auto AlignVectors::createAlignedStore(IRBuilderBase &Builder, Value *Val,
578                                       Value *Ptr, int Alignment,
579                                       Value *Mask) const -> Value * {
580   if (HVC.isZero(Mask) || HVC.isUndef(Val) || HVC.isUndef(Mask))
581     return UndefValue::get(Val->getType());
582   if (Mask == ConstantInt::getTrue(Mask->getType()))
583     return Builder.CreateAlignedStore(Val, Ptr, Align(Alignment));
584   return Builder.CreateMaskedStore(Val, Ptr, Align(Alignment), Mask);
585 }
586 
587 auto AlignVectors::createAddressGroups() -> bool {
588   // An address group created here may contain instructions spanning
589   // multiple basic blocks.
590   AddrList WorkStack;
591 
592   auto findBaseAndOffset = [&](AddrInfo &AI) -> std::pair<Instruction *, int> {
593     for (AddrInfo &W : WorkStack) {
594       if (auto D = HVC.calculatePointerDifference(AI.Addr, W.Addr))
595         return std::make_pair(W.Inst, *D);
596     }
597     return std::make_pair(nullptr, 0);
598   };
599 
600   auto traverseBlock = [&](DomTreeNode *DomN, auto Visit) -> void {
601     BasicBlock &Block = *DomN->getBlock();
602     for (Instruction &I : Block) {
603       auto AI = this->getAddrInfo(I); // Use this-> for gcc6.
604       if (!AI)
605         continue;
606       auto F = findBaseAndOffset(*AI);
607       Instruction *GroupInst;
608       if (Instruction *BI = F.first) {
609         AI->Offset = F.second;
610         GroupInst = BI;
611       } else {
612         WorkStack.push_back(*AI);
613         GroupInst = AI->Inst;
614       }
615       AddrGroups[GroupInst].push_back(*AI);
616     }
617 
618     for (DomTreeNode *C : DomN->children())
619       Visit(C, Visit);
620 
621     while (!WorkStack.empty() && WorkStack.back().Inst->getParent() == &Block)
622       WorkStack.pop_back();
623   };
624 
625   traverseBlock(HVC.DT.getRootNode(), traverseBlock);
626   assert(WorkStack.empty());
627 
628   // AddrGroups are formed.
629 
630   // Remove groups of size 1.
631   erase_if(AddrGroups, [](auto &G) { return G.second.size() == 1; });
632   // Remove groups that don't use HVX types.
633   erase_if(AddrGroups, [&](auto &G) {
634     return llvm::none_of(
635         G.second, [&](auto &I) { return HVC.HST.isTypeForHVX(I.ValTy); });
636   });
637 
638   return !AddrGroups.empty();
639 }
640 
641 auto AlignVectors::createLoadGroups(const AddrList &Group) const -> MoveList {
642   // Form load groups.
643   // To avoid complications with moving code across basic blocks, only form
644   // groups that are contained within a single basic block.
645 
646   auto getUpwardDeps = [](Instruction *In, Instruction *Base) {
647     BasicBlock *Parent = Base->getParent();
648     assert(In->getParent() == Parent &&
649            "Base and In should be in the same block");
650     assert(Base->comesBefore(In) && "Base should come before In");
651 
652     DepList Deps;
653     std::deque<Instruction *> WorkQ = {In};
654     while (!WorkQ.empty()) {
655       Instruction *D = WorkQ.front();
656       WorkQ.pop_front();
657       Deps.insert(D);
658       for (Value *Op : D->operands()) {
659         if (auto *I = dyn_cast<Instruction>(Op)) {
660           if (I->getParent() == Parent && Base->comesBefore(I))
661             WorkQ.push_back(I);
662         }
663       }
664     }
665     return Deps;
666   };
667 
668   auto tryAddTo = [&](const AddrInfo &Info, MoveGroup &Move) {
669     assert(!Move.Main.empty() && "Move group should have non-empty Main");
670     // Don't mix HVX and non-HVX instructions.
671     if (Move.IsHvx != isHvx(Info))
672       return false;
673     // Leading instruction in the load group.
674     Instruction *Base = Move.Main.front();
675     if (Base->getParent() != Info.Inst->getParent())
676       return false;
677 
678     auto isSafeToMoveToBase = [&](const Instruction *I) {
679       return HVC.isSafeToMoveBeforeInBB(*I, Base->getIterator());
680     };
681     DepList Deps = getUpwardDeps(Info.Inst, Base);
682     if (!llvm::all_of(Deps, isSafeToMoveToBase))
683       return false;
684 
685     // The dependencies will be moved together with the load, so make sure
686     // that none of them could be moved independently in another group.
687     Deps.erase(Info.Inst);
688     auto inAddrMap = [&](Instruction *I) { return AddrGroups.count(I) > 0; };
689     if (llvm::any_of(Deps, inAddrMap))
690       return false;
691     Move.Main.push_back(Info.Inst);
692     llvm::append_range(Move.Deps, Deps);
693     return true;
694   };
695 
696   MoveList LoadGroups;
697 
698   for (const AddrInfo &Info : Group) {
699     if (!Info.Inst->mayReadFromMemory())
700       continue;
701     if (LoadGroups.empty() || !tryAddTo(Info, LoadGroups.back()))
702       LoadGroups.emplace_back(Info, Group.front().Inst, isHvx(Info), true);
703   }
704 
705   // Erase singleton groups.
706   erase_if(LoadGroups, [](const MoveGroup &G) { return G.Main.size() <= 1; });
707   return LoadGroups;
708 }
709 
710 auto AlignVectors::createStoreGroups(const AddrList &Group) const -> MoveList {
711   // Form store groups.
712   // To avoid complications with moving code across basic blocks, only form
713   // groups that are contained within a single basic block.
714 
715   auto tryAddTo = [&](const AddrInfo &Info, MoveGroup &Move) {
716     assert(!Move.Main.empty() && "Move group should have non-empty Main");
717     // For stores with return values we'd have to collect downward depenencies.
718     // There are no such stores that we handle at the moment, so omit that.
719     assert(Info.Inst->getType()->isVoidTy() &&
720            "Not handling stores with return values");
721     // Don't mix HVX and non-HVX instructions.
722     if (Move.IsHvx != isHvx(Info))
723       return false;
724     // For stores we need to be careful whether it's safe to move them.
725     // Stores that are otherwise safe to move together may not appear safe
726     // to move over one another (i.e. isSafeToMoveBefore may return false).
727     Instruction *Base = Move.Main.front();
728     if (Base->getParent() != Info.Inst->getParent())
729       return false;
730     if (!HVC.isSafeToMoveBeforeInBB(*Info.Inst, Base->getIterator(), Move.Main))
731       return false;
732     Move.Main.push_back(Info.Inst);
733     return true;
734   };
735 
736   MoveList StoreGroups;
737 
738   for (auto I = Group.rbegin(), E = Group.rend(); I != E; ++I) {
739     const AddrInfo &Info = *I;
740     if (!Info.Inst->mayWriteToMemory())
741       continue;
742     if (StoreGroups.empty() || !tryAddTo(Info, StoreGroups.back()))
743       StoreGroups.emplace_back(Info, Group.front().Inst, isHvx(Info), false);
744   }
745 
746   // Erase singleton groups.
747   erase_if(StoreGroups, [](const MoveGroup &G) { return G.Main.size() <= 1; });
748   return StoreGroups;
749 }
750 
751 auto AlignVectors::move(const MoveGroup &Move) const -> bool {
752   assert(!Move.Main.empty() && "Move group should have non-empty Main");
753   Instruction *Where = Move.Main.front();
754 
755   if (Move.IsLoad) {
756     // Move all deps to before Where, keeping order.
757     for (Instruction *D : Move.Deps)
758       D->moveBefore(Where);
759     // Move all main instructions to after Where, keeping order.
760     ArrayRef<Instruction *> Main(Move.Main);
761     for (Instruction *M : Main.drop_front(1)) {
762       M->moveAfter(Where);
763       Where = M;
764     }
765   } else {
766     // NOTE: Deps are empty for "store" groups. If they need to be
767     // non-empty, decide on the order.
768     assert(Move.Deps.empty());
769     // Move all main instructions to before Where, inverting order.
770     ArrayRef<Instruction *> Main(Move.Main);
771     for (Instruction *M : Main.drop_front(1)) {
772       M->moveBefore(Where);
773       Where = M;
774     }
775   }
776 
777   return Move.Main.size() + Move.Deps.size() > 1;
778 }
779 
780 auto AlignVectors::realignGroup(const MoveGroup &Move) const -> bool {
781   // TODO: Needs support for masked loads/stores of "scalar" vectors.
782   if (!Move.IsHvx)
783     return false;
784 
785   // Return the element with the maximum alignment from Range,
786   // where GetValue obtains the value to compare from an element.
787   auto getMaxOf = [](auto Range, auto GetValue) {
788     return *std::max_element(
789         Range.begin(), Range.end(),
790         [&GetValue](auto &A, auto &B) { return GetValue(A) < GetValue(B); });
791   };
792 
793   const AddrList &BaseInfos = AddrGroups.at(Move.Base);
794 
795   // Conceptually, there is a vector of N bytes covering the addresses
796   // starting from the minimum offset (i.e. Base.Addr+Start). This vector
797   // represents a contiguous memory region that spans all accessed memory
798   // locations.
799   // The correspondence between loaded or stored values will be expressed
800   // in terms of this vector. For example, the 0th element of the vector
801   // from the Base address info will start at byte Start from the beginning
802   // of this conceptual vector.
803   //
804   // This vector will be loaded/stored starting at the nearest down-aligned
805   // address and the amount od the down-alignment will be AlignVal:
806   //   valign(load_vector(align_down(Base+Start)), AlignVal)
807 
808   std::set<Instruction *> TestSet(Move.Main.begin(), Move.Main.end());
809   AddrList MoveInfos;
810   llvm::copy_if(
811       BaseInfos, std::back_inserter(MoveInfos),
812       [&TestSet](const AddrInfo &AI) { return TestSet.count(AI.Inst); });
813 
814   // Maximum alignment present in the whole address group.
815   const AddrInfo &WithMaxAlign =
816       getMaxOf(MoveInfos, [](const AddrInfo &AI) { return AI.HaveAlign; });
817   Align MaxGiven = WithMaxAlign.HaveAlign;
818 
819   // Minimum alignment present in the move address group.
820   const AddrInfo &WithMinOffset =
821       getMaxOf(MoveInfos, [](const AddrInfo &AI) { return -AI.Offset; });
822 
823   const AddrInfo &WithMaxNeeded =
824       getMaxOf(MoveInfos, [](const AddrInfo &AI) { return AI.NeedAlign; });
825   Align MinNeeded = WithMaxNeeded.NeedAlign;
826 
827   // Set the builder at the top instruction in the move group.
828   Instruction *TopIn = Move.IsLoad ? Move.Main.front() : Move.Main.back();
829   IRBuilder<> Builder(TopIn);
830   Value *AlignAddr = nullptr; // Actual aligned address.
831   Value *AlignVal = nullptr;  // Right-shift amount (for valign).
832 
833   if (MinNeeded <= MaxGiven) {
834     int Start = WithMinOffset.Offset;
835     int OffAtMax = WithMaxAlign.Offset;
836     // Shift the offset of the maximally aligned instruction (OffAtMax)
837     // back by just enough multiples of the required alignment to cover the
838     // distance from Start to OffAtMax.
839     // Calculate the address adjustment amount based on the address with the
840     // maximum alignment. This is to allow a simple gep instruction instead
841     // of potential bitcasts to i8*.
842     int Adjust = -alignTo(OffAtMax - Start, MinNeeded.value());
843     AlignAddr = createAdjustedPointer(Builder, WithMaxAlign.Addr,
844                                       WithMaxAlign.ValTy, Adjust);
845     int Diff = Start - (OffAtMax + Adjust);
846     AlignVal = HVC.getConstInt(Diff);
847     assert(Diff >= 0);
848     assert(static_cast<decltype(MinNeeded.value())>(Diff) < MinNeeded.value());
849   } else {
850     // WithMinOffset is the lowest address in the group,
851     //   WithMinOffset.Addr = Base+Start.
852     // Align instructions for both HVX (V6_valign) and scalar (S2_valignrb)
853     // mask off unnecessary bits, so it's ok to just the original pointer as
854     // the alignment amount.
855     // Do an explicit down-alignment of the address to avoid creating an
856     // aligned instruction with an address that is not really aligned.
857     AlignAddr = createAlignedPointer(Builder, WithMinOffset.Addr,
858                                      WithMinOffset.ValTy, MinNeeded.value());
859     AlignVal = Builder.CreatePtrToInt(WithMinOffset.Addr, HVC.getIntTy());
860   }
861 
862   ByteSpan VSpan;
863   for (const AddrInfo &AI : MoveInfos) {
864     VSpan.Blocks.emplace_back(AI.Inst, HVC.getSizeOf(AI.ValTy),
865                               AI.Offset - WithMinOffset.Offset);
866   }
867 
868   // The aligned loads/stores will use blocks that are either scalars,
869   // or HVX vectors. Let "sector" be the unified term for such a block.
870   // blend(scalar, vector) -> sector...
871   int ScLen = Move.IsHvx ? HVC.HST.getVectorLength()
872                          : std::max<int>(MinNeeded.value(), 4);
873   assert(!Move.IsHvx || ScLen == 64 || ScLen == 128);
874   assert(Move.IsHvx || ScLen == 4 || ScLen == 8);
875 
876   Type *SecTy = HVC.getByteTy(ScLen);
877   int NumSectors = (VSpan.extent() + ScLen - 1) / ScLen;
878   bool DoAlign = !HVC.isZero(AlignVal);
879 
880   if (Move.IsLoad) {
881     ByteSpan ASpan;
882     auto *True = HVC.getFullValue(HVC.getBoolTy(ScLen));
883     auto *Undef = UndefValue::get(SecTy);
884 
885     for (int i = 0; i != NumSectors + DoAlign; ++i) {
886       Value *Ptr = createAdjustedPointer(Builder, AlignAddr, SecTy, i * ScLen);
887       // FIXME: generate a predicated load?
888       Value *Load = createAlignedLoad(Builder, SecTy, Ptr, ScLen, True, Undef);
889       // If vector shifting is potentially needed, accumulate metadata
890       // from source sections of twice the load width.
891       int Start = (i - DoAlign) * ScLen;
892       int Width = (1 + DoAlign) * ScLen;
893       propagateMetadata(cast<Instruction>(Load),
894                         VSpan.section(Start, Width).values());
895       ASpan.Blocks.emplace_back(Load, ScLen, i * ScLen);
896     }
897 
898     if (DoAlign) {
899       for (int j = 0; j != NumSectors; ++j) {
900         assert(isSectorTy(ASpan[j].Seg.Val->getType()));
901         ASpan[j].Seg.Val = HVC.vralignb(Builder, ASpan[j].Seg.Val,
902                                         ASpan[j + 1].Seg.Val, AlignVal);
903       }
904     }
905 
906     for (ByteSpan::Block &B : VSpan) {
907       ByteSpan ASection = ASpan.section(B.Pos, B.Seg.Size).shift(-B.Pos);
908       Value *Accum = UndefValue::get(HVC.getByteTy(B.Seg.Size));
909       for (ByteSpan::Block &S : ASection) {
910         Value *Pay = HVC.vbytes(Builder, getPayload(S.Seg.Val));
911         Accum =
912             HVC.insertb(Builder, Accum, Pay, S.Seg.Start, S.Seg.Size, S.Pos);
913       }
914       // Instead of casting everything to bytes for the vselect, cast to the
915       // original value type. This will avoid complications with casting masks.
916       // For example, in cases when the original mask applied to i32, it could
917       // be converted to a mask applicable to i8 via pred_typecast intrinsic,
918       // but if the mask is not exactly of HVX length, extra handling would be
919       // needed to make it work.
920       Type *ValTy = getPayload(B.Seg.Val)->getType();
921       Value *Cast = Builder.CreateBitCast(Accum, ValTy);
922       Value *Sel = Builder.CreateSelect(getMask(B.Seg.Val), Cast,
923                                         getPassThrough(B.Seg.Val));
924       B.Seg.Val->replaceAllUsesWith(Sel);
925     }
926   } else {
927     // Stores.
928     ByteSpan ASpanV, ASpanM;
929 
930     // Return a vector value corresponding to the input value Val:
931     // either <1 x Val> for scalar Val, or Val itself for vector Val.
932     auto MakeVec = [](IRBuilderBase &Builder, Value *Val) -> Value * {
933       Type *Ty = Val->getType();
934       if (Ty->isVectorTy())
935         return Val;
936       auto *VecTy = VectorType::get(Ty, 1, /*Scalable=*/false);
937       return Builder.CreateBitCast(Val, VecTy);
938     };
939 
940     // Create an extra "undef" sector at the beginning and at the end.
941     // They will be used as the left/right filler in the vlalign step.
942     for (int i = (DoAlign ? -1 : 0); i != NumSectors + DoAlign; ++i) {
943       // For stores, the size of each section is an aligned vector length.
944       // Adjust the store offsets relative to the section start offset.
945       ByteSpan VSection = VSpan.section(i * ScLen, ScLen).shift(-i * ScLen);
946       Value *AccumV = UndefValue::get(SecTy);
947       Value *AccumM = HVC.getNullValue(SecTy);
948       for (ByteSpan::Block &S : VSection) {
949         Value *Pay = getPayload(S.Seg.Val);
950         Value *Mask = HVC.rescale(Builder, MakeVec(Builder, getMask(S.Seg.Val)),
951                                   Pay->getType(), HVC.getByteTy());
952         AccumM = HVC.insertb(Builder, AccumM, HVC.vbytes(Builder, Mask),
953                              S.Seg.Start, S.Seg.Size, S.Pos);
954         AccumV = HVC.insertb(Builder, AccumV, HVC.vbytes(Builder, Pay),
955                              S.Seg.Start, S.Seg.Size, S.Pos);
956       }
957       ASpanV.Blocks.emplace_back(AccumV, ScLen, i * ScLen);
958       ASpanM.Blocks.emplace_back(AccumM, ScLen, i * ScLen);
959     }
960 
961     // vlalign
962     if (DoAlign) {
963       for (int j = 1; j != NumSectors + 2; ++j) {
964         Value *PrevV = ASpanV[j - 1].Seg.Val, *ThisV = ASpanV[j].Seg.Val;
965         Value *PrevM = ASpanM[j - 1].Seg.Val, *ThisM = ASpanM[j].Seg.Val;
966         assert(isSectorTy(PrevV->getType()) && isSectorTy(PrevM->getType()));
967         ASpanV[j - 1].Seg.Val = HVC.vlalignb(Builder, PrevV, ThisV, AlignVal);
968         ASpanM[j - 1].Seg.Val = HVC.vlalignb(Builder, PrevM, ThisM, AlignVal);
969       }
970     }
971 
972     for (int i = 0; i != NumSectors + DoAlign; ++i) {
973       Value *Ptr = createAdjustedPointer(Builder, AlignAddr, SecTy, i * ScLen);
974       Value *Val = ASpanV[i].Seg.Val;
975       Value *Mask = ASpanM[i].Seg.Val; // bytes
976       if (!HVC.isUndef(Val) && !HVC.isZero(Mask)) {
977         Value *Store = createAlignedStore(Builder, Val, Ptr, ScLen,
978                                           HVC.vlsb(Builder, Mask));
979         // If vector shifting is potentially needed, accumulate metadata
980         // from source sections of twice the store width.
981         int Start = (i - DoAlign) * ScLen;
982         int Width = (1 + DoAlign) * ScLen;
983         propagateMetadata(cast<Instruction>(Store),
984                           VSpan.section(Start, Width).values());
985       }
986     }
987   }
988 
989   for (auto *Inst : Move.Main)
990     Inst->eraseFromParent();
991 
992   return true;
993 }
994 
995 auto AlignVectors::isSectorTy(Type *Ty) const -> bool {
996   if (!HVC.isByteVecTy(Ty))
997     return false;
998   int Size = HVC.getSizeOf(Ty);
999   if (HVC.HST.isTypeForHVX(Ty))
1000     return Size == static_cast<int>(HVC.HST.getVectorLength());
1001   return Size == 4 || Size == 8;
1002 }
1003 
1004 auto AlignVectors::run() -> bool {
1005   if (!createAddressGroups())
1006     return false;
1007 
1008   bool Changed = false;
1009   MoveList LoadGroups, StoreGroups;
1010 
1011   for (auto &G : AddrGroups) {
1012     llvm::append_range(LoadGroups, createLoadGroups(G.second));
1013     llvm::append_range(StoreGroups, createStoreGroups(G.second));
1014   }
1015 
1016   for (auto &M : LoadGroups)
1017     Changed |= move(M);
1018   for (auto &M : StoreGroups)
1019     Changed |= move(M);
1020 
1021   for (auto &M : LoadGroups)
1022     Changed |= realignGroup(M);
1023   for (auto &M : StoreGroups)
1024     Changed |= realignGroup(M);
1025 
1026   return Changed;
1027 }
1028 
1029 // --- End AlignVectors
1030 
1031 // --- Begin HvxIdioms
1032 
1033 // Match
1034 //   (X * Y) [>> N], or
1035 //   ((X * Y) + (1 << N-1)) >> N
1036 auto HvxIdioms::matchFxpMul(Instruction &In) const -> std::optional<FxpOp> {
1037   using namespace PatternMatch;
1038   auto *Ty = In.getType();
1039 
1040   if (!Ty->isVectorTy() || !Ty->getScalarType()->isIntegerTy())
1041     return std::nullopt;
1042 
1043   unsigned Width = cast<IntegerType>(Ty->getScalarType())->getBitWidth();
1044 
1045   FxpOp Op;
1046   Value *Exp = &In;
1047 
1048   // Fixed-point multiplication is always shifted right (except when the
1049   // fraction is 0 bits).
1050   auto m_Shr = [](auto &&V, auto &&S) {
1051     return m_CombineOr(m_LShr(V, S), m_AShr(V, S));
1052   };
1053 
1054   const APInt *Qn = nullptr;
1055   if (Value * T; match(Exp, m_Shr(m_Value(T), m_APInt(Qn)))) {
1056     Op.Frac = Qn->getZExtValue();
1057     Exp = T;
1058   } else {
1059     Op.Frac = 0;
1060   }
1061 
1062   if (Op.Frac > Width)
1063     return std::nullopt;
1064 
1065   // Check if there is rounding added.
1066   const APInt *C = nullptr;
1067   if (Value * T; Op.Frac > 0 && match(Exp, m_Add(m_Value(T), m_APInt(C)))) {
1068     unsigned CV = C->getZExtValue();
1069     if (CV != 0 && !isPowerOf2_32(CV))
1070       return std::nullopt;
1071     if (CV != 0)
1072       Op.RoundAt = Log2_32(CV);
1073     Exp = T;
1074   }
1075 
1076   // Check if the rest is a multiplication.
1077   if (match(Exp, m_Mul(m_Value(Op.X), m_Value(Op.Y)))) {
1078     Op.Opcode = Instruction::Mul;
1079     return Op;
1080   }
1081 
1082   return std::nullopt;
1083 }
1084 
1085 auto HvxIdioms::processFxpMul(Instruction &In, const FxpOp &Op) const
1086     -> Value * {
1087   assert(Op.X->getType() == Op.Y->getType());
1088 
1089   auto *VecTy = cast<VectorType>(Op.X->getType());
1090   auto *ElemTy = cast<IntegerType>(VecTy->getElementType());
1091   unsigned ElemWidth = ElemTy->getBitWidth();
1092   if (ElemWidth < 8 || !isPowerOf2_32(ElemWidth))
1093     return nullptr;
1094 
1095   unsigned VecLen = HVC.length(VecTy);
1096   unsigned HvxLen = (8 * HVC.HST.getVectorLength()) / std::min(ElemWidth, 32u);
1097   if (VecLen % HvxLen != 0)
1098     return nullptr;
1099 
1100   // FIXME: handle 8-bit multiplications
1101   if (ElemWidth < 16)
1102     return nullptr;
1103 
1104   SmallVector<Value *> Results;
1105   FxpOp ChopOp;
1106   ChopOp.Opcode = Op.Opcode;
1107   ChopOp.Frac = Op.Frac;
1108   ChopOp.RoundAt = Op.RoundAt;
1109 
1110   IRBuilder<InstSimplifyFolder> Builder(In.getParent(), In.getIterator(),
1111                                         InstSimplifyFolder(HVC.DL));
1112 
1113   for (unsigned V = 0; V != VecLen / HvxLen; ++V) {
1114     ChopOp.X = HVC.subvector(Builder, Op.X, V * HvxLen, HvxLen);
1115     ChopOp.Y = HVC.subvector(Builder, Op.Y, V * HvxLen, HvxLen);
1116     Results.push_back(processFxpMulChopped(Builder, In, ChopOp));
1117     if (Results.back() == nullptr)
1118       break;
1119   }
1120 
1121   if (Results.back() == nullptr) {
1122     // FIXME: clean up leftover instructions
1123     return nullptr;
1124   }
1125 
1126   return HVC.concat(Builder, Results);
1127 }
1128 
1129 auto HvxIdioms::processFxpMulChopped(IRBuilderBase &Builder, Instruction &In,
1130                                      const FxpOp &Op) const -> Value * {
1131   // FIXME: make this more elegant
1132   struct TempValues {
1133     void insert(Value *V) { //
1134       Values.push_back(V);
1135     }
1136     void insert(ArrayRef<Value *> Vs) {
1137       Values.insert(Values.end(), Vs.begin(), Vs.end());
1138     }
1139     void clear() { //
1140       Values.clear();
1141     }
1142     ~TempValues() {
1143       for (Value *V : llvm::reverse(Values)) {
1144         if (auto *In = dyn_cast<Instruction>(V))
1145           In->eraseFromParent();
1146       }
1147     }
1148     SmallVector<Value *> Values;
1149   };
1150   TempValues DeleteOnFailure;
1151 
1152   // TODO: Make it general.
1153   // if (Op.Frac != 15 && Op.Frac != 31)
1154   //  return nullptr;
1155 
1156   enum Signedness { Positive, Signed, Unsigned };
1157   auto getNumSignificantBits =
1158       [this, &In](Value *V) -> std::pair<unsigned, Signedness> {
1159     unsigned Bits = HVC.getNumSignificantBits(V, &In);
1160     // The significant bits are calculated including the sign bit. This may
1161     // add an extra bit for zero-extended values, e.g. (zext i32 to i64) may
1162     // result in 33 significant bits. To avoid extra words, skip the extra
1163     // sign bit, but keep information that the value is to be treated as
1164     // unsigned.
1165     KnownBits Known = HVC.getKnownBits(V, &In);
1166     Signedness Sign = Signed;
1167     if (Bits > 1 && isPowerOf2_32(Bits - 1)) {
1168       if (Known.Zero.ashr(Bits - 1).isAllOnes()) {
1169         Sign = Unsigned;
1170         Bits--;
1171       }
1172     }
1173     // If the top bit of the nearest power-of-2 is zero, this value is
1174     // positive. It could be treated as either signed or unsigned.
1175     if (unsigned Pow2 = PowerOf2Ceil(Bits); Pow2 != Bits) {
1176       if (Known.Zero.ashr(Pow2 - 1).isAllOnes())
1177         Sign = Positive;
1178     }
1179     return {Bits, Sign};
1180   };
1181 
1182   auto *OrigTy = dyn_cast<VectorType>(Op.X->getType());
1183   if (OrigTy == nullptr)
1184     return nullptr;
1185 
1186   auto [BitsX, SignX] = getNumSignificantBits(Op.X);
1187   auto [BitsY, SignY] = getNumSignificantBits(Op.Y);
1188   unsigned Width = PowerOf2Ceil(std::max(BitsX, BitsY));
1189 
1190   if (!Op.RoundAt || *Op.RoundAt == Op.Frac - 1) {
1191     bool Rounding = Op.RoundAt.has_value();
1192     // The fixed-point intrinsics do signed multiplication.
1193     if (Width == Op.Frac + 1 && SignX != Unsigned && SignY != Unsigned) {
1194       auto *TruncTy = VectorType::get(HVC.getIntTy(Width), OrigTy);
1195       Value *TruncX = Builder.CreateTrunc(Op.X, TruncTy);
1196       Value *TruncY = Builder.CreateTrunc(Op.Y, TruncTy);
1197       Value *QMul = nullptr;
1198       if (Width == 16) {
1199         QMul = createMulQ15(Builder, TruncX, TruncY, Rounding);
1200       } else if (Width == 32) {
1201         QMul = createMulQ31(Builder, TruncX, TruncY, Rounding);
1202       }
1203       if (QMul != nullptr)
1204         return Builder.CreateSExt(QMul, OrigTy);
1205 
1206       if (TruncX != Op.X && isa<Instruction>(TruncX))
1207         cast<Instruction>(TruncX)->eraseFromParent();
1208       if (TruncY != Op.Y && isa<Instruction>(TruncY))
1209         cast<Instruction>(TruncY)->eraseFromParent();
1210     }
1211   }
1212 
1213   // FIXME: make it general, _64, addcarry
1214   if (!HVC.HST.useHVXV62Ops())
1215     return nullptr;
1216 
1217   // FIXME: make it general
1218   if (OrigTy->getScalarSizeInBits() < 32)
1219     return nullptr;
1220 
1221   if (Width > 64)
1222     return nullptr;
1223 
1224   // At this point, NewX and NewY may be truncated to different element
1225   // widths to save on the number of multiplications to perform.
1226   unsigned WidthX =
1227       PowerOf2Ceil(std::max(BitsX, 32u)); // FIXME: handle shorter ones
1228   unsigned WidthY = PowerOf2Ceil(std::max(BitsY, 32u));
1229   Value *NewX = Builder.CreateTrunc(
1230       Op.X, VectorType::get(HVC.getIntTy(WidthX), HVC.length(Op.X), false));
1231   Value *NewY = Builder.CreateTrunc(
1232       Op.Y, VectorType::get(HVC.getIntTy(WidthY), HVC.length(Op.Y), false));
1233   if (NewX != Op.X)
1234     DeleteOnFailure.insert(NewX);
1235   if (NewY != Op.Y)
1236     DeleteOnFailure.insert(NewY);
1237 
1238   // Break up the arguments NewX and NewY into vectors of smaller widths
1239   // in preparation of doing the multiplication via HVX intrinsics.
1240   // TODO:
1241   // Make sure that the number of elements in NewX/NewY is 32. In the future
1242   // add generic code that will break up a (presumable long) vector into
1243   // shorter pieces, pad the last one, then concatenate all the pieces back.
1244   if (HVC.length(NewX) != 32)
1245     return nullptr;
1246   auto WordX = HVC.splitVectorElements(Builder, NewX, /*ToWidth=*/32);
1247   auto WordY = HVC.splitVectorElements(Builder, NewY, /*ToWidth=*/32);
1248   auto HvxWordTy = WordX[0]->getType();
1249 
1250   SmallVector<SmallVector<Value *>> Products(WordX.size() + WordY.size());
1251 
1252   // WordX[i] * WordY[j] produces words i+j and i+j+1 of the results,
1253   // that is halves 2(i+j), 2(i+j)+1, 2(i+j)+2, 2(i+j)+3.
1254   for (int i = 0, e = WordX.size(); i != e; ++i) {
1255     for (int j = 0, f = WordY.size(); j != f; ++j) {
1256       bool SgnX = (i + 1 == e) && SignX != Unsigned;
1257       bool SgnY = (j + 1 == f) && SignY != Unsigned;
1258       auto [Lo, Hi] = createMul32(Builder, {WordX[i], SgnX}, {WordY[j], SgnY});
1259       Products[i + j + 0].push_back(Lo);
1260       Products[i + j + 1].push_back(Hi);
1261     }
1262   }
1263 
1264   // Add the optional rounding to the proper word.
1265   if (Op.RoundAt.has_value()) {
1266     Products[*Op.RoundAt / 32].push_back(
1267         HVC.getConstSplat(HvxWordTy, 1 << (*Op.RoundAt % 32)));
1268   }
1269 
1270   auto V6_vaddcarry = HVC.HST.getIntrinsicId(Hexagon::V6_vaddcarry);
1271   Value *NoCarry = HVC.getNullValue(HVC.getBoolTy(HVC.length(HvxWordTy)));
1272   auto pop_back_or_zero = [this, HvxWordTy](auto &Vector) -> Value * {
1273     if (Vector.empty())
1274       return HVC.getNullValue(HvxWordTy);
1275     auto Last = Vector.back();
1276     Vector.pop_back();
1277     return Last;
1278   };
1279 
1280   for (int i = 0, e = Products.size(); i != e; ++i) {
1281     while (Products[i].size() > 1) {
1282       Value *Carry = NoCarry;
1283       for (int j = i; j != e; ++j) {
1284         auto &ProdJ = Products[j];
1285         Value *Ret = HVC.createHvxIntrinsic(
1286             Builder, V6_vaddcarry, nullptr,
1287             {pop_back_or_zero(ProdJ), pop_back_or_zero(ProdJ), Carry});
1288         ProdJ.insert(ProdJ.begin(), Builder.CreateExtractValue(Ret, {0}));
1289         Carry = Builder.CreateExtractValue(Ret, {1});
1290       }
1291     }
1292   }
1293 
1294   SmallVector<Value *> WordP;
1295   for (auto &P : Products) {
1296     assert(P.size() == 1 && "Should have been added together");
1297     WordP.push_back(P.front());
1298   }
1299 
1300   // Shift all products right by Op.Frac.
1301   unsigned SkipWords = Op.Frac / 32;
1302   Constant *ShiftAmt = HVC.getConstSplat(HvxWordTy, Op.Frac % 32);
1303 
1304   for (int Dst = 0, End = WordP.size() - SkipWords; Dst != End; ++Dst) {
1305     int Src = Dst + SkipWords;
1306     Value *Lo = WordP[Src];
1307     if (Src + 1 < End) {
1308       Value *Hi = WordP[Src + 1];
1309       WordP[Dst] = Builder.CreateIntrinsic(HvxWordTy, Intrinsic::fshr,
1310                                            {Hi, Lo, ShiftAmt});
1311     } else {
1312       // The shift of the most significant word.
1313       WordP[Dst] = Builder.CreateAShr(Lo, ShiftAmt);
1314     }
1315   }
1316   if (SkipWords != 0)
1317     WordP.resize(WordP.size() - SkipWords);
1318 
1319   DeleteOnFailure.clear();
1320   Value *Ret = HVC.joinVectorElements(Builder, WordP, OrigTy);
1321   return Ret;
1322 }
1323 
1324 auto HvxIdioms::createMulQ15(IRBuilderBase &Builder, Value *X, Value *Y,
1325                              bool Rounding) const -> Value * {
1326   assert(X->getType() == Y->getType());
1327   assert(X->getType()->getScalarType() == HVC.getIntTy(16));
1328   if (!HVC.HST.isHVXVectorType(EVT::getEVT(X->getType(), false)))
1329     return nullptr;
1330 
1331   unsigned HwLen = HVC.HST.getVectorLength();
1332 
1333   if (Rounding) {
1334     auto V6_vmpyhvsrs = HVC.HST.getIntrinsicId(Hexagon::V6_vmpyhvsrs);
1335     return HVC.createHvxIntrinsic(Builder, V6_vmpyhvsrs, X->getType(), {X, Y});
1336   }
1337   // No rounding, do i16*i16 -> i32, << 1, take upper half.
1338   auto V6_vmpyhv = HVC.HST.getIntrinsicId(Hexagon::V6_vmpyhv);
1339 
1340   // i16*i16 -> i32 / interleaved
1341   Value *V1 = HVC.createHvxIntrinsic(Builder, V6_vmpyhv, HvxP32Ty, {X, Y});
1342   // <<1
1343   Value *V2 = Builder.CreateAdd(V1, V1);
1344   // i32 -> i32 deinterleave
1345   SmallVector<int, 64> DeintMask;
1346   for (int i = 0; i != static_cast<int>(HwLen) / 4; ++i) {
1347     DeintMask.push_back(i);
1348     DeintMask.push_back(i + HwLen / 4);
1349   }
1350 
1351   Value *V3 =
1352       HVC.vdeal(Builder, HVC.sublo(Builder, V2), HVC.subhi(Builder, V2));
1353   // High halves: i32 -> i16
1354   SmallVector<int, 64> HighMask;
1355   for (int i = 0; i != static_cast<int>(HwLen) / 2; ++i) {
1356     HighMask.push_back(2 * i + 1);
1357   }
1358   auto *HvxP16Ty = HVC.getHvxTy(HVC.getIntTy(16), /*Pair=*/true);
1359   Value *V4 = Builder.CreateBitCast(V3, HvxP16Ty);
1360   return Builder.CreateShuffleVector(V4, HighMask);
1361 }
1362 
1363 auto HvxIdioms::createMulQ31(IRBuilderBase &Builder, Value *X, Value *Y,
1364                              bool Rounding) const -> Value * {
1365   assert(X->getType() == Y->getType());
1366   assert(X->getType()->getScalarType() == HVC.getIntTy(32));
1367   if (!HVC.HST.isHVXVectorType(EVT::getEVT(X->getType(), false)))
1368     return nullptr;
1369 
1370   auto V6_vmpyewuh = HVC.HST.getIntrinsicId(Hexagon::V6_vmpyewuh);
1371   auto MpyOddAcc = Rounding
1372                        ? HVC.HST.getIntrinsicId(Hexagon::V6_vmpyowh_rnd_sacc)
1373                        : HVC.HST.getIntrinsicId(Hexagon::V6_vmpyowh_sacc);
1374   Value *V1 =
1375       HVC.createHvxIntrinsic(Builder, V6_vmpyewuh, X->getType(), {X, Y});
1376   return HVC.createHvxIntrinsic(Builder, MpyOddAcc, X->getType(), {V1, X, Y});
1377 }
1378 
1379 auto HvxIdioms::createMul32(IRBuilderBase &Builder, SValue X, SValue Y) const
1380     -> std::pair<Value *, Value *> {
1381   assert(X.Val->getType() == Y.Val->getType());
1382   assert(X.Val->getType() == HVC.getHvxTy(HVC.getIntTy(32), /*Pair=*/false));
1383 
1384   Intrinsic::ID V6_vmpy_parts;
1385   if (X.Signed == Y.Signed) {
1386     V6_vmpy_parts = X.Signed ? Intrinsic::hexagon_V6_vmpyss_parts
1387                              : Intrinsic::hexagon_V6_vmpyuu_parts;
1388   } else {
1389     if (X.Signed)
1390       std::swap(X, Y);
1391     V6_vmpy_parts = Intrinsic::hexagon_V6_vmpyus_parts;
1392   }
1393 
1394   Value *Parts = HVC.createHvxIntrinsic(Builder, V6_vmpy_parts, nullptr,
1395                                         {X.Val, Y.Val}, {HvxI32Ty});
1396   Value *Hi = Builder.CreateExtractValue(Parts, {0});
1397   Value *Lo = Builder.CreateExtractValue(Parts, {1});
1398   return {Lo, Hi};
1399 }
1400 
1401 auto HvxIdioms::run() -> bool {
1402   bool Changed = false;
1403 
1404   for (BasicBlock &B : HVC.F) {
1405     for (auto It = B.rbegin(); It != B.rend(); ++It) {
1406       if (auto Fxm = matchFxpMul(*It)) {
1407         Value *New = processFxpMul(*It, *Fxm);
1408         if (!New)
1409           continue;
1410         bool StartOver = !isa<Instruction>(New);
1411         It->replaceAllUsesWith(New);
1412         RecursivelyDeleteTriviallyDeadInstructions(&*It, &HVC.TLI);
1413         It = StartOver ? B.rbegin()
1414                        : cast<Instruction>(New)->getReverseIterator();
1415         Changed = true;
1416       }
1417     }
1418   }
1419 
1420   return Changed;
1421 }
1422 
1423 // --- End HvxIdioms
1424 
1425 auto HexagonVectorCombine::run() -> bool {
1426   if (!HST.useHVXOps())
1427     return false;
1428 
1429   bool Changed = false;
1430   Changed |= AlignVectors(*this).run();
1431   Changed |= HvxIdioms(*this).run();
1432 
1433   return Changed;
1434 }
1435 
1436 auto HexagonVectorCombine::getIntTy(unsigned Width) const -> IntegerType * {
1437   return IntegerType::get(F.getContext(), Width);
1438 }
1439 
1440 auto HexagonVectorCombine::getByteTy(int ElemCount) const -> Type * {
1441   assert(ElemCount >= 0);
1442   IntegerType *ByteTy = Type::getInt8Ty(F.getContext());
1443   if (ElemCount == 0)
1444     return ByteTy;
1445   return VectorType::get(ByteTy, ElemCount, /*Scalable=*/false);
1446 }
1447 
1448 auto HexagonVectorCombine::getBoolTy(int ElemCount) const -> Type * {
1449   assert(ElemCount >= 0);
1450   IntegerType *BoolTy = Type::getInt1Ty(F.getContext());
1451   if (ElemCount == 0)
1452     return BoolTy;
1453   return VectorType::get(BoolTy, ElemCount, /*Scalable=*/false);
1454 }
1455 
1456 auto HexagonVectorCombine::getConstInt(int Val) const -> ConstantInt * {
1457   return ConstantInt::getSigned(getIntTy(), Val);
1458 }
1459 
1460 auto HexagonVectorCombine::isZero(const Value *Val) const -> bool {
1461   if (auto *C = dyn_cast<Constant>(Val))
1462     return C->isZeroValue();
1463   return false;
1464 }
1465 
1466 auto HexagonVectorCombine::getIntValue(const Value *Val) const
1467     -> std::optional<APInt> {
1468   if (auto *CI = dyn_cast<ConstantInt>(Val))
1469     return CI->getValue();
1470   return std::nullopt;
1471 }
1472 
1473 auto HexagonVectorCombine::isUndef(const Value *Val) const -> bool {
1474   return isa<UndefValue>(Val);
1475 }
1476 
1477 auto HexagonVectorCombine::getHvxTy(Type *ElemTy, bool Pair) const
1478     -> VectorType * {
1479   EVT ETy = EVT::getEVT(ElemTy, false);
1480   assert(ETy.isSimple() && "Invalid HVX element type");
1481   // Do not allow boolean types here: they don't have a fixed length.
1482   assert(HST.isHVXElementType(ETy.getSimpleVT(), /*IncludeBool=*/false) &&
1483          "Invalid HVX element type");
1484   unsigned HwLen = HST.getVectorLength();
1485   unsigned NumElems = (8 * HwLen) / ETy.getSizeInBits();
1486   return VectorType::get(ElemTy, Pair ? 2 * NumElems : NumElems,
1487                          /*Scalable=*/false);
1488 }
1489 
1490 auto HexagonVectorCombine::getSizeOf(const Value *Val, SizeKind Kind) const
1491     -> int {
1492   return getSizeOf(Val->getType(), Kind);
1493 }
1494 
1495 auto HexagonVectorCombine::getSizeOf(const Type *Ty, SizeKind Kind) const
1496     -> int {
1497   auto *NcTy = const_cast<Type *>(Ty);
1498   switch (Kind) {
1499   case Store:
1500     return DL.getTypeStoreSize(NcTy).getFixedValue();
1501   case Alloc:
1502     return DL.getTypeAllocSize(NcTy).getFixedValue();
1503   }
1504   llvm_unreachable("Unhandled SizeKind enum");
1505 }
1506 
1507 auto HexagonVectorCombine::getTypeAlignment(Type *Ty) const -> int {
1508   // The actual type may be shorter than the HVX vector, so determine
1509   // the alignment based on subtarget info.
1510   if (HST.isTypeForHVX(Ty))
1511     return HST.getVectorLength();
1512   return DL.getABITypeAlign(Ty).value();
1513 }
1514 
1515 auto HexagonVectorCombine::length(Value *Val) const -> size_t {
1516   return length(Val->getType());
1517 }
1518 
1519 auto HexagonVectorCombine::length(Type *Ty) const -> size_t {
1520   auto *VecTy = dyn_cast<VectorType>(Ty);
1521   assert(VecTy && "Must be a vector type");
1522   return VecTy->getElementCount().getFixedValue();
1523 }
1524 
1525 auto HexagonVectorCombine::getNullValue(Type *Ty) const -> Constant * {
1526   assert(Ty->isIntOrIntVectorTy());
1527   auto Zero = ConstantInt::get(Ty->getScalarType(), 0);
1528   if (auto *VecTy = dyn_cast<VectorType>(Ty))
1529     return ConstantVector::getSplat(VecTy->getElementCount(), Zero);
1530   return Zero;
1531 }
1532 
1533 auto HexagonVectorCombine::getFullValue(Type *Ty) const -> Constant * {
1534   assert(Ty->isIntOrIntVectorTy());
1535   auto Minus1 = ConstantInt::get(Ty->getScalarType(), -1);
1536   if (auto *VecTy = dyn_cast<VectorType>(Ty))
1537     return ConstantVector::getSplat(VecTy->getElementCount(), Minus1);
1538   return Minus1;
1539 }
1540 
1541 auto HexagonVectorCombine::getConstSplat(Type *Ty, int Val) const
1542     -> Constant * {
1543   assert(Ty->isVectorTy());
1544   auto VecTy = cast<VectorType>(Ty);
1545   Type *ElemTy = VecTy->getElementType();
1546   // Add support for floats if needed.
1547   auto *Splat = ConstantVector::getSplat(VecTy->getElementCount(),
1548                                          ConstantInt::get(ElemTy, Val));
1549   return Splat;
1550 }
1551 
1552 auto HexagonVectorCombine::simplify(Value *V) const -> Value * {
1553   if (auto *In = dyn_cast<Instruction>(V)) {
1554     SimplifyQuery Q(DL, &TLI, &DT, &AC, In);
1555     return simplifyInstruction(In, Q);
1556   }
1557   return nullptr;
1558 }
1559 
1560 // Insert bytes [Start..Start+Length) of Src into Dst at byte Where.
1561 auto HexagonVectorCombine::insertb(IRBuilderBase &Builder, Value *Dst,
1562                                    Value *Src, int Start, int Length,
1563                                    int Where) const -> Value * {
1564   assert(isByteVecTy(Dst->getType()) && isByteVecTy(Src->getType()));
1565   int SrcLen = getSizeOf(Src);
1566   int DstLen = getSizeOf(Dst);
1567   assert(0 <= Start && Start + Length <= SrcLen);
1568   assert(0 <= Where && Where + Length <= DstLen);
1569 
1570   int P2Len = PowerOf2Ceil(SrcLen | DstLen);
1571   auto *Undef = UndefValue::get(getByteTy());
1572   Value *P2Src = vresize(Builder, Src, P2Len, Undef);
1573   Value *P2Dst = vresize(Builder, Dst, P2Len, Undef);
1574 
1575   SmallVector<int, 256> SMask(P2Len);
1576   for (int i = 0; i != P2Len; ++i) {
1577     // If i is in [Where, Where+Length), pick Src[Start+(i-Where)].
1578     // Otherwise, pick Dst[i];
1579     SMask[i] =
1580         (Where <= i && i < Where + Length) ? P2Len + Start + (i - Where) : i;
1581   }
1582 
1583   Value *P2Insert = Builder.CreateShuffleVector(P2Dst, P2Src, SMask);
1584   return vresize(Builder, P2Insert, DstLen, Undef);
1585 }
1586 
1587 auto HexagonVectorCombine::vlalignb(IRBuilderBase &Builder, Value *Lo,
1588                                     Value *Hi, Value *Amt) const -> Value * {
1589   assert(Lo->getType() == Hi->getType() && "Argument type mismatch");
1590   if (isZero(Amt))
1591     return Hi;
1592   int VecLen = getSizeOf(Hi);
1593   if (auto IntAmt = getIntValue(Amt))
1594     return getElementRange(Builder, Lo, Hi, VecLen - IntAmt->getSExtValue(),
1595                            VecLen);
1596 
1597   if (HST.isTypeForHVX(Hi->getType())) {
1598     assert(static_cast<unsigned>(VecLen) == HST.getVectorLength() &&
1599            "Expecting an exact HVX type");
1600     return createHvxIntrinsic(Builder, HST.getIntrinsicId(Hexagon::V6_vlalignb),
1601                               Hi->getType(), {Hi, Lo, Amt});
1602   }
1603 
1604   if (VecLen == 4) {
1605     Value *Pair = concat(Builder, {Lo, Hi});
1606     Value *Shift = Builder.CreateLShr(Builder.CreateShl(Pair, Amt), 32);
1607     Value *Trunc = Builder.CreateTrunc(Shift, Type::getInt32Ty(F.getContext()));
1608     return Builder.CreateBitCast(Trunc, Hi->getType());
1609   }
1610   if (VecLen == 8) {
1611     Value *Sub = Builder.CreateSub(getConstInt(VecLen), Amt);
1612     return vralignb(Builder, Lo, Hi, Sub);
1613   }
1614   llvm_unreachable("Unexpected vector length");
1615 }
1616 
1617 auto HexagonVectorCombine::vralignb(IRBuilderBase &Builder, Value *Lo,
1618                                     Value *Hi, Value *Amt) const -> Value * {
1619   assert(Lo->getType() == Hi->getType() && "Argument type mismatch");
1620   if (isZero(Amt))
1621     return Lo;
1622   int VecLen = getSizeOf(Lo);
1623   if (auto IntAmt = getIntValue(Amt))
1624     return getElementRange(Builder, Lo, Hi, IntAmt->getSExtValue(), VecLen);
1625 
1626   if (HST.isTypeForHVX(Lo->getType())) {
1627     assert(static_cast<unsigned>(VecLen) == HST.getVectorLength() &&
1628            "Expecting an exact HVX type");
1629     return createHvxIntrinsic(Builder, HST.getIntrinsicId(Hexagon::V6_valignb),
1630                               Lo->getType(), {Hi, Lo, Amt});
1631   }
1632 
1633   if (VecLen == 4) {
1634     Value *Pair = concat(Builder, {Lo, Hi});
1635     Value *Shift = Builder.CreateLShr(Pair, Amt);
1636     Value *Trunc = Builder.CreateTrunc(Shift, Type::getInt32Ty(F.getContext()));
1637     return Builder.CreateBitCast(Trunc, Lo->getType());
1638   }
1639   if (VecLen == 8) {
1640     Type *Int64Ty = Type::getInt64Ty(F.getContext());
1641     Value *Lo64 = Builder.CreateBitCast(Lo, Int64Ty);
1642     Value *Hi64 = Builder.CreateBitCast(Hi, Int64Ty);
1643     Function *FI = Intrinsic::getDeclaration(F.getParent(),
1644                                              Intrinsic::hexagon_S2_valignrb);
1645     Value *Call = Builder.CreateCall(FI, {Hi64, Lo64, Amt});
1646     return Builder.CreateBitCast(Call, Lo->getType());
1647   }
1648   llvm_unreachable("Unexpected vector length");
1649 }
1650 
1651 // Concatenates a sequence of vectors of the same type.
1652 auto HexagonVectorCombine::concat(IRBuilderBase &Builder,
1653                                   ArrayRef<Value *> Vecs) const -> Value * {
1654   assert(!Vecs.empty());
1655   SmallVector<int, 256> SMask;
1656   std::vector<Value *> Work[2];
1657   int ThisW = 0, OtherW = 1;
1658 
1659   Work[ThisW].assign(Vecs.begin(), Vecs.end());
1660   while (Work[ThisW].size() > 1) {
1661     auto *Ty = cast<VectorType>(Work[ThisW].front()->getType());
1662     SMask.resize(length(Ty) * 2);
1663     std::iota(SMask.begin(), SMask.end(), 0);
1664 
1665     Work[OtherW].clear();
1666     if (Work[ThisW].size() % 2 != 0)
1667       Work[ThisW].push_back(UndefValue::get(Ty));
1668     for (int i = 0, e = Work[ThisW].size(); i < e; i += 2) {
1669       Value *Joined = Builder.CreateShuffleVector(Work[ThisW][i],
1670                                                   Work[ThisW][i + 1], SMask);
1671       Work[OtherW].push_back(Joined);
1672     }
1673     std::swap(ThisW, OtherW);
1674   }
1675 
1676   // Since there may have been some undefs appended to make shuffle operands
1677   // have the same type, perform the last shuffle to only pick the original
1678   // elements.
1679   SMask.resize(Vecs.size() * length(Vecs.front()->getType()));
1680   std::iota(SMask.begin(), SMask.end(), 0);
1681   Value *Total = Work[ThisW].front();
1682   return Builder.CreateShuffleVector(Total, SMask);
1683 }
1684 
1685 auto HexagonVectorCombine::vresize(IRBuilderBase &Builder, Value *Val,
1686                                    int NewSize, Value *Pad) const -> Value * {
1687   assert(isa<VectorType>(Val->getType()));
1688   auto *ValTy = cast<VectorType>(Val->getType());
1689   assert(ValTy->getElementType() == Pad->getType());
1690 
1691   int CurSize = length(ValTy);
1692   if (CurSize == NewSize)
1693     return Val;
1694   // Truncate?
1695   if (CurSize > NewSize)
1696     return getElementRange(Builder, Val, /*Ignored*/ Val, 0, NewSize);
1697   // Extend.
1698   SmallVector<int, 128> SMask(NewSize);
1699   std::iota(SMask.begin(), SMask.begin() + CurSize, 0);
1700   std::fill(SMask.begin() + CurSize, SMask.end(), CurSize);
1701   Value *PadVec = Builder.CreateVectorSplat(CurSize, Pad);
1702   return Builder.CreateShuffleVector(Val, PadVec, SMask);
1703 }
1704 
1705 auto HexagonVectorCombine::rescale(IRBuilderBase &Builder, Value *Mask,
1706                                    Type *FromTy, Type *ToTy) const -> Value * {
1707   // Mask is a vector <N x i1>, where each element corresponds to an
1708   // element of FromTy. Remap it so that each element will correspond
1709   // to an element of ToTy.
1710   assert(isa<VectorType>(Mask->getType()));
1711 
1712   Type *FromSTy = FromTy->getScalarType();
1713   Type *ToSTy = ToTy->getScalarType();
1714   if (FromSTy == ToSTy)
1715     return Mask;
1716 
1717   int FromSize = getSizeOf(FromSTy);
1718   int ToSize = getSizeOf(ToSTy);
1719   assert(FromSize % ToSize == 0 || ToSize % FromSize == 0);
1720 
1721   auto *MaskTy = cast<VectorType>(Mask->getType());
1722   int FromCount = length(MaskTy);
1723   int ToCount = (FromCount * FromSize) / ToSize;
1724   assert((FromCount * FromSize) % ToSize == 0);
1725 
1726   auto *FromITy = getIntTy(FromSize * 8);
1727   auto *ToITy = getIntTy(ToSize * 8);
1728 
1729   // Mask <N x i1> -> sext to <N x FromTy> -> bitcast to <M x ToTy> ->
1730   // -> trunc to <M x i1>.
1731   Value *Ext = Builder.CreateSExt(
1732       Mask, VectorType::get(FromITy, FromCount, /*Scalable=*/false));
1733   Value *Cast = Builder.CreateBitCast(
1734       Ext, VectorType::get(ToITy, ToCount, /*Scalable=*/false));
1735   return Builder.CreateTrunc(
1736       Cast, VectorType::get(getBoolTy(), ToCount, /*Scalable=*/false));
1737 }
1738 
1739 // Bitcast to bytes, and return least significant bits.
1740 auto HexagonVectorCombine::vlsb(IRBuilderBase &Builder, Value *Val) const
1741     -> Value * {
1742   Type *ScalarTy = Val->getType()->getScalarType();
1743   if (ScalarTy == getBoolTy())
1744     return Val;
1745 
1746   Value *Bytes = vbytes(Builder, Val);
1747   if (auto *VecTy = dyn_cast<VectorType>(Bytes->getType()))
1748     return Builder.CreateTrunc(Bytes, getBoolTy(getSizeOf(VecTy)));
1749   // If Bytes is a scalar (i.e. Val was a scalar byte), return i1, not
1750   // <1 x i1>.
1751   return Builder.CreateTrunc(Bytes, getBoolTy());
1752 }
1753 
1754 // Bitcast to bytes for non-bool. For bool, convert i1 -> i8.
1755 auto HexagonVectorCombine::vbytes(IRBuilderBase &Builder, Value *Val) const
1756     -> Value * {
1757   Type *ScalarTy = Val->getType()->getScalarType();
1758   if (ScalarTy == getByteTy())
1759     return Val;
1760 
1761   if (ScalarTy != getBoolTy())
1762     return Builder.CreateBitCast(Val, getByteTy(getSizeOf(Val)));
1763   // For bool, return a sext from i1 to i8.
1764   if (auto *VecTy = dyn_cast<VectorType>(Val->getType()))
1765     return Builder.CreateSExt(Val, VectorType::get(getByteTy(), VecTy));
1766   return Builder.CreateSExt(Val, getByteTy());
1767 }
1768 
1769 auto HexagonVectorCombine::subvector(IRBuilderBase &Builder, Value *Val,
1770                                      unsigned Start, unsigned Length) const
1771     -> Value * {
1772   assert(Start + Length <= length(Val));
1773   return getElementRange(Builder, Val, /*Ignored*/ Val, Start, Length);
1774 }
1775 
1776 auto HexagonVectorCombine::sublo(IRBuilderBase &Builder, Value *Val) const
1777     -> Value * {
1778   size_t Len = length(Val);
1779   assert(Len % 2 == 0 && "Length should be even");
1780   return subvector(Builder, Val, 0, Len / 2);
1781 }
1782 
1783 auto HexagonVectorCombine::subhi(IRBuilderBase &Builder, Value *Val) const
1784     -> Value * {
1785   size_t Len = length(Val);
1786   assert(Len % 2 == 0 && "Length should be even");
1787   return subvector(Builder, Val, Len / 2, Len / 2);
1788 }
1789 
1790 auto HexagonVectorCombine::vdeal(IRBuilderBase &Builder, Value *Val0,
1791                                  Value *Val1) const -> Value * {
1792   assert(Val0->getType() == Val1->getType());
1793   int Len = length(Val0);
1794   SmallVector<int, 128> Mask(2 * Len);
1795 
1796   for (int i = 0; i != Len; ++i) {
1797     Mask[i] = 2 * i;           // Even
1798     Mask[i + Len] = 2 * i + 1; // Odd
1799   }
1800   return Builder.CreateShuffleVector(Val0, Val1, Mask);
1801 }
1802 
1803 auto HexagonVectorCombine::vshuff(IRBuilderBase &Builder, Value *Val0,
1804                                   Value *Val1) const -> Value * { //
1805   assert(Val0->getType() == Val1->getType());
1806   int Len = length(Val0);
1807   SmallVector<int, 128> Mask(2 * Len);
1808 
1809   for (int i = 0; i != Len; ++i) {
1810     Mask[2 * i + 0] = i;       // Val0
1811     Mask[2 * i + 1] = i + Len; // Val1
1812   }
1813   return Builder.CreateShuffleVector(Val0, Val1, Mask);
1814 }
1815 
1816 auto HexagonVectorCombine::createHvxIntrinsic(IRBuilderBase &Builder,
1817                                               Intrinsic::ID IntID, Type *RetTy,
1818                                               ArrayRef<Value *> Args,
1819                                               ArrayRef<Type *> ArgTys) const
1820     -> Value * {
1821   auto getCast = [&](IRBuilderBase &Builder, Value *Val,
1822                      Type *DestTy) -> Value * {
1823     Type *SrcTy = Val->getType();
1824     if (SrcTy == DestTy)
1825       return Val;
1826 
1827     // Non-HVX type. It should be a scalar, and it should already have
1828     // a valid type.
1829     assert(HST.isTypeForHVX(SrcTy, /*IncludeBool=*/true));
1830 
1831     Type *BoolTy = Type::getInt1Ty(F.getContext());
1832     if (cast<VectorType>(SrcTy)->getElementType() != BoolTy)
1833       return Builder.CreateBitCast(Val, DestTy);
1834 
1835     // Predicate HVX vector.
1836     unsigned HwLen = HST.getVectorLength();
1837     Intrinsic::ID TC = HwLen == 64 ? Intrinsic::hexagon_V6_pred_typecast
1838                                    : Intrinsic::hexagon_V6_pred_typecast_128B;
1839     Function *FI =
1840         Intrinsic::getDeclaration(F.getParent(), TC, {DestTy, Val->getType()});
1841     return Builder.CreateCall(FI, {Val});
1842   };
1843 
1844   Function *IntrFn = Intrinsic::getDeclaration(F.getParent(), IntID, ArgTys);
1845   FunctionType *IntrTy = IntrFn->getFunctionType();
1846 
1847   SmallVector<Value *, 4> IntrArgs;
1848   for (int i = 0, e = Args.size(); i != e; ++i) {
1849     Value *A = Args[i];
1850     Type *T = IntrTy->getParamType(i);
1851     if (A->getType() != T) {
1852       IntrArgs.push_back(getCast(Builder, A, T));
1853     } else {
1854       IntrArgs.push_back(A);
1855     }
1856   }
1857   Value *Call = Builder.CreateCall(IntrFn, IntrArgs);
1858 
1859   Type *CallTy = Call->getType();
1860   if (RetTy == nullptr || CallTy == RetTy)
1861     return Call;
1862   // Scalar types should have RetTy matching the call return type.
1863   assert(HST.isTypeForHVX(CallTy, /*IncludeBool=*/true));
1864   return getCast(Builder, Call, RetTy);
1865 }
1866 
1867 auto HexagonVectorCombine::splitVectorElements(IRBuilderBase &Builder,
1868                                                Value *Vec,
1869                                                unsigned ToWidth) const
1870     -> SmallVector<Value *> {
1871   // Break a vector of wide elements into a series of vectors with narrow
1872   // elements:
1873   //   (...c0:b0:a0, ...c1:b1:a1, ...c2:b2:a2, ...)
1874   // -->
1875   //   (a0, a1, a2, ...)    // lowest "ToWidth" bits
1876   //   (b0, b1, b2, ...)    // the next lowest...
1877   //   (c0, c1, c2, ...)    // ...
1878   //   ...
1879   //
1880   // The number of elements in each resulting vector is the same as
1881   // in the original vector.
1882 
1883   auto *VecTy = cast<VectorType>(Vec->getType());
1884   assert(VecTy->getElementType()->isIntegerTy());
1885   unsigned FromWidth = VecTy->getScalarSizeInBits();
1886   assert(isPowerOf2_32(ToWidth) && isPowerOf2_32(FromWidth));
1887   assert(ToWidth <= FromWidth && "Breaking up into wider elements?");
1888   unsigned NumResults = FromWidth / ToWidth;
1889 
1890   SmallVector<Value *> Results(NumResults);
1891   Results[0] = Vec;
1892   unsigned Length = length(VecTy);
1893 
1894   // Do it by splitting in half, since those operations correspond to deal
1895   // instructions.
1896   auto splitInHalf = [&](unsigned Begin, unsigned End, auto splitFunc) -> void {
1897     // Take V = Results[Begin], split it in L, H.
1898     // Store Results[Begin] = L, Results[(Begin+End)/2] = H
1899     // Call itself recursively split(Begin, Half), split(Half+1, End)
1900     if (Begin + 1 == End)
1901       return;
1902 
1903     Value *Val = Results[Begin];
1904     unsigned Width = Val->getType()->getScalarSizeInBits();
1905 
1906     auto *VTy = VectorType::get(getIntTy(Width / 2), 2 * Length, false);
1907     Value *VVal = Builder.CreateBitCast(Val, VTy);
1908 
1909     Value *Res = vdeal(Builder, sublo(Builder, VVal), subhi(Builder, VVal));
1910 
1911     unsigned Half = (Begin + End) / 2;
1912     Results[Begin] = sublo(Builder, Res);
1913     Results[Half] = subhi(Builder, Res);
1914 
1915     splitFunc(Begin, Half, splitFunc);
1916     splitFunc(Half, End, splitFunc);
1917   };
1918 
1919   splitInHalf(0, NumResults, splitInHalf);
1920   return Results;
1921 }
1922 
1923 auto HexagonVectorCombine::joinVectorElements(IRBuilderBase &Builder,
1924                                               ArrayRef<Value *> Values,
1925                                               VectorType *ToType) const
1926     -> Value * {
1927   assert(ToType->getElementType()->isIntegerTy());
1928 
1929   // If the list of values does not have power-of-2 elements, append copies
1930   // of the sign bit to it, to make the size be 2^n.
1931   // The reason for this is that the values will be joined in pairs, because
1932   // otherwise the shuffles will result in convoluted code. With pairwise
1933   // joins, the shuffles will hopefully be folded into a perfect shuffle.
1934   // The output will need to be sign-extended to a type with element width
1935   // being a power-of-2 anyways.
1936   SmallVector<Value *> Inputs(Values.begin(), Values.end());
1937 
1938   unsigned ToWidth = ToType->getScalarSizeInBits();
1939   unsigned Width = Inputs.front()->getType()->getScalarSizeInBits();
1940   assert(Width <= ToWidth);
1941   assert(isPowerOf2_32(Width) && isPowerOf2_32(ToWidth));
1942   unsigned Length = length(Inputs.front()->getType());
1943 
1944   unsigned NeedInputs = ToWidth / Width;
1945   if (Inputs.size() != NeedInputs) {
1946     Value *Last = Inputs.back();
1947     Value *Sign =
1948         Builder.CreateAShr(Last, getConstSplat(Last->getType(), Width - 1));
1949     Inputs.resize(NeedInputs, Sign);
1950   }
1951 
1952   while (Inputs.size() > 1) {
1953     Width *= 2;
1954     auto *VTy = VectorType::get(getIntTy(Width), Length, false);
1955     for (int i = 0, e = Inputs.size(); i < e; i += 2) {
1956       Value *Res = vshuff(Builder, Inputs[i], Inputs[i + 1]);
1957       Inputs[i / 2] = Builder.CreateBitCast(Res, VTy);
1958     }
1959     Inputs.resize(Inputs.size() / 2);
1960   }
1961 
1962   assert(Inputs.front()->getType() == ToType);
1963   return Inputs.front();
1964 }
1965 
1966 auto HexagonVectorCombine::calculatePointerDifference(Value *Ptr0,
1967                                                       Value *Ptr1) const
1968     -> std::optional<int> {
1969   struct Builder : IRBuilder<> {
1970     Builder(BasicBlock *B) : IRBuilder<>(B->getTerminator()) {}
1971     ~Builder() {
1972       for (Instruction *I : llvm::reverse(ToErase))
1973         I->eraseFromParent();
1974     }
1975     SmallVector<Instruction *, 8> ToErase;
1976   };
1977 
1978 #define CallBuilder(B, F)                                                      \
1979   [&](auto &B_) {                                                              \
1980     Value *V = B_.F;                                                           \
1981     if (auto *I = dyn_cast<Instruction>(V))                                    \
1982       B_.ToErase.push_back(I);                                                 \
1983     return V;                                                                  \
1984   }(B)
1985 
1986   auto Simplify = [&](Value *V) {
1987     if (auto *I = dyn_cast<Instruction>(V)) {
1988       SimplifyQuery Q(DL, &TLI, &DT, &AC, I);
1989       if (Value *S = simplifyInstruction(I, Q))
1990         return S;
1991     }
1992     return V;
1993   };
1994 
1995   auto StripBitCast = [](Value *V) {
1996     while (auto *C = dyn_cast<BitCastInst>(V))
1997       V = C->getOperand(0);
1998     return V;
1999   };
2000 
2001   Ptr0 = StripBitCast(Ptr0);
2002   Ptr1 = StripBitCast(Ptr1);
2003   if (!isa<GetElementPtrInst>(Ptr0) || !isa<GetElementPtrInst>(Ptr1))
2004     return std::nullopt;
2005 
2006   auto *Gep0 = cast<GetElementPtrInst>(Ptr0);
2007   auto *Gep1 = cast<GetElementPtrInst>(Ptr1);
2008   if (Gep0->getPointerOperand() != Gep1->getPointerOperand())
2009     return std::nullopt;
2010 
2011   Builder B(Gep0->getParent());
2012   int Scale = getSizeOf(Gep0->getSourceElementType(), Alloc);
2013 
2014   // FIXME: for now only check GEPs with a single index.
2015   if (Gep0->getNumOperands() != 2 || Gep1->getNumOperands() != 2)
2016     return std::nullopt;
2017 
2018   Value *Idx0 = Gep0->getOperand(1);
2019   Value *Idx1 = Gep1->getOperand(1);
2020 
2021   // First, try to simplify the subtraction directly.
2022   if (auto *Diff = dyn_cast<ConstantInt>(
2023           Simplify(CallBuilder(B, CreateSub(Idx0, Idx1)))))
2024     return Diff->getSExtValue() * Scale;
2025 
2026   KnownBits Known0 = getKnownBits(Idx0, Gep0);
2027   KnownBits Known1 = getKnownBits(Idx1, Gep1);
2028   APInt Unknown = ~(Known0.Zero | Known0.One) | ~(Known1.Zero | Known1.One);
2029   if (Unknown.isAllOnes())
2030     return std::nullopt;
2031 
2032   Value *MaskU = ConstantInt::get(Idx0->getType(), Unknown);
2033   Value *AndU0 = Simplify(CallBuilder(B, CreateAnd(Idx0, MaskU)));
2034   Value *AndU1 = Simplify(CallBuilder(B, CreateAnd(Idx1, MaskU)));
2035   Value *SubU = Simplify(CallBuilder(B, CreateSub(AndU0, AndU1)));
2036   int Diff0 = 0;
2037   if (auto *C = dyn_cast<ConstantInt>(SubU)) {
2038     Diff0 = C->getSExtValue();
2039   } else {
2040     return std::nullopt;
2041   }
2042 
2043   Value *MaskK = ConstantInt::get(MaskU->getType(), ~Unknown);
2044   Value *AndK0 = Simplify(CallBuilder(B, CreateAnd(Idx0, MaskK)));
2045   Value *AndK1 = Simplify(CallBuilder(B, CreateAnd(Idx1, MaskK)));
2046   Value *SubK = Simplify(CallBuilder(B, CreateSub(AndK0, AndK1)));
2047   int Diff1 = 0;
2048   if (auto *C = dyn_cast<ConstantInt>(SubK)) {
2049     Diff1 = C->getSExtValue();
2050   } else {
2051     return std::nullopt;
2052   }
2053 
2054   return (Diff0 + Diff1) * Scale;
2055 
2056 #undef CallBuilder
2057 }
2058 
2059 auto HexagonVectorCombine::getNumSignificantBits(const Value *V,
2060                                                  const Instruction *CtxI) const
2061     -> unsigned {
2062   return ComputeMaxSignificantBits(V, DL, /*Depth=*/0, &AC, CtxI, &DT);
2063 }
2064 
2065 auto HexagonVectorCombine::getKnownBits(const Value *V,
2066                                         const Instruction *CtxI) const
2067     -> KnownBits {
2068   return computeKnownBits(V, DL, /*Depth=*/0, &AC, CtxI, &DT, /*ORE=*/nullptr,
2069                           /*UseInstrInfo=*/true);
2070 }
2071 
2072 template <typename T>
2073 auto HexagonVectorCombine::isSafeToMoveBeforeInBB(const Instruction &In,
2074                                                   BasicBlock::const_iterator To,
2075                                                   const T &Ignore) const
2076     -> bool {
2077   auto getLocOrNone = [this](const Instruction &I) -> Optional<MemoryLocation> {
2078     if (const auto *II = dyn_cast<IntrinsicInst>(&I)) {
2079       switch (II->getIntrinsicID()) {
2080       case Intrinsic::masked_load:
2081         return MemoryLocation::getForArgument(II, 0, TLI);
2082       case Intrinsic::masked_store:
2083         return MemoryLocation::getForArgument(II, 1, TLI);
2084       }
2085     }
2086     return MemoryLocation::getOrNone(&I);
2087   };
2088 
2089   // The source and the destination must be in the same basic block.
2090   const BasicBlock &Block = *In.getParent();
2091   assert(Block.begin() == To || Block.end() == To || To->getParent() == &Block);
2092   // No PHIs.
2093   if (isa<PHINode>(In) || (To != Block.end() && isa<PHINode>(*To)))
2094     return false;
2095 
2096   if (!mayHaveNonDefUseDependency(In))
2097     return true;
2098   bool MayWrite = In.mayWriteToMemory();
2099   auto MaybeLoc = getLocOrNone(In);
2100 
2101   auto From = In.getIterator();
2102   if (From == To)
2103     return true;
2104   bool MoveUp = (To != Block.end() && To->comesBefore(&In));
2105   auto Range =
2106       MoveUp ? std::make_pair(To, From) : std::make_pair(std::next(From), To);
2107   for (auto It = Range.first; It != Range.second; ++It) {
2108     const Instruction &I = *It;
2109     if (llvm::is_contained(Ignore, &I))
2110       continue;
2111     // assume intrinsic can be ignored
2112     if (auto *II = dyn_cast<IntrinsicInst>(&I)) {
2113       if (II->getIntrinsicID() == Intrinsic::assume)
2114         continue;
2115     }
2116     // Parts based on isSafeToMoveBefore from CoveMoverUtils.cpp.
2117     if (I.mayThrow())
2118       return false;
2119     if (auto *CB = dyn_cast<CallBase>(&I)) {
2120       if (!CB->hasFnAttr(Attribute::WillReturn))
2121         return false;
2122       if (!CB->hasFnAttr(Attribute::NoSync))
2123         return false;
2124     }
2125     if (I.mayReadOrWriteMemory()) {
2126       auto MaybeLocI = getLocOrNone(I);
2127       if (MayWrite || I.mayWriteToMemory()) {
2128         if (!MaybeLoc || !MaybeLocI)
2129           return false;
2130         if (!AA.isNoAlias(*MaybeLoc, *MaybeLocI))
2131           return false;
2132       }
2133     }
2134   }
2135   return true;
2136 }
2137 
2138 auto HexagonVectorCombine::isByteVecTy(Type *Ty) const -> bool {
2139   if (auto *VecTy = dyn_cast<VectorType>(Ty))
2140     return VecTy->getElementType() == getByteTy();
2141   return false;
2142 }
2143 
2144 auto HexagonVectorCombine::getElementRange(IRBuilderBase &Builder, Value *Lo,
2145                                            Value *Hi, int Start,
2146                                            int Length) const -> Value * {
2147   assert(0 <= Start && size_t(Start + Length) < length(Lo) + length(Hi));
2148   SmallVector<int, 128> SMask(Length);
2149   std::iota(SMask.begin(), SMask.end(), Start);
2150   return Builder.CreateShuffleVector(Lo, Hi, SMask);
2151 }
2152 
2153 // Pass management.
2154 
2155 namespace llvm {
2156 void initializeHexagonVectorCombineLegacyPass(PassRegistry &);
2157 FunctionPass *createHexagonVectorCombineLegacyPass();
2158 } // namespace llvm
2159 
2160 namespace {
2161 class HexagonVectorCombineLegacy : public FunctionPass {
2162 public:
2163   static char ID;
2164 
2165   HexagonVectorCombineLegacy() : FunctionPass(ID) {}
2166 
2167   StringRef getPassName() const override { return "Hexagon Vector Combine"; }
2168 
2169   void getAnalysisUsage(AnalysisUsage &AU) const override {
2170     AU.setPreservesCFG();
2171     AU.addRequired<AAResultsWrapperPass>();
2172     AU.addRequired<AssumptionCacheTracker>();
2173     AU.addRequired<DominatorTreeWrapperPass>();
2174     AU.addRequired<TargetLibraryInfoWrapperPass>();
2175     AU.addRequired<TargetPassConfig>();
2176     FunctionPass::getAnalysisUsage(AU);
2177   }
2178 
2179   bool runOnFunction(Function &F) override {
2180     if (skipFunction(F))
2181       return false;
2182     AliasAnalysis &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
2183     AssumptionCache &AC =
2184         getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
2185     DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
2186     TargetLibraryInfo &TLI =
2187         getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
2188     auto &TM = getAnalysis<TargetPassConfig>().getTM<HexagonTargetMachine>();
2189     HexagonVectorCombine HVC(F, AA, AC, DT, TLI, TM);
2190     return HVC.run();
2191   }
2192 };
2193 } // namespace
2194 
2195 char HexagonVectorCombineLegacy::ID = 0;
2196 
2197 INITIALIZE_PASS_BEGIN(HexagonVectorCombineLegacy, DEBUG_TYPE,
2198                       "Hexagon Vector Combine", false, false)
2199 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
2200 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
2201 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
2202 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
2203 INITIALIZE_PASS_DEPENDENCY(TargetPassConfig)
2204 INITIALIZE_PASS_END(HexagonVectorCombineLegacy, DEBUG_TYPE,
2205                     "Hexagon Vector Combine", false, false)
2206 
2207 FunctionPass *llvm::createHexagonVectorCombineLegacyPass() {
2208   return new HexagonVectorCombineLegacy();
2209 }
2210