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