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