1 //===- LegalizeVectorOps.cpp - Implement SelectionDAG::LegalizeVectors ----===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the SelectionDAG::LegalizeVectors method.
10 //
11 // The vector legalizer looks for vector operations which might need to be
12 // scalarized and legalizes them. This is a separate step from Legalize because
13 // scalarizing can introduce illegal types.  For example, suppose we have an
14 // ISD::SDIV of type v2i64 on x86-32.  The type is legal (for example, addition
15 // on a v2i64 is legal), but ISD::SDIV isn't legal, so we have to unroll the
16 // operation, which introduces nodes with the illegal type i64 which must be
17 // expanded.  Similarly, suppose we have an ISD::SRA of type v16i8 on PowerPC;
18 // the operation must be unrolled, which introduces nodes with the illegal
19 // type i8 which must be promoted.
20 //
21 // This does not legalize vector manipulations like ISD::BUILD_VECTOR,
22 // or operations that happen to take a vector which are custom-lowered;
23 // the legalization for such operations never produces nodes
24 // with illegal types, so it's okay to put off legalizing them until
25 // SelectionDAG::Legalize runs.
26 //
27 //===----------------------------------------------------------------------===//
28 
29 #include "llvm/ADT/APInt.h"
30 #include "llvm/ADT/DenseMap.h"
31 #include "llvm/ADT/SmallVector.h"
32 #include "llvm/CodeGen/ISDOpcodes.h"
33 #include "llvm/CodeGen/MachineMemOperand.h"
34 #include "llvm/CodeGen/SelectionDAG.h"
35 #include "llvm/CodeGen/SelectionDAGNodes.h"
36 #include "llvm/CodeGen/TargetLowering.h"
37 #include "llvm/CodeGen/ValueTypes.h"
38 #include "llvm/IR/DataLayout.h"
39 #include "llvm/Support/Casting.h"
40 #include "llvm/Support/Compiler.h"
41 #include "llvm/Support/ErrorHandling.h"
42 #include "llvm/Support/MachineValueType.h"
43 #include "llvm/Support/MathExtras.h"
44 #include <cassert>
45 #include <cstdint>
46 #include <iterator>
47 #include <utility>
48 
49 using namespace llvm;
50 
51 #define DEBUG_TYPE "legalizevectorops"
52 
53 namespace {
54 
55 class VectorLegalizer {
56   SelectionDAG& DAG;
57   const TargetLowering &TLI;
58   bool Changed = false; // Keep track of whether anything changed
59 
60   /// For nodes that are of legal width, and that have more than one use, this
61   /// map indicates what regularized operand to use.  This allows us to avoid
62   /// legalizing the same thing more than once.
63   SmallDenseMap<SDValue, SDValue, 64> LegalizedNodes;
64 
65   /// Adds a node to the translation cache.
66   void AddLegalizedOperand(SDValue From, SDValue To) {
67     LegalizedNodes.insert(std::make_pair(From, To));
68     // If someone requests legalization of the new node, return itself.
69     if (From != To)
70       LegalizedNodes.insert(std::make_pair(To, To));
71   }
72 
73   /// Legalizes the given node.
74   SDValue LegalizeOp(SDValue Op);
75 
76   /// Assuming the node is legal, "legalize" the results.
77   SDValue TranslateLegalizeResults(SDValue Op, SDValue Result);
78 
79   /// Implements unrolling a VSETCC.
80   SDValue UnrollVSETCC(SDValue Op);
81 
82   /// Implement expand-based legalization of vector operations.
83   ///
84   /// This is just a high-level routine to dispatch to specific code paths for
85   /// operations to legalize them.
86   SDValue Expand(SDValue Op);
87 
88   /// Implements expansion for FP_TO_UINT; falls back to UnrollVectorOp if
89   /// FP_TO_SINT isn't legal.
90   SDValue ExpandFP_TO_UINT(SDValue Op);
91 
92   /// Implements expansion for UINT_TO_FLOAT; falls back to UnrollVectorOp if
93   /// SINT_TO_FLOAT and SHR on vectors isn't legal.
94   SDValue ExpandUINT_TO_FLOAT(SDValue Op);
95 
96   /// Implement expansion for SIGN_EXTEND_INREG using SRL and SRA.
97   SDValue ExpandSEXTINREG(SDValue Op);
98 
99   /// Implement expansion for ANY_EXTEND_VECTOR_INREG.
100   ///
101   /// Shuffles the low lanes of the operand into place and bitcasts to the proper
102   /// type. The contents of the bits in the extended part of each element are
103   /// undef.
104   SDValue ExpandANY_EXTEND_VECTOR_INREG(SDValue Op);
105 
106   /// Implement expansion for SIGN_EXTEND_VECTOR_INREG.
107   ///
108   /// Shuffles the low lanes of the operand into place, bitcasts to the proper
109   /// type, then shifts left and arithmetic shifts right to introduce a sign
110   /// extension.
111   SDValue ExpandSIGN_EXTEND_VECTOR_INREG(SDValue Op);
112 
113   /// Implement expansion for ZERO_EXTEND_VECTOR_INREG.
114   ///
115   /// Shuffles the low lanes of the operand into place and blends zeros into
116   /// the remaining lanes, finally bitcasting to the proper type.
117   SDValue ExpandZERO_EXTEND_VECTOR_INREG(SDValue Op);
118 
119   /// Implement expand-based legalization of ABS vector operations.
120   /// If following expanding is legal/custom then do it:
121   /// (ABS x) --> (XOR (ADD x, (SRA x, sizeof(x)-1)), (SRA x, sizeof(x)-1))
122   /// else unroll the operation.
123   SDValue ExpandABS(SDValue Op);
124 
125   /// Expand bswap of vectors into a shuffle if legal.
126   SDValue ExpandBSWAP(SDValue Op);
127 
128   /// Implement vselect in terms of XOR, AND, OR when blend is not
129   /// supported by the target.
130   SDValue ExpandVSELECT(SDValue Op);
131   SDValue ExpandSELECT(SDValue Op);
132   SDValue ExpandLoad(SDValue Op);
133   SDValue ExpandStore(SDValue Op);
134   SDValue ExpandFNEG(SDValue Op);
135   SDValue ExpandFSUB(SDValue Op);
136   SDValue ExpandBITREVERSE(SDValue Op);
137   SDValue ExpandCTPOP(SDValue Op);
138   SDValue ExpandCTLZ(SDValue Op);
139   SDValue ExpandCTTZ(SDValue Op);
140   SDValue ExpandFunnelShift(SDValue Op);
141   SDValue ExpandROT(SDValue Op);
142   SDValue ExpandFMINNUM_FMAXNUM(SDValue Op);
143   SDValue ExpandMULO(SDValue Op);
144   SDValue ExpandAddSubSat(SDValue Op);
145   SDValue ExpandFixedPointMul(SDValue Op);
146   SDValue ExpandStrictFPOp(SDValue Op);
147 
148   /// Implements vector promotion.
149   ///
150   /// This is essentially just bitcasting the operands to a different type and
151   /// bitcasting the result back to the original type.
152   SDValue Promote(SDValue Op);
153 
154   /// Implements [SU]INT_TO_FP vector promotion.
155   ///
156   /// This is a [zs]ext of the input operand to a larger integer type.
157   SDValue PromoteINT_TO_FP(SDValue Op);
158 
159   /// Implements FP_TO_[SU]INT vector promotion of the result type.
160   ///
161   /// It is promoted to a larger integer type.  The result is then
162   /// truncated back to the original type.
163   SDValue PromoteFP_TO_INT(SDValue Op);
164 
165 public:
166   VectorLegalizer(SelectionDAG& dag) :
167       DAG(dag), TLI(dag.getTargetLoweringInfo()) {}
168 
169   /// Begin legalizer the vector operations in the DAG.
170   bool Run();
171 };
172 
173 } // end anonymous namespace
174 
175 bool VectorLegalizer::Run() {
176   // Before we start legalizing vector nodes, check if there are any vectors.
177   bool HasVectors = false;
178   for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
179        E = std::prev(DAG.allnodes_end()); I != std::next(E); ++I) {
180     // Check if the values of the nodes contain vectors. We don't need to check
181     // the operands because we are going to check their values at some point.
182     for (SDNode::value_iterator J = I->value_begin(), E = I->value_end();
183          J != E; ++J)
184       HasVectors |= J->isVector();
185 
186     // If we found a vector node we can start the legalization.
187     if (HasVectors)
188       break;
189   }
190 
191   // If this basic block has no vectors then no need to legalize vectors.
192   if (!HasVectors)
193     return false;
194 
195   // The legalize process is inherently a bottom-up recursive process (users
196   // legalize their uses before themselves).  Given infinite stack space, we
197   // could just start legalizing on the root and traverse the whole graph.  In
198   // practice however, this causes us to run out of stack space on large basic
199   // blocks.  To avoid this problem, compute an ordering of the nodes where each
200   // node is only legalized after all of its operands are legalized.
201   DAG.AssignTopologicalOrder();
202   for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
203        E = std::prev(DAG.allnodes_end()); I != std::next(E); ++I)
204     LegalizeOp(SDValue(&*I, 0));
205 
206   // Finally, it's possible the root changed.  Get the new root.
207   SDValue OldRoot = DAG.getRoot();
208   assert(LegalizedNodes.count(OldRoot) && "Root didn't get legalized?");
209   DAG.setRoot(LegalizedNodes[OldRoot]);
210 
211   LegalizedNodes.clear();
212 
213   // Remove dead nodes now.
214   DAG.RemoveDeadNodes();
215 
216   return Changed;
217 }
218 
219 SDValue VectorLegalizer::TranslateLegalizeResults(SDValue Op, SDValue Result) {
220   // Generic legalization: just pass the operand through.
221   for (unsigned i = 0, e = Op.getNode()->getNumValues(); i != e; ++i)
222     AddLegalizedOperand(Op.getValue(i), Result.getValue(i));
223   return Result.getValue(Op.getResNo());
224 }
225 
226 SDValue VectorLegalizer::LegalizeOp(SDValue Op) {
227   // Note that LegalizeOp may be reentered even from single-use nodes, which
228   // means that we always must cache transformed nodes.
229   DenseMap<SDValue, SDValue>::iterator I = LegalizedNodes.find(Op);
230   if (I != LegalizedNodes.end()) return I->second;
231 
232   SDNode* Node = Op.getNode();
233 
234   // Legalize the operands
235   SmallVector<SDValue, 8> Ops;
236   for (const SDValue &Op : Node->op_values())
237     Ops.push_back(LegalizeOp(Op));
238 
239   SDValue Result = SDValue(DAG.UpdateNodeOperands(Op.getNode(), Ops),
240                            Op.getResNo());
241 
242   if (Op.getOpcode() == ISD::LOAD) {
243     LoadSDNode *LD = cast<LoadSDNode>(Op.getNode());
244     ISD::LoadExtType ExtType = LD->getExtensionType();
245     if (LD->getMemoryVT().isVector() && ExtType != ISD::NON_EXTLOAD) {
246       LLVM_DEBUG(dbgs() << "\nLegalizing extending vector load: ";
247                  Node->dump(&DAG));
248       switch (TLI.getLoadExtAction(LD->getExtensionType(), LD->getValueType(0),
249                                    LD->getMemoryVT())) {
250       default: llvm_unreachable("This action is not supported yet!");
251       case TargetLowering::Legal:
252         return TranslateLegalizeResults(Op, Result);
253       case TargetLowering::Custom:
254         if (SDValue Lowered = TLI.LowerOperation(Result, DAG)) {
255           assert(Lowered->getNumValues() == Op->getNumValues() &&
256                  "Unexpected number of results");
257           if (Lowered != Result) {
258             // Make sure the new code is also legal.
259             Lowered = LegalizeOp(Lowered);
260             Changed = true;
261           }
262           return TranslateLegalizeResults(Op, Lowered);
263         }
264         LLVM_FALLTHROUGH;
265       case TargetLowering::Expand:
266         Changed = true;
267         return LegalizeOp(ExpandLoad(Op));
268       }
269     }
270   } else if (Op.getOpcode() == ISD::STORE) {
271     StoreSDNode *ST = cast<StoreSDNode>(Op.getNode());
272     EVT StVT = ST->getMemoryVT();
273     MVT ValVT = ST->getValue().getSimpleValueType();
274     if (StVT.isVector() && ST->isTruncatingStore()) {
275       LLVM_DEBUG(dbgs() << "\nLegalizing truncating vector store: ";
276                  Node->dump(&DAG));
277       switch (TLI.getTruncStoreAction(ValVT, StVT)) {
278       default: llvm_unreachable("This action is not supported yet!");
279       case TargetLowering::Legal:
280         return TranslateLegalizeResults(Op, Result);
281       case TargetLowering::Custom: {
282         SDValue Lowered = TLI.LowerOperation(Result, DAG);
283         if (Lowered != Result) {
284           // Make sure the new code is also legal.
285           Lowered = LegalizeOp(Lowered);
286           Changed = true;
287         }
288         return TranslateLegalizeResults(Op, Lowered);
289       }
290       case TargetLowering::Expand:
291         Changed = true;
292         return LegalizeOp(ExpandStore(Op));
293       }
294     }
295   }
296 
297   bool HasVectorValueOrOp = false;
298   for (auto J = Node->value_begin(), E = Node->value_end(); J != E; ++J)
299     HasVectorValueOrOp |= J->isVector();
300   for (const SDValue &Op : Node->op_values())
301     HasVectorValueOrOp |= Op.getValueType().isVector();
302 
303   if (!HasVectorValueOrOp)
304     return TranslateLegalizeResults(Op, Result);
305 
306   TargetLowering::LegalizeAction Action = TargetLowering::Legal;
307   switch (Op.getOpcode()) {
308   default:
309     return TranslateLegalizeResults(Op, Result);
310   case ISD::STRICT_FADD:
311   case ISD::STRICT_FSUB:
312   case ISD::STRICT_FMUL:
313   case ISD::STRICT_FDIV:
314   case ISD::STRICT_FREM:
315   case ISD::STRICT_FSQRT:
316   case ISD::STRICT_FMA:
317   case ISD::STRICT_FPOW:
318   case ISD::STRICT_FPOWI:
319   case ISD::STRICT_FSIN:
320   case ISD::STRICT_FCOS:
321   case ISD::STRICT_FEXP:
322   case ISD::STRICT_FEXP2:
323   case ISD::STRICT_FLOG:
324   case ISD::STRICT_FLOG10:
325   case ISD::STRICT_FLOG2:
326   case ISD::STRICT_FRINT:
327   case ISD::STRICT_FNEARBYINT:
328   case ISD::STRICT_FMAXNUM:
329   case ISD::STRICT_FMINNUM:
330   case ISD::STRICT_FCEIL:
331   case ISD::STRICT_FFLOOR:
332   case ISD::STRICT_FROUND:
333   case ISD::STRICT_FTRUNC:
334     // These pseudo-ops get legalized as if they were their non-strict
335     // equivalent.  For instance, if ISD::FSQRT is legal then ISD::STRICT_FSQRT
336     // is also legal, but if ISD::FSQRT requires expansion then so does
337     // ISD::STRICT_FSQRT.
338     Action = TLI.getStrictFPOperationAction(Node->getOpcode(),
339                                             Node->getValueType(0));
340     break;
341   case ISD::ADD:
342   case ISD::SUB:
343   case ISD::MUL:
344   case ISD::MULHS:
345   case ISD::MULHU:
346   case ISD::SDIV:
347   case ISD::UDIV:
348   case ISD::SREM:
349   case ISD::UREM:
350   case ISD::SDIVREM:
351   case ISD::UDIVREM:
352   case ISD::FADD:
353   case ISD::FSUB:
354   case ISD::FMUL:
355   case ISD::FDIV:
356   case ISD::FREM:
357   case ISD::AND:
358   case ISD::OR:
359   case ISD::XOR:
360   case ISD::SHL:
361   case ISD::SRA:
362   case ISD::SRL:
363   case ISD::FSHL:
364   case ISD::FSHR:
365   case ISD::ROTL:
366   case ISD::ROTR:
367   case ISD::ABS:
368   case ISD::BSWAP:
369   case ISD::BITREVERSE:
370   case ISD::CTLZ:
371   case ISD::CTTZ:
372   case ISD::CTLZ_ZERO_UNDEF:
373   case ISD::CTTZ_ZERO_UNDEF:
374   case ISD::CTPOP:
375   case ISD::SELECT:
376   case ISD::VSELECT:
377   case ISD::SELECT_CC:
378   case ISD::SETCC:
379   case ISD::ZERO_EXTEND:
380   case ISD::ANY_EXTEND:
381   case ISD::TRUNCATE:
382   case ISD::SIGN_EXTEND:
383   case ISD::FP_TO_SINT:
384   case ISD::FP_TO_UINT:
385   case ISD::FNEG:
386   case ISD::FABS:
387   case ISD::FMINNUM:
388   case ISD::FMAXNUM:
389   case ISD::FMINNUM_IEEE:
390   case ISD::FMAXNUM_IEEE:
391   case ISD::FMINIMUM:
392   case ISD::FMAXIMUM:
393   case ISD::FCOPYSIGN:
394   case ISD::FSQRT:
395   case ISD::FSIN:
396   case ISD::FCOS:
397   case ISD::FPOWI:
398   case ISD::FPOW:
399   case ISD::FLOG:
400   case ISD::FLOG2:
401   case ISD::FLOG10:
402   case ISD::FEXP:
403   case ISD::FEXP2:
404   case ISD::FCEIL:
405   case ISD::FTRUNC:
406   case ISD::FRINT:
407   case ISD::FNEARBYINT:
408   case ISD::FROUND:
409   case ISD::FFLOOR:
410   case ISD::FP_ROUND:
411   case ISD::FP_EXTEND:
412   case ISD::FMA:
413   case ISD::SIGN_EXTEND_INREG:
414   case ISD::ANY_EXTEND_VECTOR_INREG:
415   case ISD::SIGN_EXTEND_VECTOR_INREG:
416   case ISD::ZERO_EXTEND_VECTOR_INREG:
417   case ISD::SMIN:
418   case ISD::SMAX:
419   case ISD::UMIN:
420   case ISD::UMAX:
421   case ISD::SMUL_LOHI:
422   case ISD::UMUL_LOHI:
423   case ISD::SMULO:
424   case ISD::UMULO:
425   case ISD::FCANONICALIZE:
426   case ISD::SADDSAT:
427   case ISD::UADDSAT:
428   case ISD::SSUBSAT:
429   case ISD::USUBSAT:
430     Action = TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0));
431     break;
432   case ISD::SMULFIX:
433   case ISD::UMULFIX: {
434     unsigned Scale = Node->getConstantOperandVal(2);
435     Action = TLI.getFixedPointOperationAction(Node->getOpcode(),
436                                               Node->getValueType(0), Scale);
437     break;
438   }
439   case ISD::FP_ROUND_INREG:
440     Action = TLI.getOperationAction(Node->getOpcode(),
441                cast<VTSDNode>(Node->getOperand(1))->getVT());
442     break;
443   case ISD::SINT_TO_FP:
444   case ISD::UINT_TO_FP:
445   case ISD::VECREDUCE_ADD:
446   case ISD::VECREDUCE_MUL:
447   case ISD::VECREDUCE_AND:
448   case ISD::VECREDUCE_OR:
449   case ISD::VECREDUCE_XOR:
450   case ISD::VECREDUCE_SMAX:
451   case ISD::VECREDUCE_SMIN:
452   case ISD::VECREDUCE_UMAX:
453   case ISD::VECREDUCE_UMIN:
454   case ISD::VECREDUCE_FADD:
455   case ISD::VECREDUCE_FMUL:
456   case ISD::VECREDUCE_FMAX:
457   case ISD::VECREDUCE_FMIN:
458     Action = TLI.getOperationAction(Node->getOpcode(),
459                                     Node->getOperand(0).getValueType());
460     break;
461   }
462 
463   LLVM_DEBUG(dbgs() << "\nLegalizing vector op: "; Node->dump(&DAG));
464 
465   switch (Action) {
466   default: llvm_unreachable("This action is not supported yet!");
467   case TargetLowering::Promote:
468     Result = Promote(Op);
469     Changed = true;
470     break;
471   case TargetLowering::Legal:
472     LLVM_DEBUG(dbgs() << "Legal node: nothing to do\n");
473     break;
474   case TargetLowering::Custom: {
475     LLVM_DEBUG(dbgs() << "Trying custom legalization\n");
476     if (SDValue Tmp1 = TLI.LowerOperation(Op, DAG)) {
477       LLVM_DEBUG(dbgs() << "Successfully custom legalized node\n");
478       Result = Tmp1;
479       break;
480     }
481     LLVM_DEBUG(dbgs() << "Could not custom legalize node\n");
482     LLVM_FALLTHROUGH;
483   }
484   case TargetLowering::Expand:
485     Result = Expand(Op);
486   }
487 
488   // Make sure that the generated code is itself legal.
489   if (Result != Op) {
490     Result = LegalizeOp(Result);
491     Changed = true;
492   }
493 
494   // Note that LegalizeOp may be reentered even from single-use nodes, which
495   // means that we always must cache transformed nodes.
496   AddLegalizedOperand(Op, Result);
497   return Result;
498 }
499 
500 SDValue VectorLegalizer::Promote(SDValue Op) {
501   // For a few operations there is a specific concept for promotion based on
502   // the operand's type.
503   switch (Op.getOpcode()) {
504   case ISD::SINT_TO_FP:
505   case ISD::UINT_TO_FP:
506     // "Promote" the operation by extending the operand.
507     return PromoteINT_TO_FP(Op);
508   case ISD::FP_TO_UINT:
509   case ISD::FP_TO_SINT:
510     // Promote the operation by extending the operand.
511     return PromoteFP_TO_INT(Op);
512   }
513 
514   // There are currently two cases of vector promotion:
515   // 1) Bitcasting a vector of integers to a different type to a vector of the
516   //    same overall length. For example, x86 promotes ISD::AND v2i32 to v1i64.
517   // 2) Extending a vector of floats to a vector of the same number of larger
518   //    floats. For example, AArch64 promotes ISD::FADD on v4f16 to v4f32.
519   MVT VT = Op.getSimpleValueType();
520   assert(Op.getNode()->getNumValues() == 1 &&
521          "Can't promote a vector with multiple results!");
522   MVT NVT = TLI.getTypeToPromoteTo(Op.getOpcode(), VT);
523   SDLoc dl(Op);
524   SmallVector<SDValue, 4> Operands(Op.getNumOperands());
525 
526   for (unsigned j = 0; j != Op.getNumOperands(); ++j) {
527     if (Op.getOperand(j).getValueType().isVector())
528       if (Op.getOperand(j)
529               .getValueType()
530               .getVectorElementType()
531               .isFloatingPoint() &&
532           NVT.isVector() && NVT.getVectorElementType().isFloatingPoint())
533         Operands[j] = DAG.getNode(ISD::FP_EXTEND, dl, NVT, Op.getOperand(j));
534       else
535         Operands[j] = DAG.getNode(ISD::BITCAST, dl, NVT, Op.getOperand(j));
536     else
537       Operands[j] = Op.getOperand(j);
538   }
539 
540   Op = DAG.getNode(Op.getOpcode(), dl, NVT, Operands, Op.getNode()->getFlags());
541   if ((VT.isFloatingPoint() && NVT.isFloatingPoint()) ||
542       (VT.isVector() && VT.getVectorElementType().isFloatingPoint() &&
543        NVT.isVector() && NVT.getVectorElementType().isFloatingPoint()))
544     return DAG.getNode(ISD::FP_ROUND, dl, VT, Op, DAG.getIntPtrConstant(0, dl));
545   else
546     return DAG.getNode(ISD::BITCAST, dl, VT, Op);
547 }
548 
549 SDValue VectorLegalizer::PromoteINT_TO_FP(SDValue Op) {
550   // INT_TO_FP operations may require the input operand be promoted even
551   // when the type is otherwise legal.
552   MVT VT = Op.getOperand(0).getSimpleValueType();
553   MVT NVT = TLI.getTypeToPromoteTo(Op.getOpcode(), VT);
554   assert(NVT.getVectorNumElements() == VT.getVectorNumElements() &&
555          "Vectors have different number of elements!");
556 
557   SDLoc dl(Op);
558   SmallVector<SDValue, 4> Operands(Op.getNumOperands());
559 
560   unsigned Opc = Op.getOpcode() == ISD::UINT_TO_FP ? ISD::ZERO_EXTEND :
561     ISD::SIGN_EXTEND;
562   for (unsigned j = 0; j != Op.getNumOperands(); ++j) {
563     if (Op.getOperand(j).getValueType().isVector())
564       Operands[j] = DAG.getNode(Opc, dl, NVT, Op.getOperand(j));
565     else
566       Operands[j] = Op.getOperand(j);
567   }
568 
569   return DAG.getNode(Op.getOpcode(), dl, Op.getValueType(), Operands);
570 }
571 
572 // For FP_TO_INT we promote the result type to a vector type with wider
573 // elements and then truncate the result.  This is different from the default
574 // PromoteVector which uses bitcast to promote thus assumning that the
575 // promoted vector type has the same overall size.
576 SDValue VectorLegalizer::PromoteFP_TO_INT(SDValue Op) {
577   MVT VT = Op.getSimpleValueType();
578   MVT NVT = TLI.getTypeToPromoteTo(Op.getOpcode(), VT);
579   assert(NVT.getVectorNumElements() == VT.getVectorNumElements() &&
580          "Vectors have different number of elements!");
581 
582   unsigned NewOpc = Op->getOpcode();
583   // Change FP_TO_UINT to FP_TO_SINT if possible.
584   // TODO: Should we only do this if FP_TO_UINT itself isn't legal?
585   if (NewOpc == ISD::FP_TO_UINT &&
586       TLI.isOperationLegalOrCustom(ISD::FP_TO_SINT, NVT))
587     NewOpc = ISD::FP_TO_SINT;
588 
589   SDLoc dl(Op);
590   SDValue Promoted  = DAG.getNode(NewOpc, dl, NVT, Op.getOperand(0));
591 
592   // Assert that the converted value fits in the original type.  If it doesn't
593   // (eg: because the value being converted is too big), then the result of the
594   // original operation was undefined anyway, so the assert is still correct.
595   Promoted = DAG.getNode(Op->getOpcode() == ISD::FP_TO_UINT ? ISD::AssertZext
596                                                             : ISD::AssertSext,
597                          dl, NVT, Promoted,
598                          DAG.getValueType(VT.getScalarType()));
599   return DAG.getNode(ISD::TRUNCATE, dl, VT, Promoted);
600 }
601 
602 SDValue VectorLegalizer::ExpandLoad(SDValue Op) {
603   LoadSDNode *LD = cast<LoadSDNode>(Op.getNode());
604 
605   EVT SrcVT = LD->getMemoryVT();
606   EVT SrcEltVT = SrcVT.getScalarType();
607   unsigned NumElem = SrcVT.getVectorNumElements();
608 
609   SDValue NewChain;
610   SDValue Value;
611   if (SrcVT.getVectorNumElements() > 1 && !SrcEltVT.isByteSized()) {
612     SDLoc dl(Op);
613 
614     SmallVector<SDValue, 8> Vals;
615     SmallVector<SDValue, 8> LoadChains;
616 
617     EVT DstEltVT = LD->getValueType(0).getScalarType();
618     SDValue Chain = LD->getChain();
619     SDValue BasePTR = LD->getBasePtr();
620     ISD::LoadExtType ExtType = LD->getExtensionType();
621 
622     // When elements in a vector is not byte-addressable, we cannot directly
623     // load each element by advancing pointer, which could only address bytes.
624     // Instead, we load all significant words, mask bits off, and concatenate
625     // them to form each element. Finally, they are extended to destination
626     // scalar type to build the destination vector.
627     EVT WideVT = TLI.getPointerTy(DAG.getDataLayout());
628 
629     assert(WideVT.isRound() &&
630            "Could not handle the sophisticated case when the widest integer is"
631            " not power of 2.");
632     assert(WideVT.bitsGE(SrcEltVT) &&
633            "Type is not legalized?");
634 
635     unsigned WideBytes = WideVT.getStoreSize();
636     unsigned Offset = 0;
637     unsigned RemainingBytes = SrcVT.getStoreSize();
638     SmallVector<SDValue, 8> LoadVals;
639     while (RemainingBytes > 0) {
640       SDValue ScalarLoad;
641       unsigned LoadBytes = WideBytes;
642 
643       if (RemainingBytes >= LoadBytes) {
644         ScalarLoad =
645             DAG.getLoad(WideVT, dl, Chain, BasePTR,
646                         LD->getPointerInfo().getWithOffset(Offset),
647                         MinAlign(LD->getAlignment(), Offset),
648                         LD->getMemOperand()->getFlags(), LD->getAAInfo());
649       } else {
650         EVT LoadVT = WideVT;
651         while (RemainingBytes < LoadBytes) {
652           LoadBytes >>= 1; // Reduce the load size by half.
653           LoadVT = EVT::getIntegerVT(*DAG.getContext(), LoadBytes << 3);
654         }
655         ScalarLoad =
656             DAG.getExtLoad(ISD::EXTLOAD, dl, WideVT, Chain, BasePTR,
657                            LD->getPointerInfo().getWithOffset(Offset), LoadVT,
658                            MinAlign(LD->getAlignment(), Offset),
659                            LD->getMemOperand()->getFlags(), LD->getAAInfo());
660       }
661 
662       RemainingBytes -= LoadBytes;
663       Offset += LoadBytes;
664 
665       BasePTR = DAG.getObjectPtrOffset(dl, BasePTR, LoadBytes);
666 
667       LoadVals.push_back(ScalarLoad.getValue(0));
668       LoadChains.push_back(ScalarLoad.getValue(1));
669     }
670 
671     unsigned BitOffset = 0;
672     unsigned WideIdx = 0;
673     unsigned WideBits = WideVT.getSizeInBits();
674 
675     // Extract bits, pack and extend/trunc them into destination type.
676     unsigned SrcEltBits = SrcEltVT.getSizeInBits();
677     SDValue SrcEltBitMask = DAG.getConstant(
678         APInt::getLowBitsSet(WideBits, SrcEltBits), dl, WideVT);
679 
680     for (unsigned Idx = 0; Idx != NumElem; ++Idx) {
681       assert(BitOffset < WideBits && "Unexpected offset!");
682 
683       SDValue ShAmt = DAG.getConstant(
684           BitOffset, dl, TLI.getShiftAmountTy(WideVT, DAG.getDataLayout()));
685       SDValue Lo = DAG.getNode(ISD::SRL, dl, WideVT, LoadVals[WideIdx], ShAmt);
686 
687       BitOffset += SrcEltBits;
688       if (BitOffset >= WideBits) {
689         WideIdx++;
690         BitOffset -= WideBits;
691         if (BitOffset > 0) {
692           ShAmt = DAG.getConstant(
693               SrcEltBits - BitOffset, dl,
694               TLI.getShiftAmountTy(WideVT, DAG.getDataLayout()));
695           SDValue Hi =
696               DAG.getNode(ISD::SHL, dl, WideVT, LoadVals[WideIdx], ShAmt);
697           Lo = DAG.getNode(ISD::OR, dl, WideVT, Lo, Hi);
698         }
699       }
700 
701       Lo = DAG.getNode(ISD::AND, dl, WideVT, Lo, SrcEltBitMask);
702 
703       switch (ExtType) {
704       default: llvm_unreachable("Unknown extended-load op!");
705       case ISD::EXTLOAD:
706         Lo = DAG.getAnyExtOrTrunc(Lo, dl, DstEltVT);
707         break;
708       case ISD::ZEXTLOAD:
709         Lo = DAG.getZExtOrTrunc(Lo, dl, DstEltVT);
710         break;
711       case ISD::SEXTLOAD:
712         ShAmt =
713             DAG.getConstant(WideBits - SrcEltBits, dl,
714                             TLI.getShiftAmountTy(WideVT, DAG.getDataLayout()));
715         Lo = DAG.getNode(ISD::SHL, dl, WideVT, Lo, ShAmt);
716         Lo = DAG.getNode(ISD::SRA, dl, WideVT, Lo, ShAmt);
717         Lo = DAG.getSExtOrTrunc(Lo, dl, DstEltVT);
718         break;
719       }
720       Vals.push_back(Lo);
721     }
722 
723     NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
724     Value = DAG.getBuildVector(Op.getNode()->getValueType(0), dl, Vals);
725   } else {
726     SDValue Scalarized = TLI.scalarizeVectorLoad(LD, DAG);
727     // Skip past MERGE_VALUE node if known.
728     if (Scalarized->getOpcode() == ISD::MERGE_VALUES) {
729       NewChain = Scalarized.getOperand(1);
730       Value = Scalarized.getOperand(0);
731     } else {
732       NewChain = Scalarized.getValue(1);
733       Value = Scalarized.getValue(0);
734     }
735   }
736 
737   AddLegalizedOperand(Op.getValue(0), Value);
738   AddLegalizedOperand(Op.getValue(1), NewChain);
739 
740   return (Op.getResNo() ? NewChain : Value);
741 }
742 
743 SDValue VectorLegalizer::ExpandStore(SDValue Op) {
744   StoreSDNode *ST = cast<StoreSDNode>(Op.getNode());
745   SDValue TF = TLI.scalarizeVectorStore(ST, DAG);
746   AddLegalizedOperand(Op, TF);
747   return TF;
748 }
749 
750 SDValue VectorLegalizer::Expand(SDValue Op) {
751   switch (Op->getOpcode()) {
752   case ISD::SIGN_EXTEND_INREG:
753     return ExpandSEXTINREG(Op);
754   case ISD::ANY_EXTEND_VECTOR_INREG:
755     return ExpandANY_EXTEND_VECTOR_INREG(Op);
756   case ISD::SIGN_EXTEND_VECTOR_INREG:
757     return ExpandSIGN_EXTEND_VECTOR_INREG(Op);
758   case ISD::ZERO_EXTEND_VECTOR_INREG:
759     return ExpandZERO_EXTEND_VECTOR_INREG(Op);
760   case ISD::BSWAP:
761     return ExpandBSWAP(Op);
762   case ISD::VSELECT:
763     return ExpandVSELECT(Op);
764   case ISD::SELECT:
765     return ExpandSELECT(Op);
766   case ISD::FP_TO_UINT:
767     return ExpandFP_TO_UINT(Op);
768   case ISD::UINT_TO_FP:
769     return ExpandUINT_TO_FLOAT(Op);
770   case ISD::FNEG:
771     return ExpandFNEG(Op);
772   case ISD::FSUB:
773     return ExpandFSUB(Op);
774   case ISD::SETCC:
775     return UnrollVSETCC(Op);
776   case ISD::ABS:
777     return ExpandABS(Op);
778   case ISD::BITREVERSE:
779     return ExpandBITREVERSE(Op);
780   case ISD::CTPOP:
781     return ExpandCTPOP(Op);
782   case ISD::CTLZ:
783   case ISD::CTLZ_ZERO_UNDEF:
784     return ExpandCTLZ(Op);
785   case ISD::CTTZ:
786   case ISD::CTTZ_ZERO_UNDEF:
787     return ExpandCTTZ(Op);
788   case ISD::FSHL:
789   case ISD::FSHR:
790     return ExpandFunnelShift(Op);
791   case ISD::ROTL:
792   case ISD::ROTR:
793     return ExpandROT(Op);
794   case ISD::FMINNUM:
795   case ISD::FMAXNUM:
796     return ExpandFMINNUM_FMAXNUM(Op);
797   case ISD::UMULO:
798   case ISD::SMULO:
799     return ExpandMULO(Op);
800   case ISD::USUBSAT:
801   case ISD::SSUBSAT:
802   case ISD::UADDSAT:
803   case ISD::SADDSAT:
804     return ExpandAddSubSat(Op);
805   case ISD::SMULFIX:
806   case ISD::UMULFIX:
807     return ExpandFixedPointMul(Op);
808   case ISD::STRICT_FADD:
809   case ISD::STRICT_FSUB:
810   case ISD::STRICT_FMUL:
811   case ISD::STRICT_FDIV:
812   case ISD::STRICT_FREM:
813   case ISD::STRICT_FSQRT:
814   case ISD::STRICT_FMA:
815   case ISD::STRICT_FPOW:
816   case ISD::STRICT_FPOWI:
817   case ISD::STRICT_FSIN:
818   case ISD::STRICT_FCOS:
819   case ISD::STRICT_FEXP:
820   case ISD::STRICT_FEXP2:
821   case ISD::STRICT_FLOG:
822   case ISD::STRICT_FLOG10:
823   case ISD::STRICT_FLOG2:
824   case ISD::STRICT_FRINT:
825   case ISD::STRICT_FNEARBYINT:
826   case ISD::STRICT_FMAXNUM:
827   case ISD::STRICT_FMINNUM:
828   case ISD::STRICT_FCEIL:
829   case ISD::STRICT_FFLOOR:
830   case ISD::STRICT_FROUND:
831   case ISD::STRICT_FTRUNC:
832     return ExpandStrictFPOp(Op);
833   case ISD::VECREDUCE_ADD:
834   case ISD::VECREDUCE_MUL:
835   case ISD::VECREDUCE_AND:
836   case ISD::VECREDUCE_OR:
837   case ISD::VECREDUCE_XOR:
838   case ISD::VECREDUCE_SMAX:
839   case ISD::VECREDUCE_SMIN:
840   case ISD::VECREDUCE_UMAX:
841   case ISD::VECREDUCE_UMIN:
842   case ISD::VECREDUCE_FADD:
843   case ISD::VECREDUCE_FMUL:
844   case ISD::VECREDUCE_FMAX:
845   case ISD::VECREDUCE_FMIN:
846     return TLI.expandVecReduce(Op.getNode(), DAG);
847   default:
848     return DAG.UnrollVectorOp(Op.getNode());
849   }
850 }
851 
852 SDValue VectorLegalizer::ExpandSELECT(SDValue Op) {
853   // Lower a select instruction where the condition is a scalar and the
854   // operands are vectors. Lower this select to VSELECT and implement it
855   // using XOR AND OR. The selector bit is broadcasted.
856   EVT VT = Op.getValueType();
857   SDLoc DL(Op);
858 
859   SDValue Mask = Op.getOperand(0);
860   SDValue Op1 = Op.getOperand(1);
861   SDValue Op2 = Op.getOperand(2);
862 
863   assert(VT.isVector() && !Mask.getValueType().isVector()
864          && Op1.getValueType() == Op2.getValueType() && "Invalid type");
865 
866   // If we can't even use the basic vector operations of
867   // AND,OR,XOR, we will have to scalarize the op.
868   // Notice that the operation may be 'promoted' which means that it is
869   // 'bitcasted' to another type which is handled.
870   // Also, we need to be able to construct a splat vector using BUILD_VECTOR.
871   if (TLI.getOperationAction(ISD::AND, VT) == TargetLowering::Expand ||
872       TLI.getOperationAction(ISD::XOR, VT) == TargetLowering::Expand ||
873       TLI.getOperationAction(ISD::OR,  VT) == TargetLowering::Expand ||
874       TLI.getOperationAction(ISD::BUILD_VECTOR,  VT) == TargetLowering::Expand)
875     return DAG.UnrollVectorOp(Op.getNode());
876 
877   // Generate a mask operand.
878   EVT MaskTy = VT.changeVectorElementTypeToInteger();
879 
880   // What is the size of each element in the vector mask.
881   EVT BitTy = MaskTy.getScalarType();
882 
883   Mask = DAG.getSelect(DL, BitTy, Mask,
884           DAG.getConstant(APInt::getAllOnesValue(BitTy.getSizeInBits()), DL,
885                           BitTy),
886           DAG.getConstant(0, DL, BitTy));
887 
888   // Broadcast the mask so that the entire vector is all-one or all zero.
889   Mask = DAG.getSplatBuildVector(MaskTy, DL, Mask);
890 
891   // Bitcast the operands to be the same type as the mask.
892   // This is needed when we select between FP types because
893   // the mask is a vector of integers.
894   Op1 = DAG.getNode(ISD::BITCAST, DL, MaskTy, Op1);
895   Op2 = DAG.getNode(ISD::BITCAST, DL, MaskTy, Op2);
896 
897   SDValue AllOnes = DAG.getConstant(
898             APInt::getAllOnesValue(BitTy.getSizeInBits()), DL, MaskTy);
899   SDValue NotMask = DAG.getNode(ISD::XOR, DL, MaskTy, Mask, AllOnes);
900 
901   Op1 = DAG.getNode(ISD::AND, DL, MaskTy, Op1, Mask);
902   Op2 = DAG.getNode(ISD::AND, DL, MaskTy, Op2, NotMask);
903   SDValue Val = DAG.getNode(ISD::OR, DL, MaskTy, Op1, Op2);
904   return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Val);
905 }
906 
907 SDValue VectorLegalizer::ExpandSEXTINREG(SDValue Op) {
908   EVT VT = Op.getValueType();
909 
910   // Make sure that the SRA and SHL instructions are available.
911   if (TLI.getOperationAction(ISD::SRA, VT) == TargetLowering::Expand ||
912       TLI.getOperationAction(ISD::SHL, VT) == TargetLowering::Expand)
913     return DAG.UnrollVectorOp(Op.getNode());
914 
915   SDLoc DL(Op);
916   EVT OrigTy = cast<VTSDNode>(Op->getOperand(1))->getVT();
917 
918   unsigned BW = VT.getScalarSizeInBits();
919   unsigned OrigBW = OrigTy.getScalarSizeInBits();
920   SDValue ShiftSz = DAG.getConstant(BW - OrigBW, DL, VT);
921 
922   Op = Op.getOperand(0);
923   Op =   DAG.getNode(ISD::SHL, DL, VT, Op, ShiftSz);
924   return DAG.getNode(ISD::SRA, DL, VT, Op, ShiftSz);
925 }
926 
927 // Generically expand a vector anyext in register to a shuffle of the relevant
928 // lanes into the appropriate locations, with other lanes left undef.
929 SDValue VectorLegalizer::ExpandANY_EXTEND_VECTOR_INREG(SDValue Op) {
930   SDLoc DL(Op);
931   EVT VT = Op.getValueType();
932   int NumElements = VT.getVectorNumElements();
933   SDValue Src = Op.getOperand(0);
934   EVT SrcVT = Src.getValueType();
935   int NumSrcElements = SrcVT.getVectorNumElements();
936 
937   // Build a base mask of undef shuffles.
938   SmallVector<int, 16> ShuffleMask;
939   ShuffleMask.resize(NumSrcElements, -1);
940 
941   // Place the extended lanes into the correct locations.
942   int ExtLaneScale = NumSrcElements / NumElements;
943   int EndianOffset = DAG.getDataLayout().isBigEndian() ? ExtLaneScale - 1 : 0;
944   for (int i = 0; i < NumElements; ++i)
945     ShuffleMask[i * ExtLaneScale + EndianOffset] = i;
946 
947   return DAG.getNode(
948       ISD::BITCAST, DL, VT,
949       DAG.getVectorShuffle(SrcVT, DL, Src, DAG.getUNDEF(SrcVT), ShuffleMask));
950 }
951 
952 SDValue VectorLegalizer::ExpandSIGN_EXTEND_VECTOR_INREG(SDValue Op) {
953   SDLoc DL(Op);
954   EVT VT = Op.getValueType();
955   SDValue Src = Op.getOperand(0);
956   EVT SrcVT = Src.getValueType();
957 
958   // First build an any-extend node which can be legalized above when we
959   // recurse through it.
960   Op = DAG.getNode(ISD::ANY_EXTEND_VECTOR_INREG, DL, VT, Src);
961 
962   // Now we need sign extend. Do this by shifting the elements. Even if these
963   // aren't legal operations, they have a better chance of being legalized
964   // without full scalarization than the sign extension does.
965   unsigned EltWidth = VT.getScalarSizeInBits();
966   unsigned SrcEltWidth = SrcVT.getScalarSizeInBits();
967   SDValue ShiftAmount = DAG.getConstant(EltWidth - SrcEltWidth, DL, VT);
968   return DAG.getNode(ISD::SRA, DL, VT,
969                      DAG.getNode(ISD::SHL, DL, VT, Op, ShiftAmount),
970                      ShiftAmount);
971 }
972 
973 // Generically expand a vector zext in register to a shuffle of the relevant
974 // lanes into the appropriate locations, a blend of zero into the high bits,
975 // and a bitcast to the wider element type.
976 SDValue VectorLegalizer::ExpandZERO_EXTEND_VECTOR_INREG(SDValue Op) {
977   SDLoc DL(Op);
978   EVT VT = Op.getValueType();
979   int NumElements = VT.getVectorNumElements();
980   SDValue Src = Op.getOperand(0);
981   EVT SrcVT = Src.getValueType();
982   int NumSrcElements = SrcVT.getVectorNumElements();
983 
984   // Build up a zero vector to blend into this one.
985   SDValue Zero = DAG.getConstant(0, DL, SrcVT);
986 
987   // Shuffle the incoming lanes into the correct position, and pull all other
988   // lanes from the zero vector.
989   SmallVector<int, 16> ShuffleMask;
990   ShuffleMask.reserve(NumSrcElements);
991   for (int i = 0; i < NumSrcElements; ++i)
992     ShuffleMask.push_back(i);
993 
994   int ExtLaneScale = NumSrcElements / NumElements;
995   int EndianOffset = DAG.getDataLayout().isBigEndian() ? ExtLaneScale - 1 : 0;
996   for (int i = 0; i < NumElements; ++i)
997     ShuffleMask[i * ExtLaneScale + EndianOffset] = NumSrcElements + i;
998 
999   return DAG.getNode(ISD::BITCAST, DL, VT,
1000                      DAG.getVectorShuffle(SrcVT, DL, Zero, Src, ShuffleMask));
1001 }
1002 
1003 static void createBSWAPShuffleMask(EVT VT, SmallVectorImpl<int> &ShuffleMask) {
1004   int ScalarSizeInBytes = VT.getScalarSizeInBits() / 8;
1005   for (int I = 0, E = VT.getVectorNumElements(); I != E; ++I)
1006     for (int J = ScalarSizeInBytes - 1; J >= 0; --J)
1007       ShuffleMask.push_back((I * ScalarSizeInBytes) + J);
1008 }
1009 
1010 SDValue VectorLegalizer::ExpandBSWAP(SDValue Op) {
1011   EVT VT = Op.getValueType();
1012 
1013   // Generate a byte wise shuffle mask for the BSWAP.
1014   SmallVector<int, 16> ShuffleMask;
1015   createBSWAPShuffleMask(VT, ShuffleMask);
1016   EVT ByteVT = EVT::getVectorVT(*DAG.getContext(), MVT::i8, ShuffleMask.size());
1017 
1018   // Only emit a shuffle if the mask is legal.
1019   if (!TLI.isShuffleMaskLegal(ShuffleMask, ByteVT))
1020     return DAG.UnrollVectorOp(Op.getNode());
1021 
1022   SDLoc DL(Op);
1023   Op = DAG.getNode(ISD::BITCAST, DL, ByteVT, Op.getOperand(0));
1024   Op = DAG.getVectorShuffle(ByteVT, DL, Op, DAG.getUNDEF(ByteVT), ShuffleMask);
1025   return DAG.getNode(ISD::BITCAST, DL, VT, Op);
1026 }
1027 
1028 SDValue VectorLegalizer::ExpandBITREVERSE(SDValue Op) {
1029   EVT VT = Op.getValueType();
1030 
1031   // If we have the scalar operation, it's probably cheaper to unroll it.
1032   if (TLI.isOperationLegalOrCustom(ISD::BITREVERSE, VT.getScalarType()))
1033     return DAG.UnrollVectorOp(Op.getNode());
1034 
1035   // If the vector element width is a whole number of bytes, test if its legal
1036   // to BSWAP shuffle the bytes and then perform the BITREVERSE on the byte
1037   // vector. This greatly reduces the number of bit shifts necessary.
1038   unsigned ScalarSizeInBits = VT.getScalarSizeInBits();
1039   if (ScalarSizeInBits > 8 && (ScalarSizeInBits % 8) == 0) {
1040     SmallVector<int, 16> BSWAPMask;
1041     createBSWAPShuffleMask(VT, BSWAPMask);
1042 
1043     EVT ByteVT = EVT::getVectorVT(*DAG.getContext(), MVT::i8, BSWAPMask.size());
1044     if (TLI.isShuffleMaskLegal(BSWAPMask, ByteVT) &&
1045         (TLI.isOperationLegalOrCustom(ISD::BITREVERSE, ByteVT) ||
1046          (TLI.isOperationLegalOrCustom(ISD::SHL, ByteVT) &&
1047           TLI.isOperationLegalOrCustom(ISD::SRL, ByteVT) &&
1048           TLI.isOperationLegalOrCustomOrPromote(ISD::AND, ByteVT) &&
1049           TLI.isOperationLegalOrCustomOrPromote(ISD::OR, ByteVT)))) {
1050       SDLoc DL(Op);
1051       Op = DAG.getNode(ISD::BITCAST, DL, ByteVT, Op.getOperand(0));
1052       Op = DAG.getVectorShuffle(ByteVT, DL, Op, DAG.getUNDEF(ByteVT),
1053                                 BSWAPMask);
1054       Op = DAG.getNode(ISD::BITREVERSE, DL, ByteVT, Op);
1055       return DAG.getNode(ISD::BITCAST, DL, VT, Op);
1056     }
1057   }
1058 
1059   // If we have the appropriate vector bit operations, it is better to use them
1060   // than unrolling and expanding each component.
1061   if (!TLI.isOperationLegalOrCustom(ISD::SHL, VT) ||
1062       !TLI.isOperationLegalOrCustom(ISD::SRL, VT) ||
1063       !TLI.isOperationLegalOrCustomOrPromote(ISD::AND, VT) ||
1064       !TLI.isOperationLegalOrCustomOrPromote(ISD::OR, VT))
1065     return DAG.UnrollVectorOp(Op.getNode());
1066 
1067   // Let LegalizeDAG handle this later.
1068   return Op;
1069 }
1070 
1071 SDValue VectorLegalizer::ExpandVSELECT(SDValue Op) {
1072   // Implement VSELECT in terms of XOR, AND, OR
1073   // on platforms which do not support blend natively.
1074   SDLoc DL(Op);
1075 
1076   SDValue Mask = Op.getOperand(0);
1077   SDValue Op1 = Op.getOperand(1);
1078   SDValue Op2 = Op.getOperand(2);
1079 
1080   EVT VT = Mask.getValueType();
1081 
1082   // If we can't even use the basic vector operations of
1083   // AND,OR,XOR, we will have to scalarize the op.
1084   // Notice that the operation may be 'promoted' which means that it is
1085   // 'bitcasted' to another type which is handled.
1086   // This operation also isn't safe with AND, OR, XOR when the boolean
1087   // type is 0/1 as we need an all ones vector constant to mask with.
1088   // FIXME: Sign extend 1 to all ones if thats legal on the target.
1089   if (TLI.getOperationAction(ISD::AND, VT) == TargetLowering::Expand ||
1090       TLI.getOperationAction(ISD::XOR, VT) == TargetLowering::Expand ||
1091       TLI.getOperationAction(ISD::OR, VT) == TargetLowering::Expand ||
1092       TLI.getBooleanContents(Op1.getValueType()) !=
1093           TargetLowering::ZeroOrNegativeOneBooleanContent)
1094     return DAG.UnrollVectorOp(Op.getNode());
1095 
1096   // If the mask and the type are different sizes, unroll the vector op. This
1097   // can occur when getSetCCResultType returns something that is different in
1098   // size from the operand types. For example, v4i8 = select v4i32, v4i8, v4i8.
1099   if (VT.getSizeInBits() != Op1.getValueSizeInBits())
1100     return DAG.UnrollVectorOp(Op.getNode());
1101 
1102   // Bitcast the operands to be the same type as the mask.
1103   // This is needed when we select between FP types because
1104   // the mask is a vector of integers.
1105   Op1 = DAG.getNode(ISD::BITCAST, DL, VT, Op1);
1106   Op2 = DAG.getNode(ISD::BITCAST, DL, VT, Op2);
1107 
1108   SDValue AllOnes = DAG.getConstant(
1109     APInt::getAllOnesValue(VT.getScalarSizeInBits()), DL, VT);
1110   SDValue NotMask = DAG.getNode(ISD::XOR, DL, VT, Mask, AllOnes);
1111 
1112   Op1 = DAG.getNode(ISD::AND, DL, VT, Op1, Mask);
1113   Op2 = DAG.getNode(ISD::AND, DL, VT, Op2, NotMask);
1114   SDValue Val = DAG.getNode(ISD::OR, DL, VT, Op1, Op2);
1115   return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Val);
1116 }
1117 
1118 SDValue VectorLegalizer::ExpandABS(SDValue Op) {
1119   // Attempt to expand using TargetLowering.
1120   SDValue Result;
1121   if (TLI.expandABS(Op.getNode(), Result, DAG))
1122     return Result;
1123 
1124   // Otherwise go ahead and unroll.
1125   return DAG.UnrollVectorOp(Op.getNode());
1126 }
1127 
1128 SDValue VectorLegalizer::ExpandFP_TO_UINT(SDValue Op) {
1129   // Attempt to expand using TargetLowering.
1130   SDValue Result;
1131   if (TLI.expandFP_TO_UINT(Op.getNode(), Result, DAG))
1132     return Result;
1133 
1134   // Otherwise go ahead and unroll.
1135   return DAG.UnrollVectorOp(Op.getNode());
1136 }
1137 
1138 SDValue VectorLegalizer::ExpandUINT_TO_FLOAT(SDValue Op) {
1139   EVT VT = Op.getOperand(0).getValueType();
1140   SDLoc DL(Op);
1141 
1142   // Attempt to expand using TargetLowering.
1143   SDValue Result;
1144   if (TLI.expandUINT_TO_FP(Op.getNode(), Result, DAG))
1145     return Result;
1146 
1147   // Make sure that the SINT_TO_FP and SRL instructions are available.
1148   if (TLI.getOperationAction(ISD::SINT_TO_FP, VT) == TargetLowering::Expand ||
1149       TLI.getOperationAction(ISD::SRL,        VT) == TargetLowering::Expand)
1150     return DAG.UnrollVectorOp(Op.getNode());
1151 
1152   unsigned BW = VT.getScalarSizeInBits();
1153   assert((BW == 64 || BW == 32) &&
1154          "Elements in vector-UINT_TO_FP must be 32 or 64 bits wide");
1155 
1156   SDValue HalfWord = DAG.getConstant(BW / 2, DL, VT);
1157 
1158   // Constants to clear the upper part of the word.
1159   // Notice that we can also use SHL+SHR, but using a constant is slightly
1160   // faster on x86.
1161   uint64_t HWMask = (BW == 64) ? 0x00000000FFFFFFFF : 0x0000FFFF;
1162   SDValue HalfWordMask = DAG.getConstant(HWMask, DL, VT);
1163 
1164   // Two to the power of half-word-size.
1165   SDValue TWOHW = DAG.getConstantFP(1ULL << (BW / 2), DL, Op.getValueType());
1166 
1167   // Clear upper part of LO, lower HI
1168   SDValue HI = DAG.getNode(ISD::SRL, DL, VT, Op.getOperand(0), HalfWord);
1169   SDValue LO = DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), HalfWordMask);
1170 
1171   // Convert hi and lo to floats
1172   // Convert the hi part back to the upper values
1173   // TODO: Can any fast-math-flags be set on these nodes?
1174   SDValue fHI = DAG.getNode(ISD::SINT_TO_FP, DL, Op.getValueType(), HI);
1175           fHI = DAG.getNode(ISD::FMUL, DL, Op.getValueType(), fHI, TWOHW);
1176   SDValue fLO = DAG.getNode(ISD::SINT_TO_FP, DL, Op.getValueType(), LO);
1177 
1178   // Add the two halves
1179   return DAG.getNode(ISD::FADD, DL, Op.getValueType(), fHI, fLO);
1180 }
1181 
1182 SDValue VectorLegalizer::ExpandFNEG(SDValue Op) {
1183   if (TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType())) {
1184     SDLoc DL(Op);
1185     SDValue Zero = DAG.getConstantFP(-0.0, DL, Op.getValueType());
1186     // TODO: If FNEG had fast-math-flags, they'd get propagated to this FSUB.
1187     return DAG.getNode(ISD::FSUB, DL, Op.getValueType(),
1188                        Zero, Op.getOperand(0));
1189   }
1190   return DAG.UnrollVectorOp(Op.getNode());
1191 }
1192 
1193 SDValue VectorLegalizer::ExpandFSUB(SDValue Op) {
1194   // For floating-point values, (a-b) is the same as a+(-b). If FNEG is legal,
1195   // we can defer this to operation legalization where it will be lowered as
1196   // a+(-b).
1197   EVT VT = Op.getValueType();
1198   if (TLI.isOperationLegalOrCustom(ISD::FNEG, VT) &&
1199       TLI.isOperationLegalOrCustom(ISD::FADD, VT))
1200     return Op; // Defer to LegalizeDAG
1201 
1202   return DAG.UnrollVectorOp(Op.getNode());
1203 }
1204 
1205 SDValue VectorLegalizer::ExpandCTPOP(SDValue Op) {
1206   SDValue Result;
1207   if (TLI.expandCTPOP(Op.getNode(), Result, DAG))
1208     return Result;
1209 
1210   return DAG.UnrollVectorOp(Op.getNode());
1211 }
1212 
1213 SDValue VectorLegalizer::ExpandCTLZ(SDValue Op) {
1214   SDValue Result;
1215   if (TLI.expandCTLZ(Op.getNode(), Result, DAG))
1216     return Result;
1217 
1218   return DAG.UnrollVectorOp(Op.getNode());
1219 }
1220 
1221 SDValue VectorLegalizer::ExpandCTTZ(SDValue Op) {
1222   SDValue Result;
1223   if (TLI.expandCTTZ(Op.getNode(), Result, DAG))
1224     return Result;
1225 
1226   return DAG.UnrollVectorOp(Op.getNode());
1227 }
1228 
1229 SDValue VectorLegalizer::ExpandFunnelShift(SDValue Op) {
1230   SDValue Result;
1231   if (TLI.expandFunnelShift(Op.getNode(), Result, DAG))
1232     return Result;
1233 
1234   return DAG.UnrollVectorOp(Op.getNode());
1235 }
1236 
1237 SDValue VectorLegalizer::ExpandROT(SDValue Op) {
1238   SDValue Result;
1239   if (TLI.expandROT(Op.getNode(), Result, DAG))
1240     return Result;
1241 
1242   return DAG.UnrollVectorOp(Op.getNode());
1243 }
1244 
1245 SDValue VectorLegalizer::ExpandFMINNUM_FMAXNUM(SDValue Op) {
1246   if (SDValue Expanded = TLI.expandFMINNUM_FMAXNUM(Op.getNode(), DAG))
1247     return Expanded;
1248   return DAG.UnrollVectorOp(Op.getNode());
1249 }
1250 
1251 SDValue VectorLegalizer::ExpandMULO(SDValue Op) {
1252   SDValue Result, Overflow;
1253   if (!TLI.expandMULO(Op.getNode(), Result, Overflow, DAG))
1254     std::tie(Result, Overflow) = DAG.UnrollVectorOverflowOp(Op.getNode());
1255 
1256   AddLegalizedOperand(Op.getValue(0), Result);
1257   AddLegalizedOperand(Op.getValue(1), Overflow);
1258   return Op.getResNo() ? Overflow : Result;
1259 }
1260 
1261 SDValue VectorLegalizer::ExpandAddSubSat(SDValue Op) {
1262   if (SDValue Expanded = TLI.expandAddSubSat(Op.getNode(), DAG))
1263     return Expanded;
1264   return DAG.UnrollVectorOp(Op.getNode());
1265 }
1266 
1267 SDValue VectorLegalizer::ExpandFixedPointMul(SDValue Op) {
1268   if (SDValue Expanded = TLI.expandFixedPointMul(Op.getNode(), DAG))
1269     return Expanded;
1270   return DAG.UnrollVectorOp(Op.getNode());
1271 }
1272 
1273 SDValue VectorLegalizer::ExpandStrictFPOp(SDValue Op) {
1274   EVT VT = Op.getValueType();
1275   EVT EltVT = VT.getVectorElementType();
1276   unsigned NumElems = VT.getVectorNumElements();
1277   unsigned NumOpers = Op.getNumOperands();
1278   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1279   EVT ValueVTs[] = {EltVT, MVT::Other};
1280   SDValue Chain = Op.getOperand(0);
1281   SDLoc dl(Op);
1282 
1283   SmallVector<SDValue, 32> OpValues;
1284   SmallVector<SDValue, 32> OpChains;
1285   for (unsigned i = 0; i < NumElems; ++i) {
1286     SmallVector<SDValue, 4> Opers;
1287     SDValue Idx = DAG.getConstant(i, dl,
1288                                   TLI.getVectorIdxTy(DAG.getDataLayout()));
1289 
1290     // The Chain is the first operand.
1291     Opers.push_back(Chain);
1292 
1293     // Now process the remaining operands.
1294     for (unsigned j = 1; j < NumOpers; ++j) {
1295       SDValue Oper = Op.getOperand(j);
1296       EVT OperVT = Oper.getValueType();
1297 
1298       if (OperVT.isVector())
1299         Oper = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
1300                            EltVT, Oper, Idx);
1301 
1302       Opers.push_back(Oper);
1303     }
1304 
1305     SDValue ScalarOp = DAG.getNode(Op->getOpcode(), dl, ValueVTs, Opers);
1306 
1307     OpValues.push_back(ScalarOp.getValue(0));
1308     OpChains.push_back(ScalarOp.getValue(1));
1309   }
1310 
1311   SDValue Result = DAG.getBuildVector(VT, dl, OpValues);
1312   SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OpChains);
1313 
1314   AddLegalizedOperand(Op.getValue(0), Result);
1315   AddLegalizedOperand(Op.getValue(1), NewChain);
1316 
1317   return Op.getResNo() ? NewChain : Result;
1318 }
1319 
1320 SDValue VectorLegalizer::UnrollVSETCC(SDValue Op) {
1321   EVT VT = Op.getValueType();
1322   unsigned NumElems = VT.getVectorNumElements();
1323   EVT EltVT = VT.getVectorElementType();
1324   SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1), CC = Op.getOperand(2);
1325   EVT TmpEltVT = LHS.getValueType().getVectorElementType();
1326   SDLoc dl(Op);
1327   SmallVector<SDValue, 8> Ops(NumElems);
1328   for (unsigned i = 0; i < NumElems; ++i) {
1329     SDValue LHSElem = DAG.getNode(
1330         ISD::EXTRACT_VECTOR_ELT, dl, TmpEltVT, LHS,
1331         DAG.getConstant(i, dl, TLI.getVectorIdxTy(DAG.getDataLayout())));
1332     SDValue RHSElem = DAG.getNode(
1333         ISD::EXTRACT_VECTOR_ELT, dl, TmpEltVT, RHS,
1334         DAG.getConstant(i, dl, TLI.getVectorIdxTy(DAG.getDataLayout())));
1335     Ops[i] = DAG.getNode(ISD::SETCC, dl,
1336                          TLI.getSetCCResultType(DAG.getDataLayout(),
1337                                                 *DAG.getContext(), TmpEltVT),
1338                          LHSElem, RHSElem, CC);
1339     Ops[i] = DAG.getSelect(dl, EltVT, Ops[i],
1340                            DAG.getConstant(APInt::getAllOnesValue
1341                                            (EltVT.getSizeInBits()), dl, EltVT),
1342                            DAG.getConstant(0, dl, EltVT));
1343   }
1344   return DAG.getBuildVector(VT, dl, Ops);
1345 }
1346 
1347 bool SelectionDAG::LegalizeVectors() {
1348   return VectorLegalizer(*this).Run();
1349 }
1350