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