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