OSDN Git Service

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