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