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