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