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