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