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