Convert more SelectionDAG functions to use ArrayRef.
[oota-llvm.git] / lib / CodeGen / SelectionDAG / LegalizeVectorOps.cpp
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   /// LegalizedNodes - For nodes that are of legal width, and that have more
41   /// than one use, this map indicates what regularized operand to use.  This
42   /// allows us to avoid legalizing the same thing more than once.
43   SmallDenseMap<SDValue, SDValue, 64> LegalizedNodes;
44
45   // 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   // Legalizes the given node
54   SDValue LegalizeOp(SDValue Op);
55   // Assuming the node is legal, "legalize" the results
56   SDValue TranslateLegalizeResults(SDValue Op, SDValue Result);
57   // Implements unrolling a VSETCC.
58   SDValue UnrollVSETCC(SDValue Op);
59   // Implements expansion for FNEG; falls back to UnrollVectorOp if FSUB
60   // isn't legal.
61   // Implements expansion for UINT_TO_FLOAT; falls back to UnrollVectorOp if
62   // SINT_TO_FLOAT and SHR on vectors isn't legal.
63   SDValue ExpandUINT_TO_FLOAT(SDValue Op);
64   // Implement expansion for SIGN_EXTEND_INREG using SRL and SRA.
65   SDValue ExpandSEXTINREG(SDValue Op);
66   // Implement vselect in terms of XOR, AND, OR when blend is not supported
67   // by the target.
68   SDValue ExpandVSELECT(SDValue Op);
69   SDValue ExpandSELECT(SDValue Op);
70   SDValue ExpandLoad(SDValue Op);
71   SDValue ExpandStore(SDValue Op);
72   SDValue ExpandFNEG(SDValue Op);
73   // Implements vector promotion; this is essentially just bitcasting the
74   // operands to a different type and bitcasting the result back to the
75   // original type.
76   SDValue PromoteVectorOp(SDValue Op);
77   // Implements [SU]INT_TO_FP vector promotion; this is a [zs]ext of the input
78   // operand to the next size up.
79   SDValue PromoteVectorOpINT_TO_FP(SDValue Op);
80   // Implements FP_TO_[SU]INT vector promotion of the result type; it is
81   // promoted to the next size up integer type.  The result is then truncated
82   // back to the original type.
83   SDValue PromoteVectorOpFP_TO_INT(SDValue Op, bool isSigned);
84
85   public:
86   bool Run();
87   VectorLegalizer(SelectionDAG& dag) :
88       DAG(dag), TLI(dag.getTargetLoweringInfo()), Changed(false) {}
89 };
90
91 bool VectorLegalizer::Run() {
92   // Before we start legalizing vector nodes, check if there are any vectors.
93   bool HasVectors = false;
94   for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
95        E = std::prev(DAG.allnodes_end()); I != std::next(E); ++I) {
96     // Check if the values of the nodes contain vectors. We don't need to check
97     // the operands because we are going to check their values at some point.
98     for (SDNode::value_iterator J = I->value_begin(), E = I->value_end();
99          J != E; ++J)
100       HasVectors |= J->isVector();
101
102     // If we found a vector node we can start the legalization.
103     if (HasVectors)
104       break;
105   }
106
107   // If this basic block has no vectors then no need to legalize vectors.
108   if (!HasVectors)
109     return false;
110
111   // The legalize process is inherently a bottom-up recursive process (users
112   // legalize their uses before themselves).  Given infinite stack space, we
113   // could just start legalizing on the root and traverse the whole graph.  In
114   // practice however, this causes us to run out of stack space on large basic
115   // blocks.  To avoid this problem, compute an ordering of the nodes where each
116   // node is only legalized after all of its operands are legalized.
117   DAG.AssignTopologicalOrder();
118   for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
119        E = std::prev(DAG.allnodes_end()); I != std::next(E); ++I)
120     LegalizeOp(SDValue(I, 0));
121
122   // Finally, it's possible the root changed.  Get the new root.
123   SDValue OldRoot = DAG.getRoot();
124   assert(LegalizedNodes.count(OldRoot) && "Root didn't get legalized?");
125   DAG.setRoot(LegalizedNodes[OldRoot]);
126
127   LegalizedNodes.clear();
128
129   // Remove dead nodes now.
130   DAG.RemoveDeadNodes();
131
132   return Changed;
133 }
134
135 SDValue VectorLegalizer::TranslateLegalizeResults(SDValue Op, SDValue Result) {
136   // Generic legalization: just pass the operand through.
137   for (unsigned i = 0, e = Op.getNode()->getNumValues(); i != e; ++i)
138     AddLegalizedOperand(Op.getValue(i), Result.getValue(i));
139   return Result.getValue(Op.getResNo());
140 }
141
142 SDValue VectorLegalizer::LegalizeOp(SDValue Op) {
143   // Note that LegalizeOp may be reentered even from single-use nodes, which
144   // means that we always must cache transformed nodes.
145   DenseMap<SDValue, SDValue>::iterator I = LegalizedNodes.find(Op);
146   if (I != LegalizedNodes.end()) return I->second;
147
148   SDNode* Node = Op.getNode();
149
150   // Legalize the operands
151   SmallVector<SDValue, 8> Ops;
152   for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i)
153     Ops.push_back(LegalizeOp(Node->getOperand(i)));
154
155   SDValue Result = SDValue(DAG.UpdateNodeOperands(Op.getNode(), Ops), 0);
156
157   if (Op.getOpcode() == ISD::LOAD) {
158     LoadSDNode *LD = cast<LoadSDNode>(Op.getNode());
159     ISD::LoadExtType ExtType = LD->getExtensionType();
160     if (LD->getMemoryVT().isVector() && ExtType != ISD::NON_EXTLOAD) {
161       if (TLI.isLoadExtLegal(LD->getExtensionType(), LD->getMemoryVT()))
162         return TranslateLegalizeResults(Op, Result);
163       Changed = true;
164       return LegalizeOp(ExpandLoad(Op));
165     }
166   } else if (Op.getOpcode() == ISD::STORE) {
167     StoreSDNode *ST = cast<StoreSDNode>(Op.getNode());
168     EVT StVT = ST->getMemoryVT();
169     MVT ValVT = ST->getValue().getSimpleValueType();
170     if (StVT.isVector() && ST->isTruncatingStore())
171       switch (TLI.getTruncStoreAction(ValVT, StVT.getSimpleVT())) {
172       default: llvm_unreachable("This action is not supported yet!");
173       case TargetLowering::Legal:
174         return TranslateLegalizeResults(Op, Result);
175       case TargetLowering::Custom:
176         Changed = true;
177         return TranslateLegalizeResults(Op, TLI.LowerOperation(Result, DAG));
178       case TargetLowering::Expand:
179         Changed = true;
180         return LegalizeOp(ExpandStore(Op));
181       }
182   }
183
184   bool HasVectorValue = false;
185   for (SDNode::value_iterator J = Node->value_begin(), E = Node->value_end();
186        J != E;
187        ++J)
188     HasVectorValue |= J->isVector();
189   if (!HasVectorValue)
190     return TranslateLegalizeResults(Op, Result);
191
192   EVT QueryType;
193   switch (Op.getOpcode()) {
194   default:
195     return TranslateLegalizeResults(Op, Result);
196   case ISD::ADD:
197   case ISD::SUB:
198   case ISD::MUL:
199   case ISD::SDIV:
200   case ISD::UDIV:
201   case ISD::SREM:
202   case ISD::UREM:
203   case ISD::FADD:
204   case ISD::FSUB:
205   case ISD::FMUL:
206   case ISD::FDIV:
207   case ISD::FREM:
208   case ISD::AND:
209   case ISD::OR:
210   case ISD::XOR:
211   case ISD::SHL:
212   case ISD::SRA:
213   case ISD::SRL:
214   case ISD::ROTL:
215   case ISD::ROTR:
216   case ISD::BSWAP:
217   case ISD::CTLZ:
218   case ISD::CTTZ:
219   case ISD::CTLZ_ZERO_UNDEF:
220   case ISD::CTTZ_ZERO_UNDEF:
221   case ISD::CTPOP:
222   case ISD::SELECT:
223   case ISD::VSELECT:
224   case ISD::SELECT_CC:
225   case ISD::SETCC:
226   case ISD::ZERO_EXTEND:
227   case ISD::ANY_EXTEND:
228   case ISD::TRUNCATE:
229   case ISD::SIGN_EXTEND:
230   case ISD::FP_TO_SINT:
231   case ISD::FP_TO_UINT:
232   case ISD::FNEG:
233   case ISD::FABS:
234   case ISD::FCOPYSIGN:
235   case ISD::FSQRT:
236   case ISD::FSIN:
237   case ISD::FCOS:
238   case ISD::FPOWI:
239   case ISD::FPOW:
240   case ISD::FLOG:
241   case ISD::FLOG2:
242   case ISD::FLOG10:
243   case ISD::FEXP:
244   case ISD::FEXP2:
245   case ISD::FCEIL:
246   case ISD::FTRUNC:
247   case ISD::FRINT:
248   case ISD::FNEARBYINT:
249   case ISD::FROUND:
250   case ISD::FFLOOR:
251   case ISD::FP_ROUND:
252   case ISD::FP_EXTEND:
253   case ISD::FMA:
254   case ISD::SIGN_EXTEND_INREG:
255     QueryType = Node->getValueType(0);
256     break;
257   case ISD::FP_ROUND_INREG:
258     QueryType = cast<VTSDNode>(Node->getOperand(1))->getVT();
259     break;
260   case ISD::SINT_TO_FP:
261   case ISD::UINT_TO_FP:
262     QueryType = Node->getOperand(0).getValueType();
263     break;
264   }
265
266   switch (TLI.getOperationAction(Node->getOpcode(), QueryType)) {
267   case TargetLowering::Promote:
268     switch (Op.getOpcode()) {
269     default:
270       // "Promote" the operation by bitcasting
271       Result = PromoteVectorOp(Op);
272       Changed = true;
273       break;
274     case ISD::SINT_TO_FP:
275     case ISD::UINT_TO_FP:
276       // "Promote" the operation by extending the operand.
277       Result = PromoteVectorOpINT_TO_FP(Op);
278       Changed = true;
279       break;
280     case ISD::FP_TO_UINT:
281     case ISD::FP_TO_SINT:
282       // Promote the operation by extending the operand.
283       Result = PromoteVectorOpFP_TO_INT(Op, Op->getOpcode() == ISD::FP_TO_SINT);
284       Changed = true;
285       break;
286     }
287     break;
288   case TargetLowering::Legal: break;
289   case TargetLowering::Custom: {
290     SDValue Tmp1 = TLI.LowerOperation(Op, DAG);
291     if (Tmp1.getNode()) {
292       Result = Tmp1;
293       break;
294     }
295     // FALL THROUGH
296   }
297   case TargetLowering::Expand:
298     if (Node->getOpcode() == ISD::SIGN_EXTEND_INREG)
299       Result = ExpandSEXTINREG(Op);
300     else if (Node->getOpcode() == ISD::VSELECT)
301       Result = ExpandVSELECT(Op);
302     else if (Node->getOpcode() == ISD::SELECT)
303       Result = ExpandSELECT(Op);
304     else if (Node->getOpcode() == ISD::UINT_TO_FP)
305       Result = ExpandUINT_TO_FLOAT(Op);
306     else if (Node->getOpcode() == ISD::FNEG)
307       Result = ExpandFNEG(Op);
308     else if (Node->getOpcode() == ISD::SETCC)
309       Result = UnrollVSETCC(Op);
310     else
311       Result = DAG.UnrollVectorOp(Op.getNode());
312     break;
313   }
314
315   // Make sure that the generated code is itself legal.
316   if (Result != Op) {
317     Result = LegalizeOp(Result);
318     Changed = true;
319   }
320
321   // Note that LegalizeOp may be reentered even from single-use nodes, which
322   // means that we always must cache transformed nodes.
323   AddLegalizedOperand(Op, Result);
324   return Result;
325 }
326
327 SDValue VectorLegalizer::PromoteVectorOp(SDValue Op) {
328   // Vector "promotion" is basically just bitcasting and doing the operation
329   // in a different type.  For example, x86 promotes ISD::AND on v2i32 to
330   // v1i64.
331   MVT VT = Op.getSimpleValueType();
332   assert(Op.getNode()->getNumValues() == 1 &&
333          "Can't promote a vector with multiple results!");
334   MVT NVT = TLI.getTypeToPromoteTo(Op.getOpcode(), VT);
335   SDLoc dl(Op);
336   SmallVector<SDValue, 4> Operands(Op.getNumOperands());
337
338   for (unsigned j = 0; j != Op.getNumOperands(); ++j) {
339     if (Op.getOperand(j).getValueType().isVector())
340       Operands[j] = DAG.getNode(ISD::BITCAST, dl, NVT, Op.getOperand(j));
341     else
342       Operands[j] = Op.getOperand(j);
343   }
344
345   Op = DAG.getNode(Op.getOpcode(), dl, NVT, Operands);
346
347   return DAG.getNode(ISD::BITCAST, dl, VT, Op);
348 }
349
350 SDValue VectorLegalizer::PromoteVectorOpINT_TO_FP(SDValue Op) {
351   // INT_TO_FP operations may require the input operand be promoted even
352   // when the type is otherwise legal.
353   EVT VT = Op.getOperand(0).getValueType();
354   assert(Op.getNode()->getNumValues() == 1 &&
355          "Can't promote a vector with multiple results!");
356
357   // Normal getTypeToPromoteTo() doesn't work here, as that will promote
358   // by widening the vector w/ the same element width and twice the number
359   // of elements. We want the other way around, the same number of elements,
360   // each twice the width.
361   //
362   // Increase the bitwidth of the element to the next pow-of-two
363   // (which is greater than 8 bits).
364
365   EVT NVT = VT.widenIntegerVectorElementType(*DAG.getContext());
366   assert(NVT.isSimple() && "Promoting to a non-simple vector type!");
367   SDLoc dl(Op);
368   SmallVector<SDValue, 4> Operands(Op.getNumOperands());
369
370   unsigned Opc = Op.getOpcode() == ISD::UINT_TO_FP ? ISD::ZERO_EXTEND :
371     ISD::SIGN_EXTEND;
372   for (unsigned j = 0; j != Op.getNumOperands(); ++j) {
373     if (Op.getOperand(j).getValueType().isVector())
374       Operands[j] = DAG.getNode(Opc, dl, NVT, Op.getOperand(j));
375     else
376       Operands[j] = Op.getOperand(j);
377   }
378
379   return DAG.getNode(Op.getOpcode(), dl, Op.getValueType(), Operands);
380 }
381
382 // For FP_TO_INT we promote the result type to a vector type with wider
383 // elements and then truncate the result.  This is different from the default
384 // PromoteVector which uses bitcast to promote thus assumning that the
385 // promoted vector type has the same overall size.
386 SDValue VectorLegalizer::PromoteVectorOpFP_TO_INT(SDValue Op, bool isSigned) {
387   assert(Op.getNode()->getNumValues() == 1 &&
388          "Can't promote a vector with multiple results!");
389   EVT VT = Op.getValueType();
390
391   EVT NewVT;
392   unsigned NewOpc;
393   while (1) {
394     NewVT = VT.widenIntegerVectorElementType(*DAG.getContext());
395     assert(NewVT.isSimple() && "Promoting to a non-simple vector type!");
396     if (TLI.isOperationLegalOrCustom(ISD::FP_TO_SINT, NewVT)) {
397       NewOpc = ISD::FP_TO_SINT;
398       break;
399     }
400     if (!isSigned && TLI.isOperationLegalOrCustom(ISD::FP_TO_UINT, NewVT)) {
401       NewOpc = ISD::FP_TO_UINT;
402       break;
403     }
404   }
405
406   SDLoc loc(Op);
407   SDValue promoted  = DAG.getNode(NewOpc, SDLoc(Op), NewVT, Op.getOperand(0));
408   return DAG.getNode(ISD::TRUNCATE, SDLoc(Op), VT, promoted);
409 }
410
411
412 SDValue VectorLegalizer::ExpandLoad(SDValue Op) {
413   SDLoc dl(Op);
414   LoadSDNode *LD = cast<LoadSDNode>(Op.getNode());
415   SDValue Chain = LD->getChain();
416   SDValue BasePTR = LD->getBasePtr();
417   EVT SrcVT = LD->getMemoryVT();
418   ISD::LoadExtType ExtType = LD->getExtensionType();
419
420   SmallVector<SDValue, 8> Vals;
421   SmallVector<SDValue, 8> LoadChains;
422   unsigned NumElem = SrcVT.getVectorNumElements();
423
424   EVT SrcEltVT = SrcVT.getScalarType();
425   EVT DstEltVT = Op.getNode()->getValueType(0).getScalarType();
426
427   if (SrcVT.getVectorNumElements() > 1 && !SrcEltVT.isByteSized()) {
428     // When elements in a vector is not byte-addressable, we cannot directly
429     // load each element by advancing pointer, which could only address bytes.
430     // Instead, we load all significant words, mask bits off, and concatenate
431     // them to form each element. Finally, they are extended to destination
432     // scalar type to build the destination vector.
433     EVT WideVT = TLI.getPointerTy();
434
435     assert(WideVT.isRound() &&
436            "Could not handle the sophisticated case when the widest integer is"
437            " not power of 2.");
438     assert(WideVT.bitsGE(SrcEltVT) &&
439            "Type is not legalized?");
440
441     unsigned WideBytes = WideVT.getStoreSize();
442     unsigned Offset = 0;
443     unsigned RemainingBytes = SrcVT.getStoreSize();
444     SmallVector<SDValue, 8> LoadVals;
445
446     while (RemainingBytes > 0) {
447       SDValue ScalarLoad;
448       unsigned LoadBytes = WideBytes;
449
450       if (RemainingBytes >= LoadBytes) {
451         ScalarLoad = DAG.getLoad(WideVT, dl, Chain, BasePTR,
452                                  LD->getPointerInfo().getWithOffset(Offset),
453                                  LD->isVolatile(), LD->isNonTemporal(),
454                                  LD->isInvariant(), LD->getAlignment(),
455                                  LD->getTBAAInfo());
456       } else {
457         EVT LoadVT = WideVT;
458         while (RemainingBytes < LoadBytes) {
459           LoadBytes >>= 1; // Reduce the load size by half.
460           LoadVT = EVT::getIntegerVT(*DAG.getContext(), LoadBytes << 3);
461         }
462         ScalarLoad = DAG.getExtLoad(ISD::EXTLOAD, dl, WideVT, Chain, BasePTR,
463                                     LD->getPointerInfo().getWithOffset(Offset),
464                                     LoadVT, LD->isVolatile(),
465                                     LD->isNonTemporal(), LD->getAlignment(),
466                                     LD->getTBAAInfo());
467       }
468
469       RemainingBytes -= LoadBytes;
470       Offset += LoadBytes;
471       BasePTR = DAG.getNode(ISD::ADD, dl, BasePTR.getValueType(), BasePTR,
472                             DAG.getConstant(LoadBytes, BasePTR.getValueType()));
473
474       LoadVals.push_back(ScalarLoad.getValue(0));
475       LoadChains.push_back(ScalarLoad.getValue(1));
476     }
477
478     // Extract bits, pack and extend/trunc them into destination type.
479     unsigned SrcEltBits = SrcEltVT.getSizeInBits();
480     SDValue SrcEltBitMask = DAG.getConstant((1U << SrcEltBits) - 1, WideVT);
481
482     unsigned BitOffset = 0;
483     unsigned WideIdx = 0;
484     unsigned WideBits = WideVT.getSizeInBits();
485
486     for (unsigned Idx = 0; Idx != NumElem; ++Idx) {
487       SDValue Lo, Hi, ShAmt;
488
489       if (BitOffset < WideBits) {
490         ShAmt = DAG.getConstant(BitOffset, TLI.getShiftAmountTy(WideVT));
491         Lo = DAG.getNode(ISD::SRL, dl, WideVT, LoadVals[WideIdx], ShAmt);
492         Lo = DAG.getNode(ISD::AND, dl, WideVT, Lo, SrcEltBitMask);
493       }
494
495       BitOffset += SrcEltBits;
496       if (BitOffset >= WideBits) {
497         WideIdx++;
498         Offset -= WideBits;
499         if (Offset > 0) {
500           ShAmt = DAG.getConstant(SrcEltBits - Offset,
501                                   TLI.getShiftAmountTy(WideVT));
502           Hi = DAG.getNode(ISD::SHL, dl, WideVT, LoadVals[WideIdx], ShAmt);
503           Hi = DAG.getNode(ISD::AND, dl, WideVT, Hi, SrcEltBitMask);
504         }
505       }
506
507       if (Hi.getNode())
508         Lo = DAG.getNode(ISD::OR, dl, WideVT, Lo, Hi);
509
510       switch (ExtType) {
511       default: llvm_unreachable("Unknown extended-load op!");
512       case ISD::EXTLOAD:
513         Lo = DAG.getAnyExtOrTrunc(Lo, dl, DstEltVT);
514         break;
515       case ISD::ZEXTLOAD:
516         Lo = DAG.getZExtOrTrunc(Lo, dl, DstEltVT);
517         break;
518       case ISD::SEXTLOAD:
519         ShAmt = DAG.getConstant(WideBits - SrcEltBits,
520                                 TLI.getShiftAmountTy(WideVT));
521         Lo = DAG.getNode(ISD::SHL, dl, WideVT, Lo, ShAmt);
522         Lo = DAG.getNode(ISD::SRA, dl, WideVT, Lo, ShAmt);
523         Lo = DAG.getSExtOrTrunc(Lo, dl, DstEltVT);
524         break;
525       }
526       Vals.push_back(Lo);
527     }
528   } else {
529     unsigned Stride = SrcVT.getScalarType().getSizeInBits()/8;
530
531     for (unsigned Idx=0; Idx<NumElem; Idx++) {
532       SDValue ScalarLoad = DAG.getExtLoad(ExtType, dl,
533                 Op.getNode()->getValueType(0).getScalarType(),
534                 Chain, BasePTR, LD->getPointerInfo().getWithOffset(Idx * Stride),
535                 SrcVT.getScalarType(),
536                 LD->isVolatile(), LD->isNonTemporal(),
537                 LD->getAlignment(), LD->getTBAAInfo());
538
539       BasePTR = DAG.getNode(ISD::ADD, dl, BasePTR.getValueType(), BasePTR,
540                          DAG.getConstant(Stride, BasePTR.getValueType()));
541
542       Vals.push_back(ScalarLoad.getValue(0));
543       LoadChains.push_back(ScalarLoad.getValue(1));
544     }
545   }
546
547   SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
548   SDValue Value = DAG.getNode(ISD::BUILD_VECTOR, dl,
549                               Op.getNode()->getValueType(0), Vals);
550
551   AddLegalizedOperand(Op.getValue(0), Value);
552   AddLegalizedOperand(Op.getValue(1), NewChain);
553
554   return (Op.getResNo() ? NewChain : Value);
555 }
556
557 SDValue VectorLegalizer::ExpandStore(SDValue Op) {
558   SDLoc dl(Op);
559   StoreSDNode *ST = cast<StoreSDNode>(Op.getNode());
560   SDValue Chain = ST->getChain();
561   SDValue BasePTR = ST->getBasePtr();
562   SDValue Value = ST->getValue();
563   EVT StVT = ST->getMemoryVT();
564
565   unsigned Alignment = ST->getAlignment();
566   bool isVolatile = ST->isVolatile();
567   bool isNonTemporal = ST->isNonTemporal();
568   const MDNode *TBAAInfo = ST->getTBAAInfo();
569
570   unsigned NumElem = StVT.getVectorNumElements();
571   // The type of the data we want to save
572   EVT RegVT = Value.getValueType();
573   EVT RegSclVT = RegVT.getScalarType();
574   // The type of data as saved in memory.
575   EVT MemSclVT = StVT.getScalarType();
576
577   // Cast floats into integers
578   unsigned ScalarSize = MemSclVT.getSizeInBits();
579
580   // Round odd types to the next pow of two.
581   if (!isPowerOf2_32(ScalarSize))
582     ScalarSize = NextPowerOf2(ScalarSize);
583
584   // Store Stride in bytes
585   unsigned Stride = ScalarSize/8;
586   // Extract each of the elements from the original vector
587   // and save them into memory individually.
588   SmallVector<SDValue, 8> Stores;
589   for (unsigned Idx = 0; Idx < NumElem; Idx++) {
590     SDValue Ex = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
591                RegSclVT, Value, DAG.getConstant(Idx, TLI.getVectorIdxTy()));
592
593     // This scalar TruncStore may be illegal, but we legalize it later.
594     SDValue Store = DAG.getTruncStore(Chain, dl, Ex, BasePTR,
595                ST->getPointerInfo().getWithOffset(Idx*Stride), MemSclVT,
596                isVolatile, isNonTemporal, Alignment, TBAAInfo);
597
598     BasePTR = DAG.getNode(ISD::ADD, dl, BasePTR.getValueType(), BasePTR,
599                                DAG.getConstant(Stride, BasePTR.getValueType()));
600
601     Stores.push_back(Store);
602   }
603   SDValue TF =  DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
604   AddLegalizedOperand(Op, TF);
605   return TF;
606 }
607
608 SDValue VectorLegalizer::ExpandSELECT(SDValue Op) {
609   // Lower a select instruction where the condition is a scalar and the
610   // operands are vectors. Lower this select to VSELECT and implement it
611   // using XOR AND OR. The selector bit is broadcasted.
612   EVT VT = Op.getValueType();
613   SDLoc DL(Op);
614
615   SDValue Mask = Op.getOperand(0);
616   SDValue Op1 = Op.getOperand(1);
617   SDValue Op2 = Op.getOperand(2);
618
619   assert(VT.isVector() && !Mask.getValueType().isVector()
620          && Op1.getValueType() == Op2.getValueType() && "Invalid type");
621
622   unsigned NumElem = VT.getVectorNumElements();
623
624   // If we can't even use the basic vector operations of
625   // AND,OR,XOR, we will have to scalarize the op.
626   // Notice that the operation may be 'promoted' which means that it is
627   // 'bitcasted' to another type which is handled.
628   // Also, we need to be able to construct a splat vector using BUILD_VECTOR.
629   if (TLI.getOperationAction(ISD::AND, VT) == TargetLowering::Expand ||
630       TLI.getOperationAction(ISD::XOR, VT) == TargetLowering::Expand ||
631       TLI.getOperationAction(ISD::OR,  VT) == TargetLowering::Expand ||
632       TLI.getOperationAction(ISD::BUILD_VECTOR,  VT) == TargetLowering::Expand)
633     return DAG.UnrollVectorOp(Op.getNode());
634
635   // Generate a mask operand.
636   EVT MaskTy = VT.changeVectorElementTypeToInteger();
637
638   // What is the size of each element in the vector mask.
639   EVT BitTy = MaskTy.getScalarType();
640
641   Mask = DAG.getSelect(DL, BitTy, Mask,
642           DAG.getConstant(APInt::getAllOnesValue(BitTy.getSizeInBits()), BitTy),
643           DAG.getConstant(0, BitTy));
644
645   // Broadcast the mask so that the entire vector is all-one or all zero.
646   SmallVector<SDValue, 8> Ops(NumElem, Mask);
647   Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, MaskTy, Ops);
648
649   // Bitcast the operands to be the same type as the mask.
650   // This is needed when we select between FP types because
651   // the mask is a vector of integers.
652   Op1 = DAG.getNode(ISD::BITCAST, DL, MaskTy, Op1);
653   Op2 = DAG.getNode(ISD::BITCAST, DL, MaskTy, Op2);
654
655   SDValue AllOnes = DAG.getConstant(
656             APInt::getAllOnesValue(BitTy.getSizeInBits()), MaskTy);
657   SDValue NotMask = DAG.getNode(ISD::XOR, DL, MaskTy, Mask, AllOnes);
658
659   Op1 = DAG.getNode(ISD::AND, DL, MaskTy, Op1, Mask);
660   Op2 = DAG.getNode(ISD::AND, DL, MaskTy, Op2, NotMask);
661   SDValue Val = DAG.getNode(ISD::OR, DL, MaskTy, Op1, Op2);
662   return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Val);
663 }
664
665 SDValue VectorLegalizer::ExpandSEXTINREG(SDValue Op) {
666   EVT VT = Op.getValueType();
667
668   // Make sure that the SRA and SHL instructions are available.
669   if (TLI.getOperationAction(ISD::SRA, VT) == TargetLowering::Expand ||
670       TLI.getOperationAction(ISD::SHL, VT) == TargetLowering::Expand)
671     return DAG.UnrollVectorOp(Op.getNode());
672
673   SDLoc DL(Op);
674   EVT OrigTy = cast<VTSDNode>(Op->getOperand(1))->getVT();
675
676   unsigned BW = VT.getScalarType().getSizeInBits();
677   unsigned OrigBW = OrigTy.getScalarType().getSizeInBits();
678   SDValue ShiftSz = DAG.getConstant(BW - OrigBW, VT);
679
680   Op = Op.getOperand(0);
681   Op =   DAG.getNode(ISD::SHL, DL, VT, Op, ShiftSz);
682   return DAG.getNode(ISD::SRA, DL, VT, Op, ShiftSz);
683 }
684
685 SDValue VectorLegalizer::ExpandVSELECT(SDValue Op) {
686   // Implement VSELECT in terms of XOR, AND, OR
687   // on platforms which do not support blend natively.
688   SDLoc DL(Op);
689
690   SDValue Mask = Op.getOperand(0);
691   SDValue Op1 = Op.getOperand(1);
692   SDValue Op2 = Op.getOperand(2);
693
694   EVT VT = Mask.getValueType();
695
696   // If we can't even use the basic vector operations of
697   // AND,OR,XOR, we will have to scalarize the op.
698   // Notice that the operation may be 'promoted' which means that it is
699   // 'bitcasted' to another type which is handled.
700   // This operation also isn't safe with AND, OR, XOR when the boolean
701   // type is 0/1 as we need an all ones vector constant to mask with.
702   // FIXME: Sign extend 1 to all ones if thats legal on the target.
703   if (TLI.getOperationAction(ISD::AND, VT) == TargetLowering::Expand ||
704       TLI.getOperationAction(ISD::XOR, VT) == TargetLowering::Expand ||
705       TLI.getOperationAction(ISD::OR,  VT) == TargetLowering::Expand ||
706       TLI.getBooleanContents(true) !=
707       TargetLowering::ZeroOrNegativeOneBooleanContent)
708     return DAG.UnrollVectorOp(Op.getNode());
709
710   // If the mask and the type are different sizes, unroll the vector op. This
711   // can occur when getSetCCResultType returns something that is different in
712   // size from the operand types. For example, v4i8 = select v4i32, v4i8, v4i8.
713   if (VT.getSizeInBits() != Op1.getValueType().getSizeInBits())
714     return DAG.UnrollVectorOp(Op.getNode());
715
716   // Bitcast the operands to be the same type as the mask.
717   // This is needed when we select between FP types because
718   // the mask is a vector of integers.
719   Op1 = DAG.getNode(ISD::BITCAST, DL, VT, Op1);
720   Op2 = DAG.getNode(ISD::BITCAST, DL, VT, Op2);
721
722   SDValue AllOnes = DAG.getConstant(
723     APInt::getAllOnesValue(VT.getScalarType().getSizeInBits()), VT);
724   SDValue NotMask = DAG.getNode(ISD::XOR, DL, VT, Mask, AllOnes);
725
726   Op1 = DAG.getNode(ISD::AND, DL, VT, Op1, Mask);
727   Op2 = DAG.getNode(ISD::AND, DL, VT, Op2, NotMask);
728   SDValue Val = DAG.getNode(ISD::OR, DL, VT, Op1, Op2);
729   return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Val);
730 }
731
732 SDValue VectorLegalizer::ExpandUINT_TO_FLOAT(SDValue Op) {
733   EVT VT = Op.getOperand(0).getValueType();
734   SDLoc DL(Op);
735
736   // Make sure that the SINT_TO_FP and SRL instructions are available.
737   if (TLI.getOperationAction(ISD::SINT_TO_FP, VT) == TargetLowering::Expand ||
738       TLI.getOperationAction(ISD::SRL,        VT) == TargetLowering::Expand)
739     return DAG.UnrollVectorOp(Op.getNode());
740
741  EVT SVT = VT.getScalarType();
742   assert((SVT.getSizeInBits() == 64 || SVT.getSizeInBits() == 32) &&
743       "Elements in vector-UINT_TO_FP must be 32 or 64 bits wide");
744
745   unsigned BW = SVT.getSizeInBits();
746   SDValue HalfWord = DAG.getConstant(BW/2, VT);
747
748   // Constants to clear the upper part of the word.
749   // Notice that we can also use SHL+SHR, but using a constant is slightly
750   // faster on x86.
751   uint64_t HWMask = (SVT.getSizeInBits()==64)?0x00000000FFFFFFFF:0x0000FFFF;
752   SDValue HalfWordMask = DAG.getConstant(HWMask, VT);
753
754   // Two to the power of half-word-size.
755   SDValue TWOHW = DAG.getConstantFP((1<<(BW/2)), Op.getValueType());
756
757   // Clear upper part of LO, lower HI
758   SDValue HI = DAG.getNode(ISD::SRL, DL, VT, Op.getOperand(0), HalfWord);
759   SDValue LO = DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), HalfWordMask);
760
761   // Convert hi and lo to floats
762   // Convert the hi part back to the upper values
763   SDValue fHI = DAG.getNode(ISD::SINT_TO_FP, DL, Op.getValueType(), HI);
764           fHI = DAG.getNode(ISD::FMUL, DL, Op.getValueType(), fHI, TWOHW);
765   SDValue fLO = DAG.getNode(ISD::SINT_TO_FP, DL, Op.getValueType(), LO);
766
767   // Add the two halves
768   return DAG.getNode(ISD::FADD, DL, Op.getValueType(), fHI, fLO);
769 }
770
771
772 SDValue VectorLegalizer::ExpandFNEG(SDValue Op) {
773   if (TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType())) {
774     SDValue Zero = DAG.getConstantFP(-0.0, Op.getValueType());
775     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
776                        Zero, Op.getOperand(0));
777   }
778   return DAG.UnrollVectorOp(Op.getNode());
779 }
780
781 SDValue VectorLegalizer::UnrollVSETCC(SDValue Op) {
782   EVT VT = Op.getValueType();
783   unsigned NumElems = VT.getVectorNumElements();
784   EVT EltVT = VT.getVectorElementType();
785   SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1), CC = Op.getOperand(2);
786   EVT TmpEltVT = LHS.getValueType().getVectorElementType();
787   SDLoc dl(Op);
788   SmallVector<SDValue, 8> Ops(NumElems);
789   for (unsigned i = 0; i < NumElems; ++i) {
790     SDValue LHSElem = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, TmpEltVT, LHS,
791                                   DAG.getConstant(i, TLI.getVectorIdxTy()));
792     SDValue RHSElem = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, TmpEltVT, RHS,
793                                   DAG.getConstant(i, TLI.getVectorIdxTy()));
794     Ops[i] = DAG.getNode(ISD::SETCC, dl,
795                          TLI.getSetCCResultType(*DAG.getContext(), TmpEltVT),
796                          LHSElem, RHSElem, CC);
797     Ops[i] = DAG.getSelect(dl, EltVT, Ops[i],
798                            DAG.getConstant(APInt::getAllOnesValue
799                                            (EltVT.getSizeInBits()), EltVT),
800                            DAG.getConstant(0, EltVT));
801   }
802   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
803 }
804
805 }
806
807 bool SelectionDAG::LegalizeVectors() {
808   return VectorLegalizer(*this).Run();
809 }