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