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