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