Lower multiply with overflow checking to __mulo<mode>
[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 #include "llvm/DerivedTypes.h"
23 #include "llvm/CodeGen/PseudoSourceValue.h"
24 #include "llvm/Support/ErrorHandling.h"
25 #include "llvm/Support/raw_ostream.h"
26 using namespace llvm;
27
28 //===----------------------------------------------------------------------===//
29 //  Integer Result Promotion
30 //===----------------------------------------------------------------------===//
31
32 /// PromoteIntegerResult - This method is called when a result of a node is
33 /// found to be in need of promotion to a larger type.  At this point, the node
34 /// may also have invalid operands or may have other results that need
35 /// expansion, we just know that (at least) one result needs promotion.
36 void DAGTypeLegalizer::PromoteIntegerResult(SDNode *N, unsigned ResNo) {
37   DEBUG(dbgs() << "Promote integer result: "; N->dump(&DAG); dbgs() << "\n");
38   SDValue Res = SDValue();
39
40   // See if the target wants to custom expand this node.
41   if (CustomLowerNode(N, N->getValueType(ResNo), true))
42     return;
43
44   switch (N->getOpcode()) {
45   default:
46 #ifndef NDEBUG
47     dbgs() << "PromoteIntegerResult #" << ResNo << ": ";
48     N->dump(&DAG); dbgs() << "\n";
49 #endif
50     llvm_unreachable("Do not know how to promote this operator!");
51   case ISD::AssertSext:  Res = PromoteIntRes_AssertSext(N); break;
52   case ISD::AssertZext:  Res = PromoteIntRes_AssertZext(N); break;
53   case ISD::BITCAST:     Res = PromoteIntRes_BITCAST(N); break;
54   case ISD::BSWAP:       Res = PromoteIntRes_BSWAP(N); break;
55   case ISD::BUILD_PAIR:  Res = PromoteIntRes_BUILD_PAIR(N); break;
56   case ISD::Constant:    Res = PromoteIntRes_Constant(N); break;
57   case ISD::CONVERT_RNDSAT:
58                          Res = PromoteIntRes_CONVERT_RNDSAT(N); break;
59   case ISD::CTLZ:        Res = PromoteIntRes_CTLZ(N); break;
60   case ISD::CTPOP:       Res = PromoteIntRes_CTPOP(N); break;
61   case ISD::CTTZ:        Res = PromoteIntRes_CTTZ(N); break;
62   case ISD::EXTRACT_VECTOR_ELT:
63                          Res = PromoteIntRes_EXTRACT_VECTOR_ELT(N); break;
64   case ISD::LOAD:        Res = PromoteIntRes_LOAD(cast<LoadSDNode>(N));break;
65   case ISD::SELECT:      Res = PromoteIntRes_SELECT(N); break;
66   case ISD::SELECT_CC:   Res = PromoteIntRes_SELECT_CC(N); break;
67   case ISD::SETCC:       Res = PromoteIntRes_SETCC(N); break;
68   case ISD::SHL:         Res = PromoteIntRes_SHL(N); break;
69   case ISD::SIGN_EXTEND_INREG:
70                          Res = PromoteIntRes_SIGN_EXTEND_INREG(N); break;
71   case ISD::SRA:         Res = PromoteIntRes_SRA(N); break;
72   case ISD::SRL:         Res = PromoteIntRes_SRL(N); break;
73   case ISD::TRUNCATE:    Res = PromoteIntRes_TRUNCATE(N); break;
74   case ISD::UNDEF:       Res = PromoteIntRes_UNDEF(N); break;
75   case ISD::VAARG:       Res = PromoteIntRes_VAARG(N); break;
76
77   case ISD::EXTRACT_SUBVECTOR:
78                          Res = PromoteIntRes_EXTRACT_SUBVECTOR(N); break;
79   case ISD::VECTOR_SHUFFLE:
80                          Res = PromoteIntRes_VECTOR_SHUFFLE(N); break;
81   case ISD::INSERT_VECTOR_ELT:
82                          Res = PromoteIntRes_INSERT_VECTOR_ELT(N); break;
83   case ISD::BUILD_VECTOR:
84                          Res = PromoteIntRes_BUILD_VECTOR(N); break;
85   case ISD::SCALAR_TO_VECTOR:
86                          Res = PromoteIntRes_SCALAR_TO_VECTOR(N); break;
87
88   case ISD::SIGN_EXTEND:
89   case ISD::ZERO_EXTEND:
90   case ISD::ANY_EXTEND:  Res = PromoteIntRes_INT_EXTEND(N); break;
91
92   case ISD::FP_TO_SINT:
93   case ISD::FP_TO_UINT:  Res = PromoteIntRes_FP_TO_XINT(N); break;
94
95   case ISD::FP32_TO_FP16:Res = PromoteIntRes_FP32_TO_FP16(N); break;
96
97   case ISD::AND:
98   case ISD::OR:
99   case ISD::XOR:
100   case ISD::ADD:
101   case ISD::SUB:
102   case ISD::MUL:         Res = PromoteIntRes_SimpleIntBinOp(N); break;
103
104   case ISD::SDIV:
105   case ISD::SREM:        Res = PromoteIntRes_SDIV(N); break;
106
107   case ISD::UDIV:
108   case ISD::UREM:        Res = PromoteIntRes_UDIV(N); break;
109
110   case ISD::SADDO:
111   case ISD::SSUBO:       Res = PromoteIntRes_SADDSUBO(N, ResNo); break;
112   case ISD::UADDO:
113   case ISD::USUBO:       Res = PromoteIntRes_UADDSUBO(N, ResNo); break;
114   case ISD::SMULO:
115   case ISD::UMULO:       Res = PromoteIntRes_XMULO(N, ResNo); break;
116
117   case ISD::ATOMIC_LOAD_ADD:
118   case ISD::ATOMIC_LOAD_SUB:
119   case ISD::ATOMIC_LOAD_AND:
120   case ISD::ATOMIC_LOAD_OR:
121   case ISD::ATOMIC_LOAD_XOR:
122   case ISD::ATOMIC_LOAD_NAND:
123   case ISD::ATOMIC_LOAD_MIN:
124   case ISD::ATOMIC_LOAD_MAX:
125   case ISD::ATOMIC_LOAD_UMIN:
126   case ISD::ATOMIC_LOAD_UMAX:
127   case ISD::ATOMIC_SWAP:
128     Res = PromoteIntRes_Atomic1(cast<AtomicSDNode>(N)); break;
129
130   case ISD::ATOMIC_CMP_SWAP:
131     Res = PromoteIntRes_Atomic2(cast<AtomicSDNode>(N)); break;
132   }
133
134   // If the result is null then the sub-method took care of registering it.
135   if (Res.getNode())
136     SetPromotedInteger(SDValue(N, ResNo), Res);
137 }
138
139 SDValue DAGTypeLegalizer::PromoteIntRes_AssertSext(SDNode *N) {
140   // Sign-extend the new bits, and continue the assertion.
141   SDValue Op = SExtPromotedInteger(N->getOperand(0));
142   return DAG.getNode(ISD::AssertSext, N->getDebugLoc(),
143                      Op.getValueType(), Op, N->getOperand(1));
144 }
145
146 SDValue DAGTypeLegalizer::PromoteIntRes_AssertZext(SDNode *N) {
147   // Zero the new bits, and continue the assertion.
148   SDValue Op = ZExtPromotedInteger(N->getOperand(0));
149   return DAG.getNode(ISD::AssertZext, N->getDebugLoc(),
150                      Op.getValueType(), Op, N->getOperand(1));
151 }
152
153 SDValue DAGTypeLegalizer::PromoteIntRes_Atomic1(AtomicSDNode *N) {
154   SDValue Op2 = GetPromotedInteger(N->getOperand(2));
155   SDValue Res = DAG.getAtomic(N->getOpcode(), N->getDebugLoc(),
156                               N->getMemoryVT(),
157                               N->getChain(), N->getBasePtr(),
158                               Op2, N->getMemOperand());
159   // Legalized the chain result - switch anything that used the old chain to
160   // use the new one.
161   ReplaceValueWith(SDValue(N, 1), Res.getValue(1));
162   return Res;
163 }
164
165 SDValue DAGTypeLegalizer::PromoteIntRes_Atomic2(AtomicSDNode *N) {
166   SDValue Op2 = GetPromotedInteger(N->getOperand(2));
167   SDValue Op3 = GetPromotedInteger(N->getOperand(3));
168   SDValue Res = DAG.getAtomic(N->getOpcode(), N->getDebugLoc(),
169                               N->getMemoryVT(), N->getChain(), N->getBasePtr(),
170                               Op2, Op3, N->getMemOperand());
171   // Legalized the chain result - switch anything that used the old chain to
172   // use the new one.
173   ReplaceValueWith(SDValue(N, 1), Res.getValue(1));
174   return Res;
175 }
176
177 SDValue DAGTypeLegalizer::PromoteIntRes_BITCAST(SDNode *N) {
178   SDValue InOp = N->getOperand(0);
179   EVT InVT = InOp.getValueType();
180   EVT NInVT = TLI.getTypeToTransformTo(*DAG.getContext(), InVT);
181   EVT OutVT = N->getValueType(0);
182   EVT NOutVT = TLI.getTypeToTransformTo(*DAG.getContext(), OutVT);
183   DebugLoc dl = N->getDebugLoc();
184
185   switch (getTypeAction(InVT)) {
186   default:
187     assert(false && "Unknown type action!");
188     break;
189   case TargetLowering::TypeLegal:
190     break;
191   case TargetLowering::TypePromoteInteger:
192     if (NOutVT.bitsEq(NInVT))
193       // The input promotes to the same size.  Convert the promoted value.
194       return DAG.getNode(ISD::BITCAST, dl, NOutVT, GetPromotedInteger(InOp));
195     if (NInVT.isVector())
196       // Promote vector element via memory load/store.
197       return DAG.getNode(ISD::ANY_EXTEND, dl, NOutVT,
198                          CreateStackStoreLoad(InOp, OutVT));
199     break;
200   case TargetLowering::TypeSoftenFloat:
201     // Promote the integer operand by hand.
202     return DAG.getNode(ISD::ANY_EXTEND, dl, NOutVT, GetSoftenedFloat(InOp));
203   case TargetLowering::TypeExpandInteger:
204   case TargetLowering::TypeExpandFloat:
205     break;
206   case TargetLowering::TypeScalarizeVector:
207     // Convert the element to an integer and promote it by hand.
208     if (!NOutVT.isVector())
209       return DAG.getNode(ISD::ANY_EXTEND, dl, NOutVT,
210                          BitConvertToInteger(GetScalarizedVector(InOp)));
211     break;
212   case TargetLowering::TypeSplitVector: {
213     // For example, i32 = BITCAST v2i16 on alpha.  Convert the split
214     // pieces of the input into integers and reassemble in the final type.
215     SDValue Lo, Hi;
216     GetSplitVector(N->getOperand(0), Lo, Hi);
217     Lo = BitConvertToInteger(Lo);
218     Hi = BitConvertToInteger(Hi);
219
220     if (TLI.isBigEndian())
221       std::swap(Lo, Hi);
222
223     InOp = DAG.getNode(ISD::ANY_EXTEND, dl,
224                        EVT::getIntegerVT(*DAG.getContext(),
225                                          NOutVT.getSizeInBits()),
226                        JoinIntegers(Lo, Hi));
227     return DAG.getNode(ISD::BITCAST, dl, NOutVT, InOp);
228   }
229   case TargetLowering::TypeWidenVector:
230     if (OutVT.bitsEq(NInVT))
231       // The input is widened to the same size.  Convert to the widened value.
232       return DAG.getNode(ISD::BITCAST, dl, OutVT, GetWidenedVector(InOp));
233   }
234
235   return DAG.getNode(ISD::ANY_EXTEND, dl, NOutVT,
236                      CreateStackStoreLoad(InOp, OutVT));
237 }
238
239 SDValue DAGTypeLegalizer::PromoteIntRes_BSWAP(SDNode *N) {
240   SDValue Op = GetPromotedInteger(N->getOperand(0));
241   EVT OVT = N->getValueType(0);
242   EVT NVT = Op.getValueType();
243   DebugLoc dl = N->getDebugLoc();
244
245   unsigned DiffBits = NVT.getSizeInBits() - OVT.getSizeInBits();
246   return DAG.getNode(ISD::SRL, dl, NVT, DAG.getNode(ISD::BSWAP, dl, NVT, Op),
247                      DAG.getConstant(DiffBits, TLI.getPointerTy()));
248 }
249
250 SDValue DAGTypeLegalizer::PromoteIntRes_BUILD_PAIR(SDNode *N) {
251   // The pair element type may be legal, or may not promote to the same type as
252   // the result, for example i14 = BUILD_PAIR (i7, i7).  Handle all cases.
253   return DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(),
254                      TLI.getTypeToTransformTo(*DAG.getContext(),
255                      N->getValueType(0)), JoinIntegers(N->getOperand(0),
256                      N->getOperand(1)));
257 }
258
259 SDValue DAGTypeLegalizer::PromoteIntRes_Constant(SDNode *N) {
260   EVT VT = N->getValueType(0);
261   // FIXME there is no actual debug info here
262   DebugLoc dl = N->getDebugLoc();
263   // Zero extend things like i1, sign extend everything else.  It shouldn't
264   // matter in theory which one we pick, but this tends to give better code?
265   unsigned Opc = VT.isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
266   SDValue Result = DAG.getNode(Opc, dl,
267                                TLI.getTypeToTransformTo(*DAG.getContext(), VT),
268                                SDValue(N, 0));
269   assert(isa<ConstantSDNode>(Result) && "Didn't constant fold ext?");
270   return Result;
271 }
272
273 SDValue DAGTypeLegalizer::PromoteIntRes_CONVERT_RNDSAT(SDNode *N) {
274   ISD::CvtCode CvtCode = cast<CvtRndSatSDNode>(N)->getCvtCode();
275   assert ((CvtCode == ISD::CVT_SS || CvtCode == ISD::CVT_SU ||
276            CvtCode == ISD::CVT_US || CvtCode == ISD::CVT_UU ||
277            CvtCode == ISD::CVT_SF || CvtCode == ISD::CVT_UF) &&
278           "can only promote integers");
279   EVT OutVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
280   return DAG.getConvertRndSat(OutVT, N->getDebugLoc(), N->getOperand(0),
281                               N->getOperand(1), N->getOperand(2),
282                               N->getOperand(3), N->getOperand(4), CvtCode);
283 }
284
285 SDValue DAGTypeLegalizer::PromoteIntRes_CTLZ(SDNode *N) {
286   // Zero extend to the promoted type and do the count there.
287   SDValue Op = ZExtPromotedInteger(N->getOperand(0));
288   DebugLoc dl = N->getDebugLoc();
289   EVT OVT = N->getValueType(0);
290   EVT NVT = Op.getValueType();
291   Op = DAG.getNode(ISD::CTLZ, dl, NVT, Op);
292   // Subtract off the extra leading bits in the bigger type.
293   return DAG.getNode(ISD::SUB, dl, NVT, Op,
294                      DAG.getConstant(NVT.getSizeInBits() -
295                                      OVT.getSizeInBits(), NVT));
296 }
297
298 SDValue DAGTypeLegalizer::PromoteIntRes_CTPOP(SDNode *N) {
299   // Zero extend to the promoted type and do the count there.
300   SDValue Op = ZExtPromotedInteger(N->getOperand(0));
301   return DAG.getNode(ISD::CTPOP, N->getDebugLoc(), Op.getValueType(), Op);
302 }
303
304 SDValue DAGTypeLegalizer::PromoteIntRes_CTTZ(SDNode *N) {
305   SDValue Op = GetPromotedInteger(N->getOperand(0));
306   EVT OVT = N->getValueType(0);
307   EVT NVT = Op.getValueType();
308   DebugLoc dl = N->getDebugLoc();
309   // The count is the same in the promoted type except if the original
310   // value was zero.  This can be handled by setting the bit just off
311   // the top of the original type.
312   APInt TopBit(NVT.getSizeInBits(), 0);
313   TopBit.setBit(OVT.getSizeInBits());
314   Op = DAG.getNode(ISD::OR, dl, NVT, Op, DAG.getConstant(TopBit, NVT));
315   return DAG.getNode(ISD::CTTZ, dl, NVT, Op);
316 }
317
318 SDValue DAGTypeLegalizer::PromoteIntRes_EXTRACT_VECTOR_ELT(SDNode *N) {
319   DebugLoc dl = N->getDebugLoc();
320   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
321   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, NVT, N->getOperand(0),
322                      N->getOperand(1));
323 }
324
325 SDValue DAGTypeLegalizer::PromoteIntRes_FP_TO_XINT(SDNode *N) {
326   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
327   unsigned NewOpc = N->getOpcode();
328   DebugLoc dl = N->getDebugLoc();
329
330   // If we're promoting a UINT to a larger size and the larger FP_TO_UINT is
331   // not Legal, check to see if we can use FP_TO_SINT instead.  (If both UINT
332   // and SINT conversions are Custom, there is no way to tell which is
333   // preferable. We choose SINT because that's the right thing on PPC.)
334   if (N->getOpcode() == ISD::FP_TO_UINT &&
335       !TLI.isOperationLegal(ISD::FP_TO_UINT, NVT) &&
336       TLI.isOperationLegalOrCustom(ISD::FP_TO_SINT, NVT))
337     NewOpc = ISD::FP_TO_SINT;
338
339   SDValue Res = DAG.getNode(NewOpc, dl, NVT, N->getOperand(0));
340
341   // Assert that the converted value fits in the original type.  If it doesn't
342   // (eg: because the value being converted is too big), then the result of the
343   // original operation was undefined anyway, so the assert is still correct.
344   return DAG.getNode(N->getOpcode() == ISD::FP_TO_UINT ?
345                      ISD::AssertZext : ISD::AssertSext, dl,
346                      NVT, Res, DAG.getValueType(N->getValueType(0)));
347 }
348
349 SDValue DAGTypeLegalizer::PromoteIntRes_FP32_TO_FP16(SDNode *N) {
350   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
351   DebugLoc dl = N->getDebugLoc();
352
353   SDValue Res = DAG.getNode(N->getOpcode(), dl, NVT, N->getOperand(0));
354
355   return DAG.getNode(ISD::AssertZext, dl,
356                      NVT, Res, DAG.getValueType(N->getValueType(0)));
357 }
358
359 SDValue DAGTypeLegalizer::PromoteIntRes_INT_EXTEND(SDNode *N) {
360   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
361   DebugLoc dl = N->getDebugLoc();
362
363   if (getTypeAction(N->getOperand(0).getValueType())
364       == TargetLowering::TypePromoteInteger) {
365     SDValue Res = GetPromotedInteger(N->getOperand(0));
366     assert(Res.getValueType().bitsLE(NVT) && "Extension doesn't make sense!");
367
368     // If the result and operand types are the same after promotion, simplify
369     // to an in-register extension.
370     if (NVT == Res.getValueType()) {
371       // The high bits are not guaranteed to be anything.  Insert an extend.
372       if (N->getOpcode() == ISD::SIGN_EXTEND)
373         return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NVT, Res,
374                            DAG.getValueType(N->getOperand(0).getValueType()));
375       if (N->getOpcode() == ISD::ZERO_EXTEND)
376         return DAG.getZeroExtendInReg(Res, dl, N->getOperand(0).getValueType());
377       assert(N->getOpcode() == ISD::ANY_EXTEND && "Unknown integer extension!");
378       return Res;
379     }
380   }
381
382   // Otherwise, just extend the original operand all the way to the larger type.
383   return DAG.getNode(N->getOpcode(), dl, NVT, N->getOperand(0));
384 }
385
386 SDValue DAGTypeLegalizer::PromoteIntRes_LOAD(LoadSDNode *N) {
387   assert(ISD::isUNINDEXEDLoad(N) && "Indexed load during type legalization!");
388   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
389   ISD::LoadExtType ExtType =
390     ISD::isNON_EXTLoad(N) ? ISD::EXTLOAD : N->getExtensionType();
391   DebugLoc dl = N->getDebugLoc();
392   SDValue Res = DAG.getExtLoad(ExtType, dl, NVT, N->getChain(), N->getBasePtr(),
393                                N->getPointerInfo(),
394                                N->getMemoryVT(), N->isVolatile(),
395                                N->isNonTemporal(), N->getAlignment());
396
397   // Legalized the chain result - switch anything that used the old chain to
398   // use the new one.
399   ReplaceValueWith(SDValue(N, 1), Res.getValue(1));
400   return Res;
401 }
402
403 /// Promote the overflow flag of an overflowing arithmetic node.
404 SDValue DAGTypeLegalizer::PromoteIntRes_Overflow(SDNode *N) {
405   // Simply change the return type of the boolean result.
406   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(1));
407   EVT ValueVTs[] = { N->getValueType(0), NVT };
408   SDValue Ops[] = { N->getOperand(0), N->getOperand(1) };
409   SDValue Res = DAG.getNode(N->getOpcode(), N->getDebugLoc(),
410                             DAG.getVTList(ValueVTs, 2), Ops, 2);
411
412   // Modified the sum result - switch anything that used the old sum to use
413   // the new one.
414   ReplaceValueWith(SDValue(N, 0), Res);
415
416   return SDValue(Res.getNode(), 1);
417 }
418
419 SDValue DAGTypeLegalizer::PromoteIntRes_SADDSUBO(SDNode *N, unsigned ResNo) {
420   if (ResNo == 1)
421     return PromoteIntRes_Overflow(N);
422
423   // The operation overflowed iff the result in the larger type is not the
424   // sign extension of its truncation to the original type.
425   SDValue LHS = SExtPromotedInteger(N->getOperand(0));
426   SDValue RHS = SExtPromotedInteger(N->getOperand(1));
427   EVT OVT = N->getOperand(0).getValueType();
428   EVT NVT = LHS.getValueType();
429   DebugLoc dl = N->getDebugLoc();
430
431   // Do the arithmetic in the larger type.
432   unsigned Opcode = N->getOpcode() == ISD::SADDO ? ISD::ADD : ISD::SUB;
433   SDValue Res = DAG.getNode(Opcode, dl, NVT, LHS, RHS);
434
435   // Calculate the overflow flag: sign extend the arithmetic result from
436   // the original type.
437   SDValue Ofl = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NVT, Res,
438                             DAG.getValueType(OVT));
439   // Overflowed if and only if this is not equal to Res.
440   Ofl = DAG.getSetCC(dl, N->getValueType(1), Ofl, Res, ISD::SETNE);
441
442   // Use the calculated overflow everywhere.
443   ReplaceValueWith(SDValue(N, 1), Ofl);
444
445   return Res;
446 }
447
448 SDValue DAGTypeLegalizer::PromoteIntRes_SDIV(SDNode *N) {
449   // Sign extend the input.
450   SDValue LHS = SExtPromotedInteger(N->getOperand(0));
451   SDValue RHS = SExtPromotedInteger(N->getOperand(1));
452   return DAG.getNode(N->getOpcode(), N->getDebugLoc(),
453                      LHS.getValueType(), LHS, RHS);
454 }
455
456 SDValue DAGTypeLegalizer::PromoteIntRes_SELECT(SDNode *N) {
457   SDValue LHS = GetPromotedInteger(N->getOperand(1));
458   SDValue RHS = GetPromotedInteger(N->getOperand(2));
459   return DAG.getNode(ISD::SELECT, N->getDebugLoc(),
460                      LHS.getValueType(), N->getOperand(0),LHS,RHS);
461 }
462
463 SDValue DAGTypeLegalizer::PromoteIntRes_SELECT_CC(SDNode *N) {
464   SDValue LHS = GetPromotedInteger(N->getOperand(2));
465   SDValue RHS = GetPromotedInteger(N->getOperand(3));
466   return DAG.getNode(ISD::SELECT_CC, N->getDebugLoc(),
467                      LHS.getValueType(), N->getOperand(0),
468                      N->getOperand(1), LHS, RHS, N->getOperand(4));
469 }
470
471 SDValue DAGTypeLegalizer::PromoteIntRes_SETCC(SDNode *N) {
472   EVT SVT = TLI.getSetCCResultType(N->getOperand(0).getValueType());
473   assert(isTypeLegal(SVT) && "Illegal SetCC type!");
474   DebugLoc dl = N->getDebugLoc();
475
476   // Get the SETCC result using the canonical SETCC type.
477   SDValue SetCC = DAG.getNode(ISD::SETCC, dl, SVT, N->getOperand(0),
478                               N->getOperand(1), N->getOperand(2));
479
480   // Convert to the expected type.
481   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
482   assert(NVT.bitsLE(SVT) && "Integer type overpromoted?");
483   return DAG.getNode(ISD::TRUNCATE, dl, NVT, SetCC);
484 }
485
486 SDValue DAGTypeLegalizer::PromoteIntRes_SHL(SDNode *N) {
487   return DAG.getNode(ISD::SHL, N->getDebugLoc(),
488                 TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0)),
489                      GetPromotedInteger(N->getOperand(0)), N->getOperand(1));
490 }
491
492 SDValue DAGTypeLegalizer::PromoteIntRes_SIGN_EXTEND_INREG(SDNode *N) {
493   SDValue Op = GetPromotedInteger(N->getOperand(0));
494   return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(),
495                      Op.getValueType(), Op, N->getOperand(1));
496 }
497
498 SDValue DAGTypeLegalizer::PromoteIntRes_SimpleIntBinOp(SDNode *N) {
499   // The input may have strange things in the top bits of the registers, but
500   // these operations don't care.  They may have weird bits going out, but
501   // that too is okay if they are integer operations.
502   SDValue LHS = GetPromotedInteger(N->getOperand(0));
503   SDValue RHS = GetPromotedInteger(N->getOperand(1));
504   return DAG.getNode(N->getOpcode(), N->getDebugLoc(),
505                     LHS.getValueType(), LHS, RHS);
506 }
507
508 SDValue DAGTypeLegalizer::PromoteIntRes_SRA(SDNode *N) {
509   // The input value must be properly sign extended.
510   SDValue Res = SExtPromotedInteger(N->getOperand(0));
511   return DAG.getNode(ISD::SRA, N->getDebugLoc(),
512                      Res.getValueType(), Res, N->getOperand(1));
513 }
514
515 SDValue DAGTypeLegalizer::PromoteIntRes_SRL(SDNode *N) {
516   // The input value must be properly zero extended.
517   EVT VT = N->getValueType(0);
518   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), VT);
519   SDValue Res = ZExtPromotedInteger(N->getOperand(0));
520   return DAG.getNode(ISD::SRL, N->getDebugLoc(), NVT, Res, N->getOperand(1));
521 }
522
523 SDValue DAGTypeLegalizer::PromoteIntRes_TRUNCATE(SDNode *N) {
524   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
525   SDValue Res;
526
527   switch (getTypeAction(N->getOperand(0).getValueType())) {
528   default: llvm_unreachable("Unknown type action!");
529   case TargetLowering::TypeLegal:
530   case TargetLowering::TypeExpandInteger:
531     Res = N->getOperand(0);
532     break;
533   case TargetLowering::TypePromoteInteger:
534     Res = GetPromotedInteger(N->getOperand(0));
535     break;
536   }
537
538   // Truncate to NVT instead of VT
539   return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), NVT, Res);
540 }
541
542 SDValue DAGTypeLegalizer::PromoteIntRes_UADDSUBO(SDNode *N, unsigned ResNo) {
543   if (ResNo == 1)
544     return PromoteIntRes_Overflow(N);
545
546   // The operation overflowed iff the result in the larger type is not the
547   // zero extension of its truncation to the original type.
548   SDValue LHS = ZExtPromotedInteger(N->getOperand(0));
549   SDValue RHS = ZExtPromotedInteger(N->getOperand(1));
550   EVT OVT = N->getOperand(0).getValueType();
551   EVT NVT = LHS.getValueType();
552   DebugLoc dl = N->getDebugLoc();
553
554   // Do the arithmetic in the larger type.
555   unsigned Opcode = N->getOpcode() == ISD::UADDO ? ISD::ADD : ISD::SUB;
556   SDValue Res = DAG.getNode(Opcode, dl, NVT, LHS, RHS);
557
558   // Calculate the overflow flag: zero extend the arithmetic result from
559   // the original type.
560   SDValue Ofl = DAG.getZeroExtendInReg(Res, dl, OVT);
561   // Overflowed if and only if this is not equal to Res.
562   Ofl = DAG.getSetCC(dl, N->getValueType(1), Ofl, Res, ISD::SETNE);
563
564   // Use the calculated overflow everywhere.
565   ReplaceValueWith(SDValue(N, 1), Ofl);
566
567   return Res;
568 }
569
570 SDValue DAGTypeLegalizer::PromoteIntRes_XMULO(SDNode *N, unsigned ResNo) {
571   // Promote the overflow bit trivially.
572   if (ResNo == 1)
573     return PromoteIntRes_Overflow(N);
574
575   SDValue LHS = N->getOperand(0), RHS = N->getOperand(1);
576   DebugLoc DL = N->getDebugLoc();
577   EVT SmallVT = LHS.getValueType();
578
579   // To determine if the result overflowed in a larger type, we extend the
580   // input to the larger type, do the multiply, then check the high bits of
581   // the result to see if the overflow happened.
582   if (N->getOpcode() == ISD::SMULO) {
583     LHS = SExtPromotedInteger(LHS);
584     RHS = SExtPromotedInteger(RHS);
585   } else {
586     LHS = ZExtPromotedInteger(LHS);
587     RHS = ZExtPromotedInteger(RHS);
588   }
589   SDValue Mul = DAG.getNode(ISD::MUL, DL, LHS.getValueType(), LHS, RHS);
590
591   // Overflow occurred iff the high part of the result does not
592   // zero/sign-extend the low part.
593   SDValue Overflow;
594   if (N->getOpcode() == ISD::UMULO) {
595     // Unsigned overflow occurred iff the high part is non-zero.
596     SDValue Hi = DAG.getNode(ISD::SRL, DL, Mul.getValueType(), Mul,
597                              DAG.getIntPtrConstant(SmallVT.getSizeInBits()));
598     Overflow = DAG.getSetCC(DL, N->getValueType(1), Hi,
599                             DAG.getConstant(0, Hi.getValueType()), ISD::SETNE);
600   } else {
601     // Signed overflow occurred iff the high part does not sign extend the low.
602     SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, Mul.getValueType(),
603                                Mul, DAG.getValueType(SmallVT));
604     Overflow = DAG.getSetCC(DL, N->getValueType(1), SExt, Mul, ISD::SETNE);
605   }
606
607   // Use the calculated overflow everywhere.
608   ReplaceValueWith(SDValue(N, 1), Overflow);
609   return Mul;
610 }
611
612 SDValue DAGTypeLegalizer::PromoteIntRes_UDIV(SDNode *N) {
613   // Zero extend the input.
614   SDValue LHS = ZExtPromotedInteger(N->getOperand(0));
615   SDValue RHS = ZExtPromotedInteger(N->getOperand(1));
616   return DAG.getNode(N->getOpcode(), N->getDebugLoc(),
617                      LHS.getValueType(), LHS, RHS);
618 }
619
620 SDValue DAGTypeLegalizer::PromoteIntRes_UNDEF(SDNode *N) {
621   return DAG.getUNDEF(TLI.getTypeToTransformTo(*DAG.getContext(),
622                                                N->getValueType(0)));
623 }
624
625 SDValue DAGTypeLegalizer::PromoteIntRes_VAARG(SDNode *N) {
626   SDValue Chain = N->getOperand(0); // Get the chain.
627   SDValue Ptr = N->getOperand(1); // Get the pointer.
628   EVT VT = N->getValueType(0);
629   DebugLoc dl = N->getDebugLoc();
630
631   EVT RegVT = TLI.getRegisterType(*DAG.getContext(), VT);
632   unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), VT);
633   // The argument is passed as NumRegs registers of type RegVT.
634
635   SmallVector<SDValue, 8> Parts(NumRegs);
636   for (unsigned i = 0; i < NumRegs; ++i) {
637     Parts[i] = DAG.getVAArg(RegVT, dl, Chain, Ptr, N->getOperand(2),
638                             N->getConstantOperandVal(3));
639     Chain = Parts[i].getValue(1);
640   }
641
642   // Handle endianness of the load.
643   if (TLI.isBigEndian())
644     std::reverse(Parts.begin(), Parts.end());
645
646   // Assemble the parts in the promoted type.
647   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
648   SDValue Res = DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, Parts[0]);
649   for (unsigned i = 1; i < NumRegs; ++i) {
650     SDValue Part = DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, Parts[i]);
651     // Shift it to the right position and "or" it in.
652     Part = DAG.getNode(ISD::SHL, dl, NVT, Part,
653                        DAG.getConstant(i * RegVT.getSizeInBits(),
654                                        TLI.getPointerTy()));
655     Res = DAG.getNode(ISD::OR, dl, NVT, Res, Part);
656   }
657
658   // Modified the chain result - switch anything that used the old chain to
659   // use the new one.
660   ReplaceValueWith(SDValue(N, 1), Chain);
661
662   return Res;
663 }
664
665 //===----------------------------------------------------------------------===//
666 //  Integer Operand Promotion
667 //===----------------------------------------------------------------------===//
668
669 /// PromoteIntegerOperand - This method is called when the specified operand of
670 /// the specified node is found to need promotion.  At this point, all of the
671 /// result types of the node are known to be legal, but other operands of the
672 /// node may need promotion or expansion as well as the specified one.
673 bool DAGTypeLegalizer::PromoteIntegerOperand(SDNode *N, unsigned OpNo) {
674   DEBUG(dbgs() << "Promote integer operand: "; N->dump(&DAG); dbgs() << "\n");
675   SDValue Res = SDValue();
676
677   if (CustomLowerNode(N, N->getOperand(OpNo).getValueType(), false))
678     return false;
679
680   switch (N->getOpcode()) {
681     default:
682   #ifndef NDEBUG
683     dbgs() << "PromoteIntegerOperand Op #" << OpNo << ": ";
684     N->dump(&DAG); dbgs() << "\n";
685   #endif
686     llvm_unreachable("Do not know how to promote this operator's operand!");
687
688   case ISD::ANY_EXTEND:   Res = PromoteIntOp_ANY_EXTEND(N); break;
689   case ISD::BITCAST:      Res = PromoteIntOp_BITCAST(N); break;
690   case ISD::BR_CC:        Res = PromoteIntOp_BR_CC(N, OpNo); break;
691   case ISD::BRCOND:       Res = PromoteIntOp_BRCOND(N, OpNo); break;
692   case ISD::BUILD_PAIR:   Res = PromoteIntOp_BUILD_PAIR(N); break;
693   case ISD::BUILD_VECTOR: Res = PromoteIntOp_BUILD_VECTOR(N); break;
694   case ISD::CONCAT_VECTORS: Res = PromoteIntOp_CONCAT_VECTORS(N); break;
695   case ISD::EXTRACT_VECTOR_ELT: Res = PromoteIntOp_EXTRACT_VECTOR_ELT(N); break;
696   case ISD::CONVERT_RNDSAT:
697                           Res = PromoteIntOp_CONVERT_RNDSAT(N); break;
698   case ISD::INSERT_VECTOR_ELT:
699                           Res = PromoteIntOp_INSERT_VECTOR_ELT(N, OpNo);break;
700   case ISD::MEMBARRIER:   Res = PromoteIntOp_MEMBARRIER(N); break;
701   case ISD::SCALAR_TO_VECTOR:
702                           Res = PromoteIntOp_SCALAR_TO_VECTOR(N); break;
703   case ISD::SELECT:       Res = PromoteIntOp_SELECT(N, OpNo); break;
704   case ISD::SELECT_CC:    Res = PromoteIntOp_SELECT_CC(N, OpNo); break;
705   case ISD::SETCC:        Res = PromoteIntOp_SETCC(N, OpNo); break;
706   case ISD::SIGN_EXTEND:  Res = PromoteIntOp_SIGN_EXTEND(N); break;
707   case ISD::SINT_TO_FP:   Res = PromoteIntOp_SINT_TO_FP(N); break;
708   case ISD::STORE:        Res = PromoteIntOp_STORE(cast<StoreSDNode>(N),
709                                                    OpNo); break;
710   case ISD::TRUNCATE:     Res = PromoteIntOp_TRUNCATE(N); break;
711   case ISD::FP16_TO_FP32:
712   case ISD::UINT_TO_FP:   Res = PromoteIntOp_UINT_TO_FP(N); break;
713   case ISD::ZERO_EXTEND:  Res = PromoteIntOp_ZERO_EXTEND(N); break;
714
715   case ISD::SHL:
716   case ISD::SRA:
717   case ISD::SRL:
718   case ISD::ROTL:
719   case ISD::ROTR: Res = PromoteIntOp_Shift(N); break;
720   }
721
722   // If the result is null, the sub-method took care of registering results etc.
723   if (!Res.getNode()) return false;
724
725   // If the result is N, the sub-method updated N in place.  Tell the legalizer
726   // core about this.
727   if (Res.getNode() == N)
728     return true;
729
730   assert(Res.getValueType() == N->getValueType(0) && N->getNumValues() == 1 &&
731          "Invalid operand expansion");
732
733   ReplaceValueWith(SDValue(N, 0), Res);
734   return false;
735 }
736
737 /// PromoteSetCCOperands - Promote the operands of a comparison.  This code is
738 /// shared among BR_CC, SELECT_CC, and SETCC handlers.
739 void DAGTypeLegalizer::PromoteSetCCOperands(SDValue &NewLHS,SDValue &NewRHS,
740                                             ISD::CondCode CCCode) {
741   // We have to insert explicit sign or zero extends.  Note that we could
742   // insert sign extends for ALL conditions, but zero extend is cheaper on
743   // many machines (an AND instead of two shifts), so prefer it.
744   switch (CCCode) {
745   default: llvm_unreachable("Unknown integer comparison!");
746   case ISD::SETEQ:
747   case ISD::SETNE:
748   case ISD::SETUGE:
749   case ISD::SETUGT:
750   case ISD::SETULE:
751   case ISD::SETULT:
752     // ALL of these operations will work if we either sign or zero extend
753     // the operands (including the unsigned comparisons!).  Zero extend is
754     // usually a simpler/cheaper operation, so prefer it.
755     NewLHS = ZExtPromotedInteger(NewLHS);
756     NewRHS = ZExtPromotedInteger(NewRHS);
757     break;
758   case ISD::SETGE:
759   case ISD::SETGT:
760   case ISD::SETLT:
761   case ISD::SETLE:
762     NewLHS = SExtPromotedInteger(NewLHS);
763     NewRHS = SExtPromotedInteger(NewRHS);
764     break;
765   }
766 }
767
768 SDValue DAGTypeLegalizer::PromoteIntOp_ANY_EXTEND(SDNode *N) {
769   SDValue Op = GetPromotedInteger(N->getOperand(0));
770   return DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), N->getValueType(0), Op);
771 }
772
773 SDValue DAGTypeLegalizer::PromoteIntOp_BITCAST(SDNode *N) {
774   // This should only occur in unusual situations like bitcasting to an
775   // x86_fp80, so just turn it into a store+load
776   return CreateStackStoreLoad(N->getOperand(0), N->getValueType(0));
777 }
778
779 SDValue DAGTypeLegalizer::PromoteIntOp_BR_CC(SDNode *N, unsigned OpNo) {
780   assert(OpNo == 2 && "Don't know how to promote this operand!");
781
782   SDValue LHS = N->getOperand(2);
783   SDValue RHS = N->getOperand(3);
784   PromoteSetCCOperands(LHS, RHS, cast<CondCodeSDNode>(N->getOperand(1))->get());
785
786   // The chain (Op#0), CC (#1) and basic block destination (Op#4) are always
787   // legal types.
788   return SDValue(DAG.UpdateNodeOperands(N, N->getOperand(0),
789                                 N->getOperand(1), LHS, RHS, N->getOperand(4)),
790                  0);
791 }
792
793 SDValue DAGTypeLegalizer::PromoteIntOp_BRCOND(SDNode *N, unsigned OpNo) {
794   assert(OpNo == 1 && "only know how to promote condition");
795
796   // Promote all the way up to the canonical SetCC type.
797   EVT SVT = TLI.getSetCCResultType(MVT::Other);
798   SDValue Cond = PromoteTargetBoolean(N->getOperand(1), SVT);
799
800   // The chain (Op#0) and basic block destination (Op#2) are always legal types.
801   return SDValue(DAG.UpdateNodeOperands(N, N->getOperand(0), Cond,
802                                         N->getOperand(2)), 0);
803 }
804
805 SDValue DAGTypeLegalizer::PromoteIntOp_BUILD_PAIR(SDNode *N) {
806   // Since the result type is legal, the operands must promote to it.
807   EVT OVT = N->getOperand(0).getValueType();
808   SDValue Lo = ZExtPromotedInteger(N->getOperand(0));
809   SDValue Hi = GetPromotedInteger(N->getOperand(1));
810   assert(Lo.getValueType() == N->getValueType(0) && "Operand over promoted?");
811   DebugLoc dl = N->getDebugLoc();
812
813   Hi = DAG.getNode(ISD::SHL, dl, N->getValueType(0), Hi,
814                    DAG.getConstant(OVT.getSizeInBits(), TLI.getPointerTy()));
815   return DAG.getNode(ISD::OR, dl, N->getValueType(0), Lo, Hi);
816 }
817
818 SDValue DAGTypeLegalizer::PromoteIntOp_BUILD_VECTOR(SDNode *N) {
819   // The vector type is legal but the element type is not.  This implies
820   // that the vector is a power-of-two in length and that the element
821   // type does not have a strange size (eg: it is not i1).
822   EVT VecVT = N->getValueType(0);
823   unsigned NumElts = VecVT.getVectorNumElements();
824   assert(!(NumElts & 1) && "Legal vector of one illegal element?");
825
826   // Promote the inserted value.  The type does not need to match the
827   // vector element type.  Check that any extra bits introduced will be
828   // truncated away.
829   assert(N->getOperand(0).getValueType().getSizeInBits() >=
830          N->getValueType(0).getVectorElementType().getSizeInBits() &&
831          "Type of inserted value narrower than vector element type!");
832
833   SmallVector<SDValue, 16> NewOps;
834   for (unsigned i = 0; i < NumElts; ++i)
835     NewOps.push_back(GetPromotedInteger(N->getOperand(i)));
836
837   return SDValue(DAG.UpdateNodeOperands(N, &NewOps[0], NumElts), 0);
838 }
839
840 SDValue DAGTypeLegalizer::PromoteIntOp_CONVERT_RNDSAT(SDNode *N) {
841   ISD::CvtCode CvtCode = cast<CvtRndSatSDNode>(N)->getCvtCode();
842   assert ((CvtCode == ISD::CVT_SS || CvtCode == ISD::CVT_SU ||
843            CvtCode == ISD::CVT_US || CvtCode == ISD::CVT_UU ||
844            CvtCode == ISD::CVT_FS || CvtCode == ISD::CVT_FU) &&
845            "can only promote integer arguments");
846   SDValue InOp = GetPromotedInteger(N->getOperand(0));
847   return DAG.getConvertRndSat(N->getValueType(0), N->getDebugLoc(), InOp,
848                               N->getOperand(1), N->getOperand(2),
849                               N->getOperand(3), N->getOperand(4), CvtCode);
850 }
851
852 SDValue DAGTypeLegalizer::PromoteIntOp_INSERT_VECTOR_ELT(SDNode *N,
853                                                          unsigned OpNo) {
854   if (OpNo == 1) {
855     // Promote the inserted value.  This is valid because the type does not
856     // have to match the vector element type.
857
858     // Check that any extra bits introduced will be truncated away.
859     assert(N->getOperand(1).getValueType().getSizeInBits() >=
860            N->getValueType(0).getVectorElementType().getSizeInBits() &&
861            "Type of inserted value narrower than vector element type!");
862     return SDValue(DAG.UpdateNodeOperands(N, N->getOperand(0),
863                                   GetPromotedInteger(N->getOperand(1)),
864                                   N->getOperand(2)),
865                    0);
866   }
867
868   assert(OpNo == 2 && "Different operand and result vector types?");
869
870   // Promote the index.
871   SDValue Idx = ZExtPromotedInteger(N->getOperand(2));
872   return SDValue(DAG.UpdateNodeOperands(N, N->getOperand(0),
873                                 N->getOperand(1), Idx), 0);
874 }
875
876 SDValue DAGTypeLegalizer::PromoteIntOp_MEMBARRIER(SDNode *N) {
877   SDValue NewOps[6];
878   DebugLoc dl = N->getDebugLoc();
879   NewOps[0] = N->getOperand(0);
880   for (unsigned i = 1; i < array_lengthof(NewOps); ++i) {
881     SDValue Flag = GetPromotedInteger(N->getOperand(i));
882     NewOps[i] = DAG.getZeroExtendInReg(Flag, dl, MVT::i1);
883   }
884   return SDValue(DAG.UpdateNodeOperands(N, NewOps, array_lengthof(NewOps)), 0);
885 }
886
887 SDValue DAGTypeLegalizer::PromoteIntOp_SCALAR_TO_VECTOR(SDNode *N) {
888   // Integer SCALAR_TO_VECTOR operands are implicitly truncated, so just promote
889   // the operand in place.
890   return SDValue(DAG.UpdateNodeOperands(N,
891                                 GetPromotedInteger(N->getOperand(0))), 0);
892 }
893
894 SDValue DAGTypeLegalizer::PromoteIntOp_SELECT(SDNode *N, unsigned OpNo) {
895   assert(OpNo == 0 && "Only know how to promote condition");
896
897   // Promote all the way up to the canonical SetCC type.
898   EVT SVT = TLI.getSetCCResultType(N->getOperand(1).getValueType());
899   SDValue Cond = PromoteTargetBoolean(N->getOperand(0), SVT);
900
901   return SDValue(DAG.UpdateNodeOperands(N, Cond,
902                                 N->getOperand(1), N->getOperand(2)), 0);
903 }
904
905 SDValue DAGTypeLegalizer::PromoteIntOp_SELECT_CC(SDNode *N, unsigned OpNo) {
906   assert(OpNo == 0 && "Don't know how to promote this operand!");
907
908   SDValue LHS = N->getOperand(0);
909   SDValue RHS = N->getOperand(1);
910   PromoteSetCCOperands(LHS, RHS, cast<CondCodeSDNode>(N->getOperand(4))->get());
911
912   // The CC (#4) and the possible return values (#2 and #3) have legal types.
913   return SDValue(DAG.UpdateNodeOperands(N, LHS, RHS, N->getOperand(2),
914                                 N->getOperand(3), N->getOperand(4)), 0);
915 }
916
917 SDValue DAGTypeLegalizer::PromoteIntOp_SETCC(SDNode *N, unsigned OpNo) {
918   assert(OpNo == 0 && "Don't know how to promote this operand!");
919
920   SDValue LHS = N->getOperand(0);
921   SDValue RHS = N->getOperand(1);
922   PromoteSetCCOperands(LHS, RHS, cast<CondCodeSDNode>(N->getOperand(2))->get());
923
924   // The CC (#2) is always legal.
925   return SDValue(DAG.UpdateNodeOperands(N, LHS, RHS, N->getOperand(2)), 0);
926 }
927
928 SDValue DAGTypeLegalizer::PromoteIntOp_Shift(SDNode *N) {
929   return SDValue(DAG.UpdateNodeOperands(N, N->getOperand(0),
930                                 ZExtPromotedInteger(N->getOperand(1))), 0);
931 }
932
933 SDValue DAGTypeLegalizer::PromoteIntOp_SIGN_EXTEND(SDNode *N) {
934   SDValue Op = GetPromotedInteger(N->getOperand(0));
935   DebugLoc dl = N->getDebugLoc();
936   Op = DAG.getNode(ISD::ANY_EXTEND, dl, N->getValueType(0), Op);
937   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, Op.getValueType(),
938                      Op, DAG.getValueType(N->getOperand(0).getValueType()));
939 }
940
941 SDValue DAGTypeLegalizer::PromoteIntOp_SINT_TO_FP(SDNode *N) {
942   return SDValue(DAG.UpdateNodeOperands(N,
943                                 SExtPromotedInteger(N->getOperand(0))), 0);
944 }
945
946 SDValue DAGTypeLegalizer::PromoteIntOp_STORE(StoreSDNode *N, unsigned OpNo){
947   assert(ISD::isUNINDEXEDStore(N) && "Indexed store during type legalization!");
948   SDValue Ch = N->getChain(), Ptr = N->getBasePtr();
949   unsigned Alignment = N->getAlignment();
950   bool isVolatile = N->isVolatile();
951   bool isNonTemporal = N->isNonTemporal();
952   DebugLoc dl = N->getDebugLoc();
953
954   SDValue Val = GetPromotedInteger(N->getValue());  // Get promoted value.
955
956   // Truncate the value and store the result.
957   return DAG.getTruncStore(Ch, dl, Val, Ptr, N->getPointerInfo(),
958                            N->getMemoryVT(),
959                            isVolatile, isNonTemporal, Alignment);
960 }
961
962 SDValue DAGTypeLegalizer::PromoteIntOp_TRUNCATE(SDNode *N) {
963   SDValue Op = GetPromotedInteger(N->getOperand(0));
964   return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), N->getValueType(0), Op);
965 }
966
967 SDValue DAGTypeLegalizer::PromoteIntOp_UINT_TO_FP(SDNode *N) {
968   return SDValue(DAG.UpdateNodeOperands(N,
969                                 ZExtPromotedInteger(N->getOperand(0))), 0);
970 }
971
972 SDValue DAGTypeLegalizer::PromoteIntOp_ZERO_EXTEND(SDNode *N) {
973   DebugLoc dl = N->getDebugLoc();
974   SDValue Op = GetPromotedInteger(N->getOperand(0));
975   Op = DAG.getNode(ISD::ANY_EXTEND, dl, N->getValueType(0), Op);
976   return DAG.getZeroExtendInReg(Op, dl,
977                                 N->getOperand(0).getValueType().getScalarType());
978 }
979
980
981 //===----------------------------------------------------------------------===//
982 //  Integer Result Expansion
983 //===----------------------------------------------------------------------===//
984
985 /// ExpandIntegerResult - This method is called when the specified result of the
986 /// specified node is found to need expansion.  At this point, the node may also
987 /// have invalid operands or may have other results that need promotion, we just
988 /// know that (at least) one result needs expansion.
989 void DAGTypeLegalizer::ExpandIntegerResult(SDNode *N, unsigned ResNo) {
990   DEBUG(dbgs() << "Expand integer result: "; N->dump(&DAG); dbgs() << "\n");
991   SDValue Lo, Hi;
992   Lo = Hi = SDValue();
993
994   // See if the target wants to custom expand this node.
995   if (CustomLowerNode(N, N->getValueType(ResNo), true))
996     return;
997
998   switch (N->getOpcode()) {
999   default:
1000 #ifndef NDEBUG
1001     dbgs() << "ExpandIntegerResult #" << ResNo << ": ";
1002     N->dump(&DAG); dbgs() << "\n";
1003 #endif
1004     llvm_unreachable("Do not know how to expand the result of this operator!");
1005
1006   case ISD::MERGE_VALUES: SplitRes_MERGE_VALUES(N, Lo, Hi); break;
1007   case ISD::SELECT:       SplitRes_SELECT(N, Lo, Hi); break;
1008   case ISD::SELECT_CC:    SplitRes_SELECT_CC(N, Lo, Hi); break;
1009   case ISD::UNDEF:        SplitRes_UNDEF(N, Lo, Hi); break;
1010
1011   case ISD::BITCAST:            ExpandRes_BITCAST(N, Lo, Hi); break;
1012   case ISD::BUILD_PAIR:         ExpandRes_BUILD_PAIR(N, Lo, Hi); break;
1013   case ISD::EXTRACT_ELEMENT:    ExpandRes_EXTRACT_ELEMENT(N, Lo, Hi); break;
1014   case ISD::EXTRACT_VECTOR_ELT: ExpandRes_EXTRACT_VECTOR_ELT(N, Lo, Hi); break;
1015   case ISD::VAARG:              ExpandRes_VAARG(N, Lo, Hi); break;
1016
1017   case ISD::ANY_EXTEND:  ExpandIntRes_ANY_EXTEND(N, Lo, Hi); break;
1018   case ISD::AssertSext:  ExpandIntRes_AssertSext(N, Lo, Hi); break;
1019   case ISD::AssertZext:  ExpandIntRes_AssertZext(N, Lo, Hi); break;
1020   case ISD::BSWAP:       ExpandIntRes_BSWAP(N, Lo, Hi); break;
1021   case ISD::Constant:    ExpandIntRes_Constant(N, Lo, Hi); break;
1022   case ISD::CTLZ:        ExpandIntRes_CTLZ(N, Lo, Hi); break;
1023   case ISD::CTPOP:       ExpandIntRes_CTPOP(N, Lo, Hi); break;
1024   case ISD::CTTZ:        ExpandIntRes_CTTZ(N, Lo, Hi); break;
1025   case ISD::FP_TO_SINT:  ExpandIntRes_FP_TO_SINT(N, Lo, Hi); break;
1026   case ISD::FP_TO_UINT:  ExpandIntRes_FP_TO_UINT(N, Lo, Hi); break;
1027   case ISD::LOAD:        ExpandIntRes_LOAD(cast<LoadSDNode>(N), Lo, Hi); break;
1028   case ISD::MUL:         ExpandIntRes_MUL(N, Lo, Hi); break;
1029   case ISD::SDIV:        ExpandIntRes_SDIV(N, Lo, Hi); break;
1030   case ISD::SIGN_EXTEND: ExpandIntRes_SIGN_EXTEND(N, Lo, Hi); break;
1031   case ISD::SIGN_EXTEND_INREG: ExpandIntRes_SIGN_EXTEND_INREG(N, Lo, Hi); break;
1032   case ISD::SREM:        ExpandIntRes_SREM(N, Lo, Hi); break;
1033   case ISD::TRUNCATE:    ExpandIntRes_TRUNCATE(N, Lo, Hi); break;
1034   case ISD::UDIV:        ExpandIntRes_UDIV(N, Lo, Hi); break;
1035   case ISD::UREM:        ExpandIntRes_UREM(N, Lo, Hi); break;
1036   case ISD::ZERO_EXTEND: ExpandIntRes_ZERO_EXTEND(N, Lo, Hi); break;
1037
1038   case ISD::ATOMIC_LOAD_ADD:
1039   case ISD::ATOMIC_LOAD_SUB:
1040   case ISD::ATOMIC_LOAD_AND:
1041   case ISD::ATOMIC_LOAD_OR:
1042   case ISD::ATOMIC_LOAD_XOR:
1043   case ISD::ATOMIC_LOAD_NAND:
1044   case ISD::ATOMIC_LOAD_MIN:
1045   case ISD::ATOMIC_LOAD_MAX:
1046   case ISD::ATOMIC_LOAD_UMIN:
1047   case ISD::ATOMIC_LOAD_UMAX:
1048   case ISD::ATOMIC_SWAP: {
1049     std::pair<SDValue, SDValue> Tmp = ExpandAtomic(N);
1050     SplitInteger(Tmp.first, Lo, Hi);
1051     ReplaceValueWith(SDValue(N, 1), Tmp.second);
1052     break;
1053   }
1054
1055   case ISD::AND:
1056   case ISD::OR:
1057   case ISD::XOR: ExpandIntRes_Logical(N, Lo, Hi); break;
1058
1059   case ISD::ADD:
1060   case ISD::SUB: ExpandIntRes_ADDSUB(N, Lo, Hi); break;
1061
1062   case ISD::ADDC:
1063   case ISD::SUBC: ExpandIntRes_ADDSUBC(N, Lo, Hi); break;
1064
1065   case ISD::ADDE:
1066   case ISD::SUBE: ExpandIntRes_ADDSUBE(N, Lo, Hi); break;
1067
1068   case ISD::SHL:
1069   case ISD::SRA:
1070   case ISD::SRL: ExpandIntRes_Shift(N, Lo, Hi); break;
1071
1072   case ISD::SADDO:
1073   case ISD::SSUBO: ExpandIntRes_SADDSUBO(N, Lo, Hi); break;
1074   case ISD::UADDO:
1075   case ISD::USUBO: ExpandIntRes_UADDSUBO(N, Lo, Hi); break;
1076   case ISD::UMULO:
1077   case ISD::SMULO: ExpandIntRes_XMULO(N, Lo, Hi); break;
1078   }
1079
1080   // If Lo/Hi is null, the sub-method took care of registering results etc.
1081   if (Lo.getNode())
1082     SetExpandedInteger(SDValue(N, ResNo), Lo, Hi);
1083 }
1084
1085 /// Lower an atomic node to the appropriate builtin call.
1086 std::pair <SDValue, SDValue> DAGTypeLegalizer::ExpandAtomic(SDNode *Node) {
1087   unsigned Opc = Node->getOpcode();
1088   MVT VT = cast<AtomicSDNode>(Node)->getMemoryVT().getSimpleVT();
1089   RTLIB::Libcall LC;
1090
1091   switch (Opc) {
1092   default:
1093     llvm_unreachable("Unhandled atomic intrinsic Expand!");
1094     break;
1095   case ISD::ATOMIC_SWAP:
1096     switch (VT.SimpleTy) {
1097     default: llvm_unreachable("Unexpected value type for atomic!");
1098     case MVT::i8:  LC = RTLIB::SYNC_LOCK_TEST_AND_SET_1; break;
1099     case MVT::i16: LC = RTLIB::SYNC_LOCK_TEST_AND_SET_2; break;
1100     case MVT::i32: LC = RTLIB::SYNC_LOCK_TEST_AND_SET_4; break;
1101     case MVT::i64: LC = RTLIB::SYNC_LOCK_TEST_AND_SET_8; break;
1102     }
1103     break;
1104   case ISD::ATOMIC_CMP_SWAP:
1105     switch (VT.SimpleTy) {
1106     default: llvm_unreachable("Unexpected value type for atomic!");
1107     case MVT::i8:  LC = RTLIB::SYNC_VAL_COMPARE_AND_SWAP_1; break;
1108     case MVT::i16: LC = RTLIB::SYNC_VAL_COMPARE_AND_SWAP_2; break;
1109     case MVT::i32: LC = RTLIB::SYNC_VAL_COMPARE_AND_SWAP_4; break;
1110     case MVT::i64: LC = RTLIB::SYNC_VAL_COMPARE_AND_SWAP_8; break;
1111     }
1112     break;
1113   case ISD::ATOMIC_LOAD_ADD:
1114     switch (VT.SimpleTy) {
1115     default: llvm_unreachable("Unexpected value type for atomic!");
1116     case MVT::i8:  LC = RTLIB::SYNC_FETCH_AND_ADD_1; break;
1117     case MVT::i16: LC = RTLIB::SYNC_FETCH_AND_ADD_2; break;
1118     case MVT::i32: LC = RTLIB::SYNC_FETCH_AND_ADD_4; break;
1119     case MVT::i64: LC = RTLIB::SYNC_FETCH_AND_ADD_8; break;
1120     }
1121     break;
1122   case ISD::ATOMIC_LOAD_SUB:
1123     switch (VT.SimpleTy) {
1124     default: llvm_unreachable("Unexpected value type for atomic!");
1125     case MVT::i8:  LC = RTLIB::SYNC_FETCH_AND_SUB_1; break;
1126     case MVT::i16: LC = RTLIB::SYNC_FETCH_AND_SUB_2; break;
1127     case MVT::i32: LC = RTLIB::SYNC_FETCH_AND_SUB_4; break;
1128     case MVT::i64: LC = RTLIB::SYNC_FETCH_AND_SUB_8; break;
1129     }
1130     break;
1131   case ISD::ATOMIC_LOAD_AND:
1132     switch (VT.SimpleTy) {
1133     default: llvm_unreachable("Unexpected value type for atomic!");
1134     case MVT::i8:  LC = RTLIB::SYNC_FETCH_AND_AND_1; break;
1135     case MVT::i16: LC = RTLIB::SYNC_FETCH_AND_AND_2; break;
1136     case MVT::i32: LC = RTLIB::SYNC_FETCH_AND_AND_4; break;
1137     case MVT::i64: LC = RTLIB::SYNC_FETCH_AND_AND_8; break;
1138     }
1139     break;
1140   case ISD::ATOMIC_LOAD_OR:
1141     switch (VT.SimpleTy) {
1142     default: llvm_unreachable("Unexpected value type for atomic!");
1143     case MVT::i8:  LC = RTLIB::SYNC_FETCH_AND_OR_1; break;
1144     case MVT::i16: LC = RTLIB::SYNC_FETCH_AND_OR_2; break;
1145     case MVT::i32: LC = RTLIB::SYNC_FETCH_AND_OR_4; break;
1146     case MVT::i64: LC = RTLIB::SYNC_FETCH_AND_OR_8; break;
1147     }
1148     break;
1149   case ISD::ATOMIC_LOAD_XOR:
1150     switch (VT.SimpleTy) {
1151     default: llvm_unreachable("Unexpected value type for atomic!");
1152     case MVT::i8:  LC = RTLIB::SYNC_FETCH_AND_XOR_1; break;
1153     case MVT::i16: LC = RTLIB::SYNC_FETCH_AND_XOR_2; break;
1154     case MVT::i32: LC = RTLIB::SYNC_FETCH_AND_XOR_4; break;
1155     case MVT::i64: LC = RTLIB::SYNC_FETCH_AND_XOR_8; break;
1156     }
1157     break;
1158   case ISD::ATOMIC_LOAD_NAND:
1159     switch (VT.SimpleTy) {
1160     default: llvm_unreachable("Unexpected value type for atomic!");
1161     case MVT::i8:  LC = RTLIB::SYNC_FETCH_AND_NAND_1; break;
1162     case MVT::i16: LC = RTLIB::SYNC_FETCH_AND_NAND_2; break;
1163     case MVT::i32: LC = RTLIB::SYNC_FETCH_AND_NAND_4; break;
1164     case MVT::i64: LC = RTLIB::SYNC_FETCH_AND_NAND_8; break;
1165     }
1166     break;
1167   }
1168
1169   return ExpandChainLibCall(LC, Node, false);
1170 }
1171
1172 /// ExpandShiftByConstant - N is a shift by a value that needs to be expanded,
1173 /// and the shift amount is a constant 'Amt'.  Expand the operation.
1174 void DAGTypeLegalizer::ExpandShiftByConstant(SDNode *N, unsigned Amt,
1175                                              SDValue &Lo, SDValue &Hi) {
1176   DebugLoc DL = N->getDebugLoc();
1177   // Expand the incoming operand to be shifted, so that we have its parts
1178   SDValue InL, InH;
1179   GetExpandedInteger(N->getOperand(0), InL, InH);
1180
1181   EVT NVT = InL.getValueType();
1182   unsigned VTBits = N->getValueType(0).getSizeInBits();
1183   unsigned NVTBits = NVT.getSizeInBits();
1184   EVT ShTy = N->getOperand(1).getValueType();
1185
1186   if (N->getOpcode() == ISD::SHL) {
1187     if (Amt > VTBits) {
1188       Lo = Hi = DAG.getConstant(0, NVT);
1189     } else if (Amt > NVTBits) {
1190       Lo = DAG.getConstant(0, NVT);
1191       Hi = DAG.getNode(ISD::SHL, DL,
1192                        NVT, InL, DAG.getConstant(Amt-NVTBits, ShTy));
1193     } else if (Amt == NVTBits) {
1194       Lo = DAG.getConstant(0, NVT);
1195       Hi = InL;
1196     } else if (Amt == 1 &&
1197                TLI.isOperationLegalOrCustom(ISD::ADDC,
1198                               TLI.getTypeToExpandTo(*DAG.getContext(), NVT))) {
1199       // Emit this X << 1 as X+X.
1200       SDVTList VTList = DAG.getVTList(NVT, MVT::Glue);
1201       SDValue LoOps[2] = { InL, InL };
1202       Lo = DAG.getNode(ISD::ADDC, DL, VTList, LoOps, 2);
1203       SDValue HiOps[3] = { InH, InH, Lo.getValue(1) };
1204       Hi = DAG.getNode(ISD::ADDE, DL, VTList, HiOps, 3);
1205     } else {
1206       Lo = DAG.getNode(ISD::SHL, DL, NVT, InL, DAG.getConstant(Amt, ShTy));
1207       Hi = DAG.getNode(ISD::OR, DL, NVT,
1208                        DAG.getNode(ISD::SHL, DL, NVT, InH,
1209                                    DAG.getConstant(Amt, ShTy)),
1210                        DAG.getNode(ISD::SRL, DL, NVT, InL,
1211                                    DAG.getConstant(NVTBits-Amt, ShTy)));
1212     }
1213     return;
1214   }
1215
1216   if (N->getOpcode() == ISD::SRL) {
1217     if (Amt > VTBits) {
1218       Lo = DAG.getConstant(0, NVT);
1219       Hi = DAG.getConstant(0, NVT);
1220     } else if (Amt > NVTBits) {
1221       Lo = DAG.getNode(ISD::SRL, DL,
1222                        NVT, InH, DAG.getConstant(Amt-NVTBits,ShTy));
1223       Hi = DAG.getConstant(0, NVT);
1224     } else if (Amt == NVTBits) {
1225       Lo = InH;
1226       Hi = DAG.getConstant(0, NVT);
1227     } else {
1228       Lo = DAG.getNode(ISD::OR, DL, NVT,
1229                        DAG.getNode(ISD::SRL, DL, NVT, InL,
1230                                    DAG.getConstant(Amt, ShTy)),
1231                        DAG.getNode(ISD::SHL, DL, NVT, InH,
1232                                    DAG.getConstant(NVTBits-Amt, ShTy)));
1233       Hi = DAG.getNode(ISD::SRL, DL, NVT, InH, DAG.getConstant(Amt, ShTy));
1234     }
1235     return;
1236   }
1237
1238   assert(N->getOpcode() == ISD::SRA && "Unknown shift!");
1239   if (Amt > VTBits) {
1240     Hi = Lo = DAG.getNode(ISD::SRA, DL, NVT, InH,
1241                           DAG.getConstant(NVTBits-1, ShTy));
1242   } else if (Amt > NVTBits) {
1243     Lo = DAG.getNode(ISD::SRA, DL, NVT, InH,
1244                      DAG.getConstant(Amt-NVTBits, ShTy));
1245     Hi = DAG.getNode(ISD::SRA, DL, NVT, InH,
1246                      DAG.getConstant(NVTBits-1, ShTy));
1247   } else if (Amt == NVTBits) {
1248     Lo = InH;
1249     Hi = DAG.getNode(ISD::SRA, DL, NVT, InH,
1250                      DAG.getConstant(NVTBits-1, ShTy));
1251   } else {
1252     Lo = DAG.getNode(ISD::OR, DL, NVT,
1253                      DAG.getNode(ISD::SRL, DL, NVT, InL,
1254                                  DAG.getConstant(Amt, ShTy)),
1255                      DAG.getNode(ISD::SHL, DL, NVT, InH,
1256                                  DAG.getConstant(NVTBits-Amt, ShTy)));
1257     Hi = DAG.getNode(ISD::SRA, DL, NVT, InH, DAG.getConstant(Amt, ShTy));
1258   }
1259 }
1260
1261 /// ExpandShiftWithKnownAmountBit - Try to determine whether we can simplify
1262 /// this shift based on knowledge of the high bit of the shift amount.  If we
1263 /// can tell this, we know that it is >= 32 or < 32, without knowing the actual
1264 /// shift amount.
1265 bool DAGTypeLegalizer::
1266 ExpandShiftWithKnownAmountBit(SDNode *N, SDValue &Lo, SDValue &Hi) {
1267   SDValue Amt = N->getOperand(1);
1268   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
1269   EVT ShTy = Amt.getValueType();
1270   unsigned ShBits = ShTy.getScalarType().getSizeInBits();
1271   unsigned NVTBits = NVT.getScalarType().getSizeInBits();
1272   assert(isPowerOf2_32(NVTBits) &&
1273          "Expanded integer type size not a power of two!");
1274   DebugLoc dl = N->getDebugLoc();
1275
1276   APInt HighBitMask = APInt::getHighBitsSet(ShBits, ShBits - Log2_32(NVTBits));
1277   APInt KnownZero, KnownOne;
1278   DAG.ComputeMaskedBits(N->getOperand(1), HighBitMask, KnownZero, KnownOne);
1279
1280   // If we don't know anything about the high bits, exit.
1281   if (((KnownZero|KnownOne) & HighBitMask) == 0)
1282     return false;
1283
1284   // Get the incoming operand to be shifted.
1285   SDValue InL, InH;
1286   GetExpandedInteger(N->getOperand(0), InL, InH);
1287
1288   // If we know that any of the high bits of the shift amount are one, then we
1289   // can do this as a couple of simple shifts.
1290   if (KnownOne.intersects(HighBitMask)) {
1291     // Mask out the high bit, which we know is set.
1292     Amt = DAG.getNode(ISD::AND, dl, ShTy, Amt,
1293                       DAG.getConstant(~HighBitMask, ShTy));
1294
1295     switch (N->getOpcode()) {
1296     default: llvm_unreachable("Unknown shift");
1297     case ISD::SHL:
1298       Lo = DAG.getConstant(0, NVT);              // Low part is zero.
1299       Hi = DAG.getNode(ISD::SHL, dl, NVT, InL, Amt); // High part from Lo part.
1300       return true;
1301     case ISD::SRL:
1302       Hi = DAG.getConstant(0, NVT);              // Hi part is zero.
1303       Lo = DAG.getNode(ISD::SRL, dl, NVT, InH, Amt); // Lo part from Hi part.
1304       return true;
1305     case ISD::SRA:
1306       Hi = DAG.getNode(ISD::SRA, dl, NVT, InH,       // Sign extend high part.
1307                        DAG.getConstant(NVTBits-1, ShTy));
1308       Lo = DAG.getNode(ISD::SRA, dl, NVT, InH, Amt); // Lo part from Hi part.
1309       return true;
1310     }
1311   }
1312
1313 #if 0
1314   // FIXME: This code is broken for shifts with a zero amount!
1315   // If we know that all of the high bits of the shift amount are zero, then we
1316   // can do this as a couple of simple shifts.
1317   if ((KnownZero & HighBitMask) == HighBitMask) {
1318     // Compute 32-amt.
1319     SDValue Amt2 = DAG.getNode(ISD::SUB, ShTy,
1320                                  DAG.getConstant(NVTBits, ShTy),
1321                                  Amt);
1322     unsigned Op1, Op2;
1323     switch (N->getOpcode()) {
1324     default: llvm_unreachable("Unknown shift");
1325     case ISD::SHL:  Op1 = ISD::SHL; Op2 = ISD::SRL; break;
1326     case ISD::SRL:
1327     case ISD::SRA:  Op1 = ISD::SRL; Op2 = ISD::SHL; break;
1328     }
1329
1330     Lo = DAG.getNode(N->getOpcode(), NVT, InL, Amt);
1331     Hi = DAG.getNode(ISD::OR, NVT,
1332                      DAG.getNode(Op1, NVT, InH, Amt),
1333                      DAG.getNode(Op2, NVT, InL, Amt2));
1334     return true;
1335   }
1336 #endif
1337
1338   return false;
1339 }
1340
1341 /// ExpandShiftWithUnknownAmountBit - Fully general expansion of integer shift
1342 /// of any size.
1343 bool DAGTypeLegalizer::
1344 ExpandShiftWithUnknownAmountBit(SDNode *N, SDValue &Lo, SDValue &Hi) {
1345   SDValue Amt = N->getOperand(1);
1346   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
1347   EVT ShTy = Amt.getValueType();
1348   unsigned NVTBits = NVT.getSizeInBits();
1349   assert(isPowerOf2_32(NVTBits) &&
1350          "Expanded integer type size not a power of two!");
1351   DebugLoc dl = N->getDebugLoc();
1352
1353   // Get the incoming operand to be shifted.
1354   SDValue InL, InH;
1355   GetExpandedInteger(N->getOperand(0), InL, InH);
1356
1357   SDValue NVBitsNode = DAG.getConstant(NVTBits, ShTy);
1358   SDValue AmtExcess = DAG.getNode(ISD::SUB, dl, ShTy, Amt, NVBitsNode);
1359   SDValue AmtLack = DAG.getNode(ISD::SUB, dl, ShTy, NVBitsNode, Amt);
1360   SDValue isShort = DAG.getSetCC(dl, TLI.getSetCCResultType(ShTy),
1361                                  Amt, NVBitsNode, ISD::SETULT);
1362
1363   SDValue LoS, HiS, LoL, HiL;
1364   switch (N->getOpcode()) {
1365   default: llvm_unreachable("Unknown shift");
1366   case ISD::SHL:
1367     // Short: ShAmt < NVTBits
1368     LoS = DAG.getNode(ISD::SHL, dl, NVT, InL, Amt);
1369     HiS = DAG.getNode(ISD::OR, dl, NVT,
1370                       DAG.getNode(ISD::SHL, dl, NVT, InH, Amt),
1371     // FIXME: If Amt is zero, the following shift generates an undefined result
1372     // on some architectures.
1373                       DAG.getNode(ISD::SRL, dl, NVT, InL, AmtLack));
1374
1375     // Long: ShAmt >= NVTBits
1376     LoL = DAG.getConstant(0, NVT);                        // Lo part is zero.
1377     HiL = DAG.getNode(ISD::SHL, dl, NVT, InL, AmtExcess); // Hi from Lo part.
1378
1379     Lo = DAG.getNode(ISD::SELECT, dl, NVT, isShort, LoS, LoL);
1380     Hi = DAG.getNode(ISD::SELECT, dl, NVT, isShort, HiS, HiL);
1381     return true;
1382   case ISD::SRL:
1383     // Short: ShAmt < NVTBits
1384     HiS = DAG.getNode(ISD::SRL, dl, NVT, InH, Amt);
1385     LoS = DAG.getNode(ISD::OR, dl, NVT,
1386                       DAG.getNode(ISD::SRL, dl, NVT, InL, Amt),
1387     // FIXME: If Amt is zero, the following shift generates an undefined result
1388     // on some architectures.
1389                       DAG.getNode(ISD::SHL, dl, NVT, InH, AmtLack));
1390
1391     // Long: ShAmt >= NVTBits
1392     HiL = DAG.getConstant(0, NVT);                        // Hi part is zero.
1393     LoL = DAG.getNode(ISD::SRL, dl, NVT, InH, AmtExcess); // Lo from Hi part.
1394
1395     Lo = DAG.getNode(ISD::SELECT, dl, NVT, isShort, LoS, LoL);
1396     Hi = DAG.getNode(ISD::SELECT, dl, NVT, isShort, HiS, HiL);
1397     return true;
1398   case ISD::SRA:
1399     // Short: ShAmt < NVTBits
1400     HiS = DAG.getNode(ISD::SRA, dl, NVT, InH, Amt);
1401     LoS = DAG.getNode(ISD::OR, dl, NVT,
1402                       DAG.getNode(ISD::SRL, dl, NVT, InL, Amt),
1403     // FIXME: If Amt is zero, the following shift generates an undefined result
1404     // on some architectures.
1405                       DAG.getNode(ISD::SHL, dl, NVT, InH, AmtLack));
1406
1407     // Long: ShAmt >= NVTBits
1408     HiL = DAG.getNode(ISD::SRA, dl, NVT, InH,             // Sign of Hi part.
1409                       DAG.getConstant(NVTBits-1, ShTy));
1410     LoL = DAG.getNode(ISD::SRA, dl, NVT, InH, AmtExcess); // Lo from Hi part.
1411
1412     Lo = DAG.getNode(ISD::SELECT, dl, NVT, isShort, LoS, LoL);
1413     Hi = DAG.getNode(ISD::SELECT, dl, NVT, isShort, HiS, HiL);
1414     return true;
1415   }
1416
1417   return false;
1418 }
1419
1420 void DAGTypeLegalizer::ExpandIntRes_ADDSUB(SDNode *N,
1421                                            SDValue &Lo, SDValue &Hi) {
1422   DebugLoc dl = N->getDebugLoc();
1423   // Expand the subcomponents.
1424   SDValue LHSL, LHSH, RHSL, RHSH;
1425   GetExpandedInteger(N->getOperand(0), LHSL, LHSH);
1426   GetExpandedInteger(N->getOperand(1), RHSL, RHSH);
1427
1428   EVT NVT = LHSL.getValueType();
1429   SDValue LoOps[2] = { LHSL, RHSL };
1430   SDValue HiOps[3] = { LHSH, RHSH };
1431
1432   // Do not generate ADDC/ADDE or SUBC/SUBE if the target does not support
1433   // them.  TODO: Teach operation legalization how to expand unsupported
1434   // ADDC/ADDE/SUBC/SUBE.  The problem is that these operations generate
1435   // a carry of type MVT::Glue, but there doesn't seem to be any way to
1436   // generate a value of this type in the expanded code sequence.
1437   bool hasCarry =
1438     TLI.isOperationLegalOrCustom(N->getOpcode() == ISD::ADD ?
1439                                    ISD::ADDC : ISD::SUBC,
1440                                  TLI.getTypeToExpandTo(*DAG.getContext(), NVT));
1441
1442   if (hasCarry) {
1443     SDVTList VTList = DAG.getVTList(NVT, MVT::Glue);
1444     if (N->getOpcode() == ISD::ADD) {
1445       Lo = DAG.getNode(ISD::ADDC, dl, VTList, LoOps, 2);
1446       HiOps[2] = Lo.getValue(1);
1447       Hi = DAG.getNode(ISD::ADDE, dl, VTList, HiOps, 3);
1448     } else {
1449       Lo = DAG.getNode(ISD::SUBC, dl, VTList, LoOps, 2);
1450       HiOps[2] = Lo.getValue(1);
1451       Hi = DAG.getNode(ISD::SUBE, dl, VTList, HiOps, 3);
1452     }
1453     return;
1454   }
1455
1456   if (N->getOpcode() == ISD::ADD) {
1457     Lo = DAG.getNode(ISD::ADD, dl, NVT, LoOps, 2);
1458     Hi = DAG.getNode(ISD::ADD, dl, NVT, HiOps, 2);
1459     SDValue Cmp1 = DAG.getSetCC(dl, TLI.getSetCCResultType(NVT), Lo, LoOps[0],
1460                                 ISD::SETULT);
1461     SDValue Carry1 = DAG.getNode(ISD::SELECT, dl, NVT, Cmp1,
1462                                  DAG.getConstant(1, NVT),
1463                                  DAG.getConstant(0, NVT));
1464     SDValue Cmp2 = DAG.getSetCC(dl, TLI.getSetCCResultType(NVT), Lo, LoOps[1],
1465                                 ISD::SETULT);
1466     SDValue Carry2 = DAG.getNode(ISD::SELECT, dl, NVT, Cmp2,
1467                                  DAG.getConstant(1, NVT), Carry1);
1468     Hi = DAG.getNode(ISD::ADD, dl, NVT, Hi, Carry2);
1469   } else {
1470     Lo = DAG.getNode(ISD::SUB, dl, NVT, LoOps, 2);
1471     Hi = DAG.getNode(ISD::SUB, dl, NVT, HiOps, 2);
1472     SDValue Cmp =
1473       DAG.getSetCC(dl, TLI.getSetCCResultType(LoOps[0].getValueType()),
1474                    LoOps[0], LoOps[1], ISD::SETULT);
1475     SDValue Borrow = DAG.getNode(ISD::SELECT, dl, NVT, Cmp,
1476                                  DAG.getConstant(1, NVT),
1477                                  DAG.getConstant(0, NVT));
1478     Hi = DAG.getNode(ISD::SUB, dl, NVT, Hi, Borrow);
1479   }
1480 }
1481
1482 void DAGTypeLegalizer::ExpandIntRes_ADDSUBC(SDNode *N,
1483                                             SDValue &Lo, SDValue &Hi) {
1484   // Expand the subcomponents.
1485   SDValue LHSL, LHSH, RHSL, RHSH;
1486   DebugLoc dl = N->getDebugLoc();
1487   GetExpandedInteger(N->getOperand(0), LHSL, LHSH);
1488   GetExpandedInteger(N->getOperand(1), RHSL, RHSH);
1489   SDVTList VTList = DAG.getVTList(LHSL.getValueType(), MVT::Glue);
1490   SDValue LoOps[2] = { LHSL, RHSL };
1491   SDValue HiOps[3] = { LHSH, RHSH };
1492
1493   if (N->getOpcode() == ISD::ADDC) {
1494     Lo = DAG.getNode(ISD::ADDC, dl, VTList, LoOps, 2);
1495     HiOps[2] = Lo.getValue(1);
1496     Hi = DAG.getNode(ISD::ADDE, dl, VTList, HiOps, 3);
1497   } else {
1498     Lo = DAG.getNode(ISD::SUBC, dl, VTList, LoOps, 2);
1499     HiOps[2] = Lo.getValue(1);
1500     Hi = DAG.getNode(ISD::SUBE, dl, VTList, HiOps, 3);
1501   }
1502
1503   // Legalized the flag result - switch anything that used the old flag to
1504   // use the new one.
1505   ReplaceValueWith(SDValue(N, 1), Hi.getValue(1));
1506 }
1507
1508 void DAGTypeLegalizer::ExpandIntRes_ADDSUBE(SDNode *N,
1509                                             SDValue &Lo, SDValue &Hi) {
1510   // Expand the subcomponents.
1511   SDValue LHSL, LHSH, RHSL, RHSH;
1512   DebugLoc dl = N->getDebugLoc();
1513   GetExpandedInteger(N->getOperand(0), LHSL, LHSH);
1514   GetExpandedInteger(N->getOperand(1), RHSL, RHSH);
1515   SDVTList VTList = DAG.getVTList(LHSL.getValueType(), MVT::Glue);
1516   SDValue LoOps[3] = { LHSL, RHSL, N->getOperand(2) };
1517   SDValue HiOps[3] = { LHSH, RHSH };
1518
1519   Lo = DAG.getNode(N->getOpcode(), dl, VTList, LoOps, 3);
1520   HiOps[2] = Lo.getValue(1);
1521   Hi = DAG.getNode(N->getOpcode(), dl, VTList, HiOps, 3);
1522
1523   // Legalized the flag result - switch anything that used the old flag to
1524   // use the new one.
1525   ReplaceValueWith(SDValue(N, 1), Hi.getValue(1));
1526 }
1527
1528 void DAGTypeLegalizer::ExpandIntRes_ANY_EXTEND(SDNode *N,
1529                                                SDValue &Lo, SDValue &Hi) {
1530   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
1531   DebugLoc dl = N->getDebugLoc();
1532   SDValue Op = N->getOperand(0);
1533   if (Op.getValueType().bitsLE(NVT)) {
1534     // The low part is any extension of the input (which degenerates to a copy).
1535     Lo = DAG.getNode(ISD::ANY_EXTEND, dl, NVT, Op);
1536     Hi = DAG.getUNDEF(NVT);   // The high part is undefined.
1537   } else {
1538     // For example, extension of an i48 to an i64.  The operand type necessarily
1539     // promotes to the result type, so will end up being expanded too.
1540     assert(getTypeAction(Op.getValueType()) ==
1541            TargetLowering::TypePromoteInteger &&
1542            "Only know how to promote this result!");
1543     SDValue Res = GetPromotedInteger(Op);
1544     assert(Res.getValueType() == N->getValueType(0) &&
1545            "Operand over promoted?");
1546     // Split the promoted operand.  This will simplify when it is expanded.
1547     SplitInteger(Res, Lo, Hi);
1548   }
1549 }
1550
1551 void DAGTypeLegalizer::ExpandIntRes_AssertSext(SDNode *N,
1552                                                SDValue &Lo, SDValue &Hi) {
1553   DebugLoc dl = N->getDebugLoc();
1554   GetExpandedInteger(N->getOperand(0), Lo, Hi);
1555   EVT NVT = Lo.getValueType();
1556   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
1557   unsigned NVTBits = NVT.getSizeInBits();
1558   unsigned EVTBits = EVT.getSizeInBits();
1559
1560   if (NVTBits < EVTBits) {
1561     Hi = DAG.getNode(ISD::AssertSext, dl, NVT, Hi,
1562                      DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(),
1563                                                         EVTBits - NVTBits)));
1564   } else {
1565     Lo = DAG.getNode(ISD::AssertSext, dl, NVT, Lo, DAG.getValueType(EVT));
1566     // The high part replicates the sign bit of Lo, make it explicit.
1567     Hi = DAG.getNode(ISD::SRA, dl, NVT, Lo,
1568                      DAG.getConstant(NVTBits-1, TLI.getPointerTy()));
1569   }
1570 }
1571
1572 void DAGTypeLegalizer::ExpandIntRes_AssertZext(SDNode *N,
1573                                                SDValue &Lo, SDValue &Hi) {
1574   DebugLoc dl = N->getDebugLoc();
1575   GetExpandedInteger(N->getOperand(0), Lo, Hi);
1576   EVT NVT = Lo.getValueType();
1577   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
1578   unsigned NVTBits = NVT.getSizeInBits();
1579   unsigned EVTBits = EVT.getSizeInBits();
1580
1581   if (NVTBits < EVTBits) {
1582     Hi = DAG.getNode(ISD::AssertZext, dl, NVT, Hi,
1583                      DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(),
1584                                                         EVTBits - NVTBits)));
1585   } else {
1586     Lo = DAG.getNode(ISD::AssertZext, dl, NVT, Lo, DAG.getValueType(EVT));
1587     // The high part must be zero, make it explicit.
1588     Hi = DAG.getConstant(0, NVT);
1589   }
1590 }
1591
1592 void DAGTypeLegalizer::ExpandIntRes_BSWAP(SDNode *N,
1593                                           SDValue &Lo, SDValue &Hi) {
1594   DebugLoc dl = N->getDebugLoc();
1595   GetExpandedInteger(N->getOperand(0), Hi, Lo);  // Note swapped operands.
1596   Lo = DAG.getNode(ISD::BSWAP, dl, Lo.getValueType(), Lo);
1597   Hi = DAG.getNode(ISD::BSWAP, dl, Hi.getValueType(), Hi);
1598 }
1599
1600 void DAGTypeLegalizer::ExpandIntRes_Constant(SDNode *N,
1601                                              SDValue &Lo, SDValue &Hi) {
1602   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
1603   unsigned NBitWidth = NVT.getSizeInBits();
1604   const APInt &Cst = cast<ConstantSDNode>(N)->getAPIntValue();
1605   Lo = DAG.getConstant(Cst.trunc(NBitWidth), NVT);
1606   Hi = DAG.getConstant(Cst.lshr(NBitWidth).trunc(NBitWidth), NVT);
1607 }
1608
1609 void DAGTypeLegalizer::ExpandIntRes_CTLZ(SDNode *N,
1610                                          SDValue &Lo, SDValue &Hi) {
1611   DebugLoc dl = N->getDebugLoc();
1612   // ctlz (HiLo) -> Hi != 0 ? ctlz(Hi) : (ctlz(Lo)+32)
1613   GetExpandedInteger(N->getOperand(0), Lo, Hi);
1614   EVT NVT = Lo.getValueType();
1615
1616   SDValue HiNotZero = DAG.getSetCC(dl, TLI.getSetCCResultType(NVT), Hi,
1617                                    DAG.getConstant(0, NVT), ISD::SETNE);
1618
1619   SDValue LoLZ = DAG.getNode(ISD::CTLZ, dl, NVT, Lo);
1620   SDValue HiLZ = DAG.getNode(ISD::CTLZ, dl, NVT, Hi);
1621
1622   Lo = DAG.getNode(ISD::SELECT, dl, NVT, HiNotZero, HiLZ,
1623                    DAG.getNode(ISD::ADD, dl, NVT, LoLZ,
1624                                DAG.getConstant(NVT.getSizeInBits(), NVT)));
1625   Hi = DAG.getConstant(0, NVT);
1626 }
1627
1628 void DAGTypeLegalizer::ExpandIntRes_CTPOP(SDNode *N,
1629                                           SDValue &Lo, SDValue &Hi) {
1630   DebugLoc dl = N->getDebugLoc();
1631   // ctpop(HiLo) -> ctpop(Hi)+ctpop(Lo)
1632   GetExpandedInteger(N->getOperand(0), Lo, Hi);
1633   EVT NVT = Lo.getValueType();
1634   Lo = DAG.getNode(ISD::ADD, dl, NVT, DAG.getNode(ISD::CTPOP, dl, NVT, Lo),
1635                    DAG.getNode(ISD::CTPOP, dl, NVT, Hi));
1636   Hi = DAG.getConstant(0, NVT);
1637 }
1638
1639 void DAGTypeLegalizer::ExpandIntRes_CTTZ(SDNode *N,
1640                                          SDValue &Lo, SDValue &Hi) {
1641   DebugLoc dl = N->getDebugLoc();
1642   // cttz (HiLo) -> Lo != 0 ? cttz(Lo) : (cttz(Hi)+32)
1643   GetExpandedInteger(N->getOperand(0), Lo, Hi);
1644   EVT NVT = Lo.getValueType();
1645
1646   SDValue LoNotZero = DAG.getSetCC(dl, TLI.getSetCCResultType(NVT), Lo,
1647                                    DAG.getConstant(0, NVT), ISD::SETNE);
1648
1649   SDValue LoLZ = DAG.getNode(ISD::CTTZ, dl, NVT, Lo);
1650   SDValue HiLZ = DAG.getNode(ISD::CTTZ, dl, NVT, Hi);
1651
1652   Lo = DAG.getNode(ISD::SELECT, dl, NVT, LoNotZero, LoLZ,
1653                    DAG.getNode(ISD::ADD, dl, NVT, HiLZ,
1654                                DAG.getConstant(NVT.getSizeInBits(), NVT)));
1655   Hi = DAG.getConstant(0, NVT);
1656 }
1657
1658 void DAGTypeLegalizer::ExpandIntRes_FP_TO_SINT(SDNode *N, SDValue &Lo,
1659                                                SDValue &Hi) {
1660   DebugLoc dl = N->getDebugLoc();
1661   EVT VT = N->getValueType(0);
1662   SDValue Op = N->getOperand(0);
1663   RTLIB::Libcall LC = RTLIB::getFPTOSINT(Op.getValueType(), VT);
1664   assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unexpected fp-to-sint conversion!");
1665   SplitInteger(MakeLibCall(LC, VT, &Op, 1, true/*irrelevant*/, dl), Lo, Hi);
1666 }
1667
1668 void DAGTypeLegalizer::ExpandIntRes_FP_TO_UINT(SDNode *N, SDValue &Lo,
1669                                                SDValue &Hi) {
1670   DebugLoc dl = N->getDebugLoc();
1671   EVT VT = N->getValueType(0);
1672   SDValue Op = N->getOperand(0);
1673   RTLIB::Libcall LC = RTLIB::getFPTOUINT(Op.getValueType(), VT);
1674   assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unexpected fp-to-uint conversion!");
1675   SplitInteger(MakeLibCall(LC, VT, &Op, 1, false/*irrelevant*/, dl), Lo, Hi);
1676 }
1677
1678 void DAGTypeLegalizer::ExpandIntRes_LOAD(LoadSDNode *N,
1679                                          SDValue &Lo, SDValue &Hi) {
1680   if (ISD::isNormalLoad(N)) {
1681     ExpandRes_NormalLoad(N, Lo, Hi);
1682     return;
1683   }
1684
1685   assert(ISD::isUNINDEXEDLoad(N) && "Indexed load during type legalization!");
1686
1687   EVT VT = N->getValueType(0);
1688   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), VT);
1689   SDValue Ch  = N->getChain();
1690   SDValue Ptr = N->getBasePtr();
1691   ISD::LoadExtType ExtType = N->getExtensionType();
1692   unsigned Alignment = N->getAlignment();
1693   bool isVolatile = N->isVolatile();
1694   bool isNonTemporal = N->isNonTemporal();
1695   DebugLoc dl = N->getDebugLoc();
1696
1697   assert(NVT.isByteSized() && "Expanded type not byte sized!");
1698
1699   if (N->getMemoryVT().bitsLE(NVT)) {
1700     EVT MemVT = N->getMemoryVT();
1701
1702     Lo = DAG.getExtLoad(ExtType, dl, NVT, Ch, Ptr, N->getPointerInfo(),
1703                         MemVT, isVolatile, isNonTemporal, Alignment);
1704
1705     // Remember the chain.
1706     Ch = Lo.getValue(1);
1707
1708     if (ExtType == ISD::SEXTLOAD) {
1709       // The high part is obtained by SRA'ing all but one of the bits of the
1710       // lo part.
1711       unsigned LoSize = Lo.getValueType().getSizeInBits();
1712       Hi = DAG.getNode(ISD::SRA, dl, NVT, Lo,
1713                        DAG.getConstant(LoSize-1, TLI.getPointerTy()));
1714     } else if (ExtType == ISD::ZEXTLOAD) {
1715       // The high part is just a zero.
1716       Hi = DAG.getConstant(0, NVT);
1717     } else {
1718       assert(ExtType == ISD::EXTLOAD && "Unknown extload!");
1719       // The high part is undefined.
1720       Hi = DAG.getUNDEF(NVT);
1721     }
1722   } else if (TLI.isLittleEndian()) {
1723     // Little-endian - low bits are at low addresses.
1724     Lo = DAG.getLoad(NVT, dl, Ch, Ptr, N->getPointerInfo(),
1725                      isVolatile, isNonTemporal, Alignment);
1726
1727     unsigned ExcessBits =
1728       N->getMemoryVT().getSizeInBits() - NVT.getSizeInBits();
1729     EVT NEVT = EVT::getIntegerVT(*DAG.getContext(), ExcessBits);
1730
1731     // Increment the pointer to the other half.
1732     unsigned IncrementSize = NVT.getSizeInBits()/8;
1733     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
1734                       DAG.getIntPtrConstant(IncrementSize));
1735     Hi = DAG.getExtLoad(ExtType, dl, NVT, Ch, Ptr,
1736                         N->getPointerInfo().getWithOffset(IncrementSize), NEVT,
1737                         isVolatile, isNonTemporal,
1738                         MinAlign(Alignment, IncrementSize));
1739
1740     // Build a factor node to remember that this load is independent of the
1741     // other one.
1742     Ch = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1),
1743                      Hi.getValue(1));
1744   } else {
1745     // Big-endian - high bits are at low addresses.  Favor aligned loads at
1746     // the cost of some bit-fiddling.
1747     EVT MemVT = N->getMemoryVT();
1748     unsigned EBytes = MemVT.getStoreSize();
1749     unsigned IncrementSize = NVT.getSizeInBits()/8;
1750     unsigned ExcessBits = (EBytes - IncrementSize)*8;
1751
1752     // Load both the high bits and maybe some of the low bits.
1753     Hi = DAG.getExtLoad(ExtType, dl, NVT, Ch, Ptr, N->getPointerInfo(),
1754                         EVT::getIntegerVT(*DAG.getContext(),
1755                                           MemVT.getSizeInBits() - ExcessBits),
1756                         isVolatile, isNonTemporal, Alignment);
1757
1758     // Increment the pointer to the other half.
1759     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
1760                       DAG.getIntPtrConstant(IncrementSize));
1761     // Load the rest of the low bits.
1762     Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, NVT, Ch, Ptr,
1763                         N->getPointerInfo().getWithOffset(IncrementSize),
1764                         EVT::getIntegerVT(*DAG.getContext(), ExcessBits),
1765                         isVolatile, isNonTemporal,
1766                         MinAlign(Alignment, IncrementSize));
1767
1768     // Build a factor node to remember that this load is independent of the
1769     // other one.
1770     Ch = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1),
1771                      Hi.getValue(1));
1772
1773     if (ExcessBits < NVT.getSizeInBits()) {
1774       // Transfer low bits from the bottom of Hi to the top of Lo.
1775       Lo = DAG.getNode(ISD::OR, dl, NVT, Lo,
1776                        DAG.getNode(ISD::SHL, dl, NVT, Hi,
1777                                    DAG.getConstant(ExcessBits,
1778                                                    TLI.getPointerTy())));
1779       // Move high bits to the right position in Hi.
1780       Hi = DAG.getNode(ExtType == ISD::SEXTLOAD ? ISD::SRA : ISD::SRL, dl,
1781                        NVT, Hi,
1782                        DAG.getConstant(NVT.getSizeInBits() - ExcessBits,
1783                                        TLI.getPointerTy()));
1784     }
1785   }
1786
1787   // Legalized the chain result - switch anything that used the old chain to
1788   // use the new one.
1789   ReplaceValueWith(SDValue(N, 1), Ch);
1790 }
1791
1792 void DAGTypeLegalizer::ExpandIntRes_Logical(SDNode *N,
1793                                             SDValue &Lo, SDValue &Hi) {
1794   DebugLoc dl = N->getDebugLoc();
1795   SDValue LL, LH, RL, RH;
1796   GetExpandedInteger(N->getOperand(0), LL, LH);
1797   GetExpandedInteger(N->getOperand(1), RL, RH);
1798   Lo = DAG.getNode(N->getOpcode(), dl, LL.getValueType(), LL, RL);
1799   Hi = DAG.getNode(N->getOpcode(), dl, LL.getValueType(), LH, RH);
1800 }
1801
1802 void DAGTypeLegalizer::ExpandIntRes_MUL(SDNode *N,
1803                                         SDValue &Lo, SDValue &Hi) {
1804   EVT VT = N->getValueType(0);
1805   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), VT);
1806   DebugLoc dl = N->getDebugLoc();
1807
1808   bool HasMULHS = TLI.isOperationLegalOrCustom(ISD::MULHS, NVT);
1809   bool HasMULHU = TLI.isOperationLegalOrCustom(ISD::MULHU, NVT);
1810   bool HasSMUL_LOHI = TLI.isOperationLegalOrCustom(ISD::SMUL_LOHI, NVT);
1811   bool HasUMUL_LOHI = TLI.isOperationLegalOrCustom(ISD::UMUL_LOHI, NVT);
1812   if (HasMULHU || HasMULHS || HasUMUL_LOHI || HasSMUL_LOHI) {
1813     SDValue LL, LH, RL, RH;
1814     GetExpandedInteger(N->getOperand(0), LL, LH);
1815     GetExpandedInteger(N->getOperand(1), RL, RH);
1816     unsigned OuterBitSize = VT.getSizeInBits();
1817     unsigned InnerBitSize = NVT.getSizeInBits();
1818     unsigned LHSSB = DAG.ComputeNumSignBits(N->getOperand(0));
1819     unsigned RHSSB = DAG.ComputeNumSignBits(N->getOperand(1));
1820
1821     APInt HighMask = APInt::getHighBitsSet(OuterBitSize, InnerBitSize);
1822     if (DAG.MaskedValueIsZero(N->getOperand(0), HighMask) &&
1823         DAG.MaskedValueIsZero(N->getOperand(1), HighMask)) {
1824       // The inputs are both zero-extended.
1825       if (HasUMUL_LOHI) {
1826         // We can emit a umul_lohi.
1827         Lo = DAG.getNode(ISD::UMUL_LOHI, dl, DAG.getVTList(NVT, NVT), LL, RL);
1828         Hi = SDValue(Lo.getNode(), 1);
1829         return;
1830       }
1831       if (HasMULHU) {
1832         // We can emit a mulhu+mul.
1833         Lo = DAG.getNode(ISD::MUL, dl, NVT, LL, RL);
1834         Hi = DAG.getNode(ISD::MULHU, dl, NVT, LL, RL);
1835         return;
1836       }
1837     }
1838     if (LHSSB > InnerBitSize && RHSSB > InnerBitSize) {
1839       // The input values are both sign-extended.
1840       if (HasSMUL_LOHI) {
1841         // We can emit a smul_lohi.
1842         Lo = DAG.getNode(ISD::SMUL_LOHI, dl, DAG.getVTList(NVT, NVT), LL, RL);
1843         Hi = SDValue(Lo.getNode(), 1);
1844         return;
1845       }
1846       if (HasMULHS) {
1847         // We can emit a mulhs+mul.
1848         Lo = DAG.getNode(ISD::MUL, dl, NVT, LL, RL);
1849         Hi = DAG.getNode(ISD::MULHS, dl, NVT, LL, RL);
1850         return;
1851       }
1852     }
1853     if (HasUMUL_LOHI) {
1854       // Lo,Hi = umul LHS, RHS.
1855       SDValue UMulLOHI = DAG.getNode(ISD::UMUL_LOHI, dl,
1856                                        DAG.getVTList(NVT, NVT), LL, RL);
1857       Lo = UMulLOHI;
1858       Hi = UMulLOHI.getValue(1);
1859       RH = DAG.getNode(ISD::MUL, dl, NVT, LL, RH);
1860       LH = DAG.getNode(ISD::MUL, dl, NVT, LH, RL);
1861       Hi = DAG.getNode(ISD::ADD, dl, NVT, Hi, RH);
1862       Hi = DAG.getNode(ISD::ADD, dl, NVT, Hi, LH);
1863       return;
1864     }
1865     if (HasMULHU) {
1866       Lo = DAG.getNode(ISD::MUL, dl, NVT, LL, RL);
1867       Hi = DAG.getNode(ISD::MULHU, dl, NVT, LL, RL);
1868       RH = DAG.getNode(ISD::MUL, dl, NVT, LL, RH);
1869       LH = DAG.getNode(ISD::MUL, dl, NVT, LH, RL);
1870       Hi = DAG.getNode(ISD::ADD, dl, NVT, Hi, RH);
1871       Hi = DAG.getNode(ISD::ADD, dl, NVT, Hi, LH);
1872       return;
1873     }
1874   }
1875
1876   // If nothing else, we can make a libcall.
1877   RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
1878   if (VT == MVT::i16)
1879     LC = RTLIB::MUL_I16;
1880   else if (VT == MVT::i32)
1881     LC = RTLIB::MUL_I32;
1882   else if (VT == MVT::i64)
1883     LC = RTLIB::MUL_I64;
1884   else if (VT == MVT::i128)
1885     LC = RTLIB::MUL_I128;
1886   assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unsupported MUL!");
1887
1888   SDValue Ops[2] = { N->getOperand(0), N->getOperand(1) };
1889   SplitInteger(MakeLibCall(LC, VT, Ops, 2, true/*irrelevant*/, dl), Lo, Hi);
1890 }
1891
1892 void DAGTypeLegalizer::ExpandIntRes_SADDSUBO(SDNode *Node,
1893                                              SDValue &Lo, SDValue &Hi) {
1894   SDValue LHS = Node->getOperand(0);
1895   SDValue RHS = Node->getOperand(1);
1896   DebugLoc dl = Node->getDebugLoc();
1897
1898   // Expand the result by simply replacing it with the equivalent
1899   // non-overflow-checking operation.
1900   SDValue Sum = DAG.getNode(Node->getOpcode() == ISD::SADDO ?
1901                             ISD::ADD : ISD::SUB, dl, LHS.getValueType(),
1902                             LHS, RHS);
1903   SplitInteger(Sum, Lo, Hi);
1904
1905   // Compute the overflow.
1906   //
1907   //   LHSSign -> LHS >= 0
1908   //   RHSSign -> RHS >= 0
1909   //   SumSign -> Sum >= 0
1910   //
1911   //   Add:
1912   //   Overflow -> (LHSSign == RHSSign) && (LHSSign != SumSign)
1913   //   Sub:
1914   //   Overflow -> (LHSSign != RHSSign) && (LHSSign != SumSign)
1915   //
1916   EVT OType = Node->getValueType(1);
1917   SDValue Zero = DAG.getConstant(0, LHS.getValueType());
1918
1919   SDValue LHSSign = DAG.getSetCC(dl, OType, LHS, Zero, ISD::SETGE);
1920   SDValue RHSSign = DAG.getSetCC(dl, OType, RHS, Zero, ISD::SETGE);
1921   SDValue SignsMatch = DAG.getSetCC(dl, OType, LHSSign, RHSSign,
1922                                     Node->getOpcode() == ISD::SADDO ?
1923                                     ISD::SETEQ : ISD::SETNE);
1924
1925   SDValue SumSign = DAG.getSetCC(dl, OType, Sum, Zero, ISD::SETGE);
1926   SDValue SumSignNE = DAG.getSetCC(dl, OType, LHSSign, SumSign, ISD::SETNE);
1927
1928   SDValue Cmp = DAG.getNode(ISD::AND, dl, OType, SignsMatch, SumSignNE);
1929
1930   // Use the calculated overflow everywhere.
1931   ReplaceValueWith(SDValue(Node, 1), Cmp);
1932 }
1933
1934 void DAGTypeLegalizer::ExpandIntRes_SDIV(SDNode *N,
1935                                          SDValue &Lo, SDValue &Hi) {
1936   EVT VT = N->getValueType(0);
1937   DebugLoc dl = N->getDebugLoc();
1938
1939   RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
1940   if (VT == MVT::i16)
1941     LC = RTLIB::SDIV_I16;
1942   else if (VT == MVT::i32)
1943     LC = RTLIB::SDIV_I32;
1944   else if (VT == MVT::i64)
1945     LC = RTLIB::SDIV_I64;
1946   else if (VT == MVT::i128)
1947     LC = RTLIB::SDIV_I128;
1948   assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unsupported SDIV!");
1949
1950   SDValue Ops[2] = { N->getOperand(0), N->getOperand(1) };
1951   SplitInteger(MakeLibCall(LC, VT, Ops, 2, true, dl), Lo, Hi);
1952 }
1953
1954 void DAGTypeLegalizer::ExpandIntRes_Shift(SDNode *N,
1955                                           SDValue &Lo, SDValue &Hi) {
1956   EVT VT = N->getValueType(0);
1957   DebugLoc dl = N->getDebugLoc();
1958
1959   // If we can emit an efficient shift operation, do so now.  Check to see if
1960   // the RHS is a constant.
1961   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N->getOperand(1)))
1962     return ExpandShiftByConstant(N, CN->getZExtValue(), Lo, Hi);
1963
1964   // If we can determine that the high bit of the shift is zero or one, even if
1965   // the low bits are variable, emit this shift in an optimized form.
1966   if (ExpandShiftWithKnownAmountBit(N, Lo, Hi))
1967     return;
1968
1969   // If this target supports shift_PARTS, use it.  First, map to the _PARTS opc.
1970   unsigned PartsOpc;
1971   if (N->getOpcode() == ISD::SHL) {
1972     PartsOpc = ISD::SHL_PARTS;
1973   } else if (N->getOpcode() == ISD::SRL) {
1974     PartsOpc = ISD::SRL_PARTS;
1975   } else {
1976     assert(N->getOpcode() == ISD::SRA && "Unknown shift!");
1977     PartsOpc = ISD::SRA_PARTS;
1978   }
1979
1980   // Next check to see if the target supports this SHL_PARTS operation or if it
1981   // will custom expand it.
1982   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), VT);
1983   TargetLowering::LegalizeAction Action = TLI.getOperationAction(PartsOpc, NVT);
1984   if ((Action == TargetLowering::Legal && TLI.isTypeLegal(NVT)) ||
1985       Action == TargetLowering::Custom) {
1986     // Expand the subcomponents.
1987     SDValue LHSL, LHSH;
1988     GetExpandedInteger(N->getOperand(0), LHSL, LHSH);
1989
1990     SDValue Ops[] = { LHSL, LHSH, N->getOperand(1) };
1991     EVT VT = LHSL.getValueType();
1992     Lo = DAG.getNode(PartsOpc, dl, DAG.getVTList(VT, VT), Ops, 3);
1993     Hi = Lo.getValue(1);
1994     return;
1995   }
1996
1997   // Otherwise, emit a libcall.
1998   RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
1999   bool isSigned;
2000   if (N->getOpcode() == ISD::SHL) {
2001     isSigned = false; /*sign irrelevant*/
2002     if (VT == MVT::i16)
2003       LC = RTLIB::SHL_I16;
2004     else if (VT == MVT::i32)
2005       LC = RTLIB::SHL_I32;
2006     else if (VT == MVT::i64)
2007       LC = RTLIB::SHL_I64;
2008     else if (VT == MVT::i128)
2009       LC = RTLIB::SHL_I128;
2010   } else if (N->getOpcode() == ISD::SRL) {
2011     isSigned = false;
2012     if (VT == MVT::i16)
2013       LC = RTLIB::SRL_I16;
2014     else if (VT == MVT::i32)
2015       LC = RTLIB::SRL_I32;
2016     else if (VT == MVT::i64)
2017       LC = RTLIB::SRL_I64;
2018     else if (VT == MVT::i128)
2019       LC = RTLIB::SRL_I128;
2020   } else {
2021     assert(N->getOpcode() == ISD::SRA && "Unknown shift!");
2022     isSigned = true;
2023     if (VT == MVT::i16)
2024       LC = RTLIB::SRA_I16;
2025     else if (VT == MVT::i32)
2026       LC = RTLIB::SRA_I32;
2027     else if (VT == MVT::i64)
2028       LC = RTLIB::SRA_I64;
2029     else if (VT == MVT::i128)
2030       LC = RTLIB::SRA_I128;
2031   }
2032
2033   if (LC != RTLIB::UNKNOWN_LIBCALL && TLI.getLibcallName(LC)) {
2034     SDValue Ops[2] = { N->getOperand(0), N->getOperand(1) };
2035     SplitInteger(MakeLibCall(LC, VT, Ops, 2, isSigned, dl), Lo, Hi);
2036     return;
2037   }
2038
2039   if (!ExpandShiftWithUnknownAmountBit(N, Lo, Hi))
2040     llvm_unreachable("Unsupported shift!");
2041 }
2042
2043 void DAGTypeLegalizer::ExpandIntRes_SIGN_EXTEND(SDNode *N,
2044                                                 SDValue &Lo, SDValue &Hi) {
2045   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
2046   DebugLoc dl = N->getDebugLoc();
2047   SDValue Op = N->getOperand(0);
2048   if (Op.getValueType().bitsLE(NVT)) {
2049     // The low part is sign extension of the input (degenerates to a copy).
2050     Lo = DAG.getNode(ISD::SIGN_EXTEND, dl, NVT, N->getOperand(0));
2051     // The high part is obtained by SRA'ing all but one of the bits of low part.
2052     unsigned LoSize = NVT.getSizeInBits();
2053     Hi = DAG.getNode(ISD::SRA, dl, NVT, Lo,
2054                      DAG.getConstant(LoSize-1, TLI.getPointerTy()));
2055   } else {
2056     // For example, extension of an i48 to an i64.  The operand type necessarily
2057     // promotes to the result type, so will end up being expanded too.
2058     assert(getTypeAction(Op.getValueType()) ==
2059            TargetLowering::TypePromoteInteger &&
2060            "Only know how to promote this result!");
2061     SDValue Res = GetPromotedInteger(Op);
2062     assert(Res.getValueType() == N->getValueType(0) &&
2063            "Operand over promoted?");
2064     // Split the promoted operand.  This will simplify when it is expanded.
2065     SplitInteger(Res, Lo, Hi);
2066     unsigned ExcessBits =
2067       Op.getValueType().getSizeInBits() - NVT.getSizeInBits();
2068     Hi = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, Hi.getValueType(), Hi,
2069                      DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(),
2070                                                         ExcessBits)));
2071   }
2072 }
2073
2074 void DAGTypeLegalizer::
2075 ExpandIntRes_SIGN_EXTEND_INREG(SDNode *N, SDValue &Lo, SDValue &Hi) {
2076   DebugLoc dl = N->getDebugLoc();
2077   GetExpandedInteger(N->getOperand(0), Lo, Hi);
2078   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
2079
2080   if (EVT.bitsLE(Lo.getValueType())) {
2081     // sext_inreg the low part if needed.
2082     Lo = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, Lo.getValueType(), Lo,
2083                      N->getOperand(1));
2084
2085     // The high part gets the sign extension from the lo-part.  This handles
2086     // things like sextinreg V:i64 from i8.
2087     Hi = DAG.getNode(ISD::SRA, dl, Hi.getValueType(), Lo,
2088                      DAG.getConstant(Hi.getValueType().getSizeInBits()-1,
2089                                      TLI.getPointerTy()));
2090   } else {
2091     // For example, extension of an i48 to an i64.  Leave the low part alone,
2092     // sext_inreg the high part.
2093     unsigned ExcessBits =
2094       EVT.getSizeInBits() - Lo.getValueType().getSizeInBits();
2095     Hi = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, Hi.getValueType(), Hi,
2096                      DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(),
2097                                                         ExcessBits)));
2098   }
2099 }
2100
2101 void DAGTypeLegalizer::ExpandIntRes_SREM(SDNode *N,
2102                                          SDValue &Lo, SDValue &Hi) {
2103   EVT VT = N->getValueType(0);
2104   DebugLoc dl = N->getDebugLoc();
2105
2106   RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
2107   if (VT == MVT::i16)
2108     LC = RTLIB::SREM_I16;
2109   else if (VT == MVT::i32)
2110     LC = RTLIB::SREM_I32;
2111   else if (VT == MVT::i64)
2112     LC = RTLIB::SREM_I64;
2113   else if (VT == MVT::i128)
2114     LC = RTLIB::SREM_I128;
2115   assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unsupported SREM!");
2116
2117   SDValue Ops[2] = { N->getOperand(0), N->getOperand(1) };
2118   SplitInteger(MakeLibCall(LC, VT, Ops, 2, true, dl), Lo, Hi);
2119 }
2120
2121 void DAGTypeLegalizer::ExpandIntRes_TRUNCATE(SDNode *N,
2122                                              SDValue &Lo, SDValue &Hi) {
2123   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
2124   DebugLoc dl = N->getDebugLoc();
2125   Lo = DAG.getNode(ISD::TRUNCATE, dl, NVT, N->getOperand(0));
2126   Hi = DAG.getNode(ISD::SRL, dl,
2127                    N->getOperand(0).getValueType(), N->getOperand(0),
2128                    DAG.getConstant(NVT.getSizeInBits(), TLI.getPointerTy()));
2129   Hi = DAG.getNode(ISD::TRUNCATE, dl, NVT, Hi);
2130 }
2131
2132 void DAGTypeLegalizer::ExpandIntRes_UADDSUBO(SDNode *N,
2133                                              SDValue &Lo, SDValue &Hi) {
2134   SDValue LHS = N->getOperand(0);
2135   SDValue RHS = N->getOperand(1);
2136   DebugLoc dl = N->getDebugLoc();
2137
2138   // Expand the result by simply replacing it with the equivalent
2139   // non-overflow-checking operation.
2140   SDValue Sum = DAG.getNode(N->getOpcode() == ISD::UADDO ?
2141                             ISD::ADD : ISD::SUB, dl, LHS.getValueType(),
2142                             LHS, RHS);
2143   SplitInteger(Sum, Lo, Hi);
2144
2145   // Calculate the overflow: addition overflows iff a + b < a, and subtraction
2146   // overflows iff a - b > a.
2147   SDValue Ofl = DAG.getSetCC(dl, N->getValueType(1), Sum, LHS,
2148                              N->getOpcode () == ISD::UADDO ?
2149                              ISD::SETULT : ISD::SETUGT);
2150
2151   // Use the calculated overflow everywhere.
2152   ReplaceValueWith(SDValue(N, 1), Ofl);
2153 }
2154
2155 void DAGTypeLegalizer::ExpandIntRes_XMULO(SDNode *N,
2156                                           SDValue &Lo, SDValue &Hi) {
2157   EVT VT = N->getValueType(0);
2158   const Type *RetTy = VT.getTypeForEVT(*DAG.getContext());
2159   EVT PtrVT = TLI.getPointerTy();
2160   const Type *PtrTy = PtrVT.getTypeForEVT(*DAG.getContext());
2161   DebugLoc dl = N->getDebugLoc();
2162
2163   // Expand the result by simply replacing it with the equivalent
2164   // non-overflow-checking operation.
2165   RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
2166   if (VT == MVT::i32)
2167     LC = RTLIB::MULO_I32;
2168   else if (VT == MVT::i64)
2169     LC = RTLIB::MULO_I64;
2170   else if (VT == MVT::i128)
2171     LC = RTLIB::MULO_I128;
2172   assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unsupported XMULO!");
2173
2174   SDValue Temp = DAG.CreateStackTemporary(PtrVT);
2175   // Temporary for the overflow value, default it to zero.
2176   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl,
2177                                DAG.getConstant(0, PtrVT), Temp,
2178                                MachinePointerInfo(), false, false, 0);
2179
2180   TargetLowering::ArgListTy Args;
2181   TargetLowering::ArgListEntry Entry;
2182   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2183     EVT ArgVT = N->getOperand(i).getValueType();
2184     const Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
2185     Entry.Node = N->getOperand(i);
2186     Entry.Ty = ArgTy;
2187     Entry.isSExt = true;
2188     Entry.isZExt = false;
2189     Args.push_back(Entry);
2190   }
2191
2192   // Also pass the address of the overflow check.
2193   Entry.Node = Temp;
2194   Entry.Ty = PtrTy->getPointerTo();
2195   Entry.isSExt = true;
2196   Entry.isZExt = false;
2197   Args.push_back(Entry);
2198
2199   SDValue Func = DAG.getExternalSymbol(TLI.getLibcallName(LC), PtrVT);
2200   std::pair<SDValue, SDValue> CallInfo =
2201     TLI.LowerCallTo(Chain, RetTy, true, false, false, false,
2202                     0, TLI.getLibcallCallingConv(LC), false,
2203                     true, Func, Args, DAG, dl);
2204
2205   SplitInteger(CallInfo.first, Lo, Hi);
2206   SDValue Temp2 = DAG.getLoad(PtrVT, dl, CallInfo.second, Temp,
2207                               MachinePointerInfo(), false, false, 0);
2208   SDValue Ofl = DAG.getSetCC(dl, N->getValueType(1), Temp2,
2209                              DAG.getConstant(0, PtrVT),
2210                              ISD::SETNE);
2211   // Use the overflow from the libcall everywhere.
2212   ReplaceValueWith(SDValue(N, 1), Ofl);
2213 }
2214
2215 void DAGTypeLegalizer::ExpandIntRes_UDIV(SDNode *N,
2216                                          SDValue &Lo, SDValue &Hi) {
2217   EVT VT = N->getValueType(0);
2218   DebugLoc dl = N->getDebugLoc();
2219
2220   RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
2221   if (VT == MVT::i16)
2222     LC = RTLIB::UDIV_I16;
2223   else if (VT == MVT::i32)
2224     LC = RTLIB::UDIV_I32;
2225   else if (VT == MVT::i64)
2226     LC = RTLIB::UDIV_I64;
2227   else if (VT == MVT::i128)
2228     LC = RTLIB::UDIV_I128;
2229   assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unsupported UDIV!");
2230
2231   SDValue Ops[2] = { N->getOperand(0), N->getOperand(1) };
2232   SplitInteger(MakeLibCall(LC, VT, Ops, 2, false, dl), Lo, Hi);
2233 }
2234
2235 void DAGTypeLegalizer::ExpandIntRes_UREM(SDNode *N,
2236                                          SDValue &Lo, SDValue &Hi) {
2237   EVT VT = N->getValueType(0);
2238   DebugLoc dl = N->getDebugLoc();
2239
2240   RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
2241   if (VT == MVT::i16)
2242     LC = RTLIB::UREM_I16;
2243   else if (VT == MVT::i32)
2244     LC = RTLIB::UREM_I32;
2245   else if (VT == MVT::i64)
2246     LC = RTLIB::UREM_I64;
2247   else if (VT == MVT::i128)
2248     LC = RTLIB::UREM_I128;
2249   assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unsupported UREM!");
2250
2251   SDValue Ops[2] = { N->getOperand(0), N->getOperand(1) };
2252   SplitInteger(MakeLibCall(LC, VT, Ops, 2, false, dl), Lo, Hi);
2253 }
2254
2255 void DAGTypeLegalizer::ExpandIntRes_ZERO_EXTEND(SDNode *N,
2256                                                 SDValue &Lo, SDValue &Hi) {
2257   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
2258   DebugLoc dl = N->getDebugLoc();
2259   SDValue Op = N->getOperand(0);
2260   if (Op.getValueType().bitsLE(NVT)) {
2261     // The low part is zero extension of the input (degenerates to a copy).
2262     Lo = DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N->getOperand(0));
2263     Hi = DAG.getConstant(0, NVT);   // The high part is just a zero.
2264   } else {
2265     // For example, extension of an i48 to an i64.  The operand type necessarily
2266     // promotes to the result type, so will end up being expanded too.
2267     assert(getTypeAction(Op.getValueType()) ==
2268            TargetLowering::TypePromoteInteger &&
2269            "Only know how to promote this result!");
2270     SDValue Res = GetPromotedInteger(Op);
2271     assert(Res.getValueType() == N->getValueType(0) &&
2272            "Operand over promoted?");
2273     // Split the promoted operand.  This will simplify when it is expanded.
2274     SplitInteger(Res, Lo, Hi);
2275     unsigned ExcessBits =
2276       Op.getValueType().getSizeInBits() - NVT.getSizeInBits();
2277     Hi = DAG.getZeroExtendInReg(Hi, dl,
2278                                 EVT::getIntegerVT(*DAG.getContext(),
2279                                                   ExcessBits));
2280   }
2281 }
2282
2283
2284 //===----------------------------------------------------------------------===//
2285 //  Integer Operand Expansion
2286 //===----------------------------------------------------------------------===//
2287
2288 /// ExpandIntegerOperand - This method is called when the specified operand of
2289 /// the specified node is found to need expansion.  At this point, all of the
2290 /// result types of the node are known to be legal, but other operands of the
2291 /// node may need promotion or expansion as well as the specified one.
2292 bool DAGTypeLegalizer::ExpandIntegerOperand(SDNode *N, unsigned OpNo) {
2293   DEBUG(dbgs() << "Expand integer operand: "; N->dump(&DAG); dbgs() << "\n");
2294   SDValue Res = SDValue();
2295
2296   if (CustomLowerNode(N, N->getOperand(OpNo).getValueType(), false))
2297     return false;
2298
2299   switch (N->getOpcode()) {
2300   default:
2301   #ifndef NDEBUG
2302     dbgs() << "ExpandIntegerOperand Op #" << OpNo << ": ";
2303     N->dump(&DAG); dbgs() << "\n";
2304   #endif
2305     llvm_unreachable("Do not know how to expand this operator's operand!");
2306
2307   case ISD::BITCAST:           Res = ExpandOp_BITCAST(N); break;
2308   case ISD::BR_CC:             Res = ExpandIntOp_BR_CC(N); break;
2309   case ISD::BUILD_VECTOR:      Res = ExpandOp_BUILD_VECTOR(N); break;
2310   case ISD::EXTRACT_ELEMENT:   Res = ExpandOp_EXTRACT_ELEMENT(N); break;
2311   case ISD::INSERT_VECTOR_ELT: Res = ExpandOp_INSERT_VECTOR_ELT(N); break;
2312   case ISD::SCALAR_TO_VECTOR:  Res = ExpandOp_SCALAR_TO_VECTOR(N); break;
2313   case ISD::SELECT_CC:         Res = ExpandIntOp_SELECT_CC(N); break;
2314   case ISD::SETCC:             Res = ExpandIntOp_SETCC(N); break;
2315   case ISD::SINT_TO_FP:        Res = ExpandIntOp_SINT_TO_FP(N); break;
2316   case ISD::STORE:   Res = ExpandIntOp_STORE(cast<StoreSDNode>(N), OpNo); break;
2317   case ISD::TRUNCATE:          Res = ExpandIntOp_TRUNCATE(N); break;
2318   case ISD::UINT_TO_FP:        Res = ExpandIntOp_UINT_TO_FP(N); break;
2319
2320   case ISD::SHL:
2321   case ISD::SRA:
2322   case ISD::SRL:
2323   case ISD::ROTL:
2324   case ISD::ROTR:              Res = ExpandIntOp_Shift(N); break;
2325   case ISD::RETURNADDR:
2326   case ISD::FRAMEADDR:         Res = ExpandIntOp_RETURNADDR(N); break;
2327   }
2328
2329   // If the result is null, the sub-method took care of registering results etc.
2330   if (!Res.getNode()) return false;
2331
2332   // If the result is N, the sub-method updated N in place.  Tell the legalizer
2333   // core about this.
2334   if (Res.getNode() == N)
2335     return true;
2336
2337   assert(Res.getValueType() == N->getValueType(0) && N->getNumValues() == 1 &&
2338          "Invalid operand expansion");
2339
2340   ReplaceValueWith(SDValue(N, 0), Res);
2341   return false;
2342 }
2343
2344 /// IntegerExpandSetCCOperands - Expand the operands of a comparison.  This code
2345 /// is shared among BR_CC, SELECT_CC, and SETCC handlers.
2346 void DAGTypeLegalizer::IntegerExpandSetCCOperands(SDValue &NewLHS,
2347                                                   SDValue &NewRHS,
2348                                                   ISD::CondCode &CCCode,
2349                                                   DebugLoc dl) {
2350   SDValue LHSLo, LHSHi, RHSLo, RHSHi;
2351   GetExpandedInteger(NewLHS, LHSLo, LHSHi);
2352   GetExpandedInteger(NewRHS, RHSLo, RHSHi);
2353
2354   if (CCCode == ISD::SETEQ || CCCode == ISD::SETNE) {
2355     if (RHSLo == RHSHi) {
2356       if (ConstantSDNode *RHSCST = dyn_cast<ConstantSDNode>(RHSLo)) {
2357         if (RHSCST->isAllOnesValue()) {
2358           // Equality comparison to -1.
2359           NewLHS = DAG.getNode(ISD::AND, dl,
2360                                LHSLo.getValueType(), LHSLo, LHSHi);
2361           NewRHS = RHSLo;
2362           return;
2363         }
2364       }
2365     }
2366
2367     NewLHS = DAG.getNode(ISD::XOR, dl, LHSLo.getValueType(), LHSLo, RHSLo);
2368     NewRHS = DAG.getNode(ISD::XOR, dl, LHSLo.getValueType(), LHSHi, RHSHi);
2369     NewLHS = DAG.getNode(ISD::OR, dl, NewLHS.getValueType(), NewLHS, NewRHS);
2370     NewRHS = DAG.getConstant(0, NewLHS.getValueType());
2371     return;
2372   }
2373
2374   // If this is a comparison of the sign bit, just look at the top part.
2375   // X > -1,  x < 0
2376   if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(NewRHS))
2377     if ((CCCode == ISD::SETLT && CST->isNullValue()) ||     // X < 0
2378         (CCCode == ISD::SETGT && CST->isAllOnesValue())) {  // X > -1
2379       NewLHS = LHSHi;
2380       NewRHS = RHSHi;
2381       return;
2382     }
2383
2384   // FIXME: This generated code sucks.
2385   ISD::CondCode LowCC;
2386   switch (CCCode) {
2387   default: llvm_unreachable("Unknown integer setcc!");
2388   case ISD::SETLT:
2389   case ISD::SETULT: LowCC = ISD::SETULT; break;
2390   case ISD::SETGT:
2391   case ISD::SETUGT: LowCC = ISD::SETUGT; break;
2392   case ISD::SETLE:
2393   case ISD::SETULE: LowCC = ISD::SETULE; break;
2394   case ISD::SETGE:
2395   case ISD::SETUGE: LowCC = ISD::SETUGE; break;
2396   }
2397
2398   // Tmp1 = lo(op1) < lo(op2)   // Always unsigned comparison
2399   // Tmp2 = hi(op1) < hi(op2)   // Signedness depends on operands
2400   // dest = hi(op1) == hi(op2) ? Tmp1 : Tmp2;
2401
2402   // NOTE: on targets without efficient SELECT of bools, we can always use
2403   // this identity: (B1 ? B2 : B3) --> (B1 & B2)|(!B1&B3)
2404   TargetLowering::DAGCombinerInfo DagCombineInfo(DAG, false, true, true, NULL);
2405   SDValue Tmp1, Tmp2;
2406   Tmp1 = TLI.SimplifySetCC(TLI.getSetCCResultType(LHSLo.getValueType()),
2407                            LHSLo, RHSLo, LowCC, false, DagCombineInfo, dl);
2408   if (!Tmp1.getNode())
2409     Tmp1 = DAG.getSetCC(dl, TLI.getSetCCResultType(LHSLo.getValueType()),
2410                         LHSLo, RHSLo, LowCC);
2411   Tmp2 = TLI.SimplifySetCC(TLI.getSetCCResultType(LHSHi.getValueType()),
2412                            LHSHi, RHSHi, CCCode, false, DagCombineInfo, dl);
2413   if (!Tmp2.getNode())
2414     Tmp2 = DAG.getNode(ISD::SETCC, dl,
2415                        TLI.getSetCCResultType(LHSHi.getValueType()),
2416                        LHSHi, RHSHi, DAG.getCondCode(CCCode));
2417
2418   ConstantSDNode *Tmp1C = dyn_cast<ConstantSDNode>(Tmp1.getNode());
2419   ConstantSDNode *Tmp2C = dyn_cast<ConstantSDNode>(Tmp2.getNode());
2420   if ((Tmp1C && Tmp1C->isNullValue()) ||
2421       (Tmp2C && Tmp2C->isNullValue() &&
2422        (CCCode == ISD::SETLE || CCCode == ISD::SETGE ||
2423         CCCode == ISD::SETUGE || CCCode == ISD::SETULE)) ||
2424       (Tmp2C && Tmp2C->getAPIntValue() == 1 &&
2425        (CCCode == ISD::SETLT || CCCode == ISD::SETGT ||
2426         CCCode == ISD::SETUGT || CCCode == ISD::SETULT))) {
2427     // low part is known false, returns high part.
2428     // For LE / GE, if high part is known false, ignore the low part.
2429     // For LT / GT, if high part is known true, ignore the low part.
2430     NewLHS = Tmp2;
2431     NewRHS = SDValue();
2432     return;
2433   }
2434
2435   NewLHS = TLI.SimplifySetCC(TLI.getSetCCResultType(LHSHi.getValueType()),
2436                              LHSHi, RHSHi, ISD::SETEQ, false,
2437                              DagCombineInfo, dl);
2438   if (!NewLHS.getNode())
2439     NewLHS = DAG.getSetCC(dl, TLI.getSetCCResultType(LHSHi.getValueType()),
2440                           LHSHi, RHSHi, ISD::SETEQ);
2441   NewLHS = DAG.getNode(ISD::SELECT, dl, Tmp1.getValueType(),
2442                        NewLHS, Tmp1, Tmp2);
2443   NewRHS = SDValue();
2444 }
2445
2446 SDValue DAGTypeLegalizer::ExpandIntOp_BR_CC(SDNode *N) {
2447   SDValue NewLHS = N->getOperand(2), NewRHS = N->getOperand(3);
2448   ISD::CondCode CCCode = cast<CondCodeSDNode>(N->getOperand(1))->get();
2449   IntegerExpandSetCCOperands(NewLHS, NewRHS, CCCode, N->getDebugLoc());
2450
2451   // If ExpandSetCCOperands returned a scalar, we need to compare the result
2452   // against zero to select between true and false values.
2453   if (NewRHS.getNode() == 0) {
2454     NewRHS = DAG.getConstant(0, NewLHS.getValueType());
2455     CCCode = ISD::SETNE;
2456   }
2457
2458   // Update N to have the operands specified.
2459   return SDValue(DAG.UpdateNodeOperands(N, N->getOperand(0),
2460                                 DAG.getCondCode(CCCode), NewLHS, NewRHS,
2461                                 N->getOperand(4)), 0);
2462 }
2463
2464 SDValue DAGTypeLegalizer::ExpandIntOp_SELECT_CC(SDNode *N) {
2465   SDValue NewLHS = N->getOperand(0), NewRHS = N->getOperand(1);
2466   ISD::CondCode CCCode = cast<CondCodeSDNode>(N->getOperand(4))->get();
2467   IntegerExpandSetCCOperands(NewLHS, NewRHS, CCCode, N->getDebugLoc());
2468
2469   // If ExpandSetCCOperands returned a scalar, we need to compare the result
2470   // against zero to select between true and false values.
2471   if (NewRHS.getNode() == 0) {
2472     NewRHS = DAG.getConstant(0, NewLHS.getValueType());
2473     CCCode = ISD::SETNE;
2474   }
2475
2476   // Update N to have the operands specified.
2477   return SDValue(DAG.UpdateNodeOperands(N, NewLHS, NewRHS,
2478                                 N->getOperand(2), N->getOperand(3),
2479                                 DAG.getCondCode(CCCode)), 0);
2480 }
2481
2482 SDValue DAGTypeLegalizer::ExpandIntOp_SETCC(SDNode *N) {
2483   SDValue NewLHS = N->getOperand(0), NewRHS = N->getOperand(1);
2484   ISD::CondCode CCCode = cast<CondCodeSDNode>(N->getOperand(2))->get();
2485   IntegerExpandSetCCOperands(NewLHS, NewRHS, CCCode, N->getDebugLoc());
2486
2487   // If ExpandSetCCOperands returned a scalar, use it.
2488   if (NewRHS.getNode() == 0) {
2489     assert(NewLHS.getValueType() == N->getValueType(0) &&
2490            "Unexpected setcc expansion!");
2491     return NewLHS;
2492   }
2493
2494   // Otherwise, update N to have the operands specified.
2495   return SDValue(DAG.UpdateNodeOperands(N, NewLHS, NewRHS,
2496                                 DAG.getCondCode(CCCode)), 0);
2497 }
2498
2499 SDValue DAGTypeLegalizer::ExpandIntOp_Shift(SDNode *N) {
2500   // The value being shifted is legal, but the shift amount is too big.
2501   // It follows that either the result of the shift is undefined, or the
2502   // upper half of the shift amount is zero.  Just use the lower half.
2503   SDValue Lo, Hi;
2504   GetExpandedInteger(N->getOperand(1), Lo, Hi);
2505   return SDValue(DAG.UpdateNodeOperands(N, N->getOperand(0), Lo), 0);
2506 }
2507
2508 SDValue DAGTypeLegalizer::ExpandIntOp_RETURNADDR(SDNode *N) {
2509   // The argument of RETURNADDR / FRAMEADDR builtin is 32 bit contant.  This
2510   // surely makes pretty nice problems on 8/16 bit targets. Just truncate this
2511   // constant to valid type.
2512   SDValue Lo, Hi;
2513   GetExpandedInteger(N->getOperand(0), Lo, Hi);
2514   return SDValue(DAG.UpdateNodeOperands(N, Lo), 0);
2515 }
2516
2517 SDValue DAGTypeLegalizer::ExpandIntOp_SINT_TO_FP(SDNode *N) {
2518   SDValue Op = N->getOperand(0);
2519   EVT DstVT = N->getValueType(0);
2520   RTLIB::Libcall LC = RTLIB::getSINTTOFP(Op.getValueType(), DstVT);
2521   assert(LC != RTLIB::UNKNOWN_LIBCALL &&
2522          "Don't know how to expand this SINT_TO_FP!");
2523   return MakeLibCall(LC, DstVT, &Op, 1, true, N->getDebugLoc());
2524 }
2525
2526 SDValue DAGTypeLegalizer::ExpandIntOp_STORE(StoreSDNode *N, unsigned OpNo) {
2527   if (ISD::isNormalStore(N))
2528     return ExpandOp_NormalStore(N, OpNo);
2529
2530   assert(ISD::isUNINDEXEDStore(N) && "Indexed store during type legalization!");
2531   assert(OpNo == 1 && "Can only expand the stored value so far");
2532
2533   EVT VT = N->getOperand(1).getValueType();
2534   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), VT);
2535   SDValue Ch  = N->getChain();
2536   SDValue Ptr = N->getBasePtr();
2537   unsigned Alignment = N->getAlignment();
2538   bool isVolatile = N->isVolatile();
2539   bool isNonTemporal = N->isNonTemporal();
2540   DebugLoc dl = N->getDebugLoc();
2541   SDValue Lo, Hi;
2542
2543   assert(NVT.isByteSized() && "Expanded type not byte sized!");
2544
2545   if (N->getMemoryVT().bitsLE(NVT)) {
2546     GetExpandedInteger(N->getValue(), Lo, Hi);
2547     return DAG.getTruncStore(Ch, dl, Lo, Ptr, N->getPointerInfo(),
2548                              N->getMemoryVT(), isVolatile, isNonTemporal,
2549                              Alignment);
2550   }
2551
2552   if (TLI.isLittleEndian()) {
2553     // Little-endian - low bits are at low addresses.
2554     GetExpandedInteger(N->getValue(), Lo, Hi);
2555
2556     Lo = DAG.getStore(Ch, dl, Lo, Ptr, N->getPointerInfo(),
2557                       isVolatile, isNonTemporal, Alignment);
2558
2559     unsigned ExcessBits =
2560       N->getMemoryVT().getSizeInBits() - NVT.getSizeInBits();
2561     EVT NEVT = EVT::getIntegerVT(*DAG.getContext(), ExcessBits);
2562
2563     // Increment the pointer to the other half.
2564     unsigned IncrementSize = NVT.getSizeInBits()/8;
2565     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
2566                       DAG.getIntPtrConstant(IncrementSize));
2567     Hi = DAG.getTruncStore(Ch, dl, Hi, Ptr,
2568                            N->getPointerInfo().getWithOffset(IncrementSize),
2569                            NEVT, isVolatile, isNonTemporal,
2570                            MinAlign(Alignment, IncrementSize));
2571     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo, Hi);
2572   }
2573
2574   // Big-endian - high bits are at low addresses.  Favor aligned stores at
2575   // the cost of some bit-fiddling.
2576   GetExpandedInteger(N->getValue(), Lo, Hi);
2577
2578   EVT ExtVT = N->getMemoryVT();
2579   unsigned EBytes = ExtVT.getStoreSize();
2580   unsigned IncrementSize = NVT.getSizeInBits()/8;
2581   unsigned ExcessBits = (EBytes - IncrementSize)*8;
2582   EVT HiVT = EVT::getIntegerVT(*DAG.getContext(),
2583                                ExtVT.getSizeInBits() - ExcessBits);
2584
2585   if (ExcessBits < NVT.getSizeInBits()) {
2586     // Transfer high bits from the top of Lo to the bottom of Hi.
2587     Hi = DAG.getNode(ISD::SHL, dl, NVT, Hi,
2588                      DAG.getConstant(NVT.getSizeInBits() - ExcessBits,
2589                                      TLI.getPointerTy()));
2590     Hi = DAG.getNode(ISD::OR, dl, NVT, Hi,
2591                      DAG.getNode(ISD::SRL, dl, NVT, Lo,
2592                                  DAG.getConstant(ExcessBits,
2593                                                  TLI.getPointerTy())));
2594   }
2595
2596   // Store both the high bits and maybe some of the low bits.
2597   Hi = DAG.getTruncStore(Ch, dl, Hi, Ptr, N->getPointerInfo(),
2598                          HiVT, isVolatile, isNonTemporal, Alignment);
2599
2600   // Increment the pointer to the other half.
2601   Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
2602                     DAG.getIntPtrConstant(IncrementSize));
2603   // Store the lowest ExcessBits bits in the second half.
2604   Lo = DAG.getTruncStore(Ch, dl, Lo, Ptr,
2605                          N->getPointerInfo().getWithOffset(IncrementSize),
2606                          EVT::getIntegerVT(*DAG.getContext(), ExcessBits),
2607                          isVolatile, isNonTemporal,
2608                          MinAlign(Alignment, IncrementSize));
2609   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo, Hi);
2610 }
2611
2612 SDValue DAGTypeLegalizer::ExpandIntOp_TRUNCATE(SDNode *N) {
2613   SDValue InL, InH;
2614   GetExpandedInteger(N->getOperand(0), InL, InH);
2615   // Just truncate the low part of the source.
2616   return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), N->getValueType(0), InL);
2617 }
2618
2619 static const fltSemantics *EVTToAPFloatSemantics(EVT VT) {
2620   switch (VT.getSimpleVT().SimpleTy) {
2621   default: llvm_unreachable("Unknown FP format");
2622   case MVT::f32:     return &APFloat::IEEEsingle;
2623   case MVT::f64:     return &APFloat::IEEEdouble;
2624   case MVT::f80:     return &APFloat::x87DoubleExtended;
2625   case MVT::f128:    return &APFloat::IEEEquad;
2626   case MVT::ppcf128: return &APFloat::PPCDoubleDouble;
2627   }
2628 }
2629
2630 SDValue DAGTypeLegalizer::ExpandIntOp_UINT_TO_FP(SDNode *N) {
2631   SDValue Op = N->getOperand(0);
2632   EVT SrcVT = Op.getValueType();
2633   EVT DstVT = N->getValueType(0);
2634   DebugLoc dl = N->getDebugLoc();
2635
2636   // The following optimization is valid only if every value in SrcVT (when
2637   // treated as signed) is representable in DstVT.  Check that the mantissa
2638   // size of DstVT is >= than the number of bits in SrcVT -1.
2639   const fltSemantics *sem = EVTToAPFloatSemantics(DstVT);
2640   if (APFloat::semanticsPrecision(*sem) >= SrcVT.getSizeInBits()-1 &&
2641       TLI.getOperationAction(ISD::SINT_TO_FP, SrcVT) == TargetLowering::Custom){
2642     // Do a signed conversion then adjust the result.
2643     SDValue SignedConv = DAG.getNode(ISD::SINT_TO_FP, dl, DstVT, Op);
2644     SignedConv = TLI.LowerOperation(SignedConv, DAG);
2645
2646     // The result of the signed conversion needs adjusting if the 'sign bit' of
2647     // the incoming integer was set.  To handle this, we dynamically test to see
2648     // if it is set, and, if so, add a fudge factor.
2649
2650     const uint64_t F32TwoE32  = 0x4F800000ULL;
2651     const uint64_t F32TwoE64  = 0x5F800000ULL;
2652     const uint64_t F32TwoE128 = 0x7F800000ULL;
2653
2654     APInt FF(32, 0);
2655     if (SrcVT == MVT::i32)
2656       FF = APInt(32, F32TwoE32);
2657     else if (SrcVT == MVT::i64)
2658       FF = APInt(32, F32TwoE64);
2659     else if (SrcVT == MVT::i128)
2660       FF = APInt(32, F32TwoE128);
2661     else
2662       assert(false && "Unsupported UINT_TO_FP!");
2663
2664     // Check whether the sign bit is set.
2665     SDValue Lo, Hi;
2666     GetExpandedInteger(Op, Lo, Hi);
2667     SDValue SignSet = DAG.getSetCC(dl,
2668                                    TLI.getSetCCResultType(Hi.getValueType()),
2669                                    Hi, DAG.getConstant(0, Hi.getValueType()),
2670                                    ISD::SETLT);
2671
2672     // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
2673     SDValue FudgePtr = DAG.getConstantPool(
2674                                ConstantInt::get(*DAG.getContext(), FF.zext(64)),
2675                                            TLI.getPointerTy());
2676
2677     // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
2678     SDValue Zero = DAG.getIntPtrConstant(0);
2679     SDValue Four = DAG.getIntPtrConstant(4);
2680     if (TLI.isBigEndian()) std::swap(Zero, Four);
2681     SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
2682                                  Zero, Four);
2683     unsigned Alignment = cast<ConstantPoolSDNode>(FudgePtr)->getAlignment();
2684     FudgePtr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(), FudgePtr, Offset);
2685     Alignment = std::min(Alignment, 4u);
2686
2687     // Load the value out, extending it from f32 to the destination float type.
2688     // FIXME: Avoid the extend by constructing the right constant pool?
2689     SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, DstVT, DAG.getEntryNode(),
2690                                    FudgePtr,
2691                                    MachinePointerInfo::getConstantPool(),
2692                                    MVT::f32,
2693                                    false, false, Alignment);
2694     return DAG.getNode(ISD::FADD, dl, DstVT, SignedConv, Fudge);
2695   }
2696
2697   // Otherwise, use a libcall.
2698   RTLIB::Libcall LC = RTLIB::getUINTTOFP(SrcVT, DstVT);
2699   assert(LC != RTLIB::UNKNOWN_LIBCALL &&
2700          "Don't know how to expand this UINT_TO_FP!");
2701   return MakeLibCall(LC, DstVT, &Op, 1, true, dl);
2702 }
2703
2704 SDValue DAGTypeLegalizer::PromoteIntRes_EXTRACT_SUBVECTOR(SDNode *N) {
2705   SDValue InOp0 = N->getOperand(0);
2706   EVT InVT = InOp0.getValueType();
2707   EVT NInVT = TLI.getTypeToTransformTo(*DAG.getContext(), InVT);
2708
2709   EVT OutVT = N->getValueType(0);
2710   EVT NOutVT = TLI.getTypeToTransformTo(*DAG.getContext(), OutVT);
2711   assert(NOutVT.isVector() && "This type must be promoted to a vector type");
2712   unsigned OutNumElems = N->getValueType(0).getVectorNumElements();
2713   EVT NOutVTElem = NOutVT.getVectorElementType();
2714
2715   DebugLoc dl = N->getDebugLoc();
2716   SDValue BaseIdx = N->getOperand(1);
2717
2718   SmallVector<SDValue, 8> Ops;
2719   for (unsigned i = 0; i != OutNumElems; ++i) {
2720
2721     // Extract the element from the original vector.
2722     SDValue Index = DAG.getNode(ISD::ADD, dl, BaseIdx.getValueType(),
2723       BaseIdx, DAG.getIntPtrConstant(i));
2724     SDValue Ext = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
2725       InVT.getVectorElementType(), N->getOperand(0), Index);
2726
2727     SDValue Op = DAG.getNode(ISD::ANY_EXTEND, dl, NOutVTElem, Ext);
2728     // Insert the converted element to the new vector.
2729     Ops.push_back(Op);
2730   }
2731
2732   return DAG.getNode(ISD::BUILD_VECTOR, dl, NOutVT, &Ops[0], Ops.size());
2733 }
2734
2735
2736 SDValue DAGTypeLegalizer::PromoteIntRes_VECTOR_SHUFFLE(SDNode *N) {
2737
2738   ShuffleVectorSDNode *SV = cast<ShuffleVectorSDNode>(N);
2739   EVT VT = N->getValueType(0);
2740   DebugLoc dl = N->getDebugLoc();
2741
2742   unsigned NumElts = VT.getVectorNumElements();
2743   SmallVector<int, 8> NewMask;
2744   for (unsigned i = 0; i != NumElts; ++i) {
2745     NewMask.push_back(SV->getMaskElt(i));
2746   }
2747
2748   SDValue V0 = GetPromotedInteger(N->getOperand(0));
2749   SDValue V1 = GetPromotedInteger(N->getOperand(1));
2750   EVT OutVT = TLI.getTypeToTransformTo(*DAG.getContext(), VT);
2751
2752   return DAG.getVectorShuffle(OutVT, dl, V0,V1, &NewMask[0]);
2753 }
2754
2755
2756 SDValue DAGTypeLegalizer::PromoteIntRes_BUILD_VECTOR(SDNode *N) {
2757
2758   SDValue InOp0 = N->getOperand(0);
2759   EVT InVT = InOp0.getValueType();
2760   EVT NInVT = TLI.getTypeToTransformTo(*DAG.getContext(), InVT);
2761
2762   EVT OutVT = N->getValueType(0);
2763   EVT NOutVT = TLI.getTypeToTransformTo(*DAG.getContext(), OutVT);
2764   assert(NOutVT.isVector() && "This type must be promoted to a vector type");
2765   unsigned NumElems = N->getNumOperands();
2766   EVT NOutVTElem = NOutVT.getVectorElementType();
2767
2768   DebugLoc dl = N->getDebugLoc();
2769
2770   SmallVector<SDValue, 8> Ops;
2771   for (unsigned i = 0; i != NumElems; ++i) {
2772     SDValue Op = DAG.getNode(ISD::ANY_EXTEND, dl, NOutVTElem, N->getOperand(i));
2773     Ops.push_back(Op);
2774   }
2775
2776   return DAG.getNode(ISD::BUILD_VECTOR, dl, NOutVT, &Ops[0], Ops.size());
2777 }
2778
2779 SDValue DAGTypeLegalizer::PromoteIntRes_SCALAR_TO_VECTOR(SDNode *N) {
2780
2781   DebugLoc dl = N->getDebugLoc();
2782
2783   SDValue InOp0 = N->getOperand(0);
2784   EVT InVT = InOp0.getValueType();
2785   EVT NInVT = TLI.getTypeToTransformTo(*DAG.getContext(), InVT);
2786   assert(!InVT.isVector() && "Input must not be a scalar");
2787
2788   EVT OutVT = N->getValueType(0);
2789   EVT NOutVT = TLI.getTypeToTransformTo(*DAG.getContext(), OutVT);
2790   assert(NOutVT.isVector() && "This type must be promoted to a vector type");
2791   EVT NOutVTElem = NOutVT.getVectorElementType();
2792
2793   SDValue Op = DAG.getNode(ISD::ANY_EXTEND, dl, NOutVTElem, N->getOperand(0));
2794
2795   return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NOutVT, Op);
2796 }
2797
2798 SDValue DAGTypeLegalizer::PromoteIntRes_INSERT_VECTOR_ELT(SDNode *N) {
2799
2800   SDValue InOp0 = N->getOperand(0);
2801   EVT InVT = InOp0.getValueType();
2802   EVT InElVT = InVT.getVectorElementType();
2803   EVT NInVT = TLI.getTypeToTransformTo(*DAG.getContext(), InVT);
2804
2805   EVT OutVT = N->getValueType(0);
2806   EVT NOutVT = TLI.getTypeToTransformTo(*DAG.getContext(), OutVT);
2807   assert(NOutVT.isVector() && "This type must be promoted to a vector type");
2808
2809   EVT NOutVTElem = NOutVT.getVectorElementType();
2810
2811   DebugLoc dl = N->getDebugLoc();
2812
2813   SDValue ConvertedVector = DAG.getNode(ISD::ANY_EXTEND, dl, NOutVT, InOp0);
2814
2815   SDValue ConvElem = DAG.getNode(ISD::ANY_EXTEND, dl,
2816     NOutVTElem, N->getOperand(1));
2817   return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,NOutVT,
2818     ConvertedVector, ConvElem, N->getOperand(2));
2819 }
2820
2821 SDValue DAGTypeLegalizer::PromoteIntOp_EXTRACT_VECTOR_ELT(SDNode *N) {
2822   DebugLoc dl = N->getDebugLoc();
2823   SDValue V0 = GetPromotedInteger(N->getOperand(0));
2824   SDValue V1 = N->getOperand(1);
2825   SDValue Ext = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
2826     V0->getValueType(0).getScalarType(), V0, V1);
2827
2828   return DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), Ext);
2829
2830 }
2831
2832 SDValue DAGTypeLegalizer::PromoteIntOp_CONCAT_VECTORS(SDNode *N) {
2833
2834   DebugLoc dl = N->getDebugLoc();
2835
2836   EVT RetSclrTy = N->getValueType(0).getVectorElementType();
2837
2838   SmallVector<SDValue, 8> NewOps;
2839
2840   // For each incoming vector
2841   for (unsigned VecIdx = 0, E = N->getNumOperands(); VecIdx!= E; ++VecIdx) {
2842     SDValue Incoming = GetPromotedInteger(N->getOperand(VecIdx));
2843     EVT SclrTy = Incoming->getValueType(0).getVectorElementType();
2844     unsigned NumElem = Incoming->getValueType(0).getVectorNumElements();
2845
2846     for (unsigned i=0; i<NumElem; ++i) {
2847       // Extract element from incoming vector
2848       SDValue Ex = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SclrTy,
2849       Incoming, DAG.getIntPtrConstant(i));
2850       SDValue Tr = DAG.getNode(ISD::TRUNCATE, dl, RetSclrTy, Ex);
2851       NewOps.push_back(Tr);
2852     }
2853   }
2854
2855   return DAG.getNode(ISD::BUILD_VECTOR, dl,  N->getValueType(0),
2856     &NewOps[0], NewOps.size());
2857   }