]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/lib/CodeGen/SelectionDAG/LegalizeIntegerTypes.cpp
Merge llvm, clang, lld, lldb, compiler-rt and libc++ r301441, and update
[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::CTLZ_ZERO_UNDEF:
61   case ISD::CTLZ:        Res = PromoteIntRes_CTLZ(N); break;
62   case ISD::CTPOP:       Res = PromoteIntRes_CTPOP(N); break;
63   case ISD::CTTZ_ZERO_UNDEF:
64   case ISD::CTTZ:        Res = PromoteIntRes_CTTZ(N); break;
65   case ISD::EXTRACT_VECTOR_ELT:
66                          Res = PromoteIntRes_EXTRACT_VECTOR_ELT(N); break;
67   case ISD::LOAD:        Res = PromoteIntRes_LOAD(cast<LoadSDNode>(N)); break;
68   case ISD::MLOAD:       Res = PromoteIntRes_MLOAD(cast<MaskedLoadSDNode>(N));
69     break;
70   case ISD::MGATHER:     Res = PromoteIntRes_MGATHER(cast<MaskedGatherSDNode>(N));
71     break;
72   case ISD::SELECT:      Res = PromoteIntRes_SELECT(N); break;
73   case ISD::VSELECT:     Res = PromoteIntRes_VSELECT(N); break;
74   case ISD::SELECT_CC:   Res = PromoteIntRes_SELECT_CC(N); break;
75   case ISD::SETCC:       Res = PromoteIntRes_SETCC(N); break;
76   case ISD::SMIN:
77   case ISD::SMAX:        Res = PromoteIntRes_SExtIntBinOp(N); break;
78   case ISD::UMIN:
79   case ISD::UMAX:        Res = PromoteIntRes_ZExtIntBinOp(N); break;
80
81   case ISD::SHL:         Res = PromoteIntRes_SHL(N); break;
82   case ISD::SIGN_EXTEND_INREG:
83                          Res = PromoteIntRes_SIGN_EXTEND_INREG(N); break;
84   case ISD::SRA:         Res = PromoteIntRes_SRA(N); break;
85   case ISD::SRL:         Res = PromoteIntRes_SRL(N); break;
86   case ISD::TRUNCATE:    Res = PromoteIntRes_TRUNCATE(N); break;
87   case ISD::UNDEF:       Res = PromoteIntRes_UNDEF(N); break;
88   case ISD::VAARG:       Res = PromoteIntRes_VAARG(N); break;
89
90   case ISD::EXTRACT_SUBVECTOR:
91                          Res = PromoteIntRes_EXTRACT_SUBVECTOR(N); break;
92   case ISD::VECTOR_SHUFFLE:
93                          Res = PromoteIntRes_VECTOR_SHUFFLE(N); break;
94   case ISD::INSERT_VECTOR_ELT:
95                          Res = PromoteIntRes_INSERT_VECTOR_ELT(N); break;
96   case ISD::BUILD_VECTOR:
97                          Res = PromoteIntRes_BUILD_VECTOR(N); break;
98   case ISD::SCALAR_TO_VECTOR:
99                          Res = PromoteIntRes_SCALAR_TO_VECTOR(N); break;
100   case ISD::CONCAT_VECTORS:
101                          Res = PromoteIntRes_CONCAT_VECTORS(N); break;
102
103   case ISD::ANY_EXTEND_VECTOR_INREG:
104   case ISD::SIGN_EXTEND_VECTOR_INREG:
105   case ISD::ZERO_EXTEND_VECTOR_INREG:
106                          Res = PromoteIntRes_EXTEND_VECTOR_INREG(N); break;
107
108   case ISD::SIGN_EXTEND:
109   case ISD::ZERO_EXTEND:
110   case ISD::ANY_EXTEND:  Res = PromoteIntRes_INT_EXTEND(N); break;
111
112   case ISD::FP_TO_SINT:
113   case ISD::FP_TO_UINT:  Res = PromoteIntRes_FP_TO_XINT(N); break;
114
115   case ISD::FP_TO_FP16:  Res = PromoteIntRes_FP_TO_FP16(N); break;
116
117   case ISD::AND:
118   case ISD::OR:
119   case ISD::XOR:
120   case ISD::ADD:
121   case ISD::SUB:
122   case ISD::MUL:         Res = PromoteIntRes_SimpleIntBinOp(N); break;
123
124   case ISD::SDIV:
125   case ISD::SREM:        Res = PromoteIntRes_SExtIntBinOp(N); break;
126
127   case ISD::UDIV:
128   case ISD::UREM:        Res = PromoteIntRes_ZExtIntBinOp(N); break;
129
130   case ISD::SADDO:
131   case ISD::SSUBO:       Res = PromoteIntRes_SADDSUBO(N, ResNo); break;
132   case ISD::UADDO:
133   case ISD::USUBO:       Res = PromoteIntRes_UADDSUBO(N, ResNo); break;
134   case ISD::SMULO:
135   case ISD::UMULO:       Res = PromoteIntRes_XMULO(N, ResNo); break;
136
137   case ISD::ATOMIC_LOAD:
138     Res = PromoteIntRes_Atomic0(cast<AtomicSDNode>(N)); break;
139
140   case ISD::ATOMIC_LOAD_ADD:
141   case ISD::ATOMIC_LOAD_SUB:
142   case ISD::ATOMIC_LOAD_AND:
143   case ISD::ATOMIC_LOAD_OR:
144   case ISD::ATOMIC_LOAD_XOR:
145   case ISD::ATOMIC_LOAD_NAND:
146   case ISD::ATOMIC_LOAD_MIN:
147   case ISD::ATOMIC_LOAD_MAX:
148   case ISD::ATOMIC_LOAD_UMIN:
149   case ISD::ATOMIC_LOAD_UMAX:
150   case ISD::ATOMIC_SWAP:
151     Res = PromoteIntRes_Atomic1(cast<AtomicSDNode>(N)); break;
152
153   case ISD::ATOMIC_CMP_SWAP:
154   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
155     Res = PromoteIntRes_AtomicCmpSwap(cast<AtomicSDNode>(N), ResNo);
156     break;
157   }
158
159   // If the result is null then the sub-method took care of registering it.
160   if (Res.getNode())
161     SetPromotedInteger(SDValue(N, ResNo), Res);
162 }
163
164 SDValue DAGTypeLegalizer::PromoteIntRes_MERGE_VALUES(SDNode *N,
165                                                      unsigned ResNo) {
166   SDValue Op = DisintegrateMERGE_VALUES(N, ResNo);
167   return GetPromotedInteger(Op);
168 }
169
170 SDValue DAGTypeLegalizer::PromoteIntRes_AssertSext(SDNode *N) {
171   // Sign-extend the new bits, and continue the assertion.
172   SDValue Op = SExtPromotedInteger(N->getOperand(0));
173   return DAG.getNode(ISD::AssertSext, SDLoc(N),
174                      Op.getValueType(), Op, N->getOperand(1));
175 }
176
177 SDValue DAGTypeLegalizer::PromoteIntRes_AssertZext(SDNode *N) {
178   // Zero the new bits, and continue the assertion.
179   SDValue Op = ZExtPromotedInteger(N->getOperand(0));
180   return DAG.getNode(ISD::AssertZext, SDLoc(N),
181                      Op.getValueType(), Op, N->getOperand(1));
182 }
183
184 SDValue DAGTypeLegalizer::PromoteIntRes_Atomic0(AtomicSDNode *N) {
185   EVT ResVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
186   SDValue Res = DAG.getAtomic(N->getOpcode(), SDLoc(N),
187                               N->getMemoryVT(), ResVT,
188                               N->getChain(), N->getBasePtr(),
189                               N->getMemOperand());
190   // Legalize the chain result - switch anything that used the old chain to
191   // use the new one.
192   ReplaceValueWith(SDValue(N, 1), Res.getValue(1));
193   return Res;
194 }
195
196 SDValue DAGTypeLegalizer::PromoteIntRes_Atomic1(AtomicSDNode *N) {
197   SDValue Op2 = GetPromotedInteger(N->getOperand(2));
198   SDValue Res = DAG.getAtomic(N->getOpcode(), SDLoc(N),
199                               N->getMemoryVT(),
200                               N->getChain(), N->getBasePtr(),
201                               Op2, N->getMemOperand());
202   // Legalize the chain result - switch anything that used the old chain to
203   // use the new one.
204   ReplaceValueWith(SDValue(N, 1), Res.getValue(1));
205   return Res;
206 }
207
208 SDValue DAGTypeLegalizer::PromoteIntRes_AtomicCmpSwap(AtomicSDNode *N,
209                                                       unsigned ResNo) {
210   if (ResNo == 1) {
211     assert(N->getOpcode() == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
212     EVT SVT = getSetCCResultType(N->getOperand(2).getValueType());
213     EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(1));
214
215     // Only use the result of getSetCCResultType if it is legal,
216     // otherwise just use the promoted result type (NVT).
217     if (!TLI.isTypeLegal(SVT))
218       SVT = NVT;
219
220     SDVTList VTs = DAG.getVTList(N->getValueType(0), SVT, MVT::Other);
221     SDValue Res = DAG.getAtomicCmpSwap(
222         ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, SDLoc(N), N->getMemoryVT(), VTs,
223         N->getChain(), N->getBasePtr(), N->getOperand(2), N->getOperand(3),
224         N->getMemOperand());
225     ReplaceValueWith(SDValue(N, 0), Res.getValue(0));
226     ReplaceValueWith(SDValue(N, 2), Res.getValue(2));
227     return Res.getValue(1);
228   }
229
230   SDValue Op2 = GetPromotedInteger(N->getOperand(2));
231   SDValue Op3 = GetPromotedInteger(N->getOperand(3));
232   SDVTList VTs =
233       DAG.getVTList(Op2.getValueType(), N->getValueType(1), MVT::Other);
234   SDValue Res = DAG.getAtomicCmpSwap(
235       N->getOpcode(), SDLoc(N), N->getMemoryVT(), VTs, N->getChain(),
236       N->getBasePtr(), Op2, Op3, N->getMemOperand());
237   // Update the use to N with the newly created Res.
238   for (unsigned i = 1, NumResults = N->getNumValues(); i < NumResults; ++i)
239     ReplaceValueWith(SDValue(N, i), Res.getValue(i));
240   return Res;
241 }
242
243 SDValue DAGTypeLegalizer::PromoteIntRes_BITCAST(SDNode *N) {
244   SDValue InOp = N->getOperand(0);
245   EVT InVT = InOp.getValueType();
246   EVT NInVT = TLI.getTypeToTransformTo(*DAG.getContext(), InVT);
247   EVT OutVT = N->getValueType(0);
248   EVT NOutVT = TLI.getTypeToTransformTo(*DAG.getContext(), OutVT);
249   SDLoc dl(N);
250
251   switch (getTypeAction(InVT)) {
252   case TargetLowering::TypeLegal:
253     break;
254   case TargetLowering::TypePromoteInteger:
255     if (NOutVT.bitsEq(NInVT) && !NOutVT.isVector() && !NInVT.isVector())
256       // The input promotes to the same size.  Convert the promoted value.
257       return DAG.getNode(ISD::BITCAST, dl, NOutVT, GetPromotedInteger(InOp));
258     break;
259   case TargetLowering::TypeSoftenFloat:
260     // Promote the integer operand by hand.
261     return DAG.getNode(ISD::ANY_EXTEND, dl, NOutVT, GetSoftenedFloat(InOp));
262   case TargetLowering::TypePromoteFloat: {
263     // Convert the promoted float by hand.
264     SDValue PromotedOp = GetPromotedFloat(InOp);
265     return DAG.getNode(ISD::FP_TO_FP16, dl, NOutVT, PromotedOp);
266     break;
267   }
268   case TargetLowering::TypeExpandInteger:
269   case TargetLowering::TypeExpandFloat:
270     break;
271   case TargetLowering::TypeScalarizeVector:
272     // Convert the element to an integer and promote it by hand.
273     if (!NOutVT.isVector())
274       return DAG.getNode(ISD::ANY_EXTEND, dl, NOutVT,
275                          BitConvertToInteger(GetScalarizedVector(InOp)));
276     break;
277   case TargetLowering::TypeSplitVector: {
278     // For example, i32 = BITCAST v2i16 on alpha.  Convert the split
279     // pieces of the input into integers and reassemble in the final type.
280     SDValue Lo, Hi;
281     GetSplitVector(N->getOperand(0), Lo, Hi);
282     Lo = BitConvertToInteger(Lo);
283     Hi = BitConvertToInteger(Hi);
284
285     if (DAG.getDataLayout().isBigEndian())
286       std::swap(Lo, Hi);
287
288     InOp = DAG.getNode(ISD::ANY_EXTEND, dl,
289                        EVT::getIntegerVT(*DAG.getContext(),
290                                          NOutVT.getSizeInBits()),
291                        JoinIntegers(Lo, Hi));
292     return DAG.getNode(ISD::BITCAST, dl, NOutVT, InOp);
293   }
294   case TargetLowering::TypeWidenVector:
295     // The input is widened to the same size. Convert to the widened value.
296     // Make sure that the outgoing value is not a vector, because this would
297     // make us bitcast between two vectors which are legalized in different ways.
298     if (NOutVT.bitsEq(NInVT) && !NOutVT.isVector())
299       return DAG.getNode(ISD::BITCAST, dl, NOutVT, GetWidenedVector(InOp));
300   }
301
302   return DAG.getNode(ISD::ANY_EXTEND, dl, NOutVT,
303                      CreateStackStoreLoad(InOp, OutVT));
304 }
305
306 SDValue DAGTypeLegalizer::PromoteIntRes_BSWAP(SDNode *N) {
307   SDValue Op = GetPromotedInteger(N->getOperand(0));
308   EVT OVT = N->getValueType(0);
309   EVT NVT = Op.getValueType();
310   SDLoc dl(N);
311
312   unsigned DiffBits = NVT.getScalarSizeInBits() - OVT.getScalarSizeInBits();
313   return DAG.getNode(
314       ISD::SRL, dl, NVT, DAG.getNode(ISD::BSWAP, dl, NVT, Op),
315       DAG.getConstant(DiffBits, dl,
316                       TLI.getShiftAmountTy(NVT, DAG.getDataLayout())));
317 }
318
319 SDValue DAGTypeLegalizer::PromoteIntRes_BITREVERSE(SDNode *N) {
320   SDValue Op = GetPromotedInteger(N->getOperand(0));
321   EVT OVT = N->getValueType(0);
322   EVT NVT = Op.getValueType();
323   SDLoc dl(N);
324
325   unsigned DiffBits = NVT.getScalarSizeInBits() - OVT.getScalarSizeInBits();
326   return DAG.getNode(
327       ISD::SRL, dl, NVT, DAG.getNode(ISD::BITREVERSE, dl, NVT, Op),
328       DAG.getConstant(DiffBits, dl,
329                       TLI.getShiftAmountTy(NVT, DAG.getDataLayout())));
330 }
331
332 SDValue DAGTypeLegalizer::PromoteIntRes_BUILD_PAIR(SDNode *N) {
333   // The pair element type may be legal, or may not promote to the same type as
334   // the result, for example i14 = BUILD_PAIR (i7, i7).  Handle all cases.
335   return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N),
336                      TLI.getTypeToTransformTo(*DAG.getContext(),
337                      N->getValueType(0)), JoinIntegers(N->getOperand(0),
338                      N->getOperand(1)));
339 }
340
341 SDValue DAGTypeLegalizer::PromoteIntRes_Constant(SDNode *N) {
342   EVT VT = N->getValueType(0);
343   // FIXME there is no actual debug info here
344   SDLoc dl(N);
345   // Zero extend things like i1, sign extend everything else.  It shouldn't
346   // matter in theory which one we pick, but this tends to give better code?
347   unsigned Opc = VT.isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
348   SDValue Result = DAG.getNode(Opc, dl,
349                                TLI.getTypeToTransformTo(*DAG.getContext(), VT),
350                                SDValue(N, 0));
351   assert(isa<ConstantSDNode>(Result) && "Didn't constant fold ext?");
352   return Result;
353 }
354
355 SDValue DAGTypeLegalizer::PromoteIntRes_CTLZ(SDNode *N) {
356   // Zero extend to the promoted type and do the count there.
357   SDValue Op = ZExtPromotedInteger(N->getOperand(0));
358   SDLoc dl(N);
359   EVT OVT = N->getValueType(0);
360   EVT NVT = Op.getValueType();
361   Op = DAG.getNode(N->getOpcode(), dl, NVT, Op);
362   // Subtract off the extra leading bits in the bigger type.
363   return DAG.getNode(
364       ISD::SUB, dl, NVT, Op,
365       DAG.getConstant(NVT.getScalarSizeInBits() - OVT.getScalarSizeInBits(), dl,
366                       NVT));
367 }
368
369 SDValue DAGTypeLegalizer::PromoteIntRes_CTPOP(SDNode *N) {
370   // Zero extend to the promoted type and do the count there.
371   SDValue Op = ZExtPromotedInteger(N->getOperand(0));
372   return DAG.getNode(ISD::CTPOP, SDLoc(N), Op.getValueType(), Op);
373 }
374
375 SDValue DAGTypeLegalizer::PromoteIntRes_CTTZ(SDNode *N) {
376   SDValue Op = GetPromotedInteger(N->getOperand(0));
377   EVT OVT = N->getValueType(0);
378   EVT NVT = Op.getValueType();
379   SDLoc dl(N);
380   if (N->getOpcode() == ISD::CTTZ) {
381     // The count is the same in the promoted type except if the original
382     // value was zero.  This can be handled by setting the bit just off
383     // the top of the original type.
384     auto TopBit = APInt::getOneBitSet(NVT.getScalarSizeInBits(),
385                                       OVT.getScalarSizeInBits());
386     Op = DAG.getNode(ISD::OR, dl, NVT, Op, DAG.getConstant(TopBit, dl, NVT));
387   }
388   return DAG.getNode(N->getOpcode(), dl, NVT, Op);
389 }
390
391 SDValue DAGTypeLegalizer::PromoteIntRes_EXTRACT_VECTOR_ELT(SDNode *N) {
392   SDLoc dl(N);
393   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
394   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, NVT, N->getOperand(0),
395                      N->getOperand(1));
396 }
397
398 SDValue DAGTypeLegalizer::PromoteIntRes_FP_TO_XINT(SDNode *N) {
399   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
400   unsigned NewOpc = N->getOpcode();
401   SDLoc dl(N);
402
403   // If we're promoting a UINT to a larger size and the larger FP_TO_UINT is
404   // not Legal, check to see if we can use FP_TO_SINT instead.  (If both UINT
405   // and SINT conversions are Custom, there is no way to tell which is
406   // preferable. We choose SINT because that's the right thing on PPC.)
407   if (N->getOpcode() == ISD::FP_TO_UINT &&
408       !TLI.isOperationLegal(ISD::FP_TO_UINT, NVT) &&
409       TLI.isOperationLegalOrCustom(ISD::FP_TO_SINT, NVT))
410     NewOpc = ISD::FP_TO_SINT;
411
412   SDValue Res = DAG.getNode(NewOpc, dl, NVT, N->getOperand(0));
413
414   // Assert that the converted value fits in the original type.  If it doesn't
415   // (eg: because the value being converted is too big), then the result of the
416   // original operation was undefined anyway, so the assert is still correct.
417   //
418   // NOTE: fp-to-uint to fp-to-sint promotion guarantees zero extend. For example:
419   //   before legalization: fp-to-uint16, 65534. -> 0xfffe
420   //   after legalization: fp-to-sint32, 65534. -> 0x0000fffe
421   return DAG.getNode(N->getOpcode() == ISD::FP_TO_UINT ?
422                      ISD::AssertZext : ISD::AssertSext, dl, NVT, Res,
423                      DAG.getValueType(N->getValueType(0).getScalarType()));
424 }
425
426 SDValue DAGTypeLegalizer::PromoteIntRes_FP_TO_FP16(SDNode *N) {
427   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
428   SDLoc dl(N);
429
430   return DAG.getNode(N->getOpcode(), dl, NVT, N->getOperand(0));
431 }
432
433 SDValue DAGTypeLegalizer::PromoteIntRes_INT_EXTEND(SDNode *N) {
434   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
435   SDLoc dl(N);
436
437   if (getTypeAction(N->getOperand(0).getValueType())
438       == TargetLowering::TypePromoteInteger) {
439     SDValue Res = GetPromotedInteger(N->getOperand(0));
440     assert(Res.getValueType().bitsLE(NVT) && "Extension doesn't make sense!");
441
442     // If the result and operand types are the same after promotion, simplify
443     // to an in-register extension.
444     if (NVT == Res.getValueType()) {
445       // The high bits are not guaranteed to be anything.  Insert an extend.
446       if (N->getOpcode() == ISD::SIGN_EXTEND)
447         return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NVT, Res,
448                            DAG.getValueType(N->getOperand(0).getValueType()));
449       if (N->getOpcode() == ISD::ZERO_EXTEND)
450         return DAG.getZeroExtendInReg(Res, dl,
451                       N->getOperand(0).getValueType().getScalarType());
452       assert(N->getOpcode() == ISD::ANY_EXTEND && "Unknown integer extension!");
453       return Res;
454     }
455   }
456
457   // Otherwise, just extend the original operand all the way to the larger type.
458   return DAG.getNode(N->getOpcode(), dl, NVT, N->getOperand(0));
459 }
460
461 SDValue DAGTypeLegalizer::PromoteIntRes_LOAD(LoadSDNode *N) {
462   assert(ISD::isUNINDEXEDLoad(N) && "Indexed load during type legalization!");
463   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
464   ISD::LoadExtType ExtType =
465     ISD::isNON_EXTLoad(N) ? ISD::EXTLOAD : N->getExtensionType();
466   SDLoc dl(N);
467   SDValue Res = DAG.getExtLoad(ExtType, dl, NVT, N->getChain(), N->getBasePtr(),
468                                N->getMemoryVT(), N->getMemOperand());
469
470   // Legalize the chain result - switch anything that used the old chain to
471   // use the new one.
472   ReplaceValueWith(SDValue(N, 1), Res.getValue(1));
473   return Res;
474 }
475
476 SDValue DAGTypeLegalizer::PromoteIntRes_MLOAD(MaskedLoadSDNode *N) {
477   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
478   SDValue ExtSrc0 = GetPromotedInteger(N->getSrc0());
479
480   SDLoc dl(N);
481   SDValue Res = DAG.getMaskedLoad(NVT, dl, N->getChain(), N->getBasePtr(),
482                                   N->getMask(), ExtSrc0, N->getMemoryVT(),
483                                   N->getMemOperand(), ISD::SEXTLOAD);
484   // Legalize the chain result - switch anything that used the old chain to
485   // use the new one.
486   ReplaceValueWith(SDValue(N, 1), Res.getValue(1));
487   return Res;
488 }
489
490 SDValue DAGTypeLegalizer::PromoteIntRes_MGATHER(MaskedGatherSDNode *N) {
491   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
492   SDValue ExtSrc0 = GetPromotedInteger(N->getValue());
493   assert(NVT == ExtSrc0.getValueType() &&
494       "Gather result type and the passThru agrument type should be the same");
495
496   SDLoc dl(N);
497   SDValue Ops[] = {N->getChain(), ExtSrc0, N->getMask(), N->getBasePtr(),
498                    N->getIndex()};
499   SDValue Res = DAG.getMaskedGather(DAG.getVTList(NVT, MVT::Other),
500                                     N->getMemoryVT(), dl, Ops,
501                                     N->getMemOperand());
502   // Legalize the chain result - switch anything that used the old chain to
503   // use the new one.
504   ReplaceValueWith(SDValue(N, 1), Res.getValue(1));
505   return Res;
506 }
507
508 /// Promote the overflow flag of an overflowing arithmetic node.
509 SDValue DAGTypeLegalizer::PromoteIntRes_Overflow(SDNode *N) {
510   // Simply change the return type of the boolean result.
511   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(1));
512   EVT ValueVTs[] = { N->getValueType(0), NVT };
513   SDValue Ops[] = { N->getOperand(0), N->getOperand(1) };
514   SDValue Res = DAG.getNode(N->getOpcode(), SDLoc(N),
515                             DAG.getVTList(ValueVTs), Ops);
516
517   // Modified the sum result - switch anything that used the old sum to use
518   // the new one.
519   ReplaceValueWith(SDValue(N, 0), Res);
520
521   return SDValue(Res.getNode(), 1);
522 }
523
524 SDValue DAGTypeLegalizer::PromoteIntRes_SADDSUBO(SDNode *N, unsigned ResNo) {
525   if (ResNo == 1)
526     return PromoteIntRes_Overflow(N);
527
528   // The operation overflowed iff the result in the larger type is not the
529   // sign extension of its truncation to the original type.
530   SDValue LHS = SExtPromotedInteger(N->getOperand(0));
531   SDValue RHS = SExtPromotedInteger(N->getOperand(1));
532   EVT OVT = N->getOperand(0).getValueType();
533   EVT NVT = LHS.getValueType();
534   SDLoc dl(N);
535
536   // Do the arithmetic in the larger type.
537   unsigned Opcode = N->getOpcode() == ISD::SADDO ? ISD::ADD : ISD::SUB;
538   SDValue Res = DAG.getNode(Opcode, dl, NVT, LHS, RHS);
539
540   // Calculate the overflow flag: sign extend the arithmetic result from
541   // the original type.
542   SDValue Ofl = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NVT, Res,
543                             DAG.getValueType(OVT));
544   // Overflowed if and only if this is not equal to Res.
545   Ofl = DAG.getSetCC(dl, N->getValueType(1), Ofl, Res, ISD::SETNE);
546
547   // Use the calculated overflow everywhere.
548   ReplaceValueWith(SDValue(N, 1), Ofl);
549
550   return Res;
551 }
552
553 SDValue DAGTypeLegalizer::PromoteIntRes_SELECT(SDNode *N) {
554   SDValue LHS = GetPromotedInteger(N->getOperand(1));
555   SDValue RHS = GetPromotedInteger(N->getOperand(2));
556   return DAG.getSelect(SDLoc(N),
557                        LHS.getValueType(), N->getOperand(0), LHS, RHS);
558 }
559
560 SDValue DAGTypeLegalizer::PromoteIntRes_VSELECT(SDNode *N) {
561   SDValue Mask = N->getOperand(0);
562   EVT OpTy = N->getOperand(1).getValueType();
563
564   // Promote all the way up to the canonical SetCC type.
565   Mask = PromoteTargetBoolean(Mask, OpTy);
566   SDValue LHS = GetPromotedInteger(N->getOperand(1));
567   SDValue RHS = GetPromotedInteger(N->getOperand(2));
568   return DAG.getNode(ISD::VSELECT, SDLoc(N),
569                      LHS.getValueType(), Mask, LHS, RHS);
570 }
571
572 SDValue DAGTypeLegalizer::PromoteIntRes_SELECT_CC(SDNode *N) {
573   SDValue LHS = GetPromotedInteger(N->getOperand(2));
574   SDValue RHS = GetPromotedInteger(N->getOperand(3));
575   return DAG.getNode(ISD::SELECT_CC, SDLoc(N),
576                      LHS.getValueType(), N->getOperand(0),
577                      N->getOperand(1), LHS, RHS, N->getOperand(4));
578 }
579
580 SDValue DAGTypeLegalizer::PromoteIntRes_SETCC(SDNode *N) {
581   EVT SVT = getSetCCResultType(N->getOperand(0).getValueType());
582
583   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
584
585   // Only use the result of getSetCCResultType if it is legal,
586   // otherwise just use the promoted result type (NVT).
587   if (!TLI.isTypeLegal(SVT))
588     SVT = NVT;
589
590   SDLoc dl(N);
591   assert(SVT.isVector() == N->getOperand(0).getValueType().isVector() &&
592          "Vector compare must return a vector result!");
593
594   SDValue LHS = N->getOperand(0);
595   SDValue RHS = N->getOperand(1);
596   if (LHS.getValueType() != RHS.getValueType()) {
597     if (getTypeAction(LHS.getValueType()) == TargetLowering::TypePromoteInteger &&
598         !LHS.getValueType().isVector())
599       LHS = GetPromotedInteger(LHS);
600     if (getTypeAction(RHS.getValueType()) == TargetLowering::TypePromoteInteger &&
601         !RHS.getValueType().isVector())
602       RHS = GetPromotedInteger(RHS);
603   }
604
605   // Get the SETCC result using the canonical SETCC type.
606   SDValue SetCC = DAG.getNode(N->getOpcode(), dl, SVT, LHS, RHS,
607                               N->getOperand(2));
608
609   assert(NVT.bitsLE(SVT) && "Integer type overpromoted?");
610   // Convert to the expected type.
611   return DAG.getNode(ISD::TRUNCATE, dl, NVT, SetCC);
612 }
613
614 SDValue DAGTypeLegalizer::PromoteIntRes_SHL(SDNode *N) {
615   SDValue LHS = N->getOperand(0);
616   SDValue RHS = N->getOperand(1);
617   if (getTypeAction(LHS.getValueType()) == TargetLowering::TypePromoteInteger)
618     LHS = GetPromotedInteger(LHS);
619   if (getTypeAction(RHS.getValueType()) == TargetLowering::TypePromoteInteger)
620     RHS = ZExtPromotedInteger(RHS);
621   return DAG.getNode(ISD::SHL, SDLoc(N), LHS.getValueType(), LHS, RHS);
622 }
623
624 SDValue DAGTypeLegalizer::PromoteIntRes_SIGN_EXTEND_INREG(SDNode *N) {
625   SDValue Op = GetPromotedInteger(N->getOperand(0));
626   return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N),
627                      Op.getValueType(), Op, N->getOperand(1));
628 }
629
630 SDValue DAGTypeLegalizer::PromoteIntRes_SimpleIntBinOp(SDNode *N) {
631   // The input may have strange things in the top bits of the registers, but
632   // these operations don't care.  They may have weird bits going out, but
633   // that too is okay if they are integer operations.
634   SDValue LHS = GetPromotedInteger(N->getOperand(0));
635   SDValue RHS = GetPromotedInteger(N->getOperand(1));
636   return DAG.getNode(N->getOpcode(), SDLoc(N),
637                      LHS.getValueType(), LHS, RHS);
638 }
639
640 SDValue DAGTypeLegalizer::PromoteIntRes_SExtIntBinOp(SDNode *N) {
641   // Sign extend the input.
642   SDValue LHS = SExtPromotedInteger(N->getOperand(0));
643   SDValue RHS = SExtPromotedInteger(N->getOperand(1));
644   return DAG.getNode(N->getOpcode(), SDLoc(N),
645                      LHS.getValueType(), LHS, RHS);
646 }
647
648 SDValue DAGTypeLegalizer::PromoteIntRes_ZExtIntBinOp(SDNode *N) {
649   // Zero extend the input.
650   SDValue LHS = ZExtPromotedInteger(N->getOperand(0));
651   SDValue RHS = ZExtPromotedInteger(N->getOperand(1));
652   return DAG.getNode(N->getOpcode(), SDLoc(N),
653                      LHS.getValueType(), LHS, RHS);
654 }
655
656 SDValue DAGTypeLegalizer::PromoteIntRes_SRA(SDNode *N) {
657   SDValue LHS = N->getOperand(0);
658   SDValue RHS = N->getOperand(1);
659   // The input value must be properly sign extended.
660   if (getTypeAction(LHS.getValueType()) == TargetLowering::TypePromoteInteger)
661     LHS = SExtPromotedInteger(LHS);
662   if (getTypeAction(RHS.getValueType()) == TargetLowering::TypePromoteInteger)
663     RHS = ZExtPromotedInteger(RHS);
664   return DAG.getNode(ISD::SRA, SDLoc(N), LHS.getValueType(), LHS, RHS);
665 }
666
667 SDValue DAGTypeLegalizer::PromoteIntRes_SRL(SDNode *N) {
668   SDValue LHS = N->getOperand(0);
669   SDValue RHS = N->getOperand(1);
670   // The input value must be properly zero extended.
671   if (getTypeAction(LHS.getValueType()) == TargetLowering::TypePromoteInteger)
672     LHS = ZExtPromotedInteger(LHS);
673   if (getTypeAction(RHS.getValueType()) == TargetLowering::TypePromoteInteger)
674     RHS = ZExtPromotedInteger(RHS);
675   return DAG.getNode(ISD::SRL, SDLoc(N), LHS.getValueType(), LHS, RHS);
676 }
677
678 SDValue DAGTypeLegalizer::PromoteIntRes_TRUNCATE(SDNode *N) {
679   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
680   SDValue Res;
681   SDValue InOp = N->getOperand(0);
682   SDLoc dl(N);
683
684   switch (getTypeAction(InOp.getValueType())) {
685   default: llvm_unreachable("Unknown type action!");
686   case TargetLowering::TypeLegal:
687   case TargetLowering::TypeExpandInteger:
688     Res = InOp;
689     break;
690   case TargetLowering::TypePromoteInteger:
691     Res = GetPromotedInteger(InOp);
692     break;
693   case TargetLowering::TypeSplitVector: {
694     EVT InVT = InOp.getValueType();
695     assert(InVT.isVector() && "Cannot split scalar types");
696     unsigned NumElts = InVT.getVectorNumElements();
697     assert(NumElts == NVT.getVectorNumElements() &&
698            "Dst and Src must have the same number of elements");
699     assert(isPowerOf2_32(NumElts) &&
700            "Promoted vector type must be a power of two");
701
702     SDValue EOp1, EOp2;
703     GetSplitVector(InOp, EOp1, EOp2);
704
705     EVT HalfNVT = EVT::getVectorVT(*DAG.getContext(), NVT.getScalarType(),
706                                    NumElts/2);
707     EOp1 = DAG.getNode(ISD::TRUNCATE, dl, HalfNVT, EOp1);
708     EOp2 = DAG.getNode(ISD::TRUNCATE, dl, HalfNVT, EOp2);
709
710     return DAG.getNode(ISD::CONCAT_VECTORS, dl, NVT, EOp1, EOp2);
711   }
712   case TargetLowering::TypeWidenVector: {
713     SDValue WideInOp = GetWidenedVector(InOp);
714
715     // Truncate widened InOp.
716     unsigned NumElem = WideInOp.getValueType().getVectorNumElements();
717     EVT TruncVT = EVT::getVectorVT(*DAG.getContext(),
718                                    N->getValueType(0).getScalarType(), NumElem);
719     SDValue WideTrunc = DAG.getNode(ISD::TRUNCATE, dl, TruncVT, WideInOp);
720
721     // Zero extend so that the elements are of same type as those of NVT
722     EVT ExtVT = EVT::getVectorVT(*DAG.getContext(), NVT.getVectorElementType(),
723                                  NumElem);
724     SDValue WideExt = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, WideTrunc);
725
726     // Extract the low NVT subvector.
727     MVT IdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
728     SDValue ZeroIdx = DAG.getConstant(0, dl, IdxTy);
729     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT, WideExt, ZeroIdx);
730   }
731   }
732
733   // Truncate to NVT instead of VT
734   return DAG.getNode(ISD::TRUNCATE, dl, NVT, Res);
735 }
736
737 SDValue DAGTypeLegalizer::PromoteIntRes_UADDSUBO(SDNode *N, unsigned ResNo) {
738   if (ResNo == 1)
739     return PromoteIntRes_Overflow(N);
740
741   // The operation overflowed iff the result in the larger type is not the
742   // zero extension of its truncation to the original type.
743   SDValue LHS = ZExtPromotedInteger(N->getOperand(0));
744   SDValue RHS = ZExtPromotedInteger(N->getOperand(1));
745   EVT OVT = N->getOperand(0).getValueType();
746   EVT NVT = LHS.getValueType();
747   SDLoc dl(N);
748
749   // Do the arithmetic in the larger type.
750   unsigned Opcode = N->getOpcode() == ISD::UADDO ? ISD::ADD : ISD::SUB;
751   SDValue Res = DAG.getNode(Opcode, dl, NVT, LHS, RHS);
752
753   // Calculate the overflow flag: zero extend the arithmetic result from
754   // the original type.
755   SDValue Ofl = DAG.getZeroExtendInReg(Res, dl, OVT);
756   // Overflowed if and only if this is not equal to Res.
757   Ofl = DAG.getSetCC(dl, N->getValueType(1), Ofl, Res, ISD::SETNE);
758
759   // Use the calculated overflow everywhere.
760   ReplaceValueWith(SDValue(N, 1), Ofl);
761
762   return Res;
763 }
764
765 SDValue DAGTypeLegalizer::PromoteIntRes_XMULO(SDNode *N, unsigned ResNo) {
766   // Promote the overflow bit trivially.
767   if (ResNo == 1)
768     return PromoteIntRes_Overflow(N);
769
770   SDValue LHS = N->getOperand(0), RHS = N->getOperand(1);
771   SDLoc DL(N);
772   EVT SmallVT = LHS.getValueType();
773
774   // To determine if the result overflowed in a larger type, we extend the
775   // input to the larger type, do the multiply (checking if it overflows),
776   // then also check the high bits of the result to see if overflow happened
777   // there.
778   if (N->getOpcode() == ISD::SMULO) {
779     LHS = SExtPromotedInteger(LHS);
780     RHS = SExtPromotedInteger(RHS);
781   } else {
782     LHS = ZExtPromotedInteger(LHS);
783     RHS = ZExtPromotedInteger(RHS);
784   }
785   SDVTList VTs = DAG.getVTList(LHS.getValueType(), N->getValueType(1));
786   SDValue Mul = DAG.getNode(N->getOpcode(), DL, VTs, LHS, RHS);
787
788   // Overflow occurred if it occurred in the larger type, or if the high part
789   // of the result does not zero/sign-extend the low part.  Check this second
790   // possibility first.
791   SDValue Overflow;
792   if (N->getOpcode() == ISD::UMULO) {
793     // Unsigned overflow occurred if the high part is non-zero.
794     SDValue Hi = DAG.getNode(ISD::SRL, DL, Mul.getValueType(), Mul,
795                              DAG.getIntPtrConstant(SmallVT.getSizeInBits(),
796                                                    DL));
797     Overflow = DAG.getSetCC(DL, N->getValueType(1), Hi,
798                             DAG.getConstant(0, DL, Hi.getValueType()),
799                             ISD::SETNE);
800   } else {
801     // Signed overflow occurred if the high part does not sign extend the low.
802     SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, Mul.getValueType(),
803                                Mul, DAG.getValueType(SmallVT));
804     Overflow = DAG.getSetCC(DL, N->getValueType(1), SExt, Mul, ISD::SETNE);
805   }
806
807   // The only other way for overflow to occur is if the multiplication in the
808   // larger type itself overflowed.
809   Overflow = DAG.getNode(ISD::OR, DL, N->getValueType(1), Overflow,
810                          SDValue(Mul.getNode(), 1));
811
812   // Use the calculated overflow everywhere.
813   ReplaceValueWith(SDValue(N, 1), Overflow);
814   return Mul;
815 }
816
817 SDValue DAGTypeLegalizer::PromoteIntRes_UNDEF(SDNode *N) {
818   return DAG.getUNDEF(TLI.getTypeToTransformTo(*DAG.getContext(),
819                                                N->getValueType(0)));
820 }
821
822 SDValue DAGTypeLegalizer::PromoteIntRes_VAARG(SDNode *N) {
823   SDValue Chain = N->getOperand(0); // Get the chain.
824   SDValue Ptr = N->getOperand(1); // Get the pointer.
825   EVT VT = N->getValueType(0);
826   SDLoc dl(N);
827
828   MVT RegVT = TLI.getRegisterType(*DAG.getContext(), VT);
829   unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), VT);
830   // The argument is passed as NumRegs registers of type RegVT.
831
832   SmallVector<SDValue, 8> Parts(NumRegs);
833   for (unsigned i = 0; i < NumRegs; ++i) {
834     Parts[i] = DAG.getVAArg(RegVT, dl, Chain, Ptr, N->getOperand(2),
835                             N->getConstantOperandVal(3));
836     Chain = Parts[i].getValue(1);
837   }
838
839   // Handle endianness of the load.
840   if (DAG.getDataLayout().isBigEndian())
841     std::reverse(Parts.begin(), Parts.end());
842
843   // Assemble the parts in the promoted type.
844   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
845   SDValue Res = DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, Parts[0]);
846   for (unsigned i = 1; i < NumRegs; ++i) {
847     SDValue Part = DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, Parts[i]);
848     // Shift it to the right position and "or" it in.
849     Part = DAG.getNode(ISD::SHL, dl, NVT, Part,
850                        DAG.getConstant(i * RegVT.getSizeInBits(), dl,
851                                        TLI.getPointerTy(DAG.getDataLayout())));
852     Res = DAG.getNode(ISD::OR, dl, NVT, Res, Part);
853   }
854
855   // Modified the chain result - switch anything that used the old chain to
856   // use the new one.
857   ReplaceValueWith(SDValue(N, 1), Chain);
858
859   return Res;
860 }
861
862 //===----------------------------------------------------------------------===//
863 //  Integer Operand Promotion
864 //===----------------------------------------------------------------------===//
865
866 /// PromoteIntegerOperand - This method is called when the specified operand of
867 /// the specified node is found to need promotion.  At this point, all of the
868 /// result types of the node are known to be legal, but other operands of the
869 /// node may need promotion or expansion as well as the specified one.
870 bool DAGTypeLegalizer::PromoteIntegerOperand(SDNode *N, unsigned OpNo) {
871   DEBUG(dbgs() << "Promote integer operand: "; N->dump(&DAG); dbgs() << "\n");
872   SDValue Res = SDValue();
873
874   if (CustomLowerNode(N, N->getOperand(OpNo).getValueType(), false))
875     return false;
876
877   switch (N->getOpcode()) {
878     default:
879   #ifndef NDEBUG
880     dbgs() << "PromoteIntegerOperand Op #" << OpNo << ": ";
881     N->dump(&DAG); dbgs() << "\n";
882   #endif
883     llvm_unreachable("Do not know how to promote this operator's operand!");
884
885   case ISD::ANY_EXTEND:   Res = PromoteIntOp_ANY_EXTEND(N); break;
886   case ISD::ATOMIC_STORE:
887     Res = PromoteIntOp_ATOMIC_STORE(cast<AtomicSDNode>(N));
888     break;
889   case ISD::BITCAST:      Res = PromoteIntOp_BITCAST(N); break;
890   case ISD::BR_CC:        Res = PromoteIntOp_BR_CC(N, OpNo); break;
891   case ISD::BRCOND:       Res = PromoteIntOp_BRCOND(N, OpNo); break;
892   case ISD::BUILD_PAIR:   Res = PromoteIntOp_BUILD_PAIR(N); break;
893   case ISD::BUILD_VECTOR: Res = PromoteIntOp_BUILD_VECTOR(N); break;
894   case ISD::CONCAT_VECTORS: Res = PromoteIntOp_CONCAT_VECTORS(N); break;
895   case ISD::EXTRACT_VECTOR_ELT: Res = PromoteIntOp_EXTRACT_VECTOR_ELT(N); break;
896   case ISD::INSERT_VECTOR_ELT:
897                           Res = PromoteIntOp_INSERT_VECTOR_ELT(N, OpNo);break;
898   case ISD::SCALAR_TO_VECTOR:
899                           Res = PromoteIntOp_SCALAR_TO_VECTOR(N); break;
900   case ISD::VSELECT:
901   case ISD::SELECT:       Res = PromoteIntOp_SELECT(N, OpNo); break;
902   case ISD::SELECT_CC:    Res = PromoteIntOp_SELECT_CC(N, OpNo); break;
903   case ISD::SETCC:        Res = PromoteIntOp_SETCC(N, OpNo); break;
904   case ISD::SIGN_EXTEND:  Res = PromoteIntOp_SIGN_EXTEND(N); break;
905   case ISD::SINT_TO_FP:   Res = PromoteIntOp_SINT_TO_FP(N); break;
906   case ISD::STORE:        Res = PromoteIntOp_STORE(cast<StoreSDNode>(N),
907                                                    OpNo); break;
908   case ISD::MSTORE:       Res = PromoteIntOp_MSTORE(cast<MaskedStoreSDNode>(N),
909                                                     OpNo); break;
910   case ISD::MLOAD:        Res = PromoteIntOp_MLOAD(cast<MaskedLoadSDNode>(N),
911                                                     OpNo); break;
912   case ISD::MGATHER:  Res = PromoteIntOp_MGATHER(cast<MaskedGatherSDNode>(N),
913                                                  OpNo); break;
914   case ISD::MSCATTER: Res = PromoteIntOp_MSCATTER(cast<MaskedScatterSDNode>(N),
915                                                   OpNo); break;
916   case ISD::TRUNCATE:     Res = PromoteIntOp_TRUNCATE(N); break;
917   case ISD::FP16_TO_FP:
918   case ISD::UINT_TO_FP:   Res = PromoteIntOp_UINT_TO_FP(N); break;
919   case ISD::ZERO_EXTEND:  Res = PromoteIntOp_ZERO_EXTEND(N); break;
920   case ISD::EXTRACT_SUBVECTOR: Res = PromoteIntOp_EXTRACT_SUBVECTOR(N); break;
921
922   case ISD::SHL:
923   case ISD::SRA:
924   case ISD::SRL:
925   case ISD::ROTL:
926   case ISD::ROTR: Res = PromoteIntOp_Shift(N); break;
927   }
928
929   // If the result is null, the sub-method took care of registering results etc.
930   if (!Res.getNode()) return false;
931
932   // If the result is N, the sub-method updated N in place.  Tell the legalizer
933   // core about this.
934   if (Res.getNode() == N)
935     return true;
936
937   assert(Res.getValueType() == N->getValueType(0) && N->getNumValues() == 1 &&
938          "Invalid operand expansion");
939
940   ReplaceValueWith(SDValue(N, 0), Res);
941   return false;
942 }
943
944 /// PromoteSetCCOperands - Promote the operands of a comparison.  This code is
945 /// shared among BR_CC, SELECT_CC, and SETCC handlers.
946 void DAGTypeLegalizer::PromoteSetCCOperands(SDValue &NewLHS,SDValue &NewRHS,
947                                             ISD::CondCode CCCode) {
948   // We have to insert explicit sign or zero extends.  Note that we could
949   // insert sign extends for ALL conditions, but zero extend is cheaper on
950   // many machines (an AND instead of two shifts), so prefer it.
951   switch (CCCode) {
952   default: llvm_unreachable("Unknown integer comparison!");
953   case ISD::SETEQ:
954   case ISD::SETNE: {
955     SDValue OpL = GetPromotedInteger(NewLHS);
956     SDValue OpR = GetPromotedInteger(NewRHS);
957
958     // We would prefer to promote the comparison operand with sign extension.
959     // If the width of OpL/OpR excluding the duplicated sign bits is no greater
960     // than the width of NewLHS/NewRH, we can avoid inserting real truncate
961     // instruction, which is redudant eventually.
962     unsigned OpLEffectiveBits =
963         OpL.getValueSizeInBits() - DAG.ComputeNumSignBits(OpL) + 1;
964     unsigned OpREffectiveBits =
965         OpR.getValueSizeInBits() - DAG.ComputeNumSignBits(OpR) + 1;
966     if (OpLEffectiveBits <= NewLHS.getValueSizeInBits() &&
967         OpREffectiveBits <= NewRHS.getValueSizeInBits()) {
968       NewLHS = OpL;
969       NewRHS = OpR;
970     } else {
971       NewLHS = ZExtPromotedInteger(NewLHS);
972       NewRHS = ZExtPromotedInteger(NewRHS);
973     }
974     break;
975   }
976   case ISD::SETUGE:
977   case ISD::SETUGT:
978   case ISD::SETULE:
979   case ISD::SETULT:
980     // ALL of these operations will work if we either sign or zero extend
981     // the operands (including the unsigned comparisons!).  Zero extend is
982     // usually a simpler/cheaper operation, so prefer it.
983     NewLHS = ZExtPromotedInteger(NewLHS);
984     NewRHS = ZExtPromotedInteger(NewRHS);
985     break;
986   case ISD::SETGE:
987   case ISD::SETGT:
988   case ISD::SETLT:
989   case ISD::SETLE:
990     NewLHS = SExtPromotedInteger(NewLHS);
991     NewRHS = SExtPromotedInteger(NewRHS);
992     break;
993   }
994 }
995
996 SDValue DAGTypeLegalizer::PromoteIntOp_ANY_EXTEND(SDNode *N) {
997   SDValue Op = GetPromotedInteger(N->getOperand(0));
998   return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), N->getValueType(0), Op);
999 }
1000
1001 SDValue DAGTypeLegalizer::PromoteIntOp_ATOMIC_STORE(AtomicSDNode *N) {
1002   SDValue Op2 = GetPromotedInteger(N->getOperand(2));
1003   return DAG.getAtomic(N->getOpcode(), SDLoc(N), N->getMemoryVT(),
1004                        N->getChain(), N->getBasePtr(), Op2, N->getMemOperand());
1005 }
1006
1007 SDValue DAGTypeLegalizer::PromoteIntOp_BITCAST(SDNode *N) {
1008   // This should only occur in unusual situations like bitcasting to an
1009   // x86_fp80, so just turn it into a store+load
1010   return CreateStackStoreLoad(N->getOperand(0), N->getValueType(0));
1011 }
1012
1013 SDValue DAGTypeLegalizer::PromoteIntOp_BR_CC(SDNode *N, unsigned OpNo) {
1014   assert(OpNo == 2 && "Don't know how to promote this operand!");
1015
1016   SDValue LHS = N->getOperand(2);
1017   SDValue RHS = N->getOperand(3);
1018   PromoteSetCCOperands(LHS, RHS, cast<CondCodeSDNode>(N->getOperand(1))->get());
1019
1020   // The chain (Op#0), CC (#1) and basic block destination (Op#4) are always
1021   // legal types.
1022   return SDValue(DAG.UpdateNodeOperands(N, N->getOperand(0),
1023                                 N->getOperand(1), LHS, RHS, N->getOperand(4)),
1024                  0);
1025 }
1026
1027 SDValue DAGTypeLegalizer::PromoteIntOp_BRCOND(SDNode *N, unsigned OpNo) {
1028   assert(OpNo == 1 && "only know how to promote condition");
1029
1030   // Promote all the way up to the canonical SetCC type.
1031   SDValue Cond = PromoteTargetBoolean(N->getOperand(1), MVT::Other);
1032
1033   // The chain (Op#0) and basic block destination (Op#2) are always legal types.
1034   return SDValue(DAG.UpdateNodeOperands(N, N->getOperand(0), Cond,
1035                                         N->getOperand(2)), 0);
1036 }
1037
1038 SDValue DAGTypeLegalizer::PromoteIntOp_BUILD_PAIR(SDNode *N) {
1039   // Since the result type is legal, the operands must promote to it.
1040   EVT OVT = N->getOperand(0).getValueType();
1041   SDValue Lo = ZExtPromotedInteger(N->getOperand(0));
1042   SDValue Hi = GetPromotedInteger(N->getOperand(1));
1043   assert(Lo.getValueType() == N->getValueType(0) && "Operand over promoted?");
1044   SDLoc dl(N);
1045
1046   Hi = DAG.getNode(ISD::SHL, dl, N->getValueType(0), Hi,
1047                    DAG.getConstant(OVT.getSizeInBits(), dl,
1048                                    TLI.getPointerTy(DAG.getDataLayout())));
1049   return DAG.getNode(ISD::OR, dl, N->getValueType(0), Lo, Hi);
1050 }
1051
1052 SDValue DAGTypeLegalizer::PromoteIntOp_BUILD_VECTOR(SDNode *N) {
1053   // The vector type is legal but the element type is not.  This implies
1054   // that the vector is a power-of-two in length and that the element
1055   // type does not have a strange size (eg: it is not i1).
1056   EVT VecVT = N->getValueType(0);
1057   unsigned NumElts = VecVT.getVectorNumElements();
1058   assert(!((NumElts & 1) && (!TLI.isTypeLegal(VecVT))) &&
1059          "Legal vector of one illegal element?");
1060
1061   // Promote the inserted value.  The type does not need to match the
1062   // vector element type.  Check that any extra bits introduced will be
1063   // truncated away.
1064   assert(N->getOperand(0).getValueSizeInBits() >=
1065          N->getValueType(0).getScalarSizeInBits() &&
1066          "Type of inserted value narrower than vector element type!");
1067
1068   SmallVector<SDValue, 16> NewOps;
1069   for (unsigned i = 0; i < NumElts; ++i)
1070     NewOps.push_back(GetPromotedInteger(N->getOperand(i)));
1071
1072   return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0);
1073 }
1074
1075 SDValue DAGTypeLegalizer::PromoteIntOp_INSERT_VECTOR_ELT(SDNode *N,
1076                                                          unsigned OpNo) {
1077   if (OpNo == 1) {
1078     // Promote the inserted value.  This is valid because the type does not
1079     // have to match the vector element type.
1080
1081     // Check that any extra bits introduced will be truncated away.
1082     assert(N->getOperand(1).getValueSizeInBits() >=
1083            N->getValueType(0).getScalarSizeInBits() &&
1084            "Type of inserted value narrower than vector element type!");
1085     return SDValue(DAG.UpdateNodeOperands(N, N->getOperand(0),
1086                                   GetPromotedInteger(N->getOperand(1)),
1087                                   N->getOperand(2)),
1088                    0);
1089   }
1090
1091   assert(OpNo == 2 && "Different operand and result vector types?");
1092
1093   // Promote the index.
1094   SDValue Idx = DAG.getZExtOrTrunc(N->getOperand(2), SDLoc(N),
1095                                    TLI.getVectorIdxTy(DAG.getDataLayout()));
1096   return SDValue(DAG.UpdateNodeOperands(N, N->getOperand(0),
1097                                 N->getOperand(1), Idx), 0);
1098 }
1099
1100 SDValue DAGTypeLegalizer::PromoteIntOp_SCALAR_TO_VECTOR(SDNode *N) {
1101   // Integer SCALAR_TO_VECTOR operands are implicitly truncated, so just promote
1102   // the operand in place.
1103   return SDValue(DAG.UpdateNodeOperands(N,
1104                                 GetPromotedInteger(N->getOperand(0))), 0);
1105 }
1106
1107 SDValue DAGTypeLegalizer::PromoteIntOp_SELECT(SDNode *N, unsigned OpNo) {
1108   assert(OpNo == 0 && "Only know how to promote the condition!");
1109   SDValue Cond = N->getOperand(0);
1110   EVT OpTy = N->getOperand(1).getValueType();
1111
1112   if (N->getOpcode() == ISD::VSELECT)
1113     if (SDValue Res = WidenVSELECTAndMask(N))
1114       return Res;
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, {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, {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)
2629       .setChain(Chain)
2630       .setLibCallee(TLI.getLibcallCallingConv(LC), RetTy, Func, std::move(Args))
2631       .setSExtResult();
2632
2633   std::pair<SDValue, SDValue> CallInfo = TLI.LowerCallTo(CLI);
2634
2635   SplitInteger(CallInfo.first, Lo, Hi);
2636   SDValue Temp2 =
2637       DAG.getLoad(PtrVT, dl, CallInfo.second, Temp, MachinePointerInfo());
2638   SDValue Ofl = DAG.getSetCC(dl, N->getValueType(1), Temp2,
2639                              DAG.getConstant(0, dl, PtrVT),
2640                              ISD::SETNE);
2641   // Use the overflow from the libcall everywhere.
2642   ReplaceValueWith(SDValue(N, 1), Ofl);
2643 }
2644
2645 void DAGTypeLegalizer::ExpandIntRes_UDIV(SDNode *N,
2646                                          SDValue &Lo, SDValue &Hi) {
2647   EVT VT = N->getValueType(0);
2648   SDLoc dl(N);
2649   SDValue Ops[2] = { N->getOperand(0), N->getOperand(1) };
2650
2651   if (TLI.getOperationAction(ISD::UDIVREM, VT) == TargetLowering::Custom) {
2652     SDValue Res = DAG.getNode(ISD::UDIVREM, dl, DAG.getVTList(VT, VT), Ops);
2653     SplitInteger(Res.getValue(0), Lo, Hi);
2654     return;
2655   }
2656
2657   RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
2658   if (VT == MVT::i16)
2659     LC = RTLIB::UDIV_I16;
2660   else if (VT == MVT::i32)
2661     LC = RTLIB::UDIV_I32;
2662   else if (VT == MVT::i64)
2663     LC = RTLIB::UDIV_I64;
2664   else if (VT == MVT::i128)
2665     LC = RTLIB::UDIV_I128;
2666   assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unsupported UDIV!");
2667
2668   SplitInteger(TLI.makeLibCall(DAG, LC, VT, Ops, false, dl).first, Lo, Hi);
2669 }
2670
2671 void DAGTypeLegalizer::ExpandIntRes_UREM(SDNode *N,
2672                                          SDValue &Lo, SDValue &Hi) {
2673   EVT VT = N->getValueType(0);
2674   SDLoc dl(N);
2675   SDValue Ops[2] = { N->getOperand(0), N->getOperand(1) };
2676
2677   if (TLI.getOperationAction(ISD::UDIVREM, VT) == TargetLowering::Custom) {
2678     SDValue Res = DAG.getNode(ISD::UDIVREM, dl, DAG.getVTList(VT, VT), Ops);
2679     SplitInteger(Res.getValue(1), Lo, Hi);
2680     return;
2681   }
2682
2683   RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
2684   if (VT == MVT::i16)
2685     LC = RTLIB::UREM_I16;
2686   else if (VT == MVT::i32)
2687     LC = RTLIB::UREM_I32;
2688   else if (VT == MVT::i64)
2689     LC = RTLIB::UREM_I64;
2690   else if (VT == MVT::i128)
2691     LC = RTLIB::UREM_I128;
2692   assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unsupported UREM!");
2693
2694   SplitInteger(TLI.makeLibCall(DAG, LC, VT, Ops, false, dl).first, Lo, Hi);
2695 }
2696
2697 void DAGTypeLegalizer::ExpandIntRes_ZERO_EXTEND(SDNode *N,
2698                                                 SDValue &Lo, SDValue &Hi) {
2699   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
2700   SDLoc dl(N);
2701   SDValue Op = N->getOperand(0);
2702   if (Op.getValueType().bitsLE(NVT)) {
2703     // The low part is zero extension of the input (degenerates to a copy).
2704     Lo = DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N->getOperand(0));
2705     Hi = DAG.getConstant(0, dl, NVT);   // The high part is just a zero.
2706   } else {
2707     // For example, extension of an i48 to an i64.  The operand type necessarily
2708     // promotes to the result type, so will end up being expanded too.
2709     assert(getTypeAction(Op.getValueType()) ==
2710            TargetLowering::TypePromoteInteger &&
2711            "Only know how to promote this result!");
2712     SDValue Res = GetPromotedInteger(Op);
2713     assert(Res.getValueType() == N->getValueType(0) &&
2714            "Operand over promoted?");
2715     // Split the promoted operand.  This will simplify when it is expanded.
2716     SplitInteger(Res, Lo, Hi);
2717     unsigned ExcessBits = Op.getValueSizeInBits() - NVT.getSizeInBits();
2718     Hi = DAG.getZeroExtendInReg(Hi, dl,
2719                                 EVT::getIntegerVT(*DAG.getContext(),
2720                                                   ExcessBits));
2721   }
2722 }
2723
2724 void DAGTypeLegalizer::ExpandIntRes_ATOMIC_LOAD(SDNode *N,
2725                                                 SDValue &Lo, SDValue &Hi) {
2726   SDLoc dl(N);
2727   EVT VT = cast<AtomicSDNode>(N)->getMemoryVT();
2728   SDVTList VTs = DAG.getVTList(VT, MVT::i1, MVT::Other);
2729   SDValue Zero = DAG.getConstant(0, dl, VT);
2730   SDValue Swap = DAG.getAtomicCmpSwap(
2731       ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, dl,
2732       cast<AtomicSDNode>(N)->getMemoryVT(), VTs, N->getOperand(0),
2733       N->getOperand(1), Zero, Zero, cast<AtomicSDNode>(N)->getMemOperand());
2734
2735   ReplaceValueWith(SDValue(N, 0), Swap.getValue(0));
2736   ReplaceValueWith(SDValue(N, 1), Swap.getValue(2));
2737 }
2738
2739 //===----------------------------------------------------------------------===//
2740 //  Integer Operand Expansion
2741 //===----------------------------------------------------------------------===//
2742
2743 /// ExpandIntegerOperand - This method is called when the specified operand of
2744 /// the specified node is found to need expansion.  At this point, all of the
2745 /// result types of the node are known to be legal, but other operands of the
2746 /// node may need promotion or expansion as well as the specified one.
2747 bool DAGTypeLegalizer::ExpandIntegerOperand(SDNode *N, unsigned OpNo) {
2748   DEBUG(dbgs() << "Expand integer operand: "; N->dump(&DAG); dbgs() << "\n");
2749   SDValue Res = SDValue();
2750
2751   if (CustomLowerNode(N, N->getOperand(OpNo).getValueType(), false))
2752     return false;
2753
2754   switch (N->getOpcode()) {
2755   default:
2756   #ifndef NDEBUG
2757     dbgs() << "ExpandIntegerOperand Op #" << OpNo << ": ";
2758     N->dump(&DAG); dbgs() << "\n";
2759   #endif
2760     llvm_unreachable("Do not know how to expand this operator's operand!");
2761
2762   case ISD::BITCAST:           Res = ExpandOp_BITCAST(N); break;
2763   case ISD::BR_CC:             Res = ExpandIntOp_BR_CC(N); break;
2764   case ISD::BUILD_VECTOR:      Res = ExpandOp_BUILD_VECTOR(N); break;
2765   case ISD::EXTRACT_ELEMENT:   Res = ExpandOp_EXTRACT_ELEMENT(N); break;
2766   case ISD::INSERT_VECTOR_ELT: Res = ExpandOp_INSERT_VECTOR_ELT(N); break;
2767   case ISD::SCALAR_TO_VECTOR:  Res = ExpandOp_SCALAR_TO_VECTOR(N); break;
2768   case ISD::SELECT_CC:         Res = ExpandIntOp_SELECT_CC(N); break;
2769   case ISD::SETCC:             Res = ExpandIntOp_SETCC(N); break;
2770   case ISD::SETCCE:            Res = ExpandIntOp_SETCCE(N); break;
2771   case ISD::SINT_TO_FP:        Res = ExpandIntOp_SINT_TO_FP(N); break;
2772   case ISD::STORE:   Res = ExpandIntOp_STORE(cast<StoreSDNode>(N), OpNo); break;
2773   case ISD::TRUNCATE:          Res = ExpandIntOp_TRUNCATE(N); break;
2774   case ISD::UINT_TO_FP:        Res = ExpandIntOp_UINT_TO_FP(N); break;
2775
2776   case ISD::SHL:
2777   case ISD::SRA:
2778   case ISD::SRL:
2779   case ISD::ROTL:
2780   case ISD::ROTR:              Res = ExpandIntOp_Shift(N); break;
2781   case ISD::RETURNADDR:
2782   case ISD::FRAMEADDR:         Res = ExpandIntOp_RETURNADDR(N); break;
2783
2784   case ISD::ATOMIC_STORE:      Res = ExpandIntOp_ATOMIC_STORE(N); break;
2785   }
2786
2787   // If the result is null, the sub-method took care of registering results etc.
2788   if (!Res.getNode()) return false;
2789
2790   // If the result is N, the sub-method updated N in place.  Tell the legalizer
2791   // core about this.
2792   if (Res.getNode() == N)
2793     return true;
2794
2795   assert(Res.getValueType() == N->getValueType(0) && N->getNumValues() == 1 &&
2796          "Invalid operand expansion");
2797
2798   ReplaceValueWith(SDValue(N, 0), Res);
2799   return false;
2800 }
2801
2802 /// IntegerExpandSetCCOperands - Expand the operands of a comparison.  This code
2803 /// is shared among BR_CC, SELECT_CC, and SETCC handlers.
2804 void DAGTypeLegalizer::IntegerExpandSetCCOperands(SDValue &NewLHS,
2805                                                   SDValue &NewRHS,
2806                                                   ISD::CondCode &CCCode,
2807                                                   const SDLoc &dl) {
2808   SDValue LHSLo, LHSHi, RHSLo, RHSHi;
2809   GetExpandedInteger(NewLHS, LHSLo, LHSHi);
2810   GetExpandedInteger(NewRHS, RHSLo, RHSHi);
2811
2812   if (CCCode == ISD::SETEQ || CCCode == ISD::SETNE) {
2813     if (RHSLo == RHSHi) {
2814       if (ConstantSDNode *RHSCST = dyn_cast<ConstantSDNode>(RHSLo)) {
2815         if (RHSCST->isAllOnesValue()) {
2816           // Equality comparison to -1.
2817           NewLHS = DAG.getNode(ISD::AND, dl,
2818                                LHSLo.getValueType(), LHSLo, LHSHi);
2819           NewRHS = RHSLo;
2820           return;
2821         }
2822       }
2823     }
2824
2825     NewLHS = DAG.getNode(ISD::XOR, dl, LHSLo.getValueType(), LHSLo, RHSLo);
2826     NewRHS = DAG.getNode(ISD::XOR, dl, LHSLo.getValueType(), LHSHi, RHSHi);
2827     NewLHS = DAG.getNode(ISD::OR, dl, NewLHS.getValueType(), NewLHS, NewRHS);
2828     NewRHS = DAG.getConstant(0, dl, NewLHS.getValueType());
2829     return;
2830   }
2831
2832   // If this is a comparison of the sign bit, just look at the top part.
2833   // X > -1,  x < 0
2834   if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(NewRHS))
2835     if ((CCCode == ISD::SETLT && CST->isNullValue()) ||     // X < 0
2836         (CCCode == ISD::SETGT && CST->isAllOnesValue())) {  // X > -1
2837       NewLHS = LHSHi;
2838       NewRHS = RHSHi;
2839       return;
2840     }
2841
2842   // FIXME: This generated code sucks.
2843   ISD::CondCode LowCC;
2844   switch (CCCode) {
2845   default: llvm_unreachable("Unknown integer setcc!");
2846   case ISD::SETLT:
2847   case ISD::SETULT: LowCC = ISD::SETULT; break;
2848   case ISD::SETGT:
2849   case ISD::SETUGT: LowCC = ISD::SETUGT; break;
2850   case ISD::SETLE:
2851   case ISD::SETULE: LowCC = ISD::SETULE; break;
2852   case ISD::SETGE:
2853   case ISD::SETUGE: LowCC = ISD::SETUGE; break;
2854   }
2855
2856   // LoCmp = lo(op1) < lo(op2)   // Always unsigned comparison
2857   // HiCmp = hi(op1) < hi(op2)   // Signedness depends on operands
2858   // dest  = hi(op1) == hi(op2) ? LoCmp : HiCmp;
2859
2860   // NOTE: on targets without efficient SELECT of bools, we can always use
2861   // this identity: (B1 ? B2 : B3) --> (B1 & B2)|(!B1&B3)
2862   TargetLowering::DAGCombinerInfo DagCombineInfo(DAG, AfterLegalizeTypes, true,
2863                                                  nullptr);
2864   SDValue LoCmp, HiCmp;
2865   if (TLI.isTypeLegal(LHSLo.getValueType()) &&
2866       TLI.isTypeLegal(RHSLo.getValueType()))
2867     LoCmp = TLI.SimplifySetCC(getSetCCResultType(LHSLo.getValueType()), LHSLo,
2868                               RHSLo, LowCC, false, DagCombineInfo, dl);
2869   if (!LoCmp.getNode())
2870     LoCmp = DAG.getSetCC(dl, getSetCCResultType(LHSLo.getValueType()), LHSLo,
2871                          RHSLo, LowCC);
2872   if (TLI.isTypeLegal(LHSHi.getValueType()) &&
2873       TLI.isTypeLegal(RHSHi.getValueType()))
2874     HiCmp = TLI.SimplifySetCC(getSetCCResultType(LHSHi.getValueType()), LHSHi,
2875                               RHSHi, CCCode, false, DagCombineInfo, dl);
2876   if (!HiCmp.getNode())
2877     HiCmp =
2878         DAG.getNode(ISD::SETCC, dl, getSetCCResultType(LHSHi.getValueType()),
2879                     LHSHi, RHSHi, DAG.getCondCode(CCCode));
2880
2881   ConstantSDNode *LoCmpC = dyn_cast<ConstantSDNode>(LoCmp.getNode());
2882   ConstantSDNode *HiCmpC = dyn_cast<ConstantSDNode>(HiCmp.getNode());
2883
2884   bool EqAllowed = (CCCode == ISD::SETLE || CCCode == ISD::SETGE ||
2885                     CCCode == ISD::SETUGE || CCCode == ISD::SETULE);
2886
2887   if ((EqAllowed && (HiCmpC && HiCmpC->isNullValue())) ||
2888       (!EqAllowed && ((HiCmpC && (HiCmpC->getAPIntValue() == 1)) ||
2889                       (LoCmpC && LoCmpC->isNullValue())))) {
2890     // For LE / GE, if high part is known false, ignore the low part.
2891     // For LT / GT: if low part is known false, return the high part.
2892     //              if high part is known true, ignore the low part.
2893     NewLHS = HiCmp;
2894     NewRHS = SDValue();
2895     return;
2896   }
2897
2898   if (LHSHi == RHSHi) {
2899     // Comparing the low bits is enough.
2900     NewLHS = LoCmp;
2901     NewRHS = SDValue();
2902     return;
2903   }
2904
2905   // Lower with SETCCE if the target supports it.
2906   // FIXME: Make all targets support this, then remove the other lowering.
2907   if (TLI.getOperationAction(
2908           ISD::SETCCE,
2909           TLI.getTypeToExpandTo(*DAG.getContext(), LHSLo.getValueType())) ==
2910       TargetLowering::Custom) {
2911     // SETCCE can detect < and >= directly. For > and <=, flip operands and
2912     // condition code.
2913     bool FlipOperands = false;
2914     switch (CCCode) {
2915     case ISD::SETGT:  CCCode = ISD::SETLT;  FlipOperands = true; break;
2916     case ISD::SETUGT: CCCode = ISD::SETULT; FlipOperands = true; break;
2917     case ISD::SETLE:  CCCode = ISD::SETGE;  FlipOperands = true; break;
2918     case ISD::SETULE: CCCode = ISD::SETUGE; FlipOperands = true; break;
2919     default: break;
2920     }
2921     if (FlipOperands) {
2922       std::swap(LHSLo, RHSLo);
2923       std::swap(LHSHi, RHSHi);
2924     }
2925     // Perform a wide subtraction, feeding the carry from the low part into
2926     // SETCCE. The SETCCE operation is essentially looking at the high part of
2927     // the result of LHS - RHS. It is negative iff LHS < RHS. It is zero or
2928     // positive iff LHS >= RHS.
2929     SDVTList VTList = DAG.getVTList(LHSLo.getValueType(), MVT::Glue);
2930     SDValue LowCmp = DAG.getNode(ISD::SUBC, dl, VTList, LHSLo, RHSLo);
2931     SDValue Res =
2932         DAG.getNode(ISD::SETCCE, dl, getSetCCResultType(LHSLo.getValueType()),
2933                     LHSHi, RHSHi, LowCmp.getValue(1), DAG.getCondCode(CCCode));
2934     NewLHS = Res;
2935     NewRHS = SDValue();
2936     return;
2937   }
2938
2939   NewLHS = TLI.SimplifySetCC(getSetCCResultType(LHSHi.getValueType()),
2940                              LHSHi, RHSHi, ISD::SETEQ, false,
2941                              DagCombineInfo, dl);
2942   if (!NewLHS.getNode())
2943     NewLHS = DAG.getSetCC(dl, getSetCCResultType(LHSHi.getValueType()),
2944                           LHSHi, RHSHi, ISD::SETEQ);
2945   NewLHS = DAG.getSelect(dl, LoCmp.getValueType(),
2946                          NewLHS, LoCmp, HiCmp);
2947   NewRHS = SDValue();
2948 }
2949
2950 SDValue DAGTypeLegalizer::ExpandIntOp_BR_CC(SDNode *N) {
2951   SDValue NewLHS = N->getOperand(2), NewRHS = N->getOperand(3);
2952   ISD::CondCode CCCode = cast<CondCodeSDNode>(N->getOperand(1))->get();
2953   IntegerExpandSetCCOperands(NewLHS, NewRHS, CCCode, SDLoc(N));
2954
2955   // If ExpandSetCCOperands returned a scalar, we need to compare the result
2956   // against zero to select between true and false values.
2957   if (!NewRHS.getNode()) {
2958     NewRHS = DAG.getConstant(0, SDLoc(N), NewLHS.getValueType());
2959     CCCode = ISD::SETNE;
2960   }
2961
2962   // Update N to have the operands specified.
2963   return SDValue(DAG.UpdateNodeOperands(N, N->getOperand(0),
2964                                 DAG.getCondCode(CCCode), NewLHS, NewRHS,
2965                                 N->getOperand(4)), 0);
2966 }
2967
2968 SDValue DAGTypeLegalizer::ExpandIntOp_SELECT_CC(SDNode *N) {
2969   SDValue NewLHS = N->getOperand(0), NewRHS = N->getOperand(1);
2970   ISD::CondCode CCCode = cast<CondCodeSDNode>(N->getOperand(4))->get();
2971   IntegerExpandSetCCOperands(NewLHS, NewRHS, CCCode, SDLoc(N));
2972
2973   // If ExpandSetCCOperands returned a scalar, we need to compare the result
2974   // against zero to select between true and false values.
2975   if (!NewRHS.getNode()) {
2976     NewRHS = DAG.getConstant(0, SDLoc(N), NewLHS.getValueType());
2977     CCCode = ISD::SETNE;
2978   }
2979
2980   // Update N to have the operands specified.
2981   return SDValue(DAG.UpdateNodeOperands(N, NewLHS, NewRHS,
2982                                 N->getOperand(2), N->getOperand(3),
2983                                 DAG.getCondCode(CCCode)), 0);
2984 }
2985
2986 SDValue DAGTypeLegalizer::ExpandIntOp_SETCC(SDNode *N) {
2987   SDValue NewLHS = N->getOperand(0), NewRHS = N->getOperand(1);
2988   ISD::CondCode CCCode = cast<CondCodeSDNode>(N->getOperand(2))->get();
2989   IntegerExpandSetCCOperands(NewLHS, NewRHS, CCCode, SDLoc(N));
2990
2991   // If ExpandSetCCOperands returned a scalar, use it.
2992   if (!NewRHS.getNode()) {
2993     assert(NewLHS.getValueType() == N->getValueType(0) &&
2994            "Unexpected setcc expansion!");
2995     return NewLHS;
2996   }
2997
2998   // Otherwise, update N to have the operands specified.
2999   return SDValue(DAG.UpdateNodeOperands(N, NewLHS, NewRHS,
3000                                 DAG.getCondCode(CCCode)), 0);
3001 }
3002
3003 SDValue DAGTypeLegalizer::ExpandIntOp_SETCCE(SDNode *N) {
3004   SDValue LHS = N->getOperand(0);
3005   SDValue RHS = N->getOperand(1);
3006   SDValue Carry = N->getOperand(2);
3007   SDValue Cond = N->getOperand(3);
3008   SDLoc dl = SDLoc(N);
3009
3010   SDValue LHSLo, LHSHi, RHSLo, RHSHi;
3011   GetExpandedInteger(LHS, LHSLo, LHSHi);
3012   GetExpandedInteger(RHS, RHSLo, RHSHi);
3013
3014   // Expand to a SUBE for the low part and a smaller SETCCE for the high.
3015   SDVTList VTList = DAG.getVTList(LHSLo.getValueType(), MVT::Glue);
3016   SDValue LowCmp = DAG.getNode(ISD::SUBE, dl, VTList, LHSLo, RHSLo, Carry);
3017   return DAG.getNode(ISD::SETCCE, dl, N->getValueType(0), LHSHi, RHSHi,
3018                      LowCmp.getValue(1), Cond);
3019 }
3020
3021 SDValue DAGTypeLegalizer::ExpandIntOp_Shift(SDNode *N) {
3022   // The value being shifted is legal, but the shift amount is too big.
3023   // It follows that either the result of the shift is undefined, or the
3024   // upper half of the shift amount is zero.  Just use the lower half.
3025   SDValue Lo, Hi;
3026   GetExpandedInteger(N->getOperand(1), Lo, Hi);
3027   return SDValue(DAG.UpdateNodeOperands(N, N->getOperand(0), Lo), 0);
3028 }
3029
3030 SDValue DAGTypeLegalizer::ExpandIntOp_RETURNADDR(SDNode *N) {
3031   // The argument of RETURNADDR / FRAMEADDR builtin is 32 bit contant.  This
3032   // surely makes pretty nice problems on 8/16 bit targets. Just truncate this
3033   // constant to valid type.
3034   SDValue Lo, Hi;
3035   GetExpandedInteger(N->getOperand(0), Lo, Hi);
3036   return SDValue(DAG.UpdateNodeOperands(N, Lo), 0);
3037 }
3038
3039 SDValue DAGTypeLegalizer::ExpandIntOp_SINT_TO_FP(SDNode *N) {
3040   SDValue Op = N->getOperand(0);
3041   EVT DstVT = N->getValueType(0);
3042   RTLIB::Libcall LC = RTLIB::getSINTTOFP(Op.getValueType(), DstVT);
3043   assert(LC != RTLIB::UNKNOWN_LIBCALL &&
3044          "Don't know how to expand this SINT_TO_FP!");
3045   return TLI.makeLibCall(DAG, LC, DstVT, Op, true, SDLoc(N)).first;
3046 }
3047
3048 SDValue DAGTypeLegalizer::ExpandIntOp_STORE(StoreSDNode *N, unsigned OpNo) {
3049   if (ISD::isNormalStore(N))
3050     return ExpandOp_NormalStore(N, OpNo);
3051
3052   assert(ISD::isUNINDEXEDStore(N) && "Indexed store during type legalization!");
3053   assert(OpNo == 1 && "Can only expand the stored value so far");
3054
3055   EVT VT = N->getOperand(1).getValueType();
3056   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), VT);
3057   SDValue Ch  = N->getChain();
3058   SDValue Ptr = N->getBasePtr();
3059   unsigned Alignment = N->getAlignment();
3060   MachineMemOperand::Flags MMOFlags = N->getMemOperand()->getFlags();
3061   AAMDNodes AAInfo = N->getAAInfo();
3062   SDLoc dl(N);
3063   SDValue Lo, Hi;
3064
3065   assert(NVT.isByteSized() && "Expanded type not byte sized!");
3066
3067   if (N->getMemoryVT().bitsLE(NVT)) {
3068     GetExpandedInteger(N->getValue(), Lo, Hi);
3069     return DAG.getTruncStore(Ch, dl, Lo, Ptr, N->getPointerInfo(),
3070                              N->getMemoryVT(), Alignment, MMOFlags, AAInfo);
3071   }
3072
3073   if (DAG.getDataLayout().isLittleEndian()) {
3074     // Little-endian - low bits are at low addresses.
3075     GetExpandedInteger(N->getValue(), Lo, Hi);
3076
3077     Lo = DAG.getStore(Ch, dl, Lo, Ptr, N->getPointerInfo(), Alignment, MMOFlags,
3078                       AAInfo);
3079
3080     unsigned ExcessBits =
3081       N->getMemoryVT().getSizeInBits() - NVT.getSizeInBits();
3082     EVT NEVT = EVT::getIntegerVT(*DAG.getContext(), ExcessBits);
3083
3084     // Increment the pointer to the other half.
3085     unsigned IncrementSize = NVT.getSizeInBits()/8;
3086     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
3087                       DAG.getConstant(IncrementSize, dl, Ptr.getValueType()));
3088     Hi = DAG.getTruncStore(
3089         Ch, dl, Hi, Ptr, N->getPointerInfo().getWithOffset(IncrementSize), NEVT,
3090         MinAlign(Alignment, IncrementSize), MMOFlags, AAInfo);
3091     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo, Hi);
3092   }
3093
3094   // Big-endian - high bits are at low addresses.  Favor aligned stores at
3095   // the cost of some bit-fiddling.
3096   GetExpandedInteger(N->getValue(), Lo, Hi);
3097
3098   EVT ExtVT = N->getMemoryVT();
3099   unsigned EBytes = ExtVT.getStoreSize();
3100   unsigned IncrementSize = NVT.getSizeInBits()/8;
3101   unsigned ExcessBits = (EBytes - IncrementSize)*8;
3102   EVT HiVT = EVT::getIntegerVT(*DAG.getContext(),
3103                                ExtVT.getSizeInBits() - ExcessBits);
3104
3105   if (ExcessBits < NVT.getSizeInBits()) {
3106     // Transfer high bits from the top of Lo to the bottom of Hi.
3107     Hi = DAG.getNode(ISD::SHL, dl, NVT, Hi,
3108                      DAG.getConstant(NVT.getSizeInBits() - ExcessBits, dl,
3109                                      TLI.getPointerTy(DAG.getDataLayout())));
3110     Hi = DAG.getNode(
3111         ISD::OR, dl, NVT, Hi,
3112         DAG.getNode(ISD::SRL, dl, NVT, Lo,
3113                     DAG.getConstant(ExcessBits, dl,
3114                                     TLI.getPointerTy(DAG.getDataLayout()))));
3115   }
3116
3117   // Store both the high bits and maybe some of the low bits.
3118   Hi = DAG.getTruncStore(Ch, dl, Hi, Ptr, N->getPointerInfo(), HiVT, Alignment,
3119                          MMOFlags, AAInfo);
3120
3121   // Increment the pointer to the other half.
3122   Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
3123                     DAG.getConstant(IncrementSize, dl, Ptr.getValueType()));
3124   // Store the lowest ExcessBits bits in the second half.
3125   Lo = DAG.getTruncStore(Ch, dl, Lo, Ptr,
3126                          N->getPointerInfo().getWithOffset(IncrementSize),
3127                          EVT::getIntegerVT(*DAG.getContext(), ExcessBits),
3128                          MinAlign(Alignment, IncrementSize), MMOFlags, AAInfo);
3129   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo, Hi);
3130 }
3131
3132 SDValue DAGTypeLegalizer::ExpandIntOp_TRUNCATE(SDNode *N) {
3133   SDValue InL, InH;
3134   GetExpandedInteger(N->getOperand(0), InL, InH);
3135   // Just truncate the low part of the source.
3136   return DAG.getNode(ISD::TRUNCATE, SDLoc(N), N->getValueType(0), InL);
3137 }
3138
3139 SDValue DAGTypeLegalizer::ExpandIntOp_UINT_TO_FP(SDNode *N) {
3140   SDValue Op = N->getOperand(0);
3141   EVT SrcVT = Op.getValueType();
3142   EVT DstVT = N->getValueType(0);
3143   SDLoc dl(N);
3144
3145   // The following optimization is valid only if every value in SrcVT (when
3146   // treated as signed) is representable in DstVT.  Check that the mantissa
3147   // size of DstVT is >= than the number of bits in SrcVT -1.
3148   const fltSemantics &sem = DAG.EVTToAPFloatSemantics(DstVT);
3149   if (APFloat::semanticsPrecision(sem) >= SrcVT.getSizeInBits()-1 &&
3150       TLI.getOperationAction(ISD::SINT_TO_FP, SrcVT) == TargetLowering::Custom){
3151     // Do a signed conversion then adjust the result.
3152     SDValue SignedConv = DAG.getNode(ISD::SINT_TO_FP, dl, DstVT, Op);
3153     SignedConv = TLI.LowerOperation(SignedConv, DAG);
3154
3155     // The result of the signed conversion needs adjusting if the 'sign bit' of
3156     // the incoming integer was set.  To handle this, we dynamically test to see
3157     // if it is set, and, if so, add a fudge factor.
3158
3159     const uint64_t F32TwoE32  = 0x4F800000ULL;
3160     const uint64_t F32TwoE64  = 0x5F800000ULL;
3161     const uint64_t F32TwoE128 = 0x7F800000ULL;
3162
3163     APInt FF(32, 0);
3164     if (SrcVT == MVT::i32)
3165       FF = APInt(32, F32TwoE32);
3166     else if (SrcVT == MVT::i64)
3167       FF = APInt(32, F32TwoE64);
3168     else if (SrcVT == MVT::i128)
3169       FF = APInt(32, F32TwoE128);
3170     else
3171       llvm_unreachable("Unsupported UINT_TO_FP!");
3172
3173     // Check whether the sign bit is set.
3174     SDValue Lo, Hi;
3175     GetExpandedInteger(Op, Lo, Hi);
3176     SDValue SignSet = DAG.getSetCC(dl,
3177                                    getSetCCResultType(Hi.getValueType()),
3178                                    Hi,
3179                                    DAG.getConstant(0, dl, Hi.getValueType()),
3180                                    ISD::SETLT);
3181
3182     // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
3183     SDValue FudgePtr =
3184         DAG.getConstantPool(ConstantInt::get(*DAG.getContext(), FF.zext(64)),
3185                             TLI.getPointerTy(DAG.getDataLayout()));
3186
3187     // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
3188     SDValue Zero = DAG.getIntPtrConstant(0, dl);
3189     SDValue Four = DAG.getIntPtrConstant(4, dl);
3190     if (DAG.getDataLayout().isBigEndian())
3191       std::swap(Zero, Four);
3192     SDValue Offset = DAG.getSelect(dl, Zero.getValueType(), SignSet,
3193                                    Zero, Four);
3194     unsigned Alignment = cast<ConstantPoolSDNode>(FudgePtr)->getAlignment();
3195     FudgePtr = DAG.getNode(ISD::ADD, dl, FudgePtr.getValueType(),
3196                            FudgePtr, Offset);
3197     Alignment = std::min(Alignment, 4u);
3198
3199     // Load the value out, extending it from f32 to the destination float type.
3200     // FIXME: Avoid the extend by constructing the right constant pool?
3201     SDValue Fudge = DAG.getExtLoad(
3202         ISD::EXTLOAD, dl, DstVT, DAG.getEntryNode(), FudgePtr,
3203         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), MVT::f32,
3204         Alignment);
3205     return DAG.getNode(ISD::FADD, dl, DstVT, SignedConv, Fudge);
3206   }
3207
3208   // Otherwise, use a libcall.
3209   RTLIB::Libcall LC = RTLIB::getUINTTOFP(SrcVT, DstVT);
3210   assert(LC != RTLIB::UNKNOWN_LIBCALL &&
3211          "Don't know how to expand this UINT_TO_FP!");
3212   return TLI.makeLibCall(DAG, LC, DstVT, Op, true, dl).first;
3213 }
3214
3215 SDValue DAGTypeLegalizer::ExpandIntOp_ATOMIC_STORE(SDNode *N) {
3216   SDLoc dl(N);
3217   SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
3218                                cast<AtomicSDNode>(N)->getMemoryVT(),
3219                                N->getOperand(0),
3220                                N->getOperand(1), N->getOperand(2),
3221                                cast<AtomicSDNode>(N)->getMemOperand());
3222   return Swap.getValue(1);
3223 }
3224
3225
3226 SDValue DAGTypeLegalizer::PromoteIntRes_EXTRACT_SUBVECTOR(SDNode *N) {
3227   SDValue InOp0 = N->getOperand(0);
3228   EVT InVT = InOp0.getValueType();
3229
3230   EVT OutVT = N->getValueType(0);
3231   EVT NOutVT = TLI.getTypeToTransformTo(*DAG.getContext(), OutVT);
3232   assert(NOutVT.isVector() && "This type must be promoted to a vector type");
3233   unsigned OutNumElems = OutVT.getVectorNumElements();
3234   EVT NOutVTElem = NOutVT.getVectorElementType();
3235
3236   SDLoc dl(N);
3237   SDValue BaseIdx = N->getOperand(1);
3238
3239   SmallVector<SDValue, 8> Ops;
3240   Ops.reserve(OutNumElems);
3241   for (unsigned i = 0; i != OutNumElems; ++i) {
3242
3243     // Extract the element from the original vector.
3244     SDValue Index = DAG.getNode(ISD::ADD, dl, BaseIdx.getValueType(),
3245       BaseIdx, DAG.getConstant(i, dl, BaseIdx.getValueType()));
3246     SDValue Ext = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
3247       InVT.getVectorElementType(), N->getOperand(0), Index);
3248
3249     SDValue Op = DAG.getNode(ISD::ANY_EXTEND, dl, NOutVTElem, Ext);
3250     // Insert the converted element to the new vector.
3251     Ops.push_back(Op);
3252   }
3253
3254   return DAG.getBuildVector(NOutVT, dl, Ops);
3255 }
3256
3257
3258 SDValue DAGTypeLegalizer::PromoteIntRes_VECTOR_SHUFFLE(SDNode *N) {
3259   ShuffleVectorSDNode *SV = cast<ShuffleVectorSDNode>(N);
3260   EVT VT = N->getValueType(0);
3261   SDLoc dl(N);
3262
3263   ArrayRef<int> NewMask = SV->getMask().slice(0, VT.getVectorNumElements());
3264
3265   SDValue V0 = GetPromotedInteger(N->getOperand(0));
3266   SDValue V1 = GetPromotedInteger(N->getOperand(1));
3267   EVT OutVT = V0.getValueType();
3268
3269   return DAG.getVectorShuffle(OutVT, dl, V0, V1, NewMask);
3270 }
3271
3272
3273 SDValue DAGTypeLegalizer::PromoteIntRes_BUILD_VECTOR(SDNode *N) {
3274   EVT OutVT = N->getValueType(0);
3275   EVT NOutVT = TLI.getTypeToTransformTo(*DAG.getContext(), OutVT);
3276   assert(NOutVT.isVector() && "This type must be promoted to a vector type");
3277   unsigned NumElems = N->getNumOperands();
3278   EVT NOutVTElem = NOutVT.getVectorElementType();
3279
3280   SDLoc dl(N);
3281
3282   SmallVector<SDValue, 8> Ops;
3283   Ops.reserve(NumElems);
3284   for (unsigned i = 0; i != NumElems; ++i) {
3285     SDValue Op;
3286     // BUILD_VECTOR integer operand types are allowed to be larger than the
3287     // result's element type. This may still be true after the promotion. For
3288     // example, we might be promoting (<v?i1> = BV <i32>, <i32>, ...) to
3289     // (v?i16 = BV <i32>, <i32>, ...), and we can't any_extend <i32> to <i16>.
3290     if (N->getOperand(i).getValueType().bitsLT(NOutVTElem))
3291       Op = DAG.getNode(ISD::ANY_EXTEND, dl, NOutVTElem, N->getOperand(i));
3292     else
3293       Op = N->getOperand(i);
3294     Ops.push_back(Op);
3295   }
3296
3297   return DAG.getBuildVector(NOutVT, dl, Ops);
3298 }
3299
3300 SDValue DAGTypeLegalizer::PromoteIntRes_SCALAR_TO_VECTOR(SDNode *N) {
3301
3302   SDLoc dl(N);
3303
3304   assert(!N->getOperand(0).getValueType().isVector() &&
3305          "Input must be a scalar");
3306
3307   EVT OutVT = N->getValueType(0);
3308   EVT NOutVT = TLI.getTypeToTransformTo(*DAG.getContext(), OutVT);
3309   assert(NOutVT.isVector() && "This type must be promoted to a vector type");
3310   EVT NOutVTElem = NOutVT.getVectorElementType();
3311
3312   SDValue Op = DAG.getNode(ISD::ANY_EXTEND, dl, NOutVTElem, N->getOperand(0));
3313
3314   return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NOutVT, Op);
3315 }
3316
3317 SDValue DAGTypeLegalizer::PromoteIntRes_CONCAT_VECTORS(SDNode *N) {
3318   SDLoc dl(N);
3319
3320   EVT OutVT = N->getValueType(0);
3321   EVT NOutVT = TLI.getTypeToTransformTo(*DAG.getContext(), OutVT);
3322   assert(NOutVT.isVector() && "This type must be promoted to a vector type");
3323
3324   EVT InElemTy = OutVT.getVectorElementType();
3325   EVT OutElemTy = NOutVT.getVectorElementType();
3326
3327   unsigned NumElem = N->getOperand(0).getValueType().getVectorNumElements();
3328   unsigned NumOutElem = NOutVT.getVectorNumElements();
3329   unsigned NumOperands = N->getNumOperands();
3330   assert(NumElem * NumOperands == NumOutElem &&
3331          "Unexpected number of elements");
3332
3333   // Take the elements from the first vector.
3334   SmallVector<SDValue, 8> Ops(NumOutElem);
3335   for (unsigned i = 0; i < NumOperands; ++i) {
3336     SDValue Op = N->getOperand(i);
3337     for (unsigned j = 0; j < NumElem; ++j) {
3338       SDValue Ext = DAG.getNode(
3339           ISD::EXTRACT_VECTOR_ELT, dl, InElemTy, Op,
3340           DAG.getConstant(j, dl, TLI.getVectorIdxTy(DAG.getDataLayout())));
3341       Ops[i * NumElem + j] = DAG.getNode(ISD::ANY_EXTEND, dl, OutElemTy, Ext);
3342     }
3343   }
3344
3345   return DAG.getBuildVector(NOutVT, dl, Ops);
3346 }
3347
3348 SDValue DAGTypeLegalizer::PromoteIntRes_EXTEND_VECTOR_INREG(SDNode *N) {
3349   EVT VT = N->getValueType(0);
3350   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), VT);
3351   assert(NVT.isVector() && "This type must be promoted to a vector type");
3352
3353   SDLoc dl(N);
3354
3355   // For operands whose TypeAction is to promote, extend the promoted node
3356   // appropriately (ZERO_EXTEND or SIGN_EXTEND) from the original pre-promotion
3357   // type, and then construct a new *_EXTEND_VECTOR_INREG node to the promote-to
3358   // type..
3359   if (getTypeAction(N->getOperand(0).getValueType())
3360       == TargetLowering::TypePromoteInteger) {
3361     SDValue Promoted;
3362
3363     switch(N->getOpcode()) {
3364       case ISD::SIGN_EXTEND_VECTOR_INREG:
3365         Promoted = SExtPromotedInteger(N->getOperand(0));
3366         break;
3367       case ISD::ZERO_EXTEND_VECTOR_INREG:
3368         Promoted = ZExtPromotedInteger(N->getOperand(0));
3369         break;
3370       case ISD::ANY_EXTEND_VECTOR_INREG:
3371         Promoted = GetPromotedInteger(N->getOperand(0));
3372         break;
3373       default:
3374         llvm_unreachable("Node has unexpected Opcode");
3375     }
3376     return DAG.getNode(N->getOpcode(), dl, NVT, Promoted);
3377   }
3378
3379   // Directly extend to the appropriate transform-to type.
3380   return DAG.getNode(N->getOpcode(), dl, NVT, N->getOperand(0));
3381 }
3382
3383 SDValue DAGTypeLegalizer::PromoteIntRes_INSERT_VECTOR_ELT(SDNode *N) {
3384   EVT OutVT = N->getValueType(0);
3385   EVT NOutVT = TLI.getTypeToTransformTo(*DAG.getContext(), OutVT);
3386   assert(NOutVT.isVector() && "This type must be promoted to a vector type");
3387
3388   EVT NOutVTElem = NOutVT.getVectorElementType();
3389
3390   SDLoc dl(N);
3391   SDValue V0 = GetPromotedInteger(N->getOperand(0));
3392
3393   SDValue ConvElem = DAG.getNode(ISD::ANY_EXTEND, dl,
3394     NOutVTElem, N->getOperand(1));
3395   return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, NOutVT,
3396     V0, ConvElem, N->getOperand(2));
3397 }
3398
3399 SDValue DAGTypeLegalizer::PromoteIntOp_EXTRACT_VECTOR_ELT(SDNode *N) {
3400   SDLoc dl(N);
3401   SDValue V0 = GetPromotedInteger(N->getOperand(0));
3402   SDValue V1 = DAG.getZExtOrTrunc(N->getOperand(1), dl,
3403                                   TLI.getVectorIdxTy(DAG.getDataLayout()));
3404   SDValue Ext = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
3405     V0->getValueType(0).getScalarType(), V0, V1);
3406
3407   // EXTRACT_VECTOR_ELT can return types which are wider than the incoming
3408   // element types. If this is the case then we need to expand the outgoing
3409   // value and not truncate it.
3410   return DAG.getAnyExtOrTrunc(Ext, dl, N->getValueType(0));
3411 }
3412
3413 SDValue DAGTypeLegalizer::PromoteIntOp_EXTRACT_SUBVECTOR(SDNode *N) {
3414   SDLoc dl(N);
3415   SDValue V0 = GetPromotedInteger(N->getOperand(0));
3416   MVT InVT = V0.getValueType().getSimpleVT();
3417   MVT OutVT = MVT::getVectorVT(InVT.getVectorElementType(),
3418                                N->getValueType(0).getVectorNumElements());
3419   SDValue Ext = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, OutVT, V0, N->getOperand(1));
3420   return DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), Ext);
3421 }
3422
3423 SDValue DAGTypeLegalizer::PromoteIntOp_CONCAT_VECTORS(SDNode *N) {
3424   SDLoc dl(N);
3425   unsigned NumElems = N->getNumOperands();
3426
3427   EVT RetSclrTy = N->getValueType(0).getVectorElementType();
3428
3429   SmallVector<SDValue, 8> NewOps;
3430   NewOps.reserve(NumElems);
3431
3432   // For each incoming vector
3433   for (unsigned VecIdx = 0; VecIdx != NumElems; ++VecIdx) {
3434     SDValue Incoming = GetPromotedInteger(N->getOperand(VecIdx));
3435     EVT SclrTy = Incoming->getValueType(0).getVectorElementType();
3436     unsigned NumElem = Incoming->getValueType(0).getVectorNumElements();
3437
3438     for (unsigned i=0; i<NumElem; ++i) {
3439       // Extract element from incoming vector
3440       SDValue Ex = DAG.getNode(
3441           ISD::EXTRACT_VECTOR_ELT, dl, SclrTy, Incoming,
3442           DAG.getConstant(i, dl, TLI.getVectorIdxTy(DAG.getDataLayout())));
3443       SDValue Tr = DAG.getNode(ISD::TRUNCATE, dl, RetSclrTy, Ex);
3444       NewOps.push_back(Tr);
3445     }
3446   }
3447
3448   return DAG.getBuildVector(N->getValueType(0), dl, NewOps);
3449 }