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