xref: /llvm-project/llvm/lib/Target/Hexagon/HexagonVectorCombine.cpp (revision 2983053d23d30b408122abf772bd50638f4ded2c)
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/Optional.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/Analysis/AliasAnalysis.h"
21 #include "llvm/Analysis/AssumptionCache.h"
22 #include "llvm/Analysis/InstructionSimplify.h"
23 #include "llvm/Analysis/TargetLibraryInfo.h"
24 #include "llvm/Analysis/ValueTracking.h"
25 #include "llvm/Analysis/VectorUtils.h"
26 #include "llvm/CodeGen/TargetPassConfig.h"
27 #include "llvm/IR/Dominators.h"
28 #include "llvm/IR/IRBuilder.h"
29 #include "llvm/IR/IntrinsicInst.h"
30 #include "llvm/IR/Intrinsics.h"
31 #include "llvm/IR/IntrinsicsHexagon.h"
32 #include "llvm/IR/Metadata.h"
33 #include "llvm/InitializePasses.h"
34 #include "llvm/Pass.h"
35 #include "llvm/Support/KnownBits.h"
36 #include "llvm/Support/MathExtras.h"
37 #include "llvm/Support/raw_ostream.h"
38 #include "llvm/Target/TargetMachine.h"
39 
40 #include "HexagonSubtarget.h"
41 #include "HexagonTargetMachine.h"
42 
43 #include <algorithm>
44 #include <deque>
45 #include <map>
46 #include <set>
47 #include <utility>
48 #include <vector>
49 
50 #define DEBUG_TYPE "hexagon-vc"
51 
52 using namespace llvm;
53 
54 namespace {
55 class HexagonVectorCombine {
56 public:
57   HexagonVectorCombine(Function &F_, AliasAnalysis &AA_, AssumptionCache &AC_,
58                        DominatorTree &DT_, TargetLibraryInfo &TLI_,
59                        const TargetMachine &TM_)
60       : F(F_), DL(F.getParent()->getDataLayout()), AA(AA_), AC(AC_), DT(DT_),
61         TLI(TLI_),
62         HST(static_cast<const HexagonSubtarget &>(*TM_.getSubtargetImpl(F))) {}
63 
64   bool run();
65 
66   // Common integer type.
67   IntegerType *getIntTy() const;
68   // Byte type: either scalar (when Length = 0), or vector with given
69   // element count.
70   Type *getByteTy(int ElemCount = 0) const;
71   // Boolean type: either scalar (when Length = 0), or vector with given
72   // element count.
73   Type *getBoolTy(int ElemCount = 0) const;
74   // Create a ConstantInt of type returned by getIntTy with the value Val.
75   ConstantInt *getConstInt(int Val) const;
76   // Get the integer value of V, if it exists.
77   Optional<APInt> getIntValue(const Value *Val) const;
78   // Is V a constant 0, or a vector of 0s?
79   bool isZero(const Value *Val) const;
80   // Is V an undef value?
81   bool isUndef(const Value *Val) const;
82 
83   int getSizeOf(const Value *Val) const;
84   int getSizeOf(const Type *Ty) const;
85   int getTypeAlignment(Type *Ty) const;
86 
87   VectorType *getByteVectorTy(int ScLen) const;
88   Constant *getNullValue(Type *Ty) const;
89   Constant *getFullValue(Type *Ty) const;
90 
91   Value *insertb(IRBuilder<> &Builder, Value *Dest, Value *Src, int Start,
92                  int Length, int Where) const;
93   Value *vlalignb(IRBuilder<> &Builder, Value *Lo, Value *Hi, Value *Amt) const;
94   Value *vralignb(IRBuilder<> &Builder, Value *Lo, Value *Hi, Value *Amt) const;
95   Value *concat(IRBuilder<> &Builder, ArrayRef<Value *> Vecs) const;
96   Value *vresize(IRBuilder<> &Builder, Value *Val, int NewSize,
97                  Value *Pad) const;
98   Value *rescale(IRBuilder<> &Builder, Value *Mask, Type *FromTy,
99                  Type *ToTy) const;
100   Value *vlsb(IRBuilder<> &Builder, Value *Val) const;
101   Value *vbytes(IRBuilder<> &Builder, Value *Val) const;
102 
103   Value *createHvxIntrinsic(IRBuilder<> &Builder, Intrinsic::ID IntID,
104                             Type *RetTy, ArrayRef<Value *> Args) const;
105 
106   Optional<int> calculatePointerDifference(Value *Ptr0, Value *Ptr1) const;
107 
108   template <typename T = std::vector<Instruction *>>
109   bool isSafeToMoveBeforeInBB(const Instruction &In,
110                               BasicBlock::const_iterator To,
111                               const T &Ignore = {}) const;
112 
113   Function &F;
114   const DataLayout &DL;
115   AliasAnalysis &AA;
116   AssumptionCache &AC;
117   DominatorTree &DT;
118   TargetLibraryInfo &TLI;
119   const HexagonSubtarget &HST;
120 
121 private:
122 #ifndef NDEBUG
123   // These two functions are only used for assertions at the moment.
124   bool isByteVecTy(Type *Ty) const;
125   bool isSectorTy(Type *Ty) const;
126 #endif
127   Value *getElementRange(IRBuilder<> &Builder, Value *Lo, Value *Hi, int Start,
128                          int Length) const;
129 };
130 
131 class AlignVectors {
132 public:
133   AlignVectors(HexagonVectorCombine &HVC_) : HVC(HVC_) {}
134 
135   bool run();
136 
137 private:
138   using InstList = std::vector<Instruction *>;
139 
140   struct Segment {
141     void *Data;
142     int Start;
143     int Size;
144   };
145 
146   struct AddrInfo {
147     AddrInfo(const AddrInfo &) = default;
148     AddrInfo(const HexagonVectorCombine &HVC, Instruction *I, Value *A, Type *T,
149              Align H)
150         : Inst(I), Addr(A), ValTy(T), HaveAlign(H),
151           NeedAlign(HVC.getTypeAlignment(ValTy)) {}
152 
153     // XXX: add Size member?
154     Instruction *Inst;
155     Value *Addr;
156     Type *ValTy;
157     Align HaveAlign;
158     Align NeedAlign;
159     int Offset = 0; // Offset (in bytes) from the first member of the
160                     // containing AddrList.
161   };
162   using AddrList = std::vector<AddrInfo>;
163 
164   struct InstrLess {
165     bool operator()(const Instruction *A, const Instruction *B) const {
166       return A->comesBefore(B);
167     }
168   };
169   using DepList = std::set<Instruction *, InstrLess>;
170 
171   struct MoveGroup {
172     MoveGroup(const AddrInfo &AI, Instruction *B, bool Hvx, bool Load)
173         : Base(B), Main{AI.Inst}, IsHvx(Hvx), IsLoad(Load) {}
174     Instruction *Base; // Base instruction of the parent address group.
175     InstList Main;     // Main group of instructions.
176     InstList Deps;     // List of dependencies.
177     bool IsHvx;        // Is this group of HVX instructions?
178     bool IsLoad;       // Is this a load group?
179   };
180   using MoveList = std::vector<MoveGroup>;
181 
182   struct ByteSpan {
183     struct Segment {
184       // Segment of a Value: 'Len' bytes starting at byte 'Begin'.
185       Segment(Value *Val, int Begin, int Len)
186           : Val(Val), Start(Begin), Size(Len) {}
187       Segment(const Segment &Seg) = default;
188       Value *Val; // Value representable as a sequence of bytes.
189       int Start;  // First byte of the value that belongs to the segment.
190       int Size;   // Number of bytes in the segment.
191     };
192 
193     struct Block {
194       Block(Value *Val, int Len, int Pos) : Seg(Val, 0, Len), Pos(Pos) {}
195       Block(Value *Val, int Off, int Len, int Pos)
196           : Seg(Val, Off, Len), Pos(Pos) {}
197       Block(const Block &Blk) = default;
198       Segment Seg; // Value segment.
199       int Pos;     // Position (offset) of the segment in the Block.
200     };
201 
202     int extent() const;
203     ByteSpan section(int Start, int Length) const;
204     ByteSpan &shift(int Offset);
205     SmallVector<Value *, 8> values() const;
206 
207     int size() const { return Blocks.size(); }
208     Block &operator[](int i) { return Blocks[i]; }
209 
210     std::vector<Block> Blocks;
211 
212     using iterator = decltype(Blocks)::iterator;
213     iterator begin() { return Blocks.begin(); }
214     iterator end() { return Blocks.end(); }
215     using const_iterator = decltype(Blocks)::const_iterator;
216     const_iterator begin() const { return Blocks.begin(); }
217     const_iterator end() const { return Blocks.end(); }
218   };
219 
220   Align getAlignFromValue(const Value *V) const;
221   Optional<MemoryLocation> getLocation(const Instruction &In) const;
222   Optional<AddrInfo> getAddrInfo(Instruction &In) const;
223   bool isHvx(const AddrInfo &AI) const;
224 
225   Value *getPayload(Value *Val) const;
226   Value *getMask(Value *Val) const;
227   Value *getPassThrough(Value *Val) const;
228 
229   Value *createAdjustedPointer(IRBuilder<> &Builder, Value *Ptr, Type *ValTy,
230                                int Adjust) const;
231   Value *createAlignedPointer(IRBuilder<> &Builder, Value *Ptr, Type *ValTy,
232                               int Alignment) const;
233   Value *createAlignedLoad(IRBuilder<> &Builder, Type *ValTy, Value *Ptr,
234                            int Alignment, Value *Mask, Value *PassThru) const;
235   Value *createAlignedStore(IRBuilder<> &Builder, Value *Val, Value *Ptr,
236                             int Alignment, Value *Mask) const;
237 
238   bool createAddressGroups();
239   MoveList createLoadGroups(const AddrList &Group) const;
240   MoveList createStoreGroups(const AddrList &Group) const;
241   bool move(const MoveGroup &Move) const;
242   bool realignGroup(const MoveGroup &Move) const;
243 
244   friend raw_ostream &operator<<(raw_ostream &OS, const AddrInfo &AI);
245   friend raw_ostream &operator<<(raw_ostream &OS, const MoveGroup &MG);
246   friend raw_ostream &operator<<(raw_ostream &OS, const ByteSpan &BS);
247 
248   std::map<Instruction *, AddrList> AddrGroups;
249   HexagonVectorCombine &HVC;
250 };
251 
252 LLVM_ATTRIBUTE_UNUSED
253 raw_ostream &operator<<(raw_ostream &OS, const AlignVectors::AddrInfo &AI) {
254   OS << "Inst: " << AI.Inst << "  " << *AI.Inst << '\n';
255   OS << "Addr: " << *AI.Addr << '\n';
256   OS << "Type: " << *AI.ValTy << '\n';
257   OS << "HaveAlign: " << AI.HaveAlign.value() << '\n';
258   OS << "NeedAlign: " << AI.NeedAlign.value() << '\n';
259   OS << "Offset: " << AI.Offset;
260   return OS;
261 }
262 
263 LLVM_ATTRIBUTE_UNUSED
264 raw_ostream &operator<<(raw_ostream &OS, const AlignVectors::MoveGroup &MG) {
265   OS << "Main\n";
266   for (Instruction *I : MG.Main)
267     OS << "  " << *I << '\n';
268   OS << "Deps\n";
269   for (Instruction *I : MG.Deps)
270     OS << "  " << *I << '\n';
271   return OS;
272 }
273 
274 LLVM_ATTRIBUTE_UNUSED
275 raw_ostream &operator<<(raw_ostream &OS, const AlignVectors::ByteSpan &BS) {
276   OS << "ByteSpan[size=" << BS.size() << ", extent=" << BS.extent() << '\n';
277   for (const AlignVectors::ByteSpan::Block &B : BS) {
278     OS << "  @" << B.Pos << " [" << B.Seg.Start << ',' << B.Seg.Size << "] "
279        << *B.Seg.Val << '\n';
280   }
281   OS << ']';
282   return OS;
283 }
284 
285 } // namespace
286 
287 namespace {
288 
289 template <typename T> T *getIfUnordered(T *MaybeT) {
290   return MaybeT && MaybeT->isUnordered() ? MaybeT : nullptr;
291 }
292 template <typename T> T *isCandidate(Instruction *In) {
293   return dyn_cast<T>(In);
294 }
295 template <> LoadInst *isCandidate<LoadInst>(Instruction *In) {
296   return getIfUnordered(dyn_cast<LoadInst>(In));
297 }
298 template <> StoreInst *isCandidate<StoreInst>(Instruction *In) {
299   return getIfUnordered(dyn_cast<StoreInst>(In));
300 }
301 
302 #if !defined(_MSC_VER) || _MSC_VER >= 1926
303 // VS2017 and some versions of VS2019 have trouble compiling this:
304 // error C2976: 'std::map': too few template arguments
305 // VS 2019 16.x is known to work, except for 16.4/16.5 (MSC_VER 1924/1925)
306 template <typename Pred, typename... Ts>
307 void erase_if(std::map<Ts...> &map, Pred p)
308 #else
309 template <typename Pred, typename T, typename U>
310 void erase_if(std::map<T, U> &map, Pred p)
311 #endif
312 {
313   for (auto i = map.begin(), e = map.end(); i != e;) {
314     if (p(*i))
315       i = map.erase(i);
316     else
317       i = std::next(i);
318   }
319 }
320 
321 // Forward other erase_ifs to the LLVM implementations.
322 template <typename Pred, typename T> void erase_if(T &&container, Pred p) {
323   llvm::erase_if(std::forward<T>(container), p);
324 }
325 
326 } // namespace
327 
328 // --- Begin AlignVectors
329 
330 auto AlignVectors::ByteSpan::extent() const -> int {
331   if (size() == 0)
332     return 0;
333   int Min = Blocks[0].Pos;
334   int Max = Blocks[0].Pos + Blocks[0].Seg.Size;
335   for (int i = 1, e = size(); i != e; ++i) {
336     Min = std::min(Min, Blocks[i].Pos);
337     Max = std::max(Max, Blocks[i].Pos + Blocks[i].Seg.Size);
338   }
339   return Max - Min;
340 }
341 
342 auto AlignVectors::ByteSpan::section(int Start, int Length) const -> ByteSpan {
343   ByteSpan Section;
344   for (const ByteSpan::Block &B : Blocks) {
345     int L = std::max(B.Pos, Start);                       // Left end.
346     int R = std::min(B.Pos + B.Seg.Size, Start + Length); // Right end+1.
347     if (L < R) {
348       // How much to chop off the beginning of the segment:
349       int Off = L > B.Pos ? L - B.Pos : 0;
350       Section.Blocks.emplace_back(B.Seg.Val, B.Seg.Start + Off, R - L, L);
351     }
352   }
353   return Section;
354 }
355 
356 auto AlignVectors::ByteSpan::shift(int Offset) -> ByteSpan & {
357   for (Block &B : Blocks)
358     B.Pos += Offset;
359   return *this;
360 }
361 
362 auto AlignVectors::ByteSpan::values() const -> SmallVector<Value *, 8> {
363   SmallVector<Value *, 8> Values(Blocks.size());
364   for (int i = 0, e = Blocks.size(); i != e; ++i)
365     Values[i] = Blocks[i].Seg.Val;
366   return Values;
367 }
368 
369 auto AlignVectors::getAlignFromValue(const Value *V) const -> Align {
370   const auto *C = dyn_cast<ConstantInt>(V);
371   assert(C && "Alignment must be a compile-time constant integer");
372   return C->getAlignValue();
373 }
374 
375 auto AlignVectors::getAddrInfo(Instruction &In) const -> Optional<AddrInfo> {
376   if (auto *L = isCandidate<LoadInst>(&In))
377     return AddrInfo(HVC, L, L->getPointerOperand(), L->getType(),
378                     L->getAlign());
379   if (auto *S = isCandidate<StoreInst>(&In))
380     return AddrInfo(HVC, S, S->getPointerOperand(),
381                     S->getValueOperand()->getType(), S->getAlign());
382   if (auto *II = isCandidate<IntrinsicInst>(&In)) {
383     Intrinsic::ID ID = II->getIntrinsicID();
384     switch (ID) {
385     case Intrinsic::masked_load:
386       return AddrInfo(HVC, II, II->getArgOperand(0), II->getType(),
387                       getAlignFromValue(II->getArgOperand(1)));
388     case Intrinsic::masked_store:
389       return AddrInfo(HVC, II, II->getArgOperand(1),
390                       II->getArgOperand(0)->getType(),
391                       getAlignFromValue(II->getArgOperand(2)));
392     }
393   }
394   return Optional<AddrInfo>();
395 }
396 
397 auto AlignVectors::isHvx(const AddrInfo &AI) const -> bool {
398   return HVC.HST.isTypeForHVX(AI.ValTy);
399 }
400 
401 auto AlignVectors::getPayload(Value *Val) const -> Value * {
402   if (auto *In = dyn_cast<Instruction>(Val)) {
403     Intrinsic::ID ID = 0;
404     if (auto *II = dyn_cast<IntrinsicInst>(In))
405       ID = II->getIntrinsicID();
406     if (isa<StoreInst>(In) || ID == Intrinsic::masked_store)
407       return In->getOperand(0);
408   }
409   return Val;
410 }
411 
412 auto AlignVectors::getMask(Value *Val) const -> Value * {
413   if (auto *II = dyn_cast<IntrinsicInst>(Val)) {
414     switch (II->getIntrinsicID()) {
415     case Intrinsic::masked_load:
416       return II->getArgOperand(2);
417     case Intrinsic::masked_store:
418       return II->getArgOperand(3);
419     }
420   }
421 
422   Type *ValTy = getPayload(Val)->getType();
423   if (auto *VecTy = dyn_cast<VectorType>(ValTy)) {
424     int ElemCount = VecTy->getElementCount().getFixedValue();
425     return HVC.getFullValue(HVC.getBoolTy(ElemCount));
426   }
427   return HVC.getFullValue(HVC.getBoolTy());
428 }
429 
430 auto AlignVectors::getPassThrough(Value *Val) const -> Value * {
431   if (auto *II = dyn_cast<IntrinsicInst>(Val)) {
432     if (II->getIntrinsicID() == Intrinsic::masked_load)
433       return II->getArgOperand(3);
434   }
435   return UndefValue::get(getPayload(Val)->getType());
436 }
437 
438 auto AlignVectors::createAdjustedPointer(IRBuilder<> &Builder, Value *Ptr,
439                                          Type *ValTy, int Adjust) const
440     -> Value * {
441   // The adjustment is in bytes, but if it's a multiple of the type size,
442   // we don't need to do pointer casts.
443   Type *ElemTy = cast<PointerType>(Ptr->getType())->getElementType();
444   int ElemSize = HVC.getSizeOf(ElemTy);
445   if (Adjust % ElemSize == 0) {
446     Value *Tmp0 =
447         Builder.CreateGEP(ElemTy, Ptr, HVC.getConstInt(Adjust / ElemSize));
448     return Builder.CreatePointerCast(Tmp0, ValTy->getPointerTo());
449   }
450 
451   PointerType *CharPtrTy = Type::getInt8PtrTy(HVC.F.getContext());
452   Value *Tmp0 = Builder.CreatePointerCast(Ptr, CharPtrTy);
453   Value *Tmp1 = Builder.CreateGEP(Type::getInt8Ty(HVC.F.getContext()), Tmp0,
454                                   HVC.getConstInt(Adjust));
455   return Builder.CreatePointerCast(Tmp1, ValTy->getPointerTo());
456 }
457 
458 auto AlignVectors::createAlignedPointer(IRBuilder<> &Builder, Value *Ptr,
459                                         Type *ValTy, int Alignment) const
460     -> Value * {
461   Value *AsInt = Builder.CreatePtrToInt(Ptr, HVC.getIntTy());
462   Value *Mask = HVC.getConstInt(-Alignment);
463   Value *And = Builder.CreateAnd(AsInt, Mask);
464   return Builder.CreateIntToPtr(And, ValTy->getPointerTo());
465 }
466 
467 auto AlignVectors::createAlignedLoad(IRBuilder<> &Builder, Type *ValTy,
468                                      Value *Ptr, int Alignment, Value *Mask,
469                                      Value *PassThru) const -> Value * {
470   assert(!HVC.isUndef(Mask)); // Should this be allowed?
471   if (HVC.isZero(Mask))
472     return PassThru;
473   if (Mask == ConstantInt::getTrue(Mask->getType()))
474     return Builder.CreateAlignedLoad(ValTy, Ptr, Align(Alignment));
475   return Builder.CreateMaskedLoad(Ptr, Align(Alignment), Mask, PassThru);
476 }
477 
478 auto AlignVectors::createAlignedStore(IRBuilder<> &Builder, Value *Val,
479                                       Value *Ptr, int Alignment,
480                                       Value *Mask) const -> Value * {
481   if (HVC.isZero(Mask) || HVC.isUndef(Val) || HVC.isUndef(Mask))
482     return UndefValue::get(Val->getType());
483   if (Mask == ConstantInt::getTrue(Mask->getType()))
484     return Builder.CreateAlignedStore(Val, Ptr, Align(Alignment));
485   return Builder.CreateMaskedStore(Val, Ptr, Align(Alignment), Mask);
486 }
487 
488 auto AlignVectors::createAddressGroups() -> bool {
489   // An address group created here may contain instructions spanning
490   // multiple basic blocks.
491   AddrList WorkStack;
492 
493   auto findBaseAndOffset = [&](AddrInfo &AI) -> std::pair<Instruction *, int> {
494     for (AddrInfo &W : WorkStack) {
495       if (auto D = HVC.calculatePointerDifference(AI.Addr, W.Addr))
496         return std::make_pair(W.Inst, *D);
497     }
498     return std::make_pair(nullptr, 0);
499   };
500 
501   auto traverseBlock = [&](DomTreeNode *DomN, auto Visit) -> void {
502     BasicBlock &Block = *DomN->getBlock();
503     for (Instruction &I : Block) {
504       auto AI = this->getAddrInfo(I); // Use this-> for gcc6.
505       if (!AI)
506         continue;
507       auto F = findBaseAndOffset(*AI);
508       Instruction *GroupInst;
509       if (Instruction *BI = F.first) {
510         AI->Offset = F.second;
511         GroupInst = BI;
512       } else {
513         WorkStack.push_back(*AI);
514         GroupInst = AI->Inst;
515       }
516       AddrGroups[GroupInst].push_back(*AI);
517     }
518 
519     for (DomTreeNode *C : DomN->children())
520       Visit(C, Visit);
521 
522     while (!WorkStack.empty() && WorkStack.back().Inst->getParent() == &Block)
523       WorkStack.pop_back();
524   };
525 
526   traverseBlock(HVC.DT.getRootNode(), traverseBlock);
527   assert(WorkStack.empty());
528 
529   // AddrGroups are formed.
530 
531   // Remove groups of size 1.
532   erase_if(AddrGroups, [](auto &G) { return G.second.size() == 1; });
533   // Remove groups that don't use HVX types.
534   erase_if(AddrGroups, [&](auto &G) {
535     return !llvm::any_of(
536         G.second, [&](auto &I) { return HVC.HST.isTypeForHVX(I.ValTy); });
537   });
538 
539   return !AddrGroups.empty();
540 }
541 
542 auto AlignVectors::createLoadGroups(const AddrList &Group) const -> MoveList {
543   // Form load groups.
544   // To avoid complications with moving code across basic blocks, only form
545   // groups that are contained within a single basic block.
546 
547   auto getUpwardDeps = [](Instruction *In, Instruction *Base) {
548     BasicBlock *Parent = Base->getParent();
549     assert(In->getParent() == Parent &&
550            "Base and In should be in the same block");
551     assert(Base->comesBefore(In) && "Base should come before In");
552 
553     DepList Deps;
554     std::deque<Instruction *> WorkQ = {In};
555     while (!WorkQ.empty()) {
556       Instruction *D = WorkQ.front();
557       WorkQ.pop_front();
558       Deps.insert(D);
559       for (Value *Op : D->operands()) {
560         if (auto *I = dyn_cast<Instruction>(Op)) {
561           if (I->getParent() == Parent && Base->comesBefore(I))
562             WorkQ.push_back(I);
563         }
564       }
565     }
566     return Deps;
567   };
568 
569   auto tryAddTo = [&](const AddrInfo &Info, MoveGroup &Move) {
570     assert(!Move.Main.empty() && "Move group should have non-empty Main");
571     // Don't mix HVX and non-HVX instructions.
572     if (Move.IsHvx != isHvx(Info))
573       return false;
574     // Leading instruction in the load group.
575     Instruction *Base = Move.Main.front();
576     if (Base->getParent() != Info.Inst->getParent())
577       return false;
578 
579     auto isSafeToMoveToBase = [&](const Instruction *I) {
580       return HVC.isSafeToMoveBeforeInBB(*I, Base->getIterator());
581     };
582     DepList Deps = getUpwardDeps(Info.Inst, Base);
583     if (!llvm::all_of(Deps, isSafeToMoveToBase))
584       return false;
585 
586     // The dependencies will be moved together with the load, so make sure
587     // that none of them could be moved independently in another group.
588     Deps.erase(Info.Inst);
589     auto inAddrMap = [&](Instruction *I) { return AddrGroups.count(I) > 0; };
590     if (llvm::any_of(Deps, inAddrMap))
591       return false;
592     Move.Main.push_back(Info.Inst);
593     llvm::append_range(Move.Deps, Deps);
594     return true;
595   };
596 
597   MoveList LoadGroups;
598 
599   for (const AddrInfo &Info : Group) {
600     if (!Info.Inst->mayReadFromMemory())
601       continue;
602     if (LoadGroups.empty() || !tryAddTo(Info, LoadGroups.back()))
603       LoadGroups.emplace_back(Info, Group.front().Inst, isHvx(Info), true);
604   }
605 
606   // Erase singleton groups.
607   erase_if(LoadGroups, [](const MoveGroup &G) { return G.Main.size() <= 1; });
608   return LoadGroups;
609 }
610 
611 auto AlignVectors::createStoreGroups(const AddrList &Group) const -> MoveList {
612   // Form store groups.
613   // To avoid complications with moving code across basic blocks, only form
614   // groups that are contained within a single basic block.
615 
616   auto tryAddTo = [&](const AddrInfo &Info, MoveGroup &Move) {
617     assert(!Move.Main.empty() && "Move group should have non-empty Main");
618     // For stores with return values we'd have to collect downward depenencies.
619     // There are no such stores that we handle at the moment, so omit that.
620     assert(Info.Inst->getType()->isVoidTy() &&
621            "Not handling stores with return values");
622     // Don't mix HVX and non-HVX instructions.
623     if (Move.IsHvx != isHvx(Info))
624       return false;
625     // For stores we need to be careful whether it's safe to move them.
626     // Stores that are otherwise safe to move together may not appear safe
627     // to move over one another (i.e. isSafeToMoveBefore may return false).
628     Instruction *Base = Move.Main.front();
629     if (Base->getParent() != Info.Inst->getParent())
630       return false;
631     if (!HVC.isSafeToMoveBeforeInBB(*Info.Inst, Base->getIterator(), Move.Main))
632       return false;
633     Move.Main.push_back(Info.Inst);
634     return true;
635   };
636 
637   MoveList StoreGroups;
638 
639   for (auto I = Group.rbegin(), E = Group.rend(); I != E; ++I) {
640     const AddrInfo &Info = *I;
641     if (!Info.Inst->mayWriteToMemory())
642       continue;
643     if (StoreGroups.empty() || !tryAddTo(Info, StoreGroups.back()))
644       StoreGroups.emplace_back(Info, Group.front().Inst, isHvx(Info), false);
645   }
646 
647   // Erase singleton groups.
648   erase_if(StoreGroups, [](const MoveGroup &G) { return G.Main.size() <= 1; });
649   return StoreGroups;
650 }
651 
652 auto AlignVectors::move(const MoveGroup &Move) const -> bool {
653   assert(!Move.Main.empty() && "Move group should have non-empty Main");
654   Instruction *Where = Move.Main.front();
655 
656   if (Move.IsLoad) {
657     // Move all deps to before Where, keeping order.
658     for (Instruction *D : Move.Deps)
659       D->moveBefore(Where);
660     // Move all main instructions to after Where, keeping order.
661     ArrayRef<Instruction *> Main(Move.Main);
662     for (Instruction *M : Main.drop_front(1)) {
663       M->moveAfter(Where);
664       Where = M;
665     }
666   } else {
667     // NOTE: Deps are empty for "store" groups. If they need to be
668     // non-empty, decide on the order.
669     assert(Move.Deps.empty());
670     // Move all main instructions to before Where, inverting order.
671     ArrayRef<Instruction *> Main(Move.Main);
672     for (Instruction *M : Main.drop_front(1)) {
673       M->moveBefore(Where);
674       Where = M;
675     }
676   }
677 
678   return Move.Main.size() + Move.Deps.size() > 1;
679 }
680 
681 auto AlignVectors::realignGroup(const MoveGroup &Move) const -> bool {
682   // TODO: Needs support for masked loads/stores of "scalar" vectors.
683   if (!Move.IsHvx)
684     return false;
685 
686   // Return the element with the maximum alignment from Range,
687   // where GetValue obtains the value to compare from an element.
688   auto getMaxOf = [](auto Range, auto GetValue) {
689     return *std::max_element(
690         Range.begin(), Range.end(),
691         [&GetValue](auto &A, auto &B) { return GetValue(A) < GetValue(B); });
692   };
693 
694   const AddrList &BaseInfos = AddrGroups.at(Move.Base);
695 
696   // Conceptually, there is a vector of N bytes covering the addresses
697   // starting from the minimum offset (i.e. Base.Addr+Start). This vector
698   // represents a contiguous memory region that spans all accessed memory
699   // locations.
700   // The correspondence between loaded or stored values will be expressed
701   // in terms of this vector. For example, the 0th element of the vector
702   // from the Base address info will start at byte Start from the beginning
703   // of this conceptual vector.
704   //
705   // This vector will be loaded/stored starting at the nearest down-aligned
706   // address and the amount od the down-alignment will be AlignVal:
707   //   valign(load_vector(align_down(Base+Start)), AlignVal)
708 
709   std::set<Instruction *> TestSet(Move.Main.begin(), Move.Main.end());
710   AddrList MoveInfos;
711   llvm::copy_if(
712       BaseInfos, std::back_inserter(MoveInfos),
713       [&TestSet](const AddrInfo &AI) { return TestSet.count(AI.Inst); });
714 
715   // Maximum alignment present in the whole address group.
716   const AddrInfo &WithMaxAlign =
717       getMaxOf(BaseInfos, [](const AddrInfo &AI) { return AI.HaveAlign; });
718   Align MaxGiven = WithMaxAlign.HaveAlign;
719 
720   // Minimum alignment present in the move address group.
721   const AddrInfo &WithMinOffset =
722       getMaxOf(MoveInfos, [](const AddrInfo &AI) { return -AI.Offset; });
723 
724   const AddrInfo &WithMaxNeeded =
725       getMaxOf(MoveInfos, [](const AddrInfo &AI) { return AI.NeedAlign; });
726   Align MinNeeded = WithMaxNeeded.NeedAlign;
727 
728   // Set the builder at the top instruction in the move group.
729   Instruction *TopIn = Move.IsLoad ? Move.Main.front() : Move.Main.back();
730   IRBuilder<> Builder(TopIn);
731   Value *AlignAddr = nullptr; // Actual aligned address.
732   Value *AlignVal = nullptr;  // Right-shift amount (for valign).
733 
734   if (MinNeeded <= MaxGiven) {
735     int Start = WithMinOffset.Offset;
736     int OffAtMax = WithMaxAlign.Offset;
737     // Shift the offset of the maximally aligned instruction (OffAtMax)
738     // back by just enough multiples of the required alignment to cover the
739     // distance from Start to OffAtMax.
740     // Calculate the address adjustment amount based on the address with the
741     // maximum alignment. This is to allow a simple gep instruction instead
742     // of potential bitcasts to i8*.
743     int Adjust = -alignTo(OffAtMax - Start, MinNeeded.value());
744     AlignAddr = createAdjustedPointer(Builder, WithMaxAlign.Addr,
745                                       WithMaxAlign.ValTy, Adjust);
746     int Diff = Start - (OffAtMax + Adjust);
747     AlignVal = HVC.getConstInt(Diff);
748     // Sanity.
749     assert(Diff >= 0);
750     assert(static_cast<decltype(MinNeeded.value())>(Diff) < MinNeeded.value());
751   } else {
752     // WithMinOffset is the lowest address in the group,
753     //   WithMinOffset.Addr = Base+Start.
754     // Align instructions for both HVX (V6_valign) and scalar (S2_valignrb)
755     // mask off unnecessary bits, so it's ok to just the original pointer as
756     // the alignment amount.
757     // Do an explicit down-alignment of the address to avoid creating an
758     // aligned instruction with an address that is not really aligned.
759     AlignAddr = createAlignedPointer(Builder, WithMinOffset.Addr,
760                                      WithMinOffset.ValTy, MinNeeded.value());
761     AlignVal = Builder.CreatePtrToInt(WithMinOffset.Addr, HVC.getIntTy());
762   }
763 
764   ByteSpan VSpan;
765   for (const AddrInfo &AI : MoveInfos) {
766     VSpan.Blocks.emplace_back(AI.Inst, HVC.getSizeOf(AI.ValTy),
767                               AI.Offset - WithMinOffset.Offset);
768   }
769 
770   // The aligned loads/stores will use blocks that are either scalars,
771   // or HVX vectors. Let "sector" be the unified term for such a block.
772   // blend(scalar, vector) -> sector...
773   int ScLen = Move.IsHvx ? HVC.HST.getVectorLength()
774                          : std::max<int>(MinNeeded.value(), 4);
775   assert(!Move.IsHvx || ScLen == 64 || ScLen == 128);
776   assert(Move.IsHvx || ScLen == 4 || ScLen == 8);
777 
778   Type *SecTy = HVC.getByteTy(ScLen);
779   int NumSectors = (VSpan.extent() + ScLen - 1) / ScLen;
780   bool DoAlign = !HVC.isZero(AlignVal);
781 
782   if (Move.IsLoad) {
783     ByteSpan ASpan;
784     auto *True = HVC.getFullValue(HVC.getBoolTy(ScLen));
785     auto *Undef = UndefValue::get(SecTy);
786 
787     for (int i = 0; i != NumSectors + DoAlign; ++i) {
788       Value *Ptr = createAdjustedPointer(Builder, AlignAddr, SecTy, i * ScLen);
789       // FIXME: generate a predicated load?
790       Value *Load = createAlignedLoad(Builder, SecTy, Ptr, ScLen, True, Undef);
791       // If vector shifting is potentially needed, accumulate metadata
792       // from source sections of twice the load width.
793       int Start = (i - DoAlign) * ScLen;
794       int Width = (1 + DoAlign) * ScLen;
795       propagateMetadata(cast<Instruction>(Load),
796                         VSpan.section(Start, Width).values());
797       ASpan.Blocks.emplace_back(Load, ScLen, i * ScLen);
798     }
799 
800     if (DoAlign) {
801       for (int j = 0; j != NumSectors; ++j) {
802         ASpan[j].Seg.Val = HVC.vralignb(Builder, ASpan[j].Seg.Val,
803                                         ASpan[j + 1].Seg.Val, AlignVal);
804       }
805     }
806 
807     for (ByteSpan::Block &B : VSpan) {
808       ByteSpan ASection = ASpan.section(B.Pos, B.Seg.Size).shift(-B.Pos);
809       Value *Accum = UndefValue::get(HVC.getByteTy(B.Seg.Size));
810       for (ByteSpan::Block &S : ASection) {
811         Value *Pay = HVC.vbytes(Builder, getPayload(S.Seg.Val));
812         Accum =
813             HVC.insertb(Builder, Accum, Pay, S.Seg.Start, S.Seg.Size, S.Pos);
814       }
815       // Instead of casting everything to bytes for the vselect, cast to the
816       // original value type. This will avoid complications with casting masks.
817       // For example, in cases when the original mask applied to i32, it could
818       // be converted to a mask applicable to i8 via pred_typecast intrinsic,
819       // but if the mask is not exactly of HVX length, extra handling would be
820       // needed to make it work.
821       Type *ValTy = getPayload(B.Seg.Val)->getType();
822       Value *Cast = Builder.CreateBitCast(Accum, ValTy);
823       Value *Sel = Builder.CreateSelect(getMask(B.Seg.Val), Cast,
824                                         getPassThrough(B.Seg.Val));
825       B.Seg.Val->replaceAllUsesWith(Sel);
826     }
827   } else {
828     // Stores.
829     ByteSpan ASpanV, ASpanM;
830 
831     // Return a vector value corresponding to the input value Val:
832     // either <1 x Val> for scalar Val, or Val itself for vector Val.
833     auto MakeVec = [](IRBuilder<> &Builder, Value *Val) -> Value * {
834       Type *Ty = Val->getType();
835       if (Ty->isVectorTy())
836         return Val;
837       auto *VecTy = VectorType::get(Ty, 1, /*Scalable*/ false);
838       return Builder.CreateBitCast(Val, VecTy);
839     };
840 
841     // Create an extra "undef" sector at the beginning and at the end.
842     // They will be used as the left/right filler in the vlalign step.
843     for (int i = (DoAlign ? -1 : 0); i != NumSectors + DoAlign; ++i) {
844       // For stores, the size of each section is an aligned vector length.
845       // Adjust the store offsets relative to the section start offset.
846       ByteSpan VSection = VSpan.section(i * ScLen, ScLen).shift(-i * ScLen);
847       Value *AccumV = UndefValue::get(SecTy);
848       Value *AccumM = HVC.getNullValue(SecTy);
849       for (ByteSpan::Block &S : VSection) {
850         Value *Pay = getPayload(S.Seg.Val);
851         Value *Mask = HVC.rescale(Builder, MakeVec(Builder, getMask(S.Seg.Val)),
852                                   Pay->getType(), HVC.getByteTy());
853         AccumM = HVC.insertb(Builder, AccumM, HVC.vbytes(Builder, Mask),
854                              S.Seg.Start, S.Seg.Size, S.Pos);
855         AccumV = HVC.insertb(Builder, AccumV, HVC.vbytes(Builder, Pay),
856                              S.Seg.Start, S.Seg.Size, S.Pos);
857       }
858       ASpanV.Blocks.emplace_back(AccumV, ScLen, i * ScLen);
859       ASpanM.Blocks.emplace_back(AccumM, ScLen, i * ScLen);
860     }
861 
862     // vlalign
863     if (DoAlign) {
864       for (int j = 1; j != NumSectors + 2; ++j) {
865         ASpanV[j - 1].Seg.Val = HVC.vlalignb(Builder, ASpanV[j - 1].Seg.Val,
866                                              ASpanV[j].Seg.Val, AlignVal);
867         ASpanM[j - 1].Seg.Val = HVC.vlalignb(Builder, ASpanM[j - 1].Seg.Val,
868                                              ASpanM[j].Seg.Val, AlignVal);
869       }
870     }
871 
872     for (int i = 0; i != NumSectors + DoAlign; ++i) {
873       Value *Ptr = createAdjustedPointer(Builder, AlignAddr, SecTy, i * ScLen);
874       Value *Val = ASpanV[i].Seg.Val;
875       Value *Mask = ASpanM[i].Seg.Val; // bytes
876       if (!HVC.isUndef(Val) && !HVC.isZero(Mask)) {
877         Value *Store = createAlignedStore(Builder, Val, Ptr, ScLen,
878                                           HVC.vlsb(Builder, Mask));
879         // If vector shifting is potentially needed, accumulate metadata
880         // from source sections of twice the store width.
881         int Start = (i - DoAlign) * ScLen;
882         int Width = (1 + DoAlign) * ScLen;
883         propagateMetadata(cast<Instruction>(Store),
884                           VSpan.section(Start, Width).values());
885       }
886     }
887   }
888 
889   for (auto *Inst : Move.Main)
890     Inst->eraseFromParent();
891 
892   return true;
893 }
894 
895 auto AlignVectors::run() -> bool {
896   if (!createAddressGroups())
897     return false;
898 
899   bool Changed = false;
900   MoveList LoadGroups, StoreGroups;
901 
902   for (auto &G : AddrGroups) {
903     llvm::append_range(LoadGroups, createLoadGroups(G.second));
904     llvm::append_range(StoreGroups, createStoreGroups(G.second));
905   }
906 
907   for (auto &M : LoadGroups)
908     Changed |= move(M);
909   for (auto &M : StoreGroups)
910     Changed |= move(M);
911 
912   for (auto &M : LoadGroups)
913     Changed |= realignGroup(M);
914   for (auto &M : StoreGroups)
915     Changed |= realignGroup(M);
916 
917   return Changed;
918 }
919 
920 // --- End AlignVectors
921 
922 auto HexagonVectorCombine::run() -> bool {
923   if (!HST.useHVXOps())
924     return false;
925 
926   bool Changed = AlignVectors(*this).run();
927   return Changed;
928 }
929 
930 auto HexagonVectorCombine::getIntTy() const -> IntegerType * {
931   return Type::getInt32Ty(F.getContext());
932 }
933 
934 auto HexagonVectorCombine::getByteTy(int ElemCount) const -> Type * {
935   assert(ElemCount >= 0);
936   IntegerType *ByteTy = Type::getInt8Ty(F.getContext());
937   if (ElemCount == 0)
938     return ByteTy;
939   return VectorType::get(ByteTy, ElemCount, /*Scalable*/ false);
940 }
941 
942 auto HexagonVectorCombine::getBoolTy(int ElemCount) const -> Type * {
943   assert(ElemCount >= 0);
944   IntegerType *BoolTy = Type::getInt1Ty(F.getContext());
945   if (ElemCount == 0)
946     return BoolTy;
947   return VectorType::get(BoolTy, ElemCount, /*Scalable*/ false);
948 }
949 
950 auto HexagonVectorCombine::getConstInt(int Val) const -> ConstantInt * {
951   return ConstantInt::getSigned(getIntTy(), Val);
952 }
953 
954 auto HexagonVectorCombine::isZero(const Value *Val) const -> bool {
955   if (auto *C = dyn_cast<Constant>(Val))
956     return C->isZeroValue();
957   return false;
958 }
959 
960 auto HexagonVectorCombine::getIntValue(const Value *Val) const
961     -> Optional<APInt> {
962   if (auto *CI = dyn_cast<ConstantInt>(Val))
963     return CI->getValue();
964   return None;
965 }
966 
967 auto HexagonVectorCombine::isUndef(const Value *Val) const -> bool {
968   return isa<UndefValue>(Val);
969 }
970 
971 auto HexagonVectorCombine::getSizeOf(const Value *Val) const -> int {
972   return getSizeOf(Val->getType());
973 }
974 
975 auto HexagonVectorCombine::getSizeOf(const Type *Ty) const -> int {
976   return DL.getTypeStoreSize(const_cast<Type *>(Ty)).getFixedValue();
977 }
978 
979 auto HexagonVectorCombine::getTypeAlignment(Type *Ty) const -> int {
980   // The actual type may be shorter than the HVX vector, so determine
981   // the alignment based on subtarget info.
982   if (HST.isTypeForHVX(Ty))
983     return HST.getVectorLength();
984   return DL.getABITypeAlign(Ty).value();
985 }
986 
987 auto HexagonVectorCombine::getNullValue(Type *Ty) const -> Constant * {
988   assert(Ty->isIntOrIntVectorTy());
989   auto Zero = ConstantInt::get(Ty->getScalarType(), 0);
990   if (auto *VecTy = dyn_cast<VectorType>(Ty))
991     return ConstantVector::getSplat(VecTy->getElementCount(), Zero);
992   return Zero;
993 }
994 
995 auto HexagonVectorCombine::getFullValue(Type *Ty) const -> Constant * {
996   assert(Ty->isIntOrIntVectorTy());
997   auto Minus1 = ConstantInt::get(Ty->getScalarType(), -1);
998   if (auto *VecTy = dyn_cast<VectorType>(Ty))
999     return ConstantVector::getSplat(VecTy->getElementCount(), Minus1);
1000   return Minus1;
1001 }
1002 
1003 // Insert bytes [Start..Start+Length) of Src into Dst at byte Where.
1004 auto HexagonVectorCombine::insertb(IRBuilder<> &Builder, Value *Dst, Value *Src,
1005                                    int Start, int Length, int Where) const
1006     -> Value * {
1007   assert(isByteVecTy(Dst->getType()) && isByteVecTy(Src->getType()));
1008   int SrcLen = getSizeOf(Src);
1009   int DstLen = getSizeOf(Dst);
1010   assert(0 <= Start && Start + Length <= SrcLen);
1011   assert(0 <= Where && Where + Length <= DstLen);
1012 
1013   int P2Len = PowerOf2Ceil(SrcLen | DstLen);
1014   auto *Undef = UndefValue::get(getByteTy());
1015   Value *P2Src = vresize(Builder, Src, P2Len, Undef);
1016   Value *P2Dst = vresize(Builder, Dst, P2Len, Undef);
1017 
1018   SmallVector<int, 256> SMask(P2Len);
1019   for (int i = 0; i != P2Len; ++i) {
1020     // If i is in [Where, Where+Length), pick Src[Start+(i-Where)].
1021     // Otherwise, pick Dst[i];
1022     SMask[i] =
1023         (Where <= i && i < Where + Length) ? P2Len + Start + (i - Where) : i;
1024   }
1025 
1026   Value *P2Insert = Builder.CreateShuffleVector(P2Dst, P2Src, SMask);
1027   return vresize(Builder, P2Insert, DstLen, Undef);
1028 }
1029 
1030 auto HexagonVectorCombine::vlalignb(IRBuilder<> &Builder, Value *Lo, Value *Hi,
1031                                     Value *Amt) const -> Value * {
1032   assert(Lo->getType() == Hi->getType() && "Argument type mismatch");
1033   assert(isSectorTy(Hi->getType()));
1034   if (isZero(Amt))
1035     return Hi;
1036   int VecLen = getSizeOf(Hi);
1037   if (auto IntAmt = getIntValue(Amt))
1038     return getElementRange(Builder, Lo, Hi, VecLen - IntAmt->getSExtValue(),
1039                            VecLen);
1040 
1041   if (HST.isTypeForHVX(Hi->getType())) {
1042     int HwLen = HST.getVectorLength();
1043     assert(VecLen == HwLen && "Expecting an exact HVX type");
1044     Intrinsic::ID V6_vlalignb = HwLen == 64
1045                                     ? Intrinsic::hexagon_V6_vlalignb
1046                                     : Intrinsic::hexagon_V6_vlalignb_128B;
1047     return createHvxIntrinsic(Builder, V6_vlalignb, Hi->getType(),
1048                               {Hi, Lo, Amt});
1049   }
1050 
1051   if (VecLen == 4) {
1052     Value *Pair = concat(Builder, {Lo, Hi});
1053     Value *Shift = Builder.CreateLShr(Builder.CreateShl(Pair, Amt), 32);
1054     Value *Trunc = Builder.CreateTrunc(Shift, Type::getInt32Ty(F.getContext()));
1055     return Builder.CreateBitCast(Trunc, Hi->getType());
1056   }
1057   if (VecLen == 8) {
1058     Value *Sub = Builder.CreateSub(getConstInt(VecLen), Amt);
1059     return vralignb(Builder, Lo, Hi, Sub);
1060   }
1061   llvm_unreachable("Unexpected vector length");
1062 }
1063 
1064 auto HexagonVectorCombine::vralignb(IRBuilder<> &Builder, Value *Lo, Value *Hi,
1065                                     Value *Amt) const -> Value * {
1066   assert(Lo->getType() == Hi->getType() && "Argument type mismatch");
1067   assert(isSectorTy(Lo->getType()));
1068   if (isZero(Amt))
1069     return Lo;
1070   int VecLen = getSizeOf(Lo);
1071   if (auto IntAmt = getIntValue(Amt))
1072     return getElementRange(Builder, Lo, Hi, IntAmt->getSExtValue(), VecLen);
1073 
1074   if (HST.isTypeForHVX(Lo->getType())) {
1075     int HwLen = HST.getVectorLength();
1076     assert(VecLen == HwLen && "Expecting an exact HVX type");
1077     Intrinsic::ID V6_valignb = HwLen == 64 ? Intrinsic::hexagon_V6_valignb
1078                                            : Intrinsic::hexagon_V6_valignb_128B;
1079     return createHvxIntrinsic(Builder, V6_valignb, Lo->getType(),
1080                               {Hi, Lo, Amt});
1081   }
1082 
1083   if (VecLen == 4) {
1084     Value *Pair = concat(Builder, {Lo, Hi});
1085     Value *Shift = Builder.CreateLShr(Pair, Amt);
1086     Value *Trunc = Builder.CreateTrunc(Shift, Type::getInt32Ty(F.getContext()));
1087     return Builder.CreateBitCast(Trunc, Lo->getType());
1088   }
1089   if (VecLen == 8) {
1090     Type *Int64Ty = Type::getInt64Ty(F.getContext());
1091     Value *Lo64 = Builder.CreateBitCast(Lo, Int64Ty);
1092     Value *Hi64 = Builder.CreateBitCast(Hi, Int64Ty);
1093     Function *FI = Intrinsic::getDeclaration(F.getParent(),
1094                                              Intrinsic::hexagon_S2_valignrb);
1095     Value *Call = Builder.CreateCall(FI, {Hi64, Lo64, Amt});
1096     return Builder.CreateBitCast(Call, Lo->getType());
1097   }
1098   llvm_unreachable("Unexpected vector length");
1099 }
1100 
1101 // Concatenates a sequence of vectors of the same type.
1102 auto HexagonVectorCombine::concat(IRBuilder<> &Builder,
1103                                   ArrayRef<Value *> Vecs) const -> Value * {
1104   assert(!Vecs.empty());
1105   SmallVector<int, 256> SMask;
1106   std::vector<Value *> Work[2];
1107   int ThisW = 0, OtherW = 1;
1108 
1109   Work[ThisW].assign(Vecs.begin(), Vecs.end());
1110   while (Work[ThisW].size() > 1) {
1111     auto *Ty = cast<VectorType>(Work[ThisW].front()->getType());
1112     int ElemCount = Ty->getElementCount().getFixedValue();
1113     SMask.resize(ElemCount * 2);
1114     std::iota(SMask.begin(), SMask.end(), 0);
1115 
1116     Work[OtherW].clear();
1117     if (Work[ThisW].size() % 2 != 0)
1118       Work[ThisW].push_back(UndefValue::get(Ty));
1119     for (int i = 0, e = Work[ThisW].size(); i < e; i += 2) {
1120       Value *Joined = Builder.CreateShuffleVector(Work[ThisW][i],
1121                                                   Work[ThisW][i + 1], SMask);
1122       Work[OtherW].push_back(Joined);
1123     }
1124     std::swap(ThisW, OtherW);
1125   }
1126 
1127   // Since there may have been some undefs appended to make shuffle operands
1128   // have the same type, perform the last shuffle to only pick the original
1129   // elements.
1130   SMask.resize(Vecs.size() * getSizeOf(Vecs.front()->getType()));
1131   std::iota(SMask.begin(), SMask.end(), 0);
1132   Value *Total = Work[OtherW].front();
1133   return Builder.CreateShuffleVector(Total, SMask);
1134 }
1135 
1136 auto HexagonVectorCombine::vresize(IRBuilder<> &Builder, Value *Val,
1137                                    int NewSize, Value *Pad) const -> Value * {
1138   assert(isa<VectorType>(Val->getType()));
1139   auto *ValTy = cast<VectorType>(Val->getType());
1140   assert(ValTy->getElementType() == Pad->getType());
1141 
1142   int CurSize = ValTy->getElementCount().getFixedValue();
1143   if (CurSize == NewSize)
1144     return Val;
1145   // Truncate?
1146   if (CurSize > NewSize)
1147     return getElementRange(Builder, Val, /*Unused*/ Val, 0, NewSize);
1148   // Extend.
1149   SmallVector<int, 128> SMask(NewSize);
1150   std::iota(SMask.begin(), SMask.begin() + CurSize, 0);
1151   std::fill(SMask.begin() + CurSize, SMask.end(), CurSize);
1152   Value *PadVec = Builder.CreateVectorSplat(CurSize, Pad);
1153   return Builder.CreateShuffleVector(Val, PadVec, SMask);
1154 }
1155 
1156 auto HexagonVectorCombine::rescale(IRBuilder<> &Builder, Value *Mask,
1157                                    Type *FromTy, Type *ToTy) const -> Value * {
1158   // Mask is a vector <N x i1>, where each element corresponds to an
1159   // element of FromTy. Remap it so that each element will correspond
1160   // to an element of ToTy.
1161   assert(isa<VectorType>(Mask->getType()));
1162 
1163   Type *FromSTy = FromTy->getScalarType();
1164   Type *ToSTy = ToTy->getScalarType();
1165   if (FromSTy == ToSTy)
1166     return Mask;
1167 
1168   int FromSize = getSizeOf(FromSTy);
1169   int ToSize = getSizeOf(ToSTy);
1170   assert(FromSize % ToSize == 0 || ToSize % FromSize == 0);
1171 
1172   auto *MaskTy = cast<VectorType>(Mask->getType());
1173   int FromCount = MaskTy->getElementCount().getFixedValue();
1174   int ToCount = (FromCount * FromSize) / ToSize;
1175   assert((FromCount * FromSize) % ToSize == 0);
1176 
1177   // Mask <N x i1> -> sext to <N x FromTy> -> bitcast to <M x ToTy> ->
1178   // -> trunc to <M x i1>.
1179   Value *Ext = Builder.CreateSExt(
1180       Mask, VectorType::get(FromSTy, FromCount, /*Scalable*/ false));
1181   Value *Cast = Builder.CreateBitCast(
1182       Ext, VectorType::get(ToSTy, ToCount, /*Scalable*/ false));
1183   return Builder.CreateTrunc(
1184       Cast, VectorType::get(getBoolTy(), ToCount, /*Scalable*/ false));
1185 }
1186 
1187 // Bitcast to bytes, and return least significant bits.
1188 auto HexagonVectorCombine::vlsb(IRBuilder<> &Builder, Value *Val) const
1189     -> Value * {
1190   Type *ScalarTy = Val->getType()->getScalarType();
1191   if (ScalarTy == getBoolTy())
1192     return Val;
1193 
1194   Value *Bytes = vbytes(Builder, Val);
1195   if (auto *VecTy = dyn_cast<VectorType>(Bytes->getType()))
1196     return Builder.CreateTrunc(Bytes, getBoolTy(getSizeOf(VecTy)));
1197   // If Bytes is a scalar (i.e. Val was a scalar byte), return i1, not
1198   // <1 x i1>.
1199   return Builder.CreateTrunc(Bytes, getBoolTy());
1200 }
1201 
1202 // Bitcast to bytes for non-bool. For bool, convert i1 -> i8.
1203 auto HexagonVectorCombine::vbytes(IRBuilder<> &Builder, Value *Val) const
1204     -> Value * {
1205   Type *ScalarTy = Val->getType()->getScalarType();
1206   if (ScalarTy == getByteTy())
1207     return Val;
1208 
1209   if (ScalarTy != getBoolTy())
1210     return Builder.CreateBitCast(Val, getByteTy(getSizeOf(Val)));
1211   // For bool, return a sext from i1 to i8.
1212   if (auto *VecTy = dyn_cast<VectorType>(Val->getType()))
1213     return Builder.CreateSExt(Val, VectorType::get(getByteTy(), VecTy));
1214   return Builder.CreateSExt(Val, getByteTy());
1215 }
1216 
1217 auto HexagonVectorCombine::createHvxIntrinsic(IRBuilder<> &Builder,
1218                                               Intrinsic::ID IntID, Type *RetTy,
1219                                               ArrayRef<Value *> Args) const
1220     -> Value * {
1221   int HwLen = HST.getVectorLength();
1222   Type *BoolTy = Type::getInt1Ty(F.getContext());
1223   Type *Int32Ty = Type::getInt32Ty(F.getContext());
1224   // HVX vector -> v16i32/v32i32
1225   // HVX vector predicate -> v512i1/v1024i1
1226   auto getTypeForIntrin = [&](Type *Ty) -> Type * {
1227     if (HST.isTypeForHVX(Ty, /*IncludeBool*/ true)) {
1228       Type *ElemTy = cast<VectorType>(Ty)->getElementType();
1229       if (ElemTy == Int32Ty)
1230         return Ty;
1231       if (ElemTy == BoolTy)
1232         return VectorType::get(BoolTy, 8 * HwLen, /*Scalable*/ false);
1233       return VectorType::get(Int32Ty, HwLen / 4, /*Scalable*/ false);
1234     }
1235     // Non-HVX type. It should be a scalar.
1236     assert(Ty == Int32Ty || Ty->isIntegerTy(64));
1237     return Ty;
1238   };
1239 
1240   auto getCast = [&](IRBuilder<> &Builder, Value *Val,
1241                      Type *DestTy) -> Value * {
1242     Type *SrcTy = Val->getType();
1243     if (SrcTy == DestTy)
1244       return Val;
1245     if (HST.isTypeForHVX(SrcTy, /*IncludeBool*/ true)) {
1246       if (cast<VectorType>(SrcTy)->getElementType() == BoolTy) {
1247         // This should take care of casts the other way too, for example
1248         // v1024i1 -> v32i1.
1249         Intrinsic::ID TC = HwLen == 64
1250                                ? Intrinsic::hexagon_V6_pred_typecast
1251                                : Intrinsic::hexagon_V6_pred_typecast_128B;
1252         Function *FI = Intrinsic::getDeclaration(F.getParent(), TC,
1253                                                  {DestTy, Val->getType()});
1254         return Builder.CreateCall(FI, {Val});
1255       }
1256       // Non-predicate HVX vector.
1257       return Builder.CreateBitCast(Val, DestTy);
1258     }
1259     // Non-HVX type. It should be a scalar, and it should already have
1260     // a valid type.
1261     llvm_unreachable("Unexpected type");
1262   };
1263 
1264   SmallVector<Value *, 4> IntOps;
1265   for (Value *A : Args)
1266     IntOps.push_back(getCast(Builder, A, getTypeForIntrin(A->getType())));
1267   Function *FI = Intrinsic::getDeclaration(F.getParent(), IntID);
1268   Value *Call = Builder.CreateCall(FI, IntOps);
1269 
1270   Type *CallTy = Call->getType();
1271   if (CallTy == RetTy)
1272     return Call;
1273   // Scalar types should have RetTy matching the call return type.
1274   assert(HST.isTypeForHVX(CallTy, /*IncludeBool*/ true));
1275   if (cast<VectorType>(CallTy)->getElementType() == BoolTy)
1276     return getCast(Builder, Call, RetTy);
1277   return Builder.CreateBitCast(Call, RetTy);
1278 }
1279 
1280 auto HexagonVectorCombine::calculatePointerDifference(Value *Ptr0,
1281                                                       Value *Ptr1) const
1282     -> Optional<int> {
1283   struct Builder : IRBuilder<> {
1284     Builder(BasicBlock *B) : IRBuilder<>(B) {}
1285     ~Builder() {
1286       for (Instruction *I : llvm::reverse(ToErase))
1287         I->eraseFromParent();
1288     }
1289     SmallVector<Instruction *, 8> ToErase;
1290   };
1291 
1292 #define CallBuilder(B, F)                                                      \
1293   [&](auto &B_) {                                                              \
1294     Value *V = B_.F;                                                           \
1295     if (auto *I = dyn_cast<Instruction>(V))                                    \
1296       B_.ToErase.push_back(I);                                                 \
1297     return V;                                                                  \
1298   }(B)
1299 
1300   auto Simplify = [&](Value *V) {
1301     if (auto *I = dyn_cast<Instruction>(V)) {
1302       SimplifyQuery Q(DL, &TLI, &DT, &AC, I);
1303       if (Value *S = SimplifyInstruction(I, Q))
1304         return S;
1305     }
1306     return V;
1307   };
1308 
1309   auto StripBitCast = [](Value *V) {
1310     while (auto *C = dyn_cast<BitCastInst>(V))
1311       V = C->getOperand(0);
1312     return V;
1313   };
1314 
1315   Ptr0 = StripBitCast(Ptr0);
1316   Ptr1 = StripBitCast(Ptr1);
1317   if (!isa<GetElementPtrInst>(Ptr0) || !isa<GetElementPtrInst>(Ptr1))
1318     return None;
1319 
1320   auto *Gep0 = cast<GetElementPtrInst>(Ptr0);
1321   auto *Gep1 = cast<GetElementPtrInst>(Ptr1);
1322   if (Gep0->getPointerOperand() != Gep1->getPointerOperand())
1323     return None;
1324 
1325   Builder B(Gep0->getParent());
1326   int Scale = DL.getTypeStoreSize(Gep0->getSourceElementType());
1327 
1328   // FIXME: for now only check GEPs with a single index.
1329   if (Gep0->getNumOperands() != 2 || Gep1->getNumOperands() != 2)
1330     return None;
1331 
1332   Value *Idx0 = Gep0->getOperand(1);
1333   Value *Idx1 = Gep1->getOperand(1);
1334 
1335   // First, try to simplify the subtraction directly.
1336   if (auto *Diff = dyn_cast<ConstantInt>(
1337           Simplify(CallBuilder(B, CreateSub(Idx0, Idx1)))))
1338     return Diff->getSExtValue() * Scale;
1339 
1340   KnownBits Known0 = computeKnownBits(Idx0, DL, 0, &AC, Gep0, &DT);
1341   KnownBits Known1 = computeKnownBits(Idx1, DL, 0, &AC, Gep1, &DT);
1342   APInt Unknown = ~(Known0.Zero | Known0.One) | ~(Known1.Zero | Known1.One);
1343   if (Unknown.isAllOnesValue())
1344     return None;
1345 
1346   Value *MaskU = ConstantInt::get(Idx0->getType(), Unknown);
1347   Value *AndU0 = Simplify(CallBuilder(B, CreateAnd(Idx0, MaskU)));
1348   Value *AndU1 = Simplify(CallBuilder(B, CreateAnd(Idx1, MaskU)));
1349   Value *SubU = Simplify(CallBuilder(B, CreateSub(AndU0, AndU1)));
1350   int Diff0 = 0;
1351   if (auto *C = dyn_cast<ConstantInt>(SubU)) {
1352     Diff0 = C->getSExtValue();
1353   } else {
1354     return None;
1355   }
1356 
1357   Value *MaskK = ConstantInt::get(MaskU->getType(), ~Unknown);
1358   Value *AndK0 = Simplify(CallBuilder(B, CreateAnd(Idx0, MaskK)));
1359   Value *AndK1 = Simplify(CallBuilder(B, CreateAnd(Idx1, MaskK)));
1360   Value *SubK = Simplify(CallBuilder(B, CreateSub(AndK0, AndK1)));
1361   int Diff1 = 0;
1362   if (auto *C = dyn_cast<ConstantInt>(SubK)) {
1363     Diff1 = C->getSExtValue();
1364   } else {
1365     return None;
1366   }
1367 
1368   return (Diff0 + Diff1) * Scale;
1369 
1370 #undef CallBuilder
1371 }
1372 
1373 template <typename T>
1374 auto HexagonVectorCombine::isSafeToMoveBeforeInBB(const Instruction &In,
1375                                                   BasicBlock::const_iterator To,
1376                                                   const T &Ignore) const
1377     -> bool {
1378   auto getLocOrNone = [this](const Instruction &I) -> Optional<MemoryLocation> {
1379     if (const auto *II = dyn_cast<IntrinsicInst>(&I)) {
1380       switch (II->getIntrinsicID()) {
1381       case Intrinsic::masked_load:
1382         return MemoryLocation::getForArgument(II, 0, TLI);
1383       case Intrinsic::masked_store:
1384         return MemoryLocation::getForArgument(II, 1, TLI);
1385       }
1386     }
1387     return MemoryLocation::getOrNone(&I);
1388   };
1389 
1390   // The source and the destination must be in the same basic block.
1391   const BasicBlock &Block = *In.getParent();
1392   assert(Block.begin() == To || Block.end() == To || To->getParent() == &Block);
1393   // No PHIs.
1394   if (isa<PHINode>(In) || (To != Block.end() && isa<PHINode>(*To)))
1395     return false;
1396 
1397   if (!mayBeMemoryDependent(In))
1398     return true;
1399   bool MayWrite = In.mayWriteToMemory();
1400   auto MaybeLoc = getLocOrNone(In);
1401 
1402   auto From = In.getIterator();
1403   if (From == To)
1404     return true;
1405   bool MoveUp = (To != Block.end() && To->comesBefore(&In));
1406   auto Range =
1407       MoveUp ? std::make_pair(To, From) : std::make_pair(std::next(From), To);
1408   for (auto It = Range.first; It != Range.second; ++It) {
1409     const Instruction &I = *It;
1410     if (llvm::is_contained(Ignore, &I))
1411       continue;
1412     // assume intrinsic can be ignored
1413     if (auto *II = dyn_cast<IntrinsicInst>(&I)) {
1414       if (II->getIntrinsicID() == Intrinsic::assume)
1415         continue;
1416     }
1417     // Parts based on isSafeToMoveBefore from CoveMoverUtils.cpp.
1418     if (I.mayThrow())
1419       return false;
1420     if (auto *CB = dyn_cast<CallBase>(&I)) {
1421       if (!CB->hasFnAttr(Attribute::WillReturn))
1422         return false;
1423       if (!CB->hasFnAttr(Attribute::NoSync))
1424         return false;
1425     }
1426     if (I.mayReadOrWriteMemory()) {
1427       auto MaybeLocI = getLocOrNone(I);
1428       if (MayWrite || I.mayWriteToMemory()) {
1429         if (!MaybeLoc || !MaybeLocI)
1430           return false;
1431         if (!AA.isNoAlias(*MaybeLoc, *MaybeLocI))
1432           return false;
1433       }
1434     }
1435   }
1436   return true;
1437 }
1438 
1439 #ifndef NDEBUG
1440 auto HexagonVectorCombine::isByteVecTy(Type *Ty) const -> bool {
1441   if (auto *VecTy = dyn_cast<VectorType>(Ty))
1442     return VecTy->getElementType() == getByteTy();
1443   return false;
1444 }
1445 
1446 auto HexagonVectorCombine::isSectorTy(Type *Ty) const -> bool {
1447   if (!isByteVecTy(Ty))
1448     return false;
1449   int Size = getSizeOf(Ty);
1450   if (HST.isTypeForHVX(Ty))
1451     return Size == static_cast<int>(HST.getVectorLength());
1452   return Size == 4 || Size == 8;
1453 }
1454 #endif
1455 
1456 auto HexagonVectorCombine::getElementRange(IRBuilder<> &Builder, Value *Lo,
1457                                            Value *Hi, int Start,
1458                                            int Length) const -> Value * {
1459   assert(0 <= Start && Start < Length);
1460   SmallVector<int, 128> SMask(Length);
1461   std::iota(SMask.begin(), SMask.end(), Start);
1462   return Builder.CreateShuffleVector(Lo, Hi, SMask);
1463 }
1464 
1465 // Pass management.
1466 
1467 namespace llvm {
1468 void initializeHexagonVectorCombineLegacyPass(PassRegistry &);
1469 FunctionPass *createHexagonVectorCombineLegacyPass();
1470 } // namespace llvm
1471 
1472 namespace {
1473 class HexagonVectorCombineLegacy : public FunctionPass {
1474 public:
1475   static char ID;
1476 
1477   HexagonVectorCombineLegacy() : FunctionPass(ID) {}
1478 
1479   StringRef getPassName() const override { return "Hexagon Vector Combine"; }
1480 
1481   void getAnalysisUsage(AnalysisUsage &AU) const override {
1482     AU.setPreservesCFG();
1483     AU.addRequired<AAResultsWrapperPass>();
1484     AU.addRequired<AssumptionCacheTracker>();
1485     AU.addRequired<DominatorTreeWrapperPass>();
1486     AU.addRequired<TargetLibraryInfoWrapperPass>();
1487     AU.addRequired<TargetPassConfig>();
1488     FunctionPass::getAnalysisUsage(AU);
1489   }
1490 
1491   bool runOnFunction(Function &F) override {
1492     if (skipFunction(F))
1493       return false;
1494     AliasAnalysis &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
1495     AssumptionCache &AC =
1496         getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
1497     DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1498     TargetLibraryInfo &TLI =
1499         getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
1500     auto &TM = getAnalysis<TargetPassConfig>().getTM<HexagonTargetMachine>();
1501     HexagonVectorCombine HVC(F, AA, AC, DT, TLI, TM);
1502     return HVC.run();
1503   }
1504 };
1505 } // namespace
1506 
1507 char HexagonVectorCombineLegacy::ID = 0;
1508 
1509 INITIALIZE_PASS_BEGIN(HexagonVectorCombineLegacy, DEBUG_TYPE,
1510                       "Hexagon Vector Combine", false, false)
1511 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
1512 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
1513 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
1514 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
1515 INITIALIZE_PASS_DEPENDENCY(TargetPassConfig)
1516 INITIALIZE_PASS_END(HexagonVectorCombineLegacy, DEBUG_TYPE,
1517                     "Hexagon Vector Combine", false, false)
1518 
1519 FunctionPass *llvm::createHexagonVectorCombineLegacyPass() {
1520   return new HexagonVectorCombineLegacy();
1521 }
1522