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