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