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