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