Clean up dwarf writer, part 1. This eliminated the horrible recursive getGlobalVariab...
[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 #include "llvm/CodeGen/PseudoSourceValue.h"
25 #include "llvm/Target/TargetData.h"
26 using namespace llvm;
27
28 //===----------------------------------------------------------------------===//
29 //  Result Vector Scalarization: <1 x ty> -> ty.
30 //===----------------------------------------------------------------------===//
31
32 void DAGTypeLegalizer::ScalarizeVectorResult(SDNode *N, unsigned ResNo) {
33   DEBUG(cerr << "Scalarize node result " << ResNo << ": "; N->dump(&DAG);
34         cerr << "\n");
35   SDValue R = SDValue();
36
37   switch (N->getOpcode()) {
38   default:
39 #ifndef NDEBUG
40     cerr << "ScalarizeVectorResult #" << ResNo << ": ";
41     N->dump(&DAG); cerr << "\n";
42 #endif
43     assert(0 && "Do not know how to scalarize the result of this operator!");
44     abort();
45
46   case ISD::BIT_CONVERT:       R = ScalarizeVecRes_BIT_CONVERT(N); break;
47   case ISD::BUILD_VECTOR:      R = N->getOperand(0); break;
48   case ISD::CONVERT_RNDSAT:    R = ScalarizeVecRes_CONVERT_RNDSAT(N); break;
49   case ISD::EXTRACT_SUBVECTOR: R = ScalarizeVecRes_EXTRACT_SUBVECTOR(N); break;
50   case ISD::FPOWI:             R = ScalarizeVecRes_FPOWI(N); break;
51   case ISD::INSERT_VECTOR_ELT: R = ScalarizeVecRes_INSERT_VECTOR_ELT(N); break;
52   case ISD::LOAD:           R = ScalarizeVecRes_LOAD(cast<LoadSDNode>(N));break;
53   case ISD::SCALAR_TO_VECTOR:  R = ScalarizeVecRes_SCALAR_TO_VECTOR(N); break;
54   case ISD::SELECT:            R = ScalarizeVecRes_SELECT(N); break;
55   case ISD::SELECT_CC:         R = ScalarizeVecRes_SELECT_CC(N); break;
56   case ISD::UNDEF:             R = ScalarizeVecRes_UNDEF(N); break;
57   case ISD::VECTOR_SHUFFLE:    R = ScalarizeVecRes_VECTOR_SHUFFLE(N); break;
58   case ISD::VSETCC:            R = ScalarizeVecRes_VSETCC(N); break;
59
60   case ISD::CTLZ:
61   case ISD::CTPOP:
62   case ISD::CTTZ:
63   case ISD::FABS:
64   case ISD::FCOS:
65   case ISD::FNEG:
66   case ISD::FP_TO_SINT:
67   case ISD::FP_TO_UINT:
68   case ISD::FSIN:
69   case ISD::FSQRT:
70   case ISD::FTRUNC:
71   case ISD::FFLOOR:
72   case ISD::FCEIL:
73   case ISD::FRINT:
74   case ISD::FNEARBYINT:
75   case ISD::SINT_TO_FP:
76   case ISD::TRUNCATE:
77   case ISD::UINT_TO_FP: R = ScalarizeVecRes_UnaryOp(N); break;
78
79   case ISD::ADD:
80   case ISD::AND:
81   case ISD::FADD:
82   case ISD::FDIV:
83   case ISD::FMUL:
84   case ISD::FPOW:
85   case ISD::FREM:
86   case ISD::FSUB:
87   case ISD::MUL:
88   case ISD::OR:
89   case ISD::SDIV:
90   case ISD::SREM:
91   case ISD::SUB:
92   case ISD::UDIV:
93   case ISD::UREM:
94   case ISD::XOR:  R = ScalarizeVecRes_BinOp(N); break;
95
96   case ISD::SHL:
97   case ISD::SRA:
98   case ISD::SRL: R = ScalarizeVecRes_ShiftOp(N); break;
99   }
100
101   // If R is null, the sub-method took care of registering the result.
102   if (R.getNode())
103     SetScalarizedVector(SDValue(N, ResNo), R);
104 }
105
106 SDValue DAGTypeLegalizer::ScalarizeVecRes_BinOp(SDNode *N) {
107   SDValue LHS = GetScalarizedVector(N->getOperand(0));
108   SDValue RHS = GetScalarizedVector(N->getOperand(1));
109   return DAG.getNode(N->getOpcode(), N->getDebugLoc(),
110                      LHS.getValueType(), LHS, RHS);
111 }
112
113 SDValue DAGTypeLegalizer::ScalarizeVecRes_ShiftOp(SDNode *N) {
114   SDValue LHS = GetScalarizedVector(N->getOperand(0));
115   SDValue ShiftAmt = GetScalarizedVector(N->getOperand(1));
116   return DAG.getNode(N->getOpcode(), N->getDebugLoc(),
117                      LHS.getValueType(), LHS, ShiftAmt);
118 }
119
120 SDValue DAGTypeLegalizer::ScalarizeVecRes_BIT_CONVERT(SDNode *N) {
121   MVT NewVT = N->getValueType(0).getVectorElementType();
122   return DAG.getNode(ISD::BIT_CONVERT, N->getDebugLoc(),
123                      NewVT, N->getOperand(0));
124 }
125
126 SDValue DAGTypeLegalizer::ScalarizeVecRes_CONVERT_RNDSAT(SDNode *N) {
127   MVT NewVT = N->getValueType(0).getVectorElementType();
128   SDValue Op0 = GetScalarizedVector(N->getOperand(0));
129   return DAG.getConvertRndSat(NewVT, N->getDebugLoc(),
130                               Op0, DAG.getValueType(NewVT),
131                               DAG.getValueType(Op0.getValueType()),
132                               N->getOperand(3),
133                               N->getOperand(4),
134                               cast<CvtRndSatSDNode>(N)->getCvtCode());
135 }
136
137 SDValue DAGTypeLegalizer::ScalarizeVecRes_EXTRACT_SUBVECTOR(SDNode *N) {
138   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, N->getDebugLoc(),
139                      N->getValueType(0).getVectorElementType(),
140                      N->getOperand(0), N->getOperand(1));
141 }
142
143 SDValue DAGTypeLegalizer::ScalarizeVecRes_FPOWI(SDNode *N) {
144   SDValue Op = GetScalarizedVector(N->getOperand(0));
145   return DAG.getNode(ISD::FPOWI, N->getDebugLoc(),
146                      Op.getValueType(), Op, N->getOperand(1));
147 }
148
149 SDValue DAGTypeLegalizer::ScalarizeVecRes_INSERT_VECTOR_ELT(SDNode *N) {
150   // The value to insert may have a wider type than the vector element type,
151   // so be sure to truncate it to the element type if necessary.
152   SDValue Op = N->getOperand(1);
153   MVT EltVT = N->getValueType(0).getVectorElementType();
154   if (Op.getValueType() != EltVT)
155     // FIXME: Can this happen for floating point types?
156     Op = DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), EltVT, Op);
157   return Op;
158 }
159
160 SDValue DAGTypeLegalizer::ScalarizeVecRes_LOAD(LoadSDNode *N) {
161   assert(N->isUnindexed() && "Indexed vector load?");
162
163   SDValue Result = DAG.getLoad(ISD::UNINDEXED, N->getDebugLoc(),
164                                N->getExtensionType(),
165                                N->getValueType(0).getVectorElementType(),
166                                N->getChain(), N->getBasePtr(),
167                                DAG.getUNDEF(N->getBasePtr().getValueType()),
168                                N->getSrcValue(), N->getSrcValueOffset(),
169                                N->getMemoryVT().getVectorElementType(),
170                                N->isVolatile(), N->getAlignment());
171
172   // Legalized the chain result - switch anything that used the old chain to
173   // use the new one.
174   ReplaceValueWith(SDValue(N, 1), Result.getValue(1));
175   return Result;
176 }
177
178 SDValue DAGTypeLegalizer::ScalarizeVecRes_UnaryOp(SDNode *N) {
179   // Get the dest type - it doesn't always match the input type, e.g. int_to_fp.
180   MVT DestVT = N->getValueType(0).getVectorElementType();
181   SDValue Op = GetScalarizedVector(N->getOperand(0));
182   return DAG.getNode(N->getOpcode(), N->getDebugLoc(), DestVT, Op);
183 }
184
185 SDValue DAGTypeLegalizer::ScalarizeVecRes_SCALAR_TO_VECTOR(SDNode *N) {
186   return N->getOperand(0);
187 }
188
189 SDValue DAGTypeLegalizer::ScalarizeVecRes_SELECT(SDNode *N) {
190   SDValue LHS = GetScalarizedVector(N->getOperand(1));
191   return DAG.getNode(ISD::SELECT, N->getDebugLoc(),
192                      LHS.getValueType(), N->getOperand(0), LHS,
193                      GetScalarizedVector(N->getOperand(2)));
194 }
195
196 SDValue DAGTypeLegalizer::ScalarizeVecRes_SELECT_CC(SDNode *N) {
197   SDValue LHS = GetScalarizedVector(N->getOperand(2));
198   return DAG.getNode(ISD::SELECT_CC, N->getDebugLoc(), LHS.getValueType(),
199                      N->getOperand(0), N->getOperand(1),
200                      LHS, GetScalarizedVector(N->getOperand(3)),
201                      N->getOperand(4));
202 }
203
204 SDValue DAGTypeLegalizer::ScalarizeVecRes_UNDEF(SDNode *N) {
205   return DAG.getUNDEF(N->getValueType(0).getVectorElementType());
206 }
207
208 SDValue DAGTypeLegalizer::ScalarizeVecRes_VECTOR_SHUFFLE(SDNode *N) {
209   // Figure out if the scalar is the LHS or RHS and return it.
210   SDValue Arg = N->getOperand(2).getOperand(0);
211   if (Arg.getOpcode() == ISD::UNDEF)
212     return DAG.getUNDEF(N->getValueType(0).getVectorElementType());
213   unsigned Op = !cast<ConstantSDNode>(Arg)->isNullValue();
214   return GetScalarizedVector(N->getOperand(Op));
215 }
216
217 SDValue DAGTypeLegalizer::ScalarizeVecRes_VSETCC(SDNode *N) {
218   SDValue LHS = GetScalarizedVector(N->getOperand(0));
219   SDValue RHS = GetScalarizedVector(N->getOperand(1));
220   MVT NVT = N->getValueType(0).getVectorElementType();
221   MVT SVT = TLI.getSetCCResultType(LHS.getValueType());
222   DebugLoc dl = N->getDebugLoc();
223
224   // Turn it into a scalar SETCC.
225   SDValue Res = DAG.getNode(ISD::SETCC, dl, SVT, LHS, RHS, N->getOperand(2));
226
227   // VSETCC always returns a sign-extended value, while SETCC may not.  The
228   // SETCC result type may not match the vector element type.  Correct these.
229   if (NVT.bitsLE(SVT)) {
230     // The SETCC result type is bigger than the vector element type.
231     // Ensure the SETCC result is sign-extended.
232     if (TLI.getBooleanContents() !=
233         TargetLowering::ZeroOrNegativeOneBooleanContent)
234       Res = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, SVT, Res,
235                         DAG.getValueType(MVT::i1));
236     // Truncate to the final type.
237     return DAG.getNode(ISD::TRUNCATE, dl, NVT, Res);
238   } else {
239     // The SETCC result type is smaller than the vector element type.
240     // If the SetCC result is not sign-extended, chop it down to MVT::i1.
241     if (TLI.getBooleanContents() !=
242         TargetLowering::ZeroOrNegativeOneBooleanContent)
243       Res = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Res);
244     // Sign extend to the final type.
245     return DAG.getNode(ISD::SIGN_EXTEND, dl, NVT, Res);
246   }
247 }
248
249
250 //===----------------------------------------------------------------------===//
251 //  Operand Vector Scalarization <1 x ty> -> ty.
252 //===----------------------------------------------------------------------===//
253
254 bool DAGTypeLegalizer::ScalarizeVectorOperand(SDNode *N, unsigned OpNo) {
255   DEBUG(cerr << "Scalarize node operand " << OpNo << ": "; N->dump(&DAG);
256         cerr << "\n");
257   SDValue Res = SDValue();
258
259   if (Res.getNode() == 0) {
260     switch (N->getOpcode()) {
261     default:
262 #ifndef NDEBUG
263       cerr << "ScalarizeVectorOperand Op #" << OpNo << ": ";
264       N->dump(&DAG); cerr << "\n";
265 #endif
266       assert(0 && "Do not know how to scalarize this operator's operand!");
267       abort();
268
269     case ISD::BIT_CONVERT:
270       Res = ScalarizeVecOp_BIT_CONVERT(N); break;
271
272     case ISD::CONCAT_VECTORS:
273       Res = ScalarizeVecOp_CONCAT_VECTORS(N); break;
274
275     case ISD::EXTRACT_VECTOR_ELT:
276       Res = ScalarizeVecOp_EXTRACT_VECTOR_ELT(N); break;
277
278     case ISD::STORE:
279       Res = ScalarizeVecOp_STORE(cast<StoreSDNode>(N), OpNo); break;
280     }
281   }
282
283   // If the result is null, the sub-method took care of registering results etc.
284   if (!Res.getNode()) return false;
285
286   // If the result is N, the sub-method updated N in place.  Tell the legalizer
287   // core about this.
288   if (Res.getNode() == N)
289     return true;
290
291   assert(Res.getValueType() == N->getValueType(0) && N->getNumValues() == 1 &&
292          "Invalid operand expansion");
293
294   ReplaceValueWith(SDValue(N, 0), Res);
295   return false;
296 }
297
298 /// ScalarizeVecOp_BIT_CONVERT - If the value to convert is a vector that needs
299 /// to be scalarized, it must be <1 x ty>.  Convert the element instead.
300 SDValue DAGTypeLegalizer::ScalarizeVecOp_BIT_CONVERT(SDNode *N) {
301   SDValue Elt = GetScalarizedVector(N->getOperand(0));
302   return DAG.getNode(ISD::BIT_CONVERT, N->getDebugLoc(),
303                      N->getValueType(0), Elt);
304 }
305
306 /// ScalarizeVecOp_CONCAT_VECTORS - The vectors to concatenate have length one -
307 /// use a BUILD_VECTOR instead.
308 SDValue DAGTypeLegalizer::ScalarizeVecOp_CONCAT_VECTORS(SDNode *N) {
309   SmallVector<SDValue, 8> Ops(N->getNumOperands());
310   for (unsigned i = 0, e = N->getNumOperands(); i < e; ++i)
311     Ops[i] = GetScalarizedVector(N->getOperand(i));
312   return DAG.getBUILD_VECTOR(N->getValueType(0), N->getDebugLoc(),
313                              &Ops[0], Ops.size());
314 }
315
316 /// ScalarizeVecOp_EXTRACT_VECTOR_ELT - If the input is a vector that needs to
317 /// be scalarized, it must be <1 x ty>, so just return the element, ignoring the
318 /// index.
319 SDValue DAGTypeLegalizer::ScalarizeVecOp_EXTRACT_VECTOR_ELT(SDNode *N) {
320   return GetScalarizedVector(N->getOperand(0));
321 }
322
323 /// ScalarizeVecOp_STORE - If the value to store is a vector that needs to be
324 /// scalarized, it must be <1 x ty>.  Just store the element.
325 SDValue DAGTypeLegalizer::ScalarizeVecOp_STORE(StoreSDNode *N, unsigned OpNo){
326   assert(N->isUnindexed() && "Indexed store of one-element vector?");
327   assert(OpNo == 1 && "Do not know how to scalarize this operand!");
328   DebugLoc dl = N->getDebugLoc();
329
330   if (N->isTruncatingStore())
331     return DAG.getTruncStore(N->getChain(), dl,
332                              GetScalarizedVector(N->getOperand(1)),
333                              N->getBasePtr(),
334                              N->getSrcValue(), N->getSrcValueOffset(),
335                              N->getMemoryVT().getVectorElementType(),
336                              N->isVolatile(), N->getAlignment());
337
338   return DAG.getStore(N->getChain(), dl, GetScalarizedVector(N->getOperand(1)),
339                       N->getBasePtr(), N->getSrcValue(), N->getSrcValueOffset(),
340                       N->isVolatile(), N->getAlignment());
341 }
342
343
344 //===----------------------------------------------------------------------===//
345 //  Result Vector Splitting
346 //===----------------------------------------------------------------------===//
347
348 /// SplitVectorResult - This method is called when the specified result of the
349 /// specified node is found to need vector splitting.  At this point, the node
350 /// may also have invalid operands or may have other results that need
351 /// legalization, we just know that (at least) one result needs vector
352 /// splitting.
353 void DAGTypeLegalizer::SplitVectorResult(SDNode *N, unsigned ResNo) {
354   DEBUG(cerr << "Split node result: "; N->dump(&DAG); cerr << "\n");
355   SDValue Lo, Hi;
356
357   switch (N->getOpcode()) {
358   default:
359 #ifndef NDEBUG
360     cerr << "SplitVectorResult #" << ResNo << ": ";
361     N->dump(&DAG); cerr << "\n";
362 #endif
363     assert(0 && "Do not know how to split the result of this operator!");
364     abort();
365
366   case ISD::MERGE_VALUES: SplitRes_MERGE_VALUES(N, Lo, Hi); break;
367   case ISD::SELECT:       SplitRes_SELECT(N, Lo, Hi); break;
368   case ISD::SELECT_CC:    SplitRes_SELECT_CC(N, Lo, Hi); break;
369   case ISD::UNDEF:        SplitRes_UNDEF(N, Lo, Hi); break;
370
371   case ISD::BIT_CONVERT:       SplitVecRes_BIT_CONVERT(N, Lo, Hi); break;
372   case ISD::BUILD_VECTOR:      SplitVecRes_BUILD_VECTOR(N, Lo, Hi); break;
373   case ISD::CONCAT_VECTORS:    SplitVecRes_CONCAT_VECTORS(N, Lo, Hi); break;
374   case ISD::CONVERT_RNDSAT:    SplitVecRes_CONVERT_RNDSAT(N, Lo, Hi); break;
375   case ISD::EXTRACT_SUBVECTOR: SplitVecRes_EXTRACT_SUBVECTOR(N, Lo, Hi); break;
376   case ISD::FPOWI:             SplitVecRes_FPOWI(N, Lo, Hi); break;
377   case ISD::INSERT_VECTOR_ELT: SplitVecRes_INSERT_VECTOR_ELT(N, Lo, Hi); break;
378   case ISD::SCALAR_TO_VECTOR:  SplitVecRes_SCALAR_TO_VECTOR(N, Lo, Hi); break;
379   case ISD::LOAD:              SplitVecRes_LOAD(cast<LoadSDNode>(N), Lo, Hi);break;
380   case ISD::VECTOR_SHUFFLE:    SplitVecRes_VECTOR_SHUFFLE(N, Lo, Hi); break;
381   case ISD::VSETCC:            SplitVecRes_VSETCC(N, Lo, Hi); break;
382
383   case ISD::CTTZ:
384   case ISD::CTLZ:
385   case ISD::CTPOP:
386   case ISD::FNEG:
387   case ISD::FABS:
388   case ISD::FSQRT:
389   case ISD::FSIN:
390   case ISD::FCOS:
391   case ISD::FTRUNC:
392   case ISD::FFLOOR:
393   case ISD::FCEIL:
394   case ISD::FRINT:
395   case ISD::FNEARBYINT:
396   case ISD::FP_TO_SINT:
397   case ISD::FP_TO_UINT:
398   case ISD::SINT_TO_FP:
399   case ISD::TRUNCATE:
400   case ISD::UINT_TO_FP: SplitVecRes_UnaryOp(N, Lo, Hi); break;
401
402   case ISD::ADD:
403   case ISD::SUB:
404   case ISD::MUL:
405   case ISD::FADD:
406   case ISD::FSUB:
407   case ISD::FMUL:
408   case ISD::SDIV:
409   case ISD::UDIV:
410   case ISD::FDIV:
411   case ISD::FPOW:
412   case ISD::AND:
413   case ISD::OR:
414   case ISD::XOR:
415   case ISD::SHL:
416   case ISD::SRA:
417   case ISD::SRL:
418   case ISD::UREM:
419   case ISD::SREM:
420   case ISD::FREM: SplitVecRes_BinOp(N, Lo, Hi); break;
421   }
422
423   // If Lo/Hi is null, the sub-method took care of registering results etc.
424   if (Lo.getNode())
425     SetSplitVector(SDValue(N, ResNo), Lo, Hi);
426 }
427
428 void DAGTypeLegalizer::SplitVecRes_BinOp(SDNode *N, SDValue &Lo,
429                                          SDValue &Hi) {
430   SDValue LHSLo, LHSHi;
431   GetSplitVector(N->getOperand(0), LHSLo, LHSHi);
432   SDValue RHSLo, RHSHi;
433   GetSplitVector(N->getOperand(1), RHSLo, RHSHi);
434   DebugLoc dl = N->getDebugLoc();
435
436   Lo = DAG.getNode(N->getOpcode(), dl, LHSLo.getValueType(), LHSLo, RHSLo);
437   Hi = DAG.getNode(N->getOpcode(), dl, LHSHi.getValueType(), LHSHi, RHSHi);
438 }
439
440 void DAGTypeLegalizer::SplitVecRes_BIT_CONVERT(SDNode *N, SDValue &Lo,
441                                                SDValue &Hi) {
442   // We know the result is a vector.  The input may be either a vector or a
443   // scalar value.
444   MVT LoVT, HiVT;
445   GetSplitDestVTs(N->getValueType(0), LoVT, HiVT);
446   DebugLoc dl = N->getDebugLoc();
447
448   SDValue InOp = N->getOperand(0);
449   MVT InVT = InOp.getValueType();
450
451   // Handle some special cases efficiently.
452   switch (getTypeAction(InVT)) {
453   default:
454     assert(false && "Unknown type action!");
455   case Legal:
456   case PromoteInteger:
457   case SoftenFloat:
458   case ScalarizeVector:
459     break;
460   case ExpandInteger:
461   case ExpandFloat:
462     // A scalar to vector conversion, where the scalar needs expansion.
463     // If the vector is being split in two then we can just convert the
464     // expanded pieces.
465     if (LoVT == HiVT) {
466       GetExpandedOp(InOp, Lo, Hi);
467       if (TLI.isBigEndian())
468         std::swap(Lo, Hi);
469       Lo = DAG.getNode(ISD::BIT_CONVERT, dl, LoVT, Lo);
470       Hi = DAG.getNode(ISD::BIT_CONVERT, dl, HiVT, Hi);
471       return;
472     }
473     break;
474   case SplitVector:
475     // If the input is a vector that needs to be split, convert each split
476     // piece of the input now.
477     GetSplitVector(InOp, Lo, Hi);
478     Lo = DAG.getNode(ISD::BIT_CONVERT, dl, LoVT, Lo);
479     Hi = DAG.getNode(ISD::BIT_CONVERT, dl, HiVT, Hi);
480     return;
481   }
482
483   // In the general case, convert the input to an integer and split it by hand.
484   MVT LoIntVT = MVT::getIntegerVT(LoVT.getSizeInBits());
485   MVT HiIntVT = MVT::getIntegerVT(HiVT.getSizeInBits());
486   if (TLI.isBigEndian())
487     std::swap(LoIntVT, HiIntVT);
488
489   SplitInteger(BitConvertToInteger(InOp), LoIntVT, HiIntVT, Lo, Hi);
490
491   if (TLI.isBigEndian())
492     std::swap(Lo, Hi);
493   Lo = DAG.getNode(ISD::BIT_CONVERT, dl, LoVT, Lo);
494   Hi = DAG.getNode(ISD::BIT_CONVERT, dl, HiVT, Hi);
495 }
496
497 void DAGTypeLegalizer::SplitVecRes_BUILD_VECTOR(SDNode *N, SDValue &Lo,
498                                                 SDValue &Hi) {
499   MVT LoVT, HiVT;
500   DebugLoc dl = N->getDebugLoc();
501   GetSplitDestVTs(N->getValueType(0), LoVT, HiVT);
502   unsigned LoNumElts = LoVT.getVectorNumElements();
503   SmallVector<SDValue, 8> LoOps(N->op_begin(), N->op_begin()+LoNumElts);
504   Lo = DAG.getBUILD_VECTOR(LoVT, dl, &LoOps[0], LoOps.size());
505
506   SmallVector<SDValue, 8> HiOps(N->op_begin()+LoNumElts, N->op_end());
507   Hi = DAG.getBUILD_VECTOR(HiVT, dl, &HiOps[0], HiOps.size());
508 }
509
510 void DAGTypeLegalizer::SplitVecRes_CONCAT_VECTORS(SDNode *N, SDValue &Lo,
511                                                   SDValue &Hi) {
512   assert(!(N->getNumOperands() & 1) && "Unsupported CONCAT_VECTORS");
513   DebugLoc dl = N->getDebugLoc();
514   unsigned NumSubvectors = N->getNumOperands() / 2;
515   if (NumSubvectors == 1) {
516     Lo = N->getOperand(0);
517     Hi = N->getOperand(1);
518     return;
519   }
520
521   MVT LoVT, HiVT;
522   GetSplitDestVTs(N->getValueType(0), LoVT, HiVT);
523
524   SmallVector<SDValue, 8> LoOps(N->op_begin(), N->op_begin()+NumSubvectors);
525   Lo = DAG.getNode(ISD::CONCAT_VECTORS, dl, LoVT, &LoOps[0], LoOps.size());
526
527   SmallVector<SDValue, 8> HiOps(N->op_begin()+NumSubvectors, N->op_end());
528   Hi = DAG.getNode(ISD::CONCAT_VECTORS, dl, HiVT, &HiOps[0], HiOps.size());
529 }
530
531 void DAGTypeLegalizer::SplitVecRes_CONVERT_RNDSAT(SDNode *N, SDValue &Lo,
532                                                   SDValue &Hi) {
533   MVT LoVT, HiVT;
534   DebugLoc dl = N->getDebugLoc();
535   GetSplitDestVTs(N->getValueType(0), LoVT, HiVT);
536   SDValue VLo, VHi;
537   GetSplitVector(N->getOperand(0), VLo, VHi);
538   SDValue DTyOpLo =  DAG.getValueType(LoVT);
539   SDValue DTyOpHi =  DAG.getValueType(HiVT);
540   SDValue STyOpLo =  DAG.getValueType(VLo.getValueType());
541   SDValue STyOpHi =  DAG.getValueType(VHi.getValueType());
542
543   SDValue RndOp = N->getOperand(3);
544   SDValue SatOp = N->getOperand(4);
545   ISD::CvtCode CvtCode = cast<CvtRndSatSDNode>(N)->getCvtCode();
546
547   Lo = DAG.getConvertRndSat(LoVT, dl, VLo, DTyOpLo, STyOpLo, RndOp, SatOp,
548                             CvtCode);
549   Hi = DAG.getConvertRndSat(HiVT, dl, VHi, DTyOpHi, STyOpHi, RndOp, SatOp,
550                             CvtCode);
551 }
552
553 void DAGTypeLegalizer::SplitVecRes_EXTRACT_SUBVECTOR(SDNode *N, SDValue &Lo,
554                                                      SDValue &Hi) {
555   SDValue Vec = N->getOperand(0);
556   SDValue Idx = N->getOperand(1);
557   MVT IdxVT = Idx.getValueType();
558   DebugLoc dl = N->getDebugLoc();
559
560   MVT LoVT, HiVT;
561   GetSplitDestVTs(N->getValueType(0), LoVT, HiVT);
562   // The indices are not guaranteed to be a multiple of the new vector
563   // size unless the original vector type was split in two.
564   assert(LoVT == HiVT && "Non power-of-two vectors not supported!");
565
566   Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, LoVT, Vec, Idx);
567   Idx = DAG.getNode(ISD::ADD, dl, IdxVT, Idx,
568                     DAG.getConstant(LoVT.getVectorNumElements(), IdxVT));
569   Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, HiVT, Vec, Idx);
570 }
571
572 void DAGTypeLegalizer::SplitVecRes_FPOWI(SDNode *N, SDValue &Lo,
573                                          SDValue &Hi) {
574   DebugLoc dl = N->getDebugLoc();
575   GetSplitVector(N->getOperand(0), Lo, Hi);
576   Lo = DAG.getNode(ISD::FPOWI, dl, Lo.getValueType(), Lo, N->getOperand(1));
577   Hi = DAG.getNode(ISD::FPOWI, dl, Hi.getValueType(), Hi, N->getOperand(1));
578 }
579
580 void DAGTypeLegalizer::SplitVecRes_INSERT_VECTOR_ELT(SDNode *N, SDValue &Lo,
581                                                      SDValue &Hi) {
582   SDValue Vec = N->getOperand(0);
583   SDValue Elt = N->getOperand(1);
584   SDValue Idx = N->getOperand(2);
585   DebugLoc dl = N->getDebugLoc();
586   GetSplitVector(Vec, Lo, Hi);
587
588   if (ConstantSDNode *CIdx = dyn_cast<ConstantSDNode>(Idx)) {
589     unsigned IdxVal = CIdx->getZExtValue();
590     unsigned LoNumElts = Lo.getValueType().getVectorNumElements();
591     if (IdxVal < LoNumElts)
592       Lo = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
593                        Lo.getValueType(), Lo, Elt, Idx);
594     else
595       Hi = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, Hi.getValueType(), Hi, Elt,
596                        DAG.getIntPtrConstant(IdxVal - LoNumElts));
597     return;
598   }
599
600   // Spill the vector to the stack.
601   MVT VecVT = Vec.getValueType();
602   MVT EltVT = VecVT.getVectorElementType();
603   SDValue StackPtr = DAG.CreateStackTemporary(VecVT);
604   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Vec, StackPtr, NULL, 0);
605
606   // Store the new element.  This may be larger than the vector element type,
607   // so use a truncating store.
608   SDValue EltPtr = GetVectorElementPointer(StackPtr, EltVT, Idx);
609   unsigned Alignment =
610     TLI.getTargetData()->getPrefTypeAlignment(VecVT.getTypeForMVT());
611   Store = DAG.getTruncStore(Store, dl, Elt, EltPtr, NULL, 0, EltVT);
612
613   // Load the Lo part from the stack slot.
614   Lo = DAG.getLoad(Lo.getValueType(), dl, Store, StackPtr, NULL, 0);
615
616   // Increment the pointer to the other part.
617   unsigned IncrementSize = Lo.getValueType().getSizeInBits() / 8;
618   StackPtr = DAG.getNode(ISD::ADD, dl, StackPtr.getValueType(), StackPtr,
619                          DAG.getIntPtrConstant(IncrementSize));
620
621   // Load the Hi part from the stack slot.
622   Hi = DAG.getLoad(Hi.getValueType(), dl, Store, StackPtr, NULL, 0, false,
623                    MinAlign(Alignment, IncrementSize));
624 }
625
626 void DAGTypeLegalizer::SplitVecRes_SCALAR_TO_VECTOR(SDNode *N, SDValue &Lo,
627                                                     SDValue &Hi) {
628   MVT LoVT, HiVT;
629   DebugLoc dl = N->getDebugLoc();
630   GetSplitDestVTs(N->getValueType(0), LoVT, HiVT);
631   Lo = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoVT, N->getOperand(0));
632   Hi = DAG.getUNDEF(HiVT);
633 }
634
635 void DAGTypeLegalizer::SplitVecRes_LOAD(LoadSDNode *LD, SDValue &Lo,
636                                         SDValue &Hi) {
637   assert(ISD::isUNINDEXEDLoad(LD) && "Indexed load during type legalization!");
638   MVT LoVT, HiVT;
639   DebugLoc dl = LD->getDebugLoc();
640   GetSplitDestVTs(LD->getValueType(0), LoVT, HiVT);
641
642   ISD::LoadExtType ExtType = LD->getExtensionType();
643   SDValue Ch = LD->getChain();
644   SDValue Ptr = LD->getBasePtr();
645   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
646   const Value *SV = LD->getSrcValue();
647   int SVOffset = LD->getSrcValueOffset();
648   MVT MemoryVT = LD->getMemoryVT();
649   unsigned Alignment = LD->getAlignment();
650   bool isVolatile = LD->isVolatile();
651
652   MVT LoMemVT, HiMemVT;
653   GetSplitDestVTs(MemoryVT, LoMemVT, HiMemVT);
654
655   Lo = DAG.getLoad(ISD::UNINDEXED, dl, ExtType, LoVT, Ch, Ptr, Offset,
656                    SV, SVOffset, LoMemVT, isVolatile, Alignment);
657
658   unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
659   Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
660                     DAG.getIntPtrConstant(IncrementSize));
661   SVOffset += IncrementSize;
662   Alignment = MinAlign(Alignment, IncrementSize);
663   Hi = DAG.getLoad(ISD::UNINDEXED, dl, ExtType, HiVT, Ch, Ptr, Offset,
664                    SV, SVOffset, HiMemVT, isVolatile, Alignment);
665
666   // Build a factor node to remember that this load is independent of the
667   // other one.
668   Ch = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1),
669                    Hi.getValue(1));
670
671   // Legalized the chain result - switch anything that used the old chain to
672   // use the new one.
673   ReplaceValueWith(SDValue(LD, 1), Ch);
674 }
675
676 void DAGTypeLegalizer::SplitVecRes_UnaryOp(SDNode *N, SDValue &Lo,
677                                            SDValue &Hi) {
678   // Get the dest types - they may not match the input types, e.g. int_to_fp.
679   MVT LoVT, HiVT;
680   DebugLoc dl = N->getDebugLoc();
681   GetSplitDestVTs(N->getValueType(0), LoVT, HiVT);
682
683   // Split the input.
684   MVT InVT = N->getOperand(0).getValueType();
685   switch (getTypeAction(InVT)) {
686   default: assert(0 && "Unexpected type action!");
687   case Legal: {
688     assert(LoVT == HiVT && "Legal non-power-of-two vector type?");
689     MVT InNVT = MVT::getVectorVT(InVT.getVectorElementType(),
690                                  LoVT.getVectorNumElements());
691     Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, InNVT, N->getOperand(0),
692                      DAG.getIntPtrConstant(0));
693     Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, InNVT, N->getOperand(0),
694                      DAG.getIntPtrConstant(InNVT.getVectorNumElements()));
695     break;
696   }
697   case SplitVector:
698     GetSplitVector(N->getOperand(0), Lo, Hi);
699     break;
700   }
701
702   Lo = DAG.getNode(N->getOpcode(), dl, LoVT, Lo);
703   Hi = DAG.getNode(N->getOpcode(), dl, HiVT, Hi);
704 }
705
706 void DAGTypeLegalizer::SplitVecRes_VECTOR_SHUFFLE(SDNode *N, SDValue &Lo,
707                                                   SDValue &Hi) {
708   // The low and high parts of the original input give four input vectors.
709   SDValue Inputs[4];
710   DebugLoc dl = N->getDebugLoc();
711   GetSplitVector(N->getOperand(0), Inputs[0], Inputs[1]);
712   GetSplitVector(N->getOperand(1), Inputs[2], Inputs[3]);
713   MVT NewVT = Inputs[0].getValueType();
714   unsigned NewElts = NewVT.getVectorNumElements();
715   assert(NewVT == Inputs[1].getValueType() &&
716          "Non power-of-two vectors not supported!");
717
718   // If Lo or Hi uses elements from at most two of the four input vectors, then
719   // express it as a vector shuffle of those two inputs.  Otherwise extract the
720   // input elements by hand and construct the Lo/Hi output using a BUILD_VECTOR.
721   SDValue Mask = N->getOperand(2);
722   MVT IdxVT = Mask.getValueType().getVectorElementType();
723   SmallVector<SDValue, 16> Ops;
724   Ops.reserve(NewElts);
725   for (unsigned High = 0; High < 2; ++High) {
726     SDValue &Output = High ? Hi : Lo;
727
728     // Build a shuffle mask for the output, discovering on the fly which
729     // input vectors to use as shuffle operands (recorded in InputUsed).
730     // If building a suitable shuffle vector proves too hard, then bail
731     // out with useBuildVector set.
732     unsigned InputUsed[2] = { -1U, -1U }; // Not yet discovered.
733     unsigned FirstMaskIdx = High * NewElts;
734     bool useBuildVector = false;
735     for (unsigned MaskOffset = 0; MaskOffset < NewElts; ++MaskOffset) {
736       SDValue Arg = Mask.getOperand(FirstMaskIdx + MaskOffset);
737
738       // The mask element.  This indexes into the input.
739       unsigned Idx = Arg.getOpcode() == ISD::UNDEF ?
740         -1U : cast<ConstantSDNode>(Arg)->getZExtValue();
741
742       // The input vector this mask element indexes into.
743       unsigned Input = Idx / NewElts;
744
745       if (Input >= array_lengthof(Inputs)) {
746         // The mask element does not index into any input vector.
747         Ops.push_back(DAG.getUNDEF(IdxVT));
748         continue;
749       }
750
751       // Turn the index into an offset from the start of the input vector.
752       Idx -= Input * NewElts;
753
754       // Find or create a shuffle vector operand to hold this input.
755       unsigned OpNo;
756       for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
757         if (InputUsed[OpNo] == Input) {
758           // This input vector is already an operand.
759           break;
760         } else if (InputUsed[OpNo] == -1U) {
761           // Create a new operand for this input vector.
762           InputUsed[OpNo] = Input;
763           break;
764         }
765       }
766
767       if (OpNo >= array_lengthof(InputUsed)) {
768         // More than two input vectors used!  Give up on trying to create a
769         // shuffle vector.  Insert all elements into a BUILD_VECTOR instead.
770         useBuildVector = true;
771         break;
772       }
773
774       // Add the mask index for the new shuffle vector.
775       Ops.push_back(DAG.getConstant(Idx + OpNo * NewElts, IdxVT));
776     }
777
778     if (useBuildVector) {
779       MVT EltVT = NewVT.getVectorElementType();
780       Ops.clear();
781
782       // Extract the input elements by hand.
783       for (unsigned MaskOffset = 0; MaskOffset < NewElts; ++MaskOffset) {
784         SDValue Arg = Mask.getOperand(FirstMaskIdx + MaskOffset);
785
786         // The mask element.  This indexes into the input.
787         unsigned Idx = Arg.getOpcode() == ISD::UNDEF ?
788           -1U : cast<ConstantSDNode>(Arg)->getZExtValue();
789
790         // The input vector this mask element indexes into.
791         unsigned Input = Idx / NewElts;
792
793         if (Input >= array_lengthof(Inputs)) {
794           // The mask element is "undef" or indexes off the end of the input.
795           Ops.push_back(DAG.getUNDEF(EltVT));
796           continue;
797         }
798
799         // Turn the index into an offset from the start of the input vector.
800         Idx -= Input * NewElts;
801
802         // Extract the vector element by hand.
803         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
804                                   Inputs[Input], DAG.getIntPtrConstant(Idx)));
805       }
806
807       // Construct the Lo/Hi output using a BUILD_VECTOR.
808       Output = DAG.getBUILD_VECTOR(NewVT, dl, &Ops[0], Ops.size());
809     } else if (InputUsed[0] == -1U) {
810       // No input vectors were used!  The result is undefined.
811       Output = DAG.getUNDEF(NewVT);
812     } else {
813       // At least one input vector was used.  Create a new shuffle vector.
814       SDValue NewMask = DAG.getBUILD_VECTOR(MVT::getVectorVT(IdxVT, Ops.size()),
815                                             dl, &Ops[0], Ops.size());
816       SDValue Op0 = Inputs[InputUsed[0]];
817       // If only one input was used, use an undefined vector for the other.
818       SDValue Op1 = InputUsed[1] == -1U ?
819         DAG.getUNDEF(NewVT) : Inputs[InputUsed[1]];
820       Output = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, NewVT, Op0, Op1, NewMask);
821     }
822
823     Ops.clear();
824   }
825 }
826
827 void DAGTypeLegalizer::SplitVecRes_VSETCC(SDNode *N, SDValue &Lo,
828                                           SDValue &Hi) {
829   MVT LoVT, HiVT;
830   DebugLoc dl = N->getDebugLoc();
831   GetSplitDestVTs(N->getValueType(0), LoVT, HiVT);
832
833   SDValue LL, LH, RL, RH;
834   GetSplitVector(N->getOperand(0), LL, LH);
835   GetSplitVector(N->getOperand(1), RL, RH);
836
837   Lo = DAG.getNode(ISD::VSETCC, dl, LoVT, LL, RL, N->getOperand(2));
838   Hi = DAG.getNode(ISD::VSETCC, dl, HiVT, LH, RH, N->getOperand(2));
839 }
840
841
842 //===----------------------------------------------------------------------===//
843 //  Operand Vector Splitting
844 //===----------------------------------------------------------------------===//
845
846 /// SplitVectorOperand - This method is called when the specified operand of the
847 /// specified node is found to need vector splitting.  At this point, all of the
848 /// result types of the node are known to be legal, but other operands of the
849 /// node may need legalization as well as the specified one.
850 bool DAGTypeLegalizer::SplitVectorOperand(SDNode *N, unsigned OpNo) {
851   DEBUG(cerr << "Split node operand: "; N->dump(&DAG); cerr << "\n");
852   SDValue Res = SDValue();
853
854   if (Res.getNode() == 0) {
855     switch (N->getOpcode()) {
856     default:
857 #ifndef NDEBUG
858       cerr << "SplitVectorOperand Op #" << OpNo << ": ";
859       N->dump(&DAG); cerr << "\n";
860 #endif
861       assert(0 && "Do not know how to split this operator's operand!");
862       abort();
863
864     case ISD::BIT_CONVERT:       Res = SplitVecOp_BIT_CONVERT(N); break;
865     case ISD::EXTRACT_SUBVECTOR: Res = SplitVecOp_EXTRACT_SUBVECTOR(N); break;
866     case ISD::EXTRACT_VECTOR_ELT:Res = SplitVecOp_EXTRACT_VECTOR_ELT(N); break;
867     case ISD::STORE:             Res = SplitVecOp_STORE(cast<StoreSDNode>(N),
868                                                         OpNo); break;
869     case ISD::VECTOR_SHUFFLE:    Res = SplitVecOp_VECTOR_SHUFFLE(N, OpNo);break;
870
871     case ISD::CTTZ:
872     case ISD::CTLZ:
873     case ISD::CTPOP:
874     case ISD::FP_TO_SINT:
875     case ISD::FP_TO_UINT:
876     case ISD::SINT_TO_FP:
877     case ISD::TRUNCATE:
878     case ISD::UINT_TO_FP: Res = SplitVecOp_UnaryOp(N); break;
879     }
880   }
881
882   // If the result is null, the sub-method took care of registering results etc.
883   if (!Res.getNode()) return false;
884
885   // If the result is N, the sub-method updated N in place.  Tell the legalizer
886   // core about this.
887   if (Res.getNode() == N)
888     return true;
889
890   assert(Res.getValueType() == N->getValueType(0) && N->getNumValues() == 1 &&
891          "Invalid operand expansion");
892
893   ReplaceValueWith(SDValue(N, 0), Res);
894   return false;
895 }
896
897 SDValue DAGTypeLegalizer::SplitVecOp_UnaryOp(SDNode *N) {
898   // The result has a legal vector type, but the input needs splitting.
899   MVT ResVT = N->getValueType(0);
900   SDValue Lo, Hi;
901   DebugLoc dl = N->getDebugLoc();
902   GetSplitVector(N->getOperand(0), Lo, Hi);
903   assert(Lo.getValueType() == Hi.getValueType() &&
904          "Returns legal non-power-of-two vector type?");
905   MVT InVT = Lo.getValueType();
906
907   MVT OutVT = MVT::getVectorVT(ResVT.getVectorElementType(),
908                                InVT.getVectorNumElements());
909
910   Lo = DAG.getNode(N->getOpcode(), dl, OutVT, Lo);
911   Hi = DAG.getNode(N->getOpcode(), dl, OutVT, Hi);
912
913   return DAG.getNode(ISD::CONCAT_VECTORS, dl, ResVT, Lo, Hi);
914 }
915
916 SDValue DAGTypeLegalizer::SplitVecOp_BIT_CONVERT(SDNode *N) {
917   // For example, i64 = BIT_CONVERT v4i16 on alpha.  Typically the vector will
918   // end up being split all the way down to individual components.  Convert the
919   // split pieces into integers and reassemble.
920   SDValue Lo, Hi;
921   GetSplitVector(N->getOperand(0), Lo, Hi);
922   Lo = BitConvertToInteger(Lo);
923   Hi = BitConvertToInteger(Hi);
924
925   if (TLI.isBigEndian())
926     std::swap(Lo, Hi);
927
928   return DAG.getNode(ISD::BIT_CONVERT, N->getDebugLoc(), N->getValueType(0),
929                      JoinIntegers(Lo, Hi));
930 }
931
932 SDValue DAGTypeLegalizer::SplitVecOp_EXTRACT_SUBVECTOR(SDNode *N) {
933   // We know that the extracted result type is legal.  For now, assume the index
934   // is a constant.
935   MVT SubVT = N->getValueType(0);
936   SDValue Idx = N->getOperand(1);
937   DebugLoc dl = N->getDebugLoc();
938   SDValue Lo, Hi;
939   GetSplitVector(N->getOperand(0), Lo, Hi);
940
941   uint64_t LoElts = Lo.getValueType().getVectorNumElements();
942   uint64_t IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
943
944   if (IdxVal < LoElts) {
945     assert(IdxVal + SubVT.getVectorNumElements() <= LoElts &&
946            "Extracted subvector crosses vector split!");
947     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, Lo, Idx);
948   } else {
949     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, Hi,
950                        DAG.getConstant(IdxVal - LoElts, Idx.getValueType()));
951   }
952 }
953
954 SDValue DAGTypeLegalizer::SplitVecOp_EXTRACT_VECTOR_ELT(SDNode *N) {
955   SDValue Vec = N->getOperand(0);
956   SDValue Idx = N->getOperand(1);
957   MVT VecVT = Vec.getValueType();
958
959   if (isa<ConstantSDNode>(Idx)) {
960     uint64_t IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
961     assert(IdxVal < VecVT.getVectorNumElements() && "Invalid vector index!");
962
963     SDValue Lo, Hi;
964     GetSplitVector(Vec, Lo, Hi);
965
966     uint64_t LoElts = Lo.getValueType().getVectorNumElements();
967
968     if (IdxVal < LoElts)
969       return DAG.UpdateNodeOperands(SDValue(N, 0), Lo, Idx);
970     else
971       return DAG.UpdateNodeOperands(SDValue(N, 0), Hi,
972                                     DAG.getConstant(IdxVal - LoElts,
973                                                     Idx.getValueType()));
974   }
975
976   // Store the vector to the stack.
977   MVT EltVT = VecVT.getVectorElementType();
978   DebugLoc dl = N->getDebugLoc();
979   SDValue StackPtr = DAG.CreateStackTemporary(VecVT);
980   int SPFI = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
981   const Value *SV = PseudoSourceValue::getFixedStack(SPFI);
982   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Vec, StackPtr, SV, 0);
983
984   // Load back the required element.
985   StackPtr = GetVectorElementPointer(StackPtr, EltVT, Idx);
986   return DAG.getLoad(EltVT, dl, Store, StackPtr, SV, 0);
987 }
988
989 SDValue DAGTypeLegalizer::SplitVecOp_STORE(StoreSDNode *N, unsigned OpNo) {
990   assert(N->isUnindexed() && "Indexed store of vector?");
991   assert(OpNo == 1 && "Can only split the stored value");
992   DebugLoc dl = N->getDebugLoc();
993
994   bool isTruncating = N->isTruncatingStore();
995   SDValue Ch  = N->getChain();
996   SDValue Ptr = N->getBasePtr();
997   int SVOffset = N->getSrcValueOffset();
998   MVT MemoryVT = N->getMemoryVT();
999   unsigned Alignment = N->getAlignment();
1000   bool isVol = N->isVolatile();
1001   SDValue Lo, Hi;
1002   GetSplitVector(N->getOperand(1), Lo, Hi);
1003
1004   MVT LoMemVT, HiMemVT;
1005   GetSplitDestVTs(MemoryVT, LoMemVT, HiMemVT);
1006
1007   unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
1008
1009   if (isTruncating)
1010     Lo = DAG.getTruncStore(Ch, dl, Lo, Ptr, N->getSrcValue(), SVOffset,
1011                            LoMemVT, isVol, Alignment);
1012   else
1013     Lo = DAG.getStore(Ch, dl, Lo, Ptr, N->getSrcValue(), SVOffset,
1014                       isVol, Alignment);
1015
1016   // Increment the pointer to the other half.
1017   Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
1018                     DAG.getIntPtrConstant(IncrementSize));
1019
1020   if (isTruncating)
1021     Hi = DAG.getTruncStore(Ch, dl, Hi, Ptr,
1022                            N->getSrcValue(), SVOffset+IncrementSize,
1023                            HiMemVT,
1024                            isVol, MinAlign(Alignment, IncrementSize));
1025   else
1026     Hi = DAG.getStore(Ch, dl, Hi, Ptr, N->getSrcValue(), SVOffset+IncrementSize,
1027                       isVol, MinAlign(Alignment, IncrementSize));
1028
1029   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo, Hi);
1030 }
1031
1032 SDValue DAGTypeLegalizer::SplitVecOp_VECTOR_SHUFFLE(SDNode *N, unsigned OpNo) {
1033   assert(OpNo == 2 && "Shuffle source type differs from result type?");
1034   SDValue Mask = N->getOperand(2);
1035   DebugLoc dl = N->getDebugLoc();
1036   unsigned MaskLength = Mask.getValueType().getVectorNumElements();
1037   unsigned LargestMaskEntryPlusOne = 2 * MaskLength;
1038   unsigned MinimumBitWidth = Log2_32_Ceil(LargestMaskEntryPlusOne);
1039
1040   // Look for a legal vector type to place the mask values in.
1041   // Note that there may not be *any* legal vector-of-integer
1042   // type for which the element type is legal!
1043   for (MVT::SimpleValueType EltVT = MVT::FIRST_INTEGER_VALUETYPE;
1044        EltVT <= MVT::LAST_INTEGER_VALUETYPE;
1045        // Integer values types are consecutively numbered.  Exploit this.
1046        EltVT = MVT::SimpleValueType(EltVT + 1)) {
1047
1048     // Is the element type big enough to hold the values?
1049     if (MVT(EltVT).getSizeInBits() < MinimumBitWidth)
1050       // Nope.
1051       continue;
1052
1053     // Is the vector type legal?
1054     MVT VecVT = MVT::getVectorVT(EltVT, MaskLength);
1055     if (!isTypeLegal(VecVT))
1056       // Nope.
1057       continue;
1058
1059     // If the element type is not legal, find a larger legal type to use for
1060     // the BUILD_VECTOR operands.  This is an ugly hack, but seems to work!
1061     // FIXME: The real solution is to change VECTOR_SHUFFLE into a variadic
1062     // node where the shuffle mask is a list of integer operands, #2 .. #2+n.
1063     for (MVT::SimpleValueType OpVT = EltVT; OpVT <= MVT::LAST_INTEGER_VALUETYPE;
1064          // Integer values types are consecutively numbered.  Exploit this.
1065          OpVT = MVT::SimpleValueType(OpVT + 1)) {
1066       if (!isTypeLegal(OpVT))
1067         continue;
1068
1069       // Success!  Rebuild the vector using the legal types.
1070       SmallVector<SDValue, 16> Ops(MaskLength);
1071       for (unsigned i = 0; i < MaskLength; ++i) {
1072         SDValue Arg = Mask.getOperand(i);
1073         if (Arg.getOpcode() == ISD::UNDEF) {
1074           Ops[i] = DAG.getUNDEF(OpVT);
1075         } else {
1076           uint64_t Idx = cast<ConstantSDNode>(Arg)->getZExtValue();
1077           Ops[i] = DAG.getConstant(Idx, OpVT);
1078         }
1079       }
1080       return DAG.UpdateNodeOperands(SDValue(N,0),
1081                                     N->getOperand(0), N->getOperand(1),
1082                                     DAG.getBUILD_VECTOR(VecVT, dl,
1083                                                         &Ops[0], Ops.size()));
1084     }
1085
1086     // Continuing is pointless - failure is certain.
1087     break;
1088   }
1089   assert(false && "Failed to find an appropriate mask type!");
1090   return SDValue(N, 0);
1091 }
1092
1093
1094 //===----------------------------------------------------------------------===//
1095 //  Result Vector Widening
1096 //===----------------------------------------------------------------------===//
1097
1098 void DAGTypeLegalizer::WidenVectorResult(SDNode *N, unsigned ResNo) {
1099   DEBUG(cerr << "Widen node result " << ResNo << ": "; N->dump(&DAG);
1100         cerr << "\n");
1101   SDValue Res = SDValue();
1102
1103   switch (N->getOpcode()) {
1104   default:
1105 #ifndef NDEBUG
1106     cerr << "WidenVectorResult #" << ResNo << ": ";
1107     N->dump(&DAG); cerr << "\n";
1108 #endif
1109     assert(0 && "Do not know how to widen the result of this operator!");
1110     abort();
1111
1112   case ISD::BIT_CONVERT:       Res = WidenVecRes_BIT_CONVERT(N); break;
1113   case ISD::BUILD_VECTOR:      Res = WidenVecRes_BUILD_VECTOR(N); break;
1114   case ISD::CONCAT_VECTORS:    Res = WidenVecRes_CONCAT_VECTORS(N); break;
1115   case ISD::CONVERT_RNDSAT:    Res = WidenVecRes_CONVERT_RNDSAT(N); break;
1116   case ISD::EXTRACT_SUBVECTOR: Res = WidenVecRes_EXTRACT_SUBVECTOR(N); break;
1117   case ISD::INSERT_VECTOR_ELT: Res = WidenVecRes_INSERT_VECTOR_ELT(N); break;
1118   case ISD::LOAD:              Res = WidenVecRes_LOAD(N); break;
1119   case ISD::SCALAR_TO_VECTOR:  Res = WidenVecRes_SCALAR_TO_VECTOR(N); break;
1120   case ISD::SELECT:            Res = WidenVecRes_SELECT(N); break;
1121   case ISD::SELECT_CC:         Res = WidenVecRes_SELECT_CC(N); break;
1122   case ISD::UNDEF:             Res = WidenVecRes_UNDEF(N); break;
1123   case ISD::VECTOR_SHUFFLE:    Res = WidenVecRes_VECTOR_SHUFFLE(N); break;
1124   case ISD::VSETCC:            Res = WidenVecRes_VSETCC(N); break;
1125
1126   case ISD::ADD:
1127   case ISD::AND:
1128   case ISD::BSWAP:
1129   case ISD::FADD:
1130   case ISD::FCOPYSIGN:
1131   case ISD::FDIV:
1132   case ISD::FMUL:
1133   case ISD::FPOW:
1134   case ISD::FPOWI:
1135   case ISD::FREM:
1136   case ISD::FSUB:
1137   case ISD::MUL:
1138   case ISD::MULHS:
1139   case ISD::MULHU:
1140   case ISD::OR:
1141   case ISD::SDIV:
1142   case ISD::SREM:
1143   case ISD::UDIV:
1144   case ISD::UREM:
1145   case ISD::SUB:
1146   case ISD::XOR:               Res = WidenVecRes_Binary(N); break;
1147
1148   case ISD::SHL:
1149   case ISD::SRA:
1150   case ISD::SRL:               Res = WidenVecRes_Shift(N); break;
1151
1152   case ISD::ANY_EXTEND:
1153   case ISD::FP_ROUND:
1154   case ISD::FP_TO_SINT:
1155   case ISD::FP_TO_UINT:
1156   case ISD::SIGN_EXTEND:
1157   case ISD::SINT_TO_FP:
1158   case ISD::TRUNCATE:
1159   case ISD::ZERO_EXTEND:
1160   case ISD::UINT_TO_FP:        Res = WidenVecRes_Convert(N); break;
1161
1162   case ISD::CTLZ:
1163   case ISD::CTPOP:
1164   case ISD::CTTZ:
1165   case ISD::FABS:
1166   case ISD::FCOS:
1167   case ISD::FNEG:
1168   case ISD::FSIN:
1169   case ISD::FSQRT:             Res = WidenVecRes_Unary(N); break;
1170   }
1171
1172   // If Res is null, the sub-method took care of registering the result.
1173   if (Res.getNode())
1174     SetWidenedVector(SDValue(N, ResNo), Res);
1175 }
1176
1177 SDValue DAGTypeLegalizer::WidenVecRes_Binary(SDNode *N) {
1178   // Binary op widening.
1179   MVT WidenVT = TLI.getTypeToTransformTo(N->getValueType(0));
1180   SDValue InOp1 = GetWidenedVector(N->getOperand(0));
1181   SDValue InOp2 = GetWidenedVector(N->getOperand(1));
1182   return DAG.getNode(N->getOpcode(), N->getDebugLoc(), WidenVT, InOp1, InOp2);
1183 }
1184
1185 SDValue DAGTypeLegalizer::WidenVecRes_Convert(SDNode *N) {
1186   SDValue InOp = N->getOperand(0);
1187   DebugLoc dl = N->getDebugLoc();
1188
1189   MVT WidenVT = TLI.getTypeToTransformTo(N->getValueType(0));
1190   unsigned WidenNumElts = WidenVT.getVectorNumElements();
1191
1192   MVT InVT = InOp.getValueType();
1193   MVT InEltVT = InVT.getVectorElementType();
1194   MVT InWidenVT = MVT::getVectorVT(InEltVT, WidenNumElts);
1195
1196   unsigned Opcode = N->getOpcode();
1197   unsigned InVTNumElts = InVT.getVectorNumElements();
1198
1199   if (getTypeAction(InVT) == WidenVector) {
1200     InOp = GetWidenedVector(N->getOperand(0));
1201     InVT = InOp.getValueType();
1202     InVTNumElts = InVT.getVectorNumElements();
1203     if (InVTNumElts == WidenNumElts)
1204       return DAG.getNode(Opcode, dl, WidenVT, InOp);
1205   }
1206
1207   if (TLI.isTypeLegal(InWidenVT)) {
1208     // Because the result and the input are different vector types, widening
1209     // the result could create a legal type but widening the input might make
1210     // it an illegal type that might lead to repeatedly splitting the input
1211     // and then widening it. To avoid this, we widen the input only if
1212     // it results in a legal type.
1213     if (WidenNumElts % InVTNumElts == 0) {
1214       // Widen the input and call convert on the widened input vector.
1215       unsigned NumConcat = WidenNumElts/InVTNumElts;
1216       SmallVector<SDValue, 16> Ops(NumConcat);
1217       Ops[0] = InOp;
1218       SDValue UndefVal = DAG.getUNDEF(InVT);
1219       for (unsigned i = 1; i != NumConcat; ++i)
1220         Ops[i] = UndefVal;
1221       return DAG.getNode(Opcode, dl, WidenVT,
1222                          DAG.getNode(ISD::CONCAT_VECTORS, dl, InWidenVT,
1223                          &Ops[0], NumConcat));
1224     }
1225
1226     if (InVTNumElts % WidenNumElts == 0) {
1227       // Extract the input and convert the shorten input vector.
1228       return DAG.getNode(Opcode, dl, WidenVT,
1229                          DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, InWidenVT,
1230                                      InOp, DAG.getIntPtrConstant(0)));
1231     }
1232   }
1233
1234   // Otherwise unroll into some nasty scalar code and rebuild the vector.
1235   SmallVector<SDValue, 16> Ops(WidenNumElts);
1236   MVT EltVT = WidenVT.getVectorElementType();
1237   unsigned MinElts = std::min(InVTNumElts, WidenNumElts);
1238   unsigned i;
1239   for (i=0; i < MinElts; ++i)
1240     Ops[i] = DAG.getNode(Opcode, dl, EltVT,
1241                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, InEltVT, InOp,
1242                                      DAG.getIntPtrConstant(i)));
1243
1244   SDValue UndefVal = DAG.getUNDEF(EltVT);
1245   for (; i < WidenNumElts; ++i)
1246     Ops[i] = UndefVal;
1247
1248   return DAG.getBUILD_VECTOR(WidenVT, dl, &Ops[0], WidenNumElts);
1249 }
1250
1251 SDValue DAGTypeLegalizer::WidenVecRes_Shift(SDNode *N) {
1252   MVT WidenVT = TLI.getTypeToTransformTo(N->getValueType(0));
1253   SDValue InOp = GetWidenedVector(N->getOperand(0));
1254   SDValue ShOp = N->getOperand(1);
1255
1256   MVT ShVT = ShOp.getValueType();
1257   if (getTypeAction(ShVT) == WidenVector) {
1258     ShOp = GetWidenedVector(ShOp);
1259     ShVT = ShOp.getValueType();
1260   }
1261   MVT ShWidenVT = MVT::getVectorVT(ShVT.getVectorElementType(),
1262                                    WidenVT.getVectorNumElements());
1263   if (ShVT != ShWidenVT)
1264     ShOp = ModifyToType(ShOp, ShWidenVT);
1265
1266   return DAG.getNode(N->getOpcode(), N->getDebugLoc(), WidenVT, InOp, ShOp);
1267 }
1268
1269 SDValue DAGTypeLegalizer::WidenVecRes_Unary(SDNode *N) {
1270   // Unary op widening.
1271   MVT WidenVT = TLI.getTypeToTransformTo(N->getValueType(0));
1272   SDValue InOp = GetWidenedVector(N->getOperand(0));
1273   return DAG.getNode(N->getOpcode(), N->getDebugLoc(), WidenVT, InOp);
1274 }
1275
1276 SDValue DAGTypeLegalizer::WidenVecRes_BIT_CONVERT(SDNode *N) {
1277   SDValue InOp = N->getOperand(0);
1278   MVT InVT = InOp.getValueType();
1279   MVT VT = N->getValueType(0);
1280   MVT WidenVT = TLI.getTypeToTransformTo(VT);
1281   DebugLoc dl = N->getDebugLoc();
1282
1283   switch (getTypeAction(InVT)) {
1284   default:
1285     assert(false && "Unknown type action!");
1286     break;
1287   case Legal:
1288     break;
1289   case PromoteInteger:
1290     // If the InOp is promoted to the same size, convert it.  Otherwise,
1291     // fall out of the switch and widen the promoted input.
1292     InOp = GetPromotedInteger(InOp);
1293     InVT = InOp.getValueType();
1294     if (WidenVT.bitsEq(InVT))
1295       return DAG.getNode(ISD::BIT_CONVERT, dl, WidenVT, InOp);
1296     break;
1297   case SoftenFloat:
1298   case ExpandInteger:
1299   case ExpandFloat:
1300   case ScalarizeVector:
1301   case SplitVector:
1302     break;
1303   case WidenVector:
1304     // If the InOp is widened to the same size, convert it.  Otherwise, fall
1305     // out of the switch and widen the widened input.
1306     InOp = GetWidenedVector(InOp);
1307     InVT = InOp.getValueType();
1308     if (WidenVT.bitsEq(InVT))
1309       // The input widens to the same size. Convert to the widen value.
1310       return DAG.getNode(ISD::BIT_CONVERT, dl, WidenVT, InOp);
1311     break;
1312   }
1313
1314   unsigned WidenSize = WidenVT.getSizeInBits();
1315   unsigned InSize = InVT.getSizeInBits();
1316   if (WidenSize % InSize == 0) {
1317     // Determine new input vector type.  The new input vector type will use
1318     // the same element type (if its a vector) or use the input type as a
1319     // vector.  It is the same size as the type to widen to.
1320     MVT NewInVT;
1321     unsigned NewNumElts = WidenSize / InSize;
1322     if (InVT.isVector()) {
1323       MVT InEltVT = InVT.getVectorElementType();
1324       NewInVT= MVT::getVectorVT(InEltVT, WidenSize / InEltVT.getSizeInBits());
1325     } else {
1326       NewInVT = MVT::getVectorVT(InVT, NewNumElts);
1327     }
1328
1329     if (TLI.isTypeLegal(NewInVT)) {
1330       // Because the result and the input are different vector types, widening
1331       // the result could create a legal type but widening the input might make
1332       // it an illegal type that might lead to repeatedly splitting the input
1333       // and then widening it. To avoid this, we widen the input only if
1334       // it results in a legal type.
1335       SmallVector<SDValue, 16> Ops(NewNumElts);
1336       SDValue UndefVal = DAG.getUNDEF(InVT);
1337       Ops[0] = InOp;
1338       for (unsigned i = 1; i < NewNumElts; ++i)
1339         Ops[i] = UndefVal;
1340
1341       SDValue NewVec;
1342       if (InVT.isVector())
1343         NewVec = DAG.getNode(ISD::CONCAT_VECTORS, dl,
1344                              NewInVT, &Ops[0], NewNumElts);
1345       else
1346         NewVec = DAG.getBUILD_VECTOR(NewInVT, dl, &Ops[0], NewNumElts);
1347       return DAG.getNode(ISD::BIT_CONVERT, dl, WidenVT, NewVec);
1348     }
1349   }
1350
1351   // This should occur rarely. Lower the bit-convert to a store/load
1352   // from the stack. Create the stack frame object.  Make sure it is aligned
1353   // for both the source and destination types.
1354   SDValue FIPtr = DAG.CreateStackTemporary(InVT, WidenVT);
1355   int FI = cast<FrameIndexSDNode>(FIPtr.getNode())->getIndex();
1356   const Value *SV = PseudoSourceValue::getFixedStack(FI);
1357
1358   // Emit a store to the stack slot.
1359   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, InOp, FIPtr, SV, 0);
1360
1361   // Result is a load from the stack slot.
1362   return DAG.getLoad(WidenVT, dl, Store, FIPtr, SV, 0);
1363 }
1364
1365 SDValue DAGTypeLegalizer::WidenVecRes_BUILD_VECTOR(SDNode *N) {
1366   DebugLoc dl = N->getDebugLoc();
1367   // Build a vector with undefined for the new nodes.
1368   MVT VT = N->getValueType(0);
1369   MVT EltVT = VT.getVectorElementType();
1370   unsigned NumElts = VT.getVectorNumElements();
1371
1372   MVT WidenVT = TLI.getTypeToTransformTo(VT);
1373   unsigned WidenNumElts = WidenVT.getVectorNumElements();
1374
1375   SmallVector<SDValue, 16> NewOps(N->op_begin(), N->op_end());
1376   NewOps.reserve(WidenNumElts);
1377   for (unsigned i = NumElts; i < WidenNumElts; ++i)
1378     NewOps.push_back(DAG.getUNDEF(EltVT));
1379
1380   return DAG.getBUILD_VECTOR(WidenVT, dl, &NewOps[0], NewOps.size());
1381 }
1382
1383 SDValue DAGTypeLegalizer::WidenVecRes_CONCAT_VECTORS(SDNode *N) {
1384   MVT InVT = N->getOperand(0).getValueType();
1385   MVT WidenVT = TLI.getTypeToTransformTo(N->getValueType(0));
1386   DebugLoc dl = N->getDebugLoc();
1387   unsigned WidenNumElts = WidenVT.getVectorNumElements();
1388   unsigned NumOperands = N->getNumOperands();
1389
1390   bool InputWidened = false; // Indicates we need to widen the input.
1391   if (getTypeAction(InVT) != WidenVector) {
1392     if (WidenVT.getVectorNumElements() % InVT.getVectorNumElements() == 0) {
1393       // Add undef vectors to widen to correct length.
1394       unsigned NumConcat = WidenVT.getVectorNumElements() /
1395                            InVT.getVectorNumElements();
1396       SDValue UndefVal = DAG.getUNDEF(InVT);
1397       SmallVector<SDValue, 16> Ops(NumConcat);
1398       for (unsigned i=0; i < NumOperands; ++i)
1399         Ops[i] = N->getOperand(i);
1400       for (unsigned i = NumOperands; i != NumConcat; ++i)
1401         Ops[i] = UndefVal;
1402       return DAG.getNode(ISD::CONCAT_VECTORS, dl, WidenVT, &Ops[0], NumConcat);
1403     }
1404   } else {
1405     InputWidened = true;
1406     if (WidenVT == TLI.getTypeToTransformTo(InVT)) {
1407       // The inputs and the result are widen to the same value.
1408       unsigned i;
1409       for (i=1; i < NumOperands; ++i)
1410         if (N->getOperand(i).getOpcode() != ISD::UNDEF)
1411           break;
1412
1413       if (i > NumOperands)
1414         // Everything but the first operand is an UNDEF so just return the
1415         // widened first operand.
1416         return GetWidenedVector(N->getOperand(0));
1417
1418       if (NumOperands == 2) {
1419         // Replace concat of two operands with a shuffle.
1420         MVT PtrVT = TLI.getPointerTy();
1421         SmallVector<SDValue, 16> MaskOps(WidenNumElts);
1422         for (unsigned i=0; i < WidenNumElts/2; ++i) {
1423           MaskOps[i] = DAG.getConstant(i, PtrVT);
1424           MaskOps[i+WidenNumElts/2] = DAG.getConstant(i+WidenNumElts, PtrVT);
1425         }
1426         SDValue Mask =
1427                 DAG.getBUILD_VECTOR(MVT::getVectorVT(PtrVT, WidenNumElts), dl,
1428                                    &MaskOps[0], WidenNumElts);
1429         return DAG.getNode(ISD::VECTOR_SHUFFLE, dl, WidenVT,
1430                            GetWidenedVector(N->getOperand(0)),
1431                            GetWidenedVector(N->getOperand(1)), Mask);
1432       }
1433     }
1434   }
1435
1436   // Fall back to use extracts and build vector.
1437   MVT EltVT = WidenVT.getVectorElementType();
1438   unsigned NumInElts = InVT.getVectorNumElements();
1439   SmallVector<SDValue, 16> Ops(WidenNumElts);
1440   unsigned Idx = 0;
1441   for (unsigned i=0; i < NumOperands; ++i) {
1442     SDValue InOp = N->getOperand(i);
1443     if (InputWidened)
1444       InOp = GetWidenedVector(InOp);
1445     for (unsigned j=0; j < NumInElts; ++j)
1446         Ops[Idx++] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, InOp,
1447                                  DAG.getIntPtrConstant(j));
1448   }
1449   SDValue UndefVal = DAG.getUNDEF(EltVT);
1450   for (; Idx < WidenNumElts; ++Idx)
1451     Ops[Idx] = UndefVal;
1452   return DAG.getBUILD_VECTOR(WidenVT, dl, &Ops[0], WidenNumElts);
1453 }
1454
1455 SDValue DAGTypeLegalizer::WidenVecRes_CONVERT_RNDSAT(SDNode *N) {
1456   DebugLoc dl = N->getDebugLoc();
1457   SDValue InOp  = N->getOperand(0);
1458   SDValue RndOp = N->getOperand(3);
1459   SDValue SatOp = N->getOperand(4);
1460
1461   MVT      WidenVT = TLI.getTypeToTransformTo(N->getValueType(0));
1462   unsigned WidenNumElts = WidenVT.getVectorNumElements();
1463
1464   MVT InVT = InOp.getValueType();
1465   MVT InEltVT = InVT.getVectorElementType();
1466   MVT InWidenVT = MVT::getVectorVT(InEltVT, WidenNumElts);
1467
1468   SDValue DTyOp = DAG.getValueType(WidenVT);
1469   SDValue STyOp = DAG.getValueType(InWidenVT);
1470   ISD::CvtCode CvtCode = cast<CvtRndSatSDNode>(N)->getCvtCode();
1471
1472   unsigned InVTNumElts = InVT.getVectorNumElements();
1473   if (getTypeAction(InVT) == WidenVector) {
1474     InOp = GetWidenedVector(InOp);
1475     InVT = InOp.getValueType();
1476     InVTNumElts = InVT.getVectorNumElements();
1477     if (InVTNumElts == WidenNumElts)
1478       return DAG.getConvertRndSat(WidenVT, dl, InOp, DTyOp, STyOp, RndOp,
1479                                   SatOp, CvtCode);
1480   }
1481
1482   if (TLI.isTypeLegal(InWidenVT)) {
1483     // Because the result and the input are different vector types, widening
1484     // the result could create a legal type but widening the input might make
1485     // it an illegal type that might lead to repeatedly splitting the input
1486     // and then widening it. To avoid this, we widen the input only if
1487     // it results in a legal type.
1488     if (WidenNumElts % InVTNumElts == 0) {
1489       // Widen the input and call convert on the widened input vector.
1490       unsigned NumConcat = WidenNumElts/InVTNumElts;
1491       SmallVector<SDValue, 16> Ops(NumConcat);
1492       Ops[0] = InOp;
1493       SDValue UndefVal = DAG.getUNDEF(InVT);
1494       for (unsigned i = 1; i != NumConcat; ++i) {
1495         Ops[i] = UndefVal;
1496       }
1497       InOp = DAG.getNode(ISD::CONCAT_VECTORS, dl, InWidenVT, &Ops[0],NumConcat);
1498       return DAG.getConvertRndSat(WidenVT, dl, InOp, DTyOp, STyOp, RndOp,
1499                                   SatOp, CvtCode);
1500     }
1501
1502     if (InVTNumElts % WidenNumElts == 0) {
1503       // Extract the input and convert the shorten input vector.
1504       InOp = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, InWidenVT, InOp,
1505                          DAG.getIntPtrConstant(0));
1506       return DAG.getConvertRndSat(WidenVT, dl, InOp, DTyOp, STyOp, RndOp,
1507                                 SatOp, CvtCode);
1508     }
1509   }
1510
1511   // Otherwise unroll into some nasty scalar code and rebuild the vector.
1512   SmallVector<SDValue, 16> Ops(WidenNumElts);
1513   MVT EltVT = WidenVT.getVectorElementType();
1514   DTyOp = DAG.getValueType(EltVT);
1515   STyOp = DAG.getValueType(InEltVT);
1516
1517   unsigned MinElts = std::min(InVTNumElts, WidenNumElts);
1518   unsigned i;
1519   for (i=0; i < MinElts; ++i) {
1520     SDValue ExtVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, InEltVT, InOp,
1521                                  DAG.getIntPtrConstant(i));
1522     Ops[i] = DAG.getConvertRndSat(WidenVT, dl, ExtVal, DTyOp, STyOp, RndOp,
1523                                         SatOp, CvtCode);
1524   }
1525
1526   SDValue UndefVal = DAG.getUNDEF(EltVT);
1527   for (; i < WidenNumElts; ++i)
1528     Ops[i] = UndefVal;
1529
1530   return DAG.getBUILD_VECTOR(WidenVT, dl, &Ops[0], WidenNumElts);
1531 }
1532
1533 SDValue DAGTypeLegalizer::WidenVecRes_EXTRACT_SUBVECTOR(SDNode *N) {
1534   MVT      VT = N->getValueType(0);
1535   MVT      WidenVT = TLI.getTypeToTransformTo(VT);
1536   unsigned WidenNumElts = WidenVT.getVectorNumElements();
1537   SDValue  InOp = N->getOperand(0);
1538   SDValue  Idx  = N->getOperand(1);
1539   DebugLoc dl = N->getDebugLoc();
1540
1541   if (getTypeAction(InOp.getValueType()) == WidenVector)
1542     InOp = GetWidenedVector(InOp);
1543
1544   MVT InVT = InOp.getValueType();
1545
1546   ConstantSDNode *CIdx = dyn_cast<ConstantSDNode>(Idx);
1547   if (CIdx) {
1548     unsigned IdxVal = CIdx->getZExtValue();
1549     // Check if we can just return the input vector after widening.
1550     if (IdxVal == 0 && InVT == WidenVT)
1551       return InOp;
1552
1553     // Check if we can extract from the vector.
1554     unsigned InNumElts = InVT.getVectorNumElements();
1555     if (IdxVal % WidenNumElts == 0 && IdxVal + WidenNumElts < InNumElts)
1556         return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, WidenVT, InOp, Idx);
1557   }
1558
1559   // We could try widening the input to the right length but for now, extract
1560   // the original elements, fill the rest with undefs and build a vector.
1561   SmallVector<SDValue, 16> Ops(WidenNumElts);
1562   MVT EltVT = VT.getVectorElementType();
1563   MVT IdxVT = Idx.getValueType();
1564   unsigned NumElts = VT.getVectorNumElements();
1565   unsigned i;
1566   if (CIdx) {
1567     unsigned IdxVal = CIdx->getZExtValue();
1568     for (i=0; i < NumElts; ++i)
1569       Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, InOp,
1570                            DAG.getConstant(IdxVal+i, IdxVT));
1571   } else {
1572     Ops[0] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, InOp, Idx);
1573     for (i=1; i < NumElts; ++i) {
1574       SDValue NewIdx = DAG.getNode(ISD::ADD, dl, Idx.getValueType(), Idx,
1575                                    DAG.getConstant(i, IdxVT));
1576       Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, InOp, NewIdx);
1577     }
1578   }
1579
1580   SDValue UndefVal = DAG.getUNDEF(EltVT);
1581   for (; i < WidenNumElts; ++i)
1582     Ops[i] = UndefVal;
1583   return DAG.getBUILD_VECTOR(WidenVT, dl, &Ops[0], WidenNumElts);
1584 }
1585
1586 SDValue DAGTypeLegalizer::WidenVecRes_INSERT_VECTOR_ELT(SDNode *N) {
1587   SDValue InOp = GetWidenedVector(N->getOperand(0));
1588   return DAG.getNode(ISD::INSERT_VECTOR_ELT, N->getDebugLoc(),
1589                      InOp.getValueType(), InOp,
1590                      N->getOperand(1), N->getOperand(2));
1591 }
1592
1593 SDValue DAGTypeLegalizer::WidenVecRes_LOAD(SDNode *N) {
1594   LoadSDNode *LD = cast<LoadSDNode>(N);
1595   MVT WidenVT = TLI.getTypeToTransformTo(LD->getValueType(0));
1596   MVT LdVT    = LD->getMemoryVT();
1597   DebugLoc dl = N->getDebugLoc();
1598   assert(LdVT.isVector() && WidenVT.isVector());
1599
1600   // Load information
1601   SDValue   Chain = LD->getChain();
1602   SDValue   BasePtr = LD->getBasePtr();
1603   int       SVOffset = LD->getSrcValueOffset();
1604   unsigned  Align    = LD->getAlignment();
1605   bool      isVolatile = LD->isVolatile();
1606   const Value *SV = LD->getSrcValue();
1607   ISD::LoadExtType ExtType = LD->getExtensionType();
1608
1609   SDValue Result;
1610   SmallVector<SDValue, 16> LdChain;  // Chain for the series of load
1611   if (ExtType != ISD::NON_EXTLOAD) {
1612     // For extension loads, we can not play the tricks of chopping legal
1613     // vector types and bit cast it to the right type.  Instead, we unroll
1614     // the load and build a vector.
1615     MVT EltVT = WidenVT.getVectorElementType();
1616     MVT LdEltVT = LdVT.getVectorElementType();
1617     unsigned NumElts = LdVT.getVectorNumElements();
1618
1619     // Load each element and widen
1620     unsigned WidenNumElts = WidenVT.getVectorNumElements();
1621     SmallVector<SDValue, 16> Ops(WidenNumElts);
1622     unsigned Increment = LdEltVT.getSizeInBits() / 8;
1623     Ops[0] = DAG.getExtLoad(ExtType, dl, EltVT, Chain, BasePtr, SV, SVOffset,
1624                             LdEltVT, isVolatile, Align);
1625     LdChain.push_back(Ops[0].getValue(1));
1626     unsigned i = 0, Offset = Increment;
1627     for (i=1; i < NumElts; ++i, Offset += Increment) {
1628       SDValue NewBasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(),
1629                                        BasePtr, DAG.getIntPtrConstant(Offset));
1630       Ops[i] = DAG.getExtLoad(ExtType, dl, EltVT, Chain, NewBasePtr, SV,
1631                               SVOffset + Offset, LdEltVT, isVolatile, Align);
1632       LdChain.push_back(Ops[i].getValue(1));
1633     }
1634
1635     // Fill the rest with undefs
1636     SDValue UndefVal = DAG.getUNDEF(EltVT);
1637     for (; i != WidenNumElts; ++i)
1638       Ops[i] = UndefVal;
1639
1640     Result =  DAG.getBUILD_VECTOR(WidenVT, dl, &Ops[0], Ops.size());
1641   } else {
1642     assert(LdVT.getVectorElementType() == WidenVT.getVectorElementType());
1643     unsigned int LdWidth = LdVT.getSizeInBits();
1644     Result = GenWidenVectorLoads(LdChain, Chain, BasePtr, SV, SVOffset,
1645                                  Align, isVolatile, LdWidth, WidenVT, dl);
1646   }
1647
1648  // If we generate a single load, we can use that for the chain.  Otherwise,
1649  // build a factor node to remember the multiple loads are independent and
1650  // chain to that.
1651  SDValue NewChain;
1652  if (LdChain.size() == 1)
1653    NewChain = LdChain[0];
1654  else
1655    NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &LdChain[0],
1656                           LdChain.size());
1657
1658   // Modified the chain - switch anything that used the old chain to use
1659   // the new one.
1660   ReplaceValueWith(SDValue(N, 1), Chain);
1661
1662   return Result;
1663 }
1664
1665 SDValue DAGTypeLegalizer::WidenVecRes_SCALAR_TO_VECTOR(SDNode *N) {
1666   MVT WidenVT = TLI.getTypeToTransformTo(N->getValueType(0));
1667   return DAG.getNode(ISD::SCALAR_TO_VECTOR, N->getDebugLoc(),
1668                      WidenVT, N->getOperand(0));
1669 }
1670
1671 SDValue DAGTypeLegalizer::WidenVecRes_SELECT(SDNode *N) {
1672   MVT WidenVT = TLI.getTypeToTransformTo(N->getValueType(0));
1673   unsigned WidenNumElts = WidenVT.getVectorNumElements();
1674
1675   SDValue Cond1 = N->getOperand(0);
1676   MVT CondVT = Cond1.getValueType();
1677   if (CondVT.isVector()) {
1678     MVT CondEltVT = CondVT.getVectorElementType();
1679     MVT CondWidenVT =  MVT::getVectorVT(CondEltVT, WidenNumElts);
1680     if (getTypeAction(CondVT) == WidenVector)
1681       Cond1 = GetWidenedVector(Cond1);
1682
1683     if (Cond1.getValueType() != CondWidenVT)
1684        Cond1 = ModifyToType(Cond1, CondWidenVT);
1685   }
1686
1687   SDValue InOp1 = GetWidenedVector(N->getOperand(1));
1688   SDValue InOp2 = GetWidenedVector(N->getOperand(2));
1689   assert(InOp1.getValueType() == WidenVT && InOp2.getValueType() == WidenVT);
1690   return DAG.getNode(ISD::SELECT, N->getDebugLoc(),
1691                      WidenVT, Cond1, InOp1, InOp2);
1692 }
1693
1694 SDValue DAGTypeLegalizer::WidenVecRes_SELECT_CC(SDNode *N) {
1695   SDValue InOp1 = GetWidenedVector(N->getOperand(2));
1696   SDValue InOp2 = GetWidenedVector(N->getOperand(3));
1697   return DAG.getNode(ISD::SELECT_CC, N->getDebugLoc(),
1698                      InOp1.getValueType(), N->getOperand(0),
1699                      N->getOperand(1), InOp1, InOp2, N->getOperand(4));
1700 }
1701
1702 SDValue DAGTypeLegalizer::WidenVecRes_UNDEF(SDNode *N) {
1703  MVT WidenVT = TLI.getTypeToTransformTo(N->getValueType(0));
1704  return DAG.getUNDEF(WidenVT);
1705 }
1706
1707 SDValue DAGTypeLegalizer::WidenVecRes_VECTOR_SHUFFLE(SDNode *N) {
1708   MVT VT = N->getValueType(0);
1709   unsigned NumElts = VT.getVectorNumElements();
1710   DebugLoc dl = N->getDebugLoc();
1711
1712   MVT WidenVT = TLI.getTypeToTransformTo(VT);
1713   unsigned WidenNumElts = WidenVT.getVectorNumElements();
1714
1715   SDValue InOp1 = GetWidenedVector(N->getOperand(0));
1716   SDValue InOp2 = GetWidenedVector(N->getOperand(1));
1717
1718   // Adjust mask based on new input vector length.
1719   SDValue Mask = N->getOperand(2);
1720   SmallVector<SDValue, 16> MaskOps(WidenNumElts);
1721   MVT IdxVT = Mask.getValueType().getVectorElementType();
1722   for (unsigned i = 0; i < NumElts; ++i) {
1723     SDValue Arg = Mask.getOperand(i);
1724     if (Arg.getOpcode() == ISD::UNDEF)
1725       MaskOps[i] = Arg;
1726     else {
1727       unsigned Idx = cast<ConstantSDNode>(Arg)->getZExtValue();
1728       if (Idx < NumElts)
1729         MaskOps[i] = Arg;
1730       else
1731         MaskOps[i] = DAG.getConstant(Idx - NumElts + WidenNumElts, IdxVT);
1732     }
1733   }
1734   for (unsigned i = NumElts; i < WidenNumElts; ++i)
1735     MaskOps[i] = DAG.getUNDEF(IdxVT);
1736   SDValue NewMask = DAG.getBUILD_VECTOR(MVT::getVectorVT(IdxVT, WidenNumElts),
1737                                         dl, &MaskOps[0], WidenNumElts);
1738
1739   return DAG.getNode(ISD::VECTOR_SHUFFLE, dl, WidenVT, InOp1, InOp2, NewMask);
1740 }
1741
1742 SDValue DAGTypeLegalizer::WidenVecRes_VSETCC(SDNode *N) {
1743   MVT WidenVT = TLI.getTypeToTransformTo(N->getValueType(0));
1744   unsigned WidenNumElts = WidenVT.getVectorNumElements();
1745
1746   SDValue InOp1 = N->getOperand(0);
1747   MVT InVT = InOp1.getValueType();
1748   assert(InVT.isVector() && "can not widen non vector type");
1749   MVT WidenInVT = MVT::getVectorVT(InVT.getVectorElementType(), WidenNumElts);
1750   InOp1 = GetWidenedVector(InOp1);
1751   SDValue InOp2 = GetWidenedVector(N->getOperand(1));
1752
1753   // Assume that the input and output will be widen appropriately.  If not,
1754   // we will have to unroll it at some point.
1755   assert(InOp1.getValueType() == WidenInVT &&
1756          InOp2.getValueType() == WidenInVT &&
1757          "Input not widened to expected type!");
1758   return DAG.getNode(ISD::VSETCC, N->getDebugLoc(),
1759                      WidenVT, InOp1, InOp2, N->getOperand(2));
1760 }
1761
1762
1763 //===----------------------------------------------------------------------===//
1764 // Widen Vector Operand
1765 //===----------------------------------------------------------------------===//
1766 bool DAGTypeLegalizer::WidenVectorOperand(SDNode *N, unsigned ResNo) {
1767   DEBUG(cerr << "Widen node operand " << ResNo << ": "; N->dump(&DAG);
1768         cerr << "\n");
1769   SDValue Res = SDValue();
1770
1771   switch (N->getOpcode()) {
1772   default:
1773 #ifndef NDEBUG
1774     cerr << "WidenVectorOperand op #" << ResNo << ": ";
1775     N->dump(&DAG); cerr << "\n";
1776 #endif
1777     assert(0 && "Do not know how to widen this operator's operand!");
1778     abort();
1779
1780   case ISD::BIT_CONVERT:        Res = WidenVecOp_BIT_CONVERT(N); break;
1781   case ISD::CONCAT_VECTORS:     Res = WidenVecOp_CONCAT_VECTORS(N); break;
1782   case ISD::EXTRACT_VECTOR_ELT: Res = WidenVecOp_EXTRACT_VECTOR_ELT(N); break;
1783   case ISD::STORE:              Res = WidenVecOp_STORE(N); break;
1784
1785   case ISD::FP_ROUND:
1786   case ISD::FP_TO_SINT:
1787   case ISD::FP_TO_UINT:
1788   case ISD::SINT_TO_FP:
1789   case ISD::TRUNCATE:
1790   case ISD::UINT_TO_FP:         Res = WidenVecOp_Convert(N); break;
1791   }
1792
1793   // If Res is null, the sub-method took care of registering the result.
1794   if (!Res.getNode()) return false;
1795
1796   // If the result is N, the sub-method updated N in place.  Tell the legalizer
1797   // core about this.
1798   if (Res.getNode() == N)
1799     return true;
1800
1801
1802   assert(Res.getValueType() == N->getValueType(0) && N->getNumValues() == 1 &&
1803          "Invalid operand expansion");
1804
1805   ReplaceValueWith(SDValue(N, 0), Res);
1806   return false;
1807 }
1808
1809 SDValue DAGTypeLegalizer::WidenVecOp_Convert(SDNode *N) {
1810   // Since the result is legal and the input is illegal, it is unlikely
1811   // that we can fix the input to a legal type so unroll the convert
1812   // into some scalar code and create a nasty build vector.
1813   MVT VT = N->getValueType(0);
1814   MVT EltVT = VT.getVectorElementType();
1815   DebugLoc dl = N->getDebugLoc();
1816   unsigned NumElts = VT.getVectorNumElements();
1817   SDValue InOp = N->getOperand(0);
1818   if (getTypeAction(InOp.getValueType()) == WidenVector)
1819     InOp = GetWidenedVector(InOp);
1820   MVT InVT = InOp.getValueType();
1821   MVT InEltVT = InVT.getVectorElementType();
1822
1823   unsigned Opcode = N->getOpcode();
1824   SmallVector<SDValue, 16> Ops(NumElts);
1825   for (unsigned i=0; i < NumElts; ++i)
1826     Ops[i] = DAG.getNode(Opcode, dl, EltVT,
1827                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, InEltVT, InOp,
1828                                      DAG.getIntPtrConstant(i)));
1829
1830   return DAG.getBUILD_VECTOR(VT, dl, &Ops[0], NumElts);
1831 }
1832
1833 SDValue DAGTypeLegalizer::WidenVecOp_BIT_CONVERT(SDNode *N) {
1834   MVT VT = N->getValueType(0);
1835   SDValue InOp = GetWidenedVector(N->getOperand(0));
1836   MVT InWidenVT = InOp.getValueType();
1837   DebugLoc dl = N->getDebugLoc();
1838
1839   // Check if we can convert between two legal vector types and extract.
1840   unsigned InWidenSize = InWidenVT.getSizeInBits();
1841   unsigned Size = VT.getSizeInBits();
1842   if (InWidenSize % Size == 0 && !VT.isVector()) {
1843     unsigned NewNumElts = InWidenSize / Size;
1844     MVT NewVT = MVT::getVectorVT(VT, NewNumElts);
1845     if (TLI.isTypeLegal(NewVT)) {
1846       SDValue BitOp = DAG.getNode(ISD::BIT_CONVERT, dl, NewVT, InOp);
1847       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, BitOp,
1848                          DAG.getIntPtrConstant(0));
1849     }
1850   }
1851
1852   // Lower the bit-convert to a store/load from the stack. Create the stack
1853   // frame object.  Make sure it is aligned for both the source and destination
1854   // types.
1855   SDValue FIPtr = DAG.CreateStackTemporary(InWidenVT, VT);
1856   int FI = cast<FrameIndexSDNode>(FIPtr.getNode())->getIndex();
1857   const Value *SV = PseudoSourceValue::getFixedStack(FI);
1858
1859   // Emit a store to the stack slot.
1860   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, InOp, FIPtr, SV, 0);
1861
1862   // Result is a load from the stack slot.
1863   return DAG.getLoad(VT, dl, Store, FIPtr, SV, 0);
1864 }
1865
1866 SDValue DAGTypeLegalizer::WidenVecOp_CONCAT_VECTORS(SDNode *N) {
1867   // If the input vector is not legal, it is likely that we will not find a
1868   // legal vector of the same size. Replace the concatenate vector with a
1869   // nasty build vector.
1870   MVT VT = N->getValueType(0);
1871   MVT EltVT = VT.getVectorElementType();
1872   DebugLoc dl = N->getDebugLoc();
1873   unsigned NumElts = VT.getVectorNumElements();
1874   SmallVector<SDValue, 16> Ops(NumElts);
1875
1876   MVT InVT = N->getOperand(0).getValueType();
1877   unsigned NumInElts = InVT.getVectorNumElements();
1878
1879   unsigned Idx = 0;
1880   unsigned NumOperands = N->getNumOperands();
1881   for (unsigned i=0; i < NumOperands; ++i) {
1882     SDValue InOp = N->getOperand(i);
1883     if (getTypeAction(InOp.getValueType()) == WidenVector)
1884       InOp = GetWidenedVector(InOp);
1885     for (unsigned j=0; j < NumInElts; ++j)
1886       Ops[Idx++] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, InOp,
1887                                DAG.getIntPtrConstant(j));
1888   }
1889   return DAG.getBUILD_VECTOR(VT, dl, &Ops[0], NumElts);
1890 }
1891
1892 SDValue DAGTypeLegalizer::WidenVecOp_EXTRACT_VECTOR_ELT(SDNode *N) {
1893   SDValue InOp = GetWidenedVector(N->getOperand(0));
1894   MVT EltVT = InOp.getValueType().getVectorElementType();
1895   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, N->getDebugLoc(),
1896                      EltVT, InOp, N->getOperand(1));
1897 }
1898
1899 SDValue DAGTypeLegalizer::WidenVecOp_STORE(SDNode *N) {
1900   // We have to widen the value but we want only to store the original
1901   // vector type.
1902   StoreSDNode *ST = cast<StoreSDNode>(N);
1903   SDValue  Chain = ST->getChain();
1904   SDValue  BasePtr = ST->getBasePtr();
1905   const    Value *SV = ST->getSrcValue();
1906   int      SVOffset = ST->getSrcValueOffset();
1907   unsigned Align = ST->getAlignment();
1908   bool     isVolatile = ST->isVolatile();
1909   SDValue  ValOp = GetWidenedVector(ST->getValue());
1910   DebugLoc dl = N->getDebugLoc();
1911
1912   MVT StVT = ST->getMemoryVT();
1913   MVT ValVT = ValOp.getValueType();
1914   // It must be true that we the widen vector type is bigger than where
1915   // we need to store.
1916   assert(StVT.isVector() && ValOp.getValueType().isVector());
1917   assert(StVT.bitsLT(ValOp.getValueType()));
1918
1919   SmallVector<SDValue, 16> StChain;
1920   if (ST->isTruncatingStore()) {
1921     // For truncating stores, we can not play the tricks of chopping legal
1922     // vector types and bit cast it to the right type.  Instead, we unroll
1923     // the store.
1924     MVT StEltVT  = StVT.getVectorElementType();
1925     MVT ValEltVT = ValVT.getVectorElementType();
1926     unsigned Increment = ValEltVT.getSizeInBits() / 8;
1927     unsigned NumElts = StVT.getVectorNumElements();
1928     SDValue EOp = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ValEltVT, ValOp,
1929                               DAG.getIntPtrConstant(0));
1930     StChain.push_back(DAG.getTruncStore(Chain, dl, EOp, BasePtr, SV,
1931                                         SVOffset, StEltVT,
1932                                         isVolatile, Align));
1933     unsigned Offset = Increment;
1934     for (unsigned i=1; i < NumElts; ++i, Offset += Increment) {
1935       SDValue NewBasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(),
1936                                        BasePtr, DAG.getIntPtrConstant(Offset));
1937       SDValue EOp = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ValEltVT, ValOp,
1938                               DAG.getIntPtrConstant(0));
1939       StChain.push_back(DAG.getTruncStore(Chain, dl, EOp, NewBasePtr, SV,
1940                                           SVOffset + Offset, StEltVT,
1941                                           isVolatile, MinAlign(Align, Offset)));
1942     }
1943   }
1944   else {
1945     assert(StVT.getVectorElementType() == ValVT.getVectorElementType());
1946     // Store value
1947     GenWidenVectorStores(StChain, Chain, BasePtr, SV, SVOffset,
1948                          Align, isVolatile, ValOp, StVT.getSizeInBits(), dl);
1949   }
1950   if (StChain.size() == 1)
1951     return StChain[0];
1952   else
1953     return DAG.getNode(ISD::TokenFactor, dl,
1954                        MVT::Other,&StChain[0],StChain.size());
1955 }
1956
1957 //===----------------------------------------------------------------------===//
1958 // Vector Widening Utilities
1959 //===----------------------------------------------------------------------===//
1960
1961
1962 // Utility function to find a vector type and its associated element
1963 // type from a preferred width and whose vector type must be the same size
1964 // as the VecVT.
1965 //  TLI:   Target lowering used to determine legal types.
1966 //  Width: Preferred width to store.
1967 //  VecVT: Vector value type whose size we must match.
1968 // Returns NewVecVT and NewEltVT - the vector type and its associated
1969 // element type.
1970 static void FindAssocWidenVecType(const TargetLowering &TLI, unsigned Width,
1971                                   MVT VecVT,
1972                                   MVT& NewEltVT, MVT& NewVecVT) {
1973   unsigned EltWidth = Width + 1;
1974   if (TLI.isTypeLegal(VecVT)) {
1975     // We start with the preferred with, making it a power of 2 and find a
1976     // legal vector type of that width.  If not, we reduce it by another of 2.
1977     // For incoming type is legal, this process will end as a vector of the
1978     // smallest loadable type should always be legal.
1979     do {
1980       assert(EltWidth > 0);
1981       EltWidth = 1 << Log2_32(EltWidth - 1);
1982       NewEltVT = MVT::getIntegerVT(EltWidth);
1983       unsigned NumElts = VecVT.getSizeInBits() / EltWidth;
1984       NewVecVT = MVT::getVectorVT(NewEltVT, NumElts);
1985     } while (!TLI.isTypeLegal(NewVecVT) ||
1986              VecVT.getSizeInBits() != NewVecVT.getSizeInBits());
1987   } else {
1988     // The incoming vector type is illegal and is the result of widening
1989     // a vector to a power of 2. In this case, we will use the preferred
1990     // with as long as it is a multiple of the incoming vector length.
1991     // The legalization process will eventually make this into a legal type
1992     // and remove the illegal bit converts (which would turn to stack converts
1993     // if they are allow to exist).
1994      do {
1995       assert(EltWidth > 0);
1996       EltWidth = 1 << Log2_32(EltWidth - 1);
1997       NewEltVT = MVT::getIntegerVT(EltWidth);
1998       unsigned NumElts = VecVT.getSizeInBits() / EltWidth;
1999       NewVecVT = MVT::getVectorVT(NewEltVT, NumElts);
2000     } while (!TLI.isTypeLegal(NewEltVT) ||
2001              VecVT.getSizeInBits() != NewVecVT.getSizeInBits());
2002   }
2003 }
2004
2005 SDValue DAGTypeLegalizer::GenWidenVectorLoads(SmallVector<SDValue, 16>& LdChain,
2006                                               SDValue      Chain,
2007                                               SDValue      BasePtr,
2008                                               const Value *SV,
2009                                               int          SVOffset,
2010                                               unsigned     Alignment,
2011                                               bool         isVolatile,
2012                                               unsigned     LdWidth,
2013                                               MVT          ResType,
2014                                               DebugLoc     dl) {
2015   // The strategy assumes that we can efficiently load powers of two widths.
2016   // The routines chops the vector into the largest power of 2 load and
2017   // can be inserted into a legal vector and then cast the result into the
2018   // vector type we want.  This avoids unnecessary stack converts.
2019
2020   // TODO: If the Ldwidth is legal, alignment is the same as the LdWidth, and
2021   //       the load is nonvolatile, we an use a wider load for the value.
2022
2023   // Find the vector type that can load from.
2024   MVT NewEltVT, NewVecVT;
2025   unsigned NewEltVTWidth;
2026   FindAssocWidenVecType(TLI, LdWidth, ResType, NewEltVT, NewVecVT);
2027   NewEltVTWidth = NewEltVT.getSizeInBits();
2028
2029   SDValue LdOp = DAG.getLoad(NewEltVT, dl, Chain, BasePtr, SV, SVOffset,
2030                              isVolatile, Alignment);
2031   SDValue VecOp = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NewVecVT, LdOp);
2032   LdChain.push_back(LdOp.getValue(1));
2033
2034   // Check if we can load the element with one instruction
2035   if (LdWidth == NewEltVTWidth) {
2036     return DAG.getNode(ISD::BIT_CONVERT, dl, ResType, VecOp);
2037   }
2038
2039   unsigned Idx = 1;
2040   LdWidth -= NewEltVTWidth;
2041   unsigned Offset = 0;
2042
2043   while (LdWidth > 0) {
2044     unsigned Increment = NewEltVTWidth / 8;
2045     Offset += Increment;
2046     BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
2047                           DAG.getIntPtrConstant(Increment));
2048
2049     if (LdWidth < NewEltVTWidth) {
2050       // Our current type we are using is too large, use a smaller size by
2051       // using a smaller power of 2
2052       unsigned oNewEltVTWidth = NewEltVTWidth;
2053       FindAssocWidenVecType(TLI, LdWidth, ResType, NewEltVT, NewVecVT);
2054       NewEltVTWidth = NewEltVT.getSizeInBits();
2055       // Readjust position and vector position based on new load type
2056       Idx = Idx * (oNewEltVTWidth/NewEltVTWidth);
2057       VecOp = DAG.getNode(ISD::BIT_CONVERT, dl, NewVecVT, VecOp);
2058     }
2059
2060     SDValue LdOp = DAG.getLoad(NewEltVT, dl, Chain, BasePtr, SV,
2061                                  SVOffset+Offset, isVolatile,
2062                                  MinAlign(Alignment, Offset));
2063     LdChain.push_back(LdOp.getValue(1));
2064     VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, NewVecVT, VecOp, LdOp,
2065                         DAG.getIntPtrConstant(Idx++));
2066
2067     LdWidth -= NewEltVTWidth;
2068   }
2069
2070   return DAG.getNode(ISD::BIT_CONVERT, dl, ResType, VecOp);
2071 }
2072
2073 void DAGTypeLegalizer::GenWidenVectorStores(SmallVector<SDValue, 16>& StChain,
2074                                             SDValue   Chain,
2075                                             SDValue   BasePtr,
2076                                             const Value *SV,
2077                                             int         SVOffset,
2078                                             unsigned    Alignment,
2079                                             bool        isVolatile,
2080                                             SDValue     ValOp,
2081                                             unsigned    StWidth,
2082                                             DebugLoc    dl) {
2083   // Breaks the stores into a series of power of 2 width stores.  For any
2084   // width, we convert the vector to the vector of element size that we
2085   // want to store.  This avoids requiring a stack convert.
2086
2087   // Find a width of the element type we can store with
2088   MVT WidenVT = ValOp.getValueType();
2089   MVT NewEltVT, NewVecVT;
2090
2091   FindAssocWidenVecType(TLI, StWidth, WidenVT, NewEltVT, NewVecVT);
2092   unsigned NewEltVTWidth = NewEltVT.getSizeInBits();
2093
2094   SDValue VecOp = DAG.getNode(ISD::BIT_CONVERT, dl, NewVecVT, ValOp);
2095   SDValue EOp = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, NewEltVT, VecOp,
2096                             DAG.getIntPtrConstant(0));
2097   SDValue StOp = DAG.getStore(Chain, dl, EOp, BasePtr, SV, SVOffset,
2098                                isVolatile, Alignment);
2099   StChain.push_back(StOp);
2100
2101   // Check if we are done
2102   if (StWidth == NewEltVTWidth) {
2103     return;
2104   }
2105
2106   unsigned Idx = 1;
2107   StWidth -= NewEltVTWidth;
2108   unsigned Offset = 0;
2109
2110   while (StWidth > 0) {
2111     unsigned Increment = NewEltVTWidth / 8;
2112     Offset += Increment;
2113     BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
2114                           DAG.getIntPtrConstant(Increment));
2115
2116     if (StWidth < NewEltVTWidth) {
2117       // Our current type we are using is too large, use a smaller size by
2118       // using a smaller power of 2
2119       unsigned oNewEltVTWidth = NewEltVTWidth;
2120       FindAssocWidenVecType(TLI, StWidth, WidenVT, NewEltVT, NewVecVT);
2121       NewEltVTWidth = NewEltVT.getSizeInBits();
2122       // Readjust position and vector position based on new load type
2123       Idx = Idx * (oNewEltVTWidth/NewEltVTWidth);
2124       VecOp = DAG.getNode(ISD::BIT_CONVERT, dl, NewVecVT, VecOp);
2125     }
2126
2127     EOp = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, NewEltVT, VecOp,
2128                       DAG.getIntPtrConstant(Idx++));
2129     StChain.push_back(DAG.getStore(Chain, dl, EOp, BasePtr, SV,
2130                                    SVOffset + Offset, isVolatile,
2131                                    MinAlign(Alignment, Offset)));
2132     StWidth -= NewEltVTWidth;
2133   }
2134 }
2135
2136 /// Modifies a vector input (widen or narrows) to a vector of NVT.  The
2137 /// input vector must have the same element type as NVT.
2138 SDValue DAGTypeLegalizer::ModifyToType(SDValue InOp, MVT NVT) {
2139   // Note that InOp might have been widened so it might already have
2140   // the right width or it might need be narrowed.
2141   MVT InVT = InOp.getValueType();
2142   assert(InVT.getVectorElementType() == NVT.getVectorElementType() &&
2143          "input and widen element type must match");
2144   DebugLoc dl = InOp.getDebugLoc();
2145
2146   // Check if InOp already has the right width.
2147   if (InVT == NVT)
2148     return InOp;
2149
2150   unsigned InNumElts = InVT.getVectorNumElements();
2151   unsigned WidenNumElts = NVT.getVectorNumElements();
2152   if (WidenNumElts > InNumElts && WidenNumElts % InNumElts == 0) {
2153     unsigned NumConcat = WidenNumElts / InNumElts;
2154     SmallVector<SDValue, 16> Ops(NumConcat);
2155     SDValue UndefVal = DAG.getUNDEF(InVT);
2156     Ops[0] = InOp;
2157     for (unsigned i = 1; i != NumConcat; ++i)
2158       Ops[i] = UndefVal;
2159
2160     return DAG.getNode(ISD::CONCAT_VECTORS, dl, NVT, &Ops[0], NumConcat);
2161   }
2162
2163   if (WidenNumElts < InNumElts && InNumElts % WidenNumElts)
2164     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT, InOp,
2165                        DAG.getIntPtrConstant(0));
2166
2167   // Fall back to extract and build.
2168   SmallVector<SDValue, 16> Ops(WidenNumElts);
2169   MVT EltVT = NVT.getVectorElementType();
2170   unsigned MinNumElts = std::min(WidenNumElts, InNumElts);
2171   unsigned Idx;
2172   for (Idx = 0; Idx < MinNumElts; ++Idx)
2173     Ops[Idx] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, InOp,
2174                            DAG.getIntPtrConstant(Idx));
2175
2176   SDValue UndefVal = DAG.getUNDEF(EltVT);
2177   for ( ; Idx < WidenNumElts; ++Idx)
2178     Ops[Idx] = UndefVal;
2179   return DAG.getBUILD_VECTOR(NVT, dl, &Ops[0], WidenNumElts);
2180 }