OSDN Git Service

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