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