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