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