blob: 835b088050ec7dd21485b61d6126712b066518ae [file] [log] [blame]
Krzysztof Parzyszek7d37dd82017-12-06 16:40:37 +00001//===-- HexagonISelDAGToDAGHVX.cpp ----------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "Hexagon.h"
11#include "HexagonISelDAGToDAG.h"
12#include "HexagonISelLowering.h"
13#include "HexagonTargetMachine.h"
14#include "llvm/CodeGen/MachineInstrBuilder.h"
15#include "llvm/CodeGen/SelectionDAGISel.h"
16#include "llvm/IR/Intrinsics.h"
17#include "llvm/Support/CommandLine.h"
18#include "llvm/Support/Debug.h"
19
20#include <deque>
21#include <map>
22#include <set>
23#include <utility>
24#include <vector>
25
26#define DEBUG_TYPE "hexagon-isel"
27
28using namespace llvm;
29
30// --------------------------------------------------------------------
31// Implementation of permutation networks.
32
33// Implementation of the node routing through butterfly networks:
34// - Forward delta.
35// - Reverse delta.
36// - Benes.
37//
38//
39// Forward delta network consists of log(N) steps, where N is the number
40// of inputs. In each step, an input can stay in place, or it can get
41// routed to another position[1]. The step after that consists of two
42// networks, each half in size in terms of the number of nodes. In those
43// terms, in the given step, an input can go to either the upper or the
44// lower network in the next step.
45//
46// [1] Hexagon's vdelta/vrdelta allow an element to be routed to both
47// positions as long as there is no conflict.
48
49// Here's a delta network for 8 inputs, only the switching routes are
50// shown:
51//
52// Steps:
53// |- 1 ---------------|- 2 -----|- 3 -|
54//
55// Inp[0] *** *** *** *** Out[0]
56// \ / \ / \ /
57// \ / \ / X
58// \ / \ / / \
59// Inp[1] *** \ / *** X *** *** Out[1]
60// \ \ / / \ / \ /
61// \ \ / / X X
62// \ \ / / / \ / \
63// Inp[2] *** \ \ / / *** X *** *** Out[2]
64// \ \ X / / / \ \ /
65// \ \ / \ / / / \ X
66// \ X X / / \ / \
67// Inp[3] *** \ / \ / \ / *** *** *** Out[3]
68// \ X X X /
69// \ / \ / \ / \ /
70// X X X X
71// / \ / \ / \ / \
72// / X X X \
73// Inp[4] *** / \ / \ / \ *** *** *** Out[4]
74// / X X \ \ / \ /
75// / / \ / \ \ \ / X
76// / / X \ \ \ / / \
77// Inp[5] *** / / \ \ *** X *** *** Out[5]
78// / / \ \ \ / \ /
79// / / \ \ X X
80// / / \ \ / \ / \
81// Inp[6] *** / \ *** X *** *** Out[6]
82// / \ / \ \ /
83// / \ / \ X
84// / \ / \ / \
85// Inp[7] *** *** *** *** Out[7]
86//
87//
88// Reverse delta network is same as delta network, with the steps in
89// the opposite order.
90//
91//
92// Benes network is a forward delta network immediately followed by
93// a reverse delta network.
94
95
96// Graph coloring utility used to partition nodes into two groups:
97// they will correspond to nodes routed to the upper and lower networks.
98struct Coloring {
99 enum : uint8_t {
100 None = 0,
101 Red,
102 Black
103 };
104
105 using Node = int;
106 using MapType = std::map<Node,uint8_t>;
107 static constexpr Node Ignore = Node(-1);
108
109 Coloring(ArrayRef<Node> Ord) : Order(Ord) {
110 build();
111 if (!color())
112 Colors.clear();
113 }
114
115 const MapType &colors() const {
116 return Colors;
117 }
118
119 uint8_t other(uint8_t Color) {
120 if (Color == None)
121 return Red;
122 return Color == Red ? Black : Red;
123 }
124
125 void dump() const;
126
127private:
128 ArrayRef<Node> Order;
129 MapType Colors;
130 std::set<Node> Needed;
131
132 using NodeSet = std::set<Node>;
133 std::map<Node,NodeSet> Edges;
134
135 Node conj(Node Pos) {
136 Node Num = Order.size();
137 return (Pos < Num/2) ? Pos + Num/2 : Pos - Num/2;
138 }
139
140 uint8_t getColor(Node N) {
141 auto F = Colors.find(N);
142 return F != Colors.end() ? F->second : None;
143 }
144
145 std::pair<bool,uint8_t> getUniqueColor(const NodeSet &Nodes);
146
147 void build();
148 bool color();
149};
150
151std::pair<bool,uint8_t> Coloring::getUniqueColor(const NodeSet &Nodes) {
152 uint8_t Color = None;
153 for (Node N : Nodes) {
154 uint8_t ColorN = getColor(N);
155 if (ColorN == None)
156 continue;
157 if (Color == None)
158 Color = ColorN;
159 else if (Color != None && Color != ColorN)
160 return { false, None };
161 }
162 return { true, Color };
163}
164
165void Coloring::build() {
166 // Add Order[P] and Order[conj(P)] to Edges.
167 for (unsigned P = 0; P != Order.size(); ++P) {
168 Node I = Order[P];
169 if (I != Ignore) {
170 Needed.insert(I);
171 Node PC = Order[conj(P)];
172 if (PC != Ignore && PC != I)
173 Edges[I].insert(PC);
174 }
175 }
176 // Add I and conj(I) to Edges.
177 for (unsigned I = 0; I != Order.size(); ++I) {
178 if (!Needed.count(I))
179 continue;
180 Node C = conj(I);
181 // This will create an entry in the edge table, even if I is not
182 // connected to any other node. This is necessary, because it still
183 // needs to be colored.
184 NodeSet &Is = Edges[I];
185 if (Needed.count(C))
186 Is.insert(C);
187 }
188}
189
190bool Coloring::color() {
191 SetVector<Node> FirstQ;
192 auto Enqueue = [this,&FirstQ] (Node N) {
193 SetVector<Node> Q;
194 Q.insert(N);
195 for (unsigned I = 0; I != Q.size(); ++I) {
196 NodeSet &Ns = Edges[Q[I]];
197 Q.insert(Ns.begin(), Ns.end());
198 }
199 FirstQ.insert(Q.begin(), Q.end());
200 };
201 for (Node N : Needed)
202 Enqueue(N);
203
204 for (Node N : FirstQ) {
205 if (Colors.count(N))
206 continue;
207 NodeSet &Ns = Edges[N];
208 auto P = getUniqueColor(Ns);
209 if (!P.first)
210 return false;
211 Colors[N] = other(P.second);
212 }
213
214 // First, color nodes that don't have any dups.
215 for (auto E : Edges) {
216 Node N = E.first;
217 if (!Needed.count(conj(N)) || Colors.count(N))
218 continue;
219 auto P = getUniqueColor(E.second);
220 if (!P.first)
221 return false;
222 Colors[N] = other(P.second);
223 }
224
225 // Now, nodes that are still uncolored. Since the graph can be modified
226 // in this step, create a work queue.
227 std::vector<Node> WorkQ;
228 for (auto E : Edges) {
229 Node N = E.first;
230 if (!Colors.count(N))
231 WorkQ.push_back(N);
232 }
233
234 for (unsigned I = 0; I < WorkQ.size(); ++I) {
235 Node N = WorkQ[I];
236 NodeSet &Ns = Edges[N];
237 auto P = getUniqueColor(Ns);
238 if (P.first) {
239 Colors[N] = other(P.second);
240 continue;
241 }
242
243 // Coloring failed. Split this node.
244 Node C = conj(N);
245 uint8_t ColorN = other(None);
246 uint8_t ColorC = other(ColorN);
247 NodeSet &Cs = Edges[C];
248 NodeSet CopyNs = Ns;
249 for (Node M : CopyNs) {
250 uint8_t ColorM = getColor(M);
251 if (ColorM == ColorC) {
252 // Connect M with C, disconnect M from N.
253 Cs.insert(M);
254 Edges[M].insert(C);
255 Ns.erase(M);
256 Edges[M].erase(N);
257 }
258 }
259 Colors[N] = ColorN;
260 Colors[C] = ColorC;
261 }
262
263 // Explicitly assign "None" all all uncolored nodes.
264 for (unsigned I = 0; I != Order.size(); ++I)
265 if (Colors.count(I) == 0)
266 Colors[I] = None;
267
268 return true;
269}
270
271LLVM_DUMP_METHOD
272void Coloring::dump() const {
273 dbgs() << "{ Order: {";
274 for (unsigned I = 0; I != Order.size(); ++I) {
275 Node P = Order[I];
276 if (P != Ignore)
277 dbgs() << ' ' << P;
278 else
279 dbgs() << " -";
280 }
281 dbgs() << " }\n";
282 dbgs() << " Needed: {";
283 for (Node N : Needed)
284 dbgs() << ' ' << N;
285 dbgs() << " }\n";
286
287 dbgs() << " Edges: {\n";
288 for (auto E : Edges) {
289 dbgs() << " " << E.first << " -> {";
290 for (auto N : E.second)
291 dbgs() << ' ' << N;
292 dbgs() << " }\n";
293 }
294 dbgs() << " }\n";
295
296 static const char *const Names[] = { "None", "Red", "Black" };
297 dbgs() << " Colors: {\n";
298 for (auto C : Colors)
299 dbgs() << " " << C.first << " -> " << Names[C.second] << "\n";
300 dbgs() << " }\n}\n";
301}
302
303// Base class of for reordering networks. They don't strictly need to be
304// permutations, as outputs with repeated occurrences of an input element
305// are allowed.
306struct PermNetwork {
307 using Controls = std::vector<uint8_t>;
308 using ElemType = int;
309 static constexpr ElemType Ignore = ElemType(-1);
310
311 enum : uint8_t {
312 None,
313 Pass,
314 Switch
315 };
316 enum : uint8_t {
317 Forward,
318 Reverse
319 };
320
321 PermNetwork(ArrayRef<ElemType> Ord, unsigned Mult = 1) {
322 Order.assign(Ord.data(), Ord.data()+Ord.size());
323 Log = 0;
324
325 unsigned S = Order.size();
326 while (S >>= 1)
327 ++Log;
328
329 Table.resize(Order.size());
330 for (RowType &Row : Table)
331 Row.resize(Mult*Log, None);
332 }
333
334 void getControls(Controls &V, unsigned StartAt, uint8_t Dir) const {
335 unsigned Size = Order.size();
336 V.resize(Size);
337 for (unsigned I = 0; I != Size; ++I) {
338 unsigned W = 0;
339 for (unsigned L = 0; L != Log; ++L) {
340 unsigned C = ctl(I, StartAt+L) == Switch;
341 if (Dir == Forward)
342 W |= C << (Log-1-L);
343 else
344 W |= C << L;
345 }
346 assert(isUInt<8>(W));
347 V[I] = uint8_t(W);
348 }
349 }
350
351 uint8_t ctl(ElemType Pos, unsigned Step) const {
352 return Table[Pos][Step];
353 }
354 unsigned size() const {
355 return Order.size();
356 }
357 unsigned steps() const {
358 return Log;
359 }
360
361protected:
362 unsigned Log;
363 std::vector<ElemType> Order;
364 using RowType = std::vector<uint8_t>;
365 std::vector<RowType> Table;
366};
367
368struct ForwardDeltaNetwork : public PermNetwork {
369 ForwardDeltaNetwork(ArrayRef<ElemType> Ord) : PermNetwork(Ord) {}
370
371 bool run(Controls &V) {
372 if (!route(Order.data(), Table.data(), size(), 0))
373 return false;
374 getControls(V, 0, Forward);
375 return true;
376 }
377
378private:
379 bool route(ElemType *P, RowType *T, unsigned Size, unsigned Step);
380};
381
382struct ReverseDeltaNetwork : public PermNetwork {
383 ReverseDeltaNetwork(ArrayRef<ElemType> Ord) : PermNetwork(Ord) {}
384
385 bool run(Controls &V) {
386 if (!route(Order.data(), Table.data(), size(), 0))
387 return false;
388 getControls(V, 0, Reverse);
389 return true;
390 }
391
392private:
393 bool route(ElemType *P, RowType *T, unsigned Size, unsigned Step);
394};
395
396struct BenesNetwork : public PermNetwork {
397 BenesNetwork(ArrayRef<ElemType> Ord) : PermNetwork(Ord, 2) {}
398
399 bool run(Controls &F, Controls &R) {
400 if (!route(Order.data(), Table.data(), size(), 0))
401 return false;
402
403 getControls(F, 0, Forward);
404 getControls(R, Log, Reverse);
405 return true;
406 }
407
408private:
409 bool route(ElemType *P, RowType *T, unsigned Size, unsigned Step);
410};
411
412
413bool ForwardDeltaNetwork::route(ElemType *P, RowType *T, unsigned Size,
414 unsigned Step) {
415 bool UseUp = false, UseDown = false;
416 ElemType Num = Size;
417
418 // Cannot use coloring here, because coloring is used to determine
419 // the "big" switch, i.e. the one that changes halves, and in a forward
420 // network, a color can be simultaneously routed to both halves in the
421 // step we're working on.
422 for (ElemType J = 0; J != Num; ++J) {
423 ElemType I = P[J];
424 // I is the position in the input,
425 // J is the position in the output.
426 if (I == Ignore)
427 continue;
428 uint8_t S;
429 if (I < Num/2)
430 S = (J < Num/2) ? Pass : Switch;
431 else
432 S = (J < Num/2) ? Switch : Pass;
433
434 // U is the element in the table that needs to be updated.
435 ElemType U = (S == Pass) ? I : (I < Num/2 ? I+Num/2 : I-Num/2);
436 if (U < Num/2)
437 UseUp = true;
438 else
439 UseDown = true;
440 if (T[U][Step] != S && T[U][Step] != None)
441 return false;
442 T[U][Step] = S;
443 }
444
445 for (ElemType J = 0; J != Num; ++J)
446 if (P[J] != Ignore && P[J] >= Num/2)
447 P[J] -= Num/2;
448
449 if (Step+1 < Log) {
450 if (UseUp && !route(P, T, Size/2, Step+1))
451 return false;
452 if (UseDown && !route(P+Size/2, T+Size/2, Size/2, Step+1))
453 return false;
454 }
455 return true;
456}
457
458bool ReverseDeltaNetwork::route(ElemType *P, RowType *T, unsigned Size,
459 unsigned Step) {
460 unsigned Pets = Log-1 - Step;
461 bool UseUp = false, UseDown = false;
462 ElemType Num = Size;
463
464 // In this step half-switching occurs, so coloring can be used.
465 Coloring G({P,Size});
466 const Coloring::MapType &M = G.colors();
467 if (M.empty())
468 return false;
469
470 uint8_t ColorUp = Coloring::None;
471 for (ElemType J = 0; J != Num; ++J) {
472 ElemType I = P[J];
473 // I is the position in the input,
474 // J is the position in the output.
475 if (I == Ignore)
476 continue;
477 uint8_t C = M.at(I);
478 if (C == Coloring::None)
479 continue;
480 // During "Step", inputs cannot switch halves, so if the "up" color
481 // is still unknown, make sure that it is selected in such a way that
482 // "I" will stay in the same half.
483 bool InpUp = I < Num/2;
484 if (ColorUp == Coloring::None)
485 ColorUp = InpUp ? C : G.other(C);
486 if ((C == ColorUp) != InpUp) {
487 // If I should go to a different half than where is it now, give up.
488 return false;
489 }
490
491 uint8_t S;
492 if (InpUp) {
493 S = (J < Num/2) ? Pass : Switch;
494 UseUp = true;
495 } else {
496 S = (J < Num/2) ? Switch : Pass;
497 UseDown = true;
498 }
499 T[J][Pets] = S;
500 }
501
502 // Reorder the working permutation according to the computed switch table
503 // for the last step (i.e. Pets).
504 for (ElemType J = 0; J != Size/2; ++J) {
505 ElemType PJ = P[J]; // Current values of P[J]
506 ElemType PC = P[J+Size/2]; // and P[conj(J)]
507 ElemType QJ = PJ; // New values of P[J]
508 ElemType QC = PC; // and P[conj(J)]
509 if (T[J][Pets] == Switch)
510 QC = PJ;
511 if (T[J+Size/2][Pets] == Switch)
512 QJ = PC;
513 P[J] = QJ;
514 P[J+Size/2] = QC;
515 }
516
517 for (ElemType J = 0; J != Num; ++J)
518 if (P[J] != Ignore && P[J] >= Num/2)
519 P[J] -= Num/2;
520
521 if (Step+1 < Log) {
522 if (UseUp && !route(P, T, Size/2, Step+1))
523 return false;
524 if (UseDown && !route(P+Size/2, T+Size/2, Size/2, Step+1))
525 return false;
526 }
527 return true;
528}
529
530bool BenesNetwork::route(ElemType *P, RowType *T, unsigned Size,
531 unsigned Step) {
532 Coloring G({P,Size});
533 const Coloring::MapType &M = G.colors();
534 if (M.empty())
535 return false;
536 ElemType Num = Size;
537
538 unsigned Pets = 2*Log-1 - Step;
539 bool UseUp = false, UseDown = false;
540
541 // Both assignments, i.e. Red->Up and Red->Down are valid, but they will
542 // result in different controls. Let's pick the one where the first
543 // control will be "Pass".
544 uint8_t ColorUp = Coloring::None;
545 for (ElemType J = 0; J != Num; ++J) {
546 ElemType I = P[J];
547 if (I == Ignore)
548 continue;
549 uint8_t C = M.at(I);
550 if (C == Coloring::None)
551 continue;
552 if (ColorUp == Coloring::None) {
553 ColorUp = (I < Num/2) ? Coloring::Red : Coloring::Black;
554 }
555 unsigned CI = (I < Num/2) ? I+Num/2 : I-Num/2;
556 if (C == ColorUp) {
557 if (I < Num/2)
558 T[I][Step] = Pass;
559 else
560 T[CI][Step] = Switch;
561 T[J][Pets] = (J < Num/2) ? Pass : Switch;
562 UseUp = true;
563 } else { // Down
564 if (I < Num/2)
565 T[CI][Step] = Switch;
566 else
567 T[I][Step] = Pass;
568 T[J][Pets] = (J < Num/2) ? Switch : Pass;
569 UseDown = true;
570 }
571 }
572
573 // Reorder the working permutation according to the computed switch table
574 // for the last step (i.e. Pets).
575 for (ElemType J = 0; J != Num/2; ++J) {
576 ElemType PJ = P[J]; // Current values of P[J]
577 ElemType PC = P[J+Num/2]; // and P[conj(J)]
578 ElemType QJ = PJ; // New values of P[J]
579 ElemType QC = PC; // and P[conj(J)]
580 if (T[J][Pets] == Switch)
581 QC = PJ;
582 if (T[J+Num/2][Pets] == Switch)
583 QJ = PC;
584 P[J] = QJ;
585 P[J+Num/2] = QC;
586 }
587
588 for (ElemType J = 0; J != Num; ++J)
589 if (P[J] != Ignore && P[J] >= Num/2)
590 P[J] -= Num/2;
591
592 if (Step+1 < Log) {
593 if (UseUp && !route(P, T, Size/2, Step+1))
594 return false;
595 if (UseDown && !route(P+Size/2, T+Size/2, Size/2, Step+1))
596 return false;
597 }
598 return true;
599}
600
601// --------------------------------------------------------------------
602// Support for building selection results (output instructions that are
603// parts of the final selection).
604
605struct OpRef {
606 OpRef(SDValue V) : OpV(V) {}
607 bool isValue() const { return OpV.getNode() != nullptr; }
608 bool isValid() const { return isValue() || !(OpN & Invalid); }
609 static OpRef res(int N) { return OpRef(Whole | (N & Index)); }
610 static OpRef fail() { return OpRef(Invalid); }
611
612 static OpRef lo(const OpRef &R) {
613 assert(!R.isValue());
614 return OpRef(R.OpN & (Undef | Index | LoHalf));
615 }
616 static OpRef hi(const OpRef &R) {
617 assert(!R.isValue());
618 return OpRef(R.OpN & (Undef | Index | HiHalf));
619 }
620 static OpRef undef(MVT Ty) { return OpRef(Undef | Ty.SimpleTy); }
621
622 // Direct value.
623 SDValue OpV = SDValue();
624
625 // Reference to the operand of the input node:
626 // If the 31st bit is 1, it's undef, otherwise, bits 28..0 are the
627 // operand index:
628 // If bit 30 is set, it's the high half of the operand.
629 // If bit 29 is set, it's the low half of the operand.
630 unsigned OpN = 0;
631
632 enum : unsigned {
633 Invalid = 0x10000000,
634 LoHalf = 0x20000000,
635 HiHalf = 0x40000000,
636 Whole = LoHalf | HiHalf,
637 Undef = 0x80000000,
638 Index = 0x0FFFFFFF, // Mask of the index value.
639 IndexBits = 28,
640 };
641
642 void print(raw_ostream &OS, const SelectionDAG &G) const;
643
644private:
645 OpRef(unsigned N) : OpN(N) {}
646};
647
648struct NodeTemplate {
649 NodeTemplate() = default;
650 unsigned Opc = 0;
651 MVT Ty = MVT::Other;
652 std::vector<OpRef> Ops;
653
654 void print(raw_ostream &OS, const SelectionDAG &G) const;
655};
656
657struct ResultStack {
658 ResultStack(SDNode *Inp)
659 : InpNode(Inp), InpTy(Inp->getValueType(0).getSimpleVT()) {}
660 SDNode *InpNode;
661 MVT InpTy;
662 unsigned push(const NodeTemplate &Res) {
663 List.push_back(Res);
664 return List.size()-1;
665 }
666 unsigned push(unsigned Opc, MVT Ty, std::vector<OpRef> &&Ops) {
667 NodeTemplate Res;
668 Res.Opc = Opc;
669 Res.Ty = Ty;
670 Res.Ops = Ops;
671 return push(Res);
672 }
673 bool empty() const { return List.empty(); }
674 unsigned size() const { return List.size(); }
675 unsigned top() const { return size()-1; }
676 const NodeTemplate &operator[](unsigned I) const { return List[I]; }
677 unsigned reset(unsigned NewTop) {
678 List.resize(NewTop+1);
679 return NewTop;
680 }
681
682 using BaseType = std::vector<NodeTemplate>;
683 BaseType::iterator begin() { return List.begin(); }
684 BaseType::iterator end() { return List.end(); }
685 BaseType::const_iterator begin() const { return List.begin(); }
686 BaseType::const_iterator end() const { return List.end(); }
687
688 BaseType List;
689
690 void print(raw_ostream &OS, const SelectionDAG &G) const;
691};
692
693void OpRef::print(raw_ostream &OS, const SelectionDAG &G) const {
694 if (isValue()) {
695 OpV.getNode()->print(OS, &G);
696 return;
697 }
698 if (OpN & Invalid) {
699 OS << "invalid";
700 return;
701 }
702 if (OpN & Undef) {
703 OS << "undef";
704 return;
705 }
706 if ((OpN & Whole) != Whole) {
707 assert((OpN & Whole) == LoHalf || (OpN & Whole) == HiHalf);
708 if (OpN & LoHalf)
709 OS << "lo ";
710 else
711 OS << "hi ";
712 }
713 OS << '#' << SignExtend32(OpN & Index, IndexBits);
714}
715
716void NodeTemplate::print(raw_ostream &OS, const SelectionDAG &G) const {
717 const TargetInstrInfo &TII = *G.getSubtarget().getInstrInfo();
718 OS << format("%8s", EVT(Ty).getEVTString().c_str()) << " "
719 << TII.getName(Opc);
720 bool Comma = false;
721 for (const auto &R : Ops) {
722 if (Comma)
723 OS << ',';
724 Comma = true;
725 OS << ' ';
726 R.print(OS, G);
727 }
728}
729
730void ResultStack::print(raw_ostream &OS, const SelectionDAG &G) const {
731 OS << "Input node:\n";
Davide Italiano9c60c7d2017-12-06 18:54:17 +0000732#ifndef NDEBUG
Krzysztof Parzyszek7d37dd82017-12-06 16:40:37 +0000733 InpNode->dumpr(&G);
Davide Italiano9c60c7d2017-12-06 18:54:17 +0000734#endif
Krzysztof Parzyszek7d37dd82017-12-06 16:40:37 +0000735 OS << "Result templates:\n";
736 for (unsigned I = 0, E = List.size(); I != E; ++I) {
737 OS << '[' << I << "] ";
738 List[I].print(OS, G);
739 OS << '\n';
740 }
741}
742
743struct ShuffleMask {
744 ShuffleMask(ArrayRef<int> M) : Mask(M) {
745 for (unsigned I = 0, E = Mask.size(); I != E; ++I) {
746 int M = Mask[I];
747 if (M == -1)
748 continue;
749 MinSrc = (MinSrc == -1) ? M : std::min(MinSrc, M);
750 MaxSrc = (MaxSrc == -1) ? M : std::max(MaxSrc, M);
751 }
752 }
753
754 ArrayRef<int> Mask;
755 int MinSrc = -1, MaxSrc = -1;
756
757 ShuffleMask lo() const {
758 size_t H = Mask.size()/2;
759 return ShuffleMask({Mask.data(), H});
760 }
761 ShuffleMask hi() const {
762 size_t H = Mask.size()/2;
763 return ShuffleMask({Mask.data()+H, H});
764 }
765};
766
767// --------------------------------------------------------------------
768// The HvxSelector class.
769
770static const HexagonTargetLowering &getHexagonLowering(SelectionDAG &G) {
771 return static_cast<const HexagonTargetLowering&>(G.getTargetLoweringInfo());
772}
773static const HexagonSubtarget &getHexagonSubtarget(SelectionDAG &G) {
774 return static_cast<const HexagonSubtarget&>(G.getSubtarget());
775}
776
777namespace llvm {
778 struct HvxSelector {
779 const HexagonTargetLowering &Lower;
780 HexagonDAGToDAGISel &ISel;
781 SelectionDAG &DAG;
782 const HexagonSubtarget &HST;
783 const unsigned HwLen;
784
785 HvxSelector(HexagonDAGToDAGISel &HS, SelectionDAG &G)
786 : Lower(getHexagonLowering(G)), ISel(HS), DAG(G),
787 HST(getHexagonSubtarget(G)), HwLen(HST.getVectorLength()) {}
788
789 MVT getSingleVT(MVT ElemTy) const {
790 unsigned NumElems = HwLen / (ElemTy.getSizeInBits()/8);
791 return MVT::getVectorVT(ElemTy, NumElems);
792 }
793
794 MVT getPairVT(MVT ElemTy) const {
795 unsigned NumElems = (2*HwLen) / (ElemTy.getSizeInBits()/8);
796 return MVT::getVectorVT(ElemTy, NumElems);
797 }
798
799 void selectShuffle(SDNode *N);
800 void selectRor(SDNode *N);
801
802 private:
803 void materialize(const ResultStack &Results);
804
805 SDValue getVectorConstant(ArrayRef<uint8_t> Data, const SDLoc &dl);
806
807 enum : unsigned {
808 None,
809 PackMux,
810 };
811 OpRef concat(OpRef Va, OpRef Vb, ResultStack &Results);
812 OpRef packs(ShuffleMask SM, OpRef Va, OpRef Vb, ResultStack &Results,
813 MutableArrayRef<int> NewMask, unsigned Options = None);
814 OpRef packp(ShuffleMask SM, OpRef Va, OpRef Vb, ResultStack &Results,
815 MutableArrayRef<int> NewMask);
816 OpRef zerous(ShuffleMask SM, OpRef Va, ResultStack &Results);
817 OpRef vmuxs(ArrayRef<uint8_t> Bytes, OpRef Va, OpRef Vb,
818 ResultStack &Results);
819 OpRef vmuxp(ArrayRef<uint8_t> Bytes, OpRef Va, OpRef Vb,
820 ResultStack &Results);
821
822 OpRef shuffs1(ShuffleMask SM, OpRef Va, ResultStack &Results);
823 OpRef shuffs2(ShuffleMask SM, OpRef Va, OpRef Vb, ResultStack &Results);
824 OpRef shuffp1(ShuffleMask SM, OpRef Va, ResultStack &Results);
825 OpRef shuffp2(ShuffleMask SM, OpRef Va, OpRef Vb, ResultStack &Results);
826
827 OpRef butterfly(ShuffleMask SM, OpRef Va, ResultStack &Results);
828 OpRef contracting(ShuffleMask SM, OpRef Va, OpRef Vb, ResultStack &Results);
829 OpRef expanding(ShuffleMask SM, OpRef Va, ResultStack &Results);
830 OpRef perfect(ShuffleMask SM, OpRef Va, ResultStack &Results);
831
832 bool selectVectorConstants(SDNode *N);
833 bool scalarizeShuffle(ArrayRef<int> Mask, const SDLoc &dl, MVT ResTy,
834 SDValue Va, SDValue Vb, SDNode *N);
835
836 };
837}
838
839// Return a submask of A that is shorter than A by |C| elements:
840// - if C > 0, return a submask of A that starts at position C,
841// - if C <= 0, return a submask of A that starts at 0 (reduce A by |C|).
842static ArrayRef<int> subm(ArrayRef<int> A, int C) {
843 if (C > 0)
844 return { A.data()+C, A.size()-C };
845 return { A.data(), A.size()+C };
846}
847
848static void splitMask(ArrayRef<int> Mask, MutableArrayRef<int> MaskL,
849 MutableArrayRef<int> MaskR) {
850 unsigned VecLen = Mask.size();
851 assert(MaskL.size() == VecLen && MaskR.size() == VecLen);
852 for (unsigned I = 0; I != VecLen; ++I) {
853 int M = Mask[I];
854 if (M < 0) {
855 MaskL[I] = MaskR[I] = -1;
856 } else if (unsigned(M) < VecLen) {
857 MaskL[I] = M;
858 MaskR[I] = -1;
859 } else {
860 MaskL[I] = -1;
861 MaskR[I] = M-VecLen;
862 }
863 }
864}
865
866static std::pair<int,unsigned> findStrip(ArrayRef<int> A, int Inc,
867 unsigned MaxLen) {
868 assert(A.size() > 0 && A.size() >= MaxLen);
869 int F = A[0];
870 int E = F;
871 for (unsigned I = 1; I != MaxLen; ++I) {
872 if (A[I] - E != Inc)
873 return { F, I };
874 E = A[I];
875 }
876 return { F, MaxLen };
877}
878
879static bool isUndef(ArrayRef<int> Mask) {
880 for (int Idx : Mask)
881 if (Idx != -1)
882 return false;
883 return true;
884}
885
886static bool isIdentity(ArrayRef<int> Mask) {
887 unsigned Size = Mask.size();
888 return findStrip(Mask, 1, Size) == std::make_pair(0, Size);
889}
890
891static bool isPermutation(ArrayRef<int> Mask) {
892 // Check by adding all numbers only works if there is no overflow.
893 assert(Mask.size() < 0x00007FFF && "Sanity failure");
894 int Sum = 0;
895 for (int Idx : Mask) {
896 if (Idx == -1)
897 return false;
898 Sum += Idx;
899 }
900 int N = Mask.size();
901 return 2*Sum == N*(N-1);
902}
903
904bool HvxSelector::selectVectorConstants(SDNode *N) {
905 // Constant vectors are generated as loads from constant pools.
906 // Since they are generated during the selection process, the main
907 // selection algorithm is not aware of them. Select them directly
908 // here.
909 if (!N->isMachineOpcode() && N->getOpcode() == ISD::LOAD) {
910 SDValue Addr = cast<LoadSDNode>(N)->getBasePtr();
911 unsigned AddrOpc = Addr.getOpcode();
912 if (AddrOpc == HexagonISD::AT_PCREL || AddrOpc == HexagonISD::CP) {
913 if (Addr.getOperand(0).getOpcode() == ISD::TargetConstantPool) {
914 ISel.Select(N);
915 return true;
916 }
917 }
918 }
919
920 bool Selected = false;
921 for (unsigned I = 0, E = N->getNumOperands(); I != E; ++I)
922 Selected = selectVectorConstants(N->getOperand(I).getNode()) || Selected;
923 return Selected;
924}
925
926void HvxSelector::materialize(const ResultStack &Results) {
927 DEBUG_WITH_TYPE("isel", {
928 dbgs() << "Materializing\n";
929 Results.print(dbgs(), DAG);
930 });
931 if (Results.empty())
932 return;
933 const SDLoc &dl(Results.InpNode);
934 std::vector<SDValue> Output;
935
936 for (unsigned I = 0, E = Results.size(); I != E; ++I) {
937 const NodeTemplate &Node = Results[I];
938 std::vector<SDValue> Ops;
939 for (const OpRef &R : Node.Ops) {
940 assert(R.isValid());
941 if (R.isValue()) {
942 Ops.push_back(R.OpV);
943 continue;
944 }
945 if (R.OpN & OpRef::Undef) {
946 MVT::SimpleValueType SVT = MVT::SimpleValueType(R.OpN & OpRef::Index);
947 Ops.push_back(ISel.selectUndef(dl, MVT(SVT)));
948 continue;
949 }
950 // R is an index of a result.
951 unsigned Part = R.OpN & OpRef::Whole;
952 int Idx = SignExtend32(R.OpN & OpRef::Index, OpRef::IndexBits);
953 if (Idx < 0)
954 Idx += I;
955 assert(Idx >= 0 && unsigned(Idx) < Output.size());
956 SDValue Op = Output[Idx];
957 MVT OpTy = Op.getValueType().getSimpleVT();
958 if (Part != OpRef::Whole) {
959 assert(Part == OpRef::LoHalf || Part == OpRef::HiHalf);
960 if (Op.getOpcode() == HexagonISD::VCOMBINE) {
961 Op = (Part == OpRef::HiHalf) ? Op.getOperand(0) : Op.getOperand(1);
962 } else {
963 MVT HalfTy = MVT::getVectorVT(OpTy.getVectorElementType(),
964 OpTy.getVectorNumElements()/2);
965 unsigned Sub = (Part == OpRef::LoHalf) ? Hexagon::vsub_lo
966 : Hexagon::vsub_hi;
967 Op = DAG.getTargetExtractSubreg(Sub, dl, HalfTy, Op);
968 }
969 }
970 Ops.push_back(Op);
971 } // for (Node : Results)
972
973 assert(Node.Ty != MVT::Other);
974 SDNode *ResN = (Node.Opc == TargetOpcode::COPY)
975 ? Ops.front().getNode()
976 : DAG.getMachineNode(Node.Opc, dl, Node.Ty, Ops);
977 Output.push_back(SDValue(ResN, 0));
978 }
979
980 SDNode *OutN = Output.back().getNode();
981 SDNode *InpN = Results.InpNode;
982 DEBUG_WITH_TYPE("isel", {
983 dbgs() << "Generated node:\n";
984 OutN->dumpr(&DAG);
985 });
986
987 ISel.ReplaceNode(InpN, OutN);
988 selectVectorConstants(OutN);
989 DAG.RemoveDeadNodes();
990}
991
992OpRef HvxSelector::concat(OpRef Lo, OpRef Hi, ResultStack &Results) {
993 DEBUG_WITH_TYPE("isel", {dbgs() << __func__ << '\n';});
994 const SDLoc &dl(Results.InpNode);
995 Results.push(TargetOpcode::REG_SEQUENCE, getPairVT(MVT::i8), {
996 DAG.getTargetConstant(Hexagon::HvxWRRegClassID, dl, MVT::i32),
997 Lo, DAG.getTargetConstant(Hexagon::vsub_lo, dl, MVT::i32),
998 Hi, DAG.getTargetConstant(Hexagon::vsub_hi, dl, MVT::i32),
999 });
1000 return OpRef::res(Results.top());
1001}
1002
1003// Va, Vb are single vectors, SM can be arbitrarily long.
1004OpRef HvxSelector::packs(ShuffleMask SM, OpRef Va, OpRef Vb,
1005 ResultStack &Results, MutableArrayRef<int> NewMask,
1006 unsigned Options) {
1007 DEBUG_WITH_TYPE("isel", {dbgs() << __func__ << '\n';});
1008 if (!Va.isValid() || !Vb.isValid())
1009 return OpRef::fail();
1010
1011 int VecLen = SM.Mask.size();
1012 MVT Ty = getSingleVT(MVT::i8);
1013
1014 if (SM.MaxSrc - SM.MinSrc < int(HwLen)) {
1015 if (SM.MaxSrc < int(HwLen)) {
1016 memcpy(NewMask.data(), SM.Mask.data(), sizeof(int)*VecLen);
1017 return Va;
1018 }
1019 if (SM.MinSrc >= int(HwLen)) {
1020 for (int I = 0; I != VecLen; ++I) {
1021 int M = SM.Mask[I];
1022 if (M != -1)
1023 M -= HwLen;
1024 NewMask[I] = M;
1025 }
1026 return Vb;
1027 }
1028 const SDLoc &dl(Results.InpNode);
1029 SDValue S = DAG.getTargetConstant(SM.MinSrc, dl, MVT::i32);
1030 if (isUInt<3>(SM.MinSrc)) {
1031 Results.push(Hexagon::V6_valignbi, Ty, {Vb, Va, S});
1032 } else {
1033 Results.push(Hexagon::A2_tfrsi, MVT::i32, {S});
1034 unsigned Top = Results.top();
1035 Results.push(Hexagon::V6_valignb, Ty, {Vb, Va, OpRef::res(Top)});
1036 }
1037 for (int I = 0; I != VecLen; ++I) {
1038 int M = SM.Mask[I];
1039 if (M != -1)
1040 M -= SM.MinSrc;
1041 NewMask[I] = M;
1042 }
1043 return OpRef::res(Results.top());
1044 }
1045
1046 if (Options & PackMux) {
1047 // If elements picked from Va and Vb have all different (source) indexes
1048 // (relative to the start of the argument), do a mux, and update the mask.
1049 BitVector Picked(HwLen);
1050 SmallVector<uint8_t,128> MuxBytes(HwLen);
1051 bool CanMux = true;
1052 for (int I = 0; I != VecLen; ++I) {
1053 int M = SM.Mask[I];
1054 if (M == -1)
1055 continue;
1056 if (M >= int(HwLen))
1057 M -= HwLen;
1058 else
1059 MuxBytes[M] = 0xFF;
1060 if (Picked[M]) {
1061 CanMux = false;
1062 break;
1063 }
1064 NewMask[I] = M;
1065 }
1066 if (CanMux)
1067 return vmuxs(MuxBytes, Va, Vb, Results);
1068 }
1069
1070 return OpRef::fail();
1071}
1072
1073OpRef HvxSelector::packp(ShuffleMask SM, OpRef Va, OpRef Vb,
1074 ResultStack &Results, MutableArrayRef<int> NewMask) {
1075 DEBUG_WITH_TYPE("isel", {dbgs() << __func__ << '\n';});
1076 unsigned HalfMask = 0;
1077 unsigned LogHw = Log2_32(HwLen);
1078 for (int M : SM.Mask) {
1079 if (M == -1)
1080 continue;
1081 HalfMask |= (1u << (M >> LogHw));
1082 }
1083
1084 if (HalfMask == 0)
1085 return OpRef::undef(getPairVT(MVT::i8));
1086
1087 // If more than two halves are used, bail.
1088 // TODO: be more aggressive here?
1089 if (countPopulation(HalfMask) > 2)
1090 return OpRef::fail();
1091
1092 MVT HalfTy = getSingleVT(MVT::i8);
1093
1094 OpRef Inp[2] = { Va, Vb };
1095 OpRef Out[2] = { OpRef::undef(HalfTy), OpRef::undef(HalfTy) };
1096
1097 uint8_t HalfIdx[4] = { 0xFF, 0xFF, 0xFF, 0xFF };
1098 unsigned Idx = 0;
1099 for (unsigned I = 0; I != 4; ++I) {
1100 if ((HalfMask & (1u << I)) == 0)
1101 continue;
1102 assert(Idx < 2);
1103 OpRef Op = Inp[I/2];
1104 Out[Idx] = (I & 1) ? OpRef::hi(Op) : OpRef::lo(Op);
1105 HalfIdx[I] = Idx++;
1106 }
1107
1108 int VecLen = SM.Mask.size();
1109 for (int I = 0; I != VecLen; ++I) {
1110 int M = SM.Mask[I];
1111 if (M >= 0) {
1112 uint8_t Idx = HalfIdx[M >> LogHw];
1113 assert(Idx == 0 || Idx == 1);
1114 M = (M & (HwLen-1)) + HwLen*Idx;
1115 }
1116 NewMask[I] = M;
1117 }
1118
1119 return concat(Out[0], Out[1], Results);
1120}
1121
1122OpRef HvxSelector::zerous(ShuffleMask SM, OpRef Va, ResultStack &Results) {
1123 DEBUG_WITH_TYPE("isel", {dbgs() << __func__ << '\n';});
1124
1125 int VecLen = SM.Mask.size();
1126 SmallVector<uint8_t,128> UsedBytes(VecLen);
1127 bool HasUnused = false;
1128 for (int I = 0; I != VecLen; ++I) {
1129 if (SM.Mask[I] != -1)
1130 UsedBytes[I] = 0xFF;
1131 else
1132 HasUnused = true;
1133 }
1134 if (!HasUnused)
1135 return Va;
1136 SDValue B = getVectorConstant(UsedBytes, SDLoc(Results.InpNode));
1137 Results.push(Hexagon::V6_vand, getSingleVT(MVT::i8), {Va, OpRef(B)});
1138 return OpRef::res(Results.top());
1139}
1140
1141OpRef HvxSelector::vmuxs(ArrayRef<uint8_t> Bytes, OpRef Va, OpRef Vb,
1142 ResultStack &Results) {
1143 DEBUG_WITH_TYPE("isel", {dbgs() << __func__ << '\n';});
1144 MVT ByteTy = getSingleVT(MVT::i8);
1145 MVT BoolTy = MVT::getVectorVT(MVT::i1, 8*HwLen); // XXX
1146 const SDLoc &dl(Results.InpNode);
1147 SDValue B = getVectorConstant(Bytes, dl);
1148 Results.push(Hexagon::V6_vd0, ByteTy, {});
1149 Results.push(Hexagon::V6_veqb, BoolTy, {OpRef(B), OpRef::res(-1)});
1150 Results.push(Hexagon::V6_vmux, ByteTy, {OpRef::res(-1), Va, Vb});
1151 return OpRef::res(Results.top());
1152}
1153
1154OpRef HvxSelector::vmuxp(ArrayRef<uint8_t> Bytes, OpRef Va, OpRef Vb,
1155 ResultStack &Results) {
1156 DEBUG_WITH_TYPE("isel", {dbgs() << __func__ << '\n';});
1157 size_t S = Bytes.size() / 2;
1158 OpRef L = vmuxs({Bytes.data(), S}, OpRef::lo(Va), OpRef::lo(Vb), Results);
1159 OpRef H = vmuxs({Bytes.data()+S, S}, OpRef::hi(Va), OpRef::hi(Vb), Results);
1160 return concat(L, H, Results);
1161}
1162
1163OpRef HvxSelector::shuffs1(ShuffleMask SM, OpRef Va, ResultStack &Results) {
1164 DEBUG_WITH_TYPE("isel", {dbgs() << __func__ << '\n';});
1165 unsigned VecLen = SM.Mask.size();
1166 assert(HwLen == VecLen);
Tim Shenb684b1a2017-12-06 19:33:42 +00001167 (void)VecLen;
Krzysztof Parzyszek7d37dd82017-12-06 16:40:37 +00001168 assert(all_of(SM.Mask, [this](int M) { return M == -1 || M < int(HwLen); }));
1169
1170 if (isIdentity(SM.Mask))
1171 return Va;
1172 if (isUndef(SM.Mask))
1173 return OpRef::undef(getSingleVT(MVT::i8));
1174
Krzysztof Parzyszek64533cf2017-12-06 21:25:03 +00001175 OpRef P = perfect(SM, Va, Results);
1176 if (P.isValid())
1177 return P;
Krzysztof Parzyszek7d37dd82017-12-06 16:40:37 +00001178 return butterfly(SM, Va, Results);
1179}
1180
1181OpRef HvxSelector::shuffs2(ShuffleMask SM, OpRef Va, OpRef Vb,
1182 ResultStack &Results) {
1183 DEBUG_WITH_TYPE("isel", {dbgs() << __func__ << '\n';});
1184 OpRef C = contracting(SM, Va, Vb, Results);
1185 if (C.isValid())
1186 return C;
1187
1188 int VecLen = SM.Mask.size();
1189 SmallVector<int,128> NewMask(VecLen);
1190 OpRef P = packs(SM, Va, Vb, Results, NewMask);
1191 if (P.isValid())
1192 return shuffs1(ShuffleMask(NewMask), P, Results);
1193
1194 SmallVector<int,128> MaskL(VecLen), MaskR(VecLen);
1195 splitMask(SM.Mask, MaskL, MaskR);
1196
1197 OpRef L = shuffs1(ShuffleMask(MaskL), Va, Results);
1198 OpRef R = shuffs1(ShuffleMask(MaskR), Vb, Results);
1199 if (!L.isValid() || !R.isValid())
1200 return OpRef::fail();
1201
1202 SmallVector<uint8_t,128> Bytes(VecLen);
1203 for (int I = 0; I != VecLen; ++I) {
1204 if (MaskL[I] != -1)
1205 Bytes[I] = 0xFF;
1206 }
1207 return vmuxs(Bytes, L, R, Results);
1208}
1209
1210OpRef HvxSelector::shuffp1(ShuffleMask SM, OpRef Va, ResultStack &Results) {
1211 DEBUG_WITH_TYPE("isel", {dbgs() << __func__ << '\n';});
1212 int VecLen = SM.Mask.size();
1213
1214 SmallVector<int,128> PackedMask(VecLen);
1215 OpRef P = packs(SM, OpRef::lo(Va), OpRef::hi(Va), Results, PackedMask);
1216 if (P.isValid()) {
1217 ShuffleMask PM(PackedMask);
1218 OpRef E = expanding(PM, P, Results);
1219 if (E.isValid())
1220 return E;
1221
1222 OpRef L = shuffs1(PM.lo(), P, Results);
1223 OpRef H = shuffs1(PM.hi(), P, Results);
1224 if (L.isValid() && H.isValid())
1225 return concat(L, H, Results);
1226 }
1227
1228 OpRef R = perfect(SM, Va, Results);
1229 if (R.isValid())
1230 return R;
1231 // TODO commute the mask and try the opposite order of the halves.
1232
1233 OpRef L = shuffs2(SM.lo(), OpRef::lo(Va), OpRef::hi(Va), Results);
1234 OpRef H = shuffs2(SM.hi(), OpRef::lo(Va), OpRef::hi(Va), Results);
1235 if (L.isValid() && H.isValid())
1236 return concat(L, H, Results);
1237
1238 return OpRef::fail();
1239}
1240
1241OpRef HvxSelector::shuffp2(ShuffleMask SM, OpRef Va, OpRef Vb,
1242 ResultStack &Results) {
1243 DEBUG_WITH_TYPE("isel", {dbgs() << __func__ << '\n';});
1244 int VecLen = SM.Mask.size();
1245
1246 SmallVector<int,256> PackedMask(VecLen);
1247 OpRef P = packp(SM, Va, Vb, Results, PackedMask);
1248 if (P.isValid())
1249 return shuffp1(ShuffleMask(PackedMask), P, Results);
1250
1251 SmallVector<int,256> MaskL(VecLen), MaskR(VecLen);
1252 OpRef L = shuffp1(ShuffleMask(MaskL), Va, Results);
1253 OpRef R = shuffp1(ShuffleMask(MaskR), Vb, Results);
1254 if (!L.isValid() || !R.isValid())
1255 return OpRef::fail();
1256
1257 // Mux the results.
1258 SmallVector<uint8_t,256> Bytes(VecLen);
1259 for (int I = 0; I != VecLen; ++I) {
1260 if (MaskL[I] != -1)
1261 Bytes[I] = 0xFF;
1262 }
1263 return vmuxp(Bytes, L, R, Results);
1264}
1265
1266bool HvxSelector::scalarizeShuffle(ArrayRef<int> Mask, const SDLoc &dl,
1267 MVT ResTy, SDValue Va, SDValue Vb,
1268 SDNode *N) {
1269 DEBUG_WITH_TYPE("isel", {dbgs() << __func__ << '\n';});
1270 MVT ElemTy = ResTy.getVectorElementType();
1271 assert(ElemTy == MVT::i8);
1272 unsigned VecLen = Mask.size();
1273 bool HavePairs = (2*HwLen == VecLen);
1274 MVT SingleTy = getSingleVT(MVT::i8);
1275
1276 SmallVector<SDValue,128> Ops;
1277 for (int I : Mask) {
1278 if (I < 0) {
1279 Ops.push_back(ISel.selectUndef(dl, ElemTy));
1280 continue;
1281 }
1282 SDValue Vec;
1283 unsigned M = I;
1284 if (M < VecLen) {
1285 Vec = Va;
1286 } else {
1287 Vec = Vb;
1288 M -= VecLen;
1289 }
1290 if (HavePairs) {
1291 if (M < HwLen) {
1292 Vec = DAG.getTargetExtractSubreg(Hexagon::vsub_lo, dl, SingleTy, Vec);
1293 } else {
1294 Vec = DAG.getTargetExtractSubreg(Hexagon::vsub_hi, dl, SingleTy, Vec);
1295 M -= HwLen;
1296 }
1297 }
1298 SDValue Idx = DAG.getConstant(M, dl, MVT::i32);
1299 SDValue Ex = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ElemTy, {Vec, Idx});
1300 SDValue L = Lower.LowerOperation(Ex, DAG);
1301 assert(L.getNode());
1302 Ops.push_back(L);
1303 }
1304
1305 SDValue LV;
1306 if (2*HwLen == VecLen) {
1307 SDValue B0 = DAG.getBuildVector(SingleTy, dl, {Ops.data(), HwLen});
1308 SDValue L0 = Lower.LowerOperation(B0, DAG);
1309 SDValue B1 = DAG.getBuildVector(SingleTy, dl, {Ops.data()+HwLen, HwLen});
1310 SDValue L1 = Lower.LowerOperation(B1, DAG);
1311 // XXX CONCAT_VECTORS is legal for HVX vectors. Legalizing (lowering)
1312 // functions may expect to be called only for illegal operations, so
1313 // make sure that they are not called for legal ones. Develop a better
1314 // mechanism for dealing with this.
1315 LV = DAG.getNode(ISD::CONCAT_VECTORS, dl, ResTy, {L0, L1});
1316 } else {
1317 SDValue BV = DAG.getBuildVector(ResTy, dl, Ops);
1318 LV = Lower.LowerOperation(BV, DAG);
1319 }
1320
1321 assert(!N->use_empty());
1322 ISel.ReplaceNode(N, LV.getNode());
1323 DAG.RemoveDeadNodes();
1324
1325 std::deque<SDNode*> SubNodes;
1326 SubNodes.push_back(LV.getNode());
1327 for (unsigned I = 0; I != SubNodes.size(); ++I) {
1328 for (SDValue Op : SubNodes[I]->ops())
1329 SubNodes.push_back(Op.getNode());
1330 }
1331 while (!SubNodes.empty()) {
1332 SDNode *S = SubNodes.front();
1333 SubNodes.pop_front();
1334 if (S->use_empty())
1335 continue;
1336 // This isn't great, but users need to be selected before any nodes that
1337 // they use. (The reason is to match larger patterns, and avoid nodes that
1338 // cannot be matched on their own, e.g. ValueType, TokenFactor, etc.).
1339 bool PendingUser = llvm::any_of(S->uses(), [&SubNodes](const SDNode *U) {
1340 return llvm::any_of(SubNodes, [U](const SDNode *T) {
1341 return T == U;
1342 });
1343 });
1344 if (PendingUser)
1345 SubNodes.push_back(S);
1346 else
1347 ISel.Select(S);
1348 }
1349
1350 DAG.RemoveDeadNodes();
1351 return true;
1352}
1353
1354OpRef HvxSelector::contracting(ShuffleMask SM, OpRef Va, OpRef Vb,
1355 ResultStack &Results) {
1356 DEBUG_WITH_TYPE("isel", {dbgs() << __func__ << '\n';});
1357 if (!Va.isValid() || !Vb.isValid())
1358 return OpRef::fail();
1359
1360 // Contracting shuffles, i.e. instructions that always discard some bytes
1361 // from the operand vectors.
1362 //
1363 // V6_vshuff{e,o}b
1364 // V6_vdealb4w
1365 // V6_vpack{e,o}{b,h}
1366
1367 int VecLen = SM.Mask.size();
1368 std::pair<int,unsigned> Strip = findStrip(SM.Mask, 1, VecLen);
1369 MVT ResTy = getSingleVT(MVT::i8);
1370
1371 // The following shuffles only work for bytes and halfwords. This requires
1372 // the strip length to be 1 or 2.
1373 if (Strip.second != 1 && Strip.second != 2)
1374 return OpRef::fail();
1375
1376 // The patterns for the shuffles, in terms of the starting offsets of the
1377 // consecutive strips (L = length of the strip, N = VecLen):
1378 //
1379 // vpacke: 0, 2L, 4L ... N+0, N+2L, N+4L ... L = 1 or 2
1380 // vpacko: L, 3L, 5L ... N+L, N+3L, N+5L ... L = 1 or 2
1381 //
1382 // vshuffe: 0, N+0, 2L, N+2L, 4L ... L = 1 or 2
1383 // vshuffo: L, N+L, 3L, N+3L, 5L ... L = 1 or 2
1384 //
1385 // vdealb4w: 0, 4, 8 ... 2, 6, 10 ... N+0, N+4, N+8 ... N+2, N+6, N+10 ...
1386
1387 // The value of the element in the mask following the strip will decide
1388 // what kind of a shuffle this can be.
1389 int NextInMask = SM.Mask[Strip.second];
1390
1391 // Check if NextInMask could be 2L, 3L or 4, i.e. if it could be a mask
1392 // for vpack or vdealb4w. VecLen > 4, so NextInMask for vdealb4w would
1393 // satisfy this.
1394 if (NextInMask < VecLen) {
1395 // vpack{e,o} or vdealb4w
1396 if (Strip.first == 0 && Strip.second == 1 && NextInMask == 4) {
1397 int N = VecLen;
1398 // Check if this is vdealb4w (L=1).
1399 for (int I = 0; I != N/4; ++I)
1400 if (SM.Mask[I] != 4*I)
1401 return OpRef::fail();
1402 for (int I = 0; I != N/4; ++I)
1403 if (SM.Mask[I+N/4] != 2 + 4*I)
1404 return OpRef::fail();
1405 for (int I = 0; I != N/4; ++I)
1406 if (SM.Mask[I+N/2] != N + 4*I)
1407 return OpRef::fail();
1408 for (int I = 0; I != N/4; ++I)
1409 if (SM.Mask[I+3*N/4] != N+2 + 4*I)
1410 return OpRef::fail();
1411 // Matched mask for vdealb4w.
1412 Results.push(Hexagon::V6_vdealb4w, ResTy, {Vb, Va});
1413 return OpRef::res(Results.top());
1414 }
1415
1416 // Check if this is vpack{e,o}.
1417 int N = VecLen;
1418 int L = Strip.second;
1419 // Check if the first strip starts at 0 or at L.
1420 if (Strip.first != 0 && Strip.first != L)
1421 return OpRef::fail();
1422 // Examine the rest of the mask.
Krzysztof Parzyszek64533cf2017-12-06 21:25:03 +00001423 for (int I = L; I < N; I += L) {
Krzysztof Parzyszek7d37dd82017-12-06 16:40:37 +00001424 auto S = findStrip(subm(SM.Mask,I), 1, N-I);
1425 // Check whether the mask element at the beginning of each strip
1426 // increases by 2L each time.
1427 if (S.first - Strip.first != 2*I)
1428 return OpRef::fail();
1429 // Check whether each strip is of the same length.
1430 if (S.second != unsigned(L))
1431 return OpRef::fail();
1432 }
1433
1434 // Strip.first == 0 => vpacke
1435 // Strip.first == L => vpacko
1436 assert(Strip.first == 0 || Strip.first == L);
1437 using namespace Hexagon;
1438 NodeTemplate Res;
1439 Res.Opc = Strip.second == 1 // Number of bytes.
1440 ? (Strip.first == 0 ? V6_vpackeb : V6_vpackob)
1441 : (Strip.first == 0 ? V6_vpackeh : V6_vpackoh);
1442 Res.Ty = ResTy;
1443 Res.Ops = { Vb, Va };
1444 Results.push(Res);
1445 return OpRef::res(Results.top());
1446 }
1447
1448 // Check if this is vshuff{e,o}.
1449 int N = VecLen;
1450 int L = Strip.second;
1451 std::pair<int,unsigned> PrevS = Strip;
1452 bool Flip = false;
1453 for (int I = L; I < N; I += L) {
1454 auto S = findStrip(subm(SM.Mask,I), 1, N-I);
1455 if (S.second != PrevS.second)
1456 return OpRef::fail();
1457 int Diff = Flip ? PrevS.first - S.first + 2*L
1458 : S.first - PrevS.first;
1459 if (Diff != N)
1460 return OpRef::fail();
1461 Flip ^= true;
1462 PrevS = S;
1463 }
1464 // Strip.first == 0 => vshuffe
1465 // Strip.first == L => vshuffo
1466 assert(Strip.first == 0 || Strip.first == L);
1467 using namespace Hexagon;
1468 NodeTemplate Res;
1469 Res.Opc = Strip.second == 1 // Number of bytes.
1470 ? (Strip.first == 0 ? V6_vshuffeb : V6_vshuffob)
1471 : (Strip.first == 0 ? V6_vshufeh : V6_vshufoh);
1472 Res.Ty = ResTy;
1473 Res.Ops = { Vb, Va };
1474 Results.push(Res);
1475 return OpRef::res(Results.top());
1476}
1477
1478OpRef HvxSelector::expanding(ShuffleMask SM, OpRef Va, ResultStack &Results) {
1479 DEBUG_WITH_TYPE("isel", {dbgs() << __func__ << '\n';});
1480 // Expanding shuffles (using all elements and inserting into larger vector):
1481 //
1482 // V6_vunpacku{b,h} [*]
1483 //
1484 // [*] Only if the upper elements (filled with 0s) are "don't care" in Mask.
1485 //
1486 // Note: V6_vunpacko{b,h} are or-ing the high byte/half in the result, so
1487 // they are not shuffles.
1488 //
1489 // The argument is a single vector.
1490
1491 int VecLen = SM.Mask.size();
1492 assert(2*HwLen == unsigned(VecLen) && "Expecting vector-pair type");
1493
1494 std::pair<int,unsigned> Strip = findStrip(SM.Mask, 1, VecLen);
1495
1496 // The patterns for the unpacks, in terms of the starting offsets of the
1497 // consecutive strips (L = length of the strip, N = VecLen):
1498 //
1499 // vunpacku: 0, -1, L, -1, 2L, -1 ...
1500
1501 if (Strip.first != 0)
1502 return OpRef::fail();
1503
1504 // The vunpackus only handle byte and half-word.
1505 if (Strip.second != 1 && Strip.second != 2)
1506 return OpRef::fail();
1507
1508 int N = VecLen;
1509 int L = Strip.second;
1510
1511 // First, check the non-ignored strips.
1512 for (int I = 2*L; I < 2*N; I += 2*L) {
1513 auto S = findStrip(subm(SM.Mask,I), 1, N-I);
1514 if (S.second != unsigned(L))
1515 return OpRef::fail();
1516 if (2*S.first != I)
1517 return OpRef::fail();
1518 }
1519 // Check the -1s.
1520 for (int I = L; I < 2*N; I += 2*L) {
1521 auto S = findStrip(subm(SM.Mask,I), 0, N-I);
1522 if (S.first != -1 || S.second != unsigned(L))
1523 return OpRef::fail();
1524 }
1525
1526 unsigned Opc = Strip.second == 1 ? Hexagon::V6_vunpackub
1527 : Hexagon::V6_vunpackuh;
1528 Results.push(Opc, getPairVT(MVT::i8), {Va});
1529 return OpRef::res(Results.top());
1530}
1531
1532OpRef HvxSelector::perfect(ShuffleMask SM, OpRef Va, ResultStack &Results) {
1533 DEBUG_WITH_TYPE("isel", {dbgs() << __func__ << '\n';});
1534 // V6_vdeal{b,h}
1535 // V6_vshuff{b,h}
1536
1537 // V6_vshufoe{b,h} those are quivalent to vshuffvdd(..,{1,2})
1538 // V6_vshuffvdd (V6_vshuff)
1539 // V6_dealvdd (V6_vdeal)
1540
Krzysztof Parzyszek7d37dd82017-12-06 16:40:37 +00001541 int VecLen = SM.Mask.size();
1542 assert(isPowerOf2_32(VecLen) && Log2_32(VecLen) <= 8);
1543 unsigned LogLen = Log2_32(VecLen);
Krzysztof Parzyszek64533cf2017-12-06 21:25:03 +00001544 unsigned HwLog = Log2_32(HwLen);
1545 // The result length must be the same as the length of a single vector,
1546 // or a vector pair.
1547 assert(LogLen == HwLog || LogLen == HwLog+1);
1548 bool Extend = (LogLen == HwLog);
Krzysztof Parzyszek7d37dd82017-12-06 16:40:37 +00001549
1550 if (!isPermutation(SM.Mask))
1551 return OpRef::fail();
1552
1553 SmallVector<unsigned,8> Perm(LogLen);
1554
1555 // Check if this could be a perfect shuffle, or a combination of perfect
1556 // shuffles.
1557 //
1558 // Consider this permutation (using hex digits to make the ASCII diagrams
1559 // easier to read):
1560 // { 0, 8, 1, 9, 2, A, 3, B, 4, C, 5, D, 6, E, 7, F }.
1561 // This is a "deal" operation: divide the input into two halves, and
1562 // create the output by picking elements by alternating between these two
1563 // halves:
1564 // 0 1 2 3 4 5 6 7 --> 0 8 1 9 2 A 3 B 4 C 5 D 6 E 7 F [*]
1565 // 8 9 A B C D E F
1566 //
1567 // Aside from a few special explicit cases (V6_vdealb, etc.), HVX provides
1568 // a somwehat different mechanism that could be used to perform shuffle/
1569 // deal operations: a 2x2 transpose.
1570 // Consider the halves of inputs again, they can be interpreted as a 2x8
1571 // matrix. A 2x8 matrix can be looked at four 2x2 matrices concatenated
1572 // together. Now, when considering 2 elements at a time, it will be a 2x4
1573 // matrix (with elements 01, 23, 45, etc.), or two 2x2 matrices:
1574 // 01 23 45 67
1575 // 89 AB CD EF
1576 // With groups of 4, this will become a single 2x2 matrix, and so on.
1577 //
1578 // The 2x2 transpose instruction works by transposing each of the 2x2
1579 // matrices (or "sub-matrices"), given a specific group size. For example,
1580 // if the group size is 1 (i.e. each element is its own group), there
1581 // will be four transposes of the four 2x2 matrices that form the 2x8.
1582 // For example, with the inputs as above, the result will be:
1583 // 0 8 2 A 4 C 6 E
1584 // 1 9 3 B 5 D 7 F
1585 // Now, this result can be tranposed again, but with the group size of 2:
1586 // 08 19 4C 5D
1587 // 2A 3B 6E 7F
1588 // If we then transpose that result, but with the group size of 4, we get:
1589 // 0819 2A3B
1590 // 4C5D 6E7F
1591 // If we concatenate these two rows, it will be
1592 // 0 8 1 9 2 A 3 B 4 C 5 D 6 E 7 F
1593 // which is the same as the "deal" [*] above.
1594 //
1595 // In general, a "deal" of individual elements is a series of 2x2 transposes,
1596 // with changing group size. HVX has two instructions:
1597 // Vdd = V6_vdealvdd Vu, Vv, Rt
1598 // Vdd = V6_shufvdd Vu, Vv, Rt
1599 // that perform exactly that. The register Rt controls which transposes are
1600 // going to happen: a bit at position n (counting from 0) indicates that a
1601 // transpose with a group size of 2^n will take place. If multiple bits are
1602 // set, multiple transposes will happen: vdealvdd will perform them starting
1603 // with the largest group size, vshuffvdd will do them in the reverse order.
1604 //
1605 // The main observation is that each 2x2 transpose corresponds to swapping
1606 // columns of bits in the binary representation of the values.
1607 //
1608 // The numbers {3,2,1,0} and the log2 of the number of contiguous 1 bits
1609 // in a given column. The * denote the columns that will be swapped.
1610 // The transpose with the group size 2^n corresponds to swapping columns
1611 // 3 (the highest log) and log2(n):
1612 //
1613 // 3 2 1 0 0 2 1 3 0 2 3 1
1614 // * * * * * *
1615 // 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
1616 // 1 0 0 0 1 8 1 0 0 0 8 1 0 0 0 8 1 0 0 0
1617 // 2 0 0 1 0 2 0 0 1 0 1 0 0 0 1 1 0 0 0 1
1618 // 3 0 0 1 1 A 1 0 1 0 9 1 0 0 1 9 1 0 0 1
1619 // 4 0 1 0 0 4 0 1 0 0 4 0 1 0 0 2 0 0 1 0
1620 // 5 0 1 0 1 C 1 1 0 0 C 1 1 0 0 A 1 0 1 0
1621 // 6 0 1 1 0 6 0 1 1 0 5 0 1 0 1 3 0 0 1 1
1622 // 7 0 1 1 1 E 1 1 1 0 D 1 1 0 1 B 1 0 1 1
1623 // 8 1 0 0 0 1 0 0 0 1 2 0 0 1 0 4 0 1 0 0
1624 // 9 1 0 0 1 9 1 0 0 1 A 1 0 1 0 C 1 1 0 0
1625 // A 1 0 1 0 3 0 0 1 1 3 0 0 1 1 5 0 1 0 1
1626 // B 1 0 1 1 B 1 0 1 1 B 1 0 1 1 D 1 1 0 1
1627 // C 1 1 0 0 5 0 1 0 1 6 0 1 1 0 6 0 1 1 0
1628 // D 1 1 0 1 D 1 1 0 1 E 1 1 1 0 E 1 1 1 0
1629 // E 1 1 1 0 7 0 1 1 1 7 0 1 1 1 7 0 1 1 1
1630 // F 1 1 1 1 F 1 1 1 1 F 1 1 1 1 F 1 1 1 1
1631
1632 auto XorPow2 = [] (ArrayRef<int> Mask, unsigned Num) {
1633 unsigned X = Mask[0] ^ Mask[Num/2];
1634 // Check that the first half has the X's bits clear.
1635 if ((Mask[0] & X) != 0)
1636 return 0u;
1637 for (unsigned I = 1; I != Num/2; ++I) {
1638 if (unsigned(Mask[I] ^ Mask[I+Num/2]) != X)
1639 return 0u;
1640 if ((Mask[I] & X) != 0)
1641 return 0u;
1642 }
1643 return X;
1644 };
1645
1646 // Create a vector of log2's for each column: Perm[i] corresponds to
1647 // the i-th bit (lsb is 0).
1648 assert(VecLen > 2);
1649 for (unsigned I = VecLen; I >= 2; I >>= 1) {
1650 // Examine the initial segment of Mask of size I.
1651 unsigned X = XorPow2(SM.Mask, I);
1652 if (!isPowerOf2_32(X))
1653 return OpRef::fail();
1654 // Check the other segments of Mask.
1655 for (int J = 0; J < VecLen; J += I) {
1656 if (XorPow2(subm(SM.Mask, -J), I) != X)
1657 return OpRef::fail();
1658 }
1659 Perm[Log2_32(X)] = Log2_32(I)-1;
1660 }
1661
1662 // Once we have Perm, represent it as cycles. Denote the maximum log2
1663 // (equal to log2(VecLen)-1) as M. The cycle containing M can then be
1664 // written as (M a1 a2 a3 ... an). That cycle can be broken up into
1665 // simple swaps as (M a1)(M a2)(M a3)...(M an), with the composition
1666 // order being from left to right. Any (contiguous) segment where the
1667 // values ai, ai+1...aj are either all increasing or all decreasing,
1668 // can be implemented via a single vshuffvdd/vdealvdd respectively.
1669 //
1670 // If there is a cycle (a1 a2 ... an) that does not involve M, it can
1671 // be written as (M an)(a1 a2 ... an)(M a1). The first two cycles can
1672 // then be folded to get (M a1 a2 ... an)(M a1), and the above procedure
1673 // can be used to generate a sequence of vshuffvdd/vdealvdd.
1674 //
1675 // Example:
1676 // Assume M = 4 and consider a permutation (0 1)(2 3). It can be written
1677 // as (4 0 1)(4 0) composed with (4 2 3)(4 2), or simply
1678 // (4 0 1)(4 0)(4 2 3)(4 2).
1679 // It can then be expanded into swaps as
1680 // (4 0)(4 1)(4 0)(4 2)(4 3)(4 2),
1681 // and broken up into "increasing" segments as
1682 // [(4 0)(4 1)] [(4 0)(4 2)(4 3)] [(4 2)].
1683 // This is equivalent to
1684 // (4 0 1)(4 0 2 3)(4 2),
1685 // which can be implemented as 3 vshufvdd instructions.
1686
1687 using CycleType = SmallVector<unsigned,8>;
1688 std::set<CycleType> Cycles;
1689 std::set<unsigned> All;
1690
1691 for (unsigned I : Perm)
1692 All.insert(I);
1693
1694 // If the cycle contains LogLen-1, move it to the front of the cycle.
1695 // Otherwise, return the cycle unchanged.
1696 auto canonicalize = [LogLen](const CycleType &C) -> CycleType {
1697 unsigned LogPos, N = C.size();
1698 for (LogPos = 0; LogPos != N; ++LogPos)
1699 if (C[LogPos] == LogLen-1)
1700 break;
1701 if (LogPos == N)
1702 return C;
1703
1704 CycleType NewC(C.begin()+LogPos, C.end());
1705 NewC.append(C.begin(), C.begin()+LogPos);
1706 return NewC;
1707 };
1708
Krzysztof Parzyszekd2967862017-12-06 22:41:49 +00001709 auto pfs = [](const std::set<CycleType> &Cs, unsigned Len) {
1710 // Ordering: shuff: 5 0 1 2 3 4, deal: 5 4 3 2 1 0 (for Log=6),
1711 // for bytes zero is included, for halfwords is not.
1712 if (Cs.size() != 1)
1713 return 0u;
1714 const CycleType &C = *Cs.begin();
1715 if (C[0] != Len-1)
1716 return 0u;
1717 int D = Len - C.size();
1718 if (D != 0 && D != 1)
1719 return 0u;
1720
1721 bool IsDeal = true, IsShuff = true;
1722 for (unsigned I = 1; I != Len-D; ++I) {
1723 if (C[I] != Len-1-I)
1724 IsDeal = false;
1725 if (C[I] != I-(1-D)) // I-1, I
1726 IsShuff = false;
1727 }
1728 // At most one, IsDeal or IsShuff, can be non-zero.
1729 assert(!(IsDeal || IsShuff) || IsDeal != IsShuff);
1730 static unsigned Deals[] = { Hexagon::V6_vdealb, Hexagon::V6_vdealh };
1731 static unsigned Shufs[] = { Hexagon::V6_vshuffb, Hexagon::V6_vshuffh };
1732 return IsDeal ? Deals[D] : (IsShuff ? Shufs[D] : 0);
1733 };
1734
Krzysztof Parzyszek7d37dd82017-12-06 16:40:37 +00001735 while (!All.empty()) {
1736 unsigned A = *All.begin();
1737 All.erase(A);
1738 CycleType C;
1739 C.push_back(A);
1740 for (unsigned B = Perm[A]; B != A; B = Perm[B]) {
1741 C.push_back(B);
1742 All.erase(B);
1743 }
1744 if (C.size() <= 1)
1745 continue;
1746 Cycles.insert(canonicalize(C));
1747 }
1748
Krzysztof Parzyszekd2967862017-12-06 22:41:49 +00001749 MVT SingleTy = getSingleVT(MVT::i8);
1750 MVT PairTy = getPairVT(MVT::i8);
1751
1752 // Recognize patterns for V6_vdeal{b,h} and V6_vshuff{b,h}.
1753 if (unsigned(VecLen) == HwLen) {
1754 if (unsigned SingleOpc = pfs(Cycles, LogLen)) {
1755 Results.push(SingleOpc, SingleTy, {Va});
1756 return OpRef::res(Results.top());
1757 }
1758 }
1759
Krzysztof Parzyszek7d37dd82017-12-06 16:40:37 +00001760 SmallVector<unsigned,8> SwapElems;
1761 if (HwLen == unsigned(VecLen))
1762 SwapElems.push_back(LogLen-1);
1763
1764 for (const CycleType &C : Cycles) {
1765 unsigned First = (C[0] == LogLen-1) ? 1 : 0;
1766 SwapElems.append(C.begin()+First, C.end());
1767 if (First == 0)
1768 SwapElems.push_back(C[0]);
1769 }
1770
Krzysztof Parzyszek64533cf2017-12-06 21:25:03 +00001771 const SDLoc &dl(Results.InpNode);
1772 OpRef Arg = !Extend ? Va
1773 : concat(Va, OpRef::undef(SingleTy), Results);
Krzysztof Parzyszek7d37dd82017-12-06 16:40:37 +00001774
1775 for (unsigned I = 0, E = SwapElems.size(); I != E; ) {
1776 bool IsInc = I == E-1 || SwapElems[I] < SwapElems[I+1];
1777 unsigned S = (1u << SwapElems[I]);
1778 if (I < E-1) {
1779 while (++I < E-1 && IsInc == (SwapElems[I] < SwapElems[I+1]))
1780 S |= 1u << SwapElems[I];
1781 // The above loop will not add a bit for the final SwapElems[I+1],
1782 // so add it here.
1783 S |= 1u << SwapElems[I];
1784 }
1785 ++I;
1786
1787 NodeTemplate Res;
1788 Results.push(Hexagon::A2_tfrsi, MVT::i32,
1789 { DAG.getTargetConstant(S, dl, MVT::i32) });
1790 Res.Opc = IsInc ? Hexagon::V6_vshuffvdd : Hexagon::V6_vdealvdd;
1791 Res.Ty = PairTy;
1792 Res.Ops = { OpRef::hi(Arg), OpRef::lo(Arg), OpRef::res(-1) };
1793 Results.push(Res);
1794 Arg = OpRef::res(Results.top());
1795 }
1796
Krzysztof Parzyszek64533cf2017-12-06 21:25:03 +00001797 return !Extend ? Arg : OpRef::lo(Arg);
Krzysztof Parzyszek7d37dd82017-12-06 16:40:37 +00001798}
1799
1800OpRef HvxSelector::butterfly(ShuffleMask SM, OpRef Va, ResultStack &Results) {
1801 DEBUG_WITH_TYPE("isel", {dbgs() << __func__ << '\n';});
1802 // Butterfly shuffles.
1803 //
1804 // V6_vdelta
1805 // V6_vrdelta
1806 // V6_vror
1807
1808 // The assumption here is that all elements picked by Mask are in the
1809 // first operand to the vector_shuffle. This assumption is enforced
1810 // by the caller.
1811
1812 MVT ResTy = getSingleVT(MVT::i8);
1813 PermNetwork::Controls FC, RC;
1814 const SDLoc &dl(Results.InpNode);
1815 int VecLen = SM.Mask.size();
1816
1817 for (int M : SM.Mask) {
1818 if (M != -1 && M >= VecLen)
1819 return OpRef::fail();
1820 }
1821
1822 // Try the deltas/benes for both single vectors and vector pairs.
1823 ForwardDeltaNetwork FN(SM.Mask);
1824 if (FN.run(FC)) {
1825 SDValue Ctl = getVectorConstant(FC, dl);
1826 Results.push(Hexagon::V6_vdelta, ResTy, {Va, OpRef(Ctl)});
1827 return OpRef::res(Results.top());
1828 }
1829
1830 // Try reverse delta.
1831 ReverseDeltaNetwork RN(SM.Mask);
1832 if (RN.run(RC)) {
1833 SDValue Ctl = getVectorConstant(RC, dl);
1834 Results.push(Hexagon::V6_vrdelta, ResTy, {Va, OpRef(Ctl)});
1835 return OpRef::res(Results.top());
1836 }
1837
1838 // Do Benes.
1839 BenesNetwork BN(SM.Mask);
1840 if (BN.run(FC, RC)) {
1841 SDValue CtlF = getVectorConstant(FC, dl);
1842 SDValue CtlR = getVectorConstant(RC, dl);
1843 Results.push(Hexagon::V6_vdelta, ResTy, {Va, OpRef(CtlF)});
1844 Results.push(Hexagon::V6_vrdelta, ResTy,
1845 {OpRef::res(-1), OpRef(CtlR)});
1846 return OpRef::res(Results.top());
1847 }
1848
1849 return OpRef::fail();
1850}
1851
1852SDValue HvxSelector::getVectorConstant(ArrayRef<uint8_t> Data,
1853 const SDLoc &dl) {
1854 SmallVector<SDValue, 128> Elems;
1855 for (uint8_t C : Data)
1856 Elems.push_back(DAG.getConstant(C, dl, MVT::i8));
1857 MVT VecTy = MVT::getVectorVT(MVT::i8, Data.size());
1858 SDValue BV = DAG.getBuildVector(VecTy, dl, Elems);
1859 SDValue LV = Lower.LowerOperation(BV, DAG);
1860 DAG.RemoveDeadNode(BV.getNode());
1861 return LV;
1862}
1863
1864void HvxSelector::selectShuffle(SDNode *N) {
1865 DEBUG_WITH_TYPE("isel", {
1866 dbgs() << "Starting " << __func__ << " on node:\n";
1867 N->dump(&DAG);
1868 });
1869 MVT ResTy = N->getValueType(0).getSimpleVT();
1870 // Assume that vector shuffles operate on vectors of bytes.
1871 assert(ResTy.isVector() && ResTy.getVectorElementType() == MVT::i8);
1872
1873 auto *SN = cast<ShuffleVectorSDNode>(N);
1874 std::vector<int> Mask(SN->getMask().begin(), SN->getMask().end());
1875 // This shouldn't really be necessary. Is it?
1876 for (int &Idx : Mask)
1877 if (Idx != -1 && Idx < 0)
1878 Idx = -1;
1879
1880 unsigned VecLen = Mask.size();
1881 bool HavePairs = (2*HwLen == VecLen);
1882 assert(ResTy.getSizeInBits() / 8 == VecLen);
1883
1884 // Vd = vector_shuffle Va, Vb, Mask
1885 //
1886
1887 bool UseLeft = false, UseRight = false;
1888 for (unsigned I = 0; I != VecLen; ++I) {
1889 if (Mask[I] == -1)
1890 continue;
1891 unsigned Idx = Mask[I];
1892 assert(Idx < 2*VecLen);
1893 if (Idx < VecLen)
1894 UseLeft = true;
1895 else
1896 UseRight = true;
1897 }
1898
1899 DEBUG_WITH_TYPE("isel", {
1900 dbgs() << "VecLen=" << VecLen << " HwLen=" << HwLen << " UseLeft="
1901 << UseLeft << " UseRight=" << UseRight << " HavePairs="
1902 << HavePairs << '\n';
1903 });
1904 // If the mask is all -1's, generate "undef".
1905 if (!UseLeft && !UseRight) {
1906 ISel.ReplaceNode(N, ISel.selectUndef(SDLoc(SN), ResTy).getNode());
1907 DAG.RemoveDeadNode(N);
1908 return;
1909 }
1910
1911 SDValue Vec0 = N->getOperand(0);
1912 SDValue Vec1 = N->getOperand(1);
1913 ResultStack Results(SN);
1914 Results.push(TargetOpcode::COPY, ResTy, {Vec0});
1915 Results.push(TargetOpcode::COPY, ResTy, {Vec1});
1916 OpRef Va = OpRef::res(Results.top()-1);
1917 OpRef Vb = OpRef::res(Results.top());
1918
1919 OpRef Res = !HavePairs ? shuffs2(ShuffleMask(Mask), Va, Vb, Results)
1920 : shuffp2(ShuffleMask(Mask), Va, Vb, Results);
1921
1922 bool Done = Res.isValid();
Krzysztof Parzyszek64533cf2017-12-06 21:25:03 +00001923 if (Done) {
1924 // Make sure that Res is on the stack before materializing.
1925 Results.push(TargetOpcode::COPY, ResTy, {Res});
Krzysztof Parzyszek7d37dd82017-12-06 16:40:37 +00001926 materialize(Results);
Krzysztof Parzyszek64533cf2017-12-06 21:25:03 +00001927 } else {
Krzysztof Parzyszek7d37dd82017-12-06 16:40:37 +00001928 Done = scalarizeShuffle(Mask, SDLoc(N), ResTy, Vec0, Vec1, N);
Krzysztof Parzyszek64533cf2017-12-06 21:25:03 +00001929 }
Krzysztof Parzyszek7d37dd82017-12-06 16:40:37 +00001930
1931 if (!Done) {
1932#ifndef NDEBUG
1933 dbgs() << "Unhandled shuffle:\n";
1934 SN->dumpr(&DAG);
1935#endif
1936 llvm_unreachable("Failed to select vector shuffle");
1937 }
1938}
1939
1940void HvxSelector::selectRor(SDNode *N) {
1941 // If this is a rotation by less than 8, use V6_valignbi.
1942 MVT Ty = N->getValueType(0).getSimpleVT();
1943 const SDLoc &dl(N);
1944 SDValue VecV = N->getOperand(0);
1945 SDValue RotV = N->getOperand(1);
1946 SDNode *NewN = nullptr;
1947
1948 if (auto *CN = dyn_cast<ConstantSDNode>(RotV.getNode())) {
1949 unsigned S = CN->getZExtValue();
1950 if (S % HST.getVectorLength() == 0) {
1951 NewN = VecV.getNode();
1952 } else if (isUInt<3>(S)) {
1953 SDValue C = DAG.getTargetConstant(S, dl, MVT::i32);
1954 NewN = DAG.getMachineNode(Hexagon::V6_valignbi, dl, Ty,
1955 {VecV, VecV, C});
1956 }
1957 }
1958
1959 if (!NewN)
1960 NewN = DAG.getMachineNode(Hexagon::V6_vror, dl, Ty, {VecV, RotV});
1961
1962 ISel.ReplaceNode(N, NewN);
1963 DAG.RemoveDeadNode(N);
1964}
1965
1966void HexagonDAGToDAGISel::SelectHvxShuffle(SDNode *N) {
1967 HvxSelector(*this, *CurDAG).selectShuffle(N);
1968}
1969
1970void HexagonDAGToDAGISel::SelectHvxRor(SDNode *N) {
1971 HvxSelector(*this, *CurDAG).selectRor(N);
1972}
1973