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