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