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