Added support for the following definition of shufflevector
[oota-llvm.git] / lib / CodeGen / SelectionDAG / LegalizeVectorTypes.cpp
1 //===------- LegalizeVectorTypes.cpp - Legalization of vector types -------===//
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 performs vector type splitting and scalarization for LegalizeTypes.
11 // Scalarization is the act of changing a computation in an illegal one-element
12 // vector type to be a computation in its scalar element type.  For example,
13 // implementing <1 x f32> arithmetic in a scalar f32 register.  This is needed
14 // as a base case when scalarizing vector arithmetic like <4 x f32>, which
15 // eventually decomposes to scalars if the target doesn't support v4f32 or v2f32
16 // types.
17 // Splitting is the act of changing a computation in an invalid vector type to
18 // be a computation in multiple vectors of a smaller type.  For example,
19 // implementing <128 x f32> operations in terms of two <64 x f32> operations.
20 //
21 //===----------------------------------------------------------------------===//
22
23 #include "LegalizeTypes.h"
24 using namespace llvm;
25
26 //===----------------------------------------------------------------------===//
27 //  Result Vector Scalarization: <1 x ty> -> ty.
28 //===----------------------------------------------------------------------===//
29
30 void DAGTypeLegalizer::ScalarizeVectorResult(SDNode *N, unsigned ResNo) {
31   DEBUG(cerr << "Scalarize node result " << ResNo << ": "; N->dump(&DAG);
32         cerr << "\n");
33   SDValue R = SDValue();
34
35   switch (N->getOpcode()) {
36   default:
37 #ifndef NDEBUG
38     cerr << "ScalarizeVectorResult #" << ResNo << ": ";
39     N->dump(&DAG); cerr << "\n";
40 #endif
41     assert(0 && "Do not know how to scalarize the result of this operator!");
42     abort();
43
44   case ISD::BIT_CONVERT:    R = ScalarizeVecRes_BIT_CONVERT(N); break;
45   case ISD::BUILD_VECTOR:   R = N->getOperand(0); break;
46   case ISD::EXTRACT_SUBVECTOR: R = ScalarizeVecRes_EXTRACT_SUBVECTOR(N); break;
47   case ISD::FPOWI:          R = ScalarizeVecRes_FPOWI(N); break;
48   case ISD::INSERT_VECTOR_ELT: R = ScalarizeVecRes_INSERT_VECTOR_ELT(N); break;
49   case ISD::LOAD:           R = ScalarizeVecRes_LOAD(cast<LoadSDNode>(N));break;
50   case ISD::SELECT:         R = ScalarizeVecRes_SELECT(N); break;
51   case ISD::SELECT_CC:      R = ScalarizeVecRes_SELECT_CC(N); break;
52   case ISD::UNDEF:          R = ScalarizeVecRes_UNDEF(N); break;
53   case ISD::VECTOR_SHUFFLE: R = ScalarizeVecRes_VECTOR_SHUFFLE(N); break;
54   case ISD::VSETCC:         R = ScalarizeVecRes_VSETCC(N); break;
55
56   case ISD::CTLZ:
57   case ISD::CTPOP:
58   case ISD::CTTZ:
59   case ISD::FABS:
60   case ISD::FCOS:
61   case ISD::FNEG:
62   case ISD::FP_TO_SINT:
63   case ISD::FP_TO_UINT:
64   case ISD::FSIN:
65   case ISD::FSQRT:
66   case ISD::FTRUNC:
67   case ISD::FFLOOR:
68   case ISD::FCEIL:
69   case ISD::FRINT:
70   case ISD::FNEARBYINT:
71   case ISD::SINT_TO_FP:
72   case ISD::TRUNCATE:
73   case ISD::UINT_TO_FP: R = ScalarizeVecRes_UnaryOp(N); break;
74
75   case ISD::ADD:
76   case ISD::AND:
77   case ISD::FADD:
78   case ISD::FDIV:
79   case ISD::FMUL:
80   case ISD::FPOW:
81   case ISD::FREM:
82   case ISD::FSUB:
83   case ISD::MUL:
84   case ISD::OR:
85   case ISD::SDIV:
86   case ISD::SREM:
87   case ISD::SUB:
88   case ISD::UDIV:
89   case ISD::UREM:
90   case ISD::XOR:  R = ScalarizeVecRes_BinOp(N); break;
91   }
92
93   // If R is null, the sub-method took care of registering the result.
94   if (R.getNode())
95     SetScalarizedVector(SDValue(N, ResNo), R);
96 }
97
98 SDValue DAGTypeLegalizer::ScalarizeVecRes_BinOp(SDNode *N) {
99   SDValue LHS = GetScalarizedVector(N->getOperand(0));
100   SDValue RHS = GetScalarizedVector(N->getOperand(1));
101   return DAG.getNode(N->getOpcode(), LHS.getValueType(), LHS, RHS);
102 }
103
104 SDValue DAGTypeLegalizer::ScalarizeVecRes_BIT_CONVERT(SDNode *N) {
105   MVT NewVT = N->getValueType(0).getVectorElementType();
106   return DAG.getNode(ISD::BIT_CONVERT, NewVT, N->getOperand(0));
107 }
108
109 SDValue DAGTypeLegalizer::ScalarizeVecRes_EXTRACT_SUBVECTOR(SDNode *N) {
110   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
111                      N->getValueType(0).getVectorElementType(),
112                      N->getOperand(0), N->getOperand(1));
113 }
114
115 SDValue DAGTypeLegalizer::ScalarizeVecRes_FPOWI(SDNode *N) {
116   SDValue Op = GetScalarizedVector(N->getOperand(0));
117   return DAG.getNode(ISD::FPOWI, Op.getValueType(), Op, N->getOperand(1));
118 }
119
120 SDValue DAGTypeLegalizer::ScalarizeVecRes_INSERT_VECTOR_ELT(SDNode *N) {
121   // The value to insert may have a wider type than the vector element type,
122   // so be sure to truncate it to the element type if necessary.
123   SDValue Op = N->getOperand(1);
124   MVT EltVT = N->getValueType(0).getVectorElementType();
125   if (Op.getValueType() != EltVT)
126     // FIXME: Can this happen for floating point types?
127     Op = DAG.getNode(ISD::TRUNCATE, EltVT, Op);
128   return Op;
129 }
130
131 SDValue DAGTypeLegalizer::ScalarizeVecRes_LOAD(LoadSDNode *N) {
132   assert(N->isUnindexed() && "Indexed vector load?");
133
134   SDValue Result = DAG.getLoad(ISD::UNINDEXED, N->getExtensionType(),
135                                N->getValueType(0).getVectorElementType(),
136                                N->getChain(), N->getBasePtr(),
137                                DAG.getNode(ISD::UNDEF,
138                                            N->getBasePtr().getValueType()),
139                                N->getSrcValue(), N->getSrcValueOffset(),
140                                N->getMemoryVT().getVectorElementType(),
141                                N->isVolatile(), N->getAlignment());
142
143   // Legalized the chain result - switch anything that used the old chain to
144   // use the new one.
145   ReplaceValueWith(SDValue(N, 1), Result.getValue(1));
146   return Result;
147 }
148
149 SDValue DAGTypeLegalizer::ScalarizeVecRes_UnaryOp(SDNode *N) {
150   // Get the dest type - it doesn't always match the input type, e.g. int_to_fp.
151   MVT DestVT = N->getValueType(0).getVectorElementType();
152   SDValue Op = GetScalarizedVector(N->getOperand(0));
153   return DAG.getNode(N->getOpcode(), DestVT, Op);
154 }
155
156 SDValue DAGTypeLegalizer::ScalarizeVecRes_UNDEF(SDNode *N) {
157   return DAG.getNode(ISD::UNDEF, N->getValueType(0).getVectorElementType());
158 }
159
160 SDValue DAGTypeLegalizer::ScalarizeVecRes_SELECT(SDNode *N) {
161   SDValue LHS = GetScalarizedVector(N->getOperand(1));
162   return DAG.getNode(ISD::SELECT, LHS.getValueType(), N->getOperand(0), LHS,
163                      GetScalarizedVector(N->getOperand(2)));
164 }
165
166 SDValue DAGTypeLegalizer::ScalarizeVecRes_SELECT_CC(SDNode *N) {
167   SDValue LHS = GetScalarizedVector(N->getOperand(2));
168   return DAG.getNode(ISD::SELECT_CC, LHS.getValueType(),
169                      N->getOperand(0), N->getOperand(1),
170                      LHS, GetScalarizedVector(N->getOperand(3)),
171                      N->getOperand(4));
172 }
173
174 SDValue DAGTypeLegalizer::ScalarizeVecRes_VECTOR_SHUFFLE(SDNode *N) {
175   // Figure out if the scalar is the LHS or RHS and return it.
176   SDValue Arg = N->getOperand(2).getOperand(0);
177   if (Arg.getOpcode() == ISD::UNDEF)
178     return DAG.getNode(ISD::UNDEF, N->getValueType(0).getVectorElementType());
179   unsigned Op = !cast<ConstantSDNode>(Arg)->isNullValue();
180   return GetScalarizedVector(N->getOperand(Op));
181 }
182
183 SDValue DAGTypeLegalizer::ScalarizeVecRes_VSETCC(SDNode *N) {
184   SDValue LHS = GetScalarizedVector(N->getOperand(0));
185   SDValue RHS = GetScalarizedVector(N->getOperand(1));
186   MVT NVT = N->getValueType(0).getVectorElementType();
187   MVT SVT = TLI.getSetCCResultType(LHS);
188
189   // Turn it into a scalar SETCC.
190   SDValue Res = DAG.getNode(ISD::SETCC, SVT, LHS, RHS, N->getOperand(2));
191
192   // VSETCC always returns a sign-extended value, while SETCC may not.  The
193   // SETCC result type may not match the vector element type.  Correct these.
194   if (NVT.getSizeInBits() <= SVT.getSizeInBits()) {
195     // The SETCC result type is bigger than the vector element type.
196     // Ensure the SETCC result is sign-extended.
197     if (TLI.getSetCCResultContents() !=
198         TargetLowering::ZeroOrNegativeOneSetCCResult)
199       Res = DAG.getNode(ISD::SIGN_EXTEND_INREG, SVT, Res,
200                         DAG.getValueType(MVT::i1));
201     // Truncate to the final type.
202     return DAG.getNode(ISD::TRUNCATE, NVT, Res);
203   } else {
204     // The SETCC result type is smaller than the vector element type.
205     // If the SetCC result is not sign-extended, chop it down to MVT::i1.
206     if (TLI.getSetCCResultContents() !=
207         TargetLowering::ZeroOrNegativeOneSetCCResult)
208       Res = DAG.getNode(ISD::TRUNCATE, MVT::i1, Res);
209     // Sign extend to the final type.
210     return DAG.getNode(ISD::SIGN_EXTEND, NVT, Res);
211   }
212 }
213
214
215 //===----------------------------------------------------------------------===//
216 //  Operand Vector Scalarization <1 x ty> -> ty.
217 //===----------------------------------------------------------------------===//
218
219 bool DAGTypeLegalizer::ScalarizeVectorOperand(SDNode *N, unsigned OpNo) {
220   DEBUG(cerr << "Scalarize node operand " << OpNo << ": "; N->dump(&DAG);
221         cerr << "\n");
222   SDValue Res = SDValue();
223
224   if (Res.getNode() == 0) {
225     switch (N->getOpcode()) {
226     default:
227 #ifndef NDEBUG
228       cerr << "ScalarizeVectorOperand Op #" << OpNo << ": ";
229       N->dump(&DAG); cerr << "\n";
230 #endif
231       assert(0 && "Do not know how to scalarize this operator's operand!");
232       abort();
233
234     case ISD::BIT_CONVERT:
235       Res = ScalarizeVecOp_BIT_CONVERT(N); break;
236
237     case ISD::CONCAT_VECTORS:
238       Res = ScalarizeVecOp_CONCAT_VECTORS(N); break;
239
240     case ISD::EXTRACT_VECTOR_ELT:
241       Res = ScalarizeVecOp_EXTRACT_VECTOR_ELT(N); break;
242
243     case ISD::STORE:
244       Res = ScalarizeVecOp_STORE(cast<StoreSDNode>(N), OpNo); break;
245     }
246   }
247
248   // If the result is null, the sub-method took care of registering results etc.
249   if (!Res.getNode()) return false;
250
251   // If the result is N, the sub-method updated N in place.  Check to see if any
252   // operands are new, and if so, mark them.
253   if (Res.getNode() == N) {
254     // Mark N as new and remark N and its operands.  This allows us to correctly
255     // revisit N if it needs another step of promotion and allows us to visit
256     // any new operands to N.
257     ReanalyzeNode(N);
258     return true;
259   }
260
261   assert(Res.getValueType() == N->getValueType(0) && N->getNumValues() == 1 &&
262          "Invalid operand expansion");
263
264   ReplaceValueWith(SDValue(N, 0), Res);
265   return false;
266 }
267
268 /// ScalarizeVecOp_BIT_CONVERT - If the value to convert is a vector that needs
269 /// to be scalarized, it must be <1 x ty>.  Convert the element instead.
270 SDValue DAGTypeLegalizer::ScalarizeVecOp_BIT_CONVERT(SDNode *N) {
271   SDValue Elt = GetScalarizedVector(N->getOperand(0));
272   return DAG.getNode(ISD::BIT_CONVERT, N->getValueType(0), Elt);
273 }
274
275 /// ScalarizeVecOp_CONCAT_VECTORS - The vectors to concatenate have length one -
276 /// use a BUILD_VECTOR instead.
277 SDValue DAGTypeLegalizer::ScalarizeVecOp_CONCAT_VECTORS(SDNode *N) {
278   SmallVector<SDValue, 8> Ops(N->getNumOperands());
279   for (unsigned i = 0, e = N->getNumOperands(); i < e; ++i)
280     Ops[i] = GetScalarizedVector(N->getOperand(i));
281   return DAG.getNode(ISD::BUILD_VECTOR, N->getValueType(0),
282                      &Ops[0], Ops.size());
283 }
284
285 /// ScalarizeVecOp_EXTRACT_VECTOR_ELT - If the input is a vector that needs to
286 /// be scalarized, it must be <1 x ty>, so just return the element, ignoring the
287 /// index.
288 SDValue DAGTypeLegalizer::ScalarizeVecOp_EXTRACT_VECTOR_ELT(SDNode *N) {
289   return GetScalarizedVector(N->getOperand(0));
290 }
291
292 /// ScalarizeVecOp_STORE - If the value to store is a vector that needs to be
293 /// scalarized, it must be <1 x ty>.  Just store the element.
294 SDValue DAGTypeLegalizer::ScalarizeVecOp_STORE(StoreSDNode *N, unsigned OpNo){
295   assert(N->isUnindexed() && "Indexed store of one-element vector?");
296   assert(OpNo == 1 && "Do not know how to scalarize this operand!");
297
298   if (N->isTruncatingStore())
299     return DAG.getTruncStore(N->getChain(),
300                              GetScalarizedVector(N->getOperand(1)),
301                              N->getBasePtr(),
302                              N->getSrcValue(), N->getSrcValueOffset(),
303                              N->getMemoryVT().getVectorElementType(),
304                              N->isVolatile(), N->getAlignment());
305
306   return DAG.getStore(N->getChain(), GetScalarizedVector(N->getOperand(1)),
307                       N->getBasePtr(), N->getSrcValue(), N->getSrcValueOffset(),
308                       N->isVolatile(), N->getAlignment());
309 }
310
311
312 //===----------------------------------------------------------------------===//
313 //  Result Vector Splitting
314 //===----------------------------------------------------------------------===//
315
316 /// SplitVectorResult - This method is called when the specified result of the
317 /// specified node is found to need vector splitting.  At this point, the node
318 /// may also have invalid operands or may have other results that need
319 /// legalization, we just know that (at least) one result needs vector
320 /// splitting.
321 void DAGTypeLegalizer::SplitVectorResult(SDNode *N, unsigned ResNo) {
322   DEBUG(cerr << "Split node result: "; N->dump(&DAG); cerr << "\n");
323   SDValue Lo, Hi;
324
325   switch (N->getOpcode()) {
326   default:
327 #ifndef NDEBUG
328     cerr << "SplitVectorResult #" << ResNo << ": ";
329     N->dump(&DAG); cerr << "\n";
330 #endif
331     assert(0 && "Do not know how to split the result of this operator!");
332     abort();
333
334   case ISD::MERGE_VALUES: SplitRes_MERGE_VALUES(N, Lo, Hi); break;
335   case ISD::SELECT:       SplitRes_SELECT(N, Lo, Hi); break;
336   case ISD::SELECT_CC:    SplitRes_SELECT_CC(N, Lo, Hi); break;
337   case ISD::UNDEF:        SplitRes_UNDEF(N, Lo, Hi); break;
338
339   case ISD::BIT_CONVERT:       SplitVecRes_BIT_CONVERT(N, Lo, Hi); break;
340   case ISD::BUILD_VECTOR:      SplitVecRes_BUILD_VECTOR(N, Lo, Hi); break;
341   case ISD::CONCAT_VECTORS:    SplitVecRes_CONCAT_VECTORS(N, Lo, Hi); break;
342   case ISD::EXTRACT_SUBVECTOR: SplitVecRes_EXTRACT_SUBVECTOR(N, Lo, Hi); break;
343   case ISD::FPOWI:             SplitVecRes_FPOWI(N, Lo, Hi); break;
344   case ISD::INSERT_VECTOR_ELT: SplitVecRes_INSERT_VECTOR_ELT(N, Lo, Hi); break;
345   case ISD::LOAD:           SplitVecRes_LOAD(cast<LoadSDNode>(N), Lo, Hi);break;
346   case ISD::VECTOR_SHUFFLE: SplitVecRes_VECTOR_SHUFFLE(N, Lo, Hi); break;
347   case ISD::VSETCC:         SplitVecRes_VSETCC(N, Lo, Hi); break;
348
349   case ISD::CTTZ:
350   case ISD::CTLZ:
351   case ISD::CTPOP:
352   case ISD::FNEG:
353   case ISD::FABS:
354   case ISD::FSQRT:
355   case ISD::FSIN:
356   case ISD::FCOS:
357   case ISD::FTRUNC:
358   case ISD::FFLOOR:
359   case ISD::FCEIL:
360   case ISD::FRINT:
361   case ISD::FNEARBYINT:
362   case ISD::FP_TO_SINT:
363   case ISD::FP_TO_UINT:
364   case ISD::SINT_TO_FP:
365   case ISD::TRUNCATE:
366   case ISD::UINT_TO_FP: SplitVecRes_UnaryOp(N, Lo, Hi); break;
367
368   case ISD::ADD:
369   case ISD::SUB:
370   case ISD::MUL:
371   case ISD::FADD:
372   case ISD::FSUB:
373   case ISD::FMUL:
374   case ISD::SDIV:
375   case ISD::UDIV:
376   case ISD::FDIV:
377   case ISD::FPOW:
378   case ISD::AND:
379   case ISD::OR:
380   case ISD::XOR:
381   case ISD::UREM:
382   case ISD::SREM:
383   case ISD::FREM: SplitVecRes_BinOp(N, Lo, Hi); break;
384   }
385
386   // If Lo/Hi is null, the sub-method took care of registering results etc.
387   if (Lo.getNode())
388     SetSplitVector(SDValue(N, ResNo), Lo, Hi);
389 }
390
391 void DAGTypeLegalizer::SplitVecRes_BinOp(SDNode *N, SDValue &Lo,
392                                          SDValue &Hi) {
393   SDValue LHSLo, LHSHi;
394   GetSplitVector(N->getOperand(0), LHSLo, LHSHi);
395   SDValue RHSLo, RHSHi;
396   GetSplitVector(N->getOperand(1), RHSLo, RHSHi);
397
398   Lo = DAG.getNode(N->getOpcode(), LHSLo.getValueType(), LHSLo, RHSLo);
399   Hi = DAG.getNode(N->getOpcode(), LHSHi.getValueType(), LHSHi, RHSHi);
400 }
401
402 void DAGTypeLegalizer::SplitVecRes_BIT_CONVERT(SDNode *N, SDValue &Lo,
403                                                SDValue &Hi) {
404   // We know the result is a vector.  The input may be either a vector or a
405   // scalar value.
406   MVT LoVT, HiVT;
407   GetSplitDestVTs(N->getValueType(0), LoVT, HiVT);
408
409   SDValue InOp = N->getOperand(0);
410   MVT InVT = InOp.getValueType();
411
412   // Handle some special cases efficiently.
413   switch (getTypeAction(InVT)) {
414   default:
415     assert(false && "Unknown type action!");
416   case Legal:
417   case PromoteInteger:
418   case SoftenFloat:
419   case ScalarizeVector:
420     break;
421   case ExpandInteger:
422   case ExpandFloat:
423     // A scalar to vector conversion, where the scalar needs expansion.
424     // If the vector is being split in two then we can just convert the
425     // expanded pieces.
426     if (LoVT == HiVT) {
427       GetExpandedOp(InOp, Lo, Hi);
428       if (TLI.isBigEndian())
429         std::swap(Lo, Hi);
430       Lo = DAG.getNode(ISD::BIT_CONVERT, LoVT, Lo);
431       Hi = DAG.getNode(ISD::BIT_CONVERT, HiVT, Hi);
432       return;
433     }
434     break;
435   case SplitVector:
436     // If the input is a vector that needs to be split, convert each split
437     // piece of the input now.
438     GetSplitVector(InOp, Lo, Hi);
439     Lo = DAG.getNode(ISD::BIT_CONVERT, LoVT, Lo);
440     Hi = DAG.getNode(ISD::BIT_CONVERT, HiVT, Hi);
441     return;
442   }
443
444   // In the general case, convert the input to an integer and split it by hand.
445   MVT LoIntVT = MVT::getIntegerVT(LoVT.getSizeInBits());
446   MVT HiIntVT = MVT::getIntegerVT(HiVT.getSizeInBits());
447   if (TLI.isBigEndian())
448     std::swap(LoIntVT, HiIntVT);
449
450   SplitInteger(BitConvertToInteger(InOp), LoIntVT, HiIntVT, Lo, Hi);
451
452   if (TLI.isBigEndian())
453     std::swap(Lo, Hi);
454   Lo = DAG.getNode(ISD::BIT_CONVERT, LoVT, Lo);
455   Hi = DAG.getNode(ISD::BIT_CONVERT, HiVT, Hi);
456 }
457
458 void DAGTypeLegalizer::SplitVecRes_BUILD_VECTOR(SDNode *N, SDValue &Lo,
459                                                 SDValue &Hi) {
460   MVT LoVT, HiVT;
461   GetSplitDestVTs(N->getValueType(0), LoVT, HiVT);
462   unsigned LoNumElts = LoVT.getVectorNumElements();
463   SmallVector<SDValue, 8> LoOps(N->op_begin(), N->op_begin()+LoNumElts);
464   Lo = DAG.getNode(ISD::BUILD_VECTOR, LoVT, &LoOps[0], LoOps.size());
465
466   SmallVector<SDValue, 8> HiOps(N->op_begin()+LoNumElts, N->op_end());
467   Hi = DAG.getNode(ISD::BUILD_VECTOR, HiVT, &HiOps[0], HiOps.size());
468 }
469
470 void DAGTypeLegalizer::SplitVecRes_CONCAT_VECTORS(SDNode *N, SDValue &Lo,
471                                                   SDValue &Hi) {
472   assert(!(N->getNumOperands() & 1) && "Unsupported CONCAT_VECTORS");
473   unsigned NumSubvectors = N->getNumOperands() / 2;
474   if (NumSubvectors == 1) {
475     Lo = N->getOperand(0);
476     Hi = N->getOperand(1);
477     return;
478   }
479
480   MVT LoVT, HiVT;
481   GetSplitDestVTs(N->getValueType(0), LoVT, HiVT);
482
483   SmallVector<SDValue, 8> LoOps(N->op_begin(), N->op_begin()+NumSubvectors);
484   Lo = DAG.getNode(ISD::CONCAT_VECTORS, LoVT, &LoOps[0], LoOps.size());
485
486   SmallVector<SDValue, 8> HiOps(N->op_begin()+NumSubvectors, N->op_end());
487   Hi = DAG.getNode(ISD::CONCAT_VECTORS, HiVT, &HiOps[0], HiOps.size());
488 }
489
490 void DAGTypeLegalizer::SplitVecRes_EXTRACT_SUBVECTOR(SDNode *N, SDValue &Lo,
491                                                      SDValue &Hi) {
492   MVT LoVT, HiVT;
493   GetSplitDestVTs(N->getValueType(0), LoVT, HiVT);
494   unsigned LoNumElts = LoVT.getVectorNumElements();
495
496   SDValue Vec = N->getOperand(0);
497   SDValue Idx = N->getOperand(1);
498   MVT     IdxVT = Idx.getValueType();
499   Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, LoVT, Vec, Idx);
500
501   ConstantSDNode *CIdx = dyn_cast<ConstantSDNode>(Idx);
502   if (CIdx) {
503     unsigned IdxVal = CIdx->getZExtValue();
504     assert (IdxVal % LoVT.getVectorNumElements() == 0 &&
505            (IdxVal+LoNumElts) % HiVT.getVectorNumElements()==0 &&
506             "Index must be a multiple of the result type");
507     Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, HiVT, Vec,
508                      DAG.getConstant(IdxVal + LoNumElts, IdxVT));
509   } else {
510     assert(LoVT == HiVT && "Low and High value type should be the same");
511     Idx = DAG.getNode(ISD::ADD, IdxVT, Idx, DAG.getConstant(LoNumElts, IdxVT));
512     Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, HiVT, Vec, Idx);
513   }
514 }
515
516 void DAGTypeLegalizer::SplitVecRes_FPOWI(SDNode *N, SDValue &Lo,
517                                          SDValue &Hi) {
518   GetSplitVector(N->getOperand(0), Lo, Hi);
519   Lo = DAG.getNode(ISD::FPOWI, Lo.getValueType(), Lo, N->getOperand(1));
520   Hi = DAG.getNode(ISD::FPOWI, Hi.getValueType(), Hi, N->getOperand(1));
521 }
522
523 void DAGTypeLegalizer::SplitVecRes_INSERT_VECTOR_ELT(SDNode *N, SDValue &Lo,
524                                                      SDValue &Hi) {
525   SDValue Vec = N->getOperand(0);
526   SDValue Elt = N->getOperand(1);
527   SDValue Idx = N->getOperand(2);
528   GetSplitVector(Vec, Lo, Hi);
529
530   if (ConstantSDNode *CIdx = dyn_cast<ConstantSDNode>(Idx)) {
531     unsigned IdxVal = CIdx->getZExtValue();
532     unsigned LoNumElts = Lo.getValueType().getVectorNumElements();
533     if (IdxVal < LoNumElts)
534       Lo = DAG.getNode(ISD::INSERT_VECTOR_ELT, Lo.getValueType(), Lo, Elt, Idx);
535     else
536       Hi = DAG.getNode(ISD::INSERT_VECTOR_ELT, Hi.getValueType(), Hi, Elt,
537                        DAG.getIntPtrConstant(IdxVal - LoNumElts));
538     return;
539   }
540
541   // Spill the vector to the stack.
542   MVT VecVT = Vec.getValueType();
543   MVT EltVT = VecVT.getVectorElementType();
544   SDValue StackPtr = DAG.CreateStackTemporary(VecVT);
545   SDValue Store = DAG.getStore(DAG.getEntryNode(), Vec, StackPtr, NULL, 0);
546
547   // Store the new element.  This may be larger than the vector element type,
548   // so use a truncating store.
549   SDValue EltPtr = GetVectorElementPointer(StackPtr, EltVT, Idx);
550   Store = DAG.getTruncStore(Store, Elt, EltPtr, NULL, 0, EltVT);
551
552   // Reload the vector from the stack.
553   SDValue Load = DAG.getLoad(VecVT, Store, StackPtr, NULL, 0);
554
555   // Split it.
556   SplitVecRes_LOAD(cast<LoadSDNode>(Load.getNode()), Lo, Hi);
557 }
558
559 void DAGTypeLegalizer::SplitVecRes_LOAD(LoadSDNode *LD, SDValue &Lo,
560                                         SDValue &Hi) {
561   assert(ISD::isUNINDEXEDLoad(LD) && "Indexed load during type legalization!");
562   MVT LoVT, HiVT;
563   GetSplitDestVTs(LD->getValueType(0), LoVT, HiVT);
564
565   ISD::LoadExtType ExtType = LD->getExtensionType();
566   SDValue Ch = LD->getChain();
567   SDValue Ptr = LD->getBasePtr();
568   SDValue Offset = DAG.getNode(ISD::UNDEF, Ptr.getValueType());
569   const Value *SV = LD->getSrcValue();
570   int SVOffset = LD->getSrcValueOffset();
571   MVT MemoryVT = LD->getMemoryVT();
572   unsigned Alignment = LD->getAlignment();
573   bool isVolatile = LD->isVolatile();
574
575   MVT LoMemVT, HiMemVT;
576   GetSplitDestVTs(MemoryVT, LoMemVT, HiMemVT);
577
578   Lo = DAG.getLoad(ISD::UNINDEXED, ExtType, LoVT, Ch, Ptr, Offset,
579                    SV, SVOffset, LoMemVT, isVolatile, Alignment);
580
581   unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
582   Ptr = DAG.getNode(ISD::ADD, Ptr.getValueType(), Ptr,
583                     DAG.getIntPtrConstant(IncrementSize));
584   SVOffset += IncrementSize;
585   Alignment = MinAlign(Alignment, IncrementSize);
586   Hi = DAG.getLoad(ISD::UNINDEXED, ExtType, HiVT, Ch, Ptr, Offset,
587                    SV, SVOffset, HiMemVT, isVolatile, Alignment);
588
589   // Build a factor node to remember that this load is independent of the
590   // other one.
591   Ch = DAG.getNode(ISD::TokenFactor, MVT::Other, Lo.getValue(1),
592                    Hi.getValue(1));
593
594   // Legalized the chain result - switch anything that used the old chain to
595   // use the new one.
596   ReplaceValueWith(SDValue(LD, 1), Ch);
597 }
598
599 void DAGTypeLegalizer::SplitVecRes_UnaryOp(SDNode *N, SDValue &Lo,
600                                            SDValue &Hi) {
601   // Get the dest types - they may not match the input types, e.g. int_to_fp.
602   MVT LoVT, HiVT;
603   GetSplitDestVTs(N->getValueType(0), LoVT, HiVT);
604
605   // Split the input.
606   MVT InVT = N->getOperand(0).getValueType();
607   switch (getTypeAction(InVT)) {
608   default: assert(0 && "Unexpected type action!");
609   case Legal: {
610     assert(LoVT == HiVT && "Legal non-power-of-two vector type?");
611     MVT InNVT = MVT::getVectorVT(InVT.getVectorElementType(),
612                                  LoVT.getVectorNumElements());
613     Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, InNVT, N->getOperand(0),
614                      DAG.getIntPtrConstant(0));
615     Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, InNVT, N->getOperand(0),
616                      DAG.getIntPtrConstant(InNVT.getVectorNumElements()));
617     break;
618   }
619   case SplitVector:
620     GetSplitVector(N->getOperand(0), Lo, Hi);
621     break;
622   }
623
624   Lo = DAG.getNode(N->getOpcode(), LoVT, Lo);
625   Hi = DAG.getNode(N->getOpcode(), HiVT, Hi);
626 }
627
628 void DAGTypeLegalizer::SplitVecRes_VECTOR_SHUFFLE(SDNode *N, SDValue &Lo,
629                                                   SDValue &Hi) {
630   // Build the low part.
631   SDValue Mask = N->getOperand(2);
632   SmallVector<SDValue, 16> Ops;
633   MVT LoVT, HiVT;
634   GetSplitDestVTs(N->getValueType(0), LoVT, HiVT);
635   MVT EltVT = LoVT.getVectorElementType();
636   unsigned LoNumElts = LoVT.getVectorNumElements();
637   unsigned NumElements = Mask.getNumOperands();
638
639   // Insert all of the elements from the input that are needed.  We use
640   // buildvector of extractelement here because the input vectors will have
641   // to be legalized, so this makes the code simpler.
642   for (unsigned i = 0; i != LoNumElts; ++i) {
643     SDValue Arg = Mask.getOperand(i);
644     if (Arg.getOpcode() == ISD::UNDEF) {
645       Ops.push_back(DAG.getNode(ISD::UNDEF, EltVT));
646     } else {
647       unsigned Idx = cast<ConstantSDNode>(Mask.getOperand(i))->getZExtValue();
648       SDValue InVec = N->getOperand(0);
649       if (Idx >= NumElements) {
650         InVec = N->getOperand(1);
651         Idx -= NumElements;
652       }
653       Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, EltVT, InVec,
654                                 DAG.getIntPtrConstant(Idx)));
655     }
656   }
657   Lo = DAG.getNode(ISD::BUILD_VECTOR, LoVT, &Ops[0], Ops.size());
658   Ops.clear();
659
660   for (unsigned i = LoNumElts; i != NumElements; ++i) {
661     SDValue Arg = Mask.getOperand(i);
662     if (Arg.getOpcode() == ISD::UNDEF) {
663       Ops.push_back(DAG.getNode(ISD::UNDEF, EltVT));
664     } else {
665       unsigned Idx = cast<ConstantSDNode>(Mask.getOperand(i))->getZExtValue();
666       SDValue InVec = N->getOperand(0);
667       if (Idx >= NumElements) {
668         InVec = N->getOperand(1);
669         Idx -= NumElements;
670       }
671       Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, EltVT, InVec,
672                                 DAG.getIntPtrConstant(Idx)));
673     }
674   }
675   Hi = DAG.getNode(ISD::BUILD_VECTOR, HiVT, &Ops[0], Ops.size());
676 }
677
678 void DAGTypeLegalizer::SplitVecRes_VSETCC(SDNode *N, SDValue &Lo,
679                                           SDValue &Hi) {
680   MVT LoVT, HiVT;
681   GetSplitDestVTs(N->getValueType(0), LoVT, HiVT);
682
683   SDValue LL, LH, RL, RH;
684   GetSplitVector(N->getOperand(0), LL, LH);
685   GetSplitVector(N->getOperand(1), RL, RH);
686
687   Lo = DAG.getNode(ISD::VSETCC, LoVT, LL, RL, N->getOperand(2));
688   Hi = DAG.getNode(ISD::VSETCC, HiVT, LH, RH, N->getOperand(2));
689 }
690
691
692 //===----------------------------------------------------------------------===//
693 //  Operand Vector Splitting
694 //===----------------------------------------------------------------------===//
695
696 /// SplitVectorOperand - This method is called when the specified operand of the
697 /// specified node is found to need vector splitting.  At this point, all of the
698 /// result types of the node are known to be legal, but other operands of the
699 /// node may need legalization as well as the specified one.
700 bool DAGTypeLegalizer::SplitVectorOperand(SDNode *N, unsigned OpNo) {
701   DEBUG(cerr << "Split node operand: "; N->dump(&DAG); cerr << "\n");
702   SDValue Res = SDValue();
703
704   if (Res.getNode() == 0) {
705     switch (N->getOpcode()) {
706     default:
707 #ifndef NDEBUG
708       cerr << "SplitVectorOperand Op #" << OpNo << ": ";
709       N->dump(&DAG); cerr << "\n";
710 #endif
711       assert(0 && "Do not know how to split this operator's operand!");
712       abort();
713
714     case ISD::BIT_CONVERT:       Res = SplitVecOp_BIT_CONVERT(N); break;
715     case ISD::EXTRACT_SUBVECTOR: Res = SplitVecOp_EXTRACT_SUBVECTOR(N); break;
716     case ISD::EXTRACT_VECTOR_ELT:Res = SplitVecOp_EXTRACT_VECTOR_ELT(N); break;
717     case ISD::STORE:             Res = SplitVecOp_STORE(cast<StoreSDNode>(N),
718                                                         OpNo); break;
719     case ISD::VECTOR_SHUFFLE:    Res = SplitVecOp_VECTOR_SHUFFLE(N, OpNo);break;
720
721     case ISD::CTTZ:
722     case ISD::CTLZ:
723     case ISD::CTPOP:
724     case ISD::FP_TO_SINT:
725     case ISD::FP_TO_UINT:
726     case ISD::SINT_TO_FP:
727     case ISD::TRUNCATE:
728     case ISD::UINT_TO_FP: Res = SplitVecOp_UnaryOp(N); break;
729     }
730   }
731
732   // If the result is null, the sub-method took care of registering results etc.
733   if (!Res.getNode()) return false;
734
735   // If the result is N, the sub-method updated N in place.  Check to see if any
736   // operands are new, and if so, mark them.
737   if (Res.getNode() == N) {
738     // Mark N as new and remark N and its operands.  This allows us to correctly
739     // revisit N if it needs another step of promotion and allows us to visit
740     // any new operands to N.
741     ReanalyzeNode(N);
742     return true;
743   }
744
745   assert(Res.getValueType() == N->getValueType(0) && N->getNumValues() == 1 &&
746          "Invalid operand expansion");
747
748   ReplaceValueWith(SDValue(N, 0), Res);
749   return false;
750 }
751
752 SDValue DAGTypeLegalizer::SplitVecOp_UnaryOp(SDNode *N) {
753   // The result has a legal vector type, but the input needs splitting.
754   MVT ResVT = N->getValueType(0);
755   SDValue Lo, Hi;
756   GetSplitVector(N->getOperand(0), Lo, Hi);
757   assert(Lo.getValueType() == Hi.getValueType() &&
758          "Returns legal non-power-of-two vector type?");
759   MVT InVT = Lo.getValueType();
760
761   MVT OutVT = MVT::getVectorVT(ResVT.getVectorElementType(),
762                                InVT.getVectorNumElements());
763
764   Lo = DAG.getNode(N->getOpcode(), OutVT, Lo);
765   Hi = DAG.getNode(N->getOpcode(), OutVT, Hi);
766
767   return DAG.getNode(ISD::CONCAT_VECTORS, ResVT, Lo, Hi);
768 }
769
770 SDValue DAGTypeLegalizer::SplitVecOp_BIT_CONVERT(SDNode *N) {
771   // For example, i64 = BIT_CONVERT v4i16 on alpha.  Typically the vector will
772   // end up being split all the way down to individual components.  Convert the
773   // split pieces into integers and reassemble.
774   SDValue Lo, Hi;
775   GetSplitVector(N->getOperand(0), Lo, Hi);
776   Lo = BitConvertToInteger(Lo);
777   Hi = BitConvertToInteger(Hi);
778
779   if (TLI.isBigEndian())
780     std::swap(Lo, Hi);
781
782   return DAG.getNode(ISD::BIT_CONVERT, N->getValueType(0),
783                      JoinIntegers(Lo, Hi));
784 }
785
786 SDValue DAGTypeLegalizer::SplitVecOp_EXTRACT_SUBVECTOR(SDNode *N) {
787   // We know that the extracted result type is legal.  For now, assume the index
788   // is a constant.
789   MVT SubVT = N->getValueType(0);
790   SDValue Idx = N->getOperand(1);
791   SDValue Lo, Hi;
792   GetSplitVector(N->getOperand(0), Lo, Hi);
793
794   uint64_t LoElts = Lo.getValueType().getVectorNumElements();
795   uint64_t IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
796
797   if (IdxVal < LoElts) {
798     assert(IdxVal + SubVT.getVectorNumElements() <= LoElts &&
799            "Extracted subvector crosses vector split!");
800     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, SubVT, Lo, Idx);
801   } else {
802     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, SubVT, Hi,
803                        DAG.getConstant(IdxVal - LoElts, Idx.getValueType()));
804   }
805 }
806
807 SDValue DAGTypeLegalizer::SplitVecOp_EXTRACT_VECTOR_ELT(SDNode *N) {
808   SDValue Vec = N->getOperand(0);
809   SDValue Idx = N->getOperand(1);
810   MVT VecVT = Vec.getValueType();
811
812   if (isa<ConstantSDNode>(Idx)) {
813     uint64_t IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
814     assert(IdxVal < VecVT.getVectorNumElements() && "Invalid vector index!");
815
816     SDValue Lo, Hi;
817     GetSplitVector(Vec, Lo, Hi);
818
819     uint64_t LoElts = Lo.getValueType().getVectorNumElements();
820
821     if (IdxVal < LoElts)
822       return DAG.UpdateNodeOperands(SDValue(N, 0), Lo, Idx);
823     else
824       return DAG.UpdateNodeOperands(SDValue(N, 0), Hi,
825                                     DAG.getConstant(IdxVal - LoElts,
826                                                     Idx.getValueType()));
827   }
828
829   // Store the vector to the stack.
830   MVT EltVT = VecVT.getVectorElementType();
831   SDValue StackPtr = DAG.CreateStackTemporary(VecVT);
832   SDValue Store = DAG.getStore(DAG.getEntryNode(), Vec, StackPtr, NULL, 0);
833
834   // Load back the required element.
835   StackPtr = GetVectorElementPointer(StackPtr, EltVT, Idx);
836   return DAG.getLoad(EltVT, Store, StackPtr, NULL, 0);
837 }
838
839 SDValue DAGTypeLegalizer::SplitVecOp_STORE(StoreSDNode *N, unsigned OpNo) {
840   assert(N->isUnindexed() && "Indexed store of vector?");
841   assert(OpNo == 1 && "Can only split the stored value");
842
843   bool isTruncating = N->isTruncatingStore();
844   SDValue Ch  = N->getChain();
845   SDValue Ptr = N->getBasePtr();
846   int SVOffset = N->getSrcValueOffset();
847   MVT MemoryVT = N->getMemoryVT();
848   unsigned Alignment = N->getAlignment();
849   bool isVol = N->isVolatile();
850   SDValue Lo, Hi;
851   GetSplitVector(N->getOperand(1), Lo, Hi);
852
853   MVT LoMemVT, HiMemVT;
854   GetSplitDestVTs(MemoryVT, LoMemVT, HiMemVT);
855
856   unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
857
858   if (isTruncating)
859     Lo = DAG.getTruncStore(Ch, Lo, Ptr, N->getSrcValue(), SVOffset,
860                            LoMemVT, isVol, Alignment);
861   else
862     Lo = DAG.getStore(Ch, Lo, Ptr, N->getSrcValue(), SVOffset,
863                       isVol, Alignment);
864
865   // Increment the pointer to the other half.
866   Ptr = DAG.getNode(ISD::ADD, Ptr.getValueType(), Ptr,
867                     DAG.getIntPtrConstant(IncrementSize));
868
869   if (isTruncating)
870     Hi = DAG.getTruncStore(Ch, Hi, Ptr,
871                            N->getSrcValue(), SVOffset+IncrementSize,
872                            HiMemVT,
873                            isVol, MinAlign(Alignment, IncrementSize));
874   else
875     Hi = DAG.getStore(Ch, Hi, Ptr, N->getSrcValue(), SVOffset+IncrementSize,
876                       isVol, MinAlign(Alignment, IncrementSize));
877
878   return DAG.getNode(ISD::TokenFactor, MVT::Other, Lo, Hi);
879 }
880
881 SDValue DAGTypeLegalizer::SplitVecOp_VECTOR_SHUFFLE(SDNode *N, unsigned OpNo) {
882   assert(OpNo == 2 && "Shuffle source type differs from result type?");
883   SDValue Mask = N->getOperand(2);
884   unsigned MaskLength = Mask.getValueType().getVectorNumElements();
885   unsigned LargestMaskEntryPlusOne = 2 * MaskLength;
886   unsigned MinimumBitWidth = Log2_32_Ceil(LargestMaskEntryPlusOne);
887
888   // Look for a legal vector type to place the mask values in.
889   // Note that there may not be *any* legal vector-of-integer
890   // type for which the element type is legal!
891   for (MVT::SimpleValueType EltVT = MVT::FIRST_INTEGER_VALUETYPE;
892        EltVT <= MVT::LAST_INTEGER_VALUETYPE;
893        // Integer values types are consecutively numbered.  Exploit this.
894        EltVT = MVT::SimpleValueType(EltVT + 1)) {
895
896     // Is the element type big enough to hold the values?
897     if (MVT(EltVT).getSizeInBits() < MinimumBitWidth)
898       // Nope.
899       continue;
900
901     // Is the vector type legal?
902     MVT VecVT = MVT::getVectorVT(EltVT, MaskLength);
903     if (!isTypeLegal(VecVT))
904       // Nope.
905       continue;
906
907     // If the element type is not legal, find a larger legal type to use for
908     // the BUILD_VECTOR operands.  This is an ugly hack, but seems to work!
909     // FIXME: The real solution is to change VECTOR_SHUFFLE into a variadic
910     // node where the shuffle mask is a list of integer operands, #2 .. #2+n.
911     for (MVT::SimpleValueType OpVT = EltVT; OpVT <= MVT::LAST_INTEGER_VALUETYPE;
912          // Integer values types are consecutively numbered.  Exploit this.
913          OpVT = MVT::SimpleValueType(OpVT + 1)) {
914       if (!isTypeLegal(OpVT))
915         continue;
916
917       // Success!  Rebuild the vector using the legal types.
918       SmallVector<SDValue, 16> Ops(MaskLength);
919       for (unsigned i = 0; i < MaskLength; ++i) {
920         SDValue Arg = Mask.getOperand(i);
921         if (Arg.getOpcode() == ISD::UNDEF) {
922           Ops[i] = DAG.getNode(ISD::UNDEF, OpVT);
923         } else {
924           uint64_t Idx = cast<ConstantSDNode>(Arg)->getZExtValue();
925           Ops[i] = DAG.getConstant(Idx, OpVT);
926         }
927       }
928       return DAG.UpdateNodeOperands(SDValue(N,0),
929                                     N->getOperand(0), N->getOperand(1),
930                                     DAG.getNode(ISD::BUILD_VECTOR,
931                                                 VecVT, &Ops[0], Ops.size()));
932     }
933
934     // Continuing is pointless - failure is certain.
935     break;
936   }
937   assert(false && "Failed to find an appropriate mask type!");
938   return SDValue(N, 0);
939 }