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