blob: 637fb3ace6a427ea62c2a5018193b03ce943c6de [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
Fangrui Song956ee792018-03-30 22:22:31 +0000262 // Explicitly assign "None" to all uncolored nodes.
Krzysztof Parzyszek7d37dd82017-12-06 16:40:37 +0000263 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 }
Krzysztof Parzyszeke3e96322018-03-02 22:22:19 +0000779
780 void print(raw_ostream &OS) const {
781 OS << "MinSrc:" << MinSrc << ", MaxSrc:" << MaxSrc << " {";
782 for (int M : Mask)
783 OS << ' ' << M;
784 OS << " }";
785 }
Krzysztof Parzyszek7d37dd82017-12-06 16:40:37 +0000786};
Benjamin Kramer802e6252017-12-24 12:46:22 +0000787} // namespace
Krzysztof Parzyszek7d37dd82017-12-06 16:40:37 +0000788
789// --------------------------------------------------------------------
790// The HvxSelector class.
791
792static const HexagonTargetLowering &getHexagonLowering(SelectionDAG &G) {
793 return static_cast<const HexagonTargetLowering&>(G.getTargetLoweringInfo());
794}
795static const HexagonSubtarget &getHexagonSubtarget(SelectionDAG &G) {
796 return static_cast<const HexagonSubtarget&>(G.getSubtarget());
797}
798
799namespace llvm {
800 struct HvxSelector {
801 const HexagonTargetLowering &Lower;
802 HexagonDAGToDAGISel &ISel;
803 SelectionDAG &DAG;
804 const HexagonSubtarget &HST;
805 const unsigned HwLen;
806
807 HvxSelector(HexagonDAGToDAGISel &HS, SelectionDAG &G)
808 : Lower(getHexagonLowering(G)), ISel(HS), DAG(G),
809 HST(getHexagonSubtarget(G)), HwLen(HST.getVectorLength()) {}
810
811 MVT getSingleVT(MVT ElemTy) const {
812 unsigned NumElems = HwLen / (ElemTy.getSizeInBits()/8);
813 return MVT::getVectorVT(ElemTy, NumElems);
814 }
815
816 MVT getPairVT(MVT ElemTy) const {
817 unsigned NumElems = (2*HwLen) / (ElemTy.getSizeInBits()/8);
818 return MVT::getVectorVT(ElemTy, NumElems);
819 }
820
821 void selectShuffle(SDNode *N);
822 void selectRor(SDNode *N);
Krzysztof Parzyszek2c3edf02018-03-07 17:27:18 +0000823 void selectVAlign(SDNode *N);
Krzysztof Parzyszek7d37dd82017-12-06 16:40:37 +0000824
825 private:
826 void materialize(const ResultStack &Results);
827
828 SDValue getVectorConstant(ArrayRef<uint8_t> Data, const SDLoc &dl);
829
830 enum : unsigned {
831 None,
832 PackMux,
833 };
834 OpRef concat(OpRef Va, OpRef Vb, ResultStack &Results);
835 OpRef packs(ShuffleMask SM, OpRef Va, OpRef Vb, ResultStack &Results,
836 MutableArrayRef<int> NewMask, unsigned Options = None);
837 OpRef packp(ShuffleMask SM, OpRef Va, OpRef Vb, ResultStack &Results,
838 MutableArrayRef<int> NewMask);
Krzysztof Parzyszek7d37dd82017-12-06 16:40:37 +0000839 OpRef vmuxs(ArrayRef<uint8_t> Bytes, OpRef Va, OpRef Vb,
840 ResultStack &Results);
841 OpRef vmuxp(ArrayRef<uint8_t> Bytes, OpRef Va, OpRef Vb,
842 ResultStack &Results);
843
844 OpRef shuffs1(ShuffleMask SM, OpRef Va, ResultStack &Results);
845 OpRef shuffs2(ShuffleMask SM, OpRef Va, OpRef Vb, ResultStack &Results);
846 OpRef shuffp1(ShuffleMask SM, OpRef Va, ResultStack &Results);
847 OpRef shuffp2(ShuffleMask SM, OpRef Va, OpRef Vb, ResultStack &Results);
848
849 OpRef butterfly(ShuffleMask SM, OpRef Va, ResultStack &Results);
850 OpRef contracting(ShuffleMask SM, OpRef Va, OpRef Vb, ResultStack &Results);
851 OpRef expanding(ShuffleMask SM, OpRef Va, ResultStack &Results);
852 OpRef perfect(ShuffleMask SM, OpRef Va, ResultStack &Results);
853
854 bool selectVectorConstants(SDNode *N);
855 bool scalarizeShuffle(ArrayRef<int> Mask, const SDLoc &dl, MVT ResTy,
856 SDValue Va, SDValue Vb, SDNode *N);
857
858 };
859}
860
Krzysztof Parzyszek7d37dd82017-12-06 16:40:37 +0000861static void splitMask(ArrayRef<int> Mask, MutableArrayRef<int> MaskL,
862 MutableArrayRef<int> MaskR) {
863 unsigned VecLen = Mask.size();
864 assert(MaskL.size() == VecLen && MaskR.size() == VecLen);
865 for (unsigned I = 0; I != VecLen; ++I) {
866 int M = Mask[I];
867 if (M < 0) {
868 MaskL[I] = MaskR[I] = -1;
869 } else if (unsigned(M) < VecLen) {
870 MaskL[I] = M;
871 MaskR[I] = -1;
872 } else {
873 MaskL[I] = -1;
874 MaskR[I] = M-VecLen;
875 }
876 }
877}
878
879static std::pair<int,unsigned> findStrip(ArrayRef<int> A, int Inc,
880 unsigned MaxLen) {
881 assert(A.size() > 0 && A.size() >= MaxLen);
882 int F = A[0];
883 int E = F;
884 for (unsigned I = 1; I != MaxLen; ++I) {
885 if (A[I] - E != Inc)
886 return { F, I };
887 E = A[I];
888 }
889 return { F, MaxLen };
890}
891
892static bool isUndef(ArrayRef<int> Mask) {
893 for (int Idx : Mask)
894 if (Idx != -1)
895 return false;
896 return true;
897}
898
899static bool isIdentity(ArrayRef<int> Mask) {
Krzysztof Parzyszekedcd9dc2017-12-12 20:23:12 +0000900 for (int I = 0, E = Mask.size(); I != E; ++I) {
901 int M = Mask[I];
902 if (M >= 0 && M != I)
903 return false;
904 }
905 return true;
Krzysztof Parzyszek7d37dd82017-12-06 16:40:37 +0000906}
907
908static bool isPermutation(ArrayRef<int> Mask) {
909 // Check by adding all numbers only works if there is no overflow.
910 assert(Mask.size() < 0x00007FFF && "Sanity failure");
911 int Sum = 0;
912 for (int Idx : Mask) {
913 if (Idx == -1)
914 return false;
915 Sum += Idx;
916 }
917 int N = Mask.size();
918 return 2*Sum == N*(N-1);
919}
920
921bool HvxSelector::selectVectorConstants(SDNode *N) {
Krzysztof Parzyszek41a24b72018-04-20 19:38:37 +0000922 // Constant vectors are generated as loads from constant pools or as
923 // splats of a constant value. Since they are generated during the
924 // selection process, the main selection algorithm is not aware of them.
925 // Select them directly here.
Krzysztof Parzyszek90ca4e82018-01-26 21:54:56 +0000926 SmallVector<SDNode*,4> Nodes;
Krzysztof Parzyszeke156e9b2018-01-11 17:59:34 +0000927 SetVector<SDNode*> WorkQ;
Krzysztof Parzyszeke7045832017-12-18 23:13:27 +0000928
Krzysztof Parzyszek41a24b72018-04-20 19:38:37 +0000929 // The one-use test for VSPLATW's operand may fail due to dead nodes
930 // left over in the DAG.
931 DAG.RemoveDeadNodes();
932
Krzysztof Parzyszeke7045832017-12-18 23:13:27 +0000933 // The DAG can change (due to CSE) during selection, so cache all the
934 // unselected nodes first to avoid traversing a mutating DAG.
935
Krzysztof Parzyszek90ca4e82018-01-26 21:54:56 +0000936 auto IsNodeToSelect = [] (SDNode *N) {
937 if (N->isMachineOpcode())
938 return false;
Krzysztof Parzyszek41a24b72018-04-20 19:38:37 +0000939 switch (N->getOpcode()) {
940 case HexagonISD::VZERO:
941 case HexagonISD::VSPLATW:
Krzysztof Parzyszek8cc636c2018-01-31 16:48:20 +0000942 return true;
Krzysztof Parzyszek41a24b72018-04-20 19:38:37 +0000943 case ISD::LOAD: {
944 SDValue Addr = cast<LoadSDNode>(N)->getBasePtr();
945 unsigned AddrOpc = Addr.getOpcode();
946 if (AddrOpc == HexagonISD::AT_PCREL || AddrOpc == HexagonISD::CP)
947 if (Addr.getOperand(0).getOpcode() == ISD::TargetConstantPool)
948 return true;
949 }
950 break;
Krzysztof Parzyszek8cc636c2018-01-31 16:48:20 +0000951 }
Krzysztof Parzyszek41a24b72018-04-20 19:38:37 +0000952 // Make sure to select the operand of VSPLATW.
953 bool IsSplatOp = N->hasOneUse() &&
954 N->use_begin()->getOpcode() == HexagonISD::VSPLATW;
955 return IsSplatOp;
Krzysztof Parzyszeke7045832017-12-18 23:13:27 +0000956 };
957
Krzysztof Parzyszeke156e9b2018-01-11 17:59:34 +0000958 WorkQ.insert(N);
Krzysztof Parzyszeke7045832017-12-18 23:13:27 +0000959 for (unsigned i = 0; i != WorkQ.size(); ++i) {
960 SDNode *W = WorkQ[i];
Krzysztof Parzyszek90ca4e82018-01-26 21:54:56 +0000961 if (IsNodeToSelect(W))
962 Nodes.push_back(W);
Krzysztof Parzyszeke7045832017-12-18 23:13:27 +0000963 for (unsigned j = 0, f = W->getNumOperands(); j != f; ++j)
Krzysztof Parzyszeke156e9b2018-01-11 17:59:34 +0000964 WorkQ.insert(W->getOperand(j).getNode());
Krzysztof Parzyszek7d37dd82017-12-06 16:40:37 +0000965 }
966
Krzysztof Parzyszek90ca4e82018-01-26 21:54:56 +0000967 for (SDNode *L : Nodes)
Krzysztof Parzyszeke7045832017-12-18 23:13:27 +0000968 ISel.Select(L);
969
Krzysztof Parzyszek90ca4e82018-01-26 21:54:56 +0000970 return !Nodes.empty();
Krzysztof Parzyszek7d37dd82017-12-06 16:40:37 +0000971}
972
973void HvxSelector::materialize(const ResultStack &Results) {
974 DEBUG_WITH_TYPE("isel", {
975 dbgs() << "Materializing\n";
976 Results.print(dbgs(), DAG);
977 });
978 if (Results.empty())
979 return;
980 const SDLoc &dl(Results.InpNode);
981 std::vector<SDValue> Output;
982
983 for (unsigned I = 0, E = Results.size(); I != E; ++I) {
984 const NodeTemplate &Node = Results[I];
985 std::vector<SDValue> Ops;
986 for (const OpRef &R : Node.Ops) {
987 assert(R.isValid());
988 if (R.isValue()) {
989 Ops.push_back(R.OpV);
990 continue;
991 }
992 if (R.OpN & OpRef::Undef) {
993 MVT::SimpleValueType SVT = MVT::SimpleValueType(R.OpN & OpRef::Index);
994 Ops.push_back(ISel.selectUndef(dl, MVT(SVT)));
995 continue;
996 }
997 // R is an index of a result.
998 unsigned Part = R.OpN & OpRef::Whole;
999 int Idx = SignExtend32(R.OpN & OpRef::Index, OpRef::IndexBits);
1000 if (Idx < 0)
1001 Idx += I;
1002 assert(Idx >= 0 && unsigned(Idx) < Output.size());
1003 SDValue Op = Output[Idx];
1004 MVT OpTy = Op.getValueType().getSimpleVT();
1005 if (Part != OpRef::Whole) {
1006 assert(Part == OpRef::LoHalf || Part == OpRef::HiHalf);
Krzysztof Parzyszek5aef4b52018-01-24 14:07:37 +00001007 MVT HalfTy = MVT::getVectorVT(OpTy.getVectorElementType(),
1008 OpTy.getVectorNumElements()/2);
1009 unsigned Sub = (Part == OpRef::LoHalf) ? Hexagon::vsub_lo
1010 : Hexagon::vsub_hi;
1011 Op = DAG.getTargetExtractSubreg(Sub, dl, HalfTy, Op);
Krzysztof Parzyszek7d37dd82017-12-06 16:40:37 +00001012 }
1013 Ops.push_back(Op);
1014 } // for (Node : Results)
1015
1016 assert(Node.Ty != MVT::Other);
1017 SDNode *ResN = (Node.Opc == TargetOpcode::COPY)
1018 ? Ops.front().getNode()
1019 : DAG.getMachineNode(Node.Opc, dl, Node.Ty, Ops);
1020 Output.push_back(SDValue(ResN, 0));
1021 }
1022
1023 SDNode *OutN = Output.back().getNode();
1024 SDNode *InpN = Results.InpNode;
1025 DEBUG_WITH_TYPE("isel", {
1026 dbgs() << "Generated node:\n";
1027 OutN->dumpr(&DAG);
1028 });
1029
1030 ISel.ReplaceNode(InpN, OutN);
1031 selectVectorConstants(OutN);
1032 DAG.RemoveDeadNodes();
1033}
1034
1035OpRef HvxSelector::concat(OpRef Lo, OpRef Hi, ResultStack &Results) {
1036 DEBUG_WITH_TYPE("isel", {dbgs() << __func__ << '\n';});
1037 const SDLoc &dl(Results.InpNode);
1038 Results.push(TargetOpcode::REG_SEQUENCE, getPairVT(MVT::i8), {
1039 DAG.getTargetConstant(Hexagon::HvxWRRegClassID, dl, MVT::i32),
1040 Lo, DAG.getTargetConstant(Hexagon::vsub_lo, dl, MVT::i32),
1041 Hi, DAG.getTargetConstant(Hexagon::vsub_hi, dl, MVT::i32),
1042 });
1043 return OpRef::res(Results.top());
1044}
1045
1046// Va, Vb are single vectors, SM can be arbitrarily long.
1047OpRef HvxSelector::packs(ShuffleMask SM, OpRef Va, OpRef Vb,
1048 ResultStack &Results, MutableArrayRef<int> NewMask,
1049 unsigned Options) {
1050 DEBUG_WITH_TYPE("isel", {dbgs() << __func__ << '\n';});
1051 if (!Va.isValid() || !Vb.isValid())
1052 return OpRef::fail();
1053
1054 int VecLen = SM.Mask.size();
1055 MVT Ty = getSingleVT(MVT::i8);
1056
Krzysztof Parzyszek89871742018-05-30 13:45:34 +00001057 auto IsExtSubvector = [] (ShuffleMask M) {
Krzysztof Parzyszeke3e96322018-03-02 22:22:19 +00001058 assert(M.MinSrc >= 0 && M.MaxSrc >= 0);
1059 for (int I = 0, E = M.Mask.size(); I != E; ++I) {
1060 if (M.Mask[I] >= 0 && M.Mask[I]-I != M.MinSrc)
1061 return false;
Krzysztof Parzyszek7d37dd82017-12-06 16:40:37 +00001062 }
Krzysztof Parzyszeke3e96322018-03-02 22:22:19 +00001063 return true;
1064 };
1065
1066 if (SM.MaxSrc - SM.MinSrc < int(HwLen)) {
Krzysztof Parzyszek89871742018-05-30 13:45:34 +00001067 if (SM.MinSrc == 0 || SM.MinSrc == int(HwLen) || !IsExtSubvector(SM)) {
Krzysztof Parzyszek95b07352018-05-25 14:53:14 +00001068 // If the mask picks elements from only one of the operands, return
1069 // that operand, and update the mask to use index 0 to refer to the
1070 // first element of that operand.
Krzysztof Parzyszek89871742018-05-30 13:45:34 +00001071 // If the mask extracts a subvector, it will be handled below, so
Krzysztof Parzyszek95b07352018-05-25 14:53:14 +00001072 // skip it here.
Krzysztof Parzyszeke3e96322018-03-02 22:22:19 +00001073 if (SM.MaxSrc < int(HwLen)) {
1074 memcpy(NewMask.data(), SM.Mask.data(), sizeof(int)*VecLen);
1075 return Va;
Krzysztof Parzyszek7d37dd82017-12-06 16:40:37 +00001076 }
Krzysztof Parzyszeke3e96322018-03-02 22:22:19 +00001077 if (SM.MinSrc >= int(HwLen)) {
1078 for (int I = 0; I != VecLen; ++I) {
1079 int M = SM.Mask[I];
1080 if (M != -1)
1081 M -= HwLen;
1082 NewMask[I] = M;
1083 }
1084 return Vb;
1085 }
1086 }
Krzysztof Parzyszek95b07352018-05-25 14:53:14 +00001087 int MinSrc = SM.MinSrc;
Krzysztof Parzyszeke3e96322018-03-02 22:22:19 +00001088 if (SM.MaxSrc < int(HwLen)) {
1089 Vb = Va;
1090 } else if (SM.MinSrc > int(HwLen)) {
1091 Va = Vb;
Krzysztof Parzyszek95b07352018-05-25 14:53:14 +00001092 MinSrc = SM.MinSrc - HwLen;
Krzysztof Parzyszek7d37dd82017-12-06 16:40:37 +00001093 }
1094 const SDLoc &dl(Results.InpNode);
Krzysztof Parzyszek89871742018-05-30 13:45:34 +00001095 if (isUInt<3>(MinSrc) || isUInt<3>(HwLen-MinSrc)) {
1096 bool IsRight = isUInt<3>(MinSrc); // Right align.
1097 SDValue S = DAG.getTargetConstant(IsRight ? MinSrc : HwLen-MinSrc,
1098 dl, MVT::i32);
1099 unsigned Opc = IsRight ? Hexagon::V6_valignbi
1100 : Hexagon::V6_vlalignbi;
1101 Results.push(Opc, Ty, {Vb, Va, S});
Krzysztof Parzyszek7d37dd82017-12-06 16:40:37 +00001102 } else {
Krzysztof Parzyszek89871742018-05-30 13:45:34 +00001103 SDValue S = DAG.getTargetConstant(MinSrc, dl, MVT::i32);
Krzysztof Parzyszek7d37dd82017-12-06 16:40:37 +00001104 Results.push(Hexagon::A2_tfrsi, MVT::i32, {S});
1105 unsigned Top = Results.top();
1106 Results.push(Hexagon::V6_valignb, Ty, {Vb, Va, OpRef::res(Top)});
1107 }
1108 for (int I = 0; I != VecLen; ++I) {
1109 int M = SM.Mask[I];
1110 if (M != -1)
1111 M -= SM.MinSrc;
1112 NewMask[I] = M;
1113 }
1114 return OpRef::res(Results.top());
1115 }
1116
1117 if (Options & PackMux) {
1118 // If elements picked from Va and Vb have all different (source) indexes
1119 // (relative to the start of the argument), do a mux, and update the mask.
1120 BitVector Picked(HwLen);
1121 SmallVector<uint8_t,128> MuxBytes(HwLen);
1122 bool CanMux = true;
1123 for (int I = 0; I != VecLen; ++I) {
1124 int M = SM.Mask[I];
1125 if (M == -1)
1126 continue;
1127 if (M >= int(HwLen))
1128 M -= HwLen;
1129 else
1130 MuxBytes[M] = 0xFF;
1131 if (Picked[M]) {
1132 CanMux = false;
1133 break;
1134 }
1135 NewMask[I] = M;
1136 }
1137 if (CanMux)
1138 return vmuxs(MuxBytes, Va, Vb, Results);
1139 }
1140
1141 return OpRef::fail();
1142}
1143
1144OpRef HvxSelector::packp(ShuffleMask SM, OpRef Va, OpRef Vb,
1145 ResultStack &Results, MutableArrayRef<int> NewMask) {
1146 DEBUG_WITH_TYPE("isel", {dbgs() << __func__ << '\n';});
1147 unsigned HalfMask = 0;
1148 unsigned LogHw = Log2_32(HwLen);
1149 for (int M : SM.Mask) {
1150 if (M == -1)
1151 continue;
1152 HalfMask |= (1u << (M >> LogHw));
1153 }
1154
1155 if (HalfMask == 0)
1156 return OpRef::undef(getPairVT(MVT::i8));
1157
1158 // If more than two halves are used, bail.
1159 // TODO: be more aggressive here?
1160 if (countPopulation(HalfMask) > 2)
1161 return OpRef::fail();
1162
1163 MVT HalfTy = getSingleVT(MVT::i8);
1164
1165 OpRef Inp[2] = { Va, Vb };
1166 OpRef Out[2] = { OpRef::undef(HalfTy), OpRef::undef(HalfTy) };
1167
1168 uint8_t HalfIdx[4] = { 0xFF, 0xFF, 0xFF, 0xFF };
1169 unsigned Idx = 0;
1170 for (unsigned I = 0; I != 4; ++I) {
1171 if ((HalfMask & (1u << I)) == 0)
1172 continue;
1173 assert(Idx < 2);
1174 OpRef Op = Inp[I/2];
1175 Out[Idx] = (I & 1) ? OpRef::hi(Op) : OpRef::lo(Op);
1176 HalfIdx[I] = Idx++;
1177 }
1178
1179 int VecLen = SM.Mask.size();
1180 for (int I = 0; I != VecLen; ++I) {
1181 int M = SM.Mask[I];
1182 if (M >= 0) {
1183 uint8_t Idx = HalfIdx[M >> LogHw];
1184 assert(Idx == 0 || Idx == 1);
1185 M = (M & (HwLen-1)) + HwLen*Idx;
1186 }
1187 NewMask[I] = M;
1188 }
1189
1190 return concat(Out[0], Out[1], Results);
1191}
1192
Krzysztof Parzyszek7d37dd82017-12-06 16:40:37 +00001193OpRef HvxSelector::vmuxs(ArrayRef<uint8_t> Bytes, OpRef Va, OpRef Vb,
1194 ResultStack &Results) {
1195 DEBUG_WITH_TYPE("isel", {dbgs() << __func__ << '\n';});
1196 MVT ByteTy = getSingleVT(MVT::i8);
1197 MVT BoolTy = MVT::getVectorVT(MVT::i1, 8*HwLen); // XXX
1198 const SDLoc &dl(Results.InpNode);
1199 SDValue B = getVectorConstant(Bytes, dl);
1200 Results.push(Hexagon::V6_vd0, ByteTy, {});
1201 Results.push(Hexagon::V6_veqb, BoolTy, {OpRef(B), OpRef::res(-1)});
Krzysztof Parzyszek40a605f2017-12-12 19:32:41 +00001202 Results.push(Hexagon::V6_vmux, ByteTy, {OpRef::res(-1), Vb, Va});
Krzysztof Parzyszek7d37dd82017-12-06 16:40:37 +00001203 return OpRef::res(Results.top());
1204}
1205
1206OpRef HvxSelector::vmuxp(ArrayRef<uint8_t> Bytes, OpRef Va, OpRef Vb,
1207 ResultStack &Results) {
1208 DEBUG_WITH_TYPE("isel", {dbgs() << __func__ << '\n';});
1209 size_t S = Bytes.size() / 2;
Krzysztof Parzyszek3f84c0f2017-12-20 20:54:13 +00001210 OpRef L = vmuxs(Bytes.take_front(S), OpRef::lo(Va), OpRef::lo(Vb), Results);
1211 OpRef H = vmuxs(Bytes.drop_front(S), OpRef::hi(Va), OpRef::hi(Vb), Results);
Krzysztof Parzyszek7d37dd82017-12-06 16:40:37 +00001212 return concat(L, H, Results);
1213}
1214
1215OpRef HvxSelector::shuffs1(ShuffleMask SM, OpRef Va, ResultStack &Results) {
1216 DEBUG_WITH_TYPE("isel", {dbgs() << __func__ << '\n';});
1217 unsigned VecLen = SM.Mask.size();
1218 assert(HwLen == VecLen);
Tim Shenb684b1a2017-12-06 19:33:42 +00001219 (void)VecLen;
Krzysztof Parzyszek7d37dd82017-12-06 16:40:37 +00001220 assert(all_of(SM.Mask, [this](int M) { return M == -1 || M < int(HwLen); }));
1221
1222 if (isIdentity(SM.Mask))
1223 return Va;
1224 if (isUndef(SM.Mask))
1225 return OpRef::undef(getSingleVT(MVT::i8));
1226
Krzysztof Parzyszek64533cf2017-12-06 21:25:03 +00001227 OpRef P = perfect(SM, Va, Results);
1228 if (P.isValid())
1229 return P;
Krzysztof Parzyszek7d37dd82017-12-06 16:40:37 +00001230 return butterfly(SM, Va, Results);
1231}
1232
1233OpRef HvxSelector::shuffs2(ShuffleMask SM, OpRef Va, OpRef Vb,
1234 ResultStack &Results) {
1235 DEBUG_WITH_TYPE("isel", {dbgs() << __func__ << '\n';});
Krzysztof Parzyszekedcd9dc2017-12-12 20:23:12 +00001236 if (isUndef(SM.Mask))
1237 return OpRef::undef(getSingleVT(MVT::i8));
1238
Krzysztof Parzyszek7d37dd82017-12-06 16:40:37 +00001239 OpRef C = contracting(SM, Va, Vb, Results);
1240 if (C.isValid())
1241 return C;
1242
1243 int VecLen = SM.Mask.size();
1244 SmallVector<int,128> NewMask(VecLen);
1245 OpRef P = packs(SM, Va, Vb, Results, NewMask);
1246 if (P.isValid())
1247 return shuffs1(ShuffleMask(NewMask), P, Results);
1248
1249 SmallVector<int,128> MaskL(VecLen), MaskR(VecLen);
1250 splitMask(SM.Mask, MaskL, MaskR);
1251
1252 OpRef L = shuffs1(ShuffleMask(MaskL), Va, Results);
1253 OpRef R = shuffs1(ShuffleMask(MaskR), Vb, Results);
1254 if (!L.isValid() || !R.isValid())
1255 return OpRef::fail();
1256
1257 SmallVector<uint8_t,128> Bytes(VecLen);
1258 for (int I = 0; I != VecLen; ++I) {
1259 if (MaskL[I] != -1)
1260 Bytes[I] = 0xFF;
1261 }
1262 return vmuxs(Bytes, L, R, Results);
1263}
1264
1265OpRef HvxSelector::shuffp1(ShuffleMask SM, OpRef Va, ResultStack &Results) {
1266 DEBUG_WITH_TYPE("isel", {dbgs() << __func__ << '\n';});
1267 int VecLen = SM.Mask.size();
1268
Krzysztof Parzyszekedcd9dc2017-12-12 20:23:12 +00001269 if (isIdentity(SM.Mask))
1270 return Va;
1271 if (isUndef(SM.Mask))
1272 return OpRef::undef(getPairVT(MVT::i8));
1273
Krzysztof Parzyszek7d37dd82017-12-06 16:40:37 +00001274 SmallVector<int,128> PackedMask(VecLen);
1275 OpRef P = packs(SM, OpRef::lo(Va), OpRef::hi(Va), Results, PackedMask);
1276 if (P.isValid()) {
1277 ShuffleMask PM(PackedMask);
1278 OpRef E = expanding(PM, P, Results);
1279 if (E.isValid())
1280 return E;
1281
1282 OpRef L = shuffs1(PM.lo(), P, Results);
1283 OpRef H = shuffs1(PM.hi(), P, Results);
1284 if (L.isValid() && H.isValid())
1285 return concat(L, H, Results);
1286 }
1287
1288 OpRef R = perfect(SM, Va, Results);
1289 if (R.isValid())
1290 return R;
1291 // TODO commute the mask and try the opposite order of the halves.
1292
1293 OpRef L = shuffs2(SM.lo(), OpRef::lo(Va), OpRef::hi(Va), Results);
1294 OpRef H = shuffs2(SM.hi(), OpRef::lo(Va), OpRef::hi(Va), Results);
1295 if (L.isValid() && H.isValid())
1296 return concat(L, H, Results);
1297
1298 return OpRef::fail();
1299}
1300
1301OpRef HvxSelector::shuffp2(ShuffleMask SM, OpRef Va, OpRef Vb,
1302 ResultStack &Results) {
1303 DEBUG_WITH_TYPE("isel", {dbgs() << __func__ << '\n';});
Krzysztof Parzyszekedcd9dc2017-12-12 20:23:12 +00001304 if (isUndef(SM.Mask))
1305 return OpRef::undef(getPairVT(MVT::i8));
Krzysztof Parzyszek7d37dd82017-12-06 16:40:37 +00001306
Krzysztof Parzyszekedcd9dc2017-12-12 20:23:12 +00001307 int VecLen = SM.Mask.size();
Krzysztof Parzyszek7d37dd82017-12-06 16:40:37 +00001308 SmallVector<int,256> PackedMask(VecLen);
1309 OpRef P = packp(SM, Va, Vb, Results, PackedMask);
1310 if (P.isValid())
1311 return shuffp1(ShuffleMask(PackedMask), P, Results);
1312
1313 SmallVector<int,256> MaskL(VecLen), MaskR(VecLen);
Krzysztof Parzyszek67079be2018-02-05 15:46:41 +00001314 splitMask(SM.Mask, MaskL, MaskR);
1315
Krzysztof Parzyszek7d37dd82017-12-06 16:40:37 +00001316 OpRef L = shuffp1(ShuffleMask(MaskL), Va, Results);
1317 OpRef R = shuffp1(ShuffleMask(MaskR), Vb, Results);
1318 if (!L.isValid() || !R.isValid())
1319 return OpRef::fail();
1320
1321 // Mux the results.
1322 SmallVector<uint8_t,256> Bytes(VecLen);
1323 for (int I = 0; I != VecLen; ++I) {
1324 if (MaskL[I] != -1)
1325 Bytes[I] = 0xFF;
1326 }
1327 return vmuxp(Bytes, L, R, Results);
1328}
1329
Krzysztof Parzyszekf8537412018-09-12 22:10:58 +00001330namespace {
1331 struct Deleter : public SelectionDAG::DAGNodeDeletedListener {
1332 template <typename T>
1333 Deleter(SelectionDAG &D, T &C)
1334 : SelectionDAG::DAGNodeDeletedListener(D, [&C] (SDNode *N, SDNode *E) {
1335 C.erase(N);
1336 }) {}
1337 };
1338
1339 template <typename T>
1340 struct NullifyingVector : public T {
1341 DenseMap<SDNode*, SDNode**> Refs;
1342 NullifyingVector(T &&V) : T(V) {
1343 for (unsigned i = 0, e = T::size(); i != e; ++i) {
1344 SDNode *&N = T::operator[](i);
1345 Refs[N] = &N;
1346 }
1347 }
1348 void erase(SDNode *N) {
1349 auto F = Refs.find(N);
1350 if (F != Refs.end())
1351 *F->second = nullptr;
1352 }
1353 };
1354}
1355
Krzysztof Parzyszek7d37dd82017-12-06 16:40:37 +00001356bool HvxSelector::scalarizeShuffle(ArrayRef<int> Mask, const SDLoc &dl,
1357 MVT ResTy, SDValue Va, SDValue Vb,
1358 SDNode *N) {
1359 DEBUG_WITH_TYPE("isel", {dbgs() << __func__ << '\n';});
1360 MVT ElemTy = ResTy.getVectorElementType();
1361 assert(ElemTy == MVT::i8);
1362 unsigned VecLen = Mask.size();
1363 bool HavePairs = (2*HwLen == VecLen);
1364 MVT SingleTy = getSingleVT(MVT::i8);
1365
Krzysztof Parzyszekf8537412018-09-12 22:10:58 +00001366 // The prior attempts to handle this shuffle may have left a bunch of
1367 // dead nodes in the DAG (such as constants). These nodes will be added
1368 // at the end of DAG's node list, which at that point had already been
1369 // sorted topologically. In the main selection loop, the node list is
1370 // traversed backwards from the root node, which means that any new
1371 // nodes (from the end of the list) will not be visited.
1372 // Scalarization will replace the shuffle node with the scalarized
1373 // expression, and if that expression reused any if the leftoever (dead)
1374 // nodes, these nodes would not be selected (since the "local" selection
1375 // only visits nodes that are not in AllNodes).
1376 // To avoid this issue, remove all dead nodes from the DAG now.
1377 DAG.RemoveDeadNodes();
1378 DenseSet<SDNode*> AllNodes;
1379 for (SDNode &S : DAG.allnodes())
1380 AllNodes.insert(&S);
1381
1382 Deleter DUA(DAG, AllNodes);
1383
Krzysztof Parzyszek7d37dd82017-12-06 16:40:37 +00001384 SmallVector<SDValue,128> Ops;
Krzysztof Parzyszekcd95e032018-09-12 20:58:48 +00001385 LLVMContext &Ctx = *DAG.getContext();
1386 MVT LegalTy = Lower.getTypeToTransformTo(Ctx, ElemTy).getSimpleVT();
Krzysztof Parzyszek7d37dd82017-12-06 16:40:37 +00001387 for (int I : Mask) {
1388 if (I < 0) {
Krzysztof Parzyszekcd95e032018-09-12 20:58:48 +00001389 Ops.push_back(ISel.selectUndef(dl, LegalTy));
Krzysztof Parzyszek7d37dd82017-12-06 16:40:37 +00001390 continue;
1391 }
1392 SDValue Vec;
1393 unsigned M = I;
1394 if (M < VecLen) {
1395 Vec = Va;
1396 } else {
1397 Vec = Vb;
1398 M -= VecLen;
1399 }
1400 if (HavePairs) {
1401 if (M < HwLen) {
1402 Vec = DAG.getTargetExtractSubreg(Hexagon::vsub_lo, dl, SingleTy, Vec);
1403 } else {
1404 Vec = DAG.getTargetExtractSubreg(Hexagon::vsub_hi, dl, SingleTy, Vec);
1405 M -= HwLen;
1406 }
1407 }
1408 SDValue Idx = DAG.getConstant(M, dl, MVT::i32);
Krzysztof Parzyszekcd95e032018-09-12 20:58:48 +00001409 SDValue Ex = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, LegalTy, {Vec, Idx});
Krzysztof Parzyszek7d37dd82017-12-06 16:40:37 +00001410 SDValue L = Lower.LowerOperation(Ex, DAG);
1411 assert(L.getNode());
1412 Ops.push_back(L);
1413 }
1414
1415 SDValue LV;
1416 if (2*HwLen == VecLen) {
1417 SDValue B0 = DAG.getBuildVector(SingleTy, dl, {Ops.data(), HwLen});
1418 SDValue L0 = Lower.LowerOperation(B0, DAG);
1419 SDValue B1 = DAG.getBuildVector(SingleTy, dl, {Ops.data()+HwLen, HwLen});
1420 SDValue L1 = Lower.LowerOperation(B1, DAG);
1421 // XXX CONCAT_VECTORS is legal for HVX vectors. Legalizing (lowering)
1422 // functions may expect to be called only for illegal operations, so
1423 // make sure that they are not called for legal ones. Develop a better
1424 // mechanism for dealing with this.
1425 LV = DAG.getNode(ISD::CONCAT_VECTORS, dl, ResTy, {L0, L1});
1426 } else {
1427 SDValue BV = DAG.getBuildVector(ResTy, dl, Ops);
1428 LV = Lower.LowerOperation(BV, DAG);
1429 }
1430
1431 assert(!N->use_empty());
1432 ISel.ReplaceNode(N, LV.getNode());
Krzysztof Parzyszek7d37dd82017-12-06 16:40:37 +00001433
Krzysztof Parzyszekf8537412018-09-12 22:10:58 +00001434 if (AllNodes.count(LV.getNode())) {
1435 DAG.RemoveDeadNodes();
1436 return true;
1437 }
1438
1439 // The lowered build-vector node will now need to be selected. It needs
1440 // to be done here because this node and its submodes are not included
1441 // in the main selection loop.
1442 // Implement essentially the same topological ordering algorithm as is
1443 // used in SelectionDAGISel.
1444
1445 SetVector<SDNode*> SubNodes, TmpQ;
1446 std::map<SDNode*,unsigned> NumOps;
1447
1448 SubNodes.insert(LV.getNode());
Krzysztof Parzyszek7d37dd82017-12-06 16:40:37 +00001449 for (unsigned I = 0; I != SubNodes.size(); ++I) {
Krzysztof Parzyszekf8537412018-09-12 22:10:58 +00001450 unsigned OpN = 0;
1451 SDNode *S = SubNodes[I];
1452 for (SDValue Op : S->ops()) {
1453 if (AllNodes.count(Op.getNode()))
1454 continue;
1455 SubNodes.insert(Op.getNode());
1456 ++OpN;
1457 }
1458 NumOps.insert({S, OpN});
1459 if (OpN == 0)
1460 TmpQ.insert(S);
Krzysztof Parzyszek7d37dd82017-12-06 16:40:37 +00001461 }
Krzysztof Parzyszekf8537412018-09-12 22:10:58 +00001462
1463 for (unsigned I = 0; I != TmpQ.size(); ++I) {
1464 SDNode *S = TmpQ[I];
1465 for (SDNode *U : S->uses()) {
1466 if (!SubNodes.count(U))
1467 continue;
1468 auto F = NumOps.find(U);
1469 assert(F != NumOps.end());
1470 assert(F->second > 0);
1471 if (!--F->second)
1472 TmpQ.insert(F->first);
1473 }
1474 }
1475 assert(SubNodes.size() == TmpQ.size());
1476 NullifyingVector<decltype(TmpQ)::vector_type> Queue(TmpQ.takeVector());
1477
1478 Deleter DUQ(DAG, Queue);
1479 for (SDNode *S : reverse(Queue))
1480 if (S != nullptr)
Krzysztof Parzyszek7d37dd82017-12-06 16:40:37 +00001481 ISel.Select(S);
Krzysztof Parzyszek7d37dd82017-12-06 16:40:37 +00001482
1483 DAG.RemoveDeadNodes();
1484 return true;
1485}
1486
1487OpRef HvxSelector::contracting(ShuffleMask SM, OpRef Va, OpRef Vb,
1488 ResultStack &Results) {
1489 DEBUG_WITH_TYPE("isel", {dbgs() << __func__ << '\n';});
1490 if (!Va.isValid() || !Vb.isValid())
1491 return OpRef::fail();
1492
1493 // Contracting shuffles, i.e. instructions that always discard some bytes
1494 // from the operand vectors.
1495 //
1496 // V6_vshuff{e,o}b
1497 // V6_vdealb4w
1498 // V6_vpack{e,o}{b,h}
1499
1500 int VecLen = SM.Mask.size();
1501 std::pair<int,unsigned> Strip = findStrip(SM.Mask, 1, VecLen);
1502 MVT ResTy = getSingleVT(MVT::i8);
1503
1504 // The following shuffles only work for bytes and halfwords. This requires
1505 // the strip length to be 1 or 2.
1506 if (Strip.second != 1 && Strip.second != 2)
1507 return OpRef::fail();
1508
1509 // The patterns for the shuffles, in terms of the starting offsets of the
1510 // consecutive strips (L = length of the strip, N = VecLen):
1511 //
1512 // vpacke: 0, 2L, 4L ... N+0, N+2L, N+4L ... L = 1 or 2
1513 // vpacko: L, 3L, 5L ... N+L, N+3L, N+5L ... L = 1 or 2
1514 //
1515 // vshuffe: 0, N+0, 2L, N+2L, 4L ... L = 1 or 2
1516 // vshuffo: L, N+L, 3L, N+3L, 5L ... L = 1 or 2
1517 //
1518 // vdealb4w: 0, 4, 8 ... 2, 6, 10 ... N+0, N+4, N+8 ... N+2, N+6, N+10 ...
1519
1520 // The value of the element in the mask following the strip will decide
1521 // what kind of a shuffle this can be.
1522 int NextInMask = SM.Mask[Strip.second];
1523
1524 // Check if NextInMask could be 2L, 3L or 4, i.e. if it could be a mask
1525 // for vpack or vdealb4w. VecLen > 4, so NextInMask for vdealb4w would
1526 // satisfy this.
1527 if (NextInMask < VecLen) {
1528 // vpack{e,o} or vdealb4w
1529 if (Strip.first == 0 && Strip.second == 1 && NextInMask == 4) {
1530 int N = VecLen;
1531 // Check if this is vdealb4w (L=1).
1532 for (int I = 0; I != N/4; ++I)
1533 if (SM.Mask[I] != 4*I)
1534 return OpRef::fail();
1535 for (int I = 0; I != N/4; ++I)
1536 if (SM.Mask[I+N/4] != 2 + 4*I)
1537 return OpRef::fail();
1538 for (int I = 0; I != N/4; ++I)
1539 if (SM.Mask[I+N/2] != N + 4*I)
1540 return OpRef::fail();
1541 for (int I = 0; I != N/4; ++I)
1542 if (SM.Mask[I+3*N/4] != N+2 + 4*I)
1543 return OpRef::fail();
1544 // Matched mask for vdealb4w.
1545 Results.push(Hexagon::V6_vdealb4w, ResTy, {Vb, Va});
1546 return OpRef::res(Results.top());
1547 }
1548
1549 // Check if this is vpack{e,o}.
1550 int N = VecLen;
1551 int L = Strip.second;
1552 // Check if the first strip starts at 0 or at L.
1553 if (Strip.first != 0 && Strip.first != L)
1554 return OpRef::fail();
1555 // Examine the rest of the mask.
Krzysztof Parzyszek64533cf2017-12-06 21:25:03 +00001556 for (int I = L; I < N; I += L) {
Krzysztof Parzyszek3f84c0f2017-12-20 20:54:13 +00001557 auto S = findStrip(SM.Mask.drop_front(I), 1, N-I);
Krzysztof Parzyszek7d37dd82017-12-06 16:40:37 +00001558 // Check whether the mask element at the beginning of each strip
1559 // increases by 2L each time.
1560 if (S.first - Strip.first != 2*I)
1561 return OpRef::fail();
1562 // Check whether each strip is of the same length.
1563 if (S.second != unsigned(L))
1564 return OpRef::fail();
1565 }
1566
1567 // Strip.first == 0 => vpacke
1568 // Strip.first == L => vpacko
1569 assert(Strip.first == 0 || Strip.first == L);
1570 using namespace Hexagon;
1571 NodeTemplate Res;
1572 Res.Opc = Strip.second == 1 // Number of bytes.
1573 ? (Strip.first == 0 ? V6_vpackeb : V6_vpackob)
1574 : (Strip.first == 0 ? V6_vpackeh : V6_vpackoh);
1575 Res.Ty = ResTy;
1576 Res.Ops = { Vb, Va };
1577 Results.push(Res);
1578 return OpRef::res(Results.top());
1579 }
1580
1581 // Check if this is vshuff{e,o}.
1582 int N = VecLen;
1583 int L = Strip.second;
1584 std::pair<int,unsigned> PrevS = Strip;
1585 bool Flip = false;
1586 for (int I = L; I < N; I += L) {
Krzysztof Parzyszek3f84c0f2017-12-20 20:54:13 +00001587 auto S = findStrip(SM.Mask.drop_front(I), 1, N-I);
Krzysztof Parzyszek7d37dd82017-12-06 16:40:37 +00001588 if (S.second != PrevS.second)
1589 return OpRef::fail();
1590 int Diff = Flip ? PrevS.first - S.first + 2*L
1591 : S.first - PrevS.first;
1592 if (Diff != N)
1593 return OpRef::fail();
1594 Flip ^= true;
1595 PrevS = S;
1596 }
1597 // Strip.first == 0 => vshuffe
1598 // Strip.first == L => vshuffo
1599 assert(Strip.first == 0 || Strip.first == L);
1600 using namespace Hexagon;
1601 NodeTemplate Res;
1602 Res.Opc = Strip.second == 1 // Number of bytes.
1603 ? (Strip.first == 0 ? V6_vshuffeb : V6_vshuffob)
1604 : (Strip.first == 0 ? V6_vshufeh : V6_vshufoh);
1605 Res.Ty = ResTy;
1606 Res.Ops = { Vb, Va };
1607 Results.push(Res);
1608 return OpRef::res(Results.top());
1609}
1610
1611OpRef HvxSelector::expanding(ShuffleMask SM, OpRef Va, ResultStack &Results) {
1612 DEBUG_WITH_TYPE("isel", {dbgs() << __func__ << '\n';});
1613 // Expanding shuffles (using all elements and inserting into larger vector):
1614 //
1615 // V6_vunpacku{b,h} [*]
1616 //
1617 // [*] Only if the upper elements (filled with 0s) are "don't care" in Mask.
1618 //
1619 // Note: V6_vunpacko{b,h} are or-ing the high byte/half in the result, so
1620 // they are not shuffles.
1621 //
1622 // The argument is a single vector.
1623
1624 int VecLen = SM.Mask.size();
1625 assert(2*HwLen == unsigned(VecLen) && "Expecting vector-pair type");
1626
1627 std::pair<int,unsigned> Strip = findStrip(SM.Mask, 1, VecLen);
1628
1629 // The patterns for the unpacks, in terms of the starting offsets of the
1630 // consecutive strips (L = length of the strip, N = VecLen):
1631 //
1632 // vunpacku: 0, -1, L, -1, 2L, -1 ...
1633
1634 if (Strip.first != 0)
1635 return OpRef::fail();
1636
1637 // The vunpackus only handle byte and half-word.
1638 if (Strip.second != 1 && Strip.second != 2)
1639 return OpRef::fail();
1640
1641 int N = VecLen;
1642 int L = Strip.second;
1643
1644 // First, check the non-ignored strips.
1645 for (int I = 2*L; I < 2*N; I += 2*L) {
Krzysztof Parzyszek3f84c0f2017-12-20 20:54:13 +00001646 auto S = findStrip(SM.Mask.drop_front(I), 1, N-I);
Krzysztof Parzyszek7d37dd82017-12-06 16:40:37 +00001647 if (S.second != unsigned(L))
1648 return OpRef::fail();
1649 if (2*S.first != I)
1650 return OpRef::fail();
1651 }
1652 // Check the -1s.
1653 for (int I = L; I < 2*N; I += 2*L) {
Krzysztof Parzyszek3f84c0f2017-12-20 20:54:13 +00001654 auto S = findStrip(SM.Mask.drop_front(I), 0, N-I);
Krzysztof Parzyszek7d37dd82017-12-06 16:40:37 +00001655 if (S.first != -1 || S.second != unsigned(L))
1656 return OpRef::fail();
1657 }
1658
1659 unsigned Opc = Strip.second == 1 ? Hexagon::V6_vunpackub
1660 : Hexagon::V6_vunpackuh;
1661 Results.push(Opc, getPairVT(MVT::i8), {Va});
1662 return OpRef::res(Results.top());
1663}
1664
1665OpRef HvxSelector::perfect(ShuffleMask SM, OpRef Va, ResultStack &Results) {
1666 DEBUG_WITH_TYPE("isel", {dbgs() << __func__ << '\n';});
1667 // V6_vdeal{b,h}
1668 // V6_vshuff{b,h}
1669
1670 // V6_vshufoe{b,h} those are quivalent to vshuffvdd(..,{1,2})
1671 // V6_vshuffvdd (V6_vshuff)
1672 // V6_dealvdd (V6_vdeal)
1673
Krzysztof Parzyszek7d37dd82017-12-06 16:40:37 +00001674 int VecLen = SM.Mask.size();
1675 assert(isPowerOf2_32(VecLen) && Log2_32(VecLen) <= 8);
1676 unsigned LogLen = Log2_32(VecLen);
Krzysztof Parzyszek64533cf2017-12-06 21:25:03 +00001677 unsigned HwLog = Log2_32(HwLen);
1678 // The result length must be the same as the length of a single vector,
1679 // or a vector pair.
1680 assert(LogLen == HwLog || LogLen == HwLog+1);
1681 bool Extend = (LogLen == HwLog);
Krzysztof Parzyszek7d37dd82017-12-06 16:40:37 +00001682
1683 if (!isPermutation(SM.Mask))
1684 return OpRef::fail();
1685
1686 SmallVector<unsigned,8> Perm(LogLen);
1687
1688 // Check if this could be a perfect shuffle, or a combination of perfect
1689 // shuffles.
1690 //
1691 // Consider this permutation (using hex digits to make the ASCII diagrams
1692 // easier to read):
1693 // { 0, 8, 1, 9, 2, A, 3, B, 4, C, 5, D, 6, E, 7, F }.
1694 // This is a "deal" operation: divide the input into two halves, and
1695 // create the output by picking elements by alternating between these two
1696 // halves:
1697 // 0 1 2 3 4 5 6 7 --> 0 8 1 9 2 A 3 B 4 C 5 D 6 E 7 F [*]
1698 // 8 9 A B C D E F
1699 //
1700 // Aside from a few special explicit cases (V6_vdealb, etc.), HVX provides
1701 // a somwehat different mechanism that could be used to perform shuffle/
1702 // deal operations: a 2x2 transpose.
1703 // Consider the halves of inputs again, they can be interpreted as a 2x8
1704 // matrix. A 2x8 matrix can be looked at four 2x2 matrices concatenated
1705 // together. Now, when considering 2 elements at a time, it will be a 2x4
1706 // matrix (with elements 01, 23, 45, etc.), or two 2x2 matrices:
1707 // 01 23 45 67
1708 // 89 AB CD EF
1709 // With groups of 4, this will become a single 2x2 matrix, and so on.
1710 //
1711 // The 2x2 transpose instruction works by transposing each of the 2x2
1712 // matrices (or "sub-matrices"), given a specific group size. For example,
1713 // if the group size is 1 (i.e. each element is its own group), there
1714 // will be four transposes of the four 2x2 matrices that form the 2x8.
1715 // For example, with the inputs as above, the result will be:
1716 // 0 8 2 A 4 C 6 E
1717 // 1 9 3 B 5 D 7 F
1718 // Now, this result can be tranposed again, but with the group size of 2:
1719 // 08 19 4C 5D
1720 // 2A 3B 6E 7F
1721 // If we then transpose that result, but with the group size of 4, we get:
1722 // 0819 2A3B
1723 // 4C5D 6E7F
1724 // If we concatenate these two rows, it will be
1725 // 0 8 1 9 2 A 3 B 4 C 5 D 6 E 7 F
1726 // which is the same as the "deal" [*] above.
1727 //
1728 // In general, a "deal" of individual elements is a series of 2x2 transposes,
1729 // with changing group size. HVX has two instructions:
1730 // Vdd = V6_vdealvdd Vu, Vv, Rt
1731 // Vdd = V6_shufvdd Vu, Vv, Rt
1732 // that perform exactly that. The register Rt controls which transposes are
1733 // going to happen: a bit at position n (counting from 0) indicates that a
1734 // transpose with a group size of 2^n will take place. If multiple bits are
1735 // set, multiple transposes will happen: vdealvdd will perform them starting
1736 // with the largest group size, vshuffvdd will do them in the reverse order.
1737 //
1738 // The main observation is that each 2x2 transpose corresponds to swapping
1739 // columns of bits in the binary representation of the values.
1740 //
1741 // The numbers {3,2,1,0} and the log2 of the number of contiguous 1 bits
1742 // in a given column. The * denote the columns that will be swapped.
1743 // The transpose with the group size 2^n corresponds to swapping columns
1744 // 3 (the highest log) and log2(n):
1745 //
1746 // 3 2 1 0 0 2 1 3 0 2 3 1
1747 // * * * * * *
1748 // 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
1749 // 1 0 0 0 1 8 1 0 0 0 8 1 0 0 0 8 1 0 0 0
1750 // 2 0 0 1 0 2 0 0 1 0 1 0 0 0 1 1 0 0 0 1
1751 // 3 0 0 1 1 A 1 0 1 0 9 1 0 0 1 9 1 0 0 1
1752 // 4 0 1 0 0 4 0 1 0 0 4 0 1 0 0 2 0 0 1 0
1753 // 5 0 1 0 1 C 1 1 0 0 C 1 1 0 0 A 1 0 1 0
1754 // 6 0 1 1 0 6 0 1 1 0 5 0 1 0 1 3 0 0 1 1
1755 // 7 0 1 1 1 E 1 1 1 0 D 1 1 0 1 B 1 0 1 1
1756 // 8 1 0 0 0 1 0 0 0 1 2 0 0 1 0 4 0 1 0 0
1757 // 9 1 0 0 1 9 1 0 0 1 A 1 0 1 0 C 1 1 0 0
1758 // A 1 0 1 0 3 0 0 1 1 3 0 0 1 1 5 0 1 0 1
1759 // B 1 0 1 1 B 1 0 1 1 B 1 0 1 1 D 1 1 0 1
1760 // C 1 1 0 0 5 0 1 0 1 6 0 1 1 0 6 0 1 1 0
1761 // D 1 1 0 1 D 1 1 0 1 E 1 1 1 0 E 1 1 1 0
1762 // E 1 1 1 0 7 0 1 1 1 7 0 1 1 1 7 0 1 1 1
1763 // F 1 1 1 1 F 1 1 1 1 F 1 1 1 1 F 1 1 1 1
1764
1765 auto XorPow2 = [] (ArrayRef<int> Mask, unsigned Num) {
1766 unsigned X = Mask[0] ^ Mask[Num/2];
1767 // Check that the first half has the X's bits clear.
1768 if ((Mask[0] & X) != 0)
1769 return 0u;
1770 for (unsigned I = 1; I != Num/2; ++I) {
1771 if (unsigned(Mask[I] ^ Mask[I+Num/2]) != X)
1772 return 0u;
1773 if ((Mask[I] & X) != 0)
1774 return 0u;
1775 }
1776 return X;
1777 };
1778
1779 // Create a vector of log2's for each column: Perm[i] corresponds to
1780 // the i-th bit (lsb is 0).
1781 assert(VecLen > 2);
1782 for (unsigned I = VecLen; I >= 2; I >>= 1) {
1783 // Examine the initial segment of Mask of size I.
1784 unsigned X = XorPow2(SM.Mask, I);
1785 if (!isPowerOf2_32(X))
1786 return OpRef::fail();
1787 // Check the other segments of Mask.
Krzysztof Parzyszek3f84c0f2017-12-20 20:54:13 +00001788 for (int J = I; J < VecLen; J += I) {
1789 if (XorPow2(SM.Mask.slice(J, I), I) != X)
Krzysztof Parzyszek7d37dd82017-12-06 16:40:37 +00001790 return OpRef::fail();
1791 }
1792 Perm[Log2_32(X)] = Log2_32(I)-1;
1793 }
1794
1795 // Once we have Perm, represent it as cycles. Denote the maximum log2
1796 // (equal to log2(VecLen)-1) as M. The cycle containing M can then be
1797 // written as (M a1 a2 a3 ... an). That cycle can be broken up into
1798 // simple swaps as (M a1)(M a2)(M a3)...(M an), with the composition
1799 // order being from left to right. Any (contiguous) segment where the
1800 // values ai, ai+1...aj are either all increasing or all decreasing,
1801 // can be implemented via a single vshuffvdd/vdealvdd respectively.
1802 //
1803 // If there is a cycle (a1 a2 ... an) that does not involve M, it can
1804 // be written as (M an)(a1 a2 ... an)(M a1). The first two cycles can
1805 // then be folded to get (M a1 a2 ... an)(M a1), and the above procedure
1806 // can be used to generate a sequence of vshuffvdd/vdealvdd.
1807 //
1808 // Example:
1809 // Assume M = 4 and consider a permutation (0 1)(2 3). It can be written
1810 // as (4 0 1)(4 0) composed with (4 2 3)(4 2), or simply
1811 // (4 0 1)(4 0)(4 2 3)(4 2).
1812 // It can then be expanded into swaps as
1813 // (4 0)(4 1)(4 0)(4 2)(4 3)(4 2),
1814 // and broken up into "increasing" segments as
1815 // [(4 0)(4 1)] [(4 0)(4 2)(4 3)] [(4 2)].
1816 // This is equivalent to
1817 // (4 0 1)(4 0 2 3)(4 2),
1818 // which can be implemented as 3 vshufvdd instructions.
1819
1820 using CycleType = SmallVector<unsigned,8>;
1821 std::set<CycleType> Cycles;
1822 std::set<unsigned> All;
1823
1824 for (unsigned I : Perm)
1825 All.insert(I);
1826
1827 // If the cycle contains LogLen-1, move it to the front of the cycle.
1828 // Otherwise, return the cycle unchanged.
1829 auto canonicalize = [LogLen](const CycleType &C) -> CycleType {
1830 unsigned LogPos, N = C.size();
1831 for (LogPos = 0; LogPos != N; ++LogPos)
1832 if (C[LogPos] == LogLen-1)
1833 break;
1834 if (LogPos == N)
1835 return C;
1836
1837 CycleType NewC(C.begin()+LogPos, C.end());
1838 NewC.append(C.begin(), C.begin()+LogPos);
1839 return NewC;
1840 };
1841
Krzysztof Parzyszekd2967862017-12-06 22:41:49 +00001842 auto pfs = [](const std::set<CycleType> &Cs, unsigned Len) {
1843 // Ordering: shuff: 5 0 1 2 3 4, deal: 5 4 3 2 1 0 (for Log=6),
1844 // for bytes zero is included, for halfwords is not.
1845 if (Cs.size() != 1)
1846 return 0u;
1847 const CycleType &C = *Cs.begin();
1848 if (C[0] != Len-1)
1849 return 0u;
1850 int D = Len - C.size();
1851 if (D != 0 && D != 1)
1852 return 0u;
1853
1854 bool IsDeal = true, IsShuff = true;
1855 for (unsigned I = 1; I != Len-D; ++I) {
1856 if (C[I] != Len-1-I)
1857 IsDeal = false;
1858 if (C[I] != I-(1-D)) // I-1, I
1859 IsShuff = false;
1860 }
1861 // At most one, IsDeal or IsShuff, can be non-zero.
1862 assert(!(IsDeal || IsShuff) || IsDeal != IsShuff);
1863 static unsigned Deals[] = { Hexagon::V6_vdealb, Hexagon::V6_vdealh };
1864 static unsigned Shufs[] = { Hexagon::V6_vshuffb, Hexagon::V6_vshuffh };
1865 return IsDeal ? Deals[D] : (IsShuff ? Shufs[D] : 0);
1866 };
1867
Krzysztof Parzyszek7d37dd82017-12-06 16:40:37 +00001868 while (!All.empty()) {
1869 unsigned A = *All.begin();
1870 All.erase(A);
1871 CycleType C;
1872 C.push_back(A);
1873 for (unsigned B = Perm[A]; B != A; B = Perm[B]) {
1874 C.push_back(B);
1875 All.erase(B);
1876 }
1877 if (C.size() <= 1)
1878 continue;
1879 Cycles.insert(canonicalize(C));
1880 }
1881
Krzysztof Parzyszekd2967862017-12-06 22:41:49 +00001882 MVT SingleTy = getSingleVT(MVT::i8);
1883 MVT PairTy = getPairVT(MVT::i8);
1884
1885 // Recognize patterns for V6_vdeal{b,h} and V6_vshuff{b,h}.
1886 if (unsigned(VecLen) == HwLen) {
1887 if (unsigned SingleOpc = pfs(Cycles, LogLen)) {
1888 Results.push(SingleOpc, SingleTy, {Va});
1889 return OpRef::res(Results.top());
1890 }
1891 }
1892
Krzysztof Parzyszek7d37dd82017-12-06 16:40:37 +00001893 SmallVector<unsigned,8> SwapElems;
1894 if (HwLen == unsigned(VecLen))
1895 SwapElems.push_back(LogLen-1);
1896
1897 for (const CycleType &C : Cycles) {
1898 unsigned First = (C[0] == LogLen-1) ? 1 : 0;
1899 SwapElems.append(C.begin()+First, C.end());
1900 if (First == 0)
1901 SwapElems.push_back(C[0]);
1902 }
1903
Krzysztof Parzyszek64533cf2017-12-06 21:25:03 +00001904 const SDLoc &dl(Results.InpNode);
1905 OpRef Arg = !Extend ? Va
1906 : concat(Va, OpRef::undef(SingleTy), Results);
Krzysztof Parzyszek7d37dd82017-12-06 16:40:37 +00001907
1908 for (unsigned I = 0, E = SwapElems.size(); I != E; ) {
1909 bool IsInc = I == E-1 || SwapElems[I] < SwapElems[I+1];
1910 unsigned S = (1u << SwapElems[I]);
1911 if (I < E-1) {
1912 while (++I < E-1 && IsInc == (SwapElems[I] < SwapElems[I+1]))
1913 S |= 1u << SwapElems[I];
1914 // The above loop will not add a bit for the final SwapElems[I+1],
1915 // so add it here.
1916 S |= 1u << SwapElems[I];
1917 }
1918 ++I;
1919
1920 NodeTemplate Res;
1921 Results.push(Hexagon::A2_tfrsi, MVT::i32,
1922 { DAG.getTargetConstant(S, dl, MVT::i32) });
1923 Res.Opc = IsInc ? Hexagon::V6_vshuffvdd : Hexagon::V6_vdealvdd;
1924 Res.Ty = PairTy;
1925 Res.Ops = { OpRef::hi(Arg), OpRef::lo(Arg), OpRef::res(-1) };
1926 Results.push(Res);
1927 Arg = OpRef::res(Results.top());
1928 }
1929
Krzysztof Parzyszek64533cf2017-12-06 21:25:03 +00001930 return !Extend ? Arg : OpRef::lo(Arg);
Krzysztof Parzyszek7d37dd82017-12-06 16:40:37 +00001931}
1932
1933OpRef HvxSelector::butterfly(ShuffleMask SM, OpRef Va, ResultStack &Results) {
1934 DEBUG_WITH_TYPE("isel", {dbgs() << __func__ << '\n';});
1935 // Butterfly shuffles.
1936 //
1937 // V6_vdelta
1938 // V6_vrdelta
1939 // V6_vror
1940
1941 // The assumption here is that all elements picked by Mask are in the
1942 // first operand to the vector_shuffle. This assumption is enforced
1943 // by the caller.
1944
1945 MVT ResTy = getSingleVT(MVT::i8);
1946 PermNetwork::Controls FC, RC;
1947 const SDLoc &dl(Results.InpNode);
1948 int VecLen = SM.Mask.size();
1949
1950 for (int M : SM.Mask) {
1951 if (M != -1 && M >= VecLen)
1952 return OpRef::fail();
1953 }
1954
1955 // Try the deltas/benes for both single vectors and vector pairs.
1956 ForwardDeltaNetwork FN(SM.Mask);
1957 if (FN.run(FC)) {
1958 SDValue Ctl = getVectorConstant(FC, dl);
1959 Results.push(Hexagon::V6_vdelta, ResTy, {Va, OpRef(Ctl)});
1960 return OpRef::res(Results.top());
1961 }
1962
1963 // Try reverse delta.
1964 ReverseDeltaNetwork RN(SM.Mask);
1965 if (RN.run(RC)) {
1966 SDValue Ctl = getVectorConstant(RC, dl);
1967 Results.push(Hexagon::V6_vrdelta, ResTy, {Va, OpRef(Ctl)});
1968 return OpRef::res(Results.top());
1969 }
1970
1971 // Do Benes.
1972 BenesNetwork BN(SM.Mask);
1973 if (BN.run(FC, RC)) {
1974 SDValue CtlF = getVectorConstant(FC, dl);
1975 SDValue CtlR = getVectorConstant(RC, dl);
1976 Results.push(Hexagon::V6_vdelta, ResTy, {Va, OpRef(CtlF)});
1977 Results.push(Hexagon::V6_vrdelta, ResTy,
1978 {OpRef::res(-1), OpRef(CtlR)});
1979 return OpRef::res(Results.top());
1980 }
1981
1982 return OpRef::fail();
1983}
1984
1985SDValue HvxSelector::getVectorConstant(ArrayRef<uint8_t> Data,
1986 const SDLoc &dl) {
1987 SmallVector<SDValue, 128> Elems;
1988 for (uint8_t C : Data)
1989 Elems.push_back(DAG.getConstant(C, dl, MVT::i8));
1990 MVT VecTy = MVT::getVectorVT(MVT::i8, Data.size());
1991 SDValue BV = DAG.getBuildVector(VecTy, dl, Elems);
1992 SDValue LV = Lower.LowerOperation(BV, DAG);
1993 DAG.RemoveDeadNode(BV.getNode());
1994 return LV;
1995}
1996
1997void HvxSelector::selectShuffle(SDNode *N) {
1998 DEBUG_WITH_TYPE("isel", {
1999 dbgs() << "Starting " << __func__ << " on node:\n";
2000 N->dump(&DAG);
2001 });
2002 MVT ResTy = N->getValueType(0).getSimpleVT();
2003 // Assume that vector shuffles operate on vectors of bytes.
2004 assert(ResTy.isVector() && ResTy.getVectorElementType() == MVT::i8);
2005
2006 auto *SN = cast<ShuffleVectorSDNode>(N);
2007 std::vector<int> Mask(SN->getMask().begin(), SN->getMask().end());
2008 // This shouldn't really be necessary. Is it?
2009 for (int &Idx : Mask)
2010 if (Idx != -1 && Idx < 0)
2011 Idx = -1;
2012
2013 unsigned VecLen = Mask.size();
2014 bool HavePairs = (2*HwLen == VecLen);
2015 assert(ResTy.getSizeInBits() / 8 == VecLen);
2016
2017 // Vd = vector_shuffle Va, Vb, Mask
2018 //
2019
2020 bool UseLeft = false, UseRight = false;
2021 for (unsigned I = 0; I != VecLen; ++I) {
2022 if (Mask[I] == -1)
2023 continue;
2024 unsigned Idx = Mask[I];
2025 assert(Idx < 2*VecLen);
2026 if (Idx < VecLen)
2027 UseLeft = true;
2028 else
2029 UseRight = true;
2030 }
2031
2032 DEBUG_WITH_TYPE("isel", {
2033 dbgs() << "VecLen=" << VecLen << " HwLen=" << HwLen << " UseLeft="
2034 << UseLeft << " UseRight=" << UseRight << " HavePairs="
2035 << HavePairs << '\n';
2036 });
2037 // If the mask is all -1's, generate "undef".
2038 if (!UseLeft && !UseRight) {
2039 ISel.ReplaceNode(N, ISel.selectUndef(SDLoc(SN), ResTy).getNode());
Krzysztof Parzyszek7d37dd82017-12-06 16:40:37 +00002040 return;
2041 }
2042
2043 SDValue Vec0 = N->getOperand(0);
2044 SDValue Vec1 = N->getOperand(1);
2045 ResultStack Results(SN);
2046 Results.push(TargetOpcode::COPY, ResTy, {Vec0});
2047 Results.push(TargetOpcode::COPY, ResTy, {Vec1});
2048 OpRef Va = OpRef::res(Results.top()-1);
2049 OpRef Vb = OpRef::res(Results.top());
2050
2051 OpRef Res = !HavePairs ? shuffs2(ShuffleMask(Mask), Va, Vb, Results)
2052 : shuffp2(ShuffleMask(Mask), Va, Vb, Results);
2053
2054 bool Done = Res.isValid();
Krzysztof Parzyszek64533cf2017-12-06 21:25:03 +00002055 if (Done) {
2056 // Make sure that Res is on the stack before materializing.
2057 Results.push(TargetOpcode::COPY, ResTy, {Res});
Krzysztof Parzyszek7d37dd82017-12-06 16:40:37 +00002058 materialize(Results);
Krzysztof Parzyszek64533cf2017-12-06 21:25:03 +00002059 } else {
Krzysztof Parzyszek7d37dd82017-12-06 16:40:37 +00002060 Done = scalarizeShuffle(Mask, SDLoc(N), ResTy, Vec0, Vec1, N);
Krzysztof Parzyszek64533cf2017-12-06 21:25:03 +00002061 }
Krzysztof Parzyszek7d37dd82017-12-06 16:40:37 +00002062
2063 if (!Done) {
2064#ifndef NDEBUG
2065 dbgs() << "Unhandled shuffle:\n";
2066 SN->dumpr(&DAG);
2067#endif
2068 llvm_unreachable("Failed to select vector shuffle");
2069 }
2070}
2071
2072void HvxSelector::selectRor(SDNode *N) {
2073 // If this is a rotation by less than 8, use V6_valignbi.
2074 MVT Ty = N->getValueType(0).getSimpleVT();
2075 const SDLoc &dl(N);
2076 SDValue VecV = N->getOperand(0);
2077 SDValue RotV = N->getOperand(1);
2078 SDNode *NewN = nullptr;
2079
2080 if (auto *CN = dyn_cast<ConstantSDNode>(RotV.getNode())) {
Krzysztof Parzyszek3780a0e2018-01-23 17:53:59 +00002081 unsigned S = CN->getZExtValue() % HST.getVectorLength();
2082 if (S == 0) {
Krzysztof Parzyszek7d37dd82017-12-06 16:40:37 +00002083 NewN = VecV.getNode();
2084 } else if (isUInt<3>(S)) {
2085 SDValue C = DAG.getTargetConstant(S, dl, MVT::i32);
2086 NewN = DAG.getMachineNode(Hexagon::V6_valignbi, dl, Ty,
2087 {VecV, VecV, C});
2088 }
2089 }
2090
2091 if (!NewN)
2092 NewN = DAG.getMachineNode(Hexagon::V6_vror, dl, Ty, {VecV, RotV});
2093
2094 ISel.ReplaceNode(N, NewN);
Krzysztof Parzyszek7d37dd82017-12-06 16:40:37 +00002095}
2096
Krzysztof Parzyszek2c3edf02018-03-07 17:27:18 +00002097void HvxSelector::selectVAlign(SDNode *N) {
2098 SDValue Vv = N->getOperand(0);
2099 SDValue Vu = N->getOperand(1);
2100 SDValue Rt = N->getOperand(2);
2101 SDNode *NewN = DAG.getMachineNode(Hexagon::V6_valignb, SDLoc(N),
2102 N->getValueType(0), {Vv, Vu, Rt});
2103 ISel.ReplaceNode(N, NewN);
2104 DAG.RemoveDeadNode(N);
2105}
2106
Krzysztof Parzyszek7d37dd82017-12-06 16:40:37 +00002107void HexagonDAGToDAGISel::SelectHvxShuffle(SDNode *N) {
2108 HvxSelector(*this, *CurDAG).selectShuffle(N);
2109}
2110
2111void HexagonDAGToDAGISel::SelectHvxRor(SDNode *N) {
2112 HvxSelector(*this, *CurDAG).selectRor(N);
2113}
2114
Krzysztof Parzyszek2c3edf02018-03-07 17:27:18 +00002115void HexagonDAGToDAGISel::SelectHvxVAlign(SDNode *N) {
2116 HvxSelector(*this, *CurDAG).selectVAlign(N);
2117}
2118
Krzysztof Parzyszeka8ab1b72017-12-11 18:57:54 +00002119void HexagonDAGToDAGISel::SelectV65GatherPred(SDNode *N) {
2120 const SDLoc &dl(N);
2121 SDValue Chain = N->getOperand(0);
2122 SDValue Address = N->getOperand(2);
2123 SDValue Predicate = N->getOperand(3);
2124 SDValue Base = N->getOperand(4);
2125 SDValue Modifier = N->getOperand(5);
2126 SDValue Offset = N->getOperand(6);
2127
2128 unsigned Opcode;
2129 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
2130 switch (IntNo) {
2131 default:
2132 llvm_unreachable("Unexpected HVX gather intrinsic.");
2133 case Intrinsic::hexagon_V6_vgathermhq:
2134 case Intrinsic::hexagon_V6_vgathermhq_128B:
2135 Opcode = Hexagon::V6_vgathermhq_pseudo;
2136 break;
2137 case Intrinsic::hexagon_V6_vgathermwq:
2138 case Intrinsic::hexagon_V6_vgathermwq_128B:
2139 Opcode = Hexagon::V6_vgathermwq_pseudo;
2140 break;
2141 case Intrinsic::hexagon_V6_vgathermhwq:
2142 case Intrinsic::hexagon_V6_vgathermhwq_128B:
2143 Opcode = Hexagon::V6_vgathermhwq_pseudo;
2144 break;
2145 }
2146
2147 SDVTList VTs = CurDAG->getVTList(MVT::Other);
2148 SDValue Ops[] = { Address, Predicate, Base, Modifier, Offset, Chain };
2149 SDNode *Result = CurDAG->getMachineNode(Opcode, dl, VTs, Ops);
2150
Chandler Carruth66654b72018-08-14 23:30:32 +00002151 MachineMemOperand *MemOp = cast<MemIntrinsicSDNode>(N)->getMemOperand();
2152 CurDAG->setNodeMemRefs(cast<MachineSDNode>(Result), {MemOp});
Krzysztof Parzyszeka8ab1b72017-12-11 18:57:54 +00002153
Nirav Dave3264c1b2018-03-19 20:19:46 +00002154 ReplaceNode(N, Result);
Krzysztof Parzyszeka8ab1b72017-12-11 18:57:54 +00002155}
2156
2157void HexagonDAGToDAGISel::SelectV65Gather(SDNode *N) {
2158 const SDLoc &dl(N);
2159 SDValue Chain = N->getOperand(0);
2160 SDValue Address = N->getOperand(2);
2161 SDValue Base = N->getOperand(3);
2162 SDValue Modifier = N->getOperand(4);
2163 SDValue Offset = N->getOperand(5);
2164
2165 unsigned Opcode;
2166 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
2167 switch (IntNo) {
2168 default:
2169 llvm_unreachable("Unexpected HVX gather intrinsic.");
2170 case Intrinsic::hexagon_V6_vgathermh:
2171 case Intrinsic::hexagon_V6_vgathermh_128B:
2172 Opcode = Hexagon::V6_vgathermh_pseudo;
2173 break;
2174 case Intrinsic::hexagon_V6_vgathermw:
2175 case Intrinsic::hexagon_V6_vgathermw_128B:
2176 Opcode = Hexagon::V6_vgathermw_pseudo;
2177 break;
2178 case Intrinsic::hexagon_V6_vgathermhw:
2179 case Intrinsic::hexagon_V6_vgathermhw_128B:
2180 Opcode = Hexagon::V6_vgathermhw_pseudo;
2181 break;
2182 }
2183
2184 SDVTList VTs = CurDAG->getVTList(MVT::Other);
2185 SDValue Ops[] = { Address, Base, Modifier, Offset, Chain };
2186 SDNode *Result = CurDAG->getMachineNode(Opcode, dl, VTs, Ops);
2187
Chandler Carruth66654b72018-08-14 23:30:32 +00002188 MachineMemOperand *MemOp = cast<MemIntrinsicSDNode>(N)->getMemOperand();
2189 CurDAG->setNodeMemRefs(cast<MachineSDNode>(Result), {MemOp});
Krzysztof Parzyszeka8ab1b72017-12-11 18:57:54 +00002190
Nirav Dave3264c1b2018-03-19 20:19:46 +00002191 ReplaceNode(N, Result);
Krzysztof Parzyszeka8ab1b72017-12-11 18:57:54 +00002192}
2193
2194void HexagonDAGToDAGISel::SelectHVXDualOutput(SDNode *N) {
2195 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
2196 SDNode *Result;
2197 switch (IID) {
2198 case Intrinsic::hexagon_V6_vaddcarry: {
2199 SmallVector<SDValue, 3> Ops = { N->getOperand(1), N->getOperand(2),
2200 N->getOperand(3) };
2201 SDVTList VTs = CurDAG->getVTList(MVT::v16i32, MVT::v512i1);
2202 Result = CurDAG->getMachineNode(Hexagon::V6_vaddcarry, SDLoc(N), VTs, Ops);
2203 break;
2204 }
2205 case Intrinsic::hexagon_V6_vaddcarry_128B: {
2206 SmallVector<SDValue, 3> Ops = { N->getOperand(1), N->getOperand(2),
2207 N->getOperand(3) };
2208 SDVTList VTs = CurDAG->getVTList(MVT::v32i32, MVT::v1024i1);
2209 Result = CurDAG->getMachineNode(Hexagon::V6_vaddcarry, SDLoc(N), VTs, Ops);
2210 break;
2211 }
2212 case Intrinsic::hexagon_V6_vsubcarry: {
2213 SmallVector<SDValue, 3> Ops = { N->getOperand(1), N->getOperand(2),
2214 N->getOperand(3) };
2215 SDVTList VTs = CurDAG->getVTList(MVT::v16i32, MVT::v512i1);
2216 Result = CurDAG->getMachineNode(Hexagon::V6_vsubcarry, SDLoc(N), VTs, Ops);
2217 break;
2218 }
2219 case Intrinsic::hexagon_V6_vsubcarry_128B: {
2220 SmallVector<SDValue, 3> Ops = { N->getOperand(1), N->getOperand(2),
2221 N->getOperand(3) };
2222 SDVTList VTs = CurDAG->getVTList(MVT::v32i32, MVT::v1024i1);
2223 Result = CurDAG->getMachineNode(Hexagon::V6_vsubcarry, SDLoc(N), VTs, Ops);
2224 break;
2225 }
2226 default:
2227 llvm_unreachable("Unexpected HVX dual output intrinsic.");
2228 }
2229 ReplaceUses(N, Result);
2230 ReplaceUses(SDValue(N, 0), SDValue(Result, 0));
2231 ReplaceUses(SDValue(N, 1), SDValue(Result, 1));
2232 CurDAG->RemoveDeadNode(N);
2233}