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