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