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