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