Allow targets to legalize operations (with illegal operands) that produces multiple...
[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 Result = SDValue();
35
36   // See if the target wants to custom expand this node.
37   if (CustomLowerResults(N, 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:  Result = PromoteIntRes_AssertSext(N); break;
49   case ISD::AssertZext:  Result = PromoteIntRes_AssertZext(N); break;
50   case ISD::BIT_CONVERT: Result = PromoteIntRes_BIT_CONVERT(N); break;
51   case ISD::BSWAP:       Result = PromoteIntRes_BSWAP(N); break;
52   case ISD::BUILD_PAIR:  Result = PromoteIntRes_BUILD_PAIR(N); break;
53   case ISD::Constant:    Result = PromoteIntRes_Constant(N); break;
54   case ISD::CONVERT_RNDSAT:
55                          Result = PromoteIntRes_CONVERT_RNDSAT(N); break;
56   case ISD::CTLZ:        Result = PromoteIntRes_CTLZ(N); break;
57   case ISD::CTPOP:       Result = PromoteIntRes_CTPOP(N); break;
58   case ISD::CTTZ:        Result = PromoteIntRes_CTTZ(N); break;
59   case ISD::EXTRACT_VECTOR_ELT:
60                          Result = PromoteIntRes_EXTRACT_VECTOR_ELT(N); break;
61   case ISD::LOAD:        Result = PromoteIntRes_LOAD(cast<LoadSDNode>(N));break;
62   case ISD::SELECT:      Result = PromoteIntRes_SELECT(N); break;
63   case ISD::SELECT_CC:   Result = PromoteIntRes_SELECT_CC(N); break;
64   case ISD::SETCC:       Result = PromoteIntRes_SETCC(N); break;
65   case ISD::SHL:         Result = PromoteIntRes_SHL(N); break;
66   case ISD::SIGN_EXTEND_INREG:
67                          Result = PromoteIntRes_SIGN_EXTEND_INREG(N); break;
68   case ISD::SRA:         Result = PromoteIntRes_SRA(N); break;
69   case ISD::SRL:         Result = PromoteIntRes_SRL(N); break;
70   case ISD::TRUNCATE:    Result = PromoteIntRes_TRUNCATE(N); break;
71   case ISD::UNDEF:       Result = PromoteIntRes_UNDEF(N); break;
72   case ISD::VAARG:       Result = PromoteIntRes_VAARG(N); break;
73
74   case ISD::SIGN_EXTEND:
75   case ISD::ZERO_EXTEND:
76   case ISD::ANY_EXTEND:  Result = PromoteIntRes_INT_EXTEND(N); break;
77
78   case ISD::FP_TO_SINT:
79   case ISD::FP_TO_UINT:  Result = 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:         Result = PromoteIntRes_SimpleIntBinOp(N); break;
87
88   case ISD::SDIV:
89   case ISD::SREM:        Result = PromoteIntRes_SDIV(N); break;
90
91   case ISD::UDIV:
92   case ISD::UREM:        Result = PromoteIntRes_UDIV(N); break;
93
94   case ISD::SADDO:
95   case ISD::SSUBO:       Result = PromoteIntRes_SADDSUBO(N, ResNo); break;
96   case ISD::UADDO:
97   case ISD::USUBO:       Result = PromoteIntRes_UADDSUBO(N, ResNo); break;
98   case ISD::SMULO:
99   case ISD::UMULO:       Result = 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     Result = PromoteIntRes_Atomic1(cast<AtomicSDNode>(N)); break;
113
114   case ISD::ATOMIC_CMP_SWAP:
115     Result = PromoteIntRes_Atomic2(cast<AtomicSDNode>(N)); break;
116   }
117
118   // If Result is null, the sub-method took care of registering the result.
119   if (Result.getNode())
120     SetPromotedInteger(SDValue(N, ResNo), Result);
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.isOperationLegal(ISD::FP_TO_UINT, NVT) &&
349       TLI.isOperationLegal(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, OpNo, 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, 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.isOperationLegal(ISD::ADDC, TLI.getTypeToExpandTo(NVT))) {
1012       // Emit this X << 1 as X+X.
1013       SDVTList VTList = DAG.getVTList(NVT, MVT::Flag);
1014       SDValue LoOps[2] = { InL, InL };
1015       Lo = DAG.getNode(ISD::ADDC, VTList, LoOps, 2);
1016       SDValue HiOps[3] = { InH, InH, Lo.getValue(1) };
1017       Hi = DAG.getNode(ISD::ADDE, VTList, HiOps, 3);
1018     } else {
1019       Lo = DAG.getNode(ISD::SHL, NVT, InL, DAG.getConstant(Amt, ShTy));
1020       Hi = DAG.getNode(ISD::OR, NVT,
1021                        DAG.getNode(ISD::SHL, NVT, InH,
1022                                    DAG.getConstant(Amt, ShTy)),
1023                        DAG.getNode(ISD::SRL, NVT, InL,
1024                                    DAG.getConstant(NVTBits-Amt, ShTy)));
1025     }
1026     return;
1027   }
1028
1029   if (N->getOpcode() == ISD::SRL) {
1030     if (Amt > VTBits) {
1031       Lo = DAG.getConstant(0, NVT);
1032       Hi = DAG.getConstant(0, NVT);
1033     } else if (Amt > NVTBits) {
1034       Lo = DAG.getNode(ISD::SRL, NVT, InH, DAG.getConstant(Amt-NVTBits,ShTy));
1035       Hi = DAG.getConstant(0, NVT);
1036     } else if (Amt == NVTBits) {
1037       Lo = InH;
1038       Hi = DAG.getConstant(0, NVT);
1039     } else {
1040       Lo = DAG.getNode(ISD::OR, NVT,
1041                        DAG.getNode(ISD::SRL, NVT, InL,
1042                                    DAG.getConstant(Amt, ShTy)),
1043                        DAG.getNode(ISD::SHL, NVT, InH,
1044                                    DAG.getConstant(NVTBits-Amt, ShTy)));
1045       Hi = DAG.getNode(ISD::SRL, NVT, InH, DAG.getConstant(Amt, ShTy));
1046     }
1047     return;
1048   }
1049
1050   assert(N->getOpcode() == ISD::SRA && "Unknown shift!");
1051   if (Amt > VTBits) {
1052     Hi = Lo = DAG.getNode(ISD::SRA, NVT, InH,
1053                           DAG.getConstant(NVTBits-1, ShTy));
1054   } else if (Amt > NVTBits) {
1055     Lo = DAG.getNode(ISD::SRA, NVT, InH,
1056                      DAG.getConstant(Amt-NVTBits, ShTy));
1057     Hi = DAG.getNode(ISD::SRA, NVT, InH,
1058                      DAG.getConstant(NVTBits-1, ShTy));
1059   } else if (Amt == NVTBits) {
1060     Lo = InH;
1061     Hi = DAG.getNode(ISD::SRA, NVT, InH,
1062                      DAG.getConstant(NVTBits-1, ShTy));
1063   } else {
1064     Lo = DAG.getNode(ISD::OR, NVT,
1065                      DAG.getNode(ISD::SRL, NVT, InL,
1066                                  DAG.getConstant(Amt, ShTy)),
1067                      DAG.getNode(ISD::SHL, NVT, InH,
1068                                  DAG.getConstant(NVTBits-Amt, ShTy)));
1069     Hi = DAG.getNode(ISD::SRA, NVT, InH, DAG.getConstant(Amt, ShTy));
1070   }
1071 }
1072
1073 /// ExpandShiftWithKnownAmountBit - Try to determine whether we can simplify
1074 /// this shift based on knowledge of the high bit of the shift amount.  If we
1075 /// can tell this, we know that it is >= 32 or < 32, without knowing the actual
1076 /// shift amount.
1077 bool DAGTypeLegalizer::
1078 ExpandShiftWithKnownAmountBit(SDNode *N, SDValue &Lo, SDValue &Hi) {
1079   SDValue Amt = N->getOperand(1);
1080   MVT NVT = TLI.getTypeToTransformTo(N->getValueType(0));
1081   MVT ShTy = Amt.getValueType();
1082   unsigned ShBits = ShTy.getSizeInBits();
1083   unsigned NVTBits = NVT.getSizeInBits();
1084   assert(isPowerOf2_32(NVTBits) &&
1085          "Expanded integer type size not a power of two!");
1086
1087   APInt HighBitMask = APInt::getHighBitsSet(ShBits, ShBits - Log2_32(NVTBits));
1088   APInt KnownZero, KnownOne;
1089   DAG.ComputeMaskedBits(N->getOperand(1), HighBitMask, KnownZero, KnownOne);
1090
1091   // If we don't know anything about the high bits, exit.
1092   if (((KnownZero|KnownOne) & HighBitMask) == 0)
1093     return false;
1094
1095   // Get the incoming operand to be shifted.
1096   SDValue InL, InH;
1097   GetExpandedInteger(N->getOperand(0), InL, InH);
1098
1099   // If we know that any of the high bits of the shift amount are one, then we
1100   // can do this as a couple of simple shifts.
1101   if (KnownOne.intersects(HighBitMask)) {
1102     // Mask out the high bit, which we know is set.
1103     Amt = DAG.getNode(ISD::AND, ShTy, Amt,
1104                       DAG.getConstant(~HighBitMask, ShTy));
1105
1106     switch (N->getOpcode()) {
1107     default: assert(0 && "Unknown shift");
1108     case ISD::SHL:
1109       Lo = DAG.getConstant(0, NVT);              // Low part is zero.
1110       Hi = DAG.getNode(ISD::SHL, NVT, InL, Amt); // High part from Lo part.
1111       return true;
1112     case ISD::SRL:
1113       Hi = DAG.getConstant(0, NVT);              // Hi part is zero.
1114       Lo = DAG.getNode(ISD::SRL, NVT, InH, Amt); // Lo part from Hi part.
1115       return true;
1116     case ISD::SRA:
1117       Hi = DAG.getNode(ISD::SRA, NVT, InH,       // Sign extend high part.
1118                        DAG.getConstant(NVTBits-1, ShTy));
1119       Lo = DAG.getNode(ISD::SRA, NVT, InH, Amt); // Lo part from Hi part.
1120       return true;
1121     }
1122   }
1123
1124 #if 0
1125   // FIXME: This code is broken for shifts with a zero amount!
1126   // If we know that all of the high bits of the shift amount are zero, then we
1127   // can do this as a couple of simple shifts.
1128   if ((KnownZero & HighBitMask) == HighBitMask) {
1129     // Compute 32-amt.
1130     SDValue Amt2 = DAG.getNode(ISD::SUB, ShTy,
1131                                  DAG.getConstant(NVTBits, ShTy),
1132                                  Amt);
1133     unsigned Op1, Op2;
1134     switch (N->getOpcode()) {
1135     default: assert(0 && "Unknown shift");
1136     case ISD::SHL:  Op1 = ISD::SHL; Op2 = ISD::SRL; break;
1137     case ISD::SRL:
1138     case ISD::SRA:  Op1 = ISD::SRL; Op2 = ISD::SHL; break;
1139     }
1140
1141     Lo = DAG.getNode(N->getOpcode(), NVT, InL, Amt);
1142     Hi = DAG.getNode(ISD::OR, NVT,
1143                      DAG.getNode(Op1, NVT, InH, Amt),
1144                      DAG.getNode(Op2, NVT, InL, Amt2));
1145     return true;
1146   }
1147 #endif
1148
1149   return false;
1150 }
1151
1152 void DAGTypeLegalizer::ExpandIntRes_ADDSUB(SDNode *N,
1153                                            SDValue &Lo, SDValue &Hi) {
1154   // Expand the subcomponents.
1155   SDValue LHSL, LHSH, RHSL, RHSH;
1156   GetExpandedInteger(N->getOperand(0), LHSL, LHSH);
1157   GetExpandedInteger(N->getOperand(1), RHSL, RHSH);
1158
1159   MVT NVT = LHSL.getValueType();
1160   SDValue LoOps[2] = { LHSL, RHSL };
1161   SDValue HiOps[3] = { LHSH, RHSH };
1162
1163   // Do not generate ADDC/ADDE or SUBC/SUBE if the target does not support
1164   // them.  TODO: Teach operation legalization how to expand unsupported
1165   // ADDC/ADDE/SUBC/SUBE.  The problem is that these operations generate
1166   // a carry of type MVT::Flag, but there doesn't seem to be any way to
1167   // generate a value of this type in the expanded code sequence.
1168   bool hasCarry =
1169     TLI.isOperationLegal(N->getOpcode() == ISD::ADD ? ISD::ADDC : ISD::SUBC,
1170                          TLI.getTypeToExpandTo(NVT));
1171
1172   if (hasCarry) {
1173     SDVTList VTList = DAG.getVTList(NVT, MVT::Flag);
1174     if (N->getOpcode() == ISD::ADD) {
1175       Lo = DAG.getNode(ISD::ADDC, VTList, LoOps, 2);
1176       HiOps[2] = Lo.getValue(1);
1177       Hi = DAG.getNode(ISD::ADDE, VTList, HiOps, 3);
1178     } else {
1179       Lo = DAG.getNode(ISD::SUBC, VTList, LoOps, 2);
1180       HiOps[2] = Lo.getValue(1);
1181       Hi = DAG.getNode(ISD::SUBE, VTList, HiOps, 3);
1182     }
1183   } else {
1184     if (N->getOpcode() == ISD::ADD) {
1185       Lo = DAG.getNode(ISD::ADD, NVT, LoOps, 2);
1186       Hi = DAG.getNode(ISD::ADD, NVT, HiOps, 2);
1187       SDValue Cmp1 = DAG.getSetCC(TLI.getSetCCResultType(NVT), Lo, LoOps[0],
1188                                   ISD::SETULT);
1189       SDValue Carry1 = DAG.getNode(ISD::SELECT, NVT, Cmp1,
1190                                    DAG.getConstant(1, NVT),
1191                                    DAG.getConstant(0, NVT));
1192       SDValue Cmp2 = DAG.getSetCC(TLI.getSetCCResultType(NVT), Lo, LoOps[1],
1193                                   ISD::SETULT);
1194       SDValue Carry2 = DAG.getNode(ISD::SELECT, NVT, Cmp2,
1195                                    DAG.getConstant(1, NVT), Carry1);
1196       Hi = DAG.getNode(ISD::ADD, NVT, Hi, Carry2);
1197     } else {
1198       Lo = DAG.getNode(ISD::SUB, NVT, LoOps, 2);
1199       Hi = DAG.getNode(ISD::SUB, NVT, HiOps, 2);
1200       SDValue Cmp =
1201         DAG.getSetCC(TLI.getSetCCResultType(LoOps[0].getValueType()),
1202                      LoOps[0], LoOps[1], ISD::SETULT);
1203       SDValue Borrow = DAG.getNode(ISD::SELECT, NVT, Cmp,
1204                                    DAG.getConstant(1, NVT),
1205                                    DAG.getConstant(0, NVT));
1206       Hi = DAG.getNode(ISD::SUB, NVT, Hi, Borrow);
1207     }
1208   }
1209 }
1210
1211 void DAGTypeLegalizer::ExpandIntRes_ADDSUBC(SDNode *N,
1212                                             SDValue &Lo, SDValue &Hi) {
1213   // Expand the subcomponents.
1214   SDValue LHSL, LHSH, RHSL, RHSH;
1215   GetExpandedInteger(N->getOperand(0), LHSL, LHSH);
1216   GetExpandedInteger(N->getOperand(1), RHSL, RHSH);
1217   SDVTList VTList = DAG.getVTList(LHSL.getValueType(), MVT::Flag);
1218   SDValue LoOps[2] = { LHSL, RHSL };
1219   SDValue HiOps[3] = { LHSH, RHSH };
1220
1221   if (N->getOpcode() == ISD::ADDC) {
1222     Lo = DAG.getNode(ISD::ADDC, VTList, LoOps, 2);
1223     HiOps[2] = Lo.getValue(1);
1224     Hi = DAG.getNode(ISD::ADDE, VTList, HiOps, 3);
1225   } else {
1226     Lo = DAG.getNode(ISD::SUBC, VTList, LoOps, 2);
1227     HiOps[2] = Lo.getValue(1);
1228     Hi = DAG.getNode(ISD::SUBE, VTList, HiOps, 3);
1229   }
1230
1231   // Legalized the flag result - switch anything that used the old flag to
1232   // use the new one.
1233   ReplaceValueWith(SDValue(N, 1), Hi.getValue(1));
1234 }
1235
1236 void DAGTypeLegalizer::ExpandIntRes_ADDSUBE(SDNode *N,
1237                                             SDValue &Lo, SDValue &Hi) {
1238   // Expand the subcomponents.
1239   SDValue LHSL, LHSH, RHSL, RHSH;
1240   GetExpandedInteger(N->getOperand(0), LHSL, LHSH);
1241   GetExpandedInteger(N->getOperand(1), RHSL, RHSH);
1242   SDVTList VTList = DAG.getVTList(LHSL.getValueType(), MVT::Flag);
1243   SDValue LoOps[3] = { LHSL, RHSL, N->getOperand(2) };
1244   SDValue HiOps[3] = { LHSH, RHSH };
1245
1246   Lo = DAG.getNode(N->getOpcode(), VTList, LoOps, 3);
1247   HiOps[2] = Lo.getValue(1);
1248   Hi = DAG.getNode(N->getOpcode(), VTList, HiOps, 3);
1249
1250   // Legalized the flag result - switch anything that used the old flag to
1251   // use the new one.
1252   ReplaceValueWith(SDValue(N, 1), Hi.getValue(1));
1253 }
1254
1255 void DAGTypeLegalizer::ExpandIntRes_ANY_EXTEND(SDNode *N,
1256                                                SDValue &Lo, SDValue &Hi) {
1257   MVT NVT = TLI.getTypeToTransformTo(N->getValueType(0));
1258   SDValue Op = N->getOperand(0);
1259   if (Op.getValueType().bitsLE(NVT)) {
1260     // The low part is any extension of the input (which degenerates to a copy).
1261     Lo = DAG.getNode(ISD::ANY_EXTEND, NVT, Op);
1262     Hi = DAG.getNode(ISD::UNDEF, NVT);   // The high part is undefined.
1263   } else {
1264     // For example, extension of an i48 to an i64.  The operand type necessarily
1265     // promotes to the result type, so will end up being expanded too.
1266     assert(getTypeAction(Op.getValueType()) == PromoteInteger &&
1267            "Only know how to promote this result!");
1268     SDValue Res = GetPromotedInteger(Op);
1269     assert(Res.getValueType() == N->getValueType(0) &&
1270            "Operand over promoted?");
1271     // Split the promoted operand.  This will simplify when it is expanded.
1272     SplitInteger(Res, Lo, Hi);
1273   }
1274 }
1275
1276 void DAGTypeLegalizer::ExpandIntRes_AssertSext(SDNode *N,
1277                                                SDValue &Lo, SDValue &Hi) {
1278   GetExpandedInteger(N->getOperand(0), Lo, Hi);
1279   MVT NVT = Lo.getValueType();
1280   MVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
1281   unsigned NVTBits = NVT.getSizeInBits();
1282   unsigned EVTBits = EVT.getSizeInBits();
1283
1284   if (NVTBits < EVTBits) {
1285     Hi = DAG.getNode(ISD::AssertSext, NVT, Hi,
1286                      DAG.getValueType(MVT::getIntegerVT(EVTBits - NVTBits)));
1287   } else {
1288     Lo = DAG.getNode(ISD::AssertSext, NVT, Lo, DAG.getValueType(EVT));
1289     // The high part replicates the sign bit of Lo, make it explicit.
1290     Hi = DAG.getNode(ISD::SRA, NVT, Lo,
1291                      DAG.getConstant(NVTBits-1, TLI.getShiftAmountTy()));
1292   }
1293 }
1294
1295 void DAGTypeLegalizer::ExpandIntRes_AssertZext(SDNode *N,
1296                                                SDValue &Lo, SDValue &Hi) {
1297   GetExpandedInteger(N->getOperand(0), Lo, Hi);
1298   MVT NVT = Lo.getValueType();
1299   MVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
1300   unsigned NVTBits = NVT.getSizeInBits();
1301   unsigned EVTBits = EVT.getSizeInBits();
1302
1303   if (NVTBits < EVTBits) {
1304     Hi = DAG.getNode(ISD::AssertZext, NVT, Hi,
1305                      DAG.getValueType(MVT::getIntegerVT(EVTBits - NVTBits)));
1306   } else {
1307     Lo = DAG.getNode(ISD::AssertZext, NVT, Lo, DAG.getValueType(EVT));
1308     // The high part must be zero, make it explicit.
1309     Hi = DAG.getConstant(0, NVT);
1310   }
1311 }
1312
1313 void DAGTypeLegalizer::ExpandIntRes_BSWAP(SDNode *N,
1314                                           SDValue &Lo, SDValue &Hi) {
1315   GetExpandedInteger(N->getOperand(0), Hi, Lo);  // Note swapped operands.
1316   Lo = DAG.getNode(ISD::BSWAP, Lo.getValueType(), Lo);
1317   Hi = DAG.getNode(ISD::BSWAP, Hi.getValueType(), Hi);
1318 }
1319
1320 void DAGTypeLegalizer::ExpandIntRes_Constant(SDNode *N,
1321                                              SDValue &Lo, SDValue &Hi) {
1322   MVT NVT = TLI.getTypeToTransformTo(N->getValueType(0));
1323   unsigned NBitWidth = NVT.getSizeInBits();
1324   const APInt &Cst = cast<ConstantSDNode>(N)->getAPIntValue();
1325   Lo = DAG.getConstant(APInt(Cst).trunc(NBitWidth), NVT);
1326   Hi = DAG.getConstant(Cst.lshr(NBitWidth).trunc(NBitWidth), NVT);
1327 }
1328
1329 void DAGTypeLegalizer::ExpandIntRes_CTLZ(SDNode *N,
1330                                          SDValue &Lo, SDValue &Hi) {
1331   // ctlz (HiLo) -> Hi != 0 ? ctlz(Hi) : (ctlz(Lo)+32)
1332   GetExpandedInteger(N->getOperand(0), Lo, Hi);
1333   MVT NVT = Lo.getValueType();
1334
1335   SDValue HiNotZero = DAG.getSetCC(TLI.getSetCCResultType(NVT), Hi,
1336                                    DAG.getConstant(0, NVT), ISD::SETNE);
1337
1338   SDValue LoLZ = DAG.getNode(ISD::CTLZ, NVT, Lo);
1339   SDValue HiLZ = DAG.getNode(ISD::CTLZ, NVT, Hi);
1340
1341   Lo = DAG.getNode(ISD::SELECT, NVT, HiNotZero, HiLZ,
1342                    DAG.getNode(ISD::ADD, NVT, LoLZ,
1343                                DAG.getConstant(NVT.getSizeInBits(), NVT)));
1344   Hi = DAG.getConstant(0, NVT);
1345 }
1346
1347 void DAGTypeLegalizer::ExpandIntRes_CTPOP(SDNode *N,
1348                                           SDValue &Lo, SDValue &Hi) {
1349   // ctpop(HiLo) -> ctpop(Hi)+ctpop(Lo)
1350   GetExpandedInteger(N->getOperand(0), Lo, Hi);
1351   MVT NVT = Lo.getValueType();
1352   Lo = DAG.getNode(ISD::ADD, NVT, DAG.getNode(ISD::CTPOP, NVT, Lo),
1353                    DAG.getNode(ISD::CTPOP, NVT, Hi));
1354   Hi = DAG.getConstant(0, NVT);
1355 }
1356
1357 void DAGTypeLegalizer::ExpandIntRes_CTTZ(SDNode *N,
1358                                          SDValue &Lo, SDValue &Hi) {
1359   // cttz (HiLo) -> Lo != 0 ? cttz(Lo) : (cttz(Hi)+32)
1360   GetExpandedInteger(N->getOperand(0), Lo, Hi);
1361   MVT NVT = Lo.getValueType();
1362
1363   SDValue LoNotZero = DAG.getSetCC(TLI.getSetCCResultType(NVT), Lo,
1364                                    DAG.getConstant(0, NVT), ISD::SETNE);
1365
1366   SDValue LoLZ = DAG.getNode(ISD::CTTZ, NVT, Lo);
1367   SDValue HiLZ = DAG.getNode(ISD::CTTZ, NVT, Hi);
1368
1369   Lo = DAG.getNode(ISD::SELECT, NVT, LoNotZero, LoLZ,
1370                    DAG.getNode(ISD::ADD, NVT, HiLZ,
1371                                DAG.getConstant(NVT.getSizeInBits(), NVT)));
1372   Hi = DAG.getConstant(0, NVT);
1373 }
1374
1375 void DAGTypeLegalizer::ExpandIntRes_FP_TO_SINT(SDNode *N, SDValue &Lo,
1376                                                SDValue &Hi) {
1377   MVT VT = N->getValueType(0);
1378   SDValue Op = N->getOperand(0);
1379   RTLIB::Libcall LC = RTLIB::getFPTOSINT(Op.getValueType(), VT);
1380   assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unexpected fp-to-sint conversion!");
1381   SplitInteger(MakeLibCall(LC, VT, &Op, 1, true/*sign irrelevant*/), Lo, Hi);
1382 }
1383
1384 void DAGTypeLegalizer::ExpandIntRes_FP_TO_UINT(SDNode *N, SDValue &Lo,
1385                                                SDValue &Hi) {
1386   MVT VT = N->getValueType(0);
1387   SDValue Op = N->getOperand(0);
1388   RTLIB::Libcall LC = RTLIB::getFPTOUINT(Op.getValueType(), VT);
1389   assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unexpected fp-to-uint conversion!");
1390   SplitInteger(MakeLibCall(LC, VT, &Op, 1, false/*sign irrelevant*/), Lo, Hi);
1391 }
1392
1393 void DAGTypeLegalizer::ExpandIntRes_LOAD(LoadSDNode *N,
1394                                          SDValue &Lo, SDValue &Hi) {
1395   if (ISD::isNormalLoad(N)) {
1396     ExpandRes_NormalLoad(N, Lo, Hi);
1397     return;
1398   }
1399
1400   assert(ISD::isUNINDEXEDLoad(N) && "Indexed load during type legalization!");
1401
1402   MVT VT = N->getValueType(0);
1403   MVT NVT = TLI.getTypeToTransformTo(VT);
1404   SDValue Ch  = N->getChain();
1405   SDValue Ptr = N->getBasePtr();
1406   ISD::LoadExtType ExtType = N->getExtensionType();
1407   int SVOffset = N->getSrcValueOffset();
1408   unsigned Alignment = N->getAlignment();
1409   bool isVolatile = N->isVolatile();
1410
1411   assert(NVT.isByteSized() && "Expanded type not byte sized!");
1412
1413   if (N->getMemoryVT().bitsLE(NVT)) {
1414     MVT EVT = N->getMemoryVT();
1415
1416     Lo = DAG.getExtLoad(ExtType, NVT, Ch, Ptr, N->getSrcValue(), SVOffset, EVT,
1417                         isVolatile, Alignment);
1418
1419     // Remember the chain.
1420     Ch = Lo.getValue(1);
1421
1422     if (ExtType == ISD::SEXTLOAD) {
1423       // The high part is obtained by SRA'ing all but one of the bits of the
1424       // lo part.
1425       unsigned LoSize = Lo.getValueType().getSizeInBits();
1426       Hi = DAG.getNode(ISD::SRA, NVT, Lo,
1427                        DAG.getConstant(LoSize-1, TLI.getShiftAmountTy()));
1428     } else if (ExtType == ISD::ZEXTLOAD) {
1429       // The high part is just a zero.
1430       Hi = DAG.getConstant(0, NVT);
1431     } else {
1432       assert(ExtType == ISD::EXTLOAD && "Unknown extload!");
1433       // The high part is undefined.
1434       Hi = DAG.getNode(ISD::UNDEF, NVT);
1435     }
1436   } else if (TLI.isLittleEndian()) {
1437     // Little-endian - low bits are at low addresses.
1438     Lo = DAG.getLoad(NVT, Ch, Ptr, N->getSrcValue(), SVOffset,
1439                      isVolatile, Alignment);
1440
1441     unsigned ExcessBits =
1442       N->getMemoryVT().getSizeInBits() - NVT.getSizeInBits();
1443     MVT NEVT = MVT::getIntegerVT(ExcessBits);
1444
1445     // Increment the pointer to the other half.
1446     unsigned IncrementSize = NVT.getSizeInBits()/8;
1447     Ptr = DAG.getNode(ISD::ADD, Ptr.getValueType(), Ptr,
1448                       DAG.getIntPtrConstant(IncrementSize));
1449     Hi = DAG.getExtLoad(ExtType, NVT, Ch, Ptr, N->getSrcValue(),
1450                         SVOffset+IncrementSize, NEVT,
1451                         isVolatile, MinAlign(Alignment, IncrementSize));
1452
1453     // Build a factor node to remember that this load is independent of the
1454     // other one.
1455     Ch = DAG.getNode(ISD::TokenFactor, MVT::Other, Lo.getValue(1),
1456                      Hi.getValue(1));
1457   } else {
1458     // Big-endian - high bits are at low addresses.  Favor aligned loads at
1459     // the cost of some bit-fiddling.
1460     MVT EVT = N->getMemoryVT();
1461     unsigned EBytes = EVT.getStoreSizeInBits()/8;
1462     unsigned IncrementSize = NVT.getSizeInBits()/8;
1463     unsigned ExcessBits = (EBytes - IncrementSize)*8;
1464
1465     // Load both the high bits and maybe some of the low bits.
1466     Hi = DAG.getExtLoad(ExtType, NVT, Ch, Ptr, N->getSrcValue(), SVOffset,
1467                         MVT::getIntegerVT(EVT.getSizeInBits() - ExcessBits),
1468                         isVolatile, Alignment);
1469
1470     // Increment the pointer to the other half.
1471     Ptr = DAG.getNode(ISD::ADD, Ptr.getValueType(), Ptr,
1472                       DAG.getIntPtrConstant(IncrementSize));
1473     // Load the rest of the low bits.
1474     Lo = DAG.getExtLoad(ISD::ZEXTLOAD, NVT, Ch, Ptr, N->getSrcValue(),
1475                         SVOffset+IncrementSize,
1476                         MVT::getIntegerVT(ExcessBits),
1477                         isVolatile, MinAlign(Alignment, IncrementSize));
1478
1479     // Build a factor node to remember that this load is independent of the
1480     // other one.
1481     Ch = DAG.getNode(ISD::TokenFactor, MVT::Other, Lo.getValue(1),
1482                      Hi.getValue(1));
1483
1484     if (ExcessBits < NVT.getSizeInBits()) {
1485       // Transfer low bits from the bottom of Hi to the top of Lo.
1486       Lo = DAG.getNode(ISD::OR, NVT, Lo,
1487                        DAG.getNode(ISD::SHL, NVT, Hi,
1488                                    DAG.getConstant(ExcessBits,
1489                                                    TLI.getShiftAmountTy())));
1490       // Move high bits to the right position in Hi.
1491       Hi = DAG.getNode(ExtType == ISD::SEXTLOAD ? ISD::SRA : ISD::SRL, NVT, Hi,
1492                        DAG.getConstant(NVT.getSizeInBits() - ExcessBits,
1493                                        TLI.getShiftAmountTy()));
1494     }
1495   }
1496
1497   // Legalized the chain result - switch anything that used the old chain to
1498   // use the new one.
1499   ReplaceValueWith(SDValue(N, 1), Ch);
1500 }
1501
1502 void DAGTypeLegalizer::ExpandIntRes_Logical(SDNode *N,
1503                                             SDValue &Lo, SDValue &Hi) {
1504   SDValue LL, LH, RL, RH;
1505   GetExpandedInteger(N->getOperand(0), LL, LH);
1506   GetExpandedInteger(N->getOperand(1), RL, RH);
1507   Lo = DAG.getNode(N->getOpcode(), LL.getValueType(), LL, RL);
1508   Hi = DAG.getNode(N->getOpcode(), LL.getValueType(), LH, RH);
1509 }
1510
1511 void DAGTypeLegalizer::ExpandIntRes_MUL(SDNode *N,
1512                                         SDValue &Lo, SDValue &Hi) {
1513   MVT VT = N->getValueType(0);
1514   MVT NVT = TLI.getTypeToTransformTo(VT);
1515
1516   bool HasMULHS = TLI.isOperationLegal(ISD::MULHS, NVT);
1517   bool HasMULHU = TLI.isOperationLegal(ISD::MULHU, NVT);
1518   bool HasSMUL_LOHI = TLI.isOperationLegal(ISD::SMUL_LOHI, NVT);
1519   bool HasUMUL_LOHI = TLI.isOperationLegal(ISD::UMUL_LOHI, NVT);
1520   if (HasMULHU || HasMULHS || HasUMUL_LOHI || HasSMUL_LOHI) {
1521     SDValue LL, LH, RL, RH;
1522     GetExpandedInteger(N->getOperand(0), LL, LH);
1523     GetExpandedInteger(N->getOperand(1), RL, RH);
1524     unsigned OuterBitSize = VT.getSizeInBits();
1525     unsigned InnerBitSize = NVT.getSizeInBits();
1526     unsigned LHSSB = DAG.ComputeNumSignBits(N->getOperand(0));
1527     unsigned RHSSB = DAG.ComputeNumSignBits(N->getOperand(1));
1528
1529     APInt HighMask = APInt::getHighBitsSet(OuterBitSize, InnerBitSize);
1530     if (DAG.MaskedValueIsZero(N->getOperand(0), HighMask) &&
1531         DAG.MaskedValueIsZero(N->getOperand(1), HighMask)) {
1532       // The inputs are both zero-extended.
1533       if (HasUMUL_LOHI) {
1534         // We can emit a umul_lohi.
1535         Lo = DAG.getNode(ISD::UMUL_LOHI, DAG.getVTList(NVT, NVT), LL, RL);
1536         Hi = SDValue(Lo.getNode(), 1);
1537         return;
1538       }
1539       if (HasMULHU) {
1540         // We can emit a mulhu+mul.
1541         Lo = DAG.getNode(ISD::MUL, NVT, LL, RL);
1542         Hi = DAG.getNode(ISD::MULHU, NVT, LL, RL);
1543         return;
1544       }
1545     }
1546     if (LHSSB > InnerBitSize && RHSSB > InnerBitSize) {
1547       // The input values are both sign-extended.
1548       if (HasSMUL_LOHI) {
1549         // We can emit a smul_lohi.
1550         Lo = DAG.getNode(ISD::SMUL_LOHI, DAG.getVTList(NVT, NVT), LL, RL);
1551         Hi = SDValue(Lo.getNode(), 1);
1552         return;
1553       }
1554       if (HasMULHS) {
1555         // We can emit a mulhs+mul.
1556         Lo = DAG.getNode(ISD::MUL, NVT, LL, RL);
1557         Hi = DAG.getNode(ISD::MULHS, NVT, LL, RL);
1558         return;
1559       }
1560     }
1561     if (HasUMUL_LOHI) {
1562       // Lo,Hi = umul LHS, RHS.
1563       SDValue UMulLOHI = DAG.getNode(ISD::UMUL_LOHI,
1564                                        DAG.getVTList(NVT, NVT), LL, RL);
1565       Lo = UMulLOHI;
1566       Hi = UMulLOHI.getValue(1);
1567       RH = DAG.getNode(ISD::MUL, NVT, LL, RH);
1568       LH = DAG.getNode(ISD::MUL, NVT, LH, RL);
1569       Hi = DAG.getNode(ISD::ADD, NVT, Hi, RH);
1570       Hi = DAG.getNode(ISD::ADD, NVT, Hi, LH);
1571       return;
1572     }
1573     if (HasMULHU) {
1574       Lo = DAG.getNode(ISD::MUL, NVT, LL, RL);
1575       Hi = DAG.getNode(ISD::MULHU, NVT, LL, RL);
1576       RH = DAG.getNode(ISD::MUL, NVT, LL, RH);
1577       LH = DAG.getNode(ISD::MUL, NVT, LH, RL);
1578       Hi = DAG.getNode(ISD::ADD, NVT, Hi, RH);
1579       Hi = DAG.getNode(ISD::ADD, NVT, Hi, LH);
1580       return;
1581     }
1582   }
1583
1584   // If nothing else, we can make a libcall.
1585   RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
1586   if (VT == MVT::i16)
1587     LC = RTLIB::MUL_I16;
1588   else if (VT == MVT::i32)
1589     LC = RTLIB::MUL_I32;
1590   else if (VT == MVT::i64)
1591     LC = RTLIB::MUL_I64;
1592   else if (VT == MVT::i128)
1593     LC = RTLIB::MUL_I128;
1594   assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unsupported MUL!");
1595
1596   SDValue Ops[2] = { N->getOperand(0), N->getOperand(1) };
1597   SplitInteger(MakeLibCall(LC, VT, Ops, 2, true/*sign irrelevant*/), Lo, Hi);
1598 }
1599
1600 void DAGTypeLegalizer::ExpandIntRes_SDIV(SDNode *N,
1601                                          SDValue &Lo, SDValue &Hi) {
1602   MVT VT = N->getValueType(0);
1603
1604   RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
1605   if (VT == MVT::i32)
1606     LC = RTLIB::SDIV_I32;
1607   else if (VT == MVT::i64)
1608     LC = RTLIB::SDIV_I64;
1609   else if (VT == MVT::i128)
1610     LC = RTLIB::SDIV_I128;
1611   assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unsupported SDIV!");
1612
1613   SDValue Ops[2] = { N->getOperand(0), N->getOperand(1) };
1614   SplitInteger(MakeLibCall(LC, VT, Ops, 2, true), Lo, Hi);
1615 }
1616
1617 void DAGTypeLegalizer::ExpandIntRes_Shift(SDNode *N,
1618                                           SDValue &Lo, SDValue &Hi) {
1619   MVT VT = N->getValueType(0);
1620
1621   // If we can emit an efficient shift operation, do so now.  Check to see if
1622   // the RHS is a constant.
1623   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N->getOperand(1)))
1624     return ExpandShiftByConstant(N, CN->getZExtValue(), Lo, Hi);
1625
1626   // If we can determine that the high bit of the shift is zero or one, even if
1627   // the low bits are variable, emit this shift in an optimized form.
1628   if (ExpandShiftWithKnownAmountBit(N, Lo, Hi))
1629     return;
1630
1631   // If this target supports shift_PARTS, use it.  First, map to the _PARTS opc.
1632   unsigned PartsOpc;
1633   if (N->getOpcode() == ISD::SHL) {
1634     PartsOpc = ISD::SHL_PARTS;
1635   } else if (N->getOpcode() == ISD::SRL) {
1636     PartsOpc = ISD::SRL_PARTS;
1637   } else {
1638     assert(N->getOpcode() == ISD::SRA && "Unknown shift!");
1639     PartsOpc = ISD::SRA_PARTS;
1640   }
1641
1642   // Next check to see if the target supports this SHL_PARTS operation or if it
1643   // will custom expand it.
1644   MVT NVT = TLI.getTypeToTransformTo(VT);
1645   TargetLowering::LegalizeAction Action = TLI.getOperationAction(PartsOpc, NVT);
1646   if ((Action == TargetLowering::Legal && TLI.isTypeLegal(NVT)) ||
1647       Action == TargetLowering::Custom) {
1648     // Expand the subcomponents.
1649     SDValue LHSL, LHSH;
1650     GetExpandedInteger(N->getOperand(0), LHSL, LHSH);
1651
1652     SDValue Ops[] = { LHSL, LHSH, N->getOperand(1) };
1653     MVT VT = LHSL.getValueType();
1654     Lo = DAG.getNode(PartsOpc, DAG.getNodeValueTypes(VT, VT), 2, Ops, 3);
1655     Hi = Lo.getValue(1);
1656     return;
1657   }
1658
1659   // Otherwise, emit a libcall.
1660   RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
1661   bool isSigned;
1662   if (N->getOpcode() == ISD::SHL) {
1663     isSigned = false; /*sign irrelevant*/
1664     if (VT == MVT::i16)
1665       LC = RTLIB::SHL_I16;
1666     else if (VT == MVT::i32)
1667       LC = RTLIB::SHL_I32;
1668     else if (VT == MVT::i64)
1669       LC = RTLIB::SHL_I64;
1670     else if (VT == MVT::i128)
1671       LC = RTLIB::SHL_I128;
1672   } else if (N->getOpcode() == ISD::SRL) {
1673     isSigned = false;
1674     if (VT == MVT::i16)
1675       LC = RTLIB::SRL_I16;
1676     else if (VT == MVT::i32)
1677       LC = RTLIB::SRL_I32;
1678     else if (VT == MVT::i64)
1679       LC = RTLIB::SRL_I64;
1680     else if (VT == MVT::i128)
1681       LC = RTLIB::SRL_I128;
1682   } else {
1683     assert(N->getOpcode() == ISD::SRA && "Unknown shift!");
1684     isSigned = true;
1685     if (VT == MVT::i16)
1686       LC = RTLIB::SRA_I16;
1687     else if (VT == MVT::i32)
1688       LC = RTLIB::SRA_I32;
1689     else if (VT == MVT::i64)
1690       LC = RTLIB::SRA_I64;
1691     else if (VT == MVT::i128)
1692       LC = RTLIB::SRA_I128;
1693   }
1694   assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unsupported shift!");
1695
1696   SDValue Ops[2] = { N->getOperand(0), N->getOperand(1) };
1697   SplitInteger(MakeLibCall(LC, VT, Ops, 2, isSigned), Lo, Hi);
1698 }
1699
1700 void DAGTypeLegalizer::ExpandIntRes_SIGN_EXTEND(SDNode *N,
1701                                                 SDValue &Lo, SDValue &Hi) {
1702   MVT NVT = TLI.getTypeToTransformTo(N->getValueType(0));
1703   SDValue Op = N->getOperand(0);
1704   if (Op.getValueType().bitsLE(NVT)) {
1705     // The low part is sign extension of the input (degenerates to a copy).
1706     Lo = DAG.getNode(ISD::SIGN_EXTEND, NVT, N->getOperand(0));
1707     // The high part is obtained by SRA'ing all but one of the bits of low part.
1708     unsigned LoSize = NVT.getSizeInBits();
1709     Hi = DAG.getNode(ISD::SRA, NVT, Lo,
1710                      DAG.getConstant(LoSize-1, TLI.getShiftAmountTy()));
1711   } else {
1712     // For example, extension of an i48 to an i64.  The operand type necessarily
1713     // promotes to the result type, so will end up being expanded too.
1714     assert(getTypeAction(Op.getValueType()) == PromoteInteger &&
1715            "Only know how to promote this result!");
1716     SDValue Res = GetPromotedInteger(Op);
1717     assert(Res.getValueType() == N->getValueType(0) &&
1718            "Operand over promoted?");
1719     // Split the promoted operand.  This will simplify when it is expanded.
1720     SplitInteger(Res, Lo, Hi);
1721     unsigned ExcessBits =
1722       Op.getValueType().getSizeInBits() - NVT.getSizeInBits();
1723     Hi = DAG.getNode(ISD::SIGN_EXTEND_INREG, Hi.getValueType(), Hi,
1724                      DAG.getValueType(MVT::getIntegerVT(ExcessBits)));
1725   }
1726 }
1727
1728 void DAGTypeLegalizer::
1729 ExpandIntRes_SIGN_EXTEND_INREG(SDNode *N, SDValue &Lo, SDValue &Hi) {
1730   GetExpandedInteger(N->getOperand(0), Lo, Hi);
1731   MVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
1732
1733   if (EVT.bitsLE(Lo.getValueType())) {
1734     // sext_inreg the low part if needed.
1735     Lo = DAG.getNode(ISD::SIGN_EXTEND_INREG, Lo.getValueType(), Lo,
1736                      N->getOperand(1));
1737
1738     // The high part gets the sign extension from the lo-part.  This handles
1739     // things like sextinreg V:i64 from i8.
1740     Hi = DAG.getNode(ISD::SRA, Hi.getValueType(), Lo,
1741                      DAG.getConstant(Hi.getValueType().getSizeInBits()-1,
1742                                      TLI.getShiftAmountTy()));
1743   } else {
1744     // For example, extension of an i48 to an i64.  Leave the low part alone,
1745     // sext_inreg the high part.
1746     unsigned ExcessBits =
1747       EVT.getSizeInBits() - Lo.getValueType().getSizeInBits();
1748     Hi = DAG.getNode(ISD::SIGN_EXTEND_INREG, Hi.getValueType(), Hi,
1749                      DAG.getValueType(MVT::getIntegerVT(ExcessBits)));
1750   }
1751 }
1752
1753 void DAGTypeLegalizer::ExpandIntRes_SREM(SDNode *N,
1754                                          SDValue &Lo, SDValue &Hi) {
1755   MVT VT = N->getValueType(0);
1756
1757   RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
1758   if (VT == MVT::i32)
1759     LC = RTLIB::SREM_I32;
1760   else if (VT == MVT::i64)
1761     LC = RTLIB::SREM_I64;
1762   else if (VT == MVT::i128)
1763     LC = RTLIB::SREM_I128;
1764   assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unsupported SREM!");
1765
1766   SDValue Ops[2] = { N->getOperand(0), N->getOperand(1) };
1767   SplitInteger(MakeLibCall(LC, VT, Ops, 2, true), Lo, Hi);
1768 }
1769
1770 void DAGTypeLegalizer::ExpandIntRes_TRUNCATE(SDNode *N,
1771                                              SDValue &Lo, SDValue &Hi) {
1772   MVT NVT = TLI.getTypeToTransformTo(N->getValueType(0));
1773   Lo = DAG.getNode(ISD::TRUNCATE, NVT, N->getOperand(0));
1774   Hi = DAG.getNode(ISD::SRL, N->getOperand(0).getValueType(), N->getOperand(0),
1775                    DAG.getConstant(NVT.getSizeInBits(),
1776                                    TLI.getShiftAmountTy()));
1777   Hi = DAG.getNode(ISD::TRUNCATE, NVT, Hi);
1778 }
1779
1780 void DAGTypeLegalizer::ExpandIntRes_UDIV(SDNode *N,
1781                                          SDValue &Lo, SDValue &Hi) {
1782   MVT VT = N->getValueType(0);
1783
1784   RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
1785   if (VT == MVT::i32)
1786     LC = RTLIB::UDIV_I32;
1787   else if (VT == MVT::i64)
1788     LC = RTLIB::UDIV_I64;
1789   else if (VT == MVT::i128)
1790     LC = RTLIB::UDIV_I128;
1791   assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unsupported UDIV!");
1792
1793   SDValue Ops[2] = { N->getOperand(0), N->getOperand(1) };
1794   SplitInteger(MakeLibCall(LC, VT, Ops, 2, false), Lo, Hi);
1795 }
1796
1797 void DAGTypeLegalizer::ExpandIntRes_UREM(SDNode *N,
1798                                          SDValue &Lo, SDValue &Hi) {
1799   MVT VT = N->getValueType(0);
1800
1801   RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
1802   if (VT == MVT::i32)
1803     LC = RTLIB::UREM_I32;
1804   else if (VT == MVT::i64)
1805     LC = RTLIB::UREM_I64;
1806   else if (VT == MVT::i128)
1807     LC = RTLIB::UREM_I128;
1808   assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unsupported UREM!");
1809
1810   SDValue Ops[2] = { N->getOperand(0), N->getOperand(1) };
1811   SplitInteger(MakeLibCall(LC, VT, Ops, 2, false), Lo, Hi);
1812 }
1813
1814 void DAGTypeLegalizer::ExpandIntRes_ZERO_EXTEND(SDNode *N,
1815                                                 SDValue &Lo, SDValue &Hi) {
1816   MVT NVT = TLI.getTypeToTransformTo(N->getValueType(0));
1817   SDValue Op = N->getOperand(0);
1818   if (Op.getValueType().bitsLE(NVT)) {
1819     // The low part is zero extension of the input (degenerates to a copy).
1820     Lo = DAG.getNode(ISD::ZERO_EXTEND, NVT, N->getOperand(0));
1821     Hi = DAG.getConstant(0, NVT);   // The high part is just a zero.
1822   } else {
1823     // For example, extension of an i48 to an i64.  The operand type necessarily
1824     // promotes to the result type, so will end up being expanded too.
1825     assert(getTypeAction(Op.getValueType()) == PromoteInteger &&
1826            "Only know how to promote this result!");
1827     SDValue Res = GetPromotedInteger(Op);
1828     assert(Res.getValueType() == N->getValueType(0) &&
1829            "Operand over promoted?");
1830     // Split the promoted operand.  This will simplify when it is expanded.
1831     SplitInteger(Res, Lo, Hi);
1832     unsigned ExcessBits =
1833       Op.getValueType().getSizeInBits() - NVT.getSizeInBits();
1834     Hi = DAG.getZeroExtendInReg(Hi, MVT::getIntegerVT(ExcessBits));
1835   }
1836 }
1837
1838
1839 //===----------------------------------------------------------------------===//
1840 //  Integer Operand Expansion
1841 //===----------------------------------------------------------------------===//
1842
1843 /// ExpandIntegerOperand - This method is called when the specified operand of
1844 /// the specified node is found to need expansion.  At this point, all of the
1845 /// result types of the node are known to be legal, but other operands of the
1846 /// node may need promotion or expansion as well as the specified one.
1847 bool DAGTypeLegalizer::ExpandIntegerOperand(SDNode *N, unsigned OpNo) {
1848   DEBUG(cerr << "Expand integer operand: "; N->dump(&DAG); cerr << "\n");
1849   SDValue Res = SDValue();
1850
1851   if (CustomLowerResults(N, OpNo, false))
1852     return false;
1853
1854   switch (N->getOpcode()) {
1855   default:
1856   #ifndef NDEBUG
1857     cerr << "ExpandIntegerOperand Op #" << OpNo << ": ";
1858     N->dump(&DAG); cerr << "\n";
1859   #endif
1860     assert(0 && "Do not know how to expand this operator's operand!");
1861     abort();
1862
1863   case ISD::BUILD_VECTOR:      Res = ExpandOp_BUILD_VECTOR(N); break;
1864   case ISD::BIT_CONVERT:       Res = ExpandOp_BIT_CONVERT(N); break;
1865   case ISD::EXTRACT_ELEMENT:   Res = ExpandOp_EXTRACT_ELEMENT(N); break;
1866   case ISD::INSERT_VECTOR_ELT: Res = ExpandOp_INSERT_VECTOR_ELT(N); break;
1867   case ISD::SCALAR_TO_VECTOR:  Res = ExpandOp_SCALAR_TO_VECTOR(N); break;
1868
1869   case ISD::BR_CC:      Res = ExpandIntOp_BR_CC(N); break;
1870   case ISD::SELECT_CC:  Res = ExpandIntOp_SELECT_CC(N); break;
1871   case ISD::SETCC:      Res = ExpandIntOp_SETCC(N); break;
1872   case ISD::SINT_TO_FP: Res = ExpandIntOp_SINT_TO_FP(N); break;
1873   case ISD::STORE:      Res = ExpandIntOp_STORE(cast<StoreSDNode>(N), OpNo);
1874     break;
1875   case ISD::TRUNCATE:   Res = ExpandIntOp_TRUNCATE(N); break;
1876   case ISD::UINT_TO_FP: Res = ExpandIntOp_UINT_TO_FP(N); break;
1877   }
1878
1879   // If the result is null, the sub-method took care of registering results etc.
1880   if (!Res.getNode()) return false;
1881
1882   // If the result is N, the sub-method updated N in place.  Tell the legalizer
1883   // core about this.
1884   if (Res.getNode() == N)
1885     return true;
1886
1887   assert(Res.getValueType() == N->getValueType(0) && N->getNumValues() == 1 &&
1888          "Invalid operand expansion");
1889
1890   ReplaceValueWith(SDValue(N, 0), Res);
1891   return false;
1892 }
1893
1894 /// IntegerExpandSetCCOperands - Expand the operands of a comparison.  This code
1895 /// is shared among BR_CC, SELECT_CC, and SETCC handlers.
1896 void DAGTypeLegalizer::IntegerExpandSetCCOperands(SDValue &NewLHS,
1897                                                   SDValue &NewRHS,
1898                                                   ISD::CondCode &CCCode) {
1899   SDValue LHSLo, LHSHi, RHSLo, RHSHi;
1900   GetExpandedInteger(NewLHS, LHSLo, LHSHi);
1901   GetExpandedInteger(NewRHS, RHSLo, RHSHi);
1902
1903   MVT VT = NewLHS.getValueType();
1904
1905   if (CCCode == ISD::SETEQ || CCCode == ISD::SETNE) {
1906     if (RHSLo == RHSHi) {
1907       if (ConstantSDNode *RHSCST = dyn_cast<ConstantSDNode>(RHSLo)) {
1908         if (RHSCST->isAllOnesValue()) {
1909           // Equality comparison to -1.
1910           NewLHS = DAG.getNode(ISD::AND, LHSLo.getValueType(), LHSLo, LHSHi);
1911           NewRHS = RHSLo;
1912           return;
1913         }
1914       }
1915     }
1916
1917     NewLHS = DAG.getNode(ISD::XOR, LHSLo.getValueType(), LHSLo, RHSLo);
1918     NewRHS = DAG.getNode(ISD::XOR, LHSLo.getValueType(), LHSHi, RHSHi);
1919     NewLHS = DAG.getNode(ISD::OR, NewLHS.getValueType(), NewLHS, NewRHS);
1920     NewRHS = DAG.getConstant(0, NewLHS.getValueType());
1921     return;
1922   }
1923
1924   // If this is a comparison of the sign bit, just look at the top part.
1925   // X > -1,  x < 0
1926   if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(NewRHS))
1927     if ((CCCode == ISD::SETLT && CST->isNullValue()) ||     // X < 0
1928         (CCCode == ISD::SETGT && CST->isAllOnesValue())) {  // X > -1
1929       NewLHS = LHSHi;
1930       NewRHS = RHSHi;
1931       return;
1932     }
1933
1934   // FIXME: This generated code sucks.
1935   ISD::CondCode LowCC;
1936   switch (CCCode) {
1937   default: assert(0 && "Unknown integer setcc!");
1938   case ISD::SETLT:
1939   case ISD::SETULT: LowCC = ISD::SETULT; break;
1940   case ISD::SETGT:
1941   case ISD::SETUGT: LowCC = ISD::SETUGT; break;
1942   case ISD::SETLE:
1943   case ISD::SETULE: LowCC = ISD::SETULE; break;
1944   case ISD::SETGE:
1945   case ISD::SETUGE: LowCC = ISD::SETUGE; break;
1946   }
1947
1948   // Tmp1 = lo(op1) < lo(op2)   // Always unsigned comparison
1949   // Tmp2 = hi(op1) < hi(op2)   // Signedness depends on operands
1950   // dest = hi(op1) == hi(op2) ? Tmp1 : Tmp2;
1951
1952   // NOTE: on targets without efficient SELECT of bools, we can always use
1953   // this identity: (B1 ? B2 : B3) --> (B1 & B2)|(!B1&B3)
1954   TargetLowering::DAGCombinerInfo DagCombineInfo(DAG, false, true, NULL);
1955   SDValue Tmp1, Tmp2;
1956   Tmp1 = TLI.SimplifySetCC(TLI.getSetCCResultType(LHSLo.getValueType()),
1957                            LHSLo, RHSLo, LowCC, false, DagCombineInfo);
1958   if (!Tmp1.getNode())
1959     Tmp1 = DAG.getSetCC(TLI.getSetCCResultType(LHSLo.getValueType()),
1960                         LHSLo, RHSLo, LowCC);
1961   Tmp2 = TLI.SimplifySetCC(TLI.getSetCCResultType(LHSHi.getValueType()),
1962                            LHSHi, RHSHi, CCCode, false, DagCombineInfo);
1963   if (!Tmp2.getNode())
1964     Tmp2 = DAG.getNode(ISD::SETCC, TLI.getSetCCResultType(LHSHi.getValueType()),
1965                        LHSHi, RHSHi, DAG.getCondCode(CCCode));
1966
1967   ConstantSDNode *Tmp1C = dyn_cast<ConstantSDNode>(Tmp1.getNode());
1968   ConstantSDNode *Tmp2C = dyn_cast<ConstantSDNode>(Tmp2.getNode());
1969   if ((Tmp1C && Tmp1C->isNullValue()) ||
1970       (Tmp2C && Tmp2C->isNullValue() &&
1971        (CCCode == ISD::SETLE || CCCode == ISD::SETGE ||
1972         CCCode == ISD::SETUGE || CCCode == ISD::SETULE)) ||
1973       (Tmp2C && Tmp2C->getAPIntValue() == 1 &&
1974        (CCCode == ISD::SETLT || CCCode == ISD::SETGT ||
1975         CCCode == ISD::SETUGT || CCCode == ISD::SETULT))) {
1976     // low part is known false, returns high part.
1977     // For LE / GE, if high part is known false, ignore the low part.
1978     // For LT / GT, if high part is known true, ignore the low part.
1979     NewLHS = Tmp2;
1980     NewRHS = SDValue();
1981     return;
1982   }
1983
1984   NewLHS = TLI.SimplifySetCC(TLI.getSetCCResultType(LHSHi.getValueType()),
1985                              LHSHi, RHSHi, ISD::SETEQ, false, DagCombineInfo);
1986   if (!NewLHS.getNode())
1987     NewLHS = DAG.getSetCC(TLI.getSetCCResultType(LHSHi.getValueType()),
1988                           LHSHi, RHSHi, ISD::SETEQ);
1989   NewLHS = DAG.getNode(ISD::SELECT, Tmp1.getValueType(),
1990                        NewLHS, Tmp1, Tmp2);
1991   NewRHS = SDValue();
1992 }
1993
1994 SDValue DAGTypeLegalizer::ExpandIntOp_BR_CC(SDNode *N) {
1995   SDValue NewLHS = N->getOperand(2), NewRHS = N->getOperand(3);
1996   ISD::CondCode CCCode = cast<CondCodeSDNode>(N->getOperand(1))->get();
1997   IntegerExpandSetCCOperands(NewLHS, NewRHS, CCCode);
1998
1999   // If ExpandSetCCOperands returned a scalar, we need to compare the result
2000   // against zero to select between true and false values.
2001   if (NewRHS.getNode() == 0) {
2002     NewRHS = DAG.getConstant(0, NewLHS.getValueType());
2003     CCCode = ISD::SETNE;
2004   }
2005
2006   // Update N to have the operands specified.
2007   return DAG.UpdateNodeOperands(SDValue(N, 0), N->getOperand(0),
2008                                 DAG.getCondCode(CCCode), NewLHS, NewRHS,
2009                                 N->getOperand(4));
2010 }
2011
2012 SDValue DAGTypeLegalizer::ExpandIntOp_SELECT_CC(SDNode *N) {
2013   SDValue NewLHS = N->getOperand(0), NewRHS = N->getOperand(1);
2014   ISD::CondCode CCCode = cast<CondCodeSDNode>(N->getOperand(4))->get();
2015   IntegerExpandSetCCOperands(NewLHS, NewRHS, CCCode);
2016
2017   // If ExpandSetCCOperands returned a scalar, we need to compare the result
2018   // against zero to select between true and false values.
2019   if (NewRHS.getNode() == 0) {
2020     NewRHS = DAG.getConstant(0, NewLHS.getValueType());
2021     CCCode = ISD::SETNE;
2022   }
2023
2024   // Update N to have the operands specified.
2025   return DAG.UpdateNodeOperands(SDValue(N, 0), NewLHS, NewRHS,
2026                                 N->getOperand(2), N->getOperand(3),
2027                                 DAG.getCondCode(CCCode));
2028 }
2029
2030 SDValue DAGTypeLegalizer::ExpandIntOp_SETCC(SDNode *N) {
2031   SDValue NewLHS = N->getOperand(0), NewRHS = N->getOperand(1);
2032   ISD::CondCode CCCode = cast<CondCodeSDNode>(N->getOperand(2))->get();
2033   IntegerExpandSetCCOperands(NewLHS, NewRHS, CCCode);
2034
2035   // If ExpandSetCCOperands returned a scalar, use it.
2036   if (NewRHS.getNode() == 0) {
2037     assert(NewLHS.getValueType() == N->getValueType(0) &&
2038            "Unexpected setcc expansion!");
2039     return NewLHS;
2040   }
2041
2042   // Otherwise, update N to have the operands specified.
2043   return DAG.UpdateNodeOperands(SDValue(N, 0), NewLHS, NewRHS,
2044                                 DAG.getCondCode(CCCode));
2045 }
2046
2047 SDValue DAGTypeLegalizer::ExpandIntOp_SINT_TO_FP(SDNode *N) {
2048   SDValue Op = N->getOperand(0);
2049   MVT DstVT = N->getValueType(0);
2050   RTLIB::Libcall LC = RTLIB::getSINTTOFP(Op.getValueType(), DstVT);
2051   assert(LC != RTLIB::UNKNOWN_LIBCALL &&
2052          "Don't know how to expand this SINT_TO_FP!");
2053   return MakeLibCall(LC, DstVT, &Op, 1, true);
2054 }
2055
2056 SDValue DAGTypeLegalizer::ExpandIntOp_STORE(StoreSDNode *N, unsigned OpNo) {
2057   if (ISD::isNormalStore(N))
2058     return ExpandOp_NormalStore(N, OpNo);
2059
2060   assert(ISD::isUNINDEXEDStore(N) && "Indexed store during type legalization!");
2061   assert(OpNo == 1 && "Can only expand the stored value so far");
2062
2063   MVT VT = N->getOperand(1).getValueType();
2064   MVT NVT = TLI.getTypeToTransformTo(VT);
2065   SDValue Ch  = N->getChain();
2066   SDValue Ptr = N->getBasePtr();
2067   int SVOffset = N->getSrcValueOffset();
2068   unsigned Alignment = N->getAlignment();
2069   bool isVolatile = N->isVolatile();
2070   SDValue Lo, Hi;
2071
2072   assert(NVT.isByteSized() && "Expanded type not byte sized!");
2073
2074   if (N->getMemoryVT().bitsLE(NVT)) {
2075     GetExpandedInteger(N->getValue(), Lo, Hi);
2076     return DAG.getTruncStore(Ch, Lo, Ptr, N->getSrcValue(), SVOffset,
2077                              N->getMemoryVT(), isVolatile, Alignment);
2078   } else if (TLI.isLittleEndian()) {
2079     // Little-endian - low bits are at low addresses.
2080     GetExpandedInteger(N->getValue(), Lo, Hi);
2081
2082     Lo = DAG.getStore(Ch, Lo, Ptr, N->getSrcValue(), SVOffset,
2083                       isVolatile, Alignment);
2084
2085     unsigned ExcessBits =
2086       N->getMemoryVT().getSizeInBits() - NVT.getSizeInBits();
2087     MVT NEVT = MVT::getIntegerVT(ExcessBits);
2088
2089     // Increment the pointer to the other half.
2090     unsigned IncrementSize = NVT.getSizeInBits()/8;
2091     Ptr = DAG.getNode(ISD::ADD, Ptr.getValueType(), Ptr,
2092                       DAG.getIntPtrConstant(IncrementSize));
2093     Hi = DAG.getTruncStore(Ch, Hi, Ptr, N->getSrcValue(),
2094                            SVOffset+IncrementSize, NEVT,
2095                            isVolatile, MinAlign(Alignment, IncrementSize));
2096     return DAG.getNode(ISD::TokenFactor, MVT::Other, Lo, Hi);
2097   } else {
2098     // Big-endian - high bits are at low addresses.  Favor aligned stores at
2099     // the cost of some bit-fiddling.
2100     GetExpandedInteger(N->getValue(), Lo, Hi);
2101
2102     MVT EVT = N->getMemoryVT();
2103     unsigned EBytes = EVT.getStoreSizeInBits()/8;
2104     unsigned IncrementSize = NVT.getSizeInBits()/8;
2105     unsigned ExcessBits = (EBytes - IncrementSize)*8;
2106     MVT HiVT = MVT::getIntegerVT(EVT.getSizeInBits() - ExcessBits);
2107
2108     if (ExcessBits < NVT.getSizeInBits()) {
2109       // Transfer high bits from the top of Lo to the bottom of Hi.
2110       Hi = DAG.getNode(ISD::SHL, NVT, Hi,
2111                        DAG.getConstant(NVT.getSizeInBits() - ExcessBits,
2112                                        TLI.getShiftAmountTy()));
2113       Hi = DAG.getNode(ISD::OR, NVT, Hi,
2114                        DAG.getNode(ISD::SRL, NVT, Lo,
2115                                    DAG.getConstant(ExcessBits,
2116                                                    TLI.getShiftAmountTy())));
2117     }
2118
2119     // Store both the high bits and maybe some of the low bits.
2120     Hi = DAG.getTruncStore(Ch, Hi, Ptr, N->getSrcValue(),
2121                            SVOffset, HiVT, isVolatile, Alignment);
2122
2123     // Increment the pointer to the other half.
2124     Ptr = DAG.getNode(ISD::ADD, Ptr.getValueType(), Ptr,
2125                       DAG.getIntPtrConstant(IncrementSize));
2126     // Store the lowest ExcessBits bits in the second half.
2127     Lo = DAG.getTruncStore(Ch, Lo, Ptr, N->getSrcValue(),
2128                            SVOffset+IncrementSize,
2129                            MVT::getIntegerVT(ExcessBits),
2130                            isVolatile, MinAlign(Alignment, IncrementSize));
2131     return DAG.getNode(ISD::TokenFactor, MVT::Other, Lo, Hi);
2132   }
2133 }
2134
2135 SDValue DAGTypeLegalizer::ExpandIntOp_TRUNCATE(SDNode *N) {
2136   SDValue InL, InH;
2137   GetExpandedInteger(N->getOperand(0), InL, InH);
2138   // Just truncate the low part of the source.
2139   return DAG.getNode(ISD::TRUNCATE, N->getValueType(0), InL);
2140 }
2141
2142 SDValue DAGTypeLegalizer::ExpandIntOp_UINT_TO_FP(SDNode *N) {
2143   SDValue Op = N->getOperand(0);
2144   MVT SrcVT = Op.getValueType();
2145   MVT DstVT = N->getValueType(0);
2146
2147   if (TLI.getOperationAction(ISD::SINT_TO_FP, SrcVT) == TargetLowering::Custom){
2148     // Do a signed conversion then adjust the result.
2149     SDValue SignedConv = DAG.getNode(ISD::SINT_TO_FP, DstVT, Op);
2150     SignedConv = TLI.LowerOperation(SignedConv, DAG);
2151
2152     // The result of the signed conversion needs adjusting if the 'sign bit' of
2153     // the incoming integer was set.  To handle this, we dynamically test to see
2154     // if it is set, and, if so, add a fudge factor.
2155
2156     const uint64_t F32TwoE32  = 0x4F800000ULL;
2157     const uint64_t F32TwoE64  = 0x5F800000ULL;
2158     const uint64_t F32TwoE128 = 0x7F800000ULL;
2159
2160     APInt FF(32, 0);
2161     if (SrcVT == MVT::i32)
2162       FF = APInt(32, F32TwoE32);
2163     else if (SrcVT == MVT::i64)
2164       FF = APInt(32, F32TwoE64);
2165     else if (SrcVT == MVT::i128)
2166       FF = APInt(32, F32TwoE128);
2167     else
2168       assert(false && "Unsupported UINT_TO_FP!");
2169
2170     // Check whether the sign bit is set.
2171     SDValue Lo, Hi;
2172     GetExpandedInteger(Op, Lo, Hi);
2173     SDValue SignSet = DAG.getSetCC(TLI.getSetCCResultType(Hi.getValueType()),
2174                                    Hi, DAG.getConstant(0, Hi.getValueType()),
2175                                    ISD::SETLT);
2176
2177     // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
2178     SDValue FudgePtr = DAG.getConstantPool(ConstantInt::get(FF.zext(64)),
2179                                            TLI.getPointerTy());
2180
2181     // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
2182     SDValue Zero = DAG.getIntPtrConstant(0);
2183     SDValue Four = DAG.getIntPtrConstant(4);
2184     if (TLI.isBigEndian()) std::swap(Zero, Four);
2185     SDValue Offset = DAG.getNode(ISD::SELECT, Zero.getValueType(), SignSet,
2186                                  Zero, Four);
2187     unsigned Alignment =
2188       1 << cast<ConstantPoolSDNode>(FudgePtr)->getAlignment();
2189     FudgePtr = DAG.getNode(ISD::ADD, TLI.getPointerTy(), FudgePtr, Offset);
2190     Alignment = std::min(Alignment, 4u);
2191
2192     // Load the value out, extending it from f32 to the destination float type.
2193     // FIXME: Avoid the extend by constructing the right constant pool?
2194     SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, DstVT, DAG.getEntryNode(),
2195                                    FudgePtr, NULL, 0, MVT::f32,
2196                                    false, Alignment);
2197     return DAG.getNode(ISD::FADD, DstVT, SignedConv, Fudge);
2198   }
2199
2200   // Otherwise, use a libcall.
2201   RTLIB::Libcall LC = RTLIB::getUINTTOFP(SrcVT, DstVT);
2202   assert(LC != RTLIB::UNKNOWN_LIBCALL &&
2203          "Don't know how to expand this UINT_TO_FP!");
2204   return MakeLibCall(LC, DstVT, &Op, 1, true);
2205 }