Fix broken type legalization of min/max
[oota-llvm.git] / lib / CodeGen / SelectionDAG / LegalizeIntegerTypes.cpp
1 //===----- LegalizeIntegerTypes.cpp - Legalization of integer 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 implements integer type expansion and promotion for LegalizeTypes.
11 // Promotion is the act of changing a computation in an illegal type into a
12 // computation in a larger type.  For example, implementing i8 arithmetic in an
13 // i32 register (often needed on powerpc).
14 // Expansion is the act of changing a computation in an illegal type into a
15 // computation in two identical registers of a smaller type.  For example,
16 // implementing i64 arithmetic in two i32 registers (often needed on 32-bit
17 // targets).
18 //
19 //===----------------------------------------------------------------------===//
20
21 #include "LegalizeTypes.h"
22 #include "llvm/IR/DerivedTypes.h"
23 #include "llvm/Support/ErrorHandling.h"
24 #include "llvm/Support/raw_ostream.h"
25 using namespace llvm;
26
27 #define DEBUG_TYPE "legalize-types"
28
29 //===----------------------------------------------------------------------===//
30 //  Integer Result Promotion
31 //===----------------------------------------------------------------------===//
32
33 /// PromoteIntegerResult - This method is called when a result of a node is
34 /// found to be in need of promotion to a larger type.  At this point, the node
35 /// may also have invalid operands or may have other results that need
36 /// expansion, we just know that (at least) one result needs promotion.
37 void DAGTypeLegalizer::PromoteIntegerResult(SDNode *N, unsigned ResNo) {
38   DEBUG(dbgs() << "Promote integer result: "; N->dump(&DAG); dbgs() << "\n");
39   SDValue Res = SDValue();
40
41   // See if the target wants to custom expand this node.
42   if (CustomLowerNode(N, N->getValueType(ResNo), true))
43     return;
44
45   switch (N->getOpcode()) {
46   default:
47 #ifndef NDEBUG
48     dbgs() << "PromoteIntegerResult #" << ResNo << ": ";
49     N->dump(&DAG); dbgs() << "\n";
50 #endif
51     llvm_unreachable("Do not know how to promote this operator!");
52   case ISD::MERGE_VALUES:Res = PromoteIntRes_MERGE_VALUES(N, ResNo); break;
53   case ISD::AssertSext:  Res = PromoteIntRes_AssertSext(N); break;
54   case ISD::AssertZext:  Res = PromoteIntRes_AssertZext(N); break;
55   case ISD::BITCAST:     Res = PromoteIntRes_BITCAST(N); break;
56   case ISD::BITREVERSE:  Res = PromoteIntRes_BITREVERSE(N); break;
57   case ISD::BSWAP:       Res = PromoteIntRes_BSWAP(N); break;
58   case ISD::BUILD_PAIR:  Res = PromoteIntRes_BUILD_PAIR(N); break;
59   case ISD::Constant:    Res = PromoteIntRes_Constant(N); break;
60   case ISD::CONVERT_RNDSAT:
61                          Res = PromoteIntRes_CONVERT_RNDSAT(N); break;
62   case ISD::CTLZ_ZERO_UNDEF:
63   case ISD::CTLZ:        Res = PromoteIntRes_CTLZ(N); break;
64   case ISD::CTPOP:       Res = PromoteIntRes_CTPOP(N); break;
65   case ISD::CTTZ_ZERO_UNDEF:
66   case ISD::CTTZ:        Res = PromoteIntRes_CTTZ(N); break;
67   case ISD::EXTRACT_VECTOR_ELT:
68                          Res = PromoteIntRes_EXTRACT_VECTOR_ELT(N); break;
69   case ISD::LOAD:        Res = PromoteIntRes_LOAD(cast<LoadSDNode>(N)); break;
70   case ISD::MLOAD:       Res = PromoteIntRes_MLOAD(cast<MaskedLoadSDNode>(N));
71     break;
72   case ISD::MGATHER:     Res = PromoteIntRes_MGATHER(cast<MaskedGatherSDNode>(N));
73     break;
74   case ISD::SELECT:      Res = PromoteIntRes_SELECT(N); break;
75   case ISD::VSELECT:     Res = PromoteIntRes_VSELECT(N); break;
76   case ISD::SELECT_CC:   Res = PromoteIntRes_SELECT_CC(N); break;
77   case ISD::SETCC:       Res = PromoteIntRes_SETCC(N); break;
78   case ISD::SMIN:
79   case ISD::SMAX:        Res = PromoteIntRes_SExtOrZExtIntBinOp(N, true); break;
80   case ISD::UMIN:
81   case ISD::UMAX:        Res = PromoteIntRes_SExtOrZExtIntBinOp(N, false); break;
82
83   case ISD::SHL:         Res = PromoteIntRes_SHL(N); break;
84   case ISD::SIGN_EXTEND_INREG:
85                          Res = PromoteIntRes_SIGN_EXTEND_INREG(N); break;
86   case ISD::SRA:         Res = PromoteIntRes_SRA(N); break;
87   case ISD::SRL:         Res = PromoteIntRes_SRL(N); break;
88   case ISD::TRUNCATE:    Res = PromoteIntRes_TRUNCATE(N); break;
89   case ISD::UNDEF:       Res = PromoteIntRes_UNDEF(N); break;
90   case ISD::VAARG:       Res = PromoteIntRes_VAARG(N); break;
91
92   case ISD::EXTRACT_SUBVECTOR:
93                          Res = PromoteIntRes_EXTRACT_SUBVECTOR(N); break;
94   case ISD::VECTOR_SHUFFLE:
95                          Res = PromoteIntRes_VECTOR_SHUFFLE(N); break;
96   case ISD::INSERT_VECTOR_ELT:
97                          Res = PromoteIntRes_INSERT_VECTOR_ELT(N); break;
98   case ISD::BUILD_VECTOR:
99                          Res = PromoteIntRes_BUILD_VECTOR(N); break;
100   case ISD::SCALAR_TO_VECTOR:
101                          Res = PromoteIntRes_SCALAR_TO_VECTOR(N); break;
102   case ISD::CONCAT_VECTORS:
103                          Res = PromoteIntRes_CONCAT_VECTORS(N); break;
104
105   case ISD::SIGN_EXTEND:
106   case ISD::ZERO_EXTEND:
107   case ISD::ANY_EXTEND:  Res = PromoteIntRes_INT_EXTEND(N); break;
108
109   case ISD::FP_TO_SINT:
110   case ISD::FP_TO_UINT:  Res = PromoteIntRes_FP_TO_XINT(N); break;
111
112   case ISD::FP_TO_FP16:  Res = PromoteIntRes_FP_TO_FP16(N); break;
113
114   case ISD::AND:
115   case ISD::OR:
116   case ISD::XOR:
117   case ISD::ADD:
118   case ISD::SUB:
119   case ISD::MUL:         Res = PromoteIntRes_SimpleIntBinOp(N); break;
120
121   case ISD::SDIV:
122   case ISD::SREM:        Res = PromoteIntRes_SDIV(N); break;
123
124   case ISD::UDIV:
125   case ISD::UREM:        Res = PromoteIntRes_UDIV(N); break;
126
127   case ISD::SADDO:
128   case ISD::SSUBO:       Res = PromoteIntRes_SADDSUBO(N, ResNo); break;
129   case ISD::UADDO:
130   case ISD::USUBO:       Res = PromoteIntRes_UADDSUBO(N, ResNo); break;
131   case ISD::SMULO:
132   case ISD::UMULO:       Res = PromoteIntRes_XMULO(N, ResNo); break;
133
134   case ISD::ATOMIC_LOAD:
135     Res = PromoteIntRes_Atomic0(cast<AtomicSDNode>(N)); break;
136
137   case ISD::ATOMIC_LOAD_ADD:
138   case ISD::ATOMIC_LOAD_SUB:
139   case ISD::ATOMIC_LOAD_AND:
140   case ISD::ATOMIC_LOAD_OR:
141   case ISD::ATOMIC_LOAD_XOR:
142   case ISD::ATOMIC_LOAD_NAND:
143   case ISD::ATOMIC_LOAD_MIN:
144   case ISD::ATOMIC_LOAD_MAX:
145   case ISD::ATOMIC_LOAD_UMIN:
146   case ISD::ATOMIC_LOAD_UMAX:
147   case ISD::ATOMIC_SWAP:
148     Res = PromoteIntRes_Atomic1(cast<AtomicSDNode>(N)); break;
149
150   case ISD::ATOMIC_CMP_SWAP:
151   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
152     Res = PromoteIntRes_AtomicCmpSwap(cast<AtomicSDNode>(N), ResNo);
153     break;
154   }
155
156   // If the result is null then the sub-method took care of registering it.
157   if (Res.getNode())
158     SetPromotedInteger(SDValue(N, ResNo), Res);
159 }
160
161 SDValue DAGTypeLegalizer::PromoteIntRes_MERGE_VALUES(SDNode *N,
162                                                      unsigned ResNo) {
163   SDValue Op = DisintegrateMERGE_VALUES(N, ResNo);
164   return GetPromotedInteger(Op);
165 }
166
167 SDValue DAGTypeLegalizer::PromoteIntRes_AssertSext(SDNode *N) {
168   // Sign-extend the new bits, and continue the assertion.
169   SDValue Op = SExtPromotedInteger(N->getOperand(0));
170   return DAG.getNode(ISD::AssertSext, SDLoc(N),
171                      Op.getValueType(), Op, N->getOperand(1));
172 }
173
174 SDValue DAGTypeLegalizer::PromoteIntRes_AssertZext(SDNode *N) {
175   // Zero the new bits, and continue the assertion.
176   SDValue Op = ZExtPromotedInteger(N->getOperand(0));
177   return DAG.getNode(ISD::AssertZext, SDLoc(N),
178                      Op.getValueType(), Op, N->getOperand(1));
179 }
180
181 SDValue DAGTypeLegalizer::PromoteIntRes_Atomic0(AtomicSDNode *N) {
182   EVT ResVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
183   SDValue Res = DAG.getAtomic(N->getOpcode(), SDLoc(N),
184                               N->getMemoryVT(), ResVT,
185                               N->getChain(), N->getBasePtr(),
186                               N->getMemOperand(), N->getOrdering(),
187                               N->getSynchScope());
188   // Legalize the chain result - switch anything that used the old chain to
189   // use the new one.
190   ReplaceValueWith(SDValue(N, 1), Res.getValue(1));
191   return Res;
192 }
193
194 SDValue DAGTypeLegalizer::PromoteIntRes_Atomic1(AtomicSDNode *N) {
195   SDValue Op2 = GetPromotedInteger(N->getOperand(2));
196   SDValue Res = DAG.getAtomic(N->getOpcode(), SDLoc(N),
197                               N->getMemoryVT(),
198                               N->getChain(), N->getBasePtr(),
199                               Op2, N->getMemOperand(), N->getOrdering(),
200                               N->getSynchScope());
201   // Legalize the chain result - switch anything that used the old chain to
202   // use the new one.
203   ReplaceValueWith(SDValue(N, 1), Res.getValue(1));
204   return Res;
205 }
206
207 SDValue DAGTypeLegalizer::PromoteIntRes_AtomicCmpSwap(AtomicSDNode *N,
208                                                       unsigned ResNo) {
209   if (ResNo == 1) {
210     assert(N->getOpcode() == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
211     EVT SVT = getSetCCResultType(N->getOperand(2).getValueType());
212     EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(1));
213
214     // Only use the result of getSetCCResultType if it is legal,
215     // otherwise just use the promoted result type (NVT).
216     if (!TLI.isTypeLegal(SVT))
217       SVT = NVT;
218
219     SDVTList VTs = DAG.getVTList(N->getValueType(0), SVT, MVT::Other);
220     SDValue Res = DAG.getAtomicCmpSwap(
221         ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, SDLoc(N), N->getMemoryVT(), VTs,
222         N->getChain(), N->getBasePtr(), N->getOperand(2), N->getOperand(3),
223         N->getMemOperand(), N->getSuccessOrdering(), N->getFailureOrdering(),
224         N->getSynchScope());
225     ReplaceValueWith(SDValue(N, 0), Res.getValue(0));
226     ReplaceValueWith(SDValue(N, 2), Res.getValue(2));
227     return Res.getValue(1);
228   }
229
230   SDValue Op2 = GetPromotedInteger(N->getOperand(2));
231   SDValue Op3 = GetPromotedInteger(N->getOperand(3));
232   SDVTList VTs =
233       DAG.getVTList(Op2.getValueType(), N->getValueType(1), MVT::Other);
234   SDValue Res = DAG.getAtomicCmpSwap(
235       N->getOpcode(), SDLoc(N), N->getMemoryVT(), VTs, N->getChain(),
236       N->getBasePtr(), Op2, Op3, N->getMemOperand(), N->getSuccessOrdering(),
237       N->getFailureOrdering(), N->getSynchScope());
238   // Update the use to N with the newly created Res.
239   for (unsigned i = 1, NumResults = N->getNumValues(); i < NumResults; ++i)
240     ReplaceValueWith(SDValue(N, i), Res.getValue(i));
241   return Res;
242 }
243
244 SDValue DAGTypeLegalizer::PromoteIntRes_BITCAST(SDNode *N) {
245   SDValue InOp = N->getOperand(0);
246   EVT InVT = InOp.getValueType();
247   EVT NInVT = TLI.getTypeToTransformTo(*DAG.getContext(), InVT);
248   EVT OutVT = N->getValueType(0);
249   EVT NOutVT = TLI.getTypeToTransformTo(*DAG.getContext(), OutVT);
250   SDLoc dl(N);
251
252   switch (getTypeAction(InVT)) {
253   case TargetLowering::TypeLegal:
254     break;
255   case TargetLowering::TypePromoteInteger:
256     if (NOutVT.bitsEq(NInVT) && !NOutVT.isVector() && !NInVT.isVector())
257       // The input promotes to the same size.  Convert the promoted value.
258       return DAG.getNode(ISD::BITCAST, dl, NOutVT, GetPromotedInteger(InOp));
259     break;
260   case TargetLowering::TypeSoftenFloat:
261     // Promote the integer operand by hand.
262     return DAG.getNode(ISD::ANY_EXTEND, dl, NOutVT, GetSoftenedFloat(InOp));
263   case TargetLowering::TypePromoteFloat: {
264     // Convert the promoted float by hand.
265     if (NOutVT.bitsEq(NInVT)) {
266       SDValue PromotedOp = GetPromotedFloat(InOp);
267       SDValue Trunc = DAG.getNode(ISD::FP_TO_FP16, dl, NOutVT, PromotedOp);
268       return DAG.getNode(ISD::AssertZext, dl, NOutVT, Trunc,
269                          DAG.getValueType(OutVT));
270     }
271     break;
272   }
273   case TargetLowering::TypeExpandInteger:
274   case TargetLowering::TypeExpandFloat:
275     break;
276   case TargetLowering::TypeScalarizeVector:
277     // Convert the element to an integer and promote it by hand.
278     if (!NOutVT.isVector())
279       return DAG.getNode(ISD::ANY_EXTEND, dl, NOutVT,
280                          BitConvertToInteger(GetScalarizedVector(InOp)));
281     break;
282   case TargetLowering::TypeSplitVector: {
283     // For example, i32 = BITCAST v2i16 on alpha.  Convert the split
284     // pieces of the input into integers and reassemble in the final type.
285     SDValue Lo, Hi;
286     GetSplitVector(N->getOperand(0), Lo, Hi);
287     Lo = BitConvertToInteger(Lo);
288     Hi = BitConvertToInteger(Hi);
289
290     if (DAG.getDataLayout().isBigEndian())
291       std::swap(Lo, Hi);
292
293     InOp = DAG.getNode(ISD::ANY_EXTEND, dl,
294                        EVT::getIntegerVT(*DAG.getContext(),
295                                          NOutVT.getSizeInBits()),
296                        JoinIntegers(Lo, Hi));
297     return DAG.getNode(ISD::BITCAST, dl, NOutVT, InOp);
298   }
299   case TargetLowering::TypeWidenVector:
300     // The input is widened to the same size. Convert to the widened value.
301     // Make sure that the outgoing value is not a vector, because this would
302     // make us bitcast between two vectors which are legalized in different ways.
303     if (NOutVT.bitsEq(NInVT) && !NOutVT.isVector())
304       return DAG.getNode(ISD::BITCAST, dl, NOutVT, GetWidenedVector(InOp));
305   }
306
307   return DAG.getNode(ISD::ANY_EXTEND, dl, NOutVT,
308                      CreateStackStoreLoad(InOp, OutVT));
309 }
310
311 SDValue DAGTypeLegalizer::PromoteIntRes_BSWAP(SDNode *N) {
312   SDValue Op = GetPromotedInteger(N->getOperand(0));
313   EVT OVT = N->getValueType(0);
314   EVT NVT = Op.getValueType();
315   SDLoc dl(N);
316
317   unsigned DiffBits = NVT.getScalarSizeInBits() - OVT.getScalarSizeInBits();
318   return DAG.getNode(
319       ISD::SRL, dl, NVT, DAG.getNode(ISD::BSWAP, dl, NVT, Op),
320       DAG.getConstant(DiffBits, dl,
321                       TLI.getShiftAmountTy(NVT, DAG.getDataLayout())));
322 }
323
324 SDValue DAGTypeLegalizer::PromoteIntRes_BITREVERSE(SDNode *N) {
325   SDValue Op = GetPromotedInteger(N->getOperand(0));
326   EVT OVT = N->getValueType(0);
327   EVT NVT = Op.getValueType();
328   SDLoc dl(N);
329
330   unsigned DiffBits = NVT.getScalarSizeInBits() - OVT.getScalarSizeInBits();
331   return DAG.getNode(
332       ISD::SRL, dl, NVT, DAG.getNode(ISD::BITREVERSE, dl, NVT, Op),
333       DAG.getConstant(DiffBits, dl,
334                       TLI.getShiftAmountTy(NVT, DAG.getDataLayout())));
335 }
336
337 SDValue DAGTypeLegalizer::PromoteIntRes_BUILD_PAIR(SDNode *N) {
338   // The pair element type may be legal, or may not promote to the same type as
339   // the result, for example i14 = BUILD_PAIR (i7, i7).  Handle all cases.
340   return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N),
341                      TLI.getTypeToTransformTo(*DAG.getContext(),
342                      N->getValueType(0)), JoinIntegers(N->getOperand(0),
343                      N->getOperand(1)));
344 }
345
346 SDValue DAGTypeLegalizer::PromoteIntRes_Constant(SDNode *N) {
347   EVT VT = N->getValueType(0);
348   // FIXME there is no actual debug info here
349   SDLoc dl(N);
350   // Zero extend things like i1, sign extend everything else.  It shouldn't
351   // matter in theory which one we pick, but this tends to give better code?
352   unsigned Opc = VT.isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
353   SDValue Result = DAG.getNode(Opc, dl,
354                                TLI.getTypeToTransformTo(*DAG.getContext(), VT),
355                                SDValue(N, 0));
356   assert(isa<ConstantSDNode>(Result) && "Didn't constant fold ext?");
357   return Result;
358 }
359
360 SDValue DAGTypeLegalizer::PromoteIntRes_CONVERT_RNDSAT(SDNode *N) {
361   ISD::CvtCode CvtCode = cast<CvtRndSatSDNode>(N)->getCvtCode();
362   assert ((CvtCode == ISD::CVT_SS || CvtCode == ISD::CVT_SU ||
363            CvtCode == ISD::CVT_US || CvtCode == ISD::CVT_UU ||
364            CvtCode == ISD::CVT_SF || CvtCode == ISD::CVT_UF) &&
365           "can only promote integers");
366   EVT OutVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
367   return DAG.getConvertRndSat(OutVT, SDLoc(N), N->getOperand(0),
368                               N->getOperand(1), N->getOperand(2),
369                               N->getOperand(3), N->getOperand(4), CvtCode);
370 }
371
372 SDValue DAGTypeLegalizer::PromoteIntRes_CTLZ(SDNode *N) {
373   // Zero extend to the promoted type and do the count there.
374   SDValue Op = ZExtPromotedInteger(N->getOperand(0));
375   SDLoc dl(N);
376   EVT OVT = N->getValueType(0);
377   EVT NVT = Op.getValueType();
378   Op = DAG.getNode(N->getOpcode(), dl, NVT, Op);
379   // Subtract off the extra leading bits in the bigger type.
380   return DAG.getNode(
381       ISD::SUB, dl, NVT, Op,
382       DAG.getConstant(NVT.getScalarSizeInBits() - OVT.getScalarSizeInBits(), dl,
383                       NVT));
384 }
385
386 SDValue DAGTypeLegalizer::PromoteIntRes_CTPOP(SDNode *N) {
387   // Zero extend to the promoted type and do the count there.
388   SDValue Op = ZExtPromotedInteger(N->getOperand(0));
389   return DAG.getNode(ISD::CTPOP, SDLoc(N), Op.getValueType(), Op);
390 }
391
392 SDValue DAGTypeLegalizer::PromoteIntRes_CTTZ(SDNode *N) {
393   SDValue Op = GetPromotedInteger(N->getOperand(0));
394   EVT OVT = N->getValueType(0);
395   EVT NVT = Op.getValueType();
396   SDLoc dl(N);
397   if (N->getOpcode() == ISD::CTTZ) {
398     // The count is the same in the promoted type except if the original
399     // value was zero.  This can be handled by setting the bit just off
400     // the top of the original type.
401     auto TopBit = APInt::getOneBitSet(NVT.getScalarSizeInBits(),
402                                       OVT.getScalarSizeInBits());
403     Op = DAG.getNode(ISD::OR, dl, NVT, Op, DAG.getConstant(TopBit, dl, NVT));
404   }
405   return DAG.getNode(N->getOpcode(), dl, NVT, Op);
406 }
407
408 SDValue DAGTypeLegalizer::PromoteIntRes_EXTRACT_VECTOR_ELT(SDNode *N) {
409   SDLoc dl(N);
410   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
411   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, NVT, N->getOperand(0),
412                      N->getOperand(1));
413 }
414
415 SDValue DAGTypeLegalizer::PromoteIntRes_FP_TO_XINT(SDNode *N) {
416   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
417   unsigned NewOpc = N->getOpcode();
418   SDLoc dl(N);
419
420   // If we're promoting a UINT to a larger size and the larger FP_TO_UINT is
421   // not Legal, check to see if we can use FP_TO_SINT instead.  (If both UINT
422   // and SINT conversions are Custom, there is no way to tell which is
423   // preferable. We choose SINT because that's the right thing on PPC.)
424   if (N->getOpcode() == ISD::FP_TO_UINT &&
425       !TLI.isOperationLegal(ISD::FP_TO_UINT, NVT) &&
426       TLI.isOperationLegalOrCustom(ISD::FP_TO_SINT, NVT))
427     NewOpc = ISD::FP_TO_SINT;
428
429   SDValue Res = DAG.getNode(NewOpc, dl, NVT, N->getOperand(0));
430
431   // Assert that the converted value fits in the original type.  If it doesn't
432   // (eg: because the value being converted is too big), then the result of the
433   // original operation was undefined anyway, so the assert is still correct.
434   return DAG.getNode(N->getOpcode() == ISD::FP_TO_UINT ?
435                      ISD::AssertZext : ISD::AssertSext, dl, NVT, Res,
436                      DAG.getValueType(N->getValueType(0).getScalarType()));
437 }
438
439 SDValue DAGTypeLegalizer::PromoteIntRes_FP_TO_FP16(SDNode *N) {
440   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
441   SDLoc dl(N);
442
443   SDValue Res = DAG.getNode(N->getOpcode(), dl, NVT, N->getOperand(0));
444
445   return DAG.getNode(ISD::AssertZext, dl,
446                      NVT, Res, DAG.getValueType(N->getValueType(0)));
447 }
448
449 SDValue DAGTypeLegalizer::PromoteIntRes_INT_EXTEND(SDNode *N) {
450   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
451   SDLoc dl(N);
452
453   if (getTypeAction(N->getOperand(0).getValueType())
454       == TargetLowering::TypePromoteInteger) {
455     SDValue Res = GetPromotedInteger(N->getOperand(0));
456     assert(Res.getValueType().bitsLE(NVT) && "Extension doesn't make sense!");
457
458     // If the result and operand types are the same after promotion, simplify
459     // to an in-register extension.
460     if (NVT == Res.getValueType()) {
461       // The high bits are not guaranteed to be anything.  Insert an extend.
462       if (N->getOpcode() == ISD::SIGN_EXTEND)
463         return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NVT, Res,
464                            DAG.getValueType(N->getOperand(0).getValueType()));
465       if (N->getOpcode() == ISD::ZERO_EXTEND)
466         return DAG.getZeroExtendInReg(Res, dl,
467                       N->getOperand(0).getValueType().getScalarType());
468       assert(N->getOpcode() == ISD::ANY_EXTEND && "Unknown integer extension!");
469       return Res;
470     }
471   }
472
473   // Otherwise, just extend the original operand all the way to the larger type.
474   return DAG.getNode(N->getOpcode(), dl, NVT, N->getOperand(0));
475 }
476
477 SDValue DAGTypeLegalizer::PromoteIntRes_LOAD(LoadSDNode *N) {
478   assert(ISD::isUNINDEXEDLoad(N) && "Indexed load during type legalization!");
479   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
480   ISD::LoadExtType ExtType =
481     ISD::isNON_EXTLoad(N) ? ISD::EXTLOAD : N->getExtensionType();
482   SDLoc dl(N);
483   SDValue Res = DAG.getExtLoad(ExtType, dl, NVT, N->getChain(), N->getBasePtr(),
484                                N->getMemoryVT(), N->getMemOperand());
485
486   // Legalize the chain result - switch anything that used the old chain to
487   // use the new one.
488   ReplaceValueWith(SDValue(N, 1), Res.getValue(1));
489   return Res;
490 }
491
492 SDValue DAGTypeLegalizer::PromoteIntRes_MLOAD(MaskedLoadSDNode *N) {
493   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
494   SDValue ExtSrc0 = GetPromotedInteger(N->getSrc0());
495
496   SDLoc dl(N);
497   SDValue Res = DAG.getMaskedLoad(NVT, dl, N->getChain(), N->getBasePtr(),
498                                   N->getMask(), ExtSrc0, N->getMemoryVT(),
499                                   N->getMemOperand(), ISD::SEXTLOAD);
500   // Legalize the chain result - switch anything that used the old chain to
501   // use the new one.
502   ReplaceValueWith(SDValue(N, 1), Res.getValue(1));
503   return Res;
504 }
505
506 SDValue DAGTypeLegalizer::PromoteIntRes_MGATHER(MaskedGatherSDNode *N) {
507   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
508   SDValue ExtSrc0 = GetPromotedInteger(N->getValue());
509   assert(NVT == ExtSrc0.getValueType() &&
510       "Gather result type and the passThru agrument type should be the same");
511
512   SDLoc dl(N);
513   SDValue Ops[] = {N->getChain(), ExtSrc0, N->getMask(), N->getBasePtr(),
514                    N->getIndex()};
515   SDValue Res = DAG.getMaskedGather(DAG.getVTList(NVT, MVT::Other),
516                                     N->getMemoryVT(), dl, Ops,
517                                     N->getMemOperand()); 
518   // Legalize the chain result - switch anything that used the old chain to
519   // use the new one.
520   ReplaceValueWith(SDValue(N, 1), Res.getValue(1));
521   return Res;
522 }
523
524 /// Promote the overflow flag of an overflowing arithmetic node.
525 SDValue DAGTypeLegalizer::PromoteIntRes_Overflow(SDNode *N) {
526   // Simply change the return type of the boolean result.
527   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(1));
528   EVT ValueVTs[] = { N->getValueType(0), NVT };
529   SDValue Ops[] = { N->getOperand(0), N->getOperand(1) };
530   SDValue Res = DAG.getNode(N->getOpcode(), SDLoc(N),
531                             DAG.getVTList(ValueVTs), Ops);
532
533   // Modified the sum result - switch anything that used the old sum to use
534   // the new one.
535   ReplaceValueWith(SDValue(N, 0), Res);
536
537   return SDValue(Res.getNode(), 1);
538 }
539
540 SDValue DAGTypeLegalizer::PromoteIntRes_SADDSUBO(SDNode *N, unsigned ResNo) {
541   if (ResNo == 1)
542     return PromoteIntRes_Overflow(N);
543
544   // The operation overflowed iff the result in the larger type is not the
545   // sign extension of its truncation to the original type.
546   SDValue LHS = SExtPromotedInteger(N->getOperand(0));
547   SDValue RHS = SExtPromotedInteger(N->getOperand(1));
548   EVT OVT = N->getOperand(0).getValueType();
549   EVT NVT = LHS.getValueType();
550   SDLoc dl(N);
551
552   // Do the arithmetic in the larger type.
553   unsigned Opcode = N->getOpcode() == ISD::SADDO ? ISD::ADD : ISD::SUB;
554   SDValue Res = DAG.getNode(Opcode, dl, NVT, LHS, RHS);
555
556   // Calculate the overflow flag: sign extend the arithmetic result from
557   // the original type.
558   SDValue Ofl = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NVT, Res,
559                             DAG.getValueType(OVT));
560   // Overflowed if and only if this is not equal to Res.
561   Ofl = DAG.getSetCC(dl, N->getValueType(1), Ofl, Res, ISD::SETNE);
562
563   // Use the calculated overflow everywhere.
564   ReplaceValueWith(SDValue(N, 1), Ofl);
565
566   return Res;
567 }
568
569 SDValue DAGTypeLegalizer::PromoteIntRes_SDIV(SDNode *N) {
570   // Sign extend the input.
571   SDValue LHS = SExtPromotedInteger(N->getOperand(0));
572   SDValue RHS = SExtPromotedInteger(N->getOperand(1));
573   return DAG.getNode(N->getOpcode(), SDLoc(N),
574                      LHS.getValueType(), LHS, RHS);
575 }
576
577 SDValue DAGTypeLegalizer::PromoteIntRes_SELECT(SDNode *N) {
578   SDValue LHS = GetPromotedInteger(N->getOperand(1));
579   SDValue RHS = GetPromotedInteger(N->getOperand(2));
580   return DAG.getSelect(SDLoc(N),
581                        LHS.getValueType(), N->getOperand(0), LHS, RHS);
582 }
583
584 SDValue DAGTypeLegalizer::PromoteIntRes_VSELECT(SDNode *N) {
585   SDValue Mask = N->getOperand(0);
586   EVT OpTy = N->getOperand(1).getValueType();
587
588   // Promote all the way up to the canonical SetCC type.
589   Mask = PromoteTargetBoolean(Mask, OpTy);
590   SDValue LHS = GetPromotedInteger(N->getOperand(1));
591   SDValue RHS = GetPromotedInteger(N->getOperand(2));
592   return DAG.getNode(ISD::VSELECT, SDLoc(N),
593                      LHS.getValueType(), Mask, LHS, RHS);
594 }
595
596 SDValue DAGTypeLegalizer::PromoteIntRes_SELECT_CC(SDNode *N) {
597   SDValue LHS = GetPromotedInteger(N->getOperand(2));
598   SDValue RHS = GetPromotedInteger(N->getOperand(3));
599   return DAG.getNode(ISD::SELECT_CC, SDLoc(N),
600                      LHS.getValueType(), N->getOperand(0),
601                      N->getOperand(1), LHS, RHS, N->getOperand(4));
602 }
603
604 SDValue DAGTypeLegalizer::PromoteIntRes_SETCC(SDNode *N) {
605   EVT SVT = getSetCCResultType(N->getOperand(0).getValueType());
606
607   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
608
609   // Only use the result of getSetCCResultType if it is legal,
610   // otherwise just use the promoted result type (NVT).
611   if (!TLI.isTypeLegal(SVT))
612     SVT = NVT;
613
614   SDLoc dl(N);
615   assert(SVT.isVector() == N->getOperand(0).getValueType().isVector() &&
616          "Vector compare must return a vector result!");
617
618   SDValue LHS = N->getOperand(0);
619   SDValue RHS = N->getOperand(1);
620   if (LHS.getValueType() != RHS.getValueType()) {
621     if (getTypeAction(LHS.getValueType()) == TargetLowering::TypePromoteInteger &&
622         !LHS.getValueType().isVector())
623       LHS = GetPromotedInteger(LHS);
624     if (getTypeAction(RHS.getValueType()) == TargetLowering::TypePromoteInteger &&
625         !RHS.getValueType().isVector())
626       RHS = GetPromotedInteger(RHS);
627   }
628
629   // Get the SETCC result using the canonical SETCC type.
630   SDValue SetCC = DAG.getNode(N->getOpcode(), dl, SVT, LHS, RHS,
631                               N->getOperand(2));
632
633   assert(NVT.bitsLE(SVT) && "Integer type overpromoted?");
634   // Convert to the expected type.
635   return DAG.getNode(ISD::TRUNCATE, dl, NVT, SetCC);
636 }
637
638 SDValue DAGTypeLegalizer::PromoteIntRes_SHL(SDNode *N) {
639   SDValue LHS = N->getOperand(0);
640   SDValue RHS = N->getOperand(1);
641   if (getTypeAction(LHS.getValueType()) == TargetLowering::TypePromoteInteger)
642     LHS = GetPromotedInteger(LHS);
643   if (getTypeAction(RHS.getValueType()) == TargetLowering::TypePromoteInteger)
644     RHS = ZExtPromotedInteger(RHS);
645   return DAG.getNode(ISD::SHL, SDLoc(N), LHS.getValueType(), LHS, RHS);
646 }
647
648 SDValue DAGTypeLegalizer::PromoteIntRes_SIGN_EXTEND_INREG(SDNode *N) {
649   SDValue Op = GetPromotedInteger(N->getOperand(0));
650   return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N),
651                      Op.getValueType(), Op, N->getOperand(1));
652 }
653
654 SDValue DAGTypeLegalizer::PromoteIntRes_SimpleIntBinOp(SDNode *N) {
655   // The input may have strange things in the top bits of the registers, but
656   // these operations don't care.  They may have weird bits going out, but
657   // that too is okay if they are integer operations.
658   SDValue LHS = GetPromotedInteger(N->getOperand(0));
659   SDValue RHS = GetPromotedInteger(N->getOperand(1));
660   return DAG.getNode(N->getOpcode(), SDLoc(N),
661                      LHS.getValueType(), LHS, RHS);
662 }
663
664 SDValue DAGTypeLegalizer::PromoteIntRes_SExtOrZExtIntBinOp(SDNode *N,
665                                                            bool Signed) {
666   SDValue LHS, RHS;
667
668   if (Signed) {
669     LHS = SExtPromotedInteger(N->getOperand(0));
670     RHS = SExtPromotedInteger(N->getOperand(1));
671   } else {
672     LHS = ZExtPromotedInteger(N->getOperand(0));
673     RHS = ZExtPromotedInteger(N->getOperand(1));
674   }
675
676   return DAG.getNode(N->getOpcode(), SDLoc(N),
677                      LHS.getValueType(), LHS, RHS);
678 }
679
680 SDValue DAGTypeLegalizer::PromoteIntRes_SRA(SDNode *N) {
681   SDValue LHS = N->getOperand(0);
682   SDValue RHS = N->getOperand(1);
683   // The input value must be properly sign extended.
684   if (getTypeAction(LHS.getValueType()) == TargetLowering::TypePromoteInteger)
685     LHS = SExtPromotedInteger(LHS);
686   if (getTypeAction(RHS.getValueType()) == TargetLowering::TypePromoteInteger)
687     RHS = ZExtPromotedInteger(RHS);
688   return DAG.getNode(ISD::SRA, SDLoc(N), LHS.getValueType(), LHS, RHS);
689 }
690
691 SDValue DAGTypeLegalizer::PromoteIntRes_SRL(SDNode *N) {
692   SDValue LHS = N->getOperand(0);
693   SDValue RHS = N->getOperand(1);
694   // The input value must be properly zero extended.
695   if (getTypeAction(LHS.getValueType()) == TargetLowering::TypePromoteInteger)
696     LHS = ZExtPromotedInteger(LHS);
697   if (getTypeAction(RHS.getValueType()) == TargetLowering::TypePromoteInteger)
698     RHS = ZExtPromotedInteger(RHS);
699   return DAG.getNode(ISD::SRL, SDLoc(N), LHS.getValueType(), LHS, RHS);
700 }
701
702 SDValue DAGTypeLegalizer::PromoteIntRes_TRUNCATE(SDNode *N) {
703   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
704   SDValue Res;
705   SDValue InOp = N->getOperand(0);
706   SDLoc dl(N);
707
708   switch (getTypeAction(InOp.getValueType())) {
709   default: llvm_unreachable("Unknown type action!");
710   case TargetLowering::TypeLegal:
711   case TargetLowering::TypeExpandInteger:
712     Res = InOp;
713     break;
714   case TargetLowering::TypePromoteInteger:
715     Res = GetPromotedInteger(InOp);
716     break;
717   case TargetLowering::TypeSplitVector:
718     EVT InVT = InOp.getValueType();
719     assert(InVT.isVector() && "Cannot split scalar types");
720     unsigned NumElts = InVT.getVectorNumElements();
721     assert(NumElts == NVT.getVectorNumElements() &&
722            "Dst and Src must have the same number of elements");
723     assert(isPowerOf2_32(NumElts) &&
724            "Promoted vector type must be a power of two");
725
726     SDValue EOp1, EOp2;
727     GetSplitVector(InOp, EOp1, EOp2);
728
729     EVT HalfNVT = EVT::getVectorVT(*DAG.getContext(), NVT.getScalarType(),
730                                    NumElts/2);
731     EOp1 = DAG.getNode(ISD::TRUNCATE, dl, HalfNVT, EOp1);
732     EOp2 = DAG.getNode(ISD::TRUNCATE, dl, HalfNVT, EOp2);
733
734     return DAG.getNode(ISD::CONCAT_VECTORS, dl, NVT, EOp1, EOp2);
735   }
736
737   // Truncate to NVT instead of VT
738   return DAG.getNode(ISD::TRUNCATE, dl, NVT, Res);
739 }
740
741 SDValue DAGTypeLegalizer::PromoteIntRes_UADDSUBO(SDNode *N, unsigned ResNo) {
742   if (ResNo == 1)
743     return PromoteIntRes_Overflow(N);
744
745   // The operation overflowed iff the result in the larger type is not the
746   // zero extension of its truncation to the original type.
747   SDValue LHS = ZExtPromotedInteger(N->getOperand(0));
748   SDValue RHS = ZExtPromotedInteger(N->getOperand(1));
749   EVT OVT = N->getOperand(0).getValueType();
750   EVT NVT = LHS.getValueType();
751   SDLoc dl(N);
752
753   // Do the arithmetic in the larger type.
754   unsigned Opcode = N->getOpcode() == ISD::UADDO ? ISD::ADD : ISD::SUB;
755   SDValue Res = DAG.getNode(Opcode, dl, NVT, LHS, RHS);
756
757   // Calculate the overflow flag: zero extend the arithmetic result from
758   // the original type.
759   SDValue Ofl = DAG.getZeroExtendInReg(Res, dl, OVT);
760   // Overflowed if and only if this is not equal to Res.
761   Ofl = DAG.getSetCC(dl, N->getValueType(1), Ofl, Res, ISD::SETNE);
762
763   // Use the calculated overflow everywhere.
764   ReplaceValueWith(SDValue(N, 1), Ofl);
765
766   return Res;
767 }
768
769 SDValue DAGTypeLegalizer::PromoteIntRes_XMULO(SDNode *N, unsigned ResNo) {
770   // Promote the overflow bit trivially.
771   if (ResNo == 1)
772     return PromoteIntRes_Overflow(N);
773
774   SDValue LHS = N->getOperand(0), RHS = N->getOperand(1);
775   SDLoc DL(N);
776   EVT SmallVT = LHS.getValueType();
777
778   // To determine if the result overflowed in a larger type, we extend the
779   // input to the larger type, do the multiply (checking if it overflows),
780   // then also check the high bits of the result to see if overflow happened
781   // there.
782   if (N->getOpcode() == ISD::SMULO) {
783     LHS = SExtPromotedInteger(LHS);
784     RHS = SExtPromotedInteger(RHS);
785   } else {
786     LHS = ZExtPromotedInteger(LHS);
787     RHS = ZExtPromotedInteger(RHS);
788   }
789   SDVTList VTs = DAG.getVTList(LHS.getValueType(), N->getValueType(1));
790   SDValue Mul = DAG.getNode(N->getOpcode(), DL, VTs, LHS, RHS);
791
792   // Overflow occurred if it occurred in the larger type, or if the high part
793   // of the result does not zero/sign-extend the low part.  Check this second
794   // possibility first.
795   SDValue Overflow;
796   if (N->getOpcode() == ISD::UMULO) {
797     // Unsigned overflow occurred if the high part is non-zero.
798     SDValue Hi = DAG.getNode(ISD::SRL, DL, Mul.getValueType(), Mul,
799                              DAG.getIntPtrConstant(SmallVT.getSizeInBits(),
800                                                    DL));
801     Overflow = DAG.getSetCC(DL, N->getValueType(1), Hi,
802                             DAG.getConstant(0, DL, Hi.getValueType()),
803                             ISD::SETNE);
804   } else {
805     // Signed overflow occurred if the high part does not sign extend the low.
806     SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, Mul.getValueType(),
807                                Mul, DAG.getValueType(SmallVT));
808     Overflow = DAG.getSetCC(DL, N->getValueType(1), SExt, Mul, ISD::SETNE);
809   }
810
811   // The only other way for overflow to occur is if the multiplication in the
812   // larger type itself overflowed.
813   Overflow = DAG.getNode(ISD::OR, DL, N->getValueType(1), Overflow,
814                          SDValue(Mul.getNode(), 1));
815
816   // Use the calculated overflow everywhere.
817   ReplaceValueWith(SDValue(N, 1), Overflow);
818   return Mul;
819 }
820
821 SDValue DAGTypeLegalizer::PromoteIntRes_UDIV(SDNode *N) {
822   // Zero extend the input.
823   SDValue LHS = ZExtPromotedInteger(N->getOperand(0));
824   SDValue RHS = ZExtPromotedInteger(N->getOperand(1));
825   return DAG.getNode(N->getOpcode(), SDLoc(N),
826                      LHS.getValueType(), LHS, RHS);
827 }
828
829 SDValue DAGTypeLegalizer::PromoteIntRes_UNDEF(SDNode *N) {
830   return DAG.getUNDEF(TLI.getTypeToTransformTo(*DAG.getContext(),
831                                                N->getValueType(0)));
832 }
833
834 SDValue DAGTypeLegalizer::PromoteIntRes_VAARG(SDNode *N) {
835   SDValue Chain = N->getOperand(0); // Get the chain.
836   SDValue Ptr = N->getOperand(1); // Get the pointer.
837   EVT VT = N->getValueType(0);
838   SDLoc dl(N);
839
840   MVT RegVT = TLI.getRegisterType(*DAG.getContext(), VT);
841   unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), VT);
842   // The argument is passed as NumRegs registers of type RegVT.
843
844   SmallVector<SDValue, 8> Parts(NumRegs);
845   for (unsigned i = 0; i < NumRegs; ++i) {
846     Parts[i] = DAG.getVAArg(RegVT, dl, Chain, Ptr, N->getOperand(2),
847                             N->getConstantOperandVal(3));
848     Chain = Parts[i].getValue(1);
849   }
850
851   // Handle endianness of the load.
852   if (DAG.getDataLayout().isBigEndian())
853     std::reverse(Parts.begin(), Parts.end());
854
855   // Assemble the parts in the promoted type.
856   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
857   SDValue Res = DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, Parts[0]);
858   for (unsigned i = 1; i < NumRegs; ++i) {
859     SDValue Part = DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, Parts[i]);
860     // Shift it to the right position and "or" it in.
861     Part = DAG.getNode(ISD::SHL, dl, NVT, Part,
862                        DAG.getConstant(i * RegVT.getSizeInBits(), dl,
863                                        TLI.getPointerTy(DAG.getDataLayout())));
864     Res = DAG.getNode(ISD::OR, dl, NVT, Res, Part);
865   }
866
867   // Modified the chain result - switch anything that used the old chain to
868   // use the new one.
869   ReplaceValueWith(SDValue(N, 1), Chain);
870
871   return Res;
872 }
873
874 //===----------------------------------------------------------------------===//
875 //  Integer Operand Promotion
876 //===----------------------------------------------------------------------===//
877
878 /// PromoteIntegerOperand - This method is called when the specified operand of
879 /// the specified node is found to need promotion.  At this point, all of the
880 /// result types of the node are known to be legal, but other operands of the
881 /// node may need promotion or expansion as well as the specified one.
882 bool DAGTypeLegalizer::PromoteIntegerOperand(SDNode *N, unsigned OpNo) {
883   DEBUG(dbgs() << "Promote integer operand: "; N->dump(&DAG); dbgs() << "\n");
884   SDValue Res = SDValue();
885
886   if (CustomLowerNode(N, N->getOperand(OpNo).getValueType(), false))
887     return false;
888
889   switch (N->getOpcode()) {
890     default:
891   #ifndef NDEBUG
892     dbgs() << "PromoteIntegerOperand Op #" << OpNo << ": ";
893     N->dump(&DAG); dbgs() << "\n";
894   #endif
895     llvm_unreachable("Do not know how to promote this operator's operand!");
896
897   case ISD::ANY_EXTEND:   Res = PromoteIntOp_ANY_EXTEND(N); break;
898   case ISD::ATOMIC_STORE:
899     Res = PromoteIntOp_ATOMIC_STORE(cast<AtomicSDNode>(N));
900     break;
901   case ISD::BITCAST:      Res = PromoteIntOp_BITCAST(N); break;
902   case ISD::BR_CC:        Res = PromoteIntOp_BR_CC(N, OpNo); break;
903   case ISD::BRCOND:       Res = PromoteIntOp_BRCOND(N, OpNo); break;
904   case ISD::BUILD_PAIR:   Res = PromoteIntOp_BUILD_PAIR(N); break;
905   case ISD::BUILD_VECTOR: Res = PromoteIntOp_BUILD_VECTOR(N); break;
906   case ISD::CONCAT_VECTORS: Res = PromoteIntOp_CONCAT_VECTORS(N); break;
907   case ISD::EXTRACT_VECTOR_ELT: Res = PromoteIntOp_EXTRACT_VECTOR_ELT(N); break;
908   case ISD::CONVERT_RNDSAT:
909                           Res = PromoteIntOp_CONVERT_RNDSAT(N); break;
910   case ISD::INSERT_VECTOR_ELT:
911                           Res = PromoteIntOp_INSERT_VECTOR_ELT(N, OpNo);break;
912   case ISD::SCALAR_TO_VECTOR:
913                           Res = PromoteIntOp_SCALAR_TO_VECTOR(N); break;
914   case ISD::VSELECT:
915   case ISD::SELECT:       Res = PromoteIntOp_SELECT(N, OpNo); break;
916   case ISD::SELECT_CC:    Res = PromoteIntOp_SELECT_CC(N, OpNo); break;
917   case ISD::SETCC:        Res = PromoteIntOp_SETCC(N, OpNo); break;
918   case ISD::SIGN_EXTEND:  Res = PromoteIntOp_SIGN_EXTEND(N); break;
919   case ISD::SINT_TO_FP:   Res = PromoteIntOp_SINT_TO_FP(N); break;
920   case ISD::STORE:        Res = PromoteIntOp_STORE(cast<StoreSDNode>(N),
921                                                    OpNo); break;
922   case ISD::MSTORE:       Res = PromoteIntOp_MSTORE(cast<MaskedStoreSDNode>(N),
923                                                     OpNo); break;
924   case ISD::MLOAD:        Res = PromoteIntOp_MLOAD(cast<MaskedLoadSDNode>(N),
925                                                     OpNo); break;
926   case ISD::MGATHER:  Res = PromoteIntOp_MGATHER(cast<MaskedGatherSDNode>(N),
927                                                  OpNo); break;
928   case ISD::MSCATTER: Res = PromoteIntOp_MSCATTER(cast<MaskedScatterSDNode>(N),
929                                                   OpNo); break;
930   case ISD::TRUNCATE:     Res = PromoteIntOp_TRUNCATE(N); break;
931   case ISD::FP16_TO_FP:
932   case ISD::UINT_TO_FP:   Res = PromoteIntOp_UINT_TO_FP(N); break;
933   case ISD::ZERO_EXTEND:  Res = PromoteIntOp_ZERO_EXTEND(N); break;
934   case ISD::EXTRACT_SUBVECTOR: Res = PromoteIntOp_EXTRACT_SUBVECTOR(N); break;
935
936   case ISD::SHL:
937   case ISD::SRA:
938   case ISD::SRL:
939   case ISD::ROTL:
940   case ISD::ROTR: Res = PromoteIntOp_Shift(N); break;
941   }
942
943   // If the result is null, the sub-method took care of registering results etc.
944   if (!Res.getNode()) return false;
945
946   // If the result is N, the sub-method updated N in place.  Tell the legalizer
947   // core about this.
948   if (Res.getNode() == N)
949     return true;
950
951   assert(Res.getValueType() == N->getValueType(0) && N->getNumValues() == 1 &&
952          "Invalid operand expansion");
953
954   ReplaceValueWith(SDValue(N, 0), Res);
955   return false;
956 }
957
958 /// PromoteSetCCOperands - Promote the operands of a comparison.  This code is
959 /// shared among BR_CC, SELECT_CC, and SETCC handlers.
960 void DAGTypeLegalizer::PromoteSetCCOperands(SDValue &NewLHS,SDValue &NewRHS,
961                                             ISD::CondCode CCCode) {
962   // We have to insert explicit sign or zero extends.  Note that we could
963   // insert sign extends for ALL conditions, but zero extend is cheaper on
964   // many machines (an AND instead of two shifts), so prefer it.
965   switch (CCCode) {
966   default: llvm_unreachable("Unknown integer comparison!");
967   case ISD::SETEQ:
968   case ISD::SETNE: {
969     SDValue OpL = GetPromotedInteger(NewLHS);
970     SDValue OpR = GetPromotedInteger(NewRHS);
971
972     // We would prefer to promote the comparison operand with sign extension,
973     // if we find the operand is actually to truncate an AssertSext. With this
974     // optimization, we can avoid inserting real truncate instruction, which
975     // is redudant eventually.
976     if (OpL->getOpcode() == ISD::AssertSext &&
977         cast<VTSDNode>(OpL->getOperand(1))->getVT() == NewLHS.getValueType() &&
978         OpR->getOpcode() == ISD::AssertSext &&
979         cast<VTSDNode>(OpR->getOperand(1))->getVT() == NewRHS.getValueType()) {
980       NewLHS = OpL;
981       NewRHS = OpR;
982     } else {
983       NewLHS = ZExtPromotedInteger(NewLHS);
984       NewRHS = ZExtPromotedInteger(NewRHS);
985     }
986     break;
987   }
988   case ISD::SETUGE:
989   case ISD::SETUGT:
990   case ISD::SETULE:
991   case ISD::SETULT:
992     // ALL of these operations will work if we either sign or zero extend
993     // the operands (including the unsigned comparisons!).  Zero extend is
994     // usually a simpler/cheaper operation, so prefer it.
995     NewLHS = ZExtPromotedInteger(NewLHS);
996     NewRHS = ZExtPromotedInteger(NewRHS);
997     break;
998   case ISD::SETGE:
999   case ISD::SETGT:
1000   case ISD::SETLT:
1001   case ISD::SETLE:
1002     NewLHS = SExtPromotedInteger(NewLHS);
1003     NewRHS = SExtPromotedInteger(NewRHS);
1004     break;
1005   }
1006 }
1007
1008 SDValue DAGTypeLegalizer::PromoteIntOp_ANY_EXTEND(SDNode *N) {
1009   SDValue Op = GetPromotedInteger(N->getOperand(0));
1010   return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), N->getValueType(0), Op);
1011 }
1012
1013 SDValue DAGTypeLegalizer::PromoteIntOp_ATOMIC_STORE(AtomicSDNode *N) {
1014   SDValue Op2 = GetPromotedInteger(N->getOperand(2));
1015   return DAG.getAtomic(N->getOpcode(), SDLoc(N), N->getMemoryVT(),
1016                        N->getChain(), N->getBasePtr(), Op2, N->getMemOperand(),
1017                        N->getOrdering(), N->getSynchScope());
1018 }
1019
1020 SDValue DAGTypeLegalizer::PromoteIntOp_BITCAST(SDNode *N) {
1021   // This should only occur in unusual situations like bitcasting to an
1022   // x86_fp80, so just turn it into a store+load
1023   return CreateStackStoreLoad(N->getOperand(0), N->getValueType(0));
1024 }
1025
1026 SDValue DAGTypeLegalizer::PromoteIntOp_BR_CC(SDNode *N, unsigned OpNo) {
1027   assert(OpNo == 2 && "Don't know how to promote this operand!");
1028
1029   SDValue LHS = N->getOperand(2);
1030   SDValue RHS = N->getOperand(3);
1031   PromoteSetCCOperands(LHS, RHS, cast<CondCodeSDNode>(N->getOperand(1))->get());
1032
1033   // The chain (Op#0), CC (#1) and basic block destination (Op#4) are always
1034   // legal types.
1035   return SDValue(DAG.UpdateNodeOperands(N, N->getOperand(0),
1036                                 N->getOperand(1), LHS, RHS, N->getOperand(4)),
1037                  0);
1038 }
1039
1040 SDValue DAGTypeLegalizer::PromoteIntOp_BRCOND(SDNode *N, unsigned OpNo) {
1041   assert(OpNo == 1 && "only know how to promote condition");
1042
1043   // Promote all the way up to the canonical SetCC type.
1044   SDValue Cond = PromoteTargetBoolean(N->getOperand(1), MVT::Other);
1045
1046   // The chain (Op#0) and basic block destination (Op#2) are always legal types.
1047   return SDValue(DAG.UpdateNodeOperands(N, N->getOperand(0), Cond,
1048                                         N->getOperand(2)), 0);
1049 }
1050
1051 SDValue DAGTypeLegalizer::PromoteIntOp_BUILD_PAIR(SDNode *N) {
1052   // Since the result type is legal, the operands must promote to it.
1053   EVT OVT = N->getOperand(0).getValueType();
1054   SDValue Lo = ZExtPromotedInteger(N->getOperand(0));
1055   SDValue Hi = GetPromotedInteger(N->getOperand(1));
1056   assert(Lo.getValueType() == N->getValueType(0) && "Operand over promoted?");
1057   SDLoc dl(N);
1058
1059   Hi = DAG.getNode(ISD::SHL, dl, N->getValueType(0), Hi,
1060                    DAG.getConstant(OVT.getSizeInBits(), dl,
1061                                    TLI.getPointerTy(DAG.getDataLayout())));
1062   return DAG.getNode(ISD::OR, dl, N->getValueType(0), Lo, Hi);
1063 }
1064
1065 SDValue DAGTypeLegalizer::PromoteIntOp_BUILD_VECTOR(SDNode *N) {
1066   // The vector type is legal but the element type is not.  This implies
1067   // that the vector is a power-of-two in length and that the element
1068   // type does not have a strange size (eg: it is not i1).
1069   EVT VecVT = N->getValueType(0);
1070   unsigned NumElts = VecVT.getVectorNumElements();
1071   assert(!((NumElts & 1) && (!TLI.isTypeLegal(VecVT))) &&
1072          "Legal vector of one illegal element?");
1073
1074   // Promote the inserted value.  The type does not need to match the
1075   // vector element type.  Check that any extra bits introduced will be
1076   // truncated away.
1077   assert(N->getOperand(0).getValueType().getSizeInBits() >=
1078          N->getValueType(0).getVectorElementType().getSizeInBits() &&
1079          "Type of inserted value narrower than vector element type!");
1080
1081   SmallVector<SDValue, 16> NewOps;
1082   for (unsigned i = 0; i < NumElts; ++i)
1083     NewOps.push_back(GetPromotedInteger(N->getOperand(i)));
1084
1085   return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0);
1086 }
1087
1088 SDValue DAGTypeLegalizer::PromoteIntOp_CONVERT_RNDSAT(SDNode *N) {
1089   ISD::CvtCode CvtCode = cast<CvtRndSatSDNode>(N)->getCvtCode();
1090   assert ((CvtCode == ISD::CVT_SS || CvtCode == ISD::CVT_SU ||
1091            CvtCode == ISD::CVT_US || CvtCode == ISD::CVT_UU ||
1092            CvtCode == ISD::CVT_FS || CvtCode == ISD::CVT_FU) &&
1093            "can only promote integer arguments");
1094   SDValue InOp = GetPromotedInteger(N->getOperand(0));
1095   return DAG.getConvertRndSat(N->getValueType(0), SDLoc(N), InOp,
1096                               N->getOperand(1), N->getOperand(2),
1097                               N->getOperand(3), N->getOperand(4), CvtCode);
1098 }
1099
1100 SDValue DAGTypeLegalizer::PromoteIntOp_INSERT_VECTOR_ELT(SDNode *N,
1101                                                          unsigned OpNo) {
1102   if (OpNo == 1) {
1103     // Promote the inserted value.  This is valid because the type does not
1104     // have to match the vector element type.
1105
1106     // Check that any extra bits introduced will be truncated away.
1107     assert(N->getOperand(1).getValueType().getSizeInBits() >=
1108            N->getValueType(0).getVectorElementType().getSizeInBits() &&
1109            "Type of inserted value narrower than vector element type!");
1110     return SDValue(DAG.UpdateNodeOperands(N, N->getOperand(0),
1111                                   GetPromotedInteger(N->getOperand(1)),
1112                                   N->getOperand(2)),
1113                    0);
1114   }
1115
1116   assert(OpNo == 2 && "Different operand and result vector types?");
1117
1118   // Promote the index.
1119   SDValue Idx = DAG.getZExtOrTrunc(N->getOperand(2), SDLoc(N),
1120                                    TLI.getVectorIdxTy(DAG.getDataLayout()));
1121   return SDValue(DAG.UpdateNodeOperands(N, N->getOperand(0),
1122                                 N->getOperand(1), Idx), 0);
1123 }
1124
1125 SDValue DAGTypeLegalizer::PromoteIntOp_SCALAR_TO_VECTOR(SDNode *N) {
1126   // Integer SCALAR_TO_VECTOR operands are implicitly truncated, so just promote
1127   // the operand in place.
1128   return SDValue(DAG.UpdateNodeOperands(N,
1129                                 GetPromotedInteger(N->getOperand(0))), 0);
1130 }
1131
1132 SDValue DAGTypeLegalizer::PromoteIntOp_SELECT(SDNode *N, unsigned OpNo) {
1133   assert(OpNo == 0 && "Only know how to promote the condition!");
1134   SDValue Cond = N->getOperand(0);
1135   EVT OpTy = N->getOperand(1).getValueType();
1136
1137   // Promote all the way up to the canonical SetCC type.
1138   EVT OpVT = N->getOpcode() == ISD::SELECT ? OpTy.getScalarType() : OpTy;
1139   Cond = PromoteTargetBoolean(Cond, OpVT);
1140
1141   return SDValue(DAG.UpdateNodeOperands(N, Cond, N->getOperand(1),
1142                                         N->getOperand(2)), 0);
1143 }
1144
1145 SDValue DAGTypeLegalizer::PromoteIntOp_SELECT_CC(SDNode *N, unsigned OpNo) {
1146   assert(OpNo == 0 && "Don't know how to promote this operand!");
1147
1148   SDValue LHS = N->getOperand(0);
1149   SDValue RHS = N->getOperand(1);
1150   PromoteSetCCOperands(LHS, RHS, cast<CondCodeSDNode>(N->getOperand(4))->get());
1151
1152   // The CC (#4) and the possible return values (#2 and #3) have legal types.
1153   return SDValue(DAG.UpdateNodeOperands(N, LHS, RHS, N->getOperand(2),
1154                                 N->getOperand(3), N->getOperand(4)), 0);
1155 }
1156
1157 SDValue DAGTypeLegalizer::PromoteIntOp_SETCC(SDNode *N, unsigned OpNo) {
1158   assert(OpNo == 0 && "Don't know how to promote this operand!");
1159
1160   SDValue LHS = N->getOperand(0);
1161   SDValue RHS = N->getOperand(1);
1162   PromoteSetCCOperands(LHS, RHS, cast<CondCodeSDNode>(N->getOperand(2))->get());
1163
1164   // The CC (#2) is always legal.
1165   return SDValue(DAG.UpdateNodeOperands(N, LHS, RHS, N->getOperand(2)), 0);
1166 }
1167
1168 SDValue DAGTypeLegalizer::PromoteIntOp_Shift(SDNode *N) {
1169   return SDValue(DAG.UpdateNodeOperands(N, N->getOperand(0),
1170                                 ZExtPromotedInteger(N->getOperand(1))), 0);
1171 }
1172
1173 SDValue DAGTypeLegalizer::PromoteIntOp_SIGN_EXTEND(SDNode *N) {
1174   SDValue Op = GetPromotedInteger(N->getOperand(0));
1175   SDLoc dl(N);
1176   Op = DAG.getNode(ISD::ANY_EXTEND, dl, N->getValueType(0), Op);
1177   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, Op.getValueType(),
1178                      Op, DAG.getValueType(N->getOperand(0).getValueType()));
1179 }
1180
1181 SDValue DAGTypeLegalizer::PromoteIntOp_SINT_TO_FP(SDNode *N) {
1182   return SDValue(DAG.UpdateNodeOperands(N,
1183                                 SExtPromotedInteger(N->getOperand(0))), 0);
1184 }
1185
1186 SDValue DAGTypeLegalizer::PromoteIntOp_STORE(StoreSDNode *N, unsigned OpNo){
1187   assert(ISD::isUNINDEXEDStore(N) && "Indexed store during type legalization!");
1188   SDValue Ch = N->getChain(), Ptr = N->getBasePtr();
1189   SDLoc dl(N);
1190
1191   SDValue Val = GetPromotedInteger(N->getValue());  // Get promoted value.
1192
1193   // Truncate the value and store the result.
1194   return DAG.getTruncStore(Ch, dl, Val, Ptr,
1195                            N->getMemoryVT(), N->getMemOperand());
1196 }
1197
1198 SDValue DAGTypeLegalizer::PromoteIntOp_MSTORE(MaskedStoreSDNode *N,
1199                                               unsigned OpNo) {
1200
1201   SDValue DataOp = N->getValue();
1202   EVT DataVT = DataOp.getValueType();
1203   SDValue Mask = N->getMask();
1204   SDLoc dl(N);
1205
1206   bool TruncateStore = false;
1207   if (OpNo == 2) {
1208     // Mask comes before the data operand. If the data operand is legal, we just
1209     // promote the mask.
1210     // When the data operand has illegal type, we should legalize the data
1211     // operand first. The mask will be promoted/splitted/widened according to
1212     // the data operand type.
1213     if (TLI.isTypeLegal(DataVT))
1214       Mask = PromoteTargetBoolean(Mask, DataVT);
1215     else {
1216       if (getTypeAction(DataVT) == TargetLowering::TypePromoteInteger)
1217         return PromoteIntOp_MSTORE(N, 3);
1218
1219       else if (getTypeAction(DataVT) == TargetLowering::TypeWidenVector)
1220         return WidenVecOp_MSTORE(N, 3);
1221
1222       else {
1223         assert (getTypeAction(DataVT) == TargetLowering::TypeSplitVector);
1224         return SplitVecOp_MSTORE(N, 3);
1225       }
1226     }
1227   } else { // Data operand
1228     assert(OpNo == 3 && "Unexpected operand for promotion");
1229     DataOp = GetPromotedInteger(DataOp);
1230     Mask = PromoteTargetBoolean(Mask, DataOp.getValueType());
1231     TruncateStore = true;
1232   }
1233
1234   return DAG.getMaskedStore(N->getChain(), dl, DataOp, N->getBasePtr(), Mask,
1235                             N->getMemoryVT(), N->getMemOperand(),
1236                             TruncateStore);
1237 }
1238
1239 SDValue DAGTypeLegalizer::PromoteIntOp_MLOAD(MaskedLoadSDNode *N,
1240                                              unsigned OpNo) {
1241   assert(OpNo == 2 && "Only know how to promote the mask!");
1242   EVT DataVT = N->getValueType(0);
1243   SDValue Mask = PromoteTargetBoolean(N->getOperand(OpNo), DataVT);
1244   SmallVector<SDValue, 4> NewOps(N->op_begin(), N->op_end());
1245   NewOps[OpNo] = Mask;
1246   return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0);
1247 }
1248
1249 SDValue DAGTypeLegalizer::PromoteIntOp_MGATHER(MaskedGatherSDNode *N,
1250                                                unsigned OpNo) {
1251
1252   SmallVector<SDValue, 5> NewOps(N->op_begin(), N->op_end());
1253   if (OpNo == 2) {
1254     // The Mask
1255     EVT DataVT = N->getValueType(0);
1256     NewOps[OpNo] = PromoteTargetBoolean(N->getOperand(OpNo), DataVT);
1257   } else
1258     NewOps[OpNo] = GetPromotedInteger(N->getOperand(OpNo));
1259   return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0);
1260 }
1261
1262 SDValue DAGTypeLegalizer::PromoteIntOp_MSCATTER(MaskedScatterSDNode *N,
1263                                                 unsigned OpNo) {
1264   SmallVector<SDValue, 5> NewOps(N->op_begin(), N->op_end());
1265   if (OpNo == 2) {
1266     // The Mask
1267     EVT DataVT = N->getValue().getValueType();
1268     NewOps[OpNo] = PromoteTargetBoolean(N->getOperand(OpNo), DataVT);
1269   } else
1270     NewOps[OpNo] = GetPromotedInteger(N->getOperand(OpNo));
1271   return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0);
1272 }
1273
1274 SDValue DAGTypeLegalizer::PromoteIntOp_TRUNCATE(SDNode *N) {
1275   SDValue Op = GetPromotedInteger(N->getOperand(0));
1276   return DAG.getNode(ISD::TRUNCATE, SDLoc(N), N->getValueType(0), Op);
1277 }
1278
1279 SDValue DAGTypeLegalizer::PromoteIntOp_UINT_TO_FP(SDNode *N) {
1280   return SDValue(DAG.UpdateNodeOperands(N,
1281                                 ZExtPromotedInteger(N->getOperand(0))), 0);
1282 }
1283
1284 SDValue DAGTypeLegalizer::PromoteIntOp_ZERO_EXTEND(SDNode *N) {
1285   SDLoc dl(N);
1286   SDValue Op = GetPromotedInteger(N->getOperand(0));
1287   Op = DAG.getNode(ISD::ANY_EXTEND, dl, N->getValueType(0), Op);
1288   return DAG.getZeroExtendInReg(Op, dl,
1289                                 N->getOperand(0).getValueType().getScalarType());
1290 }
1291
1292
1293 //===----------------------------------------------------------------------===//
1294 //  Integer Result Expansion
1295 //===----------------------------------------------------------------------===//
1296
1297 /// ExpandIntegerResult - This method is called when the specified result of the
1298 /// specified node is found to need expansion.  At this point, the node may also
1299 /// have invalid operands or may have other results that need promotion, we just
1300 /// know that (at least) one result needs expansion.
1301 void DAGTypeLegalizer::ExpandIntegerResult(SDNode *N, unsigned ResNo) {
1302   DEBUG(dbgs() << "Expand integer result: "; N->dump(&DAG); dbgs() << "\n");
1303   SDValue Lo, Hi;
1304   Lo = Hi = SDValue();
1305
1306   // See if the target wants to custom expand this node.
1307   if (CustomLowerNode(N, N->getValueType(ResNo), true))
1308     return;
1309
1310   switch (N->getOpcode()) {
1311   default:
1312 #ifndef NDEBUG
1313     dbgs() << "ExpandIntegerResult #" << ResNo << ": ";
1314     N->dump(&DAG); dbgs() << "\n";
1315 #endif
1316     llvm_unreachable("Do not know how to expand the result of this operator!");
1317
1318   case ISD::MERGE_VALUES: SplitRes_MERGE_VALUES(N, ResNo, Lo, Hi); break;
1319   case ISD::SELECT:       SplitRes_SELECT(N, Lo, Hi); break;
1320   case ISD::SELECT_CC:    SplitRes_SELECT_CC(N, Lo, Hi); break;
1321   case ISD::UNDEF:        SplitRes_UNDEF(N, Lo, Hi); break;
1322
1323   case ISD::BITCAST:            ExpandRes_BITCAST(N, Lo, Hi); break;
1324   case ISD::BUILD_PAIR:         ExpandRes_BUILD_PAIR(N, Lo, Hi); break;
1325   case ISD::EXTRACT_ELEMENT:    ExpandRes_EXTRACT_ELEMENT(N, Lo, Hi); break;
1326   case ISD::EXTRACT_VECTOR_ELT: ExpandRes_EXTRACT_VECTOR_ELT(N, Lo, Hi); break;
1327   case ISD::VAARG:              ExpandRes_VAARG(N, Lo, Hi); break;
1328
1329   case ISD::ANY_EXTEND:  ExpandIntRes_ANY_EXTEND(N, Lo, Hi); break;
1330   case ISD::AssertSext:  ExpandIntRes_AssertSext(N, Lo, Hi); break;
1331   case ISD::AssertZext:  ExpandIntRes_AssertZext(N, Lo, Hi); break;
1332   case ISD::BITREVERSE:  ExpandIntRes_BITREVERSE(N, Lo, Hi); break;
1333   case ISD::BSWAP:       ExpandIntRes_BSWAP(N, Lo, Hi); break;
1334   case ISD::Constant:    ExpandIntRes_Constant(N, Lo, Hi); break;
1335   case ISD::CTLZ_ZERO_UNDEF:
1336   case ISD::CTLZ:        ExpandIntRes_CTLZ(N, Lo, Hi); break;
1337   case ISD::CTPOP:       ExpandIntRes_CTPOP(N, Lo, Hi); break;
1338   case ISD::CTTZ_ZERO_UNDEF:
1339   case ISD::CTTZ:        ExpandIntRes_CTTZ(N, Lo, Hi); break;
1340   case ISD::FP_TO_SINT:  ExpandIntRes_FP_TO_SINT(N, Lo, Hi); break;
1341   case ISD::FP_TO_UINT:  ExpandIntRes_FP_TO_UINT(N, Lo, Hi); break;
1342   case ISD::LOAD:        ExpandIntRes_LOAD(cast<LoadSDNode>(N), Lo, Hi); break;
1343   case ISD::MUL:         ExpandIntRes_MUL(N, Lo, Hi); break;
1344   case ISD::READCYCLECOUNTER: ExpandIntRes_READCYCLECOUNTER(N, Lo, Hi); break;
1345   case ISD::SDIV:        ExpandIntRes_SDIV(N, Lo, Hi); break;
1346   case ISD::SIGN_EXTEND: ExpandIntRes_SIGN_EXTEND(N, Lo, Hi); break;
1347   case ISD::SIGN_EXTEND_INREG: ExpandIntRes_SIGN_EXTEND_INREG(N, Lo, Hi); break;
1348   case ISD::SREM:        ExpandIntRes_SREM(N, Lo, Hi); break;
1349   case ISD::TRUNCATE:    ExpandIntRes_TRUNCATE(N, Lo, Hi); break;
1350   case ISD::UDIV:        ExpandIntRes_UDIV(N, Lo, Hi); break;
1351   case ISD::UREM:        ExpandIntRes_UREM(N, Lo, Hi); break;
1352   case ISD::ZERO_EXTEND: ExpandIntRes_ZERO_EXTEND(N, Lo, Hi); break;
1353   case ISD::ATOMIC_LOAD: ExpandIntRes_ATOMIC_LOAD(N, Lo, Hi); break;
1354
1355   case ISD::ATOMIC_LOAD_ADD:
1356   case ISD::ATOMIC_LOAD_SUB:
1357   case ISD::ATOMIC_LOAD_AND:
1358   case ISD::ATOMIC_LOAD_OR:
1359   case ISD::ATOMIC_LOAD_XOR:
1360   case ISD::ATOMIC_LOAD_NAND:
1361   case ISD::ATOMIC_LOAD_MIN:
1362   case ISD::ATOMIC_LOAD_MAX:
1363   case ISD::ATOMIC_LOAD_UMIN:
1364   case ISD::ATOMIC_LOAD_UMAX:
1365   case ISD::ATOMIC_SWAP:
1366   case ISD::ATOMIC_CMP_SWAP: {
1367     std::pair<SDValue, SDValue> Tmp = ExpandAtomic(N);
1368     SplitInteger(Tmp.first, Lo, Hi);
1369     ReplaceValueWith(SDValue(N, 1), Tmp.second);
1370     break;
1371   }
1372   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
1373     AtomicSDNode *AN = cast<AtomicSDNode>(N);
1374     SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::Other);
1375     SDValue Tmp = DAG.getAtomicCmpSwap(
1376         ISD::ATOMIC_CMP_SWAP, SDLoc(N), AN->getMemoryVT(), VTs,
1377         N->getOperand(0), N->getOperand(1), N->getOperand(2), N->getOperand(3),
1378         AN->getMemOperand(), AN->getSuccessOrdering(), AN->getFailureOrdering(),
1379         AN->getSynchScope());
1380
1381     // Expanding to the strong ATOMIC_CMP_SWAP node means we can determine
1382     // success simply by comparing the loaded value against the ingoing
1383     // comparison.
1384     SDValue Success = DAG.getSetCC(SDLoc(N), N->getValueType(1), Tmp,
1385                                    N->getOperand(2), ISD::SETEQ);
1386
1387     SplitInteger(Tmp, Lo, Hi);
1388     ReplaceValueWith(SDValue(N, 1), Success);
1389     ReplaceValueWith(SDValue(N, 2), Tmp.getValue(1));
1390     break;
1391   }
1392
1393   case ISD::AND:
1394   case ISD::OR:
1395   case ISD::XOR: ExpandIntRes_Logical(N, Lo, Hi); break;
1396
1397   case ISD::ADD:
1398   case ISD::SUB: ExpandIntRes_ADDSUB(N, Lo, Hi); break;
1399
1400   case ISD::ADDC:
1401   case ISD::SUBC: ExpandIntRes_ADDSUBC(N, Lo, Hi); break;
1402
1403   case ISD::ADDE:
1404   case ISD::SUBE: ExpandIntRes_ADDSUBE(N, Lo, Hi); break;
1405
1406   case ISD::SHL:
1407   case ISD::SRA:
1408   case ISD::SRL: ExpandIntRes_Shift(N, Lo, Hi); break;
1409
1410   case ISD::SADDO:
1411   case ISD::SSUBO: ExpandIntRes_SADDSUBO(N, Lo, Hi); break;
1412   case ISD::UADDO:
1413   case ISD::USUBO: ExpandIntRes_UADDSUBO(N, Lo, Hi); break;
1414   case ISD::UMULO:
1415   case ISD::SMULO: ExpandIntRes_XMULO(N, Lo, Hi); break;
1416   }
1417
1418   // If Lo/Hi is null, the sub-method took care of registering results etc.
1419   if (Lo.getNode())
1420     SetExpandedInteger(SDValue(N, ResNo), Lo, Hi);
1421 }
1422
1423 /// Lower an atomic node to the appropriate builtin call.
1424 std::pair <SDValue, SDValue> DAGTypeLegalizer::ExpandAtomic(SDNode *Node) {
1425   unsigned Opc = Node->getOpcode();
1426   MVT VT = cast<AtomicSDNode>(Node)->getMemoryVT().getSimpleVT();
1427   RTLIB::Libcall LC = RTLIB::getATOMIC(Opc, VT);
1428   assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unexpected atomic op or value type!");
1429
1430   return ExpandChainLibCall(LC, Node, false);
1431 }
1432
1433 /// N is a shift by a value that needs to be expanded,
1434 /// and the shift amount is a constant 'Amt'.  Expand the operation.
1435 void DAGTypeLegalizer::ExpandShiftByConstant(SDNode *N, const APInt &Amt,
1436                                              SDValue &Lo, SDValue &Hi) {
1437   SDLoc DL(N);
1438   // Expand the incoming operand to be shifted, so that we have its parts
1439   SDValue InL, InH;
1440   GetExpandedInteger(N->getOperand(0), InL, InH);
1441
1442   // Though Amt shouldn't usually be 0, it's possible. E.g. when legalization
1443   // splitted a vector shift, like this: <op1, op2> SHL <0, 2>.
1444   if (!Amt) {
1445     Lo = InL;
1446     Hi = InH;
1447     return;
1448   }
1449
1450   EVT NVT = InL.getValueType();
1451   unsigned VTBits = N->getValueType(0).getSizeInBits();
1452   unsigned NVTBits = NVT.getSizeInBits();
1453   EVT ShTy = N->getOperand(1).getValueType();
1454
1455   if (N->getOpcode() == ISD::SHL) {
1456     if (Amt.ugt(VTBits)) {
1457       Lo = Hi = DAG.getConstant(0, DL, NVT);
1458     } else if (Amt.ugt(NVTBits)) {
1459       Lo = DAG.getConstant(0, DL, NVT);
1460       Hi = DAG.getNode(ISD::SHL, DL,
1461                        NVT, InL, DAG.getConstant(Amt - NVTBits, DL, ShTy));
1462     } else if (Amt == NVTBits) {
1463       Lo = DAG.getConstant(0, DL, NVT);
1464       Hi = InL;
1465     } else if (Amt == 1 &&
1466                TLI.isOperationLegalOrCustom(ISD::ADDC,
1467                               TLI.getTypeToExpandTo(*DAG.getContext(), NVT))) {
1468       // Emit this X << 1 as X+X.
1469       SDVTList VTList = DAG.getVTList(NVT, MVT::Glue);
1470       SDValue LoOps[2] = { InL, InL };
1471       Lo = DAG.getNode(ISD::ADDC, DL, VTList, LoOps);
1472       SDValue HiOps[3] = { InH, InH, Lo.getValue(1) };
1473       Hi = DAG.getNode(ISD::ADDE, DL, VTList, HiOps);
1474     } else {
1475       Lo = DAG.getNode(ISD::SHL, DL, NVT, InL, DAG.getConstant(Amt, DL, ShTy));
1476       Hi = DAG.getNode(ISD::OR, DL, NVT,
1477                        DAG.getNode(ISD::SHL, DL, NVT, InH,
1478                                    DAG.getConstant(Amt, DL, ShTy)),
1479                        DAG.getNode(ISD::SRL, DL, NVT, InL,
1480                                    DAG.getConstant(-Amt + NVTBits, DL, ShTy)));
1481     }
1482     return;
1483   }
1484
1485   if (N->getOpcode() == ISD::SRL) {
1486     if (Amt.ugt(VTBits)) {
1487       Lo = Hi = DAG.getConstant(0, DL, NVT);
1488     } else if (Amt.ugt(NVTBits)) {
1489       Lo = DAG.getNode(ISD::SRL, DL,
1490                        NVT, InH, DAG.getConstant(Amt - NVTBits, DL, ShTy));
1491       Hi = DAG.getConstant(0, DL, NVT);
1492     } else if (Amt == NVTBits) {
1493       Lo = InH;
1494       Hi = DAG.getConstant(0, DL, NVT);
1495     } else {
1496       Lo = DAG.getNode(ISD::OR, DL, NVT,
1497                        DAG.getNode(ISD::SRL, DL, NVT, InL,
1498                                    DAG.getConstant(Amt, DL, ShTy)),
1499                        DAG.getNode(ISD::SHL, DL, NVT, InH,
1500                                    DAG.getConstant(-Amt + NVTBits, DL, ShTy)));
1501       Hi = DAG.getNode(ISD::SRL, DL, NVT, InH, DAG.getConstant(Amt, DL, ShTy));
1502     }
1503     return;
1504   }
1505
1506   assert(N->getOpcode() == ISD::SRA && "Unknown shift!");
1507   if (Amt.ugt(VTBits)) {
1508     Hi = Lo = DAG.getNode(ISD::SRA, DL, NVT, InH,
1509                           DAG.getConstant(NVTBits - 1, DL, ShTy));
1510   } else if (Amt.ugt(NVTBits)) {
1511     Lo = DAG.getNode(ISD::SRA, DL, NVT, InH,
1512                      DAG.getConstant(Amt - NVTBits, DL, ShTy));
1513     Hi = DAG.getNode(ISD::SRA, DL, NVT, InH,
1514                      DAG.getConstant(NVTBits - 1, DL, ShTy));
1515   } else if (Amt == NVTBits) {
1516     Lo = InH;
1517     Hi = DAG.getNode(ISD::SRA, DL, NVT, InH,
1518                      DAG.getConstant(NVTBits - 1, DL, ShTy));
1519   } else {
1520     Lo = DAG.getNode(ISD::OR, DL, NVT,
1521                      DAG.getNode(ISD::SRL, DL, NVT, InL,
1522                                  DAG.getConstant(Amt, DL, ShTy)),
1523                      DAG.getNode(ISD::SHL, DL, NVT, InH,
1524                                  DAG.getConstant(-Amt + NVTBits, DL, ShTy)));
1525     Hi = DAG.getNode(ISD::SRA, DL, NVT, InH, DAG.getConstant(Amt, DL, ShTy));
1526   }
1527 }
1528
1529 /// ExpandShiftWithKnownAmountBit - Try to determine whether we can simplify
1530 /// this shift based on knowledge of the high bit of the shift amount.  If we
1531 /// can tell this, we know that it is >= 32 or < 32, without knowing the actual
1532 /// shift amount.
1533 bool DAGTypeLegalizer::
1534 ExpandShiftWithKnownAmountBit(SDNode *N, SDValue &Lo, SDValue &Hi) {
1535   SDValue Amt = N->getOperand(1);
1536   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
1537   EVT ShTy = Amt.getValueType();
1538   unsigned ShBits = ShTy.getScalarType().getSizeInBits();
1539   unsigned NVTBits = NVT.getScalarType().getSizeInBits();
1540   assert(isPowerOf2_32(NVTBits) &&
1541          "Expanded integer type size not a power of two!");
1542   SDLoc dl(N);
1543
1544   APInt HighBitMask = APInt::getHighBitsSet(ShBits, ShBits - Log2_32(NVTBits));
1545   APInt KnownZero, KnownOne;
1546   DAG.computeKnownBits(N->getOperand(1), KnownZero, KnownOne);
1547
1548   // If we don't know anything about the high bits, exit.
1549   if (((KnownZero|KnownOne) & HighBitMask) == 0)
1550     return false;
1551
1552   // Get the incoming operand to be shifted.
1553   SDValue InL, InH;
1554   GetExpandedInteger(N->getOperand(0), InL, InH);
1555
1556   // If we know that any of the high bits of the shift amount are one, then we
1557   // can do this as a couple of simple shifts.
1558   if (KnownOne.intersects(HighBitMask)) {
1559     // Mask out the high bit, which we know is set.
1560     Amt = DAG.getNode(ISD::AND, dl, ShTy, Amt,
1561                       DAG.getConstant(~HighBitMask, dl, ShTy));
1562
1563     switch (N->getOpcode()) {
1564     default: llvm_unreachable("Unknown shift");
1565     case ISD::SHL:
1566       Lo = DAG.getConstant(0, dl, NVT);              // Low part is zero.
1567       Hi = DAG.getNode(ISD::SHL, dl, NVT, InL, Amt); // High part from Lo part.
1568       return true;
1569     case ISD::SRL:
1570       Hi = DAG.getConstant(0, dl, NVT);              // Hi part is zero.
1571       Lo = DAG.getNode(ISD::SRL, dl, NVT, InH, Amt); // Lo part from Hi part.
1572       return true;
1573     case ISD::SRA:
1574       Hi = DAG.getNode(ISD::SRA, dl, NVT, InH,       // Sign extend high part.
1575                        DAG.getConstant(NVTBits - 1, dl, ShTy));
1576       Lo = DAG.getNode(ISD::SRA, dl, NVT, InH, Amt); // Lo part from Hi part.
1577       return true;
1578     }
1579   }
1580
1581   // If we know that all of the high bits of the shift amount are zero, then we
1582   // can do this as a couple of simple shifts.
1583   if ((KnownZero & HighBitMask) == HighBitMask) {
1584     // Calculate 31-x. 31 is used instead of 32 to avoid creating an undefined
1585     // shift if x is zero.  We can use XOR here because x is known to be smaller
1586     // than 32.
1587     SDValue Amt2 = DAG.getNode(ISD::XOR, dl, ShTy, Amt,
1588                                DAG.getConstant(NVTBits - 1, dl, ShTy));
1589
1590     unsigned Op1, Op2;
1591     switch (N->getOpcode()) {
1592     default: llvm_unreachable("Unknown shift");
1593     case ISD::SHL:  Op1 = ISD::SHL; Op2 = ISD::SRL; break;
1594     case ISD::SRL:
1595     case ISD::SRA:  Op1 = ISD::SRL; Op2 = ISD::SHL; break;
1596     }
1597
1598     // When shifting right the arithmetic for Lo and Hi is swapped.
1599     if (N->getOpcode() != ISD::SHL)
1600       std::swap(InL, InH);
1601
1602     // Use a little trick to get the bits that move from Lo to Hi. First
1603     // shift by one bit.
1604     SDValue Sh1 = DAG.getNode(Op2, dl, NVT, InL, DAG.getConstant(1, dl, ShTy));
1605     // Then compute the remaining shift with amount-1.
1606     SDValue Sh2 = DAG.getNode(Op2, dl, NVT, Sh1, Amt2);
1607
1608     Lo = DAG.getNode(N->getOpcode(), dl, NVT, InL, Amt);
1609     Hi = DAG.getNode(ISD::OR, dl, NVT, DAG.getNode(Op1, dl, NVT, InH, Amt),Sh2);
1610
1611     if (N->getOpcode() != ISD::SHL)
1612       std::swap(Hi, Lo);
1613     return true;
1614   }
1615
1616   return false;
1617 }
1618
1619 /// ExpandShiftWithUnknownAmountBit - Fully general expansion of integer shift
1620 /// of any size.
1621 bool DAGTypeLegalizer::
1622 ExpandShiftWithUnknownAmountBit(SDNode *N, SDValue &Lo, SDValue &Hi) {
1623   SDValue Amt = N->getOperand(1);
1624   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
1625   EVT ShTy = Amt.getValueType();
1626   unsigned NVTBits = NVT.getSizeInBits();
1627   assert(isPowerOf2_32(NVTBits) &&
1628          "Expanded integer type size not a power of two!");
1629   SDLoc dl(N);
1630
1631   // Get the incoming operand to be shifted.
1632   SDValue InL, InH;
1633   GetExpandedInteger(N->getOperand(0), InL, InH);
1634
1635   SDValue NVBitsNode = DAG.getConstant(NVTBits, dl, ShTy);
1636   SDValue AmtExcess = DAG.getNode(ISD::SUB, dl, ShTy, Amt, NVBitsNode);
1637   SDValue AmtLack = DAG.getNode(ISD::SUB, dl, ShTy, NVBitsNode, Amt);
1638   SDValue isShort = DAG.getSetCC(dl, getSetCCResultType(ShTy),
1639                                  Amt, NVBitsNode, ISD::SETULT);
1640   SDValue isZero = DAG.getSetCC(dl, getSetCCResultType(ShTy),
1641                                 Amt, DAG.getConstant(0, dl, ShTy),
1642                                 ISD::SETEQ);
1643
1644   SDValue LoS, HiS, LoL, HiL;
1645   switch (N->getOpcode()) {
1646   default: llvm_unreachable("Unknown shift");
1647   case ISD::SHL:
1648     // Short: ShAmt < NVTBits
1649     LoS = DAG.getNode(ISD::SHL, dl, NVT, InL, Amt);
1650     HiS = DAG.getNode(ISD::OR, dl, NVT,
1651                       DAG.getNode(ISD::SHL, dl, NVT, InH, Amt),
1652                       DAG.getNode(ISD::SRL, dl, NVT, InL, AmtLack));
1653
1654     // Long: ShAmt >= NVTBits
1655     LoL = DAG.getConstant(0, dl, NVT);                    // Lo part is zero.
1656     HiL = DAG.getNode(ISD::SHL, dl, NVT, InL, AmtExcess); // Hi from Lo part.
1657
1658     Lo = DAG.getSelect(dl, NVT, isShort, LoS, LoL);
1659     Hi = DAG.getSelect(dl, NVT, isZero, InH,
1660                        DAG.getSelect(dl, NVT, isShort, HiS, HiL));
1661     return true;
1662   case ISD::SRL:
1663     // Short: ShAmt < NVTBits
1664     HiS = DAG.getNode(ISD::SRL, dl, NVT, InH, Amt);
1665     LoS = DAG.getNode(ISD::OR, dl, NVT,
1666                       DAG.getNode(ISD::SRL, dl, NVT, InL, Amt),
1667     // FIXME: If Amt is zero, the following shift generates an undefined result
1668     // on some architectures.
1669                       DAG.getNode(ISD::SHL, dl, NVT, InH, AmtLack));
1670
1671     // Long: ShAmt >= NVTBits
1672     HiL = DAG.getConstant(0, dl, NVT);                    // Hi part is zero.
1673     LoL = DAG.getNode(ISD::SRL, dl, NVT, InH, AmtExcess); // Lo from Hi part.
1674
1675     Lo = DAG.getSelect(dl, NVT, isZero, InL,
1676                        DAG.getSelect(dl, NVT, isShort, LoS, LoL));
1677     Hi = DAG.getSelect(dl, NVT, isShort, HiS, HiL);
1678     return true;
1679   case ISD::SRA:
1680     // Short: ShAmt < NVTBits
1681     HiS = DAG.getNode(ISD::SRA, dl, NVT, InH, Amt);
1682     LoS = DAG.getNode(ISD::OR, dl, NVT,
1683                       DAG.getNode(ISD::SRL, dl, NVT, InL, Amt),
1684                       DAG.getNode(ISD::SHL, dl, NVT, InH, AmtLack));
1685
1686     // Long: ShAmt >= NVTBits
1687     HiL = DAG.getNode(ISD::SRA, dl, NVT, InH,             // Sign of Hi part.
1688                       DAG.getConstant(NVTBits - 1, dl, ShTy));
1689     LoL = DAG.getNode(ISD::SRA, dl, NVT, InH, AmtExcess); // Lo from Hi part.
1690
1691     Lo = DAG.getSelect(dl, NVT, isZero, InL,
1692                        DAG.getSelect(dl, NVT, isShort, LoS, LoL));
1693     Hi = DAG.getSelect(dl, NVT, isShort, HiS, HiL);
1694     return true;
1695   }
1696 }
1697
1698 void DAGTypeLegalizer::ExpandIntRes_ADDSUB(SDNode *N,
1699                                            SDValue &Lo, SDValue &Hi) {
1700   SDLoc dl(N);
1701   // Expand the subcomponents.
1702   SDValue LHSL, LHSH, RHSL, RHSH;
1703   GetExpandedInteger(N->getOperand(0), LHSL, LHSH);
1704   GetExpandedInteger(N->getOperand(1), RHSL, RHSH);
1705
1706   EVT NVT = LHSL.getValueType();
1707   SDValue LoOps[2] = { LHSL, RHSL };
1708   SDValue HiOps[3] = { LHSH, RHSH };
1709
1710   // Do not generate ADDC/ADDE or SUBC/SUBE if the target does not support
1711   // them.  TODO: Teach operation legalization how to expand unsupported
1712   // ADDC/ADDE/SUBC/SUBE.  The problem is that these operations generate
1713   // a carry of type MVT::Glue, but there doesn't seem to be any way to
1714   // generate a value of this type in the expanded code sequence.
1715   bool hasCarry =
1716     TLI.isOperationLegalOrCustom(N->getOpcode() == ISD::ADD ?
1717                                    ISD::ADDC : ISD::SUBC,
1718                                  TLI.getTypeToExpandTo(*DAG.getContext(), NVT));
1719
1720   if (hasCarry) {
1721     SDVTList VTList = DAG.getVTList(NVT, MVT::Glue);
1722     if (N->getOpcode() == ISD::ADD) {
1723       Lo = DAG.getNode(ISD::ADDC, dl, VTList, LoOps);
1724       HiOps[2] = Lo.getValue(1);
1725       Hi = DAG.getNode(ISD::ADDE, dl, VTList, HiOps);
1726     } else {
1727       Lo = DAG.getNode(ISD::SUBC, dl, VTList, LoOps);
1728       HiOps[2] = Lo.getValue(1);
1729       Hi = DAG.getNode(ISD::SUBE, dl, VTList, HiOps);
1730     }
1731     return;
1732   }
1733
1734   bool hasOVF =
1735     TLI.isOperationLegalOrCustom(N->getOpcode() == ISD::ADD ?
1736                                    ISD::UADDO : ISD::USUBO,
1737                                  TLI.getTypeToExpandTo(*DAG.getContext(), NVT));
1738   if (hasOVF) {
1739     SDVTList VTList = DAG.getVTList(NVT, NVT);
1740     TargetLoweringBase::BooleanContent BoolType = TLI.getBooleanContents(NVT);
1741     int RevOpc;
1742     if (N->getOpcode() == ISD::ADD) {
1743       RevOpc = ISD::SUB;
1744       Lo = DAG.getNode(ISD::UADDO, dl, VTList, LoOps);
1745       Hi = DAG.getNode(ISD::ADD, dl, NVT, makeArrayRef(HiOps, 2));
1746     } else {
1747       RevOpc = ISD::ADD;
1748       Lo = DAG.getNode(ISD::USUBO, dl, VTList, LoOps);
1749       Hi = DAG.getNode(ISD::SUB, dl, NVT, makeArrayRef(HiOps, 2));
1750     }
1751     SDValue OVF = Lo.getValue(1);
1752
1753     switch (BoolType) {
1754     case TargetLoweringBase::UndefinedBooleanContent:
1755       OVF = DAG.getNode(ISD::AND, dl, NVT, DAG.getConstant(1, dl, NVT), OVF);
1756       // Fallthrough
1757     case TargetLoweringBase::ZeroOrOneBooleanContent:
1758       Hi = DAG.getNode(N->getOpcode(), dl, NVT, Hi, OVF);
1759       break;
1760     case TargetLoweringBase::ZeroOrNegativeOneBooleanContent:
1761       Hi = DAG.getNode(RevOpc, dl, NVT, Hi, OVF);
1762     }
1763     return;
1764   }
1765
1766   if (N->getOpcode() == ISD::ADD) {
1767     Lo = DAG.getNode(ISD::ADD, dl, NVT, LoOps);
1768     Hi = DAG.getNode(ISD::ADD, dl, NVT, makeArrayRef(HiOps, 2));
1769     SDValue Cmp1 = DAG.getSetCC(dl, getSetCCResultType(NVT), Lo, LoOps[0],
1770                                 ISD::SETULT);
1771     SDValue Carry1 = DAG.getSelect(dl, NVT, Cmp1,
1772                                    DAG.getConstant(1, dl, NVT),
1773                                    DAG.getConstant(0, dl, NVT));
1774     SDValue Cmp2 = DAG.getSetCC(dl, getSetCCResultType(NVT), Lo, LoOps[1],
1775                                 ISD::SETULT);
1776     SDValue Carry2 = DAG.getSelect(dl, NVT, Cmp2,
1777                                    DAG.getConstant(1, dl, NVT), Carry1);
1778     Hi = DAG.getNode(ISD::ADD, dl, NVT, Hi, Carry2);
1779   } else {
1780     Lo = DAG.getNode(ISD::SUB, dl, NVT, LoOps);
1781     Hi = DAG.getNode(ISD::SUB, dl, NVT, makeArrayRef(HiOps, 2));
1782     SDValue Cmp =
1783       DAG.getSetCC(dl, getSetCCResultType(LoOps[0].getValueType()),
1784                    LoOps[0], LoOps[1], ISD::SETULT);
1785     SDValue Borrow = DAG.getSelect(dl, NVT, Cmp,
1786                                    DAG.getConstant(1, dl, NVT),
1787                                    DAG.getConstant(0, dl, NVT));
1788     Hi = DAG.getNode(ISD::SUB, dl, NVT, Hi, Borrow);
1789   }
1790 }
1791
1792 void DAGTypeLegalizer::ExpandIntRes_ADDSUBC(SDNode *N,
1793                                             SDValue &Lo, SDValue &Hi) {
1794   // Expand the subcomponents.
1795   SDValue LHSL, LHSH, RHSL, RHSH;
1796   SDLoc dl(N);
1797   GetExpandedInteger(N->getOperand(0), LHSL, LHSH);
1798   GetExpandedInteger(N->getOperand(1), RHSL, RHSH);
1799   SDVTList VTList = DAG.getVTList(LHSL.getValueType(), MVT::Glue);
1800   SDValue LoOps[2] = { LHSL, RHSL };
1801   SDValue HiOps[3] = { LHSH, RHSH };
1802
1803   if (N->getOpcode() == ISD::ADDC) {
1804     Lo = DAG.getNode(ISD::ADDC, dl, VTList, LoOps);
1805     HiOps[2] = Lo.getValue(1);
1806     Hi = DAG.getNode(ISD::ADDE, dl, VTList, HiOps);
1807   } else {
1808     Lo = DAG.getNode(ISD::SUBC, dl, VTList, LoOps);
1809     HiOps[2] = Lo.getValue(1);
1810     Hi = DAG.getNode(ISD::SUBE, dl, VTList, HiOps);
1811   }
1812
1813   // Legalized the flag result - switch anything that used the old flag to
1814   // use the new one.
1815   ReplaceValueWith(SDValue(N, 1), Hi.getValue(1));
1816 }
1817
1818 void DAGTypeLegalizer::ExpandIntRes_ADDSUBE(SDNode *N,
1819                                             SDValue &Lo, SDValue &Hi) {
1820   // Expand the subcomponents.
1821   SDValue LHSL, LHSH, RHSL, RHSH;
1822   SDLoc dl(N);
1823   GetExpandedInteger(N->getOperand(0), LHSL, LHSH);
1824   GetExpandedInteger(N->getOperand(1), RHSL, RHSH);
1825   SDVTList VTList = DAG.getVTList(LHSL.getValueType(), MVT::Glue);
1826   SDValue LoOps[3] = { LHSL, RHSL, N->getOperand(2) };
1827   SDValue HiOps[3] = { LHSH, RHSH };
1828
1829   Lo = DAG.getNode(N->getOpcode(), dl, VTList, LoOps);
1830   HiOps[2] = Lo.getValue(1);
1831   Hi = DAG.getNode(N->getOpcode(), dl, VTList, HiOps);
1832
1833   // Legalized the flag result - switch anything that used the old flag to
1834   // use the new one.
1835   ReplaceValueWith(SDValue(N, 1), Hi.getValue(1));
1836 }
1837
1838 void DAGTypeLegalizer::ExpandIntRes_ANY_EXTEND(SDNode *N,
1839                                                SDValue &Lo, SDValue &Hi) {
1840   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
1841   SDLoc dl(N);
1842   SDValue Op = N->getOperand(0);
1843   if (Op.getValueType().bitsLE(NVT)) {
1844     // The low part is any extension of the input (which degenerates to a copy).
1845     Lo = DAG.getNode(ISD::ANY_EXTEND, dl, NVT, Op);
1846     Hi = DAG.getUNDEF(NVT);   // The high part is undefined.
1847   } else {
1848     // For example, extension of an i48 to an i64.  The operand type necessarily
1849     // promotes to the result type, so will end up being expanded too.
1850     assert(getTypeAction(Op.getValueType()) ==
1851            TargetLowering::TypePromoteInteger &&
1852            "Only know how to promote this result!");
1853     SDValue Res = GetPromotedInteger(Op);
1854     assert(Res.getValueType() == N->getValueType(0) &&
1855            "Operand over promoted?");
1856     // Split the promoted operand.  This will simplify when it is expanded.
1857     SplitInteger(Res, Lo, Hi);
1858   }
1859 }
1860
1861 void DAGTypeLegalizer::ExpandIntRes_AssertSext(SDNode *N,
1862                                                SDValue &Lo, SDValue &Hi) {
1863   SDLoc dl(N);
1864   GetExpandedInteger(N->getOperand(0), Lo, Hi);
1865   EVT NVT = Lo.getValueType();
1866   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
1867   unsigned NVTBits = NVT.getSizeInBits();
1868   unsigned EVTBits = EVT.getSizeInBits();
1869
1870   if (NVTBits < EVTBits) {
1871     Hi = DAG.getNode(ISD::AssertSext, dl, NVT, Hi,
1872                      DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(),
1873                                                         EVTBits - NVTBits)));
1874   } else {
1875     Lo = DAG.getNode(ISD::AssertSext, dl, NVT, Lo, DAG.getValueType(EVT));
1876     // The high part replicates the sign bit of Lo, make it explicit.
1877     Hi = DAG.getNode(ISD::SRA, dl, NVT, Lo,
1878                      DAG.getConstant(NVTBits - 1, dl,
1879                                      TLI.getPointerTy(DAG.getDataLayout())));
1880   }
1881 }
1882
1883 void DAGTypeLegalizer::ExpandIntRes_AssertZext(SDNode *N,
1884                                                SDValue &Lo, SDValue &Hi) {
1885   SDLoc dl(N);
1886   GetExpandedInteger(N->getOperand(0), Lo, Hi);
1887   EVT NVT = Lo.getValueType();
1888   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
1889   unsigned NVTBits = NVT.getSizeInBits();
1890   unsigned EVTBits = EVT.getSizeInBits();
1891
1892   if (NVTBits < EVTBits) {
1893     Hi = DAG.getNode(ISD::AssertZext, dl, NVT, Hi,
1894                      DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(),
1895                                                         EVTBits - NVTBits)));
1896   } else {
1897     Lo = DAG.getNode(ISD::AssertZext, dl, NVT, Lo, DAG.getValueType(EVT));
1898     // The high part must be zero, make it explicit.
1899     Hi = DAG.getConstant(0, dl, NVT);
1900   }
1901 }
1902
1903 void DAGTypeLegalizer::ExpandIntRes_BITREVERSE(SDNode *N,
1904                                                SDValue &Lo, SDValue &Hi) {
1905   SDLoc dl(N);
1906   GetExpandedInteger(N->getOperand(0), Hi, Lo);  // Note swapped operands.
1907   Lo = DAG.getNode(ISD::BITREVERSE, dl, Lo.getValueType(), Lo);
1908   Hi = DAG.getNode(ISD::BITREVERSE, dl, Hi.getValueType(), Hi);
1909 }
1910
1911 void DAGTypeLegalizer::ExpandIntRes_BSWAP(SDNode *N,
1912                                           SDValue &Lo, SDValue &Hi) {
1913   SDLoc dl(N);
1914   GetExpandedInteger(N->getOperand(0), Hi, Lo);  // Note swapped operands.
1915   Lo = DAG.getNode(ISD::BSWAP, dl, Lo.getValueType(), Lo);
1916   Hi = DAG.getNode(ISD::BSWAP, dl, Hi.getValueType(), Hi);
1917 }
1918
1919 void DAGTypeLegalizer::ExpandIntRes_Constant(SDNode *N,
1920                                              SDValue &Lo, SDValue &Hi) {
1921   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
1922   unsigned NBitWidth = NVT.getSizeInBits();
1923   auto Constant = cast<ConstantSDNode>(N);
1924   const APInt &Cst = Constant->getAPIntValue();
1925   bool IsTarget = Constant->isTargetOpcode();
1926   bool IsOpaque = Constant->isOpaque();
1927   SDLoc dl(N);
1928   Lo = DAG.getConstant(Cst.trunc(NBitWidth), dl, NVT, IsTarget, IsOpaque);
1929   Hi = DAG.getConstant(Cst.lshr(NBitWidth).trunc(NBitWidth), dl, NVT, IsTarget,
1930                        IsOpaque);
1931 }
1932
1933 void DAGTypeLegalizer::ExpandIntRes_CTLZ(SDNode *N,
1934                                          SDValue &Lo, SDValue &Hi) {
1935   SDLoc dl(N);
1936   // ctlz (HiLo) -> Hi != 0 ? ctlz(Hi) : (ctlz(Lo)+32)
1937   GetExpandedInteger(N->getOperand(0), Lo, Hi);
1938   EVT NVT = Lo.getValueType();
1939
1940   SDValue HiNotZero = DAG.getSetCC(dl, getSetCCResultType(NVT), Hi,
1941                                    DAG.getConstant(0, dl, NVT), ISD::SETNE);
1942
1943   SDValue LoLZ = DAG.getNode(N->getOpcode(), dl, NVT, Lo);
1944   SDValue HiLZ = DAG.getNode(ISD::CTLZ_ZERO_UNDEF, dl, NVT, Hi);
1945
1946   Lo = DAG.getSelect(dl, NVT, HiNotZero, HiLZ,
1947                      DAG.getNode(ISD::ADD, dl, NVT, LoLZ,
1948                                  DAG.getConstant(NVT.getSizeInBits(), dl,
1949                                                  NVT)));
1950   Hi = DAG.getConstant(0, dl, NVT);
1951 }
1952
1953 void DAGTypeLegalizer::ExpandIntRes_CTPOP(SDNode *N,
1954                                           SDValue &Lo, SDValue &Hi) {
1955   SDLoc dl(N);
1956   // ctpop(HiLo) -> ctpop(Hi)+ctpop(Lo)
1957   GetExpandedInteger(N->getOperand(0), Lo, Hi);
1958   EVT NVT = Lo.getValueType();
1959   Lo = DAG.getNode(ISD::ADD, dl, NVT, DAG.getNode(ISD::CTPOP, dl, NVT, Lo),
1960                    DAG.getNode(ISD::CTPOP, dl, NVT, Hi));
1961   Hi = DAG.getConstant(0, dl, NVT);
1962 }
1963
1964 void DAGTypeLegalizer::ExpandIntRes_CTTZ(SDNode *N,
1965                                          SDValue &Lo, SDValue &Hi) {
1966   SDLoc dl(N);
1967   // cttz (HiLo) -> Lo != 0 ? cttz(Lo) : (cttz(Hi)+32)
1968   GetExpandedInteger(N->getOperand(0), Lo, Hi);
1969   EVT NVT = Lo.getValueType();
1970
1971   SDValue LoNotZero = DAG.getSetCC(dl, getSetCCResultType(NVT), Lo,
1972                                    DAG.getConstant(0, dl, NVT), ISD::SETNE);
1973
1974   SDValue LoLZ = DAG.getNode(ISD::CTTZ_ZERO_UNDEF, dl, NVT, Lo);
1975   SDValue HiLZ = DAG.getNode(N->getOpcode(), dl, NVT, Hi);
1976
1977   Lo = DAG.getSelect(dl, NVT, LoNotZero, LoLZ,
1978                      DAG.getNode(ISD::ADD, dl, NVT, HiLZ,
1979                                  DAG.getConstant(NVT.getSizeInBits(), dl,
1980                                                  NVT)));
1981   Hi = DAG.getConstant(0, dl, NVT);
1982 }
1983
1984 void DAGTypeLegalizer::ExpandIntRes_FP_TO_SINT(SDNode *N, SDValue &Lo,
1985                                                SDValue &Hi) {
1986   SDLoc dl(N);
1987   EVT VT = N->getValueType(0);
1988
1989   SDValue Op = N->getOperand(0);
1990   if (getTypeAction(Op.getValueType()) == TargetLowering::TypePromoteFloat)
1991     Op = GetPromotedFloat(Op);
1992
1993   RTLIB::Libcall LC = RTLIB::getFPTOSINT(Op.getValueType(), VT);
1994   assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unexpected fp-to-sint conversion!");
1995   SplitInteger(TLI.makeLibCall(DAG, LC, VT, Op, true/*irrelevant*/, dl).first,
1996                Lo, Hi);
1997 }
1998
1999 void DAGTypeLegalizer::ExpandIntRes_FP_TO_UINT(SDNode *N, SDValue &Lo,
2000                                                SDValue &Hi) {
2001   SDLoc dl(N);
2002   EVT VT = N->getValueType(0);
2003
2004   SDValue Op = N->getOperand(0);
2005   if (getTypeAction(Op.getValueType()) == TargetLowering::TypePromoteFloat)
2006     Op = GetPromotedFloat(Op);
2007
2008   RTLIB::Libcall LC = RTLIB::getFPTOUINT(Op.getValueType(), VT);
2009   assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unexpected fp-to-uint conversion!");
2010   SplitInteger(TLI.makeLibCall(DAG, LC, VT, Op, false/*irrelevant*/, dl).first,
2011                Lo, Hi);
2012 }
2013
2014 void DAGTypeLegalizer::ExpandIntRes_LOAD(LoadSDNode *N,
2015                                          SDValue &Lo, SDValue &Hi) {
2016   if (ISD::isNormalLoad(N)) {
2017     ExpandRes_NormalLoad(N, Lo, Hi);
2018     return;
2019   }
2020
2021   assert(ISD::isUNINDEXEDLoad(N) && "Indexed load during type legalization!");
2022
2023   EVT VT = N->getValueType(0);
2024   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), VT);
2025   SDValue Ch  = N->getChain();
2026   SDValue Ptr = N->getBasePtr();
2027   ISD::LoadExtType ExtType = N->getExtensionType();
2028   unsigned Alignment = N->getAlignment();
2029   bool isVolatile = N->isVolatile();
2030   bool isNonTemporal = N->isNonTemporal();
2031   bool isInvariant = N->isInvariant();
2032   AAMDNodes AAInfo = N->getAAInfo();
2033   SDLoc dl(N);
2034
2035   assert(NVT.isByteSized() && "Expanded type not byte sized!");
2036
2037   if (N->getMemoryVT().bitsLE(NVT)) {
2038     EVT MemVT = N->getMemoryVT();
2039
2040     Lo = DAG.getExtLoad(ExtType, dl, NVT, Ch, Ptr, N->getPointerInfo(),
2041                         MemVT, isVolatile, isNonTemporal, isInvariant,
2042                         Alignment, AAInfo);
2043
2044     // Remember the chain.
2045     Ch = Lo.getValue(1);
2046
2047     if (ExtType == ISD::SEXTLOAD) {
2048       // The high part is obtained by SRA'ing all but one of the bits of the
2049       // lo part.
2050       unsigned LoSize = Lo.getValueType().getSizeInBits();
2051       Hi = DAG.getNode(ISD::SRA, dl, NVT, Lo,
2052                        DAG.getConstant(LoSize - 1, dl,
2053                                        TLI.getPointerTy(DAG.getDataLayout())));
2054     } else if (ExtType == ISD::ZEXTLOAD) {
2055       // The high part is just a zero.
2056       Hi = DAG.getConstant(0, dl, NVT);
2057     } else {
2058       assert(ExtType == ISD::EXTLOAD && "Unknown extload!");
2059       // The high part is undefined.
2060       Hi = DAG.getUNDEF(NVT);
2061     }
2062   } else if (DAG.getDataLayout().isLittleEndian()) {
2063     // Little-endian - low bits are at low addresses.
2064     Lo = DAG.getLoad(NVT, dl, Ch, Ptr, N->getPointerInfo(),
2065                      isVolatile, isNonTemporal, isInvariant, Alignment,
2066                      AAInfo);
2067
2068     unsigned ExcessBits =
2069       N->getMemoryVT().getSizeInBits() - NVT.getSizeInBits();
2070     EVT NEVT = EVT::getIntegerVT(*DAG.getContext(), ExcessBits);
2071
2072     // Increment the pointer to the other half.
2073     unsigned IncrementSize = NVT.getSizeInBits()/8;
2074     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
2075                       DAG.getConstant(IncrementSize, dl, Ptr.getValueType()));
2076     Hi = DAG.getExtLoad(ExtType, dl, NVT, Ch, Ptr,
2077                         N->getPointerInfo().getWithOffset(IncrementSize), NEVT,
2078                         isVolatile, isNonTemporal, isInvariant,
2079                         MinAlign(Alignment, IncrementSize), AAInfo);
2080
2081     // Build a factor node to remember that this load is independent of the
2082     // other one.
2083     Ch = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1),
2084                      Hi.getValue(1));
2085   } else {
2086     // Big-endian - high bits are at low addresses.  Favor aligned loads at
2087     // the cost of some bit-fiddling.
2088     EVT MemVT = N->getMemoryVT();
2089     unsigned EBytes = MemVT.getStoreSize();
2090     unsigned IncrementSize = NVT.getSizeInBits()/8;
2091     unsigned ExcessBits = (EBytes - IncrementSize)*8;
2092
2093     // Load both the high bits and maybe some of the low bits.
2094     Hi = DAG.getExtLoad(ExtType, dl, NVT, Ch, Ptr, N->getPointerInfo(),
2095                         EVT::getIntegerVT(*DAG.getContext(),
2096                                           MemVT.getSizeInBits() - ExcessBits),
2097                         isVolatile, isNonTemporal, isInvariant, Alignment,
2098                         AAInfo);
2099
2100     // Increment the pointer to the other half.
2101     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
2102                       DAG.getConstant(IncrementSize, dl, Ptr.getValueType()));
2103     // Load the rest of the low bits.
2104     Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, NVT, Ch, Ptr,
2105                         N->getPointerInfo().getWithOffset(IncrementSize),
2106                         EVT::getIntegerVT(*DAG.getContext(), ExcessBits),
2107                         isVolatile, isNonTemporal, isInvariant,
2108                         MinAlign(Alignment, IncrementSize), AAInfo);
2109
2110     // Build a factor node to remember that this load is independent of the
2111     // other one.
2112     Ch = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1),
2113                      Hi.getValue(1));
2114
2115     if (ExcessBits < NVT.getSizeInBits()) {
2116       // Transfer low bits from the bottom of Hi to the top of Lo.
2117       Lo = DAG.getNode(
2118           ISD::OR, dl, NVT, Lo,
2119           DAG.getNode(ISD::SHL, dl, NVT, Hi,
2120                       DAG.getConstant(ExcessBits, dl,
2121                                       TLI.getPointerTy(DAG.getDataLayout()))));
2122       // Move high bits to the right position in Hi.
2123       Hi = DAG.getNode(ExtType == ISD::SEXTLOAD ? ISD::SRA : ISD::SRL, dl, NVT,
2124                        Hi,
2125                        DAG.getConstant(NVT.getSizeInBits() - ExcessBits, dl,
2126                                        TLI.getPointerTy(DAG.getDataLayout())));
2127     }
2128   }
2129
2130   // Legalize the chain result - switch anything that used the old chain to
2131   // use the new one.
2132   ReplaceValueWith(SDValue(N, 1), Ch);
2133 }
2134
2135 void DAGTypeLegalizer::ExpandIntRes_Logical(SDNode *N,
2136                                             SDValue &Lo, SDValue &Hi) {
2137   SDLoc dl(N);
2138   SDValue LL, LH, RL, RH;
2139   GetExpandedInteger(N->getOperand(0), LL, LH);
2140   GetExpandedInteger(N->getOperand(1), RL, RH);
2141   Lo = DAG.getNode(N->getOpcode(), dl, LL.getValueType(), LL, RL);
2142   Hi = DAG.getNode(N->getOpcode(), dl, LL.getValueType(), LH, RH);
2143 }
2144
2145 void DAGTypeLegalizer::ExpandIntRes_MUL(SDNode *N,
2146                                         SDValue &Lo, SDValue &Hi) {
2147   EVT VT = N->getValueType(0);
2148   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), VT);
2149   SDLoc dl(N);
2150
2151   SDValue LL, LH, RL, RH;
2152   GetExpandedInteger(N->getOperand(0), LL, LH);
2153   GetExpandedInteger(N->getOperand(1), RL, RH);
2154
2155   if (TLI.expandMUL(N, Lo, Hi, NVT, DAG, LL, LH, RL, RH))
2156     return;
2157
2158   // If nothing else, we can make a libcall.
2159   RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
2160   if (VT == MVT::i16)
2161     LC = RTLIB::MUL_I16;
2162   else if (VT == MVT::i32)
2163     LC = RTLIB::MUL_I32;
2164   else if (VT == MVT::i64)
2165     LC = RTLIB::MUL_I64;
2166   else if (VT == MVT::i128)
2167     LC = RTLIB::MUL_I128;
2168   assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unsupported MUL!");
2169
2170   SDValue Ops[2] = { N->getOperand(0), N->getOperand(1) };
2171   SplitInteger(TLI.makeLibCall(DAG, LC, VT, Ops, true/*irrelevant*/, dl).first,
2172                Lo, Hi);
2173 }
2174
2175 void DAGTypeLegalizer::ExpandIntRes_READCYCLECOUNTER(SDNode *N, SDValue &Lo,
2176                                                      SDValue &Hi) {
2177   SDLoc DL(N);
2178   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
2179   SDVTList VTs = DAG.getVTList(NVT, NVT, MVT::Other);
2180   SDValue R = DAG.getNode(N->getOpcode(), DL, VTs, N->getOperand(0));
2181   Lo = R.getValue(0);
2182   Hi = R.getValue(1);
2183   ReplaceValueWith(SDValue(N, 1), R.getValue(2));
2184 }
2185
2186 void DAGTypeLegalizer::ExpandIntRes_SADDSUBO(SDNode *Node,
2187                                              SDValue &Lo, SDValue &Hi) {
2188   SDValue LHS = Node->getOperand(0);
2189   SDValue RHS = Node->getOperand(1);
2190   SDLoc dl(Node);
2191
2192   // Expand the result by simply replacing it with the equivalent
2193   // non-overflow-checking operation.
2194   SDValue Sum = DAG.getNode(Node->getOpcode() == ISD::SADDO ?
2195                             ISD::ADD : ISD::SUB, dl, LHS.getValueType(),
2196                             LHS, RHS);
2197   SplitInteger(Sum, Lo, Hi);
2198
2199   // Compute the overflow.
2200   //
2201   //   LHSSign -> LHS >= 0
2202   //   RHSSign -> RHS >= 0
2203   //   SumSign -> Sum >= 0
2204   //
2205   //   Add:
2206   //   Overflow -> (LHSSign == RHSSign) && (LHSSign != SumSign)
2207   //   Sub:
2208   //   Overflow -> (LHSSign != RHSSign) && (LHSSign != SumSign)
2209   //
2210   EVT OType = Node->getValueType(1);
2211   SDValue Zero = DAG.getConstant(0, dl, LHS.getValueType());
2212
2213   SDValue LHSSign = DAG.getSetCC(dl, OType, LHS, Zero, ISD::SETGE);
2214   SDValue RHSSign = DAG.getSetCC(dl, OType, RHS, Zero, ISD::SETGE);
2215   SDValue SignsMatch = DAG.getSetCC(dl, OType, LHSSign, RHSSign,
2216                                     Node->getOpcode() == ISD::SADDO ?
2217                                     ISD::SETEQ : ISD::SETNE);
2218
2219   SDValue SumSign = DAG.getSetCC(dl, OType, Sum, Zero, ISD::SETGE);
2220   SDValue SumSignNE = DAG.getSetCC(dl, OType, LHSSign, SumSign, ISD::SETNE);
2221
2222   SDValue Cmp = DAG.getNode(ISD::AND, dl, OType, SignsMatch, SumSignNE);
2223
2224   // Use the calculated overflow everywhere.
2225   ReplaceValueWith(SDValue(Node, 1), Cmp);
2226 }
2227
2228 void DAGTypeLegalizer::ExpandIntRes_SDIV(SDNode *N,
2229                                          SDValue &Lo, SDValue &Hi) {
2230   EVT VT = N->getValueType(0);
2231   SDLoc dl(N);
2232   SDValue Ops[2] = { N->getOperand(0), N->getOperand(1) };
2233
2234   if (TLI.getOperationAction(ISD::SDIVREM, VT) == TargetLowering::Custom) {
2235     SDValue Res = DAG.getNode(ISD::SDIVREM, dl, DAG.getVTList(VT, VT), Ops);
2236     SplitInteger(Res.getValue(0), Lo, Hi);
2237     return;
2238   }
2239
2240   RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
2241   if (VT == MVT::i16)
2242     LC = RTLIB::SDIV_I16;
2243   else if (VT == MVT::i32)
2244     LC = RTLIB::SDIV_I32;
2245   else if (VT == MVT::i64)
2246     LC = RTLIB::SDIV_I64;
2247   else if (VT == MVT::i128)
2248     LC = RTLIB::SDIV_I128;
2249   assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unsupported SDIV!");
2250
2251   SplitInteger(TLI.makeLibCall(DAG, LC, VT, Ops, true, dl).first, Lo, Hi);
2252 }
2253
2254 void DAGTypeLegalizer::ExpandIntRes_Shift(SDNode *N,
2255                                           SDValue &Lo, SDValue &Hi) {
2256   EVT VT = N->getValueType(0);
2257   SDLoc dl(N);
2258
2259   // If we can emit an efficient shift operation, do so now.  Check to see if
2260   // the RHS is a constant.
2261   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2262     return ExpandShiftByConstant(N, CN->getAPIntValue(), Lo, Hi);
2263
2264   // If we can determine that the high bit of the shift is zero or one, even if
2265   // the low bits are variable, emit this shift in an optimized form.
2266   if (ExpandShiftWithKnownAmountBit(N, Lo, Hi))
2267     return;
2268
2269   // If this target supports shift_PARTS, use it.  First, map to the _PARTS opc.
2270   unsigned PartsOpc;
2271   if (N->getOpcode() == ISD::SHL) {
2272     PartsOpc = ISD::SHL_PARTS;
2273   } else if (N->getOpcode() == ISD::SRL) {
2274     PartsOpc = ISD::SRL_PARTS;
2275   } else {
2276     assert(N->getOpcode() == ISD::SRA && "Unknown shift!");
2277     PartsOpc = ISD::SRA_PARTS;
2278   }
2279
2280   // Next check to see if the target supports this SHL_PARTS operation or if it
2281   // will custom expand it.
2282   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), VT);
2283   TargetLowering::LegalizeAction Action = TLI.getOperationAction(PartsOpc, NVT);
2284   if ((Action == TargetLowering::Legal && TLI.isTypeLegal(NVT)) ||
2285       Action == TargetLowering::Custom) {
2286     // Expand the subcomponents.
2287     SDValue LHSL, LHSH;
2288     GetExpandedInteger(N->getOperand(0), LHSL, LHSH);
2289     EVT VT = LHSL.getValueType();
2290
2291     // If the shift amount operand is coming from a vector legalization it may
2292     // have an illegal type.  Fix that first by casting the operand, otherwise
2293     // the new SHL_PARTS operation would need further legalization.
2294     SDValue ShiftOp = N->getOperand(1);
2295     EVT ShiftTy = TLI.getShiftAmountTy(VT, DAG.getDataLayout());
2296     assert(ShiftTy.getScalarType().getSizeInBits() >=
2297            Log2_32_Ceil(VT.getScalarType().getSizeInBits()) &&
2298            "ShiftAmountTy is too small to cover the range of this type!");
2299     if (ShiftOp.getValueType() != ShiftTy)
2300       ShiftOp = DAG.getZExtOrTrunc(ShiftOp, dl, ShiftTy);
2301
2302     SDValue Ops[] = { LHSL, LHSH, ShiftOp };
2303     Lo = DAG.getNode(PartsOpc, dl, DAG.getVTList(VT, VT), Ops);
2304     Hi = Lo.getValue(1);
2305     return;
2306   }
2307
2308   // Otherwise, emit a libcall.
2309   RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
2310   bool isSigned;
2311   if (N->getOpcode() == ISD::SHL) {
2312     isSigned = false; /*sign irrelevant*/
2313     if (VT == MVT::i16)
2314       LC = RTLIB::SHL_I16;
2315     else if (VT == MVT::i32)
2316       LC = RTLIB::SHL_I32;
2317     else if (VT == MVT::i64)
2318       LC = RTLIB::SHL_I64;
2319     else if (VT == MVT::i128)
2320       LC = RTLIB::SHL_I128;
2321   } else if (N->getOpcode() == ISD::SRL) {
2322     isSigned = false;
2323     if (VT == MVT::i16)
2324       LC = RTLIB::SRL_I16;
2325     else if (VT == MVT::i32)
2326       LC = RTLIB::SRL_I32;
2327     else if (VT == MVT::i64)
2328       LC = RTLIB::SRL_I64;
2329     else if (VT == MVT::i128)
2330       LC = RTLIB::SRL_I128;
2331   } else {
2332     assert(N->getOpcode() == ISD::SRA && "Unknown shift!");
2333     isSigned = true;
2334     if (VT == MVT::i16)
2335       LC = RTLIB::SRA_I16;
2336     else if (VT == MVT::i32)
2337       LC = RTLIB::SRA_I32;
2338     else if (VT == MVT::i64)
2339       LC = RTLIB::SRA_I64;
2340     else if (VT == MVT::i128)
2341       LC = RTLIB::SRA_I128;
2342   }
2343
2344   if (LC != RTLIB::UNKNOWN_LIBCALL && TLI.getLibcallName(LC)) {
2345     SDValue Ops[2] = { N->getOperand(0), N->getOperand(1) };
2346     SplitInteger(TLI.makeLibCall(DAG, LC, VT, Ops, isSigned, dl).first, Lo, Hi);
2347     return;
2348   }
2349
2350   if (!ExpandShiftWithUnknownAmountBit(N, Lo, Hi))
2351     llvm_unreachable("Unsupported shift!");
2352 }
2353
2354 void DAGTypeLegalizer::ExpandIntRes_SIGN_EXTEND(SDNode *N,
2355                                                 SDValue &Lo, SDValue &Hi) {
2356   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
2357   SDLoc dl(N);
2358   SDValue Op = N->getOperand(0);
2359   if (Op.getValueType().bitsLE(NVT)) {
2360     // The low part is sign extension of the input (degenerates to a copy).
2361     Lo = DAG.getNode(ISD::SIGN_EXTEND, dl, NVT, N->getOperand(0));
2362     // The high part is obtained by SRA'ing all but one of the bits of low part.
2363     unsigned LoSize = NVT.getSizeInBits();
2364     Hi = DAG.getNode(
2365         ISD::SRA, dl, NVT, Lo,
2366         DAG.getConstant(LoSize - 1, dl, TLI.getPointerTy(DAG.getDataLayout())));
2367   } else {
2368     // For example, extension of an i48 to an i64.  The operand type necessarily
2369     // promotes to the result type, so will end up being expanded too.
2370     assert(getTypeAction(Op.getValueType()) ==
2371            TargetLowering::TypePromoteInteger &&
2372            "Only know how to promote this result!");
2373     SDValue Res = GetPromotedInteger(Op);
2374     assert(Res.getValueType() == N->getValueType(0) &&
2375            "Operand over promoted?");
2376     // Split the promoted operand.  This will simplify when it is expanded.
2377     SplitInteger(Res, Lo, Hi);
2378     unsigned ExcessBits =
2379       Op.getValueType().getSizeInBits() - NVT.getSizeInBits();
2380     Hi = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, Hi.getValueType(), Hi,
2381                      DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(),
2382                                                         ExcessBits)));
2383   }
2384 }
2385
2386 void DAGTypeLegalizer::
2387 ExpandIntRes_SIGN_EXTEND_INREG(SDNode *N, SDValue &Lo, SDValue &Hi) {
2388   SDLoc dl(N);
2389   GetExpandedInteger(N->getOperand(0), Lo, Hi);
2390   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
2391
2392   if (EVT.bitsLE(Lo.getValueType())) {
2393     // sext_inreg the low part if needed.
2394     Lo = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, Lo.getValueType(), Lo,
2395                      N->getOperand(1));
2396
2397     // The high part gets the sign extension from the lo-part.  This handles
2398     // things like sextinreg V:i64 from i8.
2399     Hi = DAG.getNode(ISD::SRA, dl, Hi.getValueType(), Lo,
2400                      DAG.getConstant(Hi.getValueType().getSizeInBits() - 1, dl,
2401                                      TLI.getPointerTy(DAG.getDataLayout())));
2402   } else {
2403     // For example, extension of an i48 to an i64.  Leave the low part alone,
2404     // sext_inreg the high part.
2405     unsigned ExcessBits =
2406       EVT.getSizeInBits() - Lo.getValueType().getSizeInBits();
2407     Hi = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, Hi.getValueType(), Hi,
2408                      DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(),
2409                                                         ExcessBits)));
2410   }
2411 }
2412
2413 void DAGTypeLegalizer::ExpandIntRes_SREM(SDNode *N,
2414                                          SDValue &Lo, SDValue &Hi) {
2415   EVT VT = N->getValueType(0);
2416   SDLoc dl(N);
2417   SDValue Ops[2] = { N->getOperand(0), N->getOperand(1) };
2418
2419   if (TLI.getOperationAction(ISD::SDIVREM, VT) == TargetLowering::Custom) {
2420     SDValue Res = DAG.getNode(ISD::SDIVREM, dl, DAG.getVTList(VT, VT), Ops);
2421     SplitInteger(Res.getValue(1), Lo, Hi);
2422     return;
2423   }
2424
2425   RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
2426   if (VT == MVT::i16)
2427     LC = RTLIB::SREM_I16;
2428   else if (VT == MVT::i32)
2429     LC = RTLIB::SREM_I32;
2430   else if (VT == MVT::i64)
2431     LC = RTLIB::SREM_I64;
2432   else if (VT == MVT::i128)
2433     LC = RTLIB::SREM_I128;
2434   assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unsupported SREM!");
2435
2436   SplitInteger(TLI.makeLibCall(DAG, LC, VT, Ops, true, dl).first, Lo, Hi);
2437 }
2438
2439 void DAGTypeLegalizer::ExpandIntRes_TRUNCATE(SDNode *N,
2440                                              SDValue &Lo, SDValue &Hi) {
2441   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
2442   SDLoc dl(N);
2443   Lo = DAG.getNode(ISD::TRUNCATE, dl, NVT, N->getOperand(0));
2444   Hi = DAG.getNode(ISD::SRL, dl, N->getOperand(0).getValueType(),
2445                    N->getOperand(0),
2446                    DAG.getConstant(NVT.getSizeInBits(), dl,
2447                                    TLI.getPointerTy(DAG.getDataLayout())));
2448   Hi = DAG.getNode(ISD::TRUNCATE, dl, NVT, Hi);
2449 }
2450
2451 void DAGTypeLegalizer::ExpandIntRes_UADDSUBO(SDNode *N,
2452                                              SDValue &Lo, SDValue &Hi) {
2453   SDValue LHS = N->getOperand(0);
2454   SDValue RHS = N->getOperand(1);
2455   SDLoc dl(N);
2456
2457   // Expand the result by simply replacing it with the equivalent
2458   // non-overflow-checking operation.
2459   SDValue Sum = DAG.getNode(N->getOpcode() == ISD::UADDO ?
2460                             ISD::ADD : ISD::SUB, dl, LHS.getValueType(),
2461                             LHS, RHS);
2462   SplitInteger(Sum, Lo, Hi);
2463
2464   // Calculate the overflow: addition overflows iff a + b < a, and subtraction
2465   // overflows iff a - b > a.
2466   SDValue Ofl = DAG.getSetCC(dl, N->getValueType(1), Sum, LHS,
2467                              N->getOpcode () == ISD::UADDO ?
2468                              ISD::SETULT : ISD::SETUGT);
2469
2470   // Use the calculated overflow everywhere.
2471   ReplaceValueWith(SDValue(N, 1), Ofl);
2472 }
2473
2474 void DAGTypeLegalizer::ExpandIntRes_XMULO(SDNode *N,
2475                                           SDValue &Lo, SDValue &Hi) {
2476   EVT VT = N->getValueType(0);
2477   SDLoc dl(N);
2478
2479   // A divide for UMULO should be faster than a function call.
2480   if (N->getOpcode() == ISD::UMULO) {
2481     SDValue LHS = N->getOperand(0), RHS = N->getOperand(1);
2482
2483     SDValue MUL = DAG.getNode(ISD::MUL, dl, LHS.getValueType(), LHS, RHS);
2484     SplitInteger(MUL, Lo, Hi);
2485
2486     // A divide for UMULO will be faster than a function call. Select to
2487     // make sure we aren't using 0.
2488     SDValue isZero = DAG.getSetCC(dl, getSetCCResultType(VT),
2489                                   RHS, DAG.getConstant(0, dl, VT), ISD::SETEQ);
2490     SDValue NotZero = DAG.getSelect(dl, VT, isZero,
2491                                     DAG.getConstant(1, dl, VT), RHS);
2492     SDValue DIV = DAG.getNode(ISD::UDIV, dl, VT, MUL, NotZero);
2493     SDValue Overflow = DAG.getSetCC(dl, N->getValueType(1), DIV, LHS,
2494                                     ISD::SETNE);
2495     Overflow = DAG.getSelect(dl, N->getValueType(1), isZero,
2496                              DAG.getConstant(0, dl, N->getValueType(1)),
2497                              Overflow);
2498     ReplaceValueWith(SDValue(N, 1), Overflow);
2499     return;
2500   }
2501
2502   Type *RetTy = VT.getTypeForEVT(*DAG.getContext());
2503   EVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
2504   Type *PtrTy = PtrVT.getTypeForEVT(*DAG.getContext());
2505
2506   // Replace this with a libcall that will check overflow.
2507   RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
2508   if (VT == MVT::i32)
2509     LC = RTLIB::MULO_I32;
2510   else if (VT == MVT::i64)
2511     LC = RTLIB::MULO_I64;
2512   else if (VT == MVT::i128)
2513     LC = RTLIB::MULO_I128;
2514   assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unsupported XMULO!");
2515
2516   SDValue Temp = DAG.CreateStackTemporary(PtrVT);
2517   // Temporary for the overflow value, default it to zero.
2518   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl,
2519                                DAG.getConstant(0, dl, PtrVT), Temp,
2520                                MachinePointerInfo(), false, false, 0);
2521
2522   TargetLowering::ArgListTy Args;
2523   TargetLowering::ArgListEntry Entry;
2524   for (const SDValue &Op : N->op_values()) {
2525     EVT ArgVT = Op.getValueType();
2526     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
2527     Entry.Node = Op;
2528     Entry.Ty = ArgTy;
2529     Entry.isSExt = true;
2530     Entry.isZExt = false;
2531     Args.push_back(Entry);
2532   }
2533
2534   // Also pass the address of the overflow check.
2535   Entry.Node = Temp;
2536   Entry.Ty = PtrTy->getPointerTo();
2537   Entry.isSExt = true;
2538   Entry.isZExt = false;
2539   Args.push_back(Entry);
2540
2541   SDValue Func = DAG.getExternalSymbol(TLI.getLibcallName(LC), PtrVT);
2542
2543   TargetLowering::CallLoweringInfo CLI(DAG);
2544   CLI.setDebugLoc(dl).setChain(Chain)
2545     .setCallee(TLI.getLibcallCallingConv(LC), RetTy, Func, std::move(Args), 0)
2546     .setSExtResult();
2547
2548   std::pair<SDValue, SDValue> CallInfo = TLI.LowerCallTo(CLI);
2549
2550   SplitInteger(CallInfo.first, Lo, Hi);
2551   SDValue Temp2 = DAG.getLoad(PtrVT, dl, CallInfo.second, Temp,
2552                               MachinePointerInfo(), false, false, false, 0);
2553   SDValue Ofl = DAG.getSetCC(dl, N->getValueType(1), Temp2,
2554                              DAG.getConstant(0, dl, PtrVT),
2555                              ISD::SETNE);
2556   // Use the overflow from the libcall everywhere.
2557   ReplaceValueWith(SDValue(N, 1), Ofl);
2558 }
2559
2560 void DAGTypeLegalizer::ExpandIntRes_UDIV(SDNode *N,
2561                                          SDValue &Lo, SDValue &Hi) {
2562   EVT VT = N->getValueType(0);
2563   SDLoc dl(N);
2564   SDValue Ops[2] = { N->getOperand(0), N->getOperand(1) };
2565
2566   if (TLI.getOperationAction(ISD::UDIVREM, VT) == TargetLowering::Custom) {
2567     SDValue Res = DAG.getNode(ISD::UDIVREM, dl, DAG.getVTList(VT, VT), Ops);
2568     SplitInteger(Res.getValue(0), Lo, Hi);
2569     return;
2570   }
2571
2572   RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
2573   if (VT == MVT::i16)
2574     LC = RTLIB::UDIV_I16;
2575   else if (VT == MVT::i32)
2576     LC = RTLIB::UDIV_I32;
2577   else if (VT == MVT::i64)
2578     LC = RTLIB::UDIV_I64;
2579   else if (VT == MVT::i128)
2580     LC = RTLIB::UDIV_I128;
2581   assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unsupported UDIV!");
2582
2583   SplitInteger(TLI.makeLibCall(DAG, LC, VT, Ops, false, dl).first, Lo, Hi);
2584 }
2585
2586 void DAGTypeLegalizer::ExpandIntRes_UREM(SDNode *N,
2587                                          SDValue &Lo, SDValue &Hi) {
2588   EVT VT = N->getValueType(0);
2589   SDLoc dl(N);
2590   SDValue Ops[2] = { N->getOperand(0), N->getOperand(1) };
2591
2592   if (TLI.getOperationAction(ISD::UDIVREM, VT) == TargetLowering::Custom) {
2593     SDValue Res = DAG.getNode(ISD::UDIVREM, dl, DAG.getVTList(VT, VT), Ops);
2594     SplitInteger(Res.getValue(1), Lo, Hi);
2595     return;
2596   }
2597
2598   RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
2599   if (VT == MVT::i16)
2600     LC = RTLIB::UREM_I16;
2601   else if (VT == MVT::i32)
2602     LC = RTLIB::UREM_I32;
2603   else if (VT == MVT::i64)
2604     LC = RTLIB::UREM_I64;
2605   else if (VT == MVT::i128)
2606     LC = RTLIB::UREM_I128;
2607   assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unsupported UREM!");
2608
2609   SplitInteger(TLI.makeLibCall(DAG, LC, VT, Ops, false, dl).first, Lo, Hi);
2610 }
2611
2612 void DAGTypeLegalizer::ExpandIntRes_ZERO_EXTEND(SDNode *N,
2613                                                 SDValue &Lo, SDValue &Hi) {
2614   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
2615   SDLoc dl(N);
2616   SDValue Op = N->getOperand(0);
2617   if (Op.getValueType().bitsLE(NVT)) {
2618     // The low part is zero extension of the input (degenerates to a copy).
2619     Lo = DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N->getOperand(0));
2620     Hi = DAG.getConstant(0, dl, NVT);   // The high part is just a zero.
2621   } else {
2622     // For example, extension of an i48 to an i64.  The operand type necessarily
2623     // promotes to the result type, so will end up being expanded too.
2624     assert(getTypeAction(Op.getValueType()) ==
2625            TargetLowering::TypePromoteInteger &&
2626            "Only know how to promote this result!");
2627     SDValue Res = GetPromotedInteger(Op);
2628     assert(Res.getValueType() == N->getValueType(0) &&
2629            "Operand over promoted?");
2630     // Split the promoted operand.  This will simplify when it is expanded.
2631     SplitInteger(Res, Lo, Hi);
2632     unsigned ExcessBits =
2633       Op.getValueType().getSizeInBits() - NVT.getSizeInBits();
2634     Hi = DAG.getZeroExtendInReg(Hi, dl,
2635                                 EVT::getIntegerVT(*DAG.getContext(),
2636                                                   ExcessBits));
2637   }
2638 }
2639
2640 void DAGTypeLegalizer::ExpandIntRes_ATOMIC_LOAD(SDNode *N,
2641                                                 SDValue &Lo, SDValue &Hi) {
2642   SDLoc dl(N);
2643   EVT VT = cast<AtomicSDNode>(N)->getMemoryVT();
2644   SDVTList VTs = DAG.getVTList(VT, MVT::i1, MVT::Other);
2645   SDValue Zero = DAG.getConstant(0, dl, VT);
2646   SDValue Swap = DAG.getAtomicCmpSwap(
2647       ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, dl,
2648       cast<AtomicSDNode>(N)->getMemoryVT(), VTs, N->getOperand(0),
2649       N->getOperand(1), Zero, Zero, cast<AtomicSDNode>(N)->getMemOperand(),
2650       cast<AtomicSDNode>(N)->getOrdering(),
2651       cast<AtomicSDNode>(N)->getOrdering(),
2652       cast<AtomicSDNode>(N)->getSynchScope());
2653
2654   ReplaceValueWith(SDValue(N, 0), Swap.getValue(0));
2655   ReplaceValueWith(SDValue(N, 1), Swap.getValue(2));
2656 }
2657
2658 //===----------------------------------------------------------------------===//
2659 //  Integer Operand Expansion
2660 //===----------------------------------------------------------------------===//
2661
2662 /// ExpandIntegerOperand - This method is called when the specified operand of
2663 /// the specified node is found to need expansion.  At this point, all of the
2664 /// result types of the node are known to be legal, but other operands of the
2665 /// node may need promotion or expansion as well as the specified one.
2666 bool DAGTypeLegalizer::ExpandIntegerOperand(SDNode *N, unsigned OpNo) {
2667   DEBUG(dbgs() << "Expand integer operand: "; N->dump(&DAG); dbgs() << "\n");
2668   SDValue Res = SDValue();
2669
2670   if (CustomLowerNode(N, N->getOperand(OpNo).getValueType(), false))
2671     return false;
2672
2673   switch (N->getOpcode()) {
2674   default:
2675   #ifndef NDEBUG
2676     dbgs() << "ExpandIntegerOperand Op #" << OpNo << ": ";
2677     N->dump(&DAG); dbgs() << "\n";
2678   #endif
2679     llvm_unreachable("Do not know how to expand this operator's operand!");
2680
2681   case ISD::BITCAST:           Res = ExpandOp_BITCAST(N); break;
2682   case ISD::BR_CC:             Res = ExpandIntOp_BR_CC(N); break;
2683   case ISD::BUILD_VECTOR:      Res = ExpandOp_BUILD_VECTOR(N); break;
2684   case ISD::EXTRACT_ELEMENT:   Res = ExpandOp_EXTRACT_ELEMENT(N); break;
2685   case ISD::INSERT_VECTOR_ELT: Res = ExpandOp_INSERT_VECTOR_ELT(N); break;
2686   case ISD::SCALAR_TO_VECTOR:  Res = ExpandOp_SCALAR_TO_VECTOR(N); break;
2687   case ISD::SELECT_CC:         Res = ExpandIntOp_SELECT_CC(N); break;
2688   case ISD::SETCC:             Res = ExpandIntOp_SETCC(N); break;
2689   case ISD::SETCCE:            Res = ExpandIntOp_SETCCE(N); break;
2690   case ISD::SINT_TO_FP:        Res = ExpandIntOp_SINT_TO_FP(N); break;
2691   case ISD::STORE:   Res = ExpandIntOp_STORE(cast<StoreSDNode>(N), OpNo); break;
2692   case ISD::TRUNCATE:          Res = ExpandIntOp_TRUNCATE(N); break;
2693   case ISD::UINT_TO_FP:        Res = ExpandIntOp_UINT_TO_FP(N); break;
2694
2695   case ISD::SHL:
2696   case ISD::SRA:
2697   case ISD::SRL:
2698   case ISD::ROTL:
2699   case ISD::ROTR:              Res = ExpandIntOp_Shift(N); break;
2700   case ISD::RETURNADDR:
2701   case ISD::FRAMEADDR:         Res = ExpandIntOp_RETURNADDR(N); break;
2702
2703   case ISD::ATOMIC_STORE:      Res = ExpandIntOp_ATOMIC_STORE(N); break;
2704   }
2705
2706   // If the result is null, the sub-method took care of registering results etc.
2707   if (!Res.getNode()) return false;
2708
2709   // If the result is N, the sub-method updated N in place.  Tell the legalizer
2710   // core about this.
2711   if (Res.getNode() == N)
2712     return true;
2713
2714   assert(Res.getValueType() == N->getValueType(0) && N->getNumValues() == 1 &&
2715          "Invalid operand expansion");
2716
2717   ReplaceValueWith(SDValue(N, 0), Res);
2718   return false;
2719 }
2720
2721 /// IntegerExpandSetCCOperands - Expand the operands of a comparison.  This code
2722 /// is shared among BR_CC, SELECT_CC, and SETCC handlers.
2723 void DAGTypeLegalizer::IntegerExpandSetCCOperands(SDValue &NewLHS,
2724                                                   SDValue &NewRHS,
2725                                                   ISD::CondCode &CCCode,
2726                                                   SDLoc dl) {
2727   SDValue LHSLo, LHSHi, RHSLo, RHSHi;
2728   GetExpandedInteger(NewLHS, LHSLo, LHSHi);
2729   GetExpandedInteger(NewRHS, RHSLo, RHSHi);
2730
2731   if (CCCode == ISD::SETEQ || CCCode == ISD::SETNE) {
2732     if (RHSLo == RHSHi) {
2733       if (ConstantSDNode *RHSCST = dyn_cast<ConstantSDNode>(RHSLo)) {
2734         if (RHSCST->isAllOnesValue()) {
2735           // Equality comparison to -1.
2736           NewLHS = DAG.getNode(ISD::AND, dl,
2737                                LHSLo.getValueType(), LHSLo, LHSHi);
2738           NewRHS = RHSLo;
2739           return;
2740         }
2741       }
2742     }
2743
2744     NewLHS = DAG.getNode(ISD::XOR, dl, LHSLo.getValueType(), LHSLo, RHSLo);
2745     NewRHS = DAG.getNode(ISD::XOR, dl, LHSLo.getValueType(), LHSHi, RHSHi);
2746     NewLHS = DAG.getNode(ISD::OR, dl, NewLHS.getValueType(), NewLHS, NewRHS);
2747     NewRHS = DAG.getConstant(0, dl, NewLHS.getValueType());
2748     return;
2749   }
2750
2751   // If this is a comparison of the sign bit, just look at the top part.
2752   // X > -1,  x < 0
2753   if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(NewRHS))
2754     if ((CCCode == ISD::SETLT && CST->isNullValue()) ||     // X < 0
2755         (CCCode == ISD::SETGT && CST->isAllOnesValue())) {  // X > -1
2756       NewLHS = LHSHi;
2757       NewRHS = RHSHi;
2758       return;
2759     }
2760
2761   // FIXME: This generated code sucks.
2762   ISD::CondCode LowCC;
2763   switch (CCCode) {
2764   default: llvm_unreachable("Unknown integer setcc!");
2765   case ISD::SETLT:
2766   case ISD::SETULT: LowCC = ISD::SETULT; break;
2767   case ISD::SETGT:
2768   case ISD::SETUGT: LowCC = ISD::SETUGT; break;
2769   case ISD::SETLE:
2770   case ISD::SETULE: LowCC = ISD::SETULE; break;
2771   case ISD::SETGE:
2772   case ISD::SETUGE: LowCC = ISD::SETUGE; break;
2773   }
2774
2775   // Tmp1 = lo(op1) < lo(op2)   // Always unsigned comparison
2776   // Tmp2 = hi(op1) < hi(op2)   // Signedness depends on operands
2777   // dest = hi(op1) == hi(op2) ? Tmp1 : Tmp2;
2778
2779   // NOTE: on targets without efficient SELECT of bools, we can always use
2780   // this identity: (B1 ? B2 : B3) --> (B1 & B2)|(!B1&B3)
2781   TargetLowering::DAGCombinerInfo DagCombineInfo(DAG, AfterLegalizeTypes, true,
2782                                                  nullptr);
2783   SDValue Tmp1, Tmp2;
2784   if (TLI.isTypeLegal(LHSLo.getValueType()) &&
2785       TLI.isTypeLegal(RHSLo.getValueType()))
2786     Tmp1 = TLI.SimplifySetCC(getSetCCResultType(LHSLo.getValueType()),
2787                              LHSLo, RHSLo, LowCC, false, DagCombineInfo, dl);
2788   if (!Tmp1.getNode())
2789     Tmp1 = DAG.getSetCC(dl, getSetCCResultType(LHSLo.getValueType()),
2790                         LHSLo, RHSLo, LowCC);
2791   if (TLI.isTypeLegal(LHSHi.getValueType()) &&
2792       TLI.isTypeLegal(RHSHi.getValueType()))
2793     Tmp2 = TLI.SimplifySetCC(getSetCCResultType(LHSHi.getValueType()),
2794                              LHSHi, RHSHi, CCCode, false, DagCombineInfo, dl);
2795   if (!Tmp2.getNode())
2796     Tmp2 = DAG.getNode(ISD::SETCC, dl,
2797                        getSetCCResultType(LHSHi.getValueType()),
2798                        LHSHi, RHSHi, DAG.getCondCode(CCCode));
2799
2800   ConstantSDNode *Tmp1C = dyn_cast<ConstantSDNode>(Tmp1.getNode());
2801   ConstantSDNode *Tmp2C = dyn_cast<ConstantSDNode>(Tmp2.getNode());
2802   if ((Tmp1C && Tmp1C->isNullValue()) ||
2803       (Tmp2C && Tmp2C->isNullValue() &&
2804        (CCCode == ISD::SETLE || CCCode == ISD::SETGE ||
2805         CCCode == ISD::SETUGE || CCCode == ISD::SETULE)) ||
2806       (Tmp2C && Tmp2C->getAPIntValue() == 1 &&
2807        (CCCode == ISD::SETLT || CCCode == ISD::SETGT ||
2808         CCCode == ISD::SETUGT || CCCode == ISD::SETULT))) {
2809     // low part is known false, returns high part.
2810     // For LE / GE, if high part is known false, ignore the low part.
2811     // For LT / GT, if high part is known true, ignore the low part.
2812     NewLHS = Tmp2;
2813     NewRHS = SDValue();
2814     return;
2815   }
2816
2817   if (LHSHi == RHSHi) {
2818     // Comparing the low bits is enough.
2819     NewLHS = Tmp1;
2820     NewRHS = SDValue();
2821     return;
2822   }
2823
2824   // Lower with SETCCE if the target supports it.
2825   // FIXME: Make all targets support this, then remove the other lowering.
2826   if (TLI.getOperationAction(
2827           ISD::SETCCE,
2828           TLI.getTypeToExpandTo(*DAG.getContext(), LHSLo.getValueType())) ==
2829       TargetLowering::Custom) {
2830     // SETCCE can detect < and >= directly. For > and <=, flip operands and
2831     // condition code.
2832     bool FlipOperands = false;
2833     switch (CCCode) {
2834     case ISD::SETGT:  CCCode = ISD::SETLT;  FlipOperands = true; break;
2835     case ISD::SETUGT: CCCode = ISD::SETULT; FlipOperands = true; break;
2836     case ISD::SETLE:  CCCode = ISD::SETGE;  FlipOperands = true; break;
2837     case ISD::SETULE: CCCode = ISD::SETUGE; FlipOperands = true; break;
2838     default: break;
2839     }
2840     if (FlipOperands) {
2841       std::swap(LHSLo, RHSLo);
2842       std::swap(LHSHi, RHSHi);
2843     }
2844     // Perform a wide subtraction, feeding the carry from the low part into
2845     // SETCCE. The SETCCE operation is essentially looking at the high part of
2846     // the result of LHS - RHS. It is negative iff LHS < RHS. It is zero or
2847     // positive iff LHS >= RHS.
2848     SDVTList VTList = DAG.getVTList(LHSLo.getValueType(), MVT::Glue);
2849     SDValue LowCmp = DAG.getNode(ISD::SUBC, dl, VTList, LHSLo, RHSLo);
2850     SDValue Res =
2851         DAG.getNode(ISD::SETCCE, dl, getSetCCResultType(LHSLo.getValueType()),
2852                     LHSHi, RHSHi, LowCmp.getValue(1), DAG.getCondCode(CCCode));
2853     NewLHS = Res;
2854     NewRHS = SDValue();
2855     return;
2856   }
2857
2858   NewLHS = TLI.SimplifySetCC(getSetCCResultType(LHSHi.getValueType()),
2859                              LHSHi, RHSHi, ISD::SETEQ, false,
2860                              DagCombineInfo, dl);
2861   if (!NewLHS.getNode())
2862     NewLHS = DAG.getSetCC(dl, getSetCCResultType(LHSHi.getValueType()),
2863                           LHSHi, RHSHi, ISD::SETEQ);
2864   NewLHS = DAG.getSelect(dl, Tmp1.getValueType(),
2865                          NewLHS, Tmp1, Tmp2);
2866   NewRHS = SDValue();
2867 }
2868
2869 SDValue DAGTypeLegalizer::ExpandIntOp_BR_CC(SDNode *N) {
2870   SDValue NewLHS = N->getOperand(2), NewRHS = N->getOperand(3);
2871   ISD::CondCode CCCode = cast<CondCodeSDNode>(N->getOperand(1))->get();
2872   IntegerExpandSetCCOperands(NewLHS, NewRHS, CCCode, SDLoc(N));
2873
2874   // If ExpandSetCCOperands returned a scalar, we need to compare the result
2875   // against zero to select between true and false values.
2876   if (!NewRHS.getNode()) {
2877     NewRHS = DAG.getConstant(0, SDLoc(N), NewLHS.getValueType());
2878     CCCode = ISD::SETNE;
2879   }
2880
2881   // Update N to have the operands specified.
2882   return SDValue(DAG.UpdateNodeOperands(N, N->getOperand(0),
2883                                 DAG.getCondCode(CCCode), NewLHS, NewRHS,
2884                                 N->getOperand(4)), 0);
2885 }
2886
2887 SDValue DAGTypeLegalizer::ExpandIntOp_SELECT_CC(SDNode *N) {
2888   SDValue NewLHS = N->getOperand(0), NewRHS = N->getOperand(1);
2889   ISD::CondCode CCCode = cast<CondCodeSDNode>(N->getOperand(4))->get();
2890   IntegerExpandSetCCOperands(NewLHS, NewRHS, CCCode, SDLoc(N));
2891
2892   // If ExpandSetCCOperands returned a scalar, we need to compare the result
2893   // against zero to select between true and false values.
2894   if (!NewRHS.getNode()) {
2895     NewRHS = DAG.getConstant(0, SDLoc(N), NewLHS.getValueType());
2896     CCCode = ISD::SETNE;
2897   }
2898
2899   // Update N to have the operands specified.
2900   return SDValue(DAG.UpdateNodeOperands(N, NewLHS, NewRHS,
2901                                 N->getOperand(2), N->getOperand(3),
2902                                 DAG.getCondCode(CCCode)), 0);
2903 }
2904
2905 SDValue DAGTypeLegalizer::ExpandIntOp_SETCC(SDNode *N) {
2906   SDValue NewLHS = N->getOperand(0), NewRHS = N->getOperand(1);
2907   ISD::CondCode CCCode = cast<CondCodeSDNode>(N->getOperand(2))->get();
2908   IntegerExpandSetCCOperands(NewLHS, NewRHS, CCCode, SDLoc(N));
2909
2910   // If ExpandSetCCOperands returned a scalar, use it.
2911   if (!NewRHS.getNode()) {
2912     assert(NewLHS.getValueType() == N->getValueType(0) &&
2913            "Unexpected setcc expansion!");
2914     return NewLHS;
2915   }
2916
2917   // Otherwise, update N to have the operands specified.
2918   return SDValue(DAG.UpdateNodeOperands(N, NewLHS, NewRHS,
2919                                 DAG.getCondCode(CCCode)), 0);
2920 }
2921
2922 SDValue DAGTypeLegalizer::ExpandIntOp_SETCCE(SDNode *N) {
2923   SDValue LHS = N->getOperand(0);
2924   SDValue RHS = N->getOperand(1);
2925   SDValue Carry = N->getOperand(2);
2926   SDValue Cond = N->getOperand(3);
2927   SDLoc dl = SDLoc(N);
2928
2929   SDValue LHSLo, LHSHi, RHSLo, RHSHi;
2930   GetExpandedInteger(LHS, LHSLo, LHSHi);
2931   GetExpandedInteger(RHS, RHSLo, RHSHi);
2932
2933   // Expand to a SUBE for the low part and a smaller SETCCE for the high.
2934   SDVTList VTList = DAG.getVTList(LHSLo.getValueType(), MVT::Glue);
2935   SDValue LowCmp = DAG.getNode(ISD::SUBE, dl, VTList, LHSLo, RHSLo, Carry);
2936   return DAG.getNode(ISD::SETCCE, dl, N->getValueType(0), LHSHi, RHSHi,
2937                      LowCmp.getValue(1), Cond);
2938 }
2939
2940 SDValue DAGTypeLegalizer::ExpandIntOp_Shift(SDNode *N) {
2941   // The value being shifted is legal, but the shift amount is too big.
2942   // It follows that either the result of the shift is undefined, or the
2943   // upper half of the shift amount is zero.  Just use the lower half.
2944   SDValue Lo, Hi;
2945   GetExpandedInteger(N->getOperand(1), Lo, Hi);
2946   return SDValue(DAG.UpdateNodeOperands(N, N->getOperand(0), Lo), 0);
2947 }
2948
2949 SDValue DAGTypeLegalizer::ExpandIntOp_RETURNADDR(SDNode *N) {
2950   // The argument of RETURNADDR / FRAMEADDR builtin is 32 bit contant.  This
2951   // surely makes pretty nice problems on 8/16 bit targets. Just truncate this
2952   // constant to valid type.
2953   SDValue Lo, Hi;
2954   GetExpandedInteger(N->getOperand(0), Lo, Hi);
2955   return SDValue(DAG.UpdateNodeOperands(N, Lo), 0);
2956 }
2957
2958 SDValue DAGTypeLegalizer::ExpandIntOp_SINT_TO_FP(SDNode *N) {
2959   SDValue Op = N->getOperand(0);
2960   EVT DstVT = N->getValueType(0);
2961   RTLIB::Libcall LC = RTLIB::getSINTTOFP(Op.getValueType(), DstVT);
2962   assert(LC != RTLIB::UNKNOWN_LIBCALL &&
2963          "Don't know how to expand this SINT_TO_FP!");
2964   return TLI.makeLibCall(DAG, LC, DstVT, Op, true, SDLoc(N)).first;
2965 }
2966
2967 SDValue DAGTypeLegalizer::ExpandIntOp_STORE(StoreSDNode *N, unsigned OpNo) {
2968   if (ISD::isNormalStore(N))
2969     return ExpandOp_NormalStore(N, OpNo);
2970
2971   assert(ISD::isUNINDEXEDStore(N) && "Indexed store during type legalization!");
2972   assert(OpNo == 1 && "Can only expand the stored value so far");
2973
2974   EVT VT = N->getOperand(1).getValueType();
2975   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), VT);
2976   SDValue Ch  = N->getChain();
2977   SDValue Ptr = N->getBasePtr();
2978   unsigned Alignment = N->getAlignment();
2979   bool isVolatile = N->isVolatile();
2980   bool isNonTemporal = N->isNonTemporal();
2981   AAMDNodes AAInfo = N->getAAInfo();
2982   SDLoc dl(N);
2983   SDValue Lo, Hi;
2984
2985   assert(NVT.isByteSized() && "Expanded type not byte sized!");
2986
2987   if (N->getMemoryVT().bitsLE(NVT)) {
2988     GetExpandedInteger(N->getValue(), Lo, Hi);
2989     return DAG.getTruncStore(Ch, dl, Lo, Ptr, N->getPointerInfo(),
2990                              N->getMemoryVT(), isVolatile, isNonTemporal,
2991                              Alignment, AAInfo);
2992   }
2993
2994   if (DAG.getDataLayout().isLittleEndian()) {
2995     // Little-endian - low bits are at low addresses.
2996     GetExpandedInteger(N->getValue(), Lo, Hi);
2997
2998     Lo = DAG.getStore(Ch, dl, Lo, Ptr, N->getPointerInfo(),
2999                       isVolatile, isNonTemporal, Alignment, AAInfo);
3000
3001     unsigned ExcessBits =
3002       N->getMemoryVT().getSizeInBits() - NVT.getSizeInBits();
3003     EVT NEVT = EVT::getIntegerVT(*DAG.getContext(), ExcessBits);
3004
3005     // Increment the pointer to the other half.
3006     unsigned IncrementSize = NVT.getSizeInBits()/8;
3007     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
3008                       DAG.getConstant(IncrementSize, dl, Ptr.getValueType()));
3009     Hi = DAG.getTruncStore(Ch, dl, Hi, Ptr,
3010                            N->getPointerInfo().getWithOffset(IncrementSize),
3011                            NEVT, isVolatile, isNonTemporal,
3012                            MinAlign(Alignment, IncrementSize), AAInfo);
3013     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo, Hi);
3014   }
3015
3016   // Big-endian - high bits are at low addresses.  Favor aligned stores at
3017   // the cost of some bit-fiddling.
3018   GetExpandedInteger(N->getValue(), Lo, Hi);
3019
3020   EVT ExtVT = N->getMemoryVT();
3021   unsigned EBytes = ExtVT.getStoreSize();
3022   unsigned IncrementSize = NVT.getSizeInBits()/8;
3023   unsigned ExcessBits = (EBytes - IncrementSize)*8;
3024   EVT HiVT = EVT::getIntegerVT(*DAG.getContext(),
3025                                ExtVT.getSizeInBits() - ExcessBits);
3026
3027   if (ExcessBits < NVT.getSizeInBits()) {
3028     // Transfer high bits from the top of Lo to the bottom of Hi.
3029     Hi = DAG.getNode(ISD::SHL, dl, NVT, Hi,
3030                      DAG.getConstant(NVT.getSizeInBits() - ExcessBits, dl,
3031                                      TLI.getPointerTy(DAG.getDataLayout())));
3032     Hi = DAG.getNode(
3033         ISD::OR, dl, NVT, Hi,
3034         DAG.getNode(ISD::SRL, dl, NVT, Lo,
3035                     DAG.getConstant(ExcessBits, dl,
3036                                     TLI.getPointerTy(DAG.getDataLayout()))));
3037   }
3038
3039   // Store both the high bits and maybe some of the low bits.
3040   Hi = DAG.getTruncStore(Ch, dl, Hi, Ptr, N->getPointerInfo(),
3041                          HiVT, isVolatile, isNonTemporal, Alignment, AAInfo);
3042
3043   // Increment the pointer to the other half.
3044   Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
3045                     DAG.getConstant(IncrementSize, dl, Ptr.getValueType()));
3046   // Store the lowest ExcessBits bits in the second half.
3047   Lo = DAG.getTruncStore(Ch, dl, Lo, Ptr,
3048                          N->getPointerInfo().getWithOffset(IncrementSize),
3049                          EVT::getIntegerVT(*DAG.getContext(), ExcessBits),
3050                          isVolatile, isNonTemporal,
3051                          MinAlign(Alignment, IncrementSize), AAInfo);
3052   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo, Hi);
3053 }
3054
3055 SDValue DAGTypeLegalizer::ExpandIntOp_TRUNCATE(SDNode *N) {
3056   SDValue InL, InH;
3057   GetExpandedInteger(N->getOperand(0), InL, InH);
3058   // Just truncate the low part of the source.
3059   return DAG.getNode(ISD::TRUNCATE, SDLoc(N), N->getValueType(0), InL);
3060 }
3061
3062 SDValue DAGTypeLegalizer::ExpandIntOp_UINT_TO_FP(SDNode *N) {
3063   SDValue Op = N->getOperand(0);
3064   EVT SrcVT = Op.getValueType();
3065   EVT DstVT = N->getValueType(0);
3066   SDLoc dl(N);
3067
3068   // The following optimization is valid only if every value in SrcVT (when
3069   // treated as signed) is representable in DstVT.  Check that the mantissa
3070   // size of DstVT is >= than the number of bits in SrcVT -1.
3071   const fltSemantics &sem = DAG.EVTToAPFloatSemantics(DstVT);
3072   if (APFloat::semanticsPrecision(sem) >= SrcVT.getSizeInBits()-1 &&
3073       TLI.getOperationAction(ISD::SINT_TO_FP, SrcVT) == TargetLowering::Custom){
3074     // Do a signed conversion then adjust the result.
3075     SDValue SignedConv = DAG.getNode(ISD::SINT_TO_FP, dl, DstVT, Op);
3076     SignedConv = TLI.LowerOperation(SignedConv, DAG);
3077
3078     // The result of the signed conversion needs adjusting if the 'sign bit' of
3079     // the incoming integer was set.  To handle this, we dynamically test to see
3080     // if it is set, and, if so, add a fudge factor.
3081
3082     const uint64_t F32TwoE32  = 0x4F800000ULL;
3083     const uint64_t F32TwoE64  = 0x5F800000ULL;
3084     const uint64_t F32TwoE128 = 0x7F800000ULL;
3085
3086     APInt FF(32, 0);
3087     if (SrcVT == MVT::i32)
3088       FF = APInt(32, F32TwoE32);
3089     else if (SrcVT == MVT::i64)
3090       FF = APInt(32, F32TwoE64);
3091     else if (SrcVT == MVT::i128)
3092       FF = APInt(32, F32TwoE128);
3093     else
3094       llvm_unreachable("Unsupported UINT_TO_FP!");
3095
3096     // Check whether the sign bit is set.
3097     SDValue Lo, Hi;
3098     GetExpandedInteger(Op, Lo, Hi);
3099     SDValue SignSet = DAG.getSetCC(dl,
3100                                    getSetCCResultType(Hi.getValueType()),
3101                                    Hi,
3102                                    DAG.getConstant(0, dl, Hi.getValueType()),
3103                                    ISD::SETLT);
3104
3105     // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
3106     SDValue FudgePtr =
3107         DAG.getConstantPool(ConstantInt::get(*DAG.getContext(), FF.zext(64)),
3108                             TLI.getPointerTy(DAG.getDataLayout()));
3109
3110     // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
3111     SDValue Zero = DAG.getIntPtrConstant(0, dl);
3112     SDValue Four = DAG.getIntPtrConstant(4, dl);
3113     if (DAG.getDataLayout().isBigEndian())
3114       std::swap(Zero, Four);
3115     SDValue Offset = DAG.getSelect(dl, Zero.getValueType(), SignSet,
3116                                    Zero, Four);
3117     unsigned Alignment = cast<ConstantPoolSDNode>(FudgePtr)->getAlignment();
3118     FudgePtr = DAG.getNode(ISD::ADD, dl, FudgePtr.getValueType(),
3119                            FudgePtr, Offset);
3120     Alignment = std::min(Alignment, 4u);
3121
3122     // Load the value out, extending it from f32 to the destination float type.
3123     // FIXME: Avoid the extend by constructing the right constant pool?
3124     SDValue Fudge = DAG.getExtLoad(
3125         ISD::EXTLOAD, dl, DstVT, DAG.getEntryNode(), FudgePtr,
3126         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), MVT::f32,
3127         false, false, false, Alignment);
3128     return DAG.getNode(ISD::FADD, dl, DstVT, SignedConv, Fudge);
3129   }
3130
3131   // Otherwise, use a libcall.
3132   RTLIB::Libcall LC = RTLIB::getUINTTOFP(SrcVT, DstVT);
3133   assert(LC != RTLIB::UNKNOWN_LIBCALL &&
3134          "Don't know how to expand this UINT_TO_FP!");
3135   return TLI.makeLibCall(DAG, LC, DstVT, Op, true, dl).first;
3136 }
3137
3138 SDValue DAGTypeLegalizer::ExpandIntOp_ATOMIC_STORE(SDNode *N) {
3139   SDLoc dl(N);
3140   SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
3141                                cast<AtomicSDNode>(N)->getMemoryVT(),
3142                                N->getOperand(0),
3143                                N->getOperand(1), N->getOperand(2),
3144                                cast<AtomicSDNode>(N)->getMemOperand(),
3145                                cast<AtomicSDNode>(N)->getOrdering(),
3146                                cast<AtomicSDNode>(N)->getSynchScope());
3147   return Swap.getValue(1);
3148 }
3149
3150
3151 SDValue DAGTypeLegalizer::PromoteIntRes_EXTRACT_SUBVECTOR(SDNode *N) {
3152   SDValue InOp0 = N->getOperand(0);
3153   EVT InVT = InOp0.getValueType();
3154
3155   EVT OutVT = N->getValueType(0);
3156   EVT NOutVT = TLI.getTypeToTransformTo(*DAG.getContext(), OutVT);
3157   assert(NOutVT.isVector() && "This type must be promoted to a vector type");
3158   unsigned OutNumElems = OutVT.getVectorNumElements();
3159   EVT NOutVTElem = NOutVT.getVectorElementType();
3160
3161   SDLoc dl(N);
3162   SDValue BaseIdx = N->getOperand(1);
3163
3164   SmallVector<SDValue, 8> Ops;
3165   Ops.reserve(OutNumElems);
3166   for (unsigned i = 0; i != OutNumElems; ++i) {
3167
3168     // Extract the element from the original vector.
3169     SDValue Index = DAG.getNode(ISD::ADD, dl, BaseIdx.getValueType(),
3170       BaseIdx, DAG.getConstant(i, dl, BaseIdx.getValueType()));
3171     SDValue Ext = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
3172       InVT.getVectorElementType(), N->getOperand(0), Index);
3173
3174     SDValue Op = DAG.getNode(ISD::ANY_EXTEND, dl, NOutVTElem, Ext);
3175     // Insert the converted element to the new vector.
3176     Ops.push_back(Op);
3177   }
3178
3179   return DAG.getNode(ISD::BUILD_VECTOR, dl, NOutVT, Ops);
3180 }
3181
3182
3183 SDValue DAGTypeLegalizer::PromoteIntRes_VECTOR_SHUFFLE(SDNode *N) {
3184   ShuffleVectorSDNode *SV = cast<ShuffleVectorSDNode>(N);
3185   EVT VT = N->getValueType(0);
3186   SDLoc dl(N);
3187
3188   ArrayRef<int> NewMask = SV->getMask().slice(0, VT.getVectorNumElements());
3189
3190   SDValue V0 = GetPromotedInteger(N->getOperand(0));
3191   SDValue V1 = GetPromotedInteger(N->getOperand(1));
3192   EVT OutVT = V0.getValueType();
3193
3194   return DAG.getVectorShuffle(OutVT, dl, V0, V1, NewMask);
3195 }
3196
3197
3198 SDValue DAGTypeLegalizer::PromoteIntRes_BUILD_VECTOR(SDNode *N) {
3199   EVT OutVT = N->getValueType(0);
3200   EVT NOutVT = TLI.getTypeToTransformTo(*DAG.getContext(), OutVT);
3201   assert(NOutVT.isVector() && "This type must be promoted to a vector type");
3202   unsigned NumElems = N->getNumOperands();
3203   EVT NOutVTElem = NOutVT.getVectorElementType();
3204
3205   SDLoc dl(N);
3206
3207   SmallVector<SDValue, 8> Ops;
3208   Ops.reserve(NumElems);
3209   for (unsigned i = 0; i != NumElems; ++i) {
3210     SDValue Op;
3211     // BUILD_VECTOR integer operand types are allowed to be larger than the
3212     // result's element type. This may still be true after the promotion. For
3213     // example, we might be promoting (<v?i1> = BV <i32>, <i32>, ...) to
3214     // (v?i16 = BV <i32>, <i32>, ...), and we can't any_extend <i32> to <i16>.
3215     if (N->getOperand(i).getValueType().bitsLT(NOutVTElem))
3216       Op = DAG.getNode(ISD::ANY_EXTEND, dl, NOutVTElem, N->getOperand(i));
3217     else
3218       Op = N->getOperand(i);
3219     Ops.push_back(Op);
3220   }
3221
3222   return DAG.getNode(ISD::BUILD_VECTOR, dl, NOutVT, Ops);
3223 }
3224
3225 SDValue DAGTypeLegalizer::PromoteIntRes_SCALAR_TO_VECTOR(SDNode *N) {
3226
3227   SDLoc dl(N);
3228
3229   assert(!N->getOperand(0).getValueType().isVector() &&
3230          "Input must be a scalar");
3231
3232   EVT OutVT = N->getValueType(0);
3233   EVT NOutVT = TLI.getTypeToTransformTo(*DAG.getContext(), OutVT);
3234   assert(NOutVT.isVector() && "This type must be promoted to a vector type");
3235   EVT NOutVTElem = NOutVT.getVectorElementType();
3236
3237   SDValue Op = DAG.getNode(ISD::ANY_EXTEND, dl, NOutVTElem, N->getOperand(0));
3238
3239   return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NOutVT, Op);
3240 }
3241
3242 SDValue DAGTypeLegalizer::PromoteIntRes_CONCAT_VECTORS(SDNode *N) {
3243   SDLoc dl(N);
3244
3245   EVT OutVT = N->getValueType(0);
3246   EVT NOutVT = TLI.getTypeToTransformTo(*DAG.getContext(), OutVT);
3247   assert(NOutVT.isVector() && "This type must be promoted to a vector type");
3248
3249   EVT InElemTy = OutVT.getVectorElementType();
3250   EVT OutElemTy = NOutVT.getVectorElementType();
3251
3252   unsigned NumElem = N->getOperand(0).getValueType().getVectorNumElements();
3253   unsigned NumOutElem = NOutVT.getVectorNumElements();
3254   unsigned NumOperands = N->getNumOperands();
3255   assert(NumElem * NumOperands == NumOutElem &&
3256          "Unexpected number of elements");
3257
3258   // Take the elements from the first vector.
3259   SmallVector<SDValue, 8> Ops(NumOutElem);
3260   for (unsigned i = 0; i < NumOperands; ++i) {
3261     SDValue Op = N->getOperand(i);
3262     for (unsigned j = 0; j < NumElem; ++j) {
3263       SDValue Ext = DAG.getNode(
3264           ISD::EXTRACT_VECTOR_ELT, dl, InElemTy, Op,
3265           DAG.getConstant(j, dl, TLI.getVectorIdxTy(DAG.getDataLayout())));
3266       Ops[i * NumElem + j] = DAG.getNode(ISD::ANY_EXTEND, dl, OutElemTy, Ext);
3267     }
3268   }
3269
3270   return DAG.getNode(ISD::BUILD_VECTOR, dl, NOutVT, Ops);
3271 }
3272
3273 SDValue DAGTypeLegalizer::PromoteIntRes_INSERT_VECTOR_ELT(SDNode *N) {
3274   EVT OutVT = N->getValueType(0);
3275   EVT NOutVT = TLI.getTypeToTransformTo(*DAG.getContext(), OutVT);
3276   assert(NOutVT.isVector() && "This type must be promoted to a vector type");
3277
3278   EVT NOutVTElem = NOutVT.getVectorElementType();
3279
3280   SDLoc dl(N);
3281   SDValue V0 = GetPromotedInteger(N->getOperand(0));
3282
3283   SDValue ConvElem = DAG.getNode(ISD::ANY_EXTEND, dl,
3284     NOutVTElem, N->getOperand(1));
3285   return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, NOutVT,
3286     V0, ConvElem, N->getOperand(2));
3287 }
3288
3289 SDValue DAGTypeLegalizer::PromoteIntOp_EXTRACT_VECTOR_ELT(SDNode *N) {
3290   SDLoc dl(N);
3291   SDValue V0 = GetPromotedInteger(N->getOperand(0));
3292   SDValue V1 = DAG.getZExtOrTrunc(N->getOperand(1), dl,
3293                                   TLI.getVectorIdxTy(DAG.getDataLayout()));
3294   SDValue Ext = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
3295     V0->getValueType(0).getScalarType(), V0, V1);
3296
3297   // EXTRACT_VECTOR_ELT can return types which are wider than the incoming
3298   // element types. If this is the case then we need to expand the outgoing
3299   // value and not truncate it.
3300   return DAG.getAnyExtOrTrunc(Ext, dl, N->getValueType(0));
3301 }
3302
3303 SDValue DAGTypeLegalizer::PromoteIntOp_EXTRACT_SUBVECTOR(SDNode *N) {
3304   SDLoc dl(N);
3305   SDValue V0 = GetPromotedInteger(N->getOperand(0));
3306   MVT InVT = V0.getValueType().getSimpleVT();
3307   MVT OutVT = MVT::getVectorVT(InVT.getVectorElementType(),
3308                                N->getValueType(0).getVectorNumElements());
3309   SDValue Ext = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, OutVT, V0, N->getOperand(1));
3310   return DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), Ext);
3311 }
3312
3313 SDValue DAGTypeLegalizer::PromoteIntOp_CONCAT_VECTORS(SDNode *N) {
3314   SDLoc dl(N);
3315   unsigned NumElems = N->getNumOperands();
3316
3317   EVT RetSclrTy = N->getValueType(0).getVectorElementType();
3318
3319   SmallVector<SDValue, 8> NewOps;
3320   NewOps.reserve(NumElems);
3321
3322   // For each incoming vector
3323   for (unsigned VecIdx = 0; VecIdx != NumElems; ++VecIdx) {
3324     SDValue Incoming = GetPromotedInteger(N->getOperand(VecIdx));
3325     EVT SclrTy = Incoming->getValueType(0).getVectorElementType();
3326     unsigned NumElem = Incoming->getValueType(0).getVectorNumElements();
3327
3328     for (unsigned i=0; i<NumElem; ++i) {
3329       // Extract element from incoming vector
3330       SDValue Ex = DAG.getNode(
3331           ISD::EXTRACT_VECTOR_ELT, dl, SclrTy, Incoming,
3332           DAG.getConstant(i, dl, TLI.getVectorIdxTy(DAG.getDataLayout())));
3333       SDValue Tr = DAG.getNode(ISD::TRUNCATE, dl, RetSclrTy, Ex);
3334       NewOps.push_back(Tr);
3335     }
3336   }
3337
3338   return DAG.getNode(ISD::BUILD_VECTOR, dl,  N->getValueType(0), NewOps);
3339 }