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