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