459af3b266b9fc20db2cc07e57353b0583f64ed1
[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 two vectors of half the size.  For example, implementing
19 // <128 x f32> operations in terms of two <64 x f32> operations.
20 //
21 //===----------------------------------------------------------------------===//
22
23 #include "LegalizeTypes.h"
24 #include "llvm/IR/DataLayout.h"
25 #include "llvm/Support/ErrorHandling.h"
26 #include "llvm/Support/raw_ostream.h"
27 using namespace llvm;
28
29 #define DEBUG_TYPE "legalize-types"
30
31 //===----------------------------------------------------------------------===//
32 //  Result Vector Scalarization: <1 x ty> -> ty.
33 //===----------------------------------------------------------------------===//
34
35 void DAGTypeLegalizer::ScalarizeVectorResult(SDNode *N, unsigned ResNo) {
36   DEBUG(dbgs() << "Scalarize node result " << ResNo << ": ";
37         N->dump(&DAG);
38         dbgs() << "\n");
39   SDValue R = SDValue();
40
41   switch (N->getOpcode()) {
42   default:
43 #ifndef NDEBUG
44     dbgs() << "ScalarizeVectorResult #" << ResNo << ": ";
45     N->dump(&DAG);
46     dbgs() << "\n";
47 #endif
48     report_fatal_error("Do not know how to scalarize the result of this "
49                        "operator!\n");
50
51   case ISD::MERGE_VALUES:      R = ScalarizeVecRes_MERGE_VALUES(N, ResNo);break;
52   case ISD::BITCAST:           R = ScalarizeVecRes_BITCAST(N); break;
53   case ISD::BUILD_VECTOR:      R = ScalarizeVecRes_BUILD_VECTOR(N); break;
54   case ISD::CONVERT_RNDSAT:    R = ScalarizeVecRes_CONVERT_RNDSAT(N); break;
55   case ISD::EXTRACT_SUBVECTOR: R = ScalarizeVecRes_EXTRACT_SUBVECTOR(N); break;
56   case ISD::FP_ROUND:          R = ScalarizeVecRes_FP_ROUND(N); break;
57   case ISD::FP_ROUND_INREG:    R = ScalarizeVecRes_InregOp(N); break;
58   case ISD::FPOWI:             R = ScalarizeVecRes_FPOWI(N); break;
59   case ISD::INSERT_VECTOR_ELT: R = ScalarizeVecRes_INSERT_VECTOR_ELT(N); break;
60   case ISD::LOAD:           R = ScalarizeVecRes_LOAD(cast<LoadSDNode>(N));break;
61   case ISD::SCALAR_TO_VECTOR:  R = ScalarizeVecRes_SCALAR_TO_VECTOR(N); break;
62   case ISD::SIGN_EXTEND_INREG: R = ScalarizeVecRes_InregOp(N); break;
63   case ISD::VSELECT:           R = ScalarizeVecRes_VSELECT(N); break;
64   case ISD::SELECT:            R = ScalarizeVecRes_SELECT(N); break;
65   case ISD::SELECT_CC:         R = ScalarizeVecRes_SELECT_CC(N); break;
66   case ISD::SETCC:             R = ScalarizeVecRes_SETCC(N); break;
67   case ISD::UNDEF:             R = ScalarizeVecRes_UNDEF(N); break;
68   case ISD::VECTOR_SHUFFLE:    R = ScalarizeVecRes_VECTOR_SHUFFLE(N); break;
69   case ISD::ANY_EXTEND:
70   case ISD::BSWAP:
71   case ISD::CTLZ:
72   case ISD::CTPOP:
73   case ISD::CTTZ:
74   case ISD::FABS:
75   case ISD::FCEIL:
76   case ISD::FCOS:
77   case ISD::FEXP:
78   case ISD::FEXP2:
79   case ISD::FFLOOR:
80   case ISD::FLOG:
81   case ISD::FLOG10:
82   case ISD::FLOG2:
83   case ISD::FNEARBYINT:
84   case ISD::FNEG:
85   case ISD::FP_EXTEND:
86   case ISD::FP_TO_SINT:
87   case ISD::FP_TO_UINT:
88   case ISD::FRINT:
89   case ISD::FROUND:
90   case ISD::FSIN:
91   case ISD::FSQRT:
92   case ISD::FTRUNC:
93   case ISD::SIGN_EXTEND:
94   case ISD::SINT_TO_FP:
95   case ISD::TRUNCATE:
96   case ISD::UINT_TO_FP:
97   case ISD::ZERO_EXTEND:
98     R = ScalarizeVecRes_UnaryOp(N);
99     break;
100
101   case ISD::ADD:
102   case ISD::AND:
103   case ISD::FADD:
104   case ISD::FCOPYSIGN:
105   case ISD::FDIV:
106   case ISD::FMUL:
107   case ISD::FPOW:
108   case ISD::FREM:
109   case ISD::FSUB:
110   case ISD::MUL:
111   case ISD::OR:
112   case ISD::SDIV:
113   case ISD::SREM:
114   case ISD::SUB:
115   case ISD::UDIV:
116   case ISD::UREM:
117   case ISD::XOR:
118   case ISD::SHL:
119   case ISD::SRA:
120   case ISD::SRL:
121     R = ScalarizeVecRes_BinOp(N);
122     break;
123   case ISD::FMA:
124     R = ScalarizeVecRes_TernaryOp(N);
125     break;
126   }
127
128   // If R is null, the sub-method took care of registering the result.
129   if (R.getNode())
130     SetScalarizedVector(SDValue(N, ResNo), R);
131 }
132
133 SDValue DAGTypeLegalizer::ScalarizeVecRes_BinOp(SDNode *N) {
134   SDValue LHS = GetScalarizedVector(N->getOperand(0));
135   SDValue RHS = GetScalarizedVector(N->getOperand(1));
136   return DAG.getNode(N->getOpcode(), SDLoc(N),
137                      LHS.getValueType(), LHS, RHS);
138 }
139
140 SDValue DAGTypeLegalizer::ScalarizeVecRes_TernaryOp(SDNode *N) {
141   SDValue Op0 = GetScalarizedVector(N->getOperand(0));
142   SDValue Op1 = GetScalarizedVector(N->getOperand(1));
143   SDValue Op2 = GetScalarizedVector(N->getOperand(2));
144   return DAG.getNode(N->getOpcode(), SDLoc(N),
145                      Op0.getValueType(), Op0, Op1, Op2);
146 }
147
148 SDValue DAGTypeLegalizer::ScalarizeVecRes_MERGE_VALUES(SDNode *N,
149                                                        unsigned ResNo) {
150   SDValue Op = DisintegrateMERGE_VALUES(N, ResNo);
151   return GetScalarizedVector(Op);
152 }
153
154 SDValue DAGTypeLegalizer::ScalarizeVecRes_BITCAST(SDNode *N) {
155   EVT NewVT = N->getValueType(0).getVectorElementType();
156   return DAG.getNode(ISD::BITCAST, SDLoc(N),
157                      NewVT, N->getOperand(0));
158 }
159
160 SDValue DAGTypeLegalizer::ScalarizeVecRes_BUILD_VECTOR(SDNode *N) {
161   EVT EltVT = N->getValueType(0).getVectorElementType();
162   SDValue InOp = N->getOperand(0);
163   // The BUILD_VECTOR operands may be of wider element types and
164   // we may need to truncate them back to the requested return type.
165   if (EltVT.isInteger())
166     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), EltVT, InOp);
167   return InOp;
168 }
169
170 SDValue DAGTypeLegalizer::ScalarizeVecRes_CONVERT_RNDSAT(SDNode *N) {
171   EVT NewVT = N->getValueType(0).getVectorElementType();
172   SDValue Op0 = GetScalarizedVector(N->getOperand(0));
173   return DAG.getConvertRndSat(NewVT, SDLoc(N),
174                               Op0, DAG.getValueType(NewVT),
175                               DAG.getValueType(Op0.getValueType()),
176                               N->getOperand(3),
177                               N->getOperand(4),
178                               cast<CvtRndSatSDNode>(N)->getCvtCode());
179 }
180
181 SDValue DAGTypeLegalizer::ScalarizeVecRes_EXTRACT_SUBVECTOR(SDNode *N) {
182   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N),
183                      N->getValueType(0).getVectorElementType(),
184                      N->getOperand(0), N->getOperand(1));
185 }
186
187 SDValue DAGTypeLegalizer::ScalarizeVecRes_FP_ROUND(SDNode *N) {
188   EVT NewVT = N->getValueType(0).getVectorElementType();
189   SDValue Op = GetScalarizedVector(N->getOperand(0));
190   return DAG.getNode(ISD::FP_ROUND, SDLoc(N),
191                      NewVT, Op, N->getOperand(1));
192 }
193
194 SDValue DAGTypeLegalizer::ScalarizeVecRes_FPOWI(SDNode *N) {
195   SDValue Op = GetScalarizedVector(N->getOperand(0));
196   return DAG.getNode(ISD::FPOWI, SDLoc(N),
197                      Op.getValueType(), Op, N->getOperand(1));
198 }
199
200 SDValue DAGTypeLegalizer::ScalarizeVecRes_INSERT_VECTOR_ELT(SDNode *N) {
201   // The value to insert may have a wider type than the vector element type,
202   // so be sure to truncate it to the element type if necessary.
203   SDValue Op = N->getOperand(1);
204   EVT EltVT = N->getValueType(0).getVectorElementType();
205   if (Op.getValueType() != EltVT)
206     // FIXME: Can this happen for floating point types?
207     Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), EltVT, Op);
208   return Op;
209 }
210
211 SDValue DAGTypeLegalizer::ScalarizeVecRes_LOAD(LoadSDNode *N) {
212   assert(N->isUnindexed() && "Indexed vector load?");
213
214   SDValue Result = DAG.getLoad(ISD::UNINDEXED,
215                                N->getExtensionType(),
216                                N->getValueType(0).getVectorElementType(),
217                                SDLoc(N),
218                                N->getChain(), N->getBasePtr(),
219                                DAG.getUNDEF(N->getBasePtr().getValueType()),
220                                N->getPointerInfo(),
221                                N->getMemoryVT().getVectorElementType(),
222                                N->isVolatile(), N->isNonTemporal(),
223                                N->isInvariant(), N->getOriginalAlignment(),
224                                N->getTBAAInfo());
225
226   // Legalized the chain result - switch anything that used the old chain to
227   // use the new one.
228   ReplaceValueWith(SDValue(N, 1), Result.getValue(1));
229   return Result;
230 }
231
232 SDValue DAGTypeLegalizer::ScalarizeVecRes_UnaryOp(SDNode *N) {
233   // Get the dest type - it doesn't always match the input type, e.g. int_to_fp.
234   EVT DestVT = N->getValueType(0).getVectorElementType();
235   SDValue Op = GetScalarizedVector(N->getOperand(0));
236   return DAG.getNode(N->getOpcode(), SDLoc(N), DestVT, Op);
237 }
238
239 SDValue DAGTypeLegalizer::ScalarizeVecRes_InregOp(SDNode *N) {
240   EVT EltVT = N->getValueType(0).getVectorElementType();
241   EVT ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT().getVectorElementType();
242   SDValue LHS = GetScalarizedVector(N->getOperand(0));
243   return DAG.getNode(N->getOpcode(), SDLoc(N), EltVT,
244                      LHS, DAG.getValueType(ExtVT));
245 }
246
247 SDValue DAGTypeLegalizer::ScalarizeVecRes_SCALAR_TO_VECTOR(SDNode *N) {
248   // If the operand is wider than the vector element type then it is implicitly
249   // truncated.  Make that explicit here.
250   EVT EltVT = N->getValueType(0).getVectorElementType();
251   SDValue InOp = N->getOperand(0);
252   if (InOp.getValueType() != EltVT)
253     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), EltVT, InOp);
254   return InOp;
255 }
256
257 SDValue DAGTypeLegalizer::ScalarizeVecRes_VSELECT(SDNode *N) {
258   SDValue Cond = GetScalarizedVector(N->getOperand(0));
259   SDValue LHS = GetScalarizedVector(N->getOperand(1));
260   TargetLowering::BooleanContent ScalarBool = TLI.getBooleanContents(false);
261   TargetLowering::BooleanContent VecBool = TLI.getBooleanContents(true);
262   if (ScalarBool != VecBool) {
263     EVT CondVT = Cond.getValueType();
264     switch (ScalarBool) {
265       case TargetLowering::UndefinedBooleanContent:
266         break;
267       case TargetLowering::ZeroOrOneBooleanContent:
268         assert(VecBool == TargetLowering::UndefinedBooleanContent ||
269                VecBool == TargetLowering::ZeroOrNegativeOneBooleanContent);
270         // Vector read from all ones, scalar expects a single 1 so mask.
271         Cond = DAG.getNode(ISD::AND, SDLoc(N), CondVT,
272                            Cond, DAG.getConstant(1, CondVT));
273         break;
274       case TargetLowering::ZeroOrNegativeOneBooleanContent:
275         assert(VecBool == TargetLowering::UndefinedBooleanContent ||
276                VecBool == TargetLowering::ZeroOrOneBooleanContent);
277         // Vector reads from a one, scalar from all ones so sign extend.
278         Cond = DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), CondVT,
279                            Cond, DAG.getValueType(MVT::i1));
280         break;
281     }
282   }
283
284   return DAG.getSelect(SDLoc(N),
285                        LHS.getValueType(), Cond, LHS,
286                        GetScalarizedVector(N->getOperand(2)));
287 }
288
289 SDValue DAGTypeLegalizer::ScalarizeVecRes_SELECT(SDNode *N) {
290   SDValue LHS = GetScalarizedVector(N->getOperand(1));
291   return DAG.getSelect(SDLoc(N),
292                        LHS.getValueType(), N->getOperand(0), LHS,
293                        GetScalarizedVector(N->getOperand(2)));
294 }
295
296 SDValue DAGTypeLegalizer::ScalarizeVecRes_SELECT_CC(SDNode *N) {
297   SDValue LHS = GetScalarizedVector(N->getOperand(2));
298   return DAG.getNode(ISD::SELECT_CC, SDLoc(N), LHS.getValueType(),
299                      N->getOperand(0), N->getOperand(1),
300                      LHS, GetScalarizedVector(N->getOperand(3)),
301                      N->getOperand(4));
302 }
303
304 SDValue DAGTypeLegalizer::ScalarizeVecRes_SETCC(SDNode *N) {
305   assert(N->getValueType(0).isVector() ==
306          N->getOperand(0).getValueType().isVector() &&
307          "Scalar/Vector type mismatch");
308
309   if (N->getValueType(0).isVector()) return ScalarizeVecRes_VSETCC(N);
310
311   SDValue LHS = GetScalarizedVector(N->getOperand(0));
312   SDValue RHS = GetScalarizedVector(N->getOperand(1));
313   SDLoc DL(N);
314
315   // Turn it into a scalar SETCC.
316   return DAG.getNode(ISD::SETCC, DL, MVT::i1, LHS, RHS, N->getOperand(2));
317 }
318
319 SDValue DAGTypeLegalizer::ScalarizeVecRes_UNDEF(SDNode *N) {
320   return DAG.getUNDEF(N->getValueType(0).getVectorElementType());
321 }
322
323 SDValue DAGTypeLegalizer::ScalarizeVecRes_VECTOR_SHUFFLE(SDNode *N) {
324   // Figure out if the scalar is the LHS or RHS and return it.
325   SDValue Arg = N->getOperand(2).getOperand(0);
326   if (Arg.getOpcode() == ISD::UNDEF)
327     return DAG.getUNDEF(N->getValueType(0).getVectorElementType());
328   unsigned Op = !cast<ConstantSDNode>(Arg)->isNullValue();
329   return GetScalarizedVector(N->getOperand(Op));
330 }
331
332 SDValue DAGTypeLegalizer::ScalarizeVecRes_VSETCC(SDNode *N) {
333   assert(N->getValueType(0).isVector() &&
334          N->getOperand(0).getValueType().isVector() &&
335          "Operand types must be vectors");
336   SDValue LHS = N->getOperand(0);
337   SDValue RHS = N->getOperand(1);
338   EVT OpVT = LHS.getValueType();
339   EVT NVT = N->getValueType(0).getVectorElementType();
340   SDLoc DL(N);
341
342   // The result needs scalarizing, but it's not a given that the source does.
343   if (getTypeAction(OpVT) == TargetLowering::TypeScalarizeVector) {
344     LHS = GetScalarizedVector(LHS);
345     RHS = GetScalarizedVector(RHS);
346   } else {
347     EVT VT = OpVT.getVectorElementType();
348     LHS = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, LHS,
349                       DAG.getConstant(0, TLI.getVectorIdxTy()));
350     RHS = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, RHS,
351                       DAG.getConstant(0, TLI.getVectorIdxTy()));
352   }
353
354   // Turn it into a scalar SETCC.
355   SDValue Res = DAG.getNode(ISD::SETCC, DL, MVT::i1, LHS, RHS,
356                             N->getOperand(2));
357   // Vectors may have a different boolean contents to scalars.  Promote the
358   // value appropriately.
359   ISD::NodeType ExtendCode =
360     TargetLowering::getExtendForContent(TLI.getBooleanContents(true));
361   return DAG.getNode(ExtendCode, DL, NVT, Res);
362 }
363
364
365 //===----------------------------------------------------------------------===//
366 //  Operand Vector Scalarization <1 x ty> -> ty.
367 //===----------------------------------------------------------------------===//
368
369 bool DAGTypeLegalizer::ScalarizeVectorOperand(SDNode *N, unsigned OpNo) {
370   DEBUG(dbgs() << "Scalarize node operand " << OpNo << ": ";
371         N->dump(&DAG);
372         dbgs() << "\n");
373   SDValue Res = SDValue();
374
375   if (!Res.getNode()) {
376     switch (N->getOpcode()) {
377     default:
378 #ifndef NDEBUG
379       dbgs() << "ScalarizeVectorOperand Op #" << OpNo << ": ";
380       N->dump(&DAG);
381       dbgs() << "\n";
382 #endif
383       llvm_unreachable("Do not know how to scalarize this operator's operand!");
384     case ISD::BITCAST:
385       Res = ScalarizeVecOp_BITCAST(N);
386       break;
387     case ISD::ANY_EXTEND:
388     case ISD::ZERO_EXTEND:
389     case ISD::SIGN_EXTEND:
390     case ISD::TRUNCATE:
391       Res = ScalarizeVecOp_UnaryOp(N);
392       break;
393     case ISD::CONCAT_VECTORS:
394       Res = ScalarizeVecOp_CONCAT_VECTORS(N);
395       break;
396     case ISD::EXTRACT_VECTOR_ELT:
397       Res = ScalarizeVecOp_EXTRACT_VECTOR_ELT(N);
398       break;
399     case ISD::VSELECT:
400       Res = ScalarizeVecOp_VSELECT(N);
401       break;
402     case ISD::STORE:
403       Res = ScalarizeVecOp_STORE(cast<StoreSDNode>(N), OpNo);
404       break;
405     case ISD::FP_ROUND:
406       Res = ScalarizeVecOp_FP_ROUND(N, OpNo);
407       break;
408     }
409   }
410
411   // If the result is null, the sub-method took care of registering results etc.
412   if (!Res.getNode()) return false;
413
414   // If the result is N, the sub-method updated N in place.  Tell the legalizer
415   // core about this.
416   if (Res.getNode() == N)
417     return true;
418
419   assert(Res.getValueType() == N->getValueType(0) && N->getNumValues() == 1 &&
420          "Invalid operand expansion");
421
422   ReplaceValueWith(SDValue(N, 0), Res);
423   return false;
424 }
425
426 /// ScalarizeVecOp_BITCAST - If the value to convert is a vector that needs
427 /// to be scalarized, it must be <1 x ty>.  Convert the element instead.
428 SDValue DAGTypeLegalizer::ScalarizeVecOp_BITCAST(SDNode *N) {
429   SDValue Elt = GetScalarizedVector(N->getOperand(0));
430   return DAG.getNode(ISD::BITCAST, SDLoc(N),
431                      N->getValueType(0), Elt);
432 }
433
434 /// ScalarizeVecOp_EXTEND - If the value to extend is a vector that needs
435 /// to be scalarized, it must be <1 x ty>.  Extend the element instead.
436 SDValue DAGTypeLegalizer::ScalarizeVecOp_UnaryOp(SDNode *N) {
437   assert(N->getValueType(0).getVectorNumElements() == 1 &&
438          "Unexected vector type!");
439   SDValue Elt = GetScalarizedVector(N->getOperand(0));
440   SmallVector<SDValue, 1> Ops(1);
441   Ops[0] = DAG.getNode(N->getOpcode(), SDLoc(N),
442                        N->getValueType(0).getScalarType(), Elt);
443   // Revectorize the result so the types line up with what the uses of this
444   // expression expect.
445   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), N->getValueType(0),
446                      &Ops[0], 1);
447 }
448
449 /// ScalarizeVecOp_CONCAT_VECTORS - The vectors to concatenate have length one -
450 /// use a BUILD_VECTOR instead.
451 SDValue DAGTypeLegalizer::ScalarizeVecOp_CONCAT_VECTORS(SDNode *N) {
452   SmallVector<SDValue, 8> Ops(N->getNumOperands());
453   for (unsigned i = 0, e = N->getNumOperands(); i < e; ++i)
454     Ops[i] = GetScalarizedVector(N->getOperand(i));
455   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), N->getValueType(0),
456                      &Ops[0], Ops.size());
457 }
458
459 /// ScalarizeVecOp_EXTRACT_VECTOR_ELT - If the input is a vector that needs to
460 /// be scalarized, it must be <1 x ty>, so just return the element, ignoring the
461 /// index.
462 SDValue DAGTypeLegalizer::ScalarizeVecOp_EXTRACT_VECTOR_ELT(SDNode *N) {
463   SDValue Res = GetScalarizedVector(N->getOperand(0));
464   if (Res.getValueType() != N->getValueType(0))
465     Res = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), N->getValueType(0),
466                       Res);
467   return Res;
468 }
469
470
471 /// ScalarizeVecOp_VSELECT - If the input condition is a vector that needs to be
472 /// scalarized, it must be <1 x i1>, so just convert to a normal ISD::SELECT
473 /// (still with vector output type since that was acceptable if we got here).
474 SDValue DAGTypeLegalizer::ScalarizeVecOp_VSELECT(SDNode *N) {
475   SDValue ScalarCond = GetScalarizedVector(N->getOperand(0));
476   EVT VT = N->getValueType(0);
477
478   return DAG.getNode(ISD::SELECT, SDLoc(N), VT, ScalarCond, N->getOperand(1),
479                      N->getOperand(2));
480 }
481
482 /// ScalarizeVecOp_STORE - If the value to store is a vector that needs to be
483 /// scalarized, it must be <1 x ty>.  Just store the element.
484 SDValue DAGTypeLegalizer::ScalarizeVecOp_STORE(StoreSDNode *N, unsigned OpNo){
485   assert(N->isUnindexed() && "Indexed store of one-element vector?");
486   assert(OpNo == 1 && "Do not know how to scalarize this operand!");
487   SDLoc dl(N);
488
489   if (N->isTruncatingStore())
490     return DAG.getTruncStore(N->getChain(), dl,
491                              GetScalarizedVector(N->getOperand(1)),
492                              N->getBasePtr(), N->getPointerInfo(),
493                              N->getMemoryVT().getVectorElementType(),
494                              N->isVolatile(), N->isNonTemporal(),
495                              N->getAlignment(), N->getTBAAInfo());
496
497   return DAG.getStore(N->getChain(), dl, GetScalarizedVector(N->getOperand(1)),
498                       N->getBasePtr(), N->getPointerInfo(),
499                       N->isVolatile(), N->isNonTemporal(),
500                       N->getOriginalAlignment(), N->getTBAAInfo());
501 }
502
503 /// ScalarizeVecOp_FP_ROUND - If the value to round is a vector that needs
504 /// to be scalarized, it must be <1 x ty>.  Convert the element instead.
505 SDValue DAGTypeLegalizer::ScalarizeVecOp_FP_ROUND(SDNode *N, unsigned OpNo) {
506   SDValue Elt = GetScalarizedVector(N->getOperand(0));
507   SDValue Res = DAG.getNode(ISD::FP_ROUND, SDLoc(N),
508                             N->getValueType(0).getVectorElementType(), Elt,
509                             N->getOperand(1));
510   return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(N), N->getValueType(0), Res);
511 }
512
513 //===----------------------------------------------------------------------===//
514 //  Result Vector Splitting
515 //===----------------------------------------------------------------------===//
516
517 /// SplitVectorResult - This method is called when the specified result of the
518 /// specified node is found to need vector splitting.  At this point, the node
519 /// may also have invalid operands or may have other results that need
520 /// legalization, we just know that (at least) one result needs vector
521 /// splitting.
522 void DAGTypeLegalizer::SplitVectorResult(SDNode *N, unsigned ResNo) {
523   DEBUG(dbgs() << "Split node result: ";
524         N->dump(&DAG);
525         dbgs() << "\n");
526   SDValue Lo, Hi;
527
528   // See if the target wants to custom expand this node.
529   if (CustomLowerNode(N, N->getValueType(ResNo), true))
530     return;
531
532   switch (N->getOpcode()) {
533   default:
534 #ifndef NDEBUG
535     dbgs() << "SplitVectorResult #" << ResNo << ": ";
536     N->dump(&DAG);
537     dbgs() << "\n";
538 #endif
539     report_fatal_error("Do not know how to split the result of this "
540                        "operator!\n");
541
542   case ISD::MERGE_VALUES: SplitRes_MERGE_VALUES(N, ResNo, Lo, Hi); break;
543   case ISD::VSELECT:
544   case ISD::SELECT:       SplitRes_SELECT(N, Lo, Hi); break;
545   case ISD::SELECT_CC:    SplitRes_SELECT_CC(N, Lo, Hi); break;
546   case ISD::UNDEF:        SplitRes_UNDEF(N, Lo, Hi); break;
547   case ISD::BITCAST:           SplitVecRes_BITCAST(N, Lo, Hi); break;
548   case ISD::BUILD_VECTOR:      SplitVecRes_BUILD_VECTOR(N, Lo, Hi); break;
549   case ISD::CONCAT_VECTORS:    SplitVecRes_CONCAT_VECTORS(N, Lo, Hi); break;
550   case ISD::EXTRACT_SUBVECTOR: SplitVecRes_EXTRACT_SUBVECTOR(N, Lo, Hi); break;
551   case ISD::FP_ROUND_INREG:    SplitVecRes_InregOp(N, Lo, Hi); break;
552   case ISD::FPOWI:             SplitVecRes_FPOWI(N, Lo, Hi); break;
553   case ISD::INSERT_VECTOR_ELT: SplitVecRes_INSERT_VECTOR_ELT(N, Lo, Hi); break;
554   case ISD::SCALAR_TO_VECTOR:  SplitVecRes_SCALAR_TO_VECTOR(N, Lo, Hi); break;
555   case ISD::SIGN_EXTEND_INREG: SplitVecRes_InregOp(N, Lo, Hi); break;
556   case ISD::LOAD:
557     SplitVecRes_LOAD(cast<LoadSDNode>(N), Lo, Hi);
558     break;
559   case ISD::SETCC:
560     SplitVecRes_SETCC(N, Lo, Hi);
561     break;
562   case ISD::VECTOR_SHUFFLE:
563     SplitVecRes_VECTOR_SHUFFLE(cast<ShuffleVectorSDNode>(N), Lo, Hi);
564     break;
565
566   case ISD::BSWAP:
567   case ISD::CONVERT_RNDSAT:
568   case ISD::CTLZ:
569   case ISD::CTTZ:
570   case ISD::CTLZ_ZERO_UNDEF:
571   case ISD::CTTZ_ZERO_UNDEF:
572   case ISD::CTPOP:
573   case ISD::FABS:
574   case ISD::FCEIL:
575   case ISD::FCOS:
576   case ISD::FEXP:
577   case ISD::FEXP2:
578   case ISD::FFLOOR:
579   case ISD::FLOG:
580   case ISD::FLOG10:
581   case ISD::FLOG2:
582   case ISD::FNEARBYINT:
583   case ISD::FNEG:
584   case ISD::FP_EXTEND:
585   case ISD::FP_ROUND:
586   case ISD::FP_TO_SINT:
587   case ISD::FP_TO_UINT:
588   case ISD::FRINT:
589   case ISD::FROUND:
590   case ISD::FSIN:
591   case ISD::FSQRT:
592   case ISD::FTRUNC:
593   case ISD::SINT_TO_FP:
594   case ISD::TRUNCATE:
595   case ISD::UINT_TO_FP:
596     SplitVecRes_UnaryOp(N, Lo, Hi);
597     break;
598
599   case ISD::ANY_EXTEND:
600   case ISD::SIGN_EXTEND:
601   case ISD::ZERO_EXTEND:
602     SplitVecRes_ExtendOp(N, Lo, Hi);
603     break;
604
605   case ISD::ADD:
606   case ISD::SUB:
607   case ISD::MUL:
608   case ISD::FADD:
609   case ISD::FCOPYSIGN:
610   case ISD::FSUB:
611   case ISD::FMUL:
612   case ISD::SDIV:
613   case ISD::UDIV:
614   case ISD::FDIV:
615   case ISD::FPOW:
616   case ISD::AND:
617   case ISD::OR:
618   case ISD::XOR:
619   case ISD::SHL:
620   case ISD::SRA:
621   case ISD::SRL:
622   case ISD::UREM:
623   case ISD::SREM:
624   case ISD::FREM:
625     SplitVecRes_BinOp(N, Lo, Hi);
626     break;
627   case ISD::FMA:
628     SplitVecRes_TernaryOp(N, Lo, Hi);
629     break;
630   }
631
632   // If Lo/Hi is null, the sub-method took care of registering results etc.
633   if (Lo.getNode())
634     SetSplitVector(SDValue(N, ResNo), Lo, Hi);
635 }
636
637 void DAGTypeLegalizer::SplitVecRes_BinOp(SDNode *N, SDValue &Lo,
638                                          SDValue &Hi) {
639   SDValue LHSLo, LHSHi;
640   GetSplitVector(N->getOperand(0), LHSLo, LHSHi);
641   SDValue RHSLo, RHSHi;
642   GetSplitVector(N->getOperand(1), RHSLo, RHSHi);
643   SDLoc dl(N);
644
645   Lo = DAG.getNode(N->getOpcode(), dl, LHSLo.getValueType(), LHSLo, RHSLo);
646   Hi = DAG.getNode(N->getOpcode(), dl, LHSHi.getValueType(), LHSHi, RHSHi);
647 }
648
649 void DAGTypeLegalizer::SplitVecRes_TernaryOp(SDNode *N, SDValue &Lo,
650                                              SDValue &Hi) {
651   SDValue Op0Lo, Op0Hi;
652   GetSplitVector(N->getOperand(0), Op0Lo, Op0Hi);
653   SDValue Op1Lo, Op1Hi;
654   GetSplitVector(N->getOperand(1), Op1Lo, Op1Hi);
655   SDValue Op2Lo, Op2Hi;
656   GetSplitVector(N->getOperand(2), Op2Lo, Op2Hi);
657   SDLoc dl(N);
658
659   Lo = DAG.getNode(N->getOpcode(), dl, Op0Lo.getValueType(),
660                    Op0Lo, Op1Lo, Op2Lo);
661   Hi = DAG.getNode(N->getOpcode(), dl, Op0Hi.getValueType(),
662                    Op0Hi, Op1Hi, Op2Hi);
663 }
664
665 void DAGTypeLegalizer::SplitVecRes_BITCAST(SDNode *N, SDValue &Lo,
666                                            SDValue &Hi) {
667   // We know the result is a vector.  The input may be either a vector or a
668   // scalar value.
669   EVT LoVT, HiVT;
670   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
671   SDLoc dl(N);
672
673   SDValue InOp = N->getOperand(0);
674   EVT InVT = InOp.getValueType();
675
676   // Handle some special cases efficiently.
677   switch (getTypeAction(InVT)) {
678   case TargetLowering::TypeLegal:
679   case TargetLowering::TypePromoteInteger:
680   case TargetLowering::TypeSoftenFloat:
681   case TargetLowering::TypeScalarizeVector:
682   case TargetLowering::TypeWidenVector:
683     break;
684   case TargetLowering::TypeExpandInteger:
685   case TargetLowering::TypeExpandFloat:
686     // A scalar to vector conversion, where the scalar needs expansion.
687     // If the vector is being split in two then we can just convert the
688     // expanded pieces.
689     if (LoVT == HiVT) {
690       GetExpandedOp(InOp, Lo, Hi);
691       if (TLI.isBigEndian())
692         std::swap(Lo, Hi);
693       Lo = DAG.getNode(ISD::BITCAST, dl, LoVT, Lo);
694       Hi = DAG.getNode(ISD::BITCAST, dl, HiVT, Hi);
695       return;
696     }
697     break;
698   case TargetLowering::TypeSplitVector:
699     // If the input is a vector that needs to be split, convert each split
700     // piece of the input now.
701     GetSplitVector(InOp, Lo, Hi);
702     Lo = DAG.getNode(ISD::BITCAST, dl, LoVT, Lo);
703     Hi = DAG.getNode(ISD::BITCAST, dl, HiVT, Hi);
704     return;
705   }
706
707   // In the general case, convert the input to an integer and split it by hand.
708   EVT LoIntVT = EVT::getIntegerVT(*DAG.getContext(), LoVT.getSizeInBits());
709   EVT HiIntVT = EVT::getIntegerVT(*DAG.getContext(), HiVT.getSizeInBits());
710   if (TLI.isBigEndian())
711     std::swap(LoIntVT, HiIntVT);
712
713   SplitInteger(BitConvertToInteger(InOp), LoIntVT, HiIntVT, Lo, Hi);
714
715   if (TLI.isBigEndian())
716     std::swap(Lo, Hi);
717   Lo = DAG.getNode(ISD::BITCAST, dl, LoVT, Lo);
718   Hi = DAG.getNode(ISD::BITCAST, dl, HiVT, Hi);
719 }
720
721 void DAGTypeLegalizer::SplitVecRes_BUILD_VECTOR(SDNode *N, SDValue &Lo,
722                                                 SDValue &Hi) {
723   EVT LoVT, HiVT;
724   SDLoc dl(N);
725   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
726   unsigned LoNumElts = LoVT.getVectorNumElements();
727   SmallVector<SDValue, 8> LoOps(N->op_begin(), N->op_begin()+LoNumElts);
728   Lo = DAG.getNode(ISD::BUILD_VECTOR, dl, LoVT, &LoOps[0], LoOps.size());
729
730   SmallVector<SDValue, 8> HiOps(N->op_begin()+LoNumElts, N->op_end());
731   Hi = DAG.getNode(ISD::BUILD_VECTOR, dl, HiVT, &HiOps[0], HiOps.size());
732 }
733
734 void DAGTypeLegalizer::SplitVecRes_CONCAT_VECTORS(SDNode *N, SDValue &Lo,
735                                                   SDValue &Hi) {
736   assert(!(N->getNumOperands() & 1) && "Unsupported CONCAT_VECTORS");
737   SDLoc dl(N);
738   unsigned NumSubvectors = N->getNumOperands() / 2;
739   if (NumSubvectors == 1) {
740     Lo = N->getOperand(0);
741     Hi = N->getOperand(1);
742     return;
743   }
744
745   EVT LoVT, HiVT;
746   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
747
748   SmallVector<SDValue, 8> LoOps(N->op_begin(), N->op_begin()+NumSubvectors);
749   Lo = DAG.getNode(ISD::CONCAT_VECTORS, dl, LoVT, &LoOps[0], LoOps.size());
750
751   SmallVector<SDValue, 8> HiOps(N->op_begin()+NumSubvectors, N->op_end());
752   Hi = DAG.getNode(ISD::CONCAT_VECTORS, dl, HiVT, &HiOps[0], HiOps.size());
753 }
754
755 void DAGTypeLegalizer::SplitVecRes_EXTRACT_SUBVECTOR(SDNode *N, SDValue &Lo,
756                                                      SDValue &Hi) {
757   SDValue Vec = N->getOperand(0);
758   SDValue Idx = N->getOperand(1);
759   SDLoc dl(N);
760
761   EVT LoVT, HiVT;
762   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
763
764   Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, LoVT, Vec, Idx);
765   uint64_t IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
766   Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, HiVT, Vec,
767                    DAG.getConstant(IdxVal + LoVT.getVectorNumElements(),
768                                    TLI.getVectorIdxTy()));
769 }
770
771 void DAGTypeLegalizer::SplitVecRes_FPOWI(SDNode *N, SDValue &Lo,
772                                          SDValue &Hi) {
773   SDLoc dl(N);
774   GetSplitVector(N->getOperand(0), Lo, Hi);
775   Lo = DAG.getNode(ISD::FPOWI, dl, Lo.getValueType(), Lo, N->getOperand(1));
776   Hi = DAG.getNode(ISD::FPOWI, dl, Hi.getValueType(), Hi, N->getOperand(1));
777 }
778
779 void DAGTypeLegalizer::SplitVecRes_InregOp(SDNode *N, SDValue &Lo,
780                                            SDValue &Hi) {
781   SDValue LHSLo, LHSHi;
782   GetSplitVector(N->getOperand(0), LHSLo, LHSHi);
783   SDLoc dl(N);
784
785   EVT LoVT, HiVT;
786   std::tie(LoVT, HiVT) =
787     DAG.GetSplitDestVTs(cast<VTSDNode>(N->getOperand(1))->getVT());
788
789   Lo = DAG.getNode(N->getOpcode(), dl, LHSLo.getValueType(), LHSLo,
790                    DAG.getValueType(LoVT));
791   Hi = DAG.getNode(N->getOpcode(), dl, LHSHi.getValueType(), LHSHi,
792                    DAG.getValueType(HiVT));
793 }
794
795 void DAGTypeLegalizer::SplitVecRes_INSERT_VECTOR_ELT(SDNode *N, SDValue &Lo,
796                                                      SDValue &Hi) {
797   SDValue Vec = N->getOperand(0);
798   SDValue Elt = N->getOperand(1);
799   SDValue Idx = N->getOperand(2);
800   SDLoc dl(N);
801   GetSplitVector(Vec, Lo, Hi);
802
803   if (ConstantSDNode *CIdx = dyn_cast<ConstantSDNode>(Idx)) {
804     unsigned IdxVal = CIdx->getZExtValue();
805     unsigned LoNumElts = Lo.getValueType().getVectorNumElements();
806     if (IdxVal < LoNumElts)
807       Lo = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
808                        Lo.getValueType(), Lo, Elt, Idx);
809     else
810       Hi = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, Hi.getValueType(), Hi, Elt,
811                        DAG.getConstant(IdxVal - LoNumElts,
812                                        TLI.getVectorIdxTy()));
813     return;
814   }
815
816   // Spill the vector to the stack.
817   EVT VecVT = Vec.getValueType();
818   EVT EltVT = VecVT.getVectorElementType();
819   SDValue StackPtr = DAG.CreateStackTemporary(VecVT);
820   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Vec, StackPtr,
821                                MachinePointerInfo(), false, false, 0);
822
823   // Store the new element.  This may be larger than the vector element type,
824   // so use a truncating store.
825   SDValue EltPtr = GetVectorElementPointer(StackPtr, EltVT, Idx);
826   Type *VecType = VecVT.getTypeForEVT(*DAG.getContext());
827   unsigned Alignment =
828     TLI.getDataLayout()->getPrefTypeAlignment(VecType);
829   Store = DAG.getTruncStore(Store, dl, Elt, EltPtr, MachinePointerInfo(), EltVT,
830                             false, false, 0);
831
832   // Load the Lo part from the stack slot.
833   Lo = DAG.getLoad(Lo.getValueType(), dl, Store, StackPtr, MachinePointerInfo(),
834                    false, false, false, 0);
835
836   // Increment the pointer to the other part.
837   unsigned IncrementSize = Lo.getValueType().getSizeInBits() / 8;
838   StackPtr = DAG.getNode(ISD::ADD, dl, StackPtr.getValueType(), StackPtr,
839                        DAG.getConstant(IncrementSize, StackPtr.getValueType()));
840
841   // Load the Hi part from the stack slot.
842   Hi = DAG.getLoad(Hi.getValueType(), dl, Store, StackPtr, MachinePointerInfo(),
843                    false, false, false, MinAlign(Alignment, IncrementSize));
844 }
845
846 void DAGTypeLegalizer::SplitVecRes_SCALAR_TO_VECTOR(SDNode *N, SDValue &Lo,
847                                                     SDValue &Hi) {
848   EVT LoVT, HiVT;
849   SDLoc dl(N);
850   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
851   Lo = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoVT, N->getOperand(0));
852   Hi = DAG.getUNDEF(HiVT);
853 }
854
855 void DAGTypeLegalizer::SplitVecRes_LOAD(LoadSDNode *LD, SDValue &Lo,
856                                         SDValue &Hi) {
857   assert(ISD::isUNINDEXEDLoad(LD) && "Indexed load during type legalization!");
858   EVT LoVT, HiVT;
859   SDLoc dl(LD);
860   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(LD->getValueType(0));
861
862   ISD::LoadExtType ExtType = LD->getExtensionType();
863   SDValue Ch = LD->getChain();
864   SDValue Ptr = LD->getBasePtr();
865   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
866   EVT MemoryVT = LD->getMemoryVT();
867   unsigned Alignment = LD->getOriginalAlignment();
868   bool isVolatile = LD->isVolatile();
869   bool isNonTemporal = LD->isNonTemporal();
870   bool isInvariant = LD->isInvariant();
871   const MDNode *TBAAInfo = LD->getTBAAInfo();
872
873   EVT LoMemVT, HiMemVT;
874   std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
875
876   Lo = DAG.getLoad(ISD::UNINDEXED, ExtType, LoVT, dl, Ch, Ptr, Offset,
877                    LD->getPointerInfo(), LoMemVT, isVolatile, isNonTemporal,
878                    isInvariant, Alignment, TBAAInfo);
879
880   unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
881   Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
882                     DAG.getConstant(IncrementSize, Ptr.getValueType()));
883   Hi = DAG.getLoad(ISD::UNINDEXED, ExtType, HiVT, dl, Ch, Ptr, Offset,
884                    LD->getPointerInfo().getWithOffset(IncrementSize),
885                    HiMemVT, isVolatile, isNonTemporal, isInvariant, Alignment,
886                    TBAAInfo);
887
888   // Build a factor node to remember that this load is independent of the
889   // other one.
890   Ch = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1),
891                    Hi.getValue(1));
892
893   // Legalized the chain result - switch anything that used the old chain to
894   // use the new one.
895   ReplaceValueWith(SDValue(LD, 1), Ch);
896 }
897
898 void DAGTypeLegalizer::SplitVecRes_SETCC(SDNode *N, SDValue &Lo, SDValue &Hi) {
899   assert(N->getValueType(0).isVector() &&
900          N->getOperand(0).getValueType().isVector() &&
901          "Operand types must be vectors");
902
903   EVT LoVT, HiVT;
904   SDLoc DL(N);
905   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
906
907   // Split the input.
908   SDValue LL, LH, RL, RH;
909   std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
910   std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
911
912   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
913   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
914 }
915
916 void DAGTypeLegalizer::SplitVecRes_UnaryOp(SDNode *N, SDValue &Lo,
917                                            SDValue &Hi) {
918   // Get the dest types - they may not match the input types, e.g. int_to_fp.
919   EVT LoVT, HiVT;
920   SDLoc dl(N);
921   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
922
923   // If the input also splits, handle it directly for a compile time speedup.
924   // Otherwise split it by hand.
925   EVT InVT = N->getOperand(0).getValueType();
926   if (getTypeAction(InVT) == TargetLowering::TypeSplitVector)
927     GetSplitVector(N->getOperand(0), Lo, Hi);
928   else
929     std::tie(Lo, Hi) = DAG.SplitVectorOperand(N, 0);
930
931   if (N->getOpcode() == ISD::FP_ROUND) {
932     Lo = DAG.getNode(N->getOpcode(), dl, LoVT, Lo, N->getOperand(1));
933     Hi = DAG.getNode(N->getOpcode(), dl, HiVT, Hi, N->getOperand(1));
934   } else if (N->getOpcode() == ISD::CONVERT_RNDSAT) {
935     SDValue DTyOpLo = DAG.getValueType(LoVT);
936     SDValue DTyOpHi = DAG.getValueType(HiVT);
937     SDValue STyOpLo = DAG.getValueType(Lo.getValueType());
938     SDValue STyOpHi = DAG.getValueType(Hi.getValueType());
939     SDValue RndOp = N->getOperand(3);
940     SDValue SatOp = N->getOperand(4);
941     ISD::CvtCode CvtCode = cast<CvtRndSatSDNode>(N)->getCvtCode();
942     Lo = DAG.getConvertRndSat(LoVT, dl, Lo, DTyOpLo, STyOpLo, RndOp, SatOp,
943                               CvtCode);
944     Hi = DAG.getConvertRndSat(HiVT, dl, Hi, DTyOpHi, STyOpHi, RndOp, SatOp,
945                               CvtCode);
946   } else {
947     Lo = DAG.getNode(N->getOpcode(), dl, LoVT, Lo);
948     Hi = DAG.getNode(N->getOpcode(), dl, HiVT, Hi);
949   }
950 }
951
952 void DAGTypeLegalizer::SplitVecRes_ExtendOp(SDNode *N, SDValue &Lo,
953                                             SDValue &Hi) {
954   SDLoc dl(N);
955   EVT SrcVT = N->getOperand(0).getValueType();
956   EVT DestVT = N->getValueType(0);
957   EVT LoVT, HiVT;
958   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(DestVT);
959
960   // We can do better than a generic split operation if the extend is doing
961   // more than just doubling the width of the elements and the following are
962   // true:
963   //   - The number of vector elements is even,
964   //   - the source type is legal,
965   //   - the type of a split source is illegal,
966   //   - the type of an extended (by doubling element size) source is legal, and
967   //   - the type of that extended source when split is legal.
968   //
969   // This won't necessarily completely legalize the operation, but it will
970   // more effectively move in the right direction and prevent falling down
971   // to scalarization in many cases due to the input vector being split too
972   // far.
973   unsigned NumElements = SrcVT.getVectorNumElements();
974   if ((NumElements & 1) == 0 &&
975       SrcVT.getSizeInBits() * 2 < DestVT.getSizeInBits()) {
976     LLVMContext &Ctx = *DAG.getContext();
977     EVT NewSrcVT = EVT::getVectorVT(
978         Ctx, EVT::getIntegerVT(
979                  Ctx, SrcVT.getVectorElementType().getSizeInBits() * 2),
980         NumElements);
981     EVT SplitSrcVT =
982         EVT::getVectorVT(Ctx, SrcVT.getVectorElementType(), NumElements / 2);
983     EVT SplitLoVT, SplitHiVT;
984     std::tie(SplitLoVT, SplitHiVT) = DAG.GetSplitDestVTs(NewSrcVT);
985     if (TLI.isTypeLegal(SrcVT) && !TLI.isTypeLegal(SplitSrcVT) &&
986         TLI.isTypeLegal(NewSrcVT) && TLI.isTypeLegal(SplitLoVT)) {
987       DEBUG(dbgs() << "Split vector extend via incremental extend:";
988             N->dump(&DAG); dbgs() << "\n");
989       // Extend the source vector by one step.
990       SDValue NewSrc =
991           DAG.getNode(N->getOpcode(), dl, NewSrcVT, N->getOperand(0));
992       // Get the low and high halves of the new, extended one step, vector.
993       std::tie(Lo, Hi) = DAG.SplitVector(NewSrc, dl);
994       // Extend those vector halves the rest of the way.
995       Lo = DAG.getNode(N->getOpcode(), dl, LoVT, Lo);
996       Hi = DAG.getNode(N->getOpcode(), dl, HiVT, Hi);
997       return;
998     }
999   }
1000   // Fall back to the generic unary operator splitting otherwise.
1001   SplitVecRes_UnaryOp(N, Lo, Hi);
1002 }
1003
1004 void DAGTypeLegalizer::SplitVecRes_VECTOR_SHUFFLE(ShuffleVectorSDNode *N,
1005                                                   SDValue &Lo, SDValue &Hi) {
1006   // The low and high parts of the original input give four input vectors.
1007   SDValue Inputs[4];
1008   SDLoc dl(N);
1009   GetSplitVector(N->getOperand(0), Inputs[0], Inputs[1]);
1010   GetSplitVector(N->getOperand(1), Inputs[2], Inputs[3]);
1011   EVT NewVT = Inputs[0].getValueType();
1012   unsigned NewElts = NewVT.getVectorNumElements();
1013
1014   // If Lo or Hi uses elements from at most two of the four input vectors, then
1015   // express it as a vector shuffle of those two inputs.  Otherwise extract the
1016   // input elements by hand and construct the Lo/Hi output using a BUILD_VECTOR.
1017   SmallVector<int, 16> Ops;
1018   for (unsigned High = 0; High < 2; ++High) {
1019     SDValue &Output = High ? Hi : Lo;
1020
1021     // Build a shuffle mask for the output, discovering on the fly which
1022     // input vectors to use as shuffle operands (recorded in InputUsed).
1023     // If building a suitable shuffle vector proves too hard, then bail
1024     // out with useBuildVector set.
1025     unsigned InputUsed[2] = { -1U, -1U }; // Not yet discovered.
1026     unsigned FirstMaskIdx = High * NewElts;
1027     bool useBuildVector = false;
1028     for (unsigned MaskOffset = 0; MaskOffset < NewElts; ++MaskOffset) {
1029       // The mask element.  This indexes into the input.
1030       int Idx = N->getMaskElt(FirstMaskIdx + MaskOffset);
1031
1032       // The input vector this mask element indexes into.
1033       unsigned Input = (unsigned)Idx / NewElts;
1034
1035       if (Input >= array_lengthof(Inputs)) {
1036         // The mask element does not index into any input vector.
1037         Ops.push_back(-1);
1038         continue;
1039       }
1040
1041       // Turn the index into an offset from the start of the input vector.
1042       Idx -= Input * NewElts;
1043
1044       // Find or create a shuffle vector operand to hold this input.
1045       unsigned OpNo;
1046       for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
1047         if (InputUsed[OpNo] == Input) {
1048           // This input vector is already an operand.
1049           break;
1050         } else if (InputUsed[OpNo] == -1U) {
1051           // Create a new operand for this input vector.
1052           InputUsed[OpNo] = Input;
1053           break;
1054         }
1055       }
1056
1057       if (OpNo >= array_lengthof(InputUsed)) {
1058         // More than two input vectors used!  Give up on trying to create a
1059         // shuffle vector.  Insert all elements into a BUILD_VECTOR instead.
1060         useBuildVector = true;
1061         break;
1062       }
1063
1064       // Add the mask index for the new shuffle vector.
1065       Ops.push_back(Idx + OpNo * NewElts);
1066     }
1067
1068     if (useBuildVector) {
1069       EVT EltVT = NewVT.getVectorElementType();
1070       SmallVector<SDValue, 16> SVOps;
1071
1072       // Extract the input elements by hand.
1073       for (unsigned MaskOffset = 0; MaskOffset < NewElts; ++MaskOffset) {
1074         // The mask element.  This indexes into the input.
1075         int Idx = N->getMaskElt(FirstMaskIdx + MaskOffset);
1076
1077         // The input vector this mask element indexes into.
1078         unsigned Input = (unsigned)Idx / NewElts;
1079
1080         if (Input >= array_lengthof(Inputs)) {
1081           // The mask element is "undef" or indexes off the end of the input.
1082           SVOps.push_back(DAG.getUNDEF(EltVT));
1083           continue;
1084         }
1085
1086         // Turn the index into an offset from the start of the input vector.
1087         Idx -= Input * NewElts;
1088
1089         // Extract the vector element by hand.
1090         SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
1091                                     Inputs[Input], DAG.getConstant(Idx,
1092                                                    TLI.getVectorIdxTy())));
1093       }
1094
1095       // Construct the Lo/Hi output using a BUILD_VECTOR.
1096       Output = DAG.getNode(ISD::BUILD_VECTOR,dl,NewVT, &SVOps[0], SVOps.size());
1097     } else if (InputUsed[0] == -1U) {
1098       // No input vectors were used!  The result is undefined.
1099       Output = DAG.getUNDEF(NewVT);
1100     } else {
1101       SDValue Op0 = Inputs[InputUsed[0]];
1102       // If only one input was used, use an undefined vector for the other.
1103       SDValue Op1 = InputUsed[1] == -1U ?
1104         DAG.getUNDEF(NewVT) : Inputs[InputUsed[1]];
1105       // At least one input vector was used.  Create a new shuffle vector.
1106       Output =  DAG.getVectorShuffle(NewVT, dl, Op0, Op1, &Ops[0]);
1107     }
1108
1109     Ops.clear();
1110   }
1111 }
1112
1113
1114 //===----------------------------------------------------------------------===//
1115 //  Operand Vector Splitting
1116 //===----------------------------------------------------------------------===//
1117
1118 /// SplitVectorOperand - This method is called when the specified operand of the
1119 /// specified node is found to need vector splitting.  At this point, all of the
1120 /// result types of the node are known to be legal, but other operands of the
1121 /// node may need legalization as well as the specified one.
1122 bool DAGTypeLegalizer::SplitVectorOperand(SDNode *N, unsigned OpNo) {
1123   DEBUG(dbgs() << "Split node operand: ";
1124         N->dump(&DAG);
1125         dbgs() << "\n");
1126   SDValue Res = SDValue();
1127
1128   // See if the target wants to custom split this node.
1129   if (CustomLowerNode(N, N->getOperand(OpNo).getValueType(), false))
1130     return false;
1131
1132   if (!Res.getNode()) {
1133     switch (N->getOpcode()) {
1134     default:
1135 #ifndef NDEBUG
1136       dbgs() << "SplitVectorOperand Op #" << OpNo << ": ";
1137       N->dump(&DAG);
1138       dbgs() << "\n";
1139 #endif
1140       report_fatal_error("Do not know how to split this operator's "
1141                          "operand!\n");
1142
1143     case ISD::SETCC:             Res = SplitVecOp_VSETCC(N); break;
1144     case ISD::BITCAST:           Res = SplitVecOp_BITCAST(N); break;
1145     case ISD::EXTRACT_SUBVECTOR: Res = SplitVecOp_EXTRACT_SUBVECTOR(N); break;
1146     case ISD::EXTRACT_VECTOR_ELT:Res = SplitVecOp_EXTRACT_VECTOR_ELT(N); break;
1147     case ISD::CONCAT_VECTORS:    Res = SplitVecOp_CONCAT_VECTORS(N); break;
1148     case ISD::TRUNCATE:          Res = SplitVecOp_TRUNCATE(N); break;
1149     case ISD::FP_ROUND:          Res = SplitVecOp_FP_ROUND(N); break;
1150     case ISD::STORE:
1151       Res = SplitVecOp_STORE(cast<StoreSDNode>(N), OpNo);
1152       break;
1153     case ISD::VSELECT:
1154       Res = SplitVecOp_VSELECT(N, OpNo);
1155       break;
1156     case ISD::CTTZ:
1157     case ISD::CTLZ:
1158     case ISD::CTPOP:
1159     case ISD::FP_EXTEND:
1160     case ISD::FP_TO_SINT:
1161     case ISD::FP_TO_UINT:
1162     case ISD::SINT_TO_FP:
1163     case ISD::UINT_TO_FP:
1164     case ISD::FTRUNC:
1165     case ISD::SIGN_EXTEND:
1166     case ISD::ZERO_EXTEND:
1167     case ISD::ANY_EXTEND:
1168       Res = SplitVecOp_UnaryOp(N);
1169       break;
1170     }
1171   }
1172
1173   // If the result is null, the sub-method took care of registering results etc.
1174   if (!Res.getNode()) return false;
1175
1176   // If the result is N, the sub-method updated N in place.  Tell the legalizer
1177   // core about this.
1178   if (Res.getNode() == N)
1179     return true;
1180
1181   assert(Res.getValueType() == N->getValueType(0) && N->getNumValues() == 1 &&
1182          "Invalid operand expansion");
1183
1184   ReplaceValueWith(SDValue(N, 0), Res);
1185   return false;
1186 }
1187
1188 SDValue DAGTypeLegalizer::SplitVecOp_VSELECT(SDNode *N, unsigned OpNo) {
1189   // The only possibility for an illegal operand is the mask, since result type
1190   // legalization would have handled this node already otherwise.
1191   assert(OpNo == 0 && "Illegal operand must be mask");
1192
1193   SDValue Mask = N->getOperand(0);
1194   SDValue Src0 = N->getOperand(1);
1195   SDValue Src1 = N->getOperand(2);
1196   EVT Src0VT = Src0.getValueType();
1197   SDLoc DL(N);
1198   assert(Mask.getValueType().isVector() && "VSELECT without a vector mask?");
1199
1200   SDValue Lo, Hi;
1201   GetSplitVector(N->getOperand(0), Lo, Hi);
1202   assert(Lo.getValueType() == Hi.getValueType() &&
1203          "Lo and Hi have differing types");
1204
1205   EVT LoOpVT, HiOpVT;
1206   std::tie(LoOpVT, HiOpVT) = DAG.GetSplitDestVTs(Src0VT);
1207   assert(LoOpVT == HiOpVT && "Asymmetric vector split?");
1208
1209   SDValue LoOp0, HiOp0, LoOp1, HiOp1, LoMask, HiMask;
1210   std::tie(LoOp0, HiOp0) = DAG.SplitVector(Src0, DL);
1211   std::tie(LoOp1, HiOp1) = DAG.SplitVector(Src1, DL);
1212   std::tie(LoMask, HiMask) = DAG.SplitVector(Mask, DL);
1213
1214   SDValue LoSelect =
1215     DAG.getNode(ISD::VSELECT, DL, LoOpVT, LoMask, LoOp0, LoOp1);
1216   SDValue HiSelect =
1217     DAG.getNode(ISD::VSELECT, DL, HiOpVT, HiMask, HiOp0, HiOp1);
1218
1219   return DAG.getNode(ISD::CONCAT_VECTORS, DL, Src0VT, LoSelect, HiSelect);
1220 }
1221
1222 SDValue DAGTypeLegalizer::SplitVecOp_UnaryOp(SDNode *N) {
1223   // The result has a legal vector type, but the input needs splitting.
1224   EVT ResVT = N->getValueType(0);
1225   SDValue Lo, Hi;
1226   SDLoc dl(N);
1227   GetSplitVector(N->getOperand(0), Lo, Hi);
1228   EVT InVT = Lo.getValueType();
1229
1230   EVT OutVT = EVT::getVectorVT(*DAG.getContext(), ResVT.getVectorElementType(),
1231                                InVT.getVectorNumElements());
1232
1233   Lo = DAG.getNode(N->getOpcode(), dl, OutVT, Lo);
1234   Hi = DAG.getNode(N->getOpcode(), dl, OutVT, Hi);
1235
1236   return DAG.getNode(ISD::CONCAT_VECTORS, dl, ResVT, Lo, Hi);
1237 }
1238
1239 SDValue DAGTypeLegalizer::SplitVecOp_BITCAST(SDNode *N) {
1240   // For example, i64 = BITCAST v4i16 on alpha.  Typically the vector will
1241   // end up being split all the way down to individual components.  Convert the
1242   // split pieces into integers and reassemble.
1243   SDValue Lo, Hi;
1244   GetSplitVector(N->getOperand(0), Lo, Hi);
1245   Lo = BitConvertToInteger(Lo);
1246   Hi = BitConvertToInteger(Hi);
1247
1248   if (TLI.isBigEndian())
1249     std::swap(Lo, Hi);
1250
1251   return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0),
1252                      JoinIntegers(Lo, Hi));
1253 }
1254
1255 SDValue DAGTypeLegalizer::SplitVecOp_EXTRACT_SUBVECTOR(SDNode *N) {
1256   // We know that the extracted result type is legal.
1257   EVT SubVT = N->getValueType(0);
1258   SDValue Idx = N->getOperand(1);
1259   SDLoc dl(N);
1260   SDValue Lo, Hi;
1261   GetSplitVector(N->getOperand(0), Lo, Hi);
1262
1263   uint64_t LoElts = Lo.getValueType().getVectorNumElements();
1264   uint64_t IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
1265
1266   if (IdxVal < LoElts) {
1267     assert(IdxVal + SubVT.getVectorNumElements() <= LoElts &&
1268            "Extracted subvector crosses vector split!");
1269     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, Lo, Idx);
1270   } else {
1271     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, Hi,
1272                        DAG.getConstant(IdxVal - LoElts, Idx.getValueType()));
1273   }
1274 }
1275
1276 SDValue DAGTypeLegalizer::SplitVecOp_EXTRACT_VECTOR_ELT(SDNode *N) {
1277   SDValue Vec = N->getOperand(0);
1278   SDValue Idx = N->getOperand(1);
1279   EVT VecVT = Vec.getValueType();
1280
1281   if (isa<ConstantSDNode>(Idx)) {
1282     uint64_t IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
1283     assert(IdxVal < VecVT.getVectorNumElements() && "Invalid vector index!");
1284
1285     SDValue Lo, Hi;
1286     GetSplitVector(Vec, Lo, Hi);
1287
1288     uint64_t LoElts = Lo.getValueType().getVectorNumElements();
1289
1290     if (IdxVal < LoElts)
1291       return SDValue(DAG.UpdateNodeOperands(N, Lo, Idx), 0);
1292     return SDValue(DAG.UpdateNodeOperands(N, Hi,
1293                                   DAG.getConstant(IdxVal - LoElts,
1294                                                   Idx.getValueType())), 0);
1295   }
1296
1297   // Store the vector to the stack.
1298   EVT EltVT = VecVT.getVectorElementType();
1299   SDLoc dl(N);
1300   SDValue StackPtr = DAG.CreateStackTemporary(VecVT);
1301   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Vec, StackPtr,
1302                                MachinePointerInfo(), false, false, 0);
1303
1304   // Load back the required element.
1305   StackPtr = GetVectorElementPointer(StackPtr, EltVT, Idx);
1306   return DAG.getExtLoad(ISD::EXTLOAD, dl, N->getValueType(0), Store, StackPtr,
1307                         MachinePointerInfo(), EltVT, false, false, 0);
1308 }
1309
1310 SDValue DAGTypeLegalizer::SplitVecOp_STORE(StoreSDNode *N, unsigned OpNo) {
1311   assert(N->isUnindexed() && "Indexed store of vector?");
1312   assert(OpNo == 1 && "Can only split the stored value");
1313   SDLoc DL(N);
1314
1315   bool isTruncating = N->isTruncatingStore();
1316   SDValue Ch  = N->getChain();
1317   SDValue Ptr = N->getBasePtr();
1318   EVT MemoryVT = N->getMemoryVT();
1319   unsigned Alignment = N->getOriginalAlignment();
1320   bool isVol = N->isVolatile();
1321   bool isNT = N->isNonTemporal();
1322   const MDNode *TBAAInfo = N->getTBAAInfo();
1323   SDValue Lo, Hi;
1324   GetSplitVector(N->getOperand(1), Lo, Hi);
1325
1326   EVT LoMemVT, HiMemVT;
1327   std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
1328
1329   unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
1330
1331   if (isTruncating)
1332     Lo = DAG.getTruncStore(Ch, DL, Lo, Ptr, N->getPointerInfo(),
1333                            LoMemVT, isVol, isNT, Alignment, TBAAInfo);
1334   else
1335     Lo = DAG.getStore(Ch, DL, Lo, Ptr, N->getPointerInfo(),
1336                       isVol, isNT, Alignment, TBAAInfo);
1337
1338   // Increment the pointer to the other half.
1339   Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
1340                     DAG.getConstant(IncrementSize, Ptr.getValueType()));
1341
1342   if (isTruncating)
1343     Hi = DAG.getTruncStore(Ch, DL, Hi, Ptr,
1344                            N->getPointerInfo().getWithOffset(IncrementSize),
1345                            HiMemVT, isVol, isNT, Alignment, TBAAInfo);
1346   else
1347     Hi = DAG.getStore(Ch, DL, Hi, Ptr,
1348                       N->getPointerInfo().getWithOffset(IncrementSize),
1349                       isVol, isNT, Alignment, TBAAInfo);
1350
1351   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
1352 }
1353
1354 SDValue DAGTypeLegalizer::SplitVecOp_CONCAT_VECTORS(SDNode *N) {
1355   SDLoc DL(N);
1356
1357   // The input operands all must have the same type, and we know the result
1358   // type is valid.  Convert this to a buildvector which extracts all the
1359   // input elements.
1360   // TODO: If the input elements are power-two vectors, we could convert this to
1361   // a new CONCAT_VECTORS node with elements that are half-wide.
1362   SmallVector<SDValue, 32> Elts;
1363   EVT EltVT = N->getValueType(0).getVectorElementType();
1364   for (unsigned op = 0, e = N->getNumOperands(); op != e; ++op) {
1365     SDValue Op = N->getOperand(op);
1366     for (unsigned i = 0, e = Op.getValueType().getVectorNumElements();
1367          i != e; ++i) {
1368       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT,
1369                                  Op, DAG.getConstant(i, TLI.getVectorIdxTy())));
1370
1371     }
1372   }
1373
1374   return DAG.getNode(ISD::BUILD_VECTOR, DL, N->getValueType(0),
1375                      &Elts[0], Elts.size());
1376 }
1377
1378 SDValue DAGTypeLegalizer::SplitVecOp_TRUNCATE(SDNode *N) {
1379   // The result type is legal, but the input type is illegal.  If splitting
1380   // ends up with the result type of each half still being legal, just
1381   // do that.  If, however, that would result in an illegal result type,
1382   // we can try to get more clever with power-two vectors. Specifically,
1383   // split the input type, but also widen the result element size, then
1384   // concatenate the halves and truncate again.  For example, consider a target
1385   // where v8i8 is legal and v8i32 is not (ARM, which doesn't have 256-bit
1386   // vectors). To perform a "%res = v8i8 trunc v8i32 %in" we do:
1387   //   %inlo = v4i32 extract_subvector %in, 0
1388   //   %inhi = v4i32 extract_subvector %in, 4
1389   //   %lo16 = v4i16 trunc v4i32 %inlo
1390   //   %hi16 = v4i16 trunc v4i32 %inhi
1391   //   %in16 = v8i16 concat_vectors v4i16 %lo16, v4i16 %hi16
1392   //   %res = v8i8 trunc v8i16 %in16
1393   //
1394   // Without this transform, the original truncate would end up being
1395   // scalarized, which is pretty much always a last resort.
1396   SDValue InVec = N->getOperand(0);
1397   EVT InVT = InVec->getValueType(0);
1398   EVT OutVT = N->getValueType(0);
1399   unsigned NumElements = OutVT.getVectorNumElements();
1400   // Widening should have already made sure this is a power-two vector
1401   // if we're trying to split it at all. assert() that's true, just in case.
1402   assert(!(NumElements & 1) && "Splitting vector, but not in half!");
1403
1404   unsigned InElementSize = InVT.getVectorElementType().getSizeInBits();
1405   unsigned OutElementSize = OutVT.getVectorElementType().getSizeInBits();
1406
1407   // If the input elements are only 1/2 the width of the result elements,
1408   // just use the normal splitting. Our trick only work if there's room
1409   // to split more than once.
1410   if (InElementSize <= OutElementSize * 2)
1411     return SplitVecOp_UnaryOp(N);
1412   SDLoc DL(N);
1413
1414   // Extract the halves of the input via extract_subvector.
1415   SDValue InLoVec, InHiVec;
1416   std::tie(InLoVec, InHiVec) = DAG.SplitVector(InVec, DL);
1417   // Truncate them to 1/2 the element size.
1418   EVT HalfElementVT = EVT::getIntegerVT(*DAG.getContext(), InElementSize/2);
1419   EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), HalfElementVT,
1420                                 NumElements/2);
1421   SDValue HalfLo = DAG.getNode(ISD::TRUNCATE, DL, HalfVT, InLoVec);
1422   SDValue HalfHi = DAG.getNode(ISD::TRUNCATE, DL, HalfVT, InHiVec);
1423   // Concatenate them to get the full intermediate truncation result.
1424   EVT InterVT = EVT::getVectorVT(*DAG.getContext(), HalfElementVT, NumElements);
1425   SDValue InterVec = DAG.getNode(ISD::CONCAT_VECTORS, DL, InterVT, HalfLo,
1426                                  HalfHi);
1427   // Now finish up by truncating all the way down to the original result
1428   // type. This should normally be something that ends up being legal directly,
1429   // but in theory if a target has very wide vectors and an annoyingly
1430   // restricted set of legal types, this split can chain to build things up.
1431   return DAG.getNode(ISD::TRUNCATE, DL, OutVT, InterVec);
1432 }
1433
1434 SDValue DAGTypeLegalizer::SplitVecOp_VSETCC(SDNode *N) {
1435   assert(N->getValueType(0).isVector() &&
1436          N->getOperand(0).getValueType().isVector() &&
1437          "Operand types must be vectors");
1438   // The result has a legal vector type, but the input needs splitting.
1439   SDValue Lo0, Hi0, Lo1, Hi1, LoRes, HiRes;
1440   SDLoc DL(N);
1441   GetSplitVector(N->getOperand(0), Lo0, Hi0);
1442   GetSplitVector(N->getOperand(1), Lo1, Hi1);
1443   unsigned PartElements = Lo0.getValueType().getVectorNumElements();
1444   EVT PartResVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1, PartElements);
1445   EVT WideResVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1, 2*PartElements);
1446
1447   LoRes = DAG.getNode(ISD::SETCC, DL, PartResVT, Lo0, Lo1, N->getOperand(2));
1448   HiRes = DAG.getNode(ISD::SETCC, DL, PartResVT, Hi0, Hi1, N->getOperand(2));
1449   SDValue Con = DAG.getNode(ISD::CONCAT_VECTORS, DL, WideResVT, LoRes, HiRes);
1450   return PromoteTargetBoolean(Con, N->getValueType(0));
1451 }
1452
1453
1454 SDValue DAGTypeLegalizer::SplitVecOp_FP_ROUND(SDNode *N) {
1455   // The result has a legal vector type, but the input needs splitting.
1456   EVT ResVT = N->getValueType(0);
1457   SDValue Lo, Hi;
1458   SDLoc DL(N);
1459   GetSplitVector(N->getOperand(0), Lo, Hi);
1460   EVT InVT = Lo.getValueType();
1461
1462   EVT OutVT = EVT::getVectorVT(*DAG.getContext(), ResVT.getVectorElementType(),
1463                                InVT.getVectorNumElements());
1464
1465   Lo = DAG.getNode(ISD::FP_ROUND, DL, OutVT, Lo, N->getOperand(1));
1466   Hi = DAG.getNode(ISD::FP_ROUND, DL, OutVT, Hi, N->getOperand(1));
1467
1468   return DAG.getNode(ISD::CONCAT_VECTORS, DL, ResVT, Lo, Hi);
1469 }
1470
1471
1472
1473 //===----------------------------------------------------------------------===//
1474 //  Result Vector Widening
1475 //===----------------------------------------------------------------------===//
1476
1477 void DAGTypeLegalizer::WidenVectorResult(SDNode *N, unsigned ResNo) {
1478   DEBUG(dbgs() << "Widen node result " << ResNo << ": ";
1479         N->dump(&DAG);
1480         dbgs() << "\n");
1481
1482   // See if the target wants to custom widen this node.
1483   if (CustomWidenLowerNode(N, N->getValueType(ResNo)))
1484     return;
1485
1486   SDValue Res = SDValue();
1487   switch (N->getOpcode()) {
1488   default:
1489 #ifndef NDEBUG
1490     dbgs() << "WidenVectorResult #" << ResNo << ": ";
1491     N->dump(&DAG);
1492     dbgs() << "\n";
1493 #endif
1494     llvm_unreachable("Do not know how to widen the result of this operator!");
1495
1496   case ISD::MERGE_VALUES:      Res = WidenVecRes_MERGE_VALUES(N, ResNo); break;
1497   case ISD::BITCAST:           Res = WidenVecRes_BITCAST(N); break;
1498   case ISD::BUILD_VECTOR:      Res = WidenVecRes_BUILD_VECTOR(N); break;
1499   case ISD::CONCAT_VECTORS:    Res = WidenVecRes_CONCAT_VECTORS(N); break;
1500   case ISD::CONVERT_RNDSAT:    Res = WidenVecRes_CONVERT_RNDSAT(N); break;
1501   case ISD::EXTRACT_SUBVECTOR: Res = WidenVecRes_EXTRACT_SUBVECTOR(N); break;
1502   case ISD::FP_ROUND_INREG:    Res = WidenVecRes_InregOp(N); break;
1503   case ISD::INSERT_VECTOR_ELT: Res = WidenVecRes_INSERT_VECTOR_ELT(N); break;
1504   case ISD::LOAD:              Res = WidenVecRes_LOAD(N); break;
1505   case ISD::SCALAR_TO_VECTOR:  Res = WidenVecRes_SCALAR_TO_VECTOR(N); break;
1506   case ISD::SIGN_EXTEND_INREG: Res = WidenVecRes_InregOp(N); break;
1507   case ISD::VSELECT:
1508   case ISD::SELECT:            Res = WidenVecRes_SELECT(N); break;
1509   case ISD::SELECT_CC:         Res = WidenVecRes_SELECT_CC(N); break;
1510   case ISD::SETCC:             Res = WidenVecRes_SETCC(N); break;
1511   case ISD::UNDEF:             Res = WidenVecRes_UNDEF(N); break;
1512   case ISD::VECTOR_SHUFFLE:
1513     Res = WidenVecRes_VECTOR_SHUFFLE(cast<ShuffleVectorSDNode>(N));
1514     break;
1515
1516   case ISD::ADD:
1517   case ISD::AND:
1518   case ISD::BSWAP:
1519   case ISD::MUL:
1520   case ISD::MULHS:
1521   case ISD::MULHU:
1522   case ISD::OR:
1523   case ISD::SUB:
1524   case ISD::XOR:
1525     Res = WidenVecRes_Binary(N);
1526     break;
1527
1528   case ISD::FADD:
1529   case ISD::FCOPYSIGN:
1530   case ISD::FMUL:
1531   case ISD::FPOW:
1532   case ISD::FSUB:
1533   case ISD::FDIV:
1534   case ISD::FREM:
1535   case ISD::SDIV:
1536   case ISD::UDIV:
1537   case ISD::SREM:
1538   case ISD::UREM:
1539     Res = WidenVecRes_BinaryCanTrap(N);
1540     break;
1541
1542   case ISD::FPOWI:
1543     Res = WidenVecRes_POWI(N);
1544     break;
1545
1546   case ISD::SHL:
1547   case ISD::SRA:
1548   case ISD::SRL:
1549     Res = WidenVecRes_Shift(N);
1550     break;
1551
1552   case ISD::ANY_EXTEND:
1553   case ISD::FP_EXTEND:
1554   case ISD::FP_ROUND:
1555   case ISD::FP_TO_SINT:
1556   case ISD::FP_TO_UINT:
1557   case ISD::SIGN_EXTEND:
1558   case ISD::SINT_TO_FP:
1559   case ISD::TRUNCATE:
1560   case ISD::UINT_TO_FP:
1561   case ISD::ZERO_EXTEND:
1562     Res = WidenVecRes_Convert(N);
1563     break;
1564
1565   case ISD::CTLZ:
1566   case ISD::CTPOP:
1567   case ISD::CTTZ:
1568   case ISD::FABS:
1569   case ISD::FCEIL:
1570   case ISD::FCOS:
1571   case ISD::FEXP:
1572   case ISD::FEXP2:
1573   case ISD::FFLOOR:
1574   case ISD::FLOG:
1575   case ISD::FLOG10:
1576   case ISD::FLOG2:
1577   case ISD::FNEARBYINT:
1578   case ISD::FNEG:
1579   case ISD::FRINT:
1580   case ISD::FROUND:
1581   case ISD::FSIN:
1582   case ISD::FSQRT:
1583   case ISD::FTRUNC:
1584     Res = WidenVecRes_Unary(N);
1585     break;
1586   case ISD::FMA:
1587     Res = WidenVecRes_Ternary(N);
1588     break;
1589   }
1590
1591   // If Res is null, the sub-method took care of registering the result.
1592   if (Res.getNode())
1593     SetWidenedVector(SDValue(N, ResNo), Res);
1594 }
1595
1596 SDValue DAGTypeLegalizer::WidenVecRes_Ternary(SDNode *N) {
1597   // Ternary op widening.
1598   SDLoc dl(N);
1599   EVT WidenVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
1600   SDValue InOp1 = GetWidenedVector(N->getOperand(0));
1601   SDValue InOp2 = GetWidenedVector(N->getOperand(1));
1602   SDValue InOp3 = GetWidenedVector(N->getOperand(2));
1603   return DAG.getNode(N->getOpcode(), dl, WidenVT, InOp1, InOp2, InOp3);
1604 }
1605
1606 SDValue DAGTypeLegalizer::WidenVecRes_Binary(SDNode *N) {
1607   // Binary op widening.
1608   SDLoc dl(N);
1609   EVT WidenVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
1610   SDValue InOp1 = GetWidenedVector(N->getOperand(0));
1611   SDValue InOp2 = GetWidenedVector(N->getOperand(1));
1612   return DAG.getNode(N->getOpcode(), dl, WidenVT, InOp1, InOp2);
1613 }
1614
1615 SDValue DAGTypeLegalizer::WidenVecRes_BinaryCanTrap(SDNode *N) {
1616   // Binary op widening for operations that can trap.
1617   unsigned Opcode = N->getOpcode();
1618   SDLoc dl(N);
1619   EVT WidenVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
1620   EVT WidenEltVT = WidenVT.getVectorElementType();
1621   EVT VT = WidenVT;
1622   unsigned NumElts =  VT.getVectorNumElements();
1623   while (!TLI.isTypeLegal(VT) && NumElts != 1) {
1624     NumElts = NumElts / 2;
1625     VT = EVT::getVectorVT(*DAG.getContext(), WidenEltVT, NumElts);
1626   }
1627
1628   if (NumElts != 1 && !TLI.canOpTrap(N->getOpcode(), VT)) {
1629     // Operation doesn't trap so just widen as normal.
1630     SDValue InOp1 = GetWidenedVector(N->getOperand(0));
1631     SDValue InOp2 = GetWidenedVector(N->getOperand(1));
1632     return DAG.getNode(N->getOpcode(), dl, WidenVT, InOp1, InOp2);
1633   }
1634
1635   // No legal vector version so unroll the vector operation and then widen.
1636   if (NumElts == 1)
1637     return DAG.UnrollVectorOp(N, WidenVT.getVectorNumElements());
1638
1639   // Since the operation can trap, apply operation on the original vector.
1640   EVT MaxVT = VT;
1641   SDValue InOp1 = GetWidenedVector(N->getOperand(0));
1642   SDValue InOp2 = GetWidenedVector(N->getOperand(1));
1643   unsigned CurNumElts = N->getValueType(0).getVectorNumElements();
1644
1645   SmallVector<SDValue, 16> ConcatOps(CurNumElts);
1646   unsigned ConcatEnd = 0;  // Current ConcatOps index.
1647   int Idx = 0;        // Current Idx into input vectors.
1648
1649   // NumElts := greatest legal vector size (at most WidenVT)
1650   // while (orig. vector has unhandled elements) {
1651   //   take munches of size NumElts from the beginning and add to ConcatOps
1652   //   NumElts := next smaller supported vector size or 1
1653   // }
1654   while (CurNumElts != 0) {
1655     while (CurNumElts >= NumElts) {
1656       SDValue EOp1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, InOp1,
1657                                  DAG.getConstant(Idx, TLI.getVectorIdxTy()));
1658       SDValue EOp2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, InOp2,
1659                                  DAG.getConstant(Idx, TLI.getVectorIdxTy()));
1660       ConcatOps[ConcatEnd++] = DAG.getNode(Opcode, dl, VT, EOp1, EOp2);
1661       Idx += NumElts;
1662       CurNumElts -= NumElts;
1663     }
1664     do {
1665       NumElts = NumElts / 2;
1666       VT = EVT::getVectorVT(*DAG.getContext(), WidenEltVT, NumElts);
1667     } while (!TLI.isTypeLegal(VT) && NumElts != 1);
1668
1669     if (NumElts == 1) {
1670       for (unsigned i = 0; i != CurNumElts; ++i, ++Idx) {
1671         SDValue EOp1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, WidenEltVT,
1672                                    InOp1, DAG.getConstant(Idx,
1673                                                          TLI.getVectorIdxTy()));
1674         SDValue EOp2 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, WidenEltVT,
1675                                    InOp2, DAG.getConstant(Idx,
1676                                                          TLI.getVectorIdxTy()));
1677         ConcatOps[ConcatEnd++] = DAG.getNode(Opcode, dl, WidenEltVT,
1678                                              EOp1, EOp2);
1679       }
1680       CurNumElts = 0;
1681     }
1682   }
1683
1684   // Check to see if we have a single operation with the widen type.
1685   if (ConcatEnd == 1) {
1686     VT = ConcatOps[0].getValueType();
1687     if (VT == WidenVT)
1688       return ConcatOps[0];
1689   }
1690
1691   // while (Some element of ConcatOps is not of type MaxVT) {
1692   //   From the end of ConcatOps, collect elements of the same type and put
1693   //   them into an op of the next larger supported type
1694   // }
1695   while (ConcatOps[ConcatEnd-1].getValueType() != MaxVT) {
1696     Idx = ConcatEnd - 1;
1697     VT = ConcatOps[Idx--].getValueType();
1698     while (Idx >= 0 && ConcatOps[Idx].getValueType() == VT)
1699       Idx--;
1700
1701     int NextSize = VT.isVector() ? VT.getVectorNumElements() : 1;
1702     EVT NextVT;
1703     do {
1704       NextSize *= 2;
1705       NextVT = EVT::getVectorVT(*DAG.getContext(), WidenEltVT, NextSize);
1706     } while (!TLI.isTypeLegal(NextVT));
1707
1708     if (!VT.isVector()) {
1709       // Scalar type, create an INSERT_VECTOR_ELEMENT of type NextVT
1710       SDValue VecOp = DAG.getUNDEF(NextVT);
1711       unsigned NumToInsert = ConcatEnd - Idx - 1;
1712       for (unsigned i = 0, OpIdx = Idx+1; i < NumToInsert; i++, OpIdx++) {
1713         VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, NextVT, VecOp,
1714                             ConcatOps[OpIdx], DAG.getConstant(i,
1715                                                          TLI.getVectorIdxTy()));
1716       }
1717       ConcatOps[Idx+1] = VecOp;
1718       ConcatEnd = Idx + 2;
1719     } else {
1720       // Vector type, create a CONCAT_VECTORS of type NextVT
1721       SDValue undefVec = DAG.getUNDEF(VT);
1722       unsigned OpsToConcat = NextSize/VT.getVectorNumElements();
1723       SmallVector<SDValue, 16> SubConcatOps(OpsToConcat);
1724       unsigned RealVals = ConcatEnd - Idx - 1;
1725       unsigned SubConcatEnd = 0;
1726       unsigned SubConcatIdx = Idx + 1;
1727       while (SubConcatEnd < RealVals)
1728         SubConcatOps[SubConcatEnd++] = ConcatOps[++Idx];
1729       while (SubConcatEnd < OpsToConcat)
1730         SubConcatOps[SubConcatEnd++] = undefVec;
1731       ConcatOps[SubConcatIdx] = DAG.getNode(ISD::CONCAT_VECTORS, dl,
1732                                             NextVT, &SubConcatOps[0],
1733                                             OpsToConcat);
1734       ConcatEnd = SubConcatIdx + 1;
1735     }
1736   }
1737
1738   // Check to see if we have a single operation with the widen type.
1739   if (ConcatEnd == 1) {
1740     VT = ConcatOps[0].getValueType();
1741     if (VT == WidenVT)
1742       return ConcatOps[0];
1743   }
1744
1745   // add undefs of size MaxVT until ConcatOps grows to length of WidenVT
1746   unsigned NumOps = WidenVT.getVectorNumElements()/MaxVT.getVectorNumElements();
1747   if (NumOps != ConcatEnd ) {
1748     SDValue UndefVal = DAG.getUNDEF(MaxVT);
1749     for (unsigned j = ConcatEnd; j < NumOps; ++j)
1750       ConcatOps[j] = UndefVal;
1751   }
1752   return DAG.getNode(ISD::CONCAT_VECTORS, dl, WidenVT, &ConcatOps[0], NumOps);
1753 }
1754
1755 SDValue DAGTypeLegalizer::WidenVecRes_Convert(SDNode *N) {
1756   SDValue InOp = N->getOperand(0);
1757   SDLoc DL(N);
1758
1759   EVT WidenVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
1760   unsigned WidenNumElts = WidenVT.getVectorNumElements();
1761
1762   EVT InVT = InOp.getValueType();
1763   EVT InEltVT = InVT.getVectorElementType();
1764   EVT InWidenVT = EVT::getVectorVT(*DAG.getContext(), InEltVT, WidenNumElts);
1765
1766   unsigned Opcode = N->getOpcode();
1767   unsigned InVTNumElts = InVT.getVectorNumElements();
1768
1769   if (getTypeAction(InVT) == TargetLowering::TypeWidenVector) {
1770     InOp = GetWidenedVector(N->getOperand(0));
1771     InVT = InOp.getValueType();
1772     InVTNumElts = InVT.getVectorNumElements();
1773     if (InVTNumElts == WidenNumElts) {
1774       if (N->getNumOperands() == 1)
1775         return DAG.getNode(Opcode, DL, WidenVT, InOp);
1776       return DAG.getNode(Opcode, DL, WidenVT, InOp, N->getOperand(1));
1777     }
1778   }
1779
1780   if (TLI.isTypeLegal(InWidenVT)) {
1781     // Because the result and the input are different vector types, widening
1782     // the result could create a legal type but widening the input might make
1783     // it an illegal type that might lead to repeatedly splitting the input
1784     // and then widening it. To avoid this, we widen the input only if
1785     // it results in a legal type.
1786     if (WidenNumElts % InVTNumElts == 0) {
1787       // Widen the input and call convert on the widened input vector.
1788       unsigned NumConcat = WidenNumElts/InVTNumElts;
1789       SmallVector<SDValue, 16> Ops(NumConcat);
1790       Ops[0] = InOp;
1791       SDValue UndefVal = DAG.getUNDEF(InVT);
1792       for (unsigned i = 1; i != NumConcat; ++i)
1793         Ops[i] = UndefVal;
1794       SDValue InVec = DAG.getNode(ISD::CONCAT_VECTORS, DL, InWidenVT,
1795                                   &Ops[0], NumConcat);
1796       if (N->getNumOperands() == 1)
1797         return DAG.getNode(Opcode, DL, WidenVT, InVec);
1798       return DAG.getNode(Opcode, DL, WidenVT, InVec, N->getOperand(1));
1799     }
1800
1801     if (InVTNumElts % WidenNumElts == 0) {
1802       SDValue InVal = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InWidenVT,
1803                                   InOp, DAG.getConstant(0,
1804                                                         TLI.getVectorIdxTy()));
1805       // Extract the input and convert the shorten input vector.
1806       if (N->getNumOperands() == 1)
1807         return DAG.getNode(Opcode, DL, WidenVT, InVal);
1808       return DAG.getNode(Opcode, DL, WidenVT, InVal, N->getOperand(1));
1809     }
1810   }
1811
1812   // Otherwise unroll into some nasty scalar code and rebuild the vector.
1813   SmallVector<SDValue, 16> Ops(WidenNumElts);
1814   EVT EltVT = WidenVT.getVectorElementType();
1815   unsigned MinElts = std::min(InVTNumElts, WidenNumElts);
1816   unsigned i;
1817   for (i=0; i < MinElts; ++i) {
1818     SDValue Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, InEltVT, InOp,
1819                               DAG.getConstant(i, TLI.getVectorIdxTy()));
1820     if (N->getNumOperands() == 1)
1821       Ops[i] = DAG.getNode(Opcode, DL, EltVT, Val);
1822     else
1823       Ops[i] = DAG.getNode(Opcode, DL, EltVT, Val, N->getOperand(1));
1824   }
1825
1826   SDValue UndefVal = DAG.getUNDEF(EltVT);
1827   for (; i < WidenNumElts; ++i)
1828     Ops[i] = UndefVal;
1829
1830   return DAG.getNode(ISD::BUILD_VECTOR, DL, WidenVT, &Ops[0], WidenNumElts);
1831 }
1832
1833 SDValue DAGTypeLegalizer::WidenVecRes_POWI(SDNode *N) {
1834   EVT WidenVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
1835   SDValue InOp = GetWidenedVector(N->getOperand(0));
1836   SDValue ShOp = N->getOperand(1);
1837   return DAG.getNode(N->getOpcode(), SDLoc(N), WidenVT, InOp, ShOp);
1838 }
1839
1840 SDValue DAGTypeLegalizer::WidenVecRes_Shift(SDNode *N) {
1841   EVT WidenVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
1842   SDValue InOp = GetWidenedVector(N->getOperand(0));
1843   SDValue ShOp = N->getOperand(1);
1844
1845   EVT ShVT = ShOp.getValueType();
1846   if (getTypeAction(ShVT) == TargetLowering::TypeWidenVector) {
1847     ShOp = GetWidenedVector(ShOp);
1848     ShVT = ShOp.getValueType();
1849   }
1850   EVT ShWidenVT = EVT::getVectorVT(*DAG.getContext(),
1851                                    ShVT.getVectorElementType(),
1852                                    WidenVT.getVectorNumElements());
1853   if (ShVT != ShWidenVT)
1854     ShOp = ModifyToType(ShOp, ShWidenVT);
1855
1856   return DAG.getNode(N->getOpcode(), SDLoc(N), WidenVT, InOp, ShOp);
1857 }
1858
1859 SDValue DAGTypeLegalizer::WidenVecRes_Unary(SDNode *N) {
1860   // Unary op widening.
1861   EVT WidenVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
1862   SDValue InOp = GetWidenedVector(N->getOperand(0));
1863   return DAG.getNode(N->getOpcode(), SDLoc(N), WidenVT, InOp);
1864 }
1865
1866 SDValue DAGTypeLegalizer::WidenVecRes_InregOp(SDNode *N) {
1867   EVT WidenVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
1868   EVT ExtVT = EVT::getVectorVT(*DAG.getContext(),
1869                                cast<VTSDNode>(N->getOperand(1))->getVT()
1870                                  .getVectorElementType(),
1871                                WidenVT.getVectorNumElements());
1872   SDValue WidenLHS = GetWidenedVector(N->getOperand(0));
1873   return DAG.getNode(N->getOpcode(), SDLoc(N),
1874                      WidenVT, WidenLHS, DAG.getValueType(ExtVT));
1875 }
1876
1877 SDValue DAGTypeLegalizer::WidenVecRes_MERGE_VALUES(SDNode *N, unsigned ResNo) {
1878   SDValue WidenVec = DisintegrateMERGE_VALUES(N, ResNo);
1879   return GetWidenedVector(WidenVec);
1880 }
1881
1882 SDValue DAGTypeLegalizer::WidenVecRes_BITCAST(SDNode *N) {
1883   SDValue InOp = N->getOperand(0);
1884   EVT InVT = InOp.getValueType();
1885   EVT VT = N->getValueType(0);
1886   EVT WidenVT = TLI.getTypeToTransformTo(*DAG.getContext(), VT);
1887   SDLoc dl(N);
1888
1889   switch (getTypeAction(InVT)) {
1890   case TargetLowering::TypeLegal:
1891     break;
1892   case TargetLowering::TypePromoteInteger:
1893     // If the incoming type is a vector that is being promoted, then
1894     // we know that the elements are arranged differently and that we
1895     // must perform the conversion using a stack slot.
1896     if (InVT.isVector())
1897       break;
1898
1899     // If the InOp is promoted to the same size, convert it.  Otherwise,
1900     // fall out of the switch and widen the promoted input.
1901     InOp = GetPromotedInteger(InOp);
1902     InVT = InOp.getValueType();
1903     if (WidenVT.bitsEq(InVT))
1904       return DAG.getNode(ISD::BITCAST, dl, WidenVT, InOp);
1905     break;
1906   case TargetLowering::TypeSoftenFloat:
1907   case TargetLowering::TypeExpandInteger:
1908   case TargetLowering::TypeExpandFloat:
1909   case TargetLowering::TypeScalarizeVector:
1910   case TargetLowering::TypeSplitVector:
1911     break;
1912   case TargetLowering::TypeWidenVector:
1913     // If the InOp is widened to the same size, convert it.  Otherwise, fall
1914     // out of the switch and widen the widened input.
1915     InOp = GetWidenedVector(InOp);
1916     InVT = InOp.getValueType();
1917     if (WidenVT.bitsEq(InVT))
1918       // The input widens to the same size. Convert to the widen value.
1919       return DAG.getNode(ISD::BITCAST, dl, WidenVT, InOp);
1920     break;
1921   }
1922
1923   unsigned WidenSize = WidenVT.getSizeInBits();
1924   unsigned InSize = InVT.getSizeInBits();
1925   // x86mmx is not an acceptable vector element type, so don't try.
1926   if (WidenSize % InSize == 0 && InVT != MVT::x86mmx) {
1927     // Determine new input vector type.  The new input vector type will use
1928     // the same element type (if its a vector) or use the input type as a
1929     // vector.  It is the same size as the type to widen to.
1930     EVT NewInVT;
1931     unsigned NewNumElts = WidenSize / InSize;
1932     if (InVT.isVector()) {
1933       EVT InEltVT = InVT.getVectorElementType();
1934       NewInVT = EVT::getVectorVT(*DAG.getContext(), InEltVT,
1935                                  WidenSize / InEltVT.getSizeInBits());
1936     } else {
1937       NewInVT = EVT::getVectorVT(*DAG.getContext(), InVT, NewNumElts);
1938     }
1939
1940     if (TLI.isTypeLegal(NewInVT)) {
1941       // Because the result and the input are different vector types, widening
1942       // the result could create a legal type but widening the input might make
1943       // it an illegal type that might lead to repeatedly splitting the input
1944       // and then widening it. To avoid this, we widen the input only if
1945       // it results in a legal type.
1946       SmallVector<SDValue, 16> Ops(NewNumElts);
1947       SDValue UndefVal = DAG.getUNDEF(InVT);
1948       Ops[0] = InOp;
1949       for (unsigned i = 1; i < NewNumElts; ++i)
1950         Ops[i] = UndefVal;
1951
1952       SDValue NewVec;
1953       if (InVT.isVector())
1954         NewVec = DAG.getNode(ISD::CONCAT_VECTORS, dl,
1955                              NewInVT, &Ops[0], NewNumElts);
1956       else
1957         NewVec = DAG.getNode(ISD::BUILD_VECTOR, dl,
1958                              NewInVT, &Ops[0], NewNumElts);
1959       return DAG.getNode(ISD::BITCAST, dl, WidenVT, NewVec);
1960     }
1961   }
1962
1963   return CreateStackStoreLoad(InOp, WidenVT);
1964 }
1965
1966 SDValue DAGTypeLegalizer::WidenVecRes_BUILD_VECTOR(SDNode *N) {
1967   SDLoc dl(N);
1968   // Build a vector with undefined for the new nodes.
1969   EVT VT = N->getValueType(0);
1970
1971   // Integer BUILD_VECTOR operands may be larger than the node's vector element
1972   // type. The UNDEFs need to have the same type as the existing operands.
1973   EVT EltVT = N->getOperand(0).getValueType();
1974   unsigned NumElts = VT.getVectorNumElements();
1975
1976   EVT WidenVT = TLI.getTypeToTransformTo(*DAG.getContext(), VT);
1977   unsigned WidenNumElts = WidenVT.getVectorNumElements();
1978
1979   SmallVector<SDValue, 16> NewOps(N->op_begin(), N->op_end());
1980   assert(WidenNumElts >= NumElts && "Shrinking vector instead of widening!");
1981   NewOps.append(WidenNumElts - NumElts, DAG.getUNDEF(EltVT));
1982
1983   return DAG.getNode(ISD::BUILD_VECTOR, dl, WidenVT, &NewOps[0], NewOps.size());
1984 }
1985
1986 SDValue DAGTypeLegalizer::WidenVecRes_CONCAT_VECTORS(SDNode *N) {
1987   EVT InVT = N->getOperand(0).getValueType();
1988   EVT WidenVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
1989   SDLoc dl(N);
1990   unsigned WidenNumElts = WidenVT.getVectorNumElements();
1991   unsigned NumInElts = InVT.getVectorNumElements();
1992   unsigned NumOperands = N->getNumOperands();
1993
1994   bool InputWidened = false; // Indicates we need to widen the input.
1995   if (getTypeAction(InVT) != TargetLowering::TypeWidenVector) {
1996     if (WidenVT.getVectorNumElements() % InVT.getVectorNumElements() == 0) {
1997       // Add undef vectors to widen to correct length.
1998       unsigned NumConcat = WidenVT.getVectorNumElements() /
1999                            InVT.getVectorNumElements();
2000       SDValue UndefVal = DAG.getUNDEF(InVT);
2001       SmallVector<SDValue, 16> Ops(NumConcat);
2002       for (unsigned i=0; i < NumOperands; ++i)
2003         Ops[i] = N->getOperand(i);
2004       for (unsigned i = NumOperands; i != NumConcat; ++i)
2005         Ops[i] = UndefVal;
2006       return DAG.getNode(ISD::CONCAT_VECTORS, dl, WidenVT, &Ops[0], NumConcat);
2007     }
2008   } else {
2009     InputWidened = true;
2010     if (WidenVT == TLI.getTypeToTransformTo(*DAG.getContext(), InVT)) {
2011       // The inputs and the result are widen to the same value.
2012       unsigned i;
2013       for (i=1; i < NumOperands; ++i)
2014         if (N->getOperand(i).getOpcode() != ISD::UNDEF)
2015           break;
2016
2017       if (i == NumOperands)
2018         // Everything but the first operand is an UNDEF so just return the
2019         // widened first operand.
2020         return GetWidenedVector(N->getOperand(0));
2021
2022       if (NumOperands == 2) {
2023         // Replace concat of two operands with a shuffle.
2024         SmallVector<int, 16> MaskOps(WidenNumElts, -1);
2025         for (unsigned i = 0; i < NumInElts; ++i) {
2026           MaskOps[i] = i;
2027           MaskOps[i + NumInElts] = i + WidenNumElts;
2028         }
2029         return DAG.getVectorShuffle(WidenVT, dl,
2030                                     GetWidenedVector(N->getOperand(0)),
2031                                     GetWidenedVector(N->getOperand(1)),
2032                                     &MaskOps[0]);
2033       }
2034     }
2035   }
2036
2037   // Fall back to use extracts and build vector.
2038   EVT EltVT = WidenVT.getVectorElementType();
2039   SmallVector<SDValue, 16> Ops(WidenNumElts);
2040   unsigned Idx = 0;
2041   for (unsigned i=0; i < NumOperands; ++i) {
2042     SDValue InOp = N->getOperand(i);
2043     if (InputWidened)
2044       InOp = GetWidenedVector(InOp);
2045     for (unsigned j=0; j < NumInElts; ++j)
2046       Ops[Idx++] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, InOp,
2047                                DAG.getConstant(j, TLI.getVectorIdxTy()));
2048   }
2049   SDValue UndefVal = DAG.getUNDEF(EltVT);
2050   for (; Idx < WidenNumElts; ++Idx)
2051     Ops[Idx] = UndefVal;
2052   return DAG.getNode(ISD::BUILD_VECTOR, dl, WidenVT, &Ops[0], WidenNumElts);
2053 }
2054
2055 SDValue DAGTypeLegalizer::WidenVecRes_CONVERT_RNDSAT(SDNode *N) {
2056   SDLoc dl(N);
2057   SDValue InOp  = N->getOperand(0);
2058   SDValue RndOp = N->getOperand(3);
2059   SDValue SatOp = N->getOperand(4);
2060
2061   EVT WidenVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
2062   unsigned WidenNumElts = WidenVT.getVectorNumElements();
2063
2064   EVT InVT = InOp.getValueType();
2065   EVT InEltVT = InVT.getVectorElementType();
2066   EVT InWidenVT = EVT::getVectorVT(*DAG.getContext(), InEltVT, WidenNumElts);
2067
2068   SDValue DTyOp = DAG.getValueType(WidenVT);
2069   SDValue STyOp = DAG.getValueType(InWidenVT);
2070   ISD::CvtCode CvtCode = cast<CvtRndSatSDNode>(N)->getCvtCode();
2071
2072   unsigned InVTNumElts = InVT.getVectorNumElements();
2073   if (getTypeAction(InVT) == TargetLowering::TypeWidenVector) {
2074     InOp = GetWidenedVector(InOp);
2075     InVT = InOp.getValueType();
2076     InVTNumElts = InVT.getVectorNumElements();
2077     if (InVTNumElts == WidenNumElts)
2078       return DAG.getConvertRndSat(WidenVT, dl, InOp, DTyOp, STyOp, RndOp,
2079                                   SatOp, CvtCode);
2080   }
2081
2082   if (TLI.isTypeLegal(InWidenVT)) {
2083     // Because the result and the input are different vector types, widening
2084     // the result could create a legal type but widening the input might make
2085     // it an illegal type that might lead to repeatedly splitting the input
2086     // and then widening it. To avoid this, we widen the input only if
2087     // it results in a legal type.
2088     if (WidenNumElts % InVTNumElts == 0) {
2089       // Widen the input and call convert on the widened input vector.
2090       unsigned NumConcat = WidenNumElts/InVTNumElts;
2091       SmallVector<SDValue, 16> Ops(NumConcat);
2092       Ops[0] = InOp;
2093       SDValue UndefVal = DAG.getUNDEF(InVT);
2094       for (unsigned i = 1; i != NumConcat; ++i)
2095         Ops[i] = UndefVal;
2096
2097       InOp = DAG.getNode(ISD::CONCAT_VECTORS, dl, InWidenVT, &Ops[0],NumConcat);
2098       return DAG.getConvertRndSat(WidenVT, dl, InOp, DTyOp, STyOp, RndOp,
2099                                   SatOp, CvtCode);
2100     }
2101
2102     if (InVTNumElts % WidenNumElts == 0) {
2103       // Extract the input and convert the shorten input vector.
2104       InOp = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, InWidenVT, InOp,
2105                          DAG.getConstant(0, TLI.getVectorIdxTy()));
2106       return DAG.getConvertRndSat(WidenVT, dl, InOp, DTyOp, STyOp, RndOp,
2107                                   SatOp, CvtCode);
2108     }
2109   }
2110
2111   // Otherwise unroll into some nasty scalar code and rebuild the vector.
2112   SmallVector<SDValue, 16> Ops(WidenNumElts);
2113   EVT EltVT = WidenVT.getVectorElementType();
2114   DTyOp = DAG.getValueType(EltVT);
2115   STyOp = DAG.getValueType(InEltVT);
2116
2117   unsigned MinElts = std::min(InVTNumElts, WidenNumElts);
2118   unsigned i;
2119   for (i=0; i < MinElts; ++i) {
2120     SDValue ExtVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, InEltVT, InOp,
2121                                  DAG.getConstant(i, TLI.getVectorIdxTy()));
2122     Ops[i] = DAG.getConvertRndSat(WidenVT, dl, ExtVal, DTyOp, STyOp, RndOp,
2123                                   SatOp, CvtCode);
2124   }
2125
2126   SDValue UndefVal = DAG.getUNDEF(EltVT);
2127   for (; i < WidenNumElts; ++i)
2128     Ops[i] = UndefVal;
2129
2130   return DAG.getNode(ISD::BUILD_VECTOR, dl, WidenVT, &Ops[0], WidenNumElts);
2131 }
2132
2133 SDValue DAGTypeLegalizer::WidenVecRes_EXTRACT_SUBVECTOR(SDNode *N) {
2134   EVT      VT = N->getValueType(0);
2135   EVT      WidenVT = TLI.getTypeToTransformTo(*DAG.getContext(), VT);
2136   unsigned WidenNumElts = WidenVT.getVectorNumElements();
2137   SDValue  InOp = N->getOperand(0);
2138   SDValue  Idx  = N->getOperand(1);
2139   SDLoc dl(N);
2140
2141   if (getTypeAction(InOp.getValueType()) == TargetLowering::TypeWidenVector)
2142     InOp = GetWidenedVector(InOp);
2143
2144   EVT InVT = InOp.getValueType();
2145
2146   // Check if we can just return the input vector after widening.
2147   uint64_t IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
2148   if (IdxVal == 0 && InVT == WidenVT)
2149     return InOp;
2150
2151   // Check if we can extract from the vector.
2152   unsigned InNumElts = InVT.getVectorNumElements();
2153   if (IdxVal % WidenNumElts == 0 && IdxVal + WidenNumElts < InNumElts)
2154     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, WidenVT, InOp, Idx);
2155
2156   // We could try widening the input to the right length but for now, extract
2157   // the original elements, fill the rest with undefs and build a vector.
2158   SmallVector<SDValue, 16> Ops(WidenNumElts);
2159   EVT EltVT = VT.getVectorElementType();
2160   unsigned NumElts = VT.getVectorNumElements();
2161   unsigned i;
2162   for (i=0; i < NumElts; ++i)
2163     Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, InOp,
2164                          DAG.getConstant(IdxVal+i, TLI.getVectorIdxTy()));
2165
2166   SDValue UndefVal = DAG.getUNDEF(EltVT);
2167   for (; i < WidenNumElts; ++i)
2168     Ops[i] = UndefVal;
2169   return DAG.getNode(ISD::BUILD_VECTOR, dl, WidenVT, &Ops[0], WidenNumElts);
2170 }
2171
2172 SDValue DAGTypeLegalizer::WidenVecRes_INSERT_VECTOR_ELT(SDNode *N) {
2173   SDValue InOp = GetWidenedVector(N->getOperand(0));
2174   return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N),
2175                      InOp.getValueType(), InOp,
2176                      N->getOperand(1), N->getOperand(2));
2177 }
2178
2179 SDValue DAGTypeLegalizer::WidenVecRes_LOAD(SDNode *N) {
2180   LoadSDNode *LD = cast<LoadSDNode>(N);
2181   ISD::LoadExtType ExtType = LD->getExtensionType();
2182
2183   SDValue Result;
2184   SmallVector<SDValue, 16> LdChain;  // Chain for the series of load
2185   if (ExtType != ISD::NON_EXTLOAD)
2186     Result = GenWidenVectorExtLoads(LdChain, LD, ExtType);
2187   else
2188     Result = GenWidenVectorLoads(LdChain, LD);
2189
2190   // If we generate a single load, we can use that for the chain.  Otherwise,
2191   // build a factor node to remember the multiple loads are independent and
2192   // chain to that.
2193   SDValue NewChain;
2194   if (LdChain.size() == 1)
2195     NewChain = LdChain[0];
2196   else
2197     NewChain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
2198                            &LdChain[0], LdChain.size());
2199
2200   // Modified the chain - switch anything that used the old chain to use
2201   // the new one.
2202   ReplaceValueWith(SDValue(N, 1), NewChain);
2203
2204   return Result;
2205 }
2206
2207 SDValue DAGTypeLegalizer::WidenVecRes_SCALAR_TO_VECTOR(SDNode *N) {
2208   EVT WidenVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
2209   return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(N),
2210                      WidenVT, N->getOperand(0));
2211 }
2212
2213 SDValue DAGTypeLegalizer::WidenVecRes_SELECT(SDNode *N) {
2214   EVT WidenVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
2215   unsigned WidenNumElts = WidenVT.getVectorNumElements();
2216
2217   SDValue Cond1 = N->getOperand(0);
2218   EVT CondVT = Cond1.getValueType();
2219   if (CondVT.isVector()) {
2220     EVT CondEltVT = CondVT.getVectorElementType();
2221     EVT CondWidenVT =  EVT::getVectorVT(*DAG.getContext(),
2222                                         CondEltVT, WidenNumElts);
2223     if (getTypeAction(CondVT) == TargetLowering::TypeWidenVector)
2224       Cond1 = GetWidenedVector(Cond1);
2225
2226     // If we have to split the condition there is no point in widening the
2227     // select. This would result in an cycle of widening the select ->
2228     // widening the condition operand -> splitting the condition operand ->
2229     // splitting the select -> widening the select. Instead split this select
2230     // further and widen the resulting type.
2231     if (getTypeAction(CondVT) == TargetLowering::TypeSplitVector) {
2232       SDValue SplitSelect = SplitVecOp_VSELECT(N, 0);
2233       SDValue Res = ModifyToType(SplitSelect, WidenVT);
2234       return Res;
2235     }
2236
2237     if (Cond1.getValueType() != CondWidenVT)
2238       Cond1 = ModifyToType(Cond1, CondWidenVT);
2239   }
2240
2241   SDValue InOp1 = GetWidenedVector(N->getOperand(1));
2242   SDValue InOp2 = GetWidenedVector(N->getOperand(2));
2243   assert(InOp1.getValueType() == WidenVT && InOp2.getValueType() == WidenVT);
2244   return DAG.getNode(N->getOpcode(), SDLoc(N),
2245                      WidenVT, Cond1, InOp1, InOp2);
2246 }
2247
2248 SDValue DAGTypeLegalizer::WidenVecRes_SELECT_CC(SDNode *N) {
2249   SDValue InOp1 = GetWidenedVector(N->getOperand(2));
2250   SDValue InOp2 = GetWidenedVector(N->getOperand(3));
2251   return DAG.getNode(ISD::SELECT_CC, SDLoc(N),
2252                      InOp1.getValueType(), N->getOperand(0),
2253                      N->getOperand(1), InOp1, InOp2, N->getOperand(4));
2254 }
2255
2256 SDValue DAGTypeLegalizer::WidenVecRes_SETCC(SDNode *N) {
2257   assert(N->getValueType(0).isVector() ==
2258          N->getOperand(0).getValueType().isVector() &&
2259          "Scalar/Vector type mismatch");
2260   if (N->getValueType(0).isVector()) return WidenVecRes_VSETCC(N);
2261
2262   EVT WidenVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
2263   SDValue InOp1 = GetWidenedVector(N->getOperand(0));
2264   SDValue InOp2 = GetWidenedVector(N->getOperand(1));
2265   return DAG.getNode(ISD::SETCC, SDLoc(N), WidenVT,
2266                      InOp1, InOp2, N->getOperand(2));
2267 }
2268
2269 SDValue DAGTypeLegalizer::WidenVecRes_UNDEF(SDNode *N) {
2270  EVT WidenVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
2271  return DAG.getUNDEF(WidenVT);
2272 }
2273
2274 SDValue DAGTypeLegalizer::WidenVecRes_VECTOR_SHUFFLE(ShuffleVectorSDNode *N) {
2275   EVT VT = N->getValueType(0);
2276   SDLoc dl(N);
2277
2278   EVT WidenVT = TLI.getTypeToTransformTo(*DAG.getContext(), VT);
2279   unsigned NumElts = VT.getVectorNumElements();
2280   unsigned WidenNumElts = WidenVT.getVectorNumElements();
2281
2282   SDValue InOp1 = GetWidenedVector(N->getOperand(0));
2283   SDValue InOp2 = GetWidenedVector(N->getOperand(1));
2284
2285   // Adjust mask based on new input vector length.
2286   SmallVector<int, 16> NewMask;
2287   for (unsigned i = 0; i != NumElts; ++i) {
2288     int Idx = N->getMaskElt(i);
2289     if (Idx < (int)NumElts)
2290       NewMask.push_back(Idx);
2291     else
2292       NewMask.push_back(Idx - NumElts + WidenNumElts);
2293   }
2294   for (unsigned i = NumElts; i != WidenNumElts; ++i)
2295     NewMask.push_back(-1);
2296   return DAG.getVectorShuffle(WidenVT, dl, InOp1, InOp2, &NewMask[0]);
2297 }
2298
2299 SDValue DAGTypeLegalizer::WidenVecRes_VSETCC(SDNode *N) {
2300   assert(N->getValueType(0).isVector() &&
2301          N->getOperand(0).getValueType().isVector() &&
2302          "Operands must be vectors");
2303   EVT WidenVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
2304   unsigned WidenNumElts = WidenVT.getVectorNumElements();
2305
2306   SDValue InOp1 = N->getOperand(0);
2307   EVT InVT = InOp1.getValueType();
2308   assert(InVT.isVector() && "can not widen non-vector type");
2309   EVT WidenInVT = EVT::getVectorVT(*DAG.getContext(),
2310                                    InVT.getVectorElementType(), WidenNumElts);
2311   InOp1 = GetWidenedVector(InOp1);
2312   SDValue InOp2 = GetWidenedVector(N->getOperand(1));
2313
2314   // Assume that the input and output will be widen appropriately.  If not,
2315   // we will have to unroll it at some point.
2316   assert(InOp1.getValueType() == WidenInVT &&
2317          InOp2.getValueType() == WidenInVT &&
2318          "Input not widened to expected type!");
2319   (void)WidenInVT;
2320   return DAG.getNode(ISD::SETCC, SDLoc(N),
2321                      WidenVT, InOp1, InOp2, N->getOperand(2));
2322 }
2323
2324
2325 //===----------------------------------------------------------------------===//
2326 // Widen Vector Operand
2327 //===----------------------------------------------------------------------===//
2328 bool DAGTypeLegalizer::WidenVectorOperand(SDNode *N, unsigned OpNo) {
2329   DEBUG(dbgs() << "Widen node operand " << OpNo << ": ";
2330         N->dump(&DAG);
2331         dbgs() << "\n");
2332   SDValue Res = SDValue();
2333
2334   // See if the target wants to custom widen this node.
2335   if (CustomLowerNode(N, N->getOperand(OpNo).getValueType(), false))
2336     return false;
2337
2338   switch (N->getOpcode()) {
2339   default:
2340 #ifndef NDEBUG
2341     dbgs() << "WidenVectorOperand op #" << OpNo << ": ";
2342     N->dump(&DAG);
2343     dbgs() << "\n";
2344 #endif
2345     llvm_unreachable("Do not know how to widen this operator's operand!");
2346
2347   case ISD::BITCAST:            Res = WidenVecOp_BITCAST(N); break;
2348   case ISD::CONCAT_VECTORS:     Res = WidenVecOp_CONCAT_VECTORS(N); break;
2349   case ISD::EXTRACT_SUBVECTOR:  Res = WidenVecOp_EXTRACT_SUBVECTOR(N); break;
2350   case ISD::EXTRACT_VECTOR_ELT: Res = WidenVecOp_EXTRACT_VECTOR_ELT(N); break;
2351   case ISD::STORE:              Res = WidenVecOp_STORE(N); break;
2352   case ISD::SETCC:              Res = WidenVecOp_SETCC(N); break;
2353
2354   case ISD::FP_EXTEND:
2355   case ISD::FP_TO_SINT:
2356   case ISD::FP_TO_UINT:
2357   case ISD::SINT_TO_FP:
2358   case ISD::UINT_TO_FP:
2359   case ISD::TRUNCATE:
2360   case ISD::SIGN_EXTEND:
2361   case ISD::ZERO_EXTEND:
2362   case ISD::ANY_EXTEND:
2363     Res = WidenVecOp_Convert(N);
2364     break;
2365   }
2366
2367   // If Res is null, the sub-method took care of registering the result.
2368   if (!Res.getNode()) return false;
2369
2370   // If the result is N, the sub-method updated N in place.  Tell the legalizer
2371   // core about this.
2372   if (Res.getNode() == N)
2373     return true;
2374
2375
2376   assert(Res.getValueType() == N->getValueType(0) && N->getNumValues() == 1 &&
2377          "Invalid operand expansion");
2378
2379   ReplaceValueWith(SDValue(N, 0), Res);
2380   return false;
2381 }
2382
2383 SDValue DAGTypeLegalizer::WidenVecOp_Convert(SDNode *N) {
2384   // Since the result is legal and the input is illegal, it is unlikely
2385   // that we can fix the input to a legal type so unroll the convert
2386   // into some scalar code and create a nasty build vector.
2387   EVT VT = N->getValueType(0);
2388   EVT EltVT = VT.getVectorElementType();
2389   SDLoc dl(N);
2390   unsigned NumElts = VT.getVectorNumElements();
2391   SDValue InOp = N->getOperand(0);
2392   if (getTypeAction(InOp.getValueType()) == TargetLowering::TypeWidenVector)
2393     InOp = GetWidenedVector(InOp);
2394   EVT InVT = InOp.getValueType();
2395   EVT InEltVT = InVT.getVectorElementType();
2396
2397   unsigned Opcode = N->getOpcode();
2398   SmallVector<SDValue, 16> Ops(NumElts);
2399   for (unsigned i=0; i < NumElts; ++i)
2400     Ops[i] = DAG.getNode(Opcode, dl, EltVT,
2401                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, InEltVT, InOp,
2402                                      DAG.getConstant(i, TLI.getVectorIdxTy())));
2403
2404   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Ops[0], NumElts);
2405 }
2406
2407 SDValue DAGTypeLegalizer::WidenVecOp_BITCAST(SDNode *N) {
2408   EVT VT = N->getValueType(0);
2409   SDValue InOp = GetWidenedVector(N->getOperand(0));
2410   EVT InWidenVT = InOp.getValueType();
2411   SDLoc dl(N);
2412
2413   // Check if we can convert between two legal vector types and extract.
2414   unsigned InWidenSize = InWidenVT.getSizeInBits();
2415   unsigned Size = VT.getSizeInBits();
2416   // x86mmx is not an acceptable vector element type, so don't try.
2417   if (InWidenSize % Size == 0 && !VT.isVector() && VT != MVT::x86mmx) {
2418     unsigned NewNumElts = InWidenSize / Size;
2419     EVT NewVT = EVT::getVectorVT(*DAG.getContext(), VT, NewNumElts);
2420     if (TLI.isTypeLegal(NewVT)) {
2421       SDValue BitOp = DAG.getNode(ISD::BITCAST, dl, NewVT, InOp);
2422       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, BitOp,
2423                          DAG.getConstant(0, TLI.getVectorIdxTy()));
2424     }
2425   }
2426
2427   return CreateStackStoreLoad(InOp, VT);
2428 }
2429
2430 SDValue DAGTypeLegalizer::WidenVecOp_CONCAT_VECTORS(SDNode *N) {
2431   // If the input vector is not legal, it is likely that we will not find a
2432   // legal vector of the same size. Replace the concatenate vector with a
2433   // nasty build vector.
2434   EVT VT = N->getValueType(0);
2435   EVT EltVT = VT.getVectorElementType();
2436   SDLoc dl(N);
2437   unsigned NumElts = VT.getVectorNumElements();
2438   SmallVector<SDValue, 16> Ops(NumElts);
2439
2440   EVT InVT = N->getOperand(0).getValueType();
2441   unsigned NumInElts = InVT.getVectorNumElements();
2442
2443   unsigned Idx = 0;
2444   unsigned NumOperands = N->getNumOperands();
2445   for (unsigned i=0; i < NumOperands; ++i) {
2446     SDValue InOp = N->getOperand(i);
2447     if (getTypeAction(InOp.getValueType()) == TargetLowering::TypeWidenVector)
2448       InOp = GetWidenedVector(InOp);
2449     for (unsigned j=0; j < NumInElts; ++j)
2450       Ops[Idx++] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, InOp,
2451                                DAG.getConstant(j, TLI.getVectorIdxTy()));
2452   }
2453   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Ops[0], NumElts);
2454 }
2455
2456 SDValue DAGTypeLegalizer::WidenVecOp_EXTRACT_SUBVECTOR(SDNode *N) {
2457   SDValue InOp = GetWidenedVector(N->getOperand(0));
2458   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(N),
2459                      N->getValueType(0), InOp, N->getOperand(1));
2460 }
2461
2462 SDValue DAGTypeLegalizer::WidenVecOp_EXTRACT_VECTOR_ELT(SDNode *N) {
2463   SDValue InOp = GetWidenedVector(N->getOperand(0));
2464   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N),
2465                      N->getValueType(0), InOp, N->getOperand(1));
2466 }
2467
2468 SDValue DAGTypeLegalizer::WidenVecOp_STORE(SDNode *N) {
2469   // We have to widen the value but we want only to store the original
2470   // vector type.
2471   StoreSDNode *ST = cast<StoreSDNode>(N);
2472
2473   SmallVector<SDValue, 16> StChain;
2474   if (ST->isTruncatingStore())
2475     GenWidenVectorTruncStores(StChain, ST);
2476   else
2477     GenWidenVectorStores(StChain, ST);
2478
2479   if (StChain.size() == 1)
2480     return StChain[0];
2481   else
2482     return DAG.getNode(ISD::TokenFactor, SDLoc(ST),
2483                        MVT::Other,&StChain[0],StChain.size());
2484 }
2485
2486 SDValue DAGTypeLegalizer::WidenVecOp_SETCC(SDNode *N) {
2487   SDValue InOp0 = GetWidenedVector(N->getOperand(0));
2488   SDValue InOp1 = GetWidenedVector(N->getOperand(1));
2489   SDLoc dl(N);
2490
2491   // WARNING: In this code we widen the compare instruction with garbage.
2492   // This garbage may contain denormal floats which may be slow. Is this a real
2493   // concern ? Should we zero the unused lanes if this is a float compare ?
2494
2495   // Get a new SETCC node to compare the newly widened operands.
2496   // Only some of the compared elements are legal.
2497   EVT SVT = TLI.getSetCCResultType(*DAG.getContext(), InOp0.getValueType());
2498   SDValue WideSETCC = DAG.getNode(ISD::SETCC, SDLoc(N),
2499                      SVT, InOp0, InOp1, N->getOperand(2));
2500
2501   // Extract the needed results from the result vector.
2502   EVT ResVT = EVT::getVectorVT(*DAG.getContext(),
2503                                SVT.getVectorElementType(),
2504                                N->getValueType(0).getVectorNumElements());
2505   SDValue CC = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl,
2506                            ResVT, WideSETCC, DAG.getConstant(0,
2507                                              TLI.getVectorIdxTy()));
2508
2509   return PromoteTargetBoolean(CC, N->getValueType(0));
2510 }
2511
2512
2513 //===----------------------------------------------------------------------===//
2514 // Vector Widening Utilities
2515 //===----------------------------------------------------------------------===//
2516
2517 // Utility function to find the type to chop up a widen vector for load/store
2518 //  TLI:       Target lowering used to determine legal types.
2519 //  Width:     Width left need to load/store.
2520 //  WidenVT:   The widen vector type to load to/store from
2521 //  Align:     If 0, don't allow use of a wider type
2522 //  WidenEx:   If Align is not 0, the amount additional we can load/store from.
2523
2524 static EVT FindMemType(SelectionDAG& DAG, const TargetLowering &TLI,
2525                        unsigned Width, EVT WidenVT,
2526                        unsigned Align = 0, unsigned WidenEx = 0) {
2527   EVT WidenEltVT = WidenVT.getVectorElementType();
2528   unsigned WidenWidth = WidenVT.getSizeInBits();
2529   unsigned WidenEltWidth = WidenEltVT.getSizeInBits();
2530   unsigned AlignInBits = Align*8;
2531
2532   // If we have one element to load/store, return it.
2533   EVT RetVT = WidenEltVT;
2534   if (Width == WidenEltWidth)
2535     return RetVT;
2536
2537   // See if there is larger legal integer than the element type to load/store
2538   unsigned VT;
2539   for (VT = (unsigned)MVT::LAST_INTEGER_VALUETYPE;
2540        VT >= (unsigned)MVT::FIRST_INTEGER_VALUETYPE; --VT) {
2541     EVT MemVT((MVT::SimpleValueType) VT);
2542     unsigned MemVTWidth = MemVT.getSizeInBits();
2543     if (MemVT.getSizeInBits() <= WidenEltWidth)
2544       break;
2545     if (TLI.isTypeLegal(MemVT) && (WidenWidth % MemVTWidth) == 0 &&
2546         isPowerOf2_32(WidenWidth / MemVTWidth) &&
2547         (MemVTWidth <= Width ||
2548          (Align!=0 && MemVTWidth<=AlignInBits && MemVTWidth<=Width+WidenEx))) {
2549       RetVT = MemVT;
2550       break;
2551     }
2552   }
2553
2554   // See if there is a larger vector type to load/store that has the same vector
2555   // element type and is evenly divisible with the WidenVT.
2556   for (VT = (unsigned)MVT::LAST_VECTOR_VALUETYPE;
2557        VT >= (unsigned)MVT::FIRST_VECTOR_VALUETYPE; --VT) {
2558     EVT MemVT = (MVT::SimpleValueType) VT;
2559     unsigned MemVTWidth = MemVT.getSizeInBits();
2560     if (TLI.isTypeLegal(MemVT) && WidenEltVT == MemVT.getVectorElementType() &&
2561         (WidenWidth % MemVTWidth) == 0 &&
2562         isPowerOf2_32(WidenWidth / MemVTWidth) &&
2563         (MemVTWidth <= Width ||
2564          (Align!=0 && MemVTWidth<=AlignInBits && MemVTWidth<=Width+WidenEx))) {
2565       if (RetVT.getSizeInBits() < MemVTWidth || MemVT == WidenVT)
2566         return MemVT;
2567     }
2568   }
2569
2570   return RetVT;
2571 }
2572
2573 // Builds a vector type from scalar loads
2574 //  VecTy: Resulting Vector type
2575 //  LDOps: Load operators to build a vector type
2576 //  [Start,End) the list of loads to use.
2577 static SDValue BuildVectorFromScalar(SelectionDAG& DAG, EVT VecTy,
2578                                      SmallVectorImpl<SDValue> &LdOps,
2579                                      unsigned Start, unsigned End) {
2580   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2581   SDLoc dl(LdOps[Start]);
2582   EVT LdTy = LdOps[Start].getValueType();
2583   unsigned Width = VecTy.getSizeInBits();
2584   unsigned NumElts = Width / LdTy.getSizeInBits();
2585   EVT NewVecVT = EVT::getVectorVT(*DAG.getContext(), LdTy, NumElts);
2586
2587   unsigned Idx = 1;
2588   SDValue VecOp = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NewVecVT,LdOps[Start]);
2589
2590   for (unsigned i = Start + 1; i != End; ++i) {
2591     EVT NewLdTy = LdOps[i].getValueType();
2592     if (NewLdTy != LdTy) {
2593       NumElts = Width / NewLdTy.getSizeInBits();
2594       NewVecVT = EVT::getVectorVT(*DAG.getContext(), NewLdTy, NumElts);
2595       VecOp = DAG.getNode(ISD::BITCAST, dl, NewVecVT, VecOp);
2596       // Readjust position and vector position based on new load type
2597       Idx = Idx * LdTy.getSizeInBits() / NewLdTy.getSizeInBits();
2598       LdTy = NewLdTy;
2599     }
2600     VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, NewVecVT, VecOp, LdOps[i],
2601                         DAG.getConstant(Idx++, TLI.getVectorIdxTy()));
2602   }
2603   return DAG.getNode(ISD::BITCAST, dl, VecTy, VecOp);
2604 }
2605
2606 SDValue DAGTypeLegalizer::GenWidenVectorLoads(SmallVectorImpl<SDValue> &LdChain,
2607                                               LoadSDNode *LD) {
2608   // The strategy assumes that we can efficiently load powers of two widths.
2609   // The routines chops the vector into the largest vector loads with the same
2610   // element type or scalar loads and then recombines it to the widen vector
2611   // type.
2612   EVT WidenVT = TLI.getTypeToTransformTo(*DAG.getContext(),LD->getValueType(0));
2613   unsigned WidenWidth = WidenVT.getSizeInBits();
2614   EVT LdVT    = LD->getMemoryVT();
2615   SDLoc dl(LD);
2616   assert(LdVT.isVector() && WidenVT.isVector());
2617   assert(LdVT.getVectorElementType() == WidenVT.getVectorElementType());
2618
2619   // Load information
2620   SDValue   Chain = LD->getChain();
2621   SDValue   BasePtr = LD->getBasePtr();
2622   unsigned  Align    = LD->getAlignment();
2623   bool      isVolatile = LD->isVolatile();
2624   bool      isNonTemporal = LD->isNonTemporal();
2625   bool      isInvariant = LD->isInvariant();
2626   const MDNode *TBAAInfo = LD->getTBAAInfo();
2627
2628   int LdWidth = LdVT.getSizeInBits();
2629   int WidthDiff = WidenWidth - LdWidth;          // Difference
2630   unsigned LdAlign = (isVolatile) ? 0 : Align; // Allow wider loads
2631
2632   // Find the vector type that can load from.
2633   EVT NewVT = FindMemType(DAG, TLI, LdWidth, WidenVT, LdAlign, WidthDiff);
2634   int NewVTWidth = NewVT.getSizeInBits();
2635   SDValue LdOp = DAG.getLoad(NewVT, dl, Chain, BasePtr, LD->getPointerInfo(),
2636                              isVolatile, isNonTemporal, isInvariant, Align,
2637                              TBAAInfo);
2638   LdChain.push_back(LdOp.getValue(1));
2639
2640   // Check if we can load the element with one instruction
2641   if (LdWidth <= NewVTWidth) {
2642     if (!NewVT.isVector()) {
2643       unsigned NumElts = WidenWidth / NewVTWidth;
2644       EVT NewVecVT = EVT::getVectorVT(*DAG.getContext(), NewVT, NumElts);
2645       SDValue VecOp = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NewVecVT, LdOp);
2646       return DAG.getNode(ISD::BITCAST, dl, WidenVT, VecOp);
2647     }
2648     if (NewVT == WidenVT)
2649       return LdOp;
2650
2651     assert(WidenWidth % NewVTWidth == 0);
2652     unsigned NumConcat = WidenWidth / NewVTWidth;
2653     SmallVector<SDValue, 16> ConcatOps(NumConcat);
2654     SDValue UndefVal = DAG.getUNDEF(NewVT);
2655     ConcatOps[0] = LdOp;
2656     for (unsigned i = 1; i != NumConcat; ++i)
2657       ConcatOps[i] = UndefVal;
2658     return DAG.getNode(ISD::CONCAT_VECTORS, dl, WidenVT, &ConcatOps[0],
2659                        NumConcat);
2660   }
2661
2662   // Load vector by using multiple loads from largest vector to scalar
2663   SmallVector<SDValue, 16> LdOps;
2664   LdOps.push_back(LdOp);
2665
2666   LdWidth -= NewVTWidth;
2667   unsigned Offset = 0;
2668
2669   while (LdWidth > 0) {
2670     unsigned Increment = NewVTWidth / 8;
2671     Offset += Increment;
2672     BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
2673                           DAG.getConstant(Increment, BasePtr.getValueType()));
2674
2675     SDValue L;
2676     if (LdWidth < NewVTWidth) {
2677       // Our current type we are using is too large, find a better size
2678       NewVT = FindMemType(DAG, TLI, LdWidth, WidenVT, LdAlign, WidthDiff);
2679       NewVTWidth = NewVT.getSizeInBits();
2680       L = DAG.getLoad(NewVT, dl, Chain, BasePtr,
2681                       LD->getPointerInfo().getWithOffset(Offset), isVolatile,
2682                       isNonTemporal, isInvariant, MinAlign(Align, Increment),
2683                       TBAAInfo);
2684       LdChain.push_back(L.getValue(1));
2685       if (L->getValueType(0).isVector()) {
2686         SmallVector<SDValue, 16> Loads;
2687         Loads.push_back(L);
2688         unsigned size = L->getValueSizeInBits(0);
2689         while (size < LdOp->getValueSizeInBits(0)) {
2690           Loads.push_back(DAG.getUNDEF(L->getValueType(0)));
2691           size += L->getValueSizeInBits(0);
2692         }
2693         L = DAG.getNode(ISD::CONCAT_VECTORS, dl, LdOp->getValueType(0),
2694                         &Loads[0], Loads.size());
2695       }
2696     } else {
2697       L = DAG.getLoad(NewVT, dl, Chain, BasePtr,
2698                       LD->getPointerInfo().getWithOffset(Offset), isVolatile,
2699                       isNonTemporal, isInvariant, MinAlign(Align, Increment),
2700                       TBAAInfo);
2701       LdChain.push_back(L.getValue(1));
2702     }
2703
2704     LdOps.push_back(L);
2705
2706
2707     LdWidth -= NewVTWidth;
2708   }
2709
2710   // Build the vector from the loads operations
2711   unsigned End = LdOps.size();
2712   if (!LdOps[0].getValueType().isVector())
2713     // All the loads are scalar loads.
2714     return BuildVectorFromScalar(DAG, WidenVT, LdOps, 0, End);
2715
2716   // If the load contains vectors, build the vector using concat vector.
2717   // All of the vectors used to loads are power of 2 and the scalars load
2718   // can be combined to make a power of 2 vector.
2719   SmallVector<SDValue, 16> ConcatOps(End);
2720   int i = End - 1;
2721   int Idx = End;
2722   EVT LdTy = LdOps[i].getValueType();
2723   // First combine the scalar loads to a vector
2724   if (!LdTy.isVector())  {
2725     for (--i; i >= 0; --i) {
2726       LdTy = LdOps[i].getValueType();
2727       if (LdTy.isVector())
2728         break;
2729     }
2730     ConcatOps[--Idx] = BuildVectorFromScalar(DAG, LdTy, LdOps, i+1, End);
2731   }
2732   ConcatOps[--Idx] = LdOps[i];
2733   for (--i; i >= 0; --i) {
2734     EVT NewLdTy = LdOps[i].getValueType();
2735     if (NewLdTy != LdTy) {
2736       // Create a larger vector
2737       ConcatOps[End-1] = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewLdTy,
2738                                      &ConcatOps[Idx], End - Idx);
2739       Idx = End - 1;
2740       LdTy = NewLdTy;
2741     }
2742     ConcatOps[--Idx] = LdOps[i];
2743   }
2744
2745   if (WidenWidth == LdTy.getSizeInBits()*(End - Idx))
2746     return DAG.getNode(ISD::CONCAT_VECTORS, dl, WidenVT,
2747                        &ConcatOps[Idx], End - Idx);
2748
2749   // We need to fill the rest with undefs to build the vector
2750   unsigned NumOps = WidenWidth / LdTy.getSizeInBits();
2751   SmallVector<SDValue, 16> WidenOps(NumOps);
2752   SDValue UndefVal = DAG.getUNDEF(LdTy);
2753   {
2754     unsigned i = 0;
2755     for (; i != End-Idx; ++i)
2756       WidenOps[i] = ConcatOps[Idx+i];
2757     for (; i != NumOps; ++i)
2758       WidenOps[i] = UndefVal;
2759   }
2760   return DAG.getNode(ISD::CONCAT_VECTORS, dl, WidenVT, &WidenOps[0],NumOps);
2761 }
2762
2763 SDValue
2764 DAGTypeLegalizer::GenWidenVectorExtLoads(SmallVectorImpl<SDValue> &LdChain,
2765                                          LoadSDNode *LD,
2766                                          ISD::LoadExtType ExtType) {
2767   // For extension loads, it may not be more efficient to chop up the vector
2768   // and then extended it.  Instead, we unroll the load and build a new vector.
2769   EVT WidenVT = TLI.getTypeToTransformTo(*DAG.getContext(),LD->getValueType(0));
2770   EVT LdVT    = LD->getMemoryVT();
2771   SDLoc dl(LD);
2772   assert(LdVT.isVector() && WidenVT.isVector());
2773
2774   // Load information
2775   SDValue   Chain = LD->getChain();
2776   SDValue   BasePtr = LD->getBasePtr();
2777   unsigned  Align    = LD->getAlignment();
2778   bool      isVolatile = LD->isVolatile();
2779   bool      isNonTemporal = LD->isNonTemporal();
2780   const MDNode *TBAAInfo = LD->getTBAAInfo();
2781
2782   EVT EltVT = WidenVT.getVectorElementType();
2783   EVT LdEltVT = LdVT.getVectorElementType();
2784   unsigned NumElts = LdVT.getVectorNumElements();
2785
2786   // Load each element and widen
2787   unsigned WidenNumElts = WidenVT.getVectorNumElements();
2788   SmallVector<SDValue, 16> Ops(WidenNumElts);
2789   unsigned Increment = LdEltVT.getSizeInBits() / 8;
2790   Ops[0] = DAG.getExtLoad(ExtType, dl, EltVT, Chain, BasePtr,
2791                           LD->getPointerInfo(),
2792                           LdEltVT, isVolatile, isNonTemporal, Align, TBAAInfo);
2793   LdChain.push_back(Ops[0].getValue(1));
2794   unsigned i = 0, Offset = Increment;
2795   for (i=1; i < NumElts; ++i, Offset += Increment) {
2796     SDValue NewBasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(),
2797                                      BasePtr,
2798                                      DAG.getConstant(Offset,
2799                                                      BasePtr.getValueType()));
2800     Ops[i] = DAG.getExtLoad(ExtType, dl, EltVT, Chain, NewBasePtr,
2801                             LD->getPointerInfo().getWithOffset(Offset), LdEltVT,
2802                             isVolatile, isNonTemporal, Align, TBAAInfo);
2803     LdChain.push_back(Ops[i].getValue(1));
2804   }
2805
2806   // Fill the rest with undefs
2807   SDValue UndefVal = DAG.getUNDEF(EltVT);
2808   for (; i != WidenNumElts; ++i)
2809     Ops[i] = UndefVal;
2810
2811   return DAG.getNode(ISD::BUILD_VECTOR, dl, WidenVT, &Ops[0], Ops.size());
2812 }
2813
2814
2815 void DAGTypeLegalizer::GenWidenVectorStores(SmallVectorImpl<SDValue> &StChain,
2816                                             StoreSDNode *ST) {
2817   // The strategy assumes that we can efficiently store powers of two widths.
2818   // The routines chops the vector into the largest vector stores with the same
2819   // element type or scalar stores.
2820   SDValue  Chain = ST->getChain();
2821   SDValue  BasePtr = ST->getBasePtr();
2822   unsigned Align = ST->getAlignment();
2823   bool     isVolatile = ST->isVolatile();
2824   bool     isNonTemporal = ST->isNonTemporal();
2825   const MDNode *TBAAInfo = ST->getTBAAInfo();
2826   SDValue  ValOp = GetWidenedVector(ST->getValue());
2827   SDLoc dl(ST);
2828
2829   EVT StVT = ST->getMemoryVT();
2830   unsigned StWidth = StVT.getSizeInBits();
2831   EVT ValVT = ValOp.getValueType();
2832   unsigned ValWidth = ValVT.getSizeInBits();
2833   EVT ValEltVT = ValVT.getVectorElementType();
2834   unsigned ValEltWidth = ValEltVT.getSizeInBits();
2835   assert(StVT.getVectorElementType() == ValEltVT);
2836
2837   int Idx = 0;          // current index to store
2838   unsigned Offset = 0;  // offset from base to store
2839   while (StWidth != 0) {
2840     // Find the largest vector type we can store with
2841     EVT NewVT = FindMemType(DAG, TLI, StWidth, ValVT);
2842     unsigned NewVTWidth = NewVT.getSizeInBits();
2843     unsigned Increment = NewVTWidth / 8;
2844     if (NewVT.isVector()) {
2845       unsigned NumVTElts = NewVT.getVectorNumElements();
2846       do {
2847         SDValue EOp = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NewVT, ValOp,
2848                                    DAG.getConstant(Idx, TLI.getVectorIdxTy()));
2849         StChain.push_back(DAG.getStore(Chain, dl, EOp, BasePtr,
2850                                     ST->getPointerInfo().getWithOffset(Offset),
2851                                        isVolatile, isNonTemporal,
2852                                        MinAlign(Align, Offset), TBAAInfo));
2853         StWidth -= NewVTWidth;
2854         Offset += Increment;
2855         Idx += NumVTElts;
2856         BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
2857                               DAG.getConstant(Increment, BasePtr.getValueType()));
2858       } while (StWidth != 0 && StWidth >= NewVTWidth);
2859     } else {
2860       // Cast the vector to the scalar type we can store
2861       unsigned NumElts = ValWidth / NewVTWidth;
2862       EVT NewVecVT = EVT::getVectorVT(*DAG.getContext(), NewVT, NumElts);
2863       SDValue VecOp = DAG.getNode(ISD::BITCAST, dl, NewVecVT, ValOp);
2864       // Readjust index position based on new vector type
2865       Idx = Idx * ValEltWidth / NewVTWidth;
2866       do {
2867         SDValue EOp = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, NewVT, VecOp,
2868                       DAG.getConstant(Idx++, TLI.getVectorIdxTy()));
2869         StChain.push_back(DAG.getStore(Chain, dl, EOp, BasePtr,
2870                                     ST->getPointerInfo().getWithOffset(Offset),
2871                                        isVolatile, isNonTemporal,
2872                                        MinAlign(Align, Offset), TBAAInfo));
2873         StWidth -= NewVTWidth;
2874         Offset += Increment;
2875         BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
2876                             DAG.getConstant(Increment, BasePtr.getValueType()));
2877       } while (StWidth != 0 && StWidth >= NewVTWidth);
2878       // Restore index back to be relative to the original widen element type
2879       Idx = Idx * NewVTWidth / ValEltWidth;
2880     }
2881   }
2882 }
2883
2884 void
2885 DAGTypeLegalizer::GenWidenVectorTruncStores(SmallVectorImpl<SDValue> &StChain,
2886                                             StoreSDNode *ST) {
2887   // For extension loads, it may not be more efficient to truncate the vector
2888   // and then store it.  Instead, we extract each element and then store it.
2889   SDValue  Chain = ST->getChain();
2890   SDValue  BasePtr = ST->getBasePtr();
2891   unsigned Align = ST->getAlignment();
2892   bool     isVolatile = ST->isVolatile();
2893   bool     isNonTemporal = ST->isNonTemporal();
2894   const MDNode *TBAAInfo = ST->getTBAAInfo();
2895   SDValue  ValOp = GetWidenedVector(ST->getValue());
2896   SDLoc dl(ST);
2897
2898   EVT StVT = ST->getMemoryVT();
2899   EVT ValVT = ValOp.getValueType();
2900
2901   // It must be true that we the widen vector type is bigger than where
2902   // we need to store.
2903   assert(StVT.isVector() && ValOp.getValueType().isVector());
2904   assert(StVT.bitsLT(ValOp.getValueType()));
2905
2906   // For truncating stores, we can not play the tricks of chopping legal
2907   // vector types and bit cast it to the right type.  Instead, we unroll
2908   // the store.
2909   EVT StEltVT  = StVT.getVectorElementType();
2910   EVT ValEltVT = ValVT.getVectorElementType();
2911   unsigned Increment = ValEltVT.getSizeInBits() / 8;
2912   unsigned NumElts = StVT.getVectorNumElements();
2913   SDValue EOp = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ValEltVT, ValOp,
2914                             DAG.getConstant(0, TLI.getVectorIdxTy()));
2915   StChain.push_back(DAG.getTruncStore(Chain, dl, EOp, BasePtr,
2916                                       ST->getPointerInfo(), StEltVT,
2917                                       isVolatile, isNonTemporal, Align,
2918                                       TBAAInfo));
2919   unsigned Offset = Increment;
2920   for (unsigned i=1; i < NumElts; ++i, Offset += Increment) {
2921     SDValue NewBasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(),
2922                                      BasePtr, DAG.getConstant(Offset,
2923                                                        BasePtr.getValueType()));
2924     SDValue EOp = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ValEltVT, ValOp,
2925                             DAG.getConstant(0, TLI.getVectorIdxTy()));
2926     StChain.push_back(DAG.getTruncStore(Chain, dl, EOp, NewBasePtr,
2927                                       ST->getPointerInfo().getWithOffset(Offset),
2928                                         StEltVT, isVolatile, isNonTemporal,
2929                                         MinAlign(Align, Offset), TBAAInfo));
2930   }
2931 }
2932
2933 /// Modifies a vector input (widen or narrows) to a vector of NVT.  The
2934 /// input vector must have the same element type as NVT.
2935 SDValue DAGTypeLegalizer::ModifyToType(SDValue InOp, EVT NVT) {
2936   // Note that InOp might have been widened so it might already have
2937   // the right width or it might need be narrowed.
2938   EVT InVT = InOp.getValueType();
2939   assert(InVT.getVectorElementType() == NVT.getVectorElementType() &&
2940          "input and widen element type must match");
2941   SDLoc dl(InOp);
2942
2943   // Check if InOp already has the right width.
2944   if (InVT == NVT)
2945     return InOp;
2946
2947   unsigned InNumElts = InVT.getVectorNumElements();
2948   unsigned WidenNumElts = NVT.getVectorNumElements();
2949   if (WidenNumElts > InNumElts && WidenNumElts % InNumElts == 0) {
2950     unsigned NumConcat = WidenNumElts / InNumElts;
2951     SmallVector<SDValue, 16> Ops(NumConcat);
2952     SDValue UndefVal = DAG.getUNDEF(InVT);
2953     Ops[0] = InOp;
2954     for (unsigned i = 1; i != NumConcat; ++i)
2955       Ops[i] = UndefVal;
2956
2957     return DAG.getNode(ISD::CONCAT_VECTORS, dl, NVT, &Ops[0], NumConcat);
2958   }
2959
2960   if (WidenNumElts < InNumElts && InNumElts % WidenNumElts)
2961     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT, InOp,
2962                        DAG.getConstant(0, TLI.getVectorIdxTy()));
2963
2964   // Fall back to extract and build.
2965   SmallVector<SDValue, 16> Ops(WidenNumElts);
2966   EVT EltVT = NVT.getVectorElementType();
2967   unsigned MinNumElts = std::min(WidenNumElts, InNumElts);
2968   unsigned Idx;
2969   for (Idx = 0; Idx < MinNumElts; ++Idx)
2970     Ops[Idx] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, InOp,
2971                            DAG.getConstant(Idx, TLI.getVectorIdxTy()));
2972
2973   SDValue UndefVal = DAG.getUNDEF(EltVT);
2974   for ( ; Idx < WidenNumElts; ++Idx)
2975     Ops[Idx] = UndefVal;
2976   return DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, &Ops[0], WidenNumElts);
2977 }