1 //===----- LegalizeIntegerTypes.cpp - Legalization of integer types -------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements integer type expansion and promotion for LegalizeTypes.
10 // Promotion is the act of changing a computation in an illegal type into a
11 // computation in a larger type.  For example, implementing i8 arithmetic in an
12 // i32 register (often needed on powerpc).
13 // Expansion is the act of changing a computation in an illegal type into a
14 // computation in two identical registers of a smaller type.  For example,
15 // implementing i64 arithmetic in two i32 registers (often needed on 32-bit
16 // targets).
17 //
18 //===----------------------------------------------------------------------===//
19 
20 #include "LegalizeTypes.h"
21 #include "llvm/IR/DerivedTypes.h"
22 #include "llvm/Support/ErrorHandling.h"
23 #include "llvm/Support/KnownBits.h"
24 #include "llvm/Support/raw_ostream.h"
25 using namespace llvm;
26 
27 #define DEBUG_TYPE "legalize-types"
28 
29 //===----------------------------------------------------------------------===//
30 //  Integer Result Promotion
31 //===----------------------------------------------------------------------===//
32 
33 /// PromoteIntegerResult - This method is called when a result of a node is
34 /// found to be in need of promotion to a larger type.  At this point, the node
35 /// may also have invalid operands or may have other results that need
36 /// expansion, we just know that (at least) one result needs promotion.
37 void DAGTypeLegalizer::PromoteIntegerResult(SDNode *N, unsigned ResNo) {
38   LLVM_DEBUG(dbgs() << "Promote integer result: "; N->dump(&DAG);
39              dbgs() << "\n");
40   SDValue Res = SDValue();
41 
42   // See if the target wants to custom expand this node.
43   if (CustomLowerNode(N, N->getValueType(ResNo), true)) {
44     LLVM_DEBUG(dbgs() << "Node has been custom expanded, done\n");
45     return;
46   }
47 
48   switch (N->getOpcode()) {
49   default:
50 #ifndef NDEBUG
51     dbgs() << "PromoteIntegerResult #" << ResNo << ": ";
52     N->dump(&DAG); dbgs() << "\n";
53 #endif
54     llvm_unreachable("Do not know how to promote this operator!");
55   case ISD::MERGE_VALUES:Res = PromoteIntRes_MERGE_VALUES(N, ResNo); break;
56   case ISD::AssertSext:  Res = PromoteIntRes_AssertSext(N); break;
57   case ISD::AssertZext:  Res = PromoteIntRes_AssertZext(N); break;
58   case ISD::BITCAST:     Res = PromoteIntRes_BITCAST(N); break;
59   case ISD::BITREVERSE:  Res = PromoteIntRes_BITREVERSE(N); break;
60   case ISD::BSWAP:       Res = PromoteIntRes_BSWAP(N); break;
61   case ISD::BUILD_PAIR:  Res = PromoteIntRes_BUILD_PAIR(N); break;
62   case ISD::Constant:    Res = PromoteIntRes_Constant(N); break;
63   case ISD::CTLZ_ZERO_UNDEF:
64   case ISD::CTLZ:        Res = PromoteIntRes_CTLZ(N); break;
65   case ISD::CTPOP:       Res = PromoteIntRes_CTPOP(N); break;
66   case ISD::CTTZ_ZERO_UNDEF:
67   case ISD::CTTZ:        Res = PromoteIntRes_CTTZ(N); break;
68   case ISD::EXTRACT_VECTOR_ELT:
69                          Res = PromoteIntRes_EXTRACT_VECTOR_ELT(N); break;
70   case ISD::LOAD:        Res = PromoteIntRes_LOAD(cast<LoadSDNode>(N)); break;
71   case ISD::MLOAD:       Res = PromoteIntRes_MLOAD(cast<MaskedLoadSDNode>(N));
72     break;
73   case ISD::MGATHER:     Res = PromoteIntRes_MGATHER(cast<MaskedGatherSDNode>(N));
74     break;
75   case ISD::SELECT:      Res = PromoteIntRes_SELECT(N); break;
76   case ISD::VSELECT:     Res = PromoteIntRes_VSELECT(N); break;
77   case ISD::SELECT_CC:   Res = PromoteIntRes_SELECT_CC(N); break;
78   case ISD::STRICT_FSETCC:
79   case ISD::STRICT_FSETCCS:
80   case ISD::SETCC:       Res = PromoteIntRes_SETCC(N); break;
81   case ISD::SMIN:
82   case ISD::SMAX:        Res = PromoteIntRes_SExtIntBinOp(N); break;
83   case ISD::UMIN:
84   case ISD::UMAX:        Res = PromoteIntRes_ZExtIntBinOp(N); break;
85 
86   case ISD::SHL:         Res = PromoteIntRes_SHL(N); break;
87   case ISD::SIGN_EXTEND_INREG:
88                          Res = PromoteIntRes_SIGN_EXTEND_INREG(N); break;
89   case ISD::SRA:         Res = PromoteIntRes_SRA(N); break;
90   case ISD::SRL:         Res = PromoteIntRes_SRL(N); break;
91   case ISD::TRUNCATE:    Res = PromoteIntRes_TRUNCATE(N); break;
92   case ISD::UNDEF:       Res = PromoteIntRes_UNDEF(N); break;
93   case ISD::VAARG:       Res = PromoteIntRes_VAARG(N); break;
94   case ISD::VSCALE:      Res = PromoteIntRes_VSCALE(N); break;
95 
96   case ISD::EXTRACT_SUBVECTOR:
97                          Res = PromoteIntRes_EXTRACT_SUBVECTOR(N); break;
98   case ISD::VECTOR_SHUFFLE:
99                          Res = PromoteIntRes_VECTOR_SHUFFLE(N); break;
100   case ISD::INSERT_VECTOR_ELT:
101                          Res = PromoteIntRes_INSERT_VECTOR_ELT(N); break;
102   case ISD::BUILD_VECTOR:
103                          Res = PromoteIntRes_BUILD_VECTOR(N); break;
104   case ISD::SCALAR_TO_VECTOR:
105                          Res = PromoteIntRes_SCALAR_TO_VECTOR(N); break;
106   case ISD::SPLAT_VECTOR:
107                          Res = PromoteIntRes_SPLAT_VECTOR(N); break;
108   case ISD::CONCAT_VECTORS:
109                          Res = PromoteIntRes_CONCAT_VECTORS(N); break;
110 
111   case ISD::ANY_EXTEND_VECTOR_INREG:
112   case ISD::SIGN_EXTEND_VECTOR_INREG:
113   case ISD::ZERO_EXTEND_VECTOR_INREG:
114                          Res = PromoteIntRes_EXTEND_VECTOR_INREG(N); break;
115 
116   case ISD::SIGN_EXTEND:
117   case ISD::ZERO_EXTEND:
118   case ISD::ANY_EXTEND:  Res = PromoteIntRes_INT_EXTEND(N); break;
119 
120   case ISD::STRICT_FP_TO_SINT:
121   case ISD::STRICT_FP_TO_UINT:
122   case ISD::FP_TO_SINT:
123   case ISD::FP_TO_UINT:  Res = PromoteIntRes_FP_TO_XINT(N); break;
124 
125   case ISD::FP_TO_FP16:  Res = PromoteIntRes_FP_TO_FP16(N); break;
126 
127   case ISD::FLT_ROUNDS_: Res = PromoteIntRes_FLT_ROUNDS(N); break;
128 
129   case ISD::AND:
130   case ISD::OR:
131   case ISD::XOR:
132   case ISD::ADD:
133   case ISD::SUB:
134   case ISD::MUL:         Res = PromoteIntRes_SimpleIntBinOp(N); break;
135 
136   case ISD::SDIV:
137   case ISD::SREM:        Res = PromoteIntRes_SExtIntBinOp(N); break;
138 
139   case ISD::UDIV:
140   case ISD::UREM:        Res = PromoteIntRes_ZExtIntBinOp(N); break;
141 
142   case ISD::SADDO:
143   case ISD::SSUBO:       Res = PromoteIntRes_SADDSUBO(N, ResNo); break;
144   case ISD::UADDO:
145   case ISD::USUBO:       Res = PromoteIntRes_UADDSUBO(N, ResNo); break;
146   case ISD::SMULO:
147   case ISD::UMULO:       Res = PromoteIntRes_XMULO(N, ResNo); break;
148 
149   case ISD::ADDE:
150   case ISD::SUBE:
151   case ISD::ADDCARRY:
152   case ISD::SUBCARRY:    Res = PromoteIntRes_ADDSUBCARRY(N, ResNo); break;
153 
154   case ISD::SADDSAT:
155   case ISD::UADDSAT:
156   case ISD::SSUBSAT:
157   case ISD::USUBSAT:     Res = PromoteIntRes_ADDSUBSAT(N); break;
158 
159   case ISD::SMULFIX:
160   case ISD::SMULFIXSAT:
161   case ISD::UMULFIX:
162   case ISD::UMULFIXSAT:  Res = PromoteIntRes_MULFIX(N); break;
163 
164   case ISD::SDIVFIX:
165   case ISD::SDIVFIXSAT:
166   case ISD::UDIVFIX:
167   case ISD::UDIVFIXSAT:  Res = PromoteIntRes_DIVFIX(N); break;
168 
169   case ISD::ABS:         Res = PromoteIntRes_ABS(N); break;
170 
171   case ISD::ATOMIC_LOAD:
172     Res = PromoteIntRes_Atomic0(cast<AtomicSDNode>(N)); break;
173 
174   case ISD::ATOMIC_LOAD_ADD:
175   case ISD::ATOMIC_LOAD_SUB:
176   case ISD::ATOMIC_LOAD_AND:
177   case ISD::ATOMIC_LOAD_CLR:
178   case ISD::ATOMIC_LOAD_OR:
179   case ISD::ATOMIC_LOAD_XOR:
180   case ISD::ATOMIC_LOAD_NAND:
181   case ISD::ATOMIC_LOAD_MIN:
182   case ISD::ATOMIC_LOAD_MAX:
183   case ISD::ATOMIC_LOAD_UMIN:
184   case ISD::ATOMIC_LOAD_UMAX:
185   case ISD::ATOMIC_SWAP:
186     Res = PromoteIntRes_Atomic1(cast<AtomicSDNode>(N)); break;
187 
188   case ISD::ATOMIC_CMP_SWAP:
189   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
190     Res = PromoteIntRes_AtomicCmpSwap(cast<AtomicSDNode>(N), ResNo);
191     break;
192 
193   case ISD::VECREDUCE_ADD:
194   case ISD::VECREDUCE_MUL:
195   case ISD::VECREDUCE_AND:
196   case ISD::VECREDUCE_OR:
197   case ISD::VECREDUCE_XOR:
198   case ISD::VECREDUCE_SMAX:
199   case ISD::VECREDUCE_SMIN:
200   case ISD::VECREDUCE_UMAX:
201   case ISD::VECREDUCE_UMIN:
202     Res = PromoteIntRes_VECREDUCE(N);
203     break;
204 
205   case ISD::FREEZE:
206     Res = PromoteIntRes_FREEZE(N);
207     break;
208   }
209 
210   // If the result is null then the sub-method took care of registering it.
211   if (Res.getNode())
212     SetPromotedInteger(SDValue(N, ResNo), Res);
213 }
214 
215 SDValue DAGTypeLegalizer::PromoteIntRes_MERGE_VALUES(SDNode *N,
216                                                      unsigned ResNo) {
217   SDValue Op = DisintegrateMERGE_VALUES(N, ResNo);
218   return GetPromotedInteger(Op);
219 }
220 
221 SDValue DAGTypeLegalizer::PromoteIntRes_AssertSext(SDNode *N) {
222   // Sign-extend the new bits, and continue the assertion.
223   SDValue Op = SExtPromotedInteger(N->getOperand(0));
224   return DAG.getNode(ISD::AssertSext, SDLoc(N),
225                      Op.getValueType(), Op, N->getOperand(1));
226 }
227 
228 SDValue DAGTypeLegalizer::PromoteIntRes_AssertZext(SDNode *N) {
229   // Zero the new bits, and continue the assertion.
230   SDValue Op = ZExtPromotedInteger(N->getOperand(0));
231   return DAG.getNode(ISD::AssertZext, SDLoc(N),
232                      Op.getValueType(), Op, N->getOperand(1));
233 }
234 
235 SDValue DAGTypeLegalizer::PromoteIntRes_Atomic0(AtomicSDNode *N) {
236   EVT ResVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
237   SDValue Res = DAG.getAtomic(N->getOpcode(), SDLoc(N),
238                               N->getMemoryVT(), ResVT,
239                               N->getChain(), N->getBasePtr(),
240                               N->getMemOperand());
241   // Legalize the chain result - switch anything that used the old chain to
242   // use the new one.
243   ReplaceValueWith(SDValue(N, 1), Res.getValue(1));
244   return Res;
245 }
246 
247 SDValue DAGTypeLegalizer::PromoteIntRes_Atomic1(AtomicSDNode *N) {
248   SDValue Op2 = GetPromotedInteger(N->getOperand(2));
249   SDValue Res = DAG.getAtomic(N->getOpcode(), SDLoc(N),
250                               N->getMemoryVT(),
251                               N->getChain(), N->getBasePtr(),
252                               Op2, N->getMemOperand());
253   // Legalize the chain result - switch anything that used the old chain to
254   // use the new one.
255   ReplaceValueWith(SDValue(N, 1), Res.getValue(1));
256   return Res;
257 }
258 
259 SDValue DAGTypeLegalizer::PromoteIntRes_AtomicCmpSwap(AtomicSDNode *N,
260                                                       unsigned ResNo) {
261   if (ResNo == 1) {
262     assert(N->getOpcode() == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
263     EVT SVT = getSetCCResultType(N->getOperand(2).getValueType());
264     EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(1));
265 
266     // Only use the result of getSetCCResultType if it is legal,
267     // otherwise just use the promoted result type (NVT).
268     if (!TLI.isTypeLegal(SVT))
269       SVT = NVT;
270 
271     SDVTList VTs = DAG.getVTList(N->getValueType(0), SVT, MVT::Other);
272     SDValue Res = DAG.getAtomicCmpSwap(
273         ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, SDLoc(N), N->getMemoryVT(), VTs,
274         N->getChain(), N->getBasePtr(), N->getOperand(2), N->getOperand(3),
275         N->getMemOperand());
276     ReplaceValueWith(SDValue(N, 0), Res.getValue(0));
277     ReplaceValueWith(SDValue(N, 2), Res.getValue(2));
278     return Res.getValue(1);
279   }
280 
281   // Op2 is used for the comparison and thus must be extended according to the
282   // target's atomic operations. Op3 is merely stored and so can be left alone.
283   SDValue Op2 = N->getOperand(2);
284   SDValue Op3 = GetPromotedInteger(N->getOperand(3));
285   switch (TLI.getExtendForAtomicCmpSwapArg()) {
286   case ISD::SIGN_EXTEND:
287     Op2 = SExtPromotedInteger(Op2);
288     break;
289   case ISD::ZERO_EXTEND:
290     Op2 = ZExtPromotedInteger(Op2);
291     break;
292   case ISD::ANY_EXTEND:
293     Op2 = GetPromotedInteger(Op2);
294     break;
295   default:
296     llvm_unreachable("Invalid atomic op extension");
297   }
298 
299   SDVTList VTs =
300       DAG.getVTList(Op2.getValueType(), N->getValueType(1), MVT::Other);
301   SDValue Res = DAG.getAtomicCmpSwap(
302       N->getOpcode(), SDLoc(N), N->getMemoryVT(), VTs, N->getChain(),
303       N->getBasePtr(), Op2, Op3, N->getMemOperand());
304   // Update the use to N with the newly created Res.
305   for (unsigned i = 1, NumResults = N->getNumValues(); i < NumResults; ++i)
306     ReplaceValueWith(SDValue(N, i), Res.getValue(i));
307   return Res;
308 }
309 
310 SDValue DAGTypeLegalizer::PromoteIntRes_BITCAST(SDNode *N) {
311   SDValue InOp = N->getOperand(0);
312   EVT InVT = InOp.getValueType();
313   EVT NInVT = TLI.getTypeToTransformTo(*DAG.getContext(), InVT);
314   EVT OutVT = N->getValueType(0);
315   EVT NOutVT = TLI.getTypeToTransformTo(*DAG.getContext(), OutVT);
316   SDLoc dl(N);
317 
318   switch (getTypeAction(InVT)) {
319   case TargetLowering::TypeLegal:
320     break;
321   case TargetLowering::TypePromoteInteger:
322     if (NOutVT.bitsEq(NInVT) && !NOutVT.isVector() && !NInVT.isVector())
323       // The input promotes to the same size.  Convert the promoted value.
324       return DAG.getNode(ISD::BITCAST, dl, NOutVT, GetPromotedInteger(InOp));
325     break;
326   case TargetLowering::TypeSoftenFloat:
327     // Promote the integer operand by hand.
328     return DAG.getNode(ISD::ANY_EXTEND, dl, NOutVT, GetSoftenedFloat(InOp));
329   case TargetLowering::TypeSoftPromoteHalf:
330     // Promote the integer operand by hand.
331     return DAG.getNode(ISD::ANY_EXTEND, dl, NOutVT, GetSoftPromotedHalf(InOp));
332   case TargetLowering::TypePromoteFloat: {
333     // Convert the promoted float by hand.
334     if (!NOutVT.isVector())
335       return DAG.getNode(ISD::FP_TO_FP16, dl, NOutVT, GetPromotedFloat(InOp));
336     break;
337   }
338   case TargetLowering::TypeExpandInteger:
339   case TargetLowering::TypeExpandFloat:
340     break;
341   case TargetLowering::TypeScalarizeVector:
342     // Convert the element to an integer and promote it by hand.
343     if (!NOutVT.isVector())
344       return DAG.getNode(ISD::ANY_EXTEND, dl, NOutVT,
345                          BitConvertToInteger(GetScalarizedVector(InOp)));
346     break;
347   case TargetLowering::TypeScalarizeScalableVector:
348     report_fatal_error("Scalarization of scalable vectors is not supported.");
349   case TargetLowering::TypeSplitVector: {
350     if (!NOutVT.isVector()) {
351       // For example, i32 = BITCAST v2i16 on alpha.  Convert the split
352       // pieces of the input into integers and reassemble in the final type.
353       SDValue Lo, Hi;
354       GetSplitVector(N->getOperand(0), Lo, Hi);
355       Lo = BitConvertToInteger(Lo);
356       Hi = BitConvertToInteger(Hi);
357 
358       if (DAG.getDataLayout().isBigEndian())
359         std::swap(Lo, Hi);
360 
361       InOp = DAG.getNode(ISD::ANY_EXTEND, dl,
362                          EVT::getIntegerVT(*DAG.getContext(),
363                                            NOutVT.getSizeInBits()),
364                          JoinIntegers(Lo, Hi));
365       return DAG.getNode(ISD::BITCAST, dl, NOutVT, InOp);
366     }
367     break;
368   }
369   case TargetLowering::TypeWidenVector:
370     // The input is widened to the same size. Convert to the widened value.
371     // Make sure that the outgoing value is not a vector, because this would
372     // make us bitcast between two vectors which are legalized in different ways.
373     if (NOutVT.bitsEq(NInVT) && !NOutVT.isVector()) {
374       SDValue Res =
375         DAG.getNode(ISD::BITCAST, dl, NOutVT, GetWidenedVector(InOp));
376 
377       // For big endian targets we need to shift the casted value or the
378       // interesting bits will end up at the wrong place.
379       if (DAG.getDataLayout().isBigEndian()) {
380         unsigned ShiftAmt = NInVT.getSizeInBits() - InVT.getSizeInBits();
381         EVT ShiftAmtTy = TLI.getShiftAmountTy(NOutVT, DAG.getDataLayout());
382         assert(ShiftAmt < NOutVT.getSizeInBits() && "Too large shift amount!");
383         Res = DAG.getNode(ISD::SRL, dl, NOutVT, Res,
384                           DAG.getConstant(ShiftAmt, dl, ShiftAmtTy));
385       }
386       return Res;
387     }
388     // If the output type is also a vector and widening it to the same size
389     // as the widened input type would be a legal type, we can widen the bitcast
390     // and handle the promotion after.
391     if (NOutVT.isVector()) {
392       unsigned WidenInSize = NInVT.getSizeInBits();
393       unsigned OutSize = OutVT.getSizeInBits();
394       if (WidenInSize % OutSize == 0) {
395         unsigned Scale = WidenInSize / OutSize;
396         EVT WideOutVT = EVT::getVectorVT(*DAG.getContext(),
397                                          OutVT.getVectorElementType(),
398                                          OutVT.getVectorNumElements() * Scale);
399         if (isTypeLegal(WideOutVT)) {
400           InOp = DAG.getBitcast(WideOutVT, GetWidenedVector(InOp));
401           InOp = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, OutVT, InOp,
402                              DAG.getVectorIdxConstant(0, dl));
403           return DAG.getNode(ISD::ANY_EXTEND, dl, NOutVT, InOp);
404         }
405       }
406     }
407   }
408 
409   return DAG.getNode(ISD::ANY_EXTEND, dl, NOutVT,
410                      CreateStackStoreLoad(InOp, OutVT));
411 }
412 
413 // Helper for BSWAP/BITREVERSE promotion to ensure we can fit any shift amount
414 // in the VT returned by getShiftAmountTy and to return a safe VT if we can't.
415 static EVT getShiftAmountTyForConstant(EVT VT, const TargetLowering &TLI,
416                                        SelectionDAG &DAG) {
417   EVT ShiftVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout());
418   // If any possible shift value won't fit in the prefered type, just use
419   // something safe. It will be legalized when the shift is expanded.
420   if (!ShiftVT.isVector() &&
421       ShiftVT.getSizeInBits() < Log2_32_Ceil(VT.getSizeInBits()))
422     ShiftVT = MVT::i32;
423   return ShiftVT;
424 }
425 
426 SDValue DAGTypeLegalizer::PromoteIntRes_FREEZE(SDNode *N) {
427   SDValue V = GetPromotedInteger(N->getOperand(0));
428   return DAG.getNode(ISD::FREEZE, SDLoc(N),
429                      V.getValueType(), V);
430 }
431 
432 SDValue DAGTypeLegalizer::PromoteIntRes_BSWAP(SDNode *N) {
433   SDValue Op = GetPromotedInteger(N->getOperand(0));
434   EVT OVT = N->getValueType(0);
435   EVT NVT = Op.getValueType();
436   SDLoc dl(N);
437 
438   unsigned DiffBits = NVT.getScalarSizeInBits() - OVT.getScalarSizeInBits();
439   EVT ShiftVT = getShiftAmountTyForConstant(NVT, TLI, DAG);
440   return DAG.getNode(ISD::SRL, dl, NVT, DAG.getNode(ISD::BSWAP, dl, NVT, Op),
441                      DAG.getConstant(DiffBits, dl, ShiftVT));
442 }
443 
444 SDValue DAGTypeLegalizer::PromoteIntRes_BITREVERSE(SDNode *N) {
445   SDValue Op = GetPromotedInteger(N->getOperand(0));
446   EVT OVT = N->getValueType(0);
447   EVT NVT = Op.getValueType();
448   SDLoc dl(N);
449 
450   unsigned DiffBits = NVT.getScalarSizeInBits() - OVT.getScalarSizeInBits();
451   EVT ShiftVT = getShiftAmountTyForConstant(NVT, TLI, DAG);
452   return DAG.getNode(ISD::SRL, dl, NVT,
453                      DAG.getNode(ISD::BITREVERSE, dl, NVT, Op),
454                      DAG.getConstant(DiffBits, dl, ShiftVT));
455 }
456 
457 SDValue DAGTypeLegalizer::PromoteIntRes_BUILD_PAIR(SDNode *N) {
458   // The pair element type may be legal, or may not promote to the same type as
459   // the result, for example i14 = BUILD_PAIR (i7, i7).  Handle all cases.
460   return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N),
461                      TLI.getTypeToTransformTo(*DAG.getContext(),
462                      N->getValueType(0)), JoinIntegers(N->getOperand(0),
463                      N->getOperand(1)));
464 }
465 
466 SDValue DAGTypeLegalizer::PromoteIntRes_Constant(SDNode *N) {
467   EVT VT = N->getValueType(0);
468   // FIXME there is no actual debug info here
469   SDLoc dl(N);
470   // Zero extend things like i1, sign extend everything else.  It shouldn't
471   // matter in theory which one we pick, but this tends to give better code?
472   unsigned Opc = VT.isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
473   SDValue Result = DAG.getNode(Opc, dl,
474                                TLI.getTypeToTransformTo(*DAG.getContext(), VT),
475                                SDValue(N, 0));
476   assert(isa<ConstantSDNode>(Result) && "Didn't constant fold ext?");
477   return Result;
478 }
479 
480 SDValue DAGTypeLegalizer::PromoteIntRes_CTLZ(SDNode *N) {
481   // Zero extend to the promoted type and do the count there.
482   SDValue Op = ZExtPromotedInteger(N->getOperand(0));
483   SDLoc dl(N);
484   EVT OVT = N->getValueType(0);
485   EVT NVT = Op.getValueType();
486   Op = DAG.getNode(N->getOpcode(), dl, NVT, Op);
487   // Subtract off the extra leading bits in the bigger type.
488   return DAG.getNode(
489       ISD::SUB, dl, NVT, Op,
490       DAG.getConstant(NVT.getScalarSizeInBits() - OVT.getScalarSizeInBits(), dl,
491                       NVT));
492 }
493 
494 SDValue DAGTypeLegalizer::PromoteIntRes_CTPOP(SDNode *N) {
495   // Zero extend to the promoted type and do the count there.
496   SDValue Op = ZExtPromotedInteger(N->getOperand(0));
497   return DAG.getNode(ISD::CTPOP, SDLoc(N), Op.getValueType(), Op);
498 }
499 
500 SDValue DAGTypeLegalizer::PromoteIntRes_CTTZ(SDNode *N) {
501   SDValue Op = GetPromotedInteger(N->getOperand(0));
502   EVT OVT = N->getValueType(0);
503   EVT NVT = Op.getValueType();
504   SDLoc dl(N);
505   if (N->getOpcode() == ISD::CTTZ) {
506     // The count is the same in the promoted type except if the original
507     // value was zero.  This can be handled by setting the bit just off
508     // the top of the original type.
509     auto TopBit = APInt::getOneBitSet(NVT.getScalarSizeInBits(),
510                                       OVT.getScalarSizeInBits());
511     Op = DAG.getNode(ISD::OR, dl, NVT, Op, DAG.getConstant(TopBit, dl, NVT));
512   }
513   return DAG.getNode(N->getOpcode(), dl, NVT, Op);
514 }
515 
516 SDValue DAGTypeLegalizer::PromoteIntRes_EXTRACT_VECTOR_ELT(SDNode *N) {
517   SDLoc dl(N);
518   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
519 
520   SDValue Op0 = N->getOperand(0);
521   SDValue Op1 = N->getOperand(1);
522 
523   // If the input also needs to be promoted, do that first so we can get a
524   // get a good idea for the output type.
525   if (TLI.getTypeAction(*DAG.getContext(), Op0.getValueType())
526       == TargetLowering::TypePromoteInteger) {
527     SDValue In = GetPromotedInteger(Op0);
528 
529     // If the new type is larger than NVT, use it. We probably won't need to
530     // promote it again.
531     EVT SVT = In.getValueType().getScalarType();
532     if (SVT.bitsGE(NVT)) {
533       SDValue Ext = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, In, Op1);
534       return DAG.getAnyExtOrTrunc(Ext, dl, NVT);
535     }
536   }
537 
538   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, NVT, Op0, Op1);
539 }
540 
541 SDValue DAGTypeLegalizer::PromoteIntRes_FP_TO_XINT(SDNode *N) {
542   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
543   unsigned NewOpc = N->getOpcode();
544   SDLoc dl(N);
545 
546   // If we're promoting a UINT to a larger size and the larger FP_TO_UINT is
547   // not Legal, check to see if we can use FP_TO_SINT instead.  (If both UINT
548   // and SINT conversions are Custom, there is no way to tell which is
549   // preferable. We choose SINT because that's the right thing on PPC.)
550   if (N->getOpcode() == ISD::FP_TO_UINT &&
551       !TLI.isOperationLegal(ISD::FP_TO_UINT, NVT) &&
552       TLI.isOperationLegalOrCustom(ISD::FP_TO_SINT, NVT))
553     NewOpc = ISD::FP_TO_SINT;
554 
555   if (N->getOpcode() == ISD::STRICT_FP_TO_UINT &&
556       !TLI.isOperationLegal(ISD::STRICT_FP_TO_UINT, NVT) &&
557       TLI.isOperationLegalOrCustom(ISD::STRICT_FP_TO_SINT, NVT))
558     NewOpc = ISD::STRICT_FP_TO_SINT;
559 
560   SDValue Res;
561   if (N->isStrictFPOpcode()) {
562     Res = DAG.getNode(NewOpc, dl, { NVT, MVT::Other },
563                       { N->getOperand(0), N->getOperand(1) });
564     // Legalize the chain result - switch anything that used the old chain to
565     // use the new one.
566     ReplaceValueWith(SDValue(N, 1), Res.getValue(1));
567   } else
568     Res = DAG.getNode(NewOpc, dl, NVT, N->getOperand(0));
569 
570   // Assert that the converted value fits in the original type.  If it doesn't
571   // (eg: because the value being converted is too big), then the result of the
572   // original operation was undefined anyway, so the assert is still correct.
573   //
574   // NOTE: fp-to-uint to fp-to-sint promotion guarantees zero extend. For example:
575   //   before legalization: fp-to-uint16, 65534. -> 0xfffe
576   //   after legalization: fp-to-sint32, 65534. -> 0x0000fffe
577   return DAG.getNode((N->getOpcode() == ISD::FP_TO_UINT ||
578                       N->getOpcode() == ISD::STRICT_FP_TO_UINT) ?
579                      ISD::AssertZext : ISD::AssertSext, dl, NVT, Res,
580                      DAG.getValueType(N->getValueType(0).getScalarType()));
581 }
582 
583 SDValue DAGTypeLegalizer::PromoteIntRes_FP_TO_FP16(SDNode *N) {
584   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
585   SDLoc dl(N);
586 
587   return DAG.getNode(N->getOpcode(), dl, NVT, N->getOperand(0));
588 }
589 
590 SDValue DAGTypeLegalizer::PromoteIntRes_FLT_ROUNDS(SDNode *N) {
591   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
592   SDLoc dl(N);
593 
594   SDValue Res =
595       DAG.getNode(N->getOpcode(), dl, {NVT, MVT::Other}, N->getOperand(0));
596 
597   // Legalize the chain result - switch anything that used the old chain to
598   // use the new one.
599   ReplaceValueWith(SDValue(N, 1), Res.getValue(1));
600   return Res;
601 }
602 
603 SDValue DAGTypeLegalizer::PromoteIntRes_INT_EXTEND(SDNode *N) {
604   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
605   SDLoc dl(N);
606 
607   if (getTypeAction(N->getOperand(0).getValueType())
608       == TargetLowering::TypePromoteInteger) {
609     SDValue Res = GetPromotedInteger(N->getOperand(0));
610     assert(Res.getValueType().bitsLE(NVT) && "Extension doesn't make sense!");
611 
612     // If the result and operand types are the same after promotion, simplify
613     // to an in-register extension.
614     if (NVT == Res.getValueType()) {
615       // The high bits are not guaranteed to be anything.  Insert an extend.
616       if (N->getOpcode() == ISD::SIGN_EXTEND)
617         return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NVT, Res,
618                            DAG.getValueType(N->getOperand(0).getValueType()));
619       if (N->getOpcode() == ISD::ZERO_EXTEND)
620         return DAG.getZeroExtendInReg(Res, dl, N->getOperand(0).getValueType());
621       assert(N->getOpcode() == ISD::ANY_EXTEND && "Unknown integer extension!");
622       return Res;
623     }
624   }
625 
626   // Otherwise, just extend the original operand all the way to the larger type.
627   return DAG.getNode(N->getOpcode(), dl, NVT, N->getOperand(0));
628 }
629 
630 SDValue DAGTypeLegalizer::PromoteIntRes_LOAD(LoadSDNode *N) {
631   assert(ISD::isUNINDEXEDLoad(N) && "Indexed load during type legalization!");
632   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
633   ISD::LoadExtType ExtType =
634     ISD::isNON_EXTLoad(N) ? ISD::EXTLOAD : N->getExtensionType();
635   SDLoc dl(N);
636   SDValue Res = DAG.getExtLoad(ExtType, dl, NVT, N->getChain(), N->getBasePtr(),
637                                N->getMemoryVT(), N->getMemOperand());
638 
639   // Legalize the chain result - switch anything that used the old chain to
640   // use the new one.
641   ReplaceValueWith(SDValue(N, 1), Res.getValue(1));
642   return Res;
643 }
644 
645 SDValue DAGTypeLegalizer::PromoteIntRes_MLOAD(MaskedLoadSDNode *N) {
646   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
647   SDValue ExtPassThru = GetPromotedInteger(N->getPassThru());
648 
649   SDLoc dl(N);
650   SDValue Res = DAG.getMaskedLoad(NVT, dl, N->getChain(), N->getBasePtr(),
651                                   N->getOffset(), N->getMask(), ExtPassThru,
652                                   N->getMemoryVT(), N->getMemOperand(),
653                                   N->getAddressingMode(), ISD::EXTLOAD);
654   // Legalize the chain result - switch anything that used the old chain to
655   // use the new one.
656   ReplaceValueWith(SDValue(N, 1), Res.getValue(1));
657   return Res;
658 }
659 
660 SDValue DAGTypeLegalizer::PromoteIntRes_MGATHER(MaskedGatherSDNode *N) {
661   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
662   SDValue ExtPassThru = GetPromotedInteger(N->getPassThru());
663   assert(NVT == ExtPassThru.getValueType() &&
664       "Gather result type and the passThru argument type should be the same");
665 
666   SDLoc dl(N);
667   SDValue Ops[] = {N->getChain(), ExtPassThru, N->getMask(), N->getBasePtr(),
668                    N->getIndex(), N->getScale() };
669   SDValue Res = DAG.getMaskedGather(DAG.getVTList(NVT, MVT::Other),
670                                     N->getMemoryVT(), dl, Ops,
671                                     N->getMemOperand(), N->getIndexType());
672   // Legalize the chain result - switch anything that used the old chain to
673   // use the new one.
674   ReplaceValueWith(SDValue(N, 1), Res.getValue(1));
675   return Res;
676 }
677 
678 /// Promote the overflow flag of an overflowing arithmetic node.
679 SDValue DAGTypeLegalizer::PromoteIntRes_Overflow(SDNode *N) {
680   // Change the return type of the boolean result while obeying
681   // getSetCCResultType.
682   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(1));
683   EVT VT = N->getValueType(0);
684   EVT SVT = getSetCCResultType(VT);
685   SDValue Ops[3] = { N->getOperand(0), N->getOperand(1) };
686   unsigned NumOps = N->getNumOperands();
687   assert(NumOps <= 3 && "Too many operands");
688   if (NumOps == 3)
689     Ops[2] = N->getOperand(2);
690 
691   SDLoc dl(N);
692   SDValue Res = DAG.getNode(N->getOpcode(), dl, DAG.getVTList(VT, SVT),
693                             makeArrayRef(Ops, NumOps));
694 
695   // Modified the sum result - switch anything that used the old sum to use
696   // the new one.
697   ReplaceValueWith(SDValue(N, 0), Res);
698 
699   // Convert to the expected type.
700   return DAG.getBoolExtOrTrunc(Res.getValue(1), dl, NVT, VT);
701 }
702 
703 SDValue DAGTypeLegalizer::PromoteIntRes_ADDSUBSAT(SDNode *N) {
704   // If the promoted type is legal, we can convert this to:
705   //   1. ANY_EXTEND iN to iM
706   //   2. SHL by M-N
707   //   3. [US][ADD|SUB]SAT
708   //   4. L/ASHR by M-N
709   // Else it is more efficient to convert this to a min and a max
710   // operation in the higher precision arithmetic.
711   SDLoc dl(N);
712   SDValue Op1 = N->getOperand(0);
713   SDValue Op2 = N->getOperand(1);
714   unsigned OldBits = Op1.getScalarValueSizeInBits();
715 
716   unsigned Opcode = N->getOpcode();
717 
718   SDValue Op1Promoted, Op2Promoted;
719   if (Opcode == ISD::UADDSAT || Opcode == ISD::USUBSAT) {
720     Op1Promoted = ZExtPromotedInteger(Op1);
721     Op2Promoted = ZExtPromotedInteger(Op2);
722   } else {
723     Op1Promoted = SExtPromotedInteger(Op1);
724     Op2Promoted = SExtPromotedInteger(Op2);
725   }
726   EVT PromotedType = Op1Promoted.getValueType();
727   unsigned NewBits = PromotedType.getScalarSizeInBits();
728 
729   if (TLI.isOperationLegalOrCustom(Opcode, PromotedType)) {
730     unsigned ShiftOp;
731     switch (Opcode) {
732     case ISD::SADDSAT:
733     case ISD::SSUBSAT:
734       ShiftOp = ISD::SRA;
735       break;
736     case ISD::UADDSAT:
737     case ISD::USUBSAT:
738       ShiftOp = ISD::SRL;
739       break;
740     default:
741       llvm_unreachable("Expected opcode to be signed or unsigned saturation "
742                        "addition or subtraction");
743     }
744 
745     unsigned SHLAmount = NewBits - OldBits;
746     EVT SHVT = TLI.getShiftAmountTy(PromotedType, DAG.getDataLayout());
747     SDValue ShiftAmount = DAG.getConstant(SHLAmount, dl, SHVT);
748     Op1Promoted =
749         DAG.getNode(ISD::SHL, dl, PromotedType, Op1Promoted, ShiftAmount);
750     Op2Promoted =
751         DAG.getNode(ISD::SHL, dl, PromotedType, Op2Promoted, ShiftAmount);
752 
753     SDValue Result =
754         DAG.getNode(Opcode, dl, PromotedType, Op1Promoted, Op2Promoted);
755     return DAG.getNode(ShiftOp, dl, PromotedType, Result, ShiftAmount);
756   } else {
757     if (Opcode == ISD::USUBSAT) {
758       SDValue Max =
759           DAG.getNode(ISD::UMAX, dl, PromotedType, Op1Promoted, Op2Promoted);
760       return DAG.getNode(ISD::SUB, dl, PromotedType, Max, Op2Promoted);
761     }
762 
763     if (Opcode == ISD::UADDSAT) {
764       APInt MaxVal = APInt::getAllOnesValue(OldBits).zext(NewBits);
765       SDValue SatMax = DAG.getConstant(MaxVal, dl, PromotedType);
766       SDValue Add =
767           DAG.getNode(ISD::ADD, dl, PromotedType, Op1Promoted, Op2Promoted);
768       return DAG.getNode(ISD::UMIN, dl, PromotedType, Add, SatMax);
769     }
770 
771     unsigned AddOp = Opcode == ISD::SADDSAT ? ISD::ADD : ISD::SUB;
772     APInt MinVal = APInt::getSignedMinValue(OldBits).sext(NewBits);
773     APInt MaxVal = APInt::getSignedMaxValue(OldBits).sext(NewBits);
774     SDValue SatMin = DAG.getConstant(MinVal, dl, PromotedType);
775     SDValue SatMax = DAG.getConstant(MaxVal, dl, PromotedType);
776     SDValue Result =
777         DAG.getNode(AddOp, dl, PromotedType, Op1Promoted, Op2Promoted);
778     Result = DAG.getNode(ISD::SMIN, dl, PromotedType, Result, SatMax);
779     Result = DAG.getNode(ISD::SMAX, dl, PromotedType, Result, SatMin);
780     return Result;
781   }
782 }
783 
784 SDValue DAGTypeLegalizer::PromoteIntRes_MULFIX(SDNode *N) {
785   // Can just promote the operands then continue with operation.
786   SDLoc dl(N);
787   SDValue Op1Promoted, Op2Promoted;
788   bool Signed =
789       N->getOpcode() == ISD::SMULFIX || N->getOpcode() == ISD::SMULFIXSAT;
790   bool Saturating =
791       N->getOpcode() == ISD::SMULFIXSAT || N->getOpcode() == ISD::UMULFIXSAT;
792   if (Signed) {
793     Op1Promoted = SExtPromotedInteger(N->getOperand(0));
794     Op2Promoted = SExtPromotedInteger(N->getOperand(1));
795   } else {
796     Op1Promoted = ZExtPromotedInteger(N->getOperand(0));
797     Op2Promoted = ZExtPromotedInteger(N->getOperand(1));
798   }
799   EVT OldType = N->getOperand(0).getValueType();
800   EVT PromotedType = Op1Promoted.getValueType();
801   unsigned DiffSize =
802       PromotedType.getScalarSizeInBits() - OldType.getScalarSizeInBits();
803 
804   if (Saturating) {
805     // Promoting the operand and result values changes the saturation width,
806     // which is extends the values that we clamp to on saturation. This could be
807     // resolved by shifting one of the operands the same amount, which would
808     // also shift the result we compare against, then shifting back.
809     EVT ShiftTy = TLI.getShiftAmountTy(PromotedType, DAG.getDataLayout());
810     Op1Promoted = DAG.getNode(ISD::SHL, dl, PromotedType, Op1Promoted,
811                               DAG.getConstant(DiffSize, dl, ShiftTy));
812     SDValue Result = DAG.getNode(N->getOpcode(), dl, PromotedType, Op1Promoted,
813                                  Op2Promoted, N->getOperand(2));
814     unsigned ShiftOp = Signed ? ISD::SRA : ISD::SRL;
815     return DAG.getNode(ShiftOp, dl, PromotedType, Result,
816                        DAG.getConstant(DiffSize, dl, ShiftTy));
817   }
818   return DAG.getNode(N->getOpcode(), dl, PromotedType, Op1Promoted, Op2Promoted,
819                      N->getOperand(2));
820 }
821 
822 static SDValue SaturateWidenedDIVFIX(SDValue V, SDLoc &dl,
823                                      unsigned SatW, bool Signed,
824                                      const TargetLowering &TLI,
825                                      SelectionDAG &DAG) {
826   EVT VT = V.getValueType();
827   unsigned VTW = VT.getScalarSizeInBits();
828 
829   if (!Signed) {
830     // Saturate to the unsigned maximum by getting the minimum of V and the
831     // maximum.
832     return DAG.getNode(ISD::UMIN, dl, VT, V,
833                        DAG.getConstant(APInt::getLowBitsSet(VTW, SatW),
834                                        dl, VT));
835   }
836 
837   // Saturate to the signed maximum (the low SatW - 1 bits) by taking the
838   // signed minimum of it and V.
839   V = DAG.getNode(ISD::SMIN, dl, VT, V,
840                   DAG.getConstant(APInt::getLowBitsSet(VTW, SatW - 1),
841                                   dl, VT));
842   // Saturate to the signed minimum (the high SatW + 1 bits) by taking the
843   // signed maximum of it and V.
844   V = DAG.getNode(ISD::SMAX, dl, VT, V,
845                   DAG.getConstant(APInt::getHighBitsSet(VTW, VTW - SatW + 1),
846                                   dl, VT));
847   return V;
848 }
849 
850 static SDValue earlyExpandDIVFIX(SDNode *N, SDValue LHS, SDValue RHS,
851                                  unsigned Scale, const TargetLowering &TLI,
852                                  SelectionDAG &DAG, unsigned SatW = 0) {
853   EVT VT = LHS.getValueType();
854   unsigned VTSize = VT.getScalarSizeInBits();
855   bool Signed = N->getOpcode() == ISD::SDIVFIX ||
856                 N->getOpcode() == ISD::SDIVFIXSAT;
857   bool Saturating = N->getOpcode() == ISD::SDIVFIXSAT ||
858                     N->getOpcode() == ISD::UDIVFIXSAT;
859 
860   SDLoc dl(N);
861   // Widen the types by a factor of two. This is guaranteed to expand, since it
862   // will always have enough high bits in the LHS to shift into.
863   EVT WideVT = EVT::getIntegerVT(*DAG.getContext(), VTSize * 2);
864   if (VT.isVector())
865     WideVT = EVT::getVectorVT(*DAG.getContext(), WideVT,
866                               VT.getVectorElementCount());
867   if (Signed) {
868     LHS = DAG.getSExtOrTrunc(LHS, dl, WideVT);
869     RHS = DAG.getSExtOrTrunc(RHS, dl, WideVT);
870   } else {
871     LHS = DAG.getZExtOrTrunc(LHS, dl, WideVT);
872     RHS = DAG.getZExtOrTrunc(RHS, dl, WideVT);
873   }
874 
875   SDValue Res = TLI.expandFixedPointDiv(N->getOpcode(), dl, LHS, RHS, Scale,
876                                         DAG);
877   assert(Res && "Expanding DIVFIX with wide type failed?");
878   if (Saturating) {
879     // If the caller has told us to saturate at something less, use that width
880     // instead of the type before doubling. However, it cannot be more than
881     // what we just widened!
882     assert(SatW <= VTSize &&
883            "Tried to saturate to more than the original type?");
884     Res = SaturateWidenedDIVFIX(Res, dl, SatW == 0 ? VTSize : SatW, Signed,
885                                 TLI, DAG);
886   }
887   return DAG.getZExtOrTrunc(Res, dl, VT);
888 }
889 
890 SDValue DAGTypeLegalizer::PromoteIntRes_DIVFIX(SDNode *N) {
891   SDLoc dl(N);
892   SDValue Op1Promoted, Op2Promoted;
893   bool Signed = N->getOpcode() == ISD::SDIVFIX ||
894                 N->getOpcode() == ISD::SDIVFIXSAT;
895   bool Saturating = N->getOpcode() == ISD::SDIVFIXSAT ||
896                     N->getOpcode() == ISD::UDIVFIXSAT;
897   if (Signed) {
898     Op1Promoted = SExtPromotedInteger(N->getOperand(0));
899     Op2Promoted = SExtPromotedInteger(N->getOperand(1));
900   } else {
901     Op1Promoted = ZExtPromotedInteger(N->getOperand(0));
902     Op2Promoted = ZExtPromotedInteger(N->getOperand(1));
903   }
904   EVT PromotedType = Op1Promoted.getValueType();
905   unsigned Scale = N->getConstantOperandVal(2);
906 
907   // If the type is already legal and the operation is legal in that type, we
908   // should not early expand.
909   if (TLI.isTypeLegal(PromotedType)) {
910     TargetLowering::LegalizeAction Action =
911         TLI.getFixedPointOperationAction(N->getOpcode(), PromotedType, Scale);
912     if (Action == TargetLowering::Legal || Action == TargetLowering::Custom) {
913       EVT ShiftTy = TLI.getShiftAmountTy(PromotedType, DAG.getDataLayout());
914       unsigned Diff = PromotedType.getScalarSizeInBits() -
915                       N->getValueType(0).getScalarSizeInBits();
916       if (Saturating)
917         Op1Promoted = DAG.getNode(ISD::SHL, dl, PromotedType, Op1Promoted,
918                                   DAG.getConstant(Diff, dl, ShiftTy));
919       SDValue Res = DAG.getNode(N->getOpcode(), dl, PromotedType, Op1Promoted,
920                                 Op2Promoted, N->getOperand(2));
921       if (Saturating)
922         Res = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, dl, PromotedType, Res,
923                           DAG.getConstant(Diff, dl, ShiftTy));
924       return Res;
925     }
926   }
927 
928   // See if we can perform the division in this type without expanding.
929   if (SDValue Res = TLI.expandFixedPointDiv(N->getOpcode(), dl, Op1Promoted,
930                                         Op2Promoted, Scale, DAG)) {
931     if (Saturating)
932       Res = SaturateWidenedDIVFIX(Res, dl,
933                                   N->getValueType(0).getScalarSizeInBits(),
934                                   Signed, TLI, DAG);
935     return Res;
936   }
937   // If we cannot, expand it to twice the type width. If we are saturating, give
938   // it the original width as a saturating width so we don't need to emit
939   // two saturations.
940   return earlyExpandDIVFIX(N, Op1Promoted, Op2Promoted, Scale, TLI, DAG,
941                             N->getValueType(0).getScalarSizeInBits());
942 }
943 
944 SDValue DAGTypeLegalizer::PromoteIntRes_SADDSUBO(SDNode *N, unsigned ResNo) {
945   if (ResNo == 1)
946     return PromoteIntRes_Overflow(N);
947 
948   // The operation overflowed iff the result in the larger type is not the
949   // sign extension of its truncation to the original type.
950   SDValue LHS = SExtPromotedInteger(N->getOperand(0));
951   SDValue RHS = SExtPromotedInteger(N->getOperand(1));
952   EVT OVT = N->getOperand(0).getValueType();
953   EVT NVT = LHS.getValueType();
954   SDLoc dl(N);
955 
956   // Do the arithmetic in the larger type.
957   unsigned Opcode = N->getOpcode() == ISD::SADDO ? ISD::ADD : ISD::SUB;
958   SDValue Res = DAG.getNode(Opcode, dl, NVT, LHS, RHS);
959 
960   // Calculate the overflow flag: sign extend the arithmetic result from
961   // the original type.
962   SDValue Ofl = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NVT, Res,
963                             DAG.getValueType(OVT));
964   // Overflowed if and only if this is not equal to Res.
965   Ofl = DAG.getSetCC(dl, N->getValueType(1), Ofl, Res, ISD::SETNE);
966 
967   // Use the calculated overflow everywhere.
968   ReplaceValueWith(SDValue(N, 1), Ofl);
969 
970   return Res;
971 }
972 
973 SDValue DAGTypeLegalizer::PromoteIntRes_SELECT(SDNode *N) {
974   SDValue LHS = GetPromotedInteger(N->getOperand(1));
975   SDValue RHS = GetPromotedInteger(N->getOperand(2));
976   return DAG.getSelect(SDLoc(N),
977                        LHS.getValueType(), N->getOperand(0), LHS, RHS);
978 }
979 
980 SDValue DAGTypeLegalizer::PromoteIntRes_VSELECT(SDNode *N) {
981   SDValue Mask = N->getOperand(0);
982 
983   SDValue LHS = GetPromotedInteger(N->getOperand(1));
984   SDValue RHS = GetPromotedInteger(N->getOperand(2));
985   return DAG.getNode(ISD::VSELECT, SDLoc(N),
986                      LHS.getValueType(), Mask, LHS, RHS);
987 }
988 
989 SDValue DAGTypeLegalizer::PromoteIntRes_SELECT_CC(SDNode *N) {
990   SDValue LHS = GetPromotedInteger(N->getOperand(2));
991   SDValue RHS = GetPromotedInteger(N->getOperand(3));
992   return DAG.getNode(ISD::SELECT_CC, SDLoc(N),
993                      LHS.getValueType(), N->getOperand(0),
994                      N->getOperand(1), LHS, RHS, N->getOperand(4));
995 }
996 
997 SDValue DAGTypeLegalizer::PromoteIntRes_SETCC(SDNode *N) {
998   unsigned OpNo = N->isStrictFPOpcode() ? 1 : 0;
999   EVT InVT = N->getOperand(OpNo).getValueType();
1000   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
1001 
1002   EVT SVT = getSetCCResultType(InVT);
1003 
1004   // If we got back a type that needs to be promoted, this likely means the
1005   // the input type also needs to be promoted. So get the promoted type for
1006   // the input and try the query again.
1007   if (getTypeAction(SVT) == TargetLowering::TypePromoteInteger) {
1008     if (getTypeAction(InVT) == TargetLowering::TypePromoteInteger) {
1009       InVT = TLI.getTypeToTransformTo(*DAG.getContext(), InVT);
1010       SVT = getSetCCResultType(InVT);
1011     } else {
1012       // Input type isn't promoted, just use the default promoted type.
1013       SVT = NVT;
1014     }
1015   }
1016 
1017   SDLoc dl(N);
1018   assert(SVT.isVector() == N->getOperand(OpNo).getValueType().isVector() &&
1019          "Vector compare must return a vector result!");
1020 
1021   // Get the SETCC result using the canonical SETCC type.
1022   SDValue SetCC;
1023   if (N->isStrictFPOpcode()) {
1024     EVT VTs[] = {SVT, MVT::Other};
1025     SDValue Opers[] = {N->getOperand(0), N->getOperand(1),
1026                        N->getOperand(2), N->getOperand(3)};
1027     SetCC = DAG.getNode(N->getOpcode(), dl, VTs, Opers);
1028     // Legalize the chain result - switch anything that used the old chain to
1029     // use the new one.
1030     ReplaceValueWith(SDValue(N, 1), SetCC.getValue(1));
1031   } else
1032     SetCC = DAG.getNode(N->getOpcode(), dl, SVT, N->getOperand(0),
1033                         N->getOperand(1), N->getOperand(2));
1034 
1035   // Convert to the expected type.
1036   return DAG.getSExtOrTrunc(SetCC, dl, NVT);
1037 }
1038 
1039 SDValue DAGTypeLegalizer::PromoteIntRes_SHL(SDNode *N) {
1040   SDValue LHS = GetPromotedInteger(N->getOperand(0));
1041   SDValue RHS = N->getOperand(1);
1042   if (getTypeAction(RHS.getValueType()) == TargetLowering::TypePromoteInteger)
1043     RHS = ZExtPromotedInteger(RHS);
1044   return DAG.getNode(ISD::SHL, SDLoc(N), LHS.getValueType(), LHS, RHS);
1045 }
1046 
1047 SDValue DAGTypeLegalizer::PromoteIntRes_SIGN_EXTEND_INREG(SDNode *N) {
1048   SDValue Op = GetPromotedInteger(N->getOperand(0));
1049   return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N),
1050                      Op.getValueType(), Op, N->getOperand(1));
1051 }
1052 
1053 SDValue DAGTypeLegalizer::PromoteIntRes_SimpleIntBinOp(SDNode *N) {
1054   // The input may have strange things in the top bits of the registers, but
1055   // these operations don't care.  They may have weird bits going out, but
1056   // that too is okay if they are integer operations.
1057   SDValue LHS = GetPromotedInteger(N->getOperand(0));
1058   SDValue RHS = GetPromotedInteger(N->getOperand(1));
1059   return DAG.getNode(N->getOpcode(), SDLoc(N),
1060                      LHS.getValueType(), LHS, RHS);
1061 }
1062 
1063 SDValue DAGTypeLegalizer::PromoteIntRes_SExtIntBinOp(SDNode *N) {
1064   // Sign extend the input.
1065   SDValue LHS = SExtPromotedInteger(N->getOperand(0));
1066   SDValue RHS = SExtPromotedInteger(N->getOperand(1));
1067   return DAG.getNode(N->getOpcode(), SDLoc(N),
1068                      LHS.getValueType(), LHS, RHS);
1069 }
1070 
1071 SDValue DAGTypeLegalizer::PromoteIntRes_ZExtIntBinOp(SDNode *N) {
1072   // Zero extend the input.
1073   SDValue LHS = ZExtPromotedInteger(N->getOperand(0));
1074   SDValue RHS = ZExtPromotedInteger(N->getOperand(1));
1075   return DAG.getNode(N->getOpcode(), SDLoc(N),
1076                      LHS.getValueType(), LHS, RHS);
1077 }
1078 
1079 SDValue DAGTypeLegalizer::PromoteIntRes_SRA(SDNode *N) {
1080   // The input value must be properly sign extended.
1081   SDValue LHS = SExtPromotedInteger(N->getOperand(0));
1082   SDValue RHS = N->getOperand(1);
1083   if (getTypeAction(RHS.getValueType()) == TargetLowering::TypePromoteInteger)
1084     RHS = ZExtPromotedInteger(RHS);
1085   return DAG.getNode(ISD::SRA, SDLoc(N), LHS.getValueType(), LHS, RHS);
1086 }
1087 
1088 SDValue DAGTypeLegalizer::PromoteIntRes_SRL(SDNode *N) {
1089   // The input value must be properly zero extended.
1090   SDValue LHS = ZExtPromotedInteger(N->getOperand(0));
1091   SDValue RHS = N->getOperand(1);
1092   if (getTypeAction(RHS.getValueType()) == TargetLowering::TypePromoteInteger)
1093     RHS = ZExtPromotedInteger(RHS);
1094   return DAG.getNode(ISD::SRL, SDLoc(N), LHS.getValueType(), LHS, RHS);
1095 }
1096 
1097 SDValue DAGTypeLegalizer::PromoteIntRes_TRUNCATE(SDNode *N) {
1098   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
1099   SDValue Res;
1100   SDValue InOp = N->getOperand(0);
1101   SDLoc dl(N);
1102 
1103   switch (getTypeAction(InOp.getValueType())) {
1104   default: llvm_unreachable("Unknown type action!");
1105   case TargetLowering::TypeLegal:
1106   case TargetLowering::TypeExpandInteger:
1107     Res = InOp;
1108     break;
1109   case TargetLowering::TypePromoteInteger:
1110     Res = GetPromotedInteger(InOp);
1111     break;
1112   case TargetLowering::TypeSplitVector: {
1113     EVT InVT = InOp.getValueType();
1114     assert(InVT.isVector() && "Cannot split scalar types");
1115     unsigned NumElts = InVT.getVectorNumElements();
1116     assert(NumElts == NVT.getVectorNumElements() &&
1117            "Dst and Src must have the same number of elements");
1118     assert(isPowerOf2_32(NumElts) &&
1119            "Promoted vector type must be a power of two");
1120 
1121     SDValue EOp1, EOp2;
1122     GetSplitVector(InOp, EOp1, EOp2);
1123 
1124     EVT HalfNVT = EVT::getVectorVT(*DAG.getContext(), NVT.getScalarType(),
1125                                    NumElts/2);
1126     EOp1 = DAG.getNode(ISD::TRUNCATE, dl, HalfNVT, EOp1);
1127     EOp2 = DAG.getNode(ISD::TRUNCATE, dl, HalfNVT, EOp2);
1128 
1129     return DAG.getNode(ISD::CONCAT_VECTORS, dl, NVT, EOp1, EOp2);
1130   }
1131   case TargetLowering::TypeWidenVector: {
1132     SDValue WideInOp = GetWidenedVector(InOp);
1133 
1134     // Truncate widened InOp.
1135     unsigned NumElem = WideInOp.getValueType().getVectorNumElements();
1136     EVT TruncVT = EVT::getVectorVT(*DAG.getContext(),
1137                                    N->getValueType(0).getScalarType(), NumElem);
1138     SDValue WideTrunc = DAG.getNode(ISD::TRUNCATE, dl, TruncVT, WideInOp);
1139 
1140     // Zero extend so that the elements are of same type as those of NVT
1141     EVT ExtVT = EVT::getVectorVT(*DAG.getContext(), NVT.getVectorElementType(),
1142                                  NumElem);
1143     SDValue WideExt = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, WideTrunc);
1144 
1145     // Extract the low NVT subvector.
1146     SDValue ZeroIdx = DAG.getVectorIdxConstant(0, dl);
1147     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT, WideExt, ZeroIdx);
1148   }
1149   }
1150 
1151   // Truncate to NVT instead of VT
1152   return DAG.getNode(ISD::TRUNCATE, dl, NVT, Res);
1153 }
1154 
1155 SDValue DAGTypeLegalizer::PromoteIntRes_UADDSUBO(SDNode *N, unsigned ResNo) {
1156   if (ResNo == 1)
1157     return PromoteIntRes_Overflow(N);
1158 
1159   // The operation overflowed iff the result in the larger type is not the
1160   // zero extension of its truncation to the original type.
1161   SDValue LHS = ZExtPromotedInteger(N->getOperand(0));
1162   SDValue RHS = ZExtPromotedInteger(N->getOperand(1));
1163   EVT OVT = N->getOperand(0).getValueType();
1164   EVT NVT = LHS.getValueType();
1165   SDLoc dl(N);
1166 
1167   // Do the arithmetic in the larger type.
1168   unsigned Opcode = N->getOpcode() == ISD::UADDO ? ISD::ADD : ISD::SUB;
1169   SDValue Res = DAG.getNode(Opcode, dl, NVT, LHS, RHS);
1170 
1171   // Calculate the overflow flag: zero extend the arithmetic result from
1172   // the original type.
1173   SDValue Ofl = DAG.getZeroExtendInReg(Res, dl, OVT);
1174   // Overflowed if and only if this is not equal to Res.
1175   Ofl = DAG.getSetCC(dl, N->getValueType(1), Ofl, Res, ISD::SETNE);
1176 
1177   // Use the calculated overflow everywhere.
1178   ReplaceValueWith(SDValue(N, 1), Ofl);
1179 
1180   return Res;
1181 }
1182 
1183 // Handle promotion for the ADDE/SUBE/ADDCARRY/SUBCARRY nodes. Notice that
1184 // the third operand of ADDE/SUBE nodes is carry flag, which differs from
1185 // the ADDCARRY/SUBCARRY nodes in that the third operand is carry Boolean.
1186 SDValue DAGTypeLegalizer::PromoteIntRes_ADDSUBCARRY(SDNode *N, unsigned ResNo) {
1187   if (ResNo == 1)
1188     return PromoteIntRes_Overflow(N);
1189 
1190   // We need to sign-extend the operands so the carry value computed by the
1191   // wide operation will be equivalent to the carry value computed by the
1192   // narrow operation.
1193   // An ADDCARRY can generate carry only if any of the operands has its
1194   // most significant bit set. Sign extension propagates the most significant
1195   // bit into the higher bits which means the extra bit that the narrow
1196   // addition would need (i.e. the carry) will be propagated through the higher
1197   // bits of the wide addition.
1198   // A SUBCARRY can generate borrow only if LHS < RHS and this property will be
1199   // preserved by sign extension.
1200   SDValue LHS = SExtPromotedInteger(N->getOperand(0));
1201   SDValue RHS = SExtPromotedInteger(N->getOperand(1));
1202 
1203   EVT ValueVTs[] = {LHS.getValueType(), N->getValueType(1)};
1204 
1205   // Do the arithmetic in the wide type.
1206   SDValue Res = DAG.getNode(N->getOpcode(), SDLoc(N), DAG.getVTList(ValueVTs),
1207                             LHS, RHS, N->getOperand(2));
1208 
1209   // Update the users of the original carry/borrow value.
1210   ReplaceValueWith(SDValue(N, 1), Res.getValue(1));
1211 
1212   return SDValue(Res.getNode(), 0);
1213 }
1214 
1215 SDValue DAGTypeLegalizer::PromoteIntRes_ABS(SDNode *N) {
1216   SDValue Op0 = SExtPromotedInteger(N->getOperand(0));
1217   return DAG.getNode(ISD::ABS, SDLoc(N), Op0.getValueType(), Op0);
1218 }
1219 
1220 SDValue DAGTypeLegalizer::PromoteIntRes_XMULO(SDNode *N, unsigned ResNo) {
1221   // Promote the overflow bit trivially.
1222   if (ResNo == 1)
1223     return PromoteIntRes_Overflow(N);
1224 
1225   SDValue LHS = N->getOperand(0), RHS = N->getOperand(1);
1226   SDLoc DL(N);
1227   EVT SmallVT = LHS.getValueType();
1228 
1229   // To determine if the result overflowed in a larger type, we extend the
1230   // input to the larger type, do the multiply (checking if it overflows),
1231   // then also check the high bits of the result to see if overflow happened
1232   // there.
1233   if (N->getOpcode() == ISD::SMULO) {
1234     LHS = SExtPromotedInteger(LHS);
1235     RHS = SExtPromotedInteger(RHS);
1236   } else {
1237     LHS = ZExtPromotedInteger(LHS);
1238     RHS = ZExtPromotedInteger(RHS);
1239   }
1240   SDVTList VTs = DAG.getVTList(LHS.getValueType(), N->getValueType(1));
1241   SDValue Mul = DAG.getNode(N->getOpcode(), DL, VTs, LHS, RHS);
1242 
1243   // Overflow occurred if it occurred in the larger type, or if the high part
1244   // of the result does not zero/sign-extend the low part.  Check this second
1245   // possibility first.
1246   SDValue Overflow;
1247   if (N->getOpcode() == ISD::UMULO) {
1248     // Unsigned overflow occurred if the high part is non-zero.
1249     unsigned Shift = SmallVT.getScalarSizeInBits();
1250     EVT ShiftTy = getShiftAmountTyForConstant(Mul.getValueType(), TLI, DAG);
1251     SDValue Hi = DAG.getNode(ISD::SRL, DL, Mul.getValueType(), Mul,
1252                              DAG.getConstant(Shift, DL, ShiftTy));
1253     Overflow = DAG.getSetCC(DL, N->getValueType(1), Hi,
1254                             DAG.getConstant(0, DL, Hi.getValueType()),
1255                             ISD::SETNE);
1256   } else {
1257     // Signed overflow occurred if the high part does not sign extend the low.
1258     SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, Mul.getValueType(),
1259                                Mul, DAG.getValueType(SmallVT));
1260     Overflow = DAG.getSetCC(DL, N->getValueType(1), SExt, Mul, ISD::SETNE);
1261   }
1262 
1263   // The only other way for overflow to occur is if the multiplication in the
1264   // larger type itself overflowed.
1265   Overflow = DAG.getNode(ISD::OR, DL, N->getValueType(1), Overflow,
1266                          SDValue(Mul.getNode(), 1));
1267 
1268   // Use the calculated overflow everywhere.
1269   ReplaceValueWith(SDValue(N, 1), Overflow);
1270   return Mul;
1271 }
1272 
1273 SDValue DAGTypeLegalizer::PromoteIntRes_UNDEF(SDNode *N) {
1274   return DAG.getUNDEF(TLI.getTypeToTransformTo(*DAG.getContext(),
1275                                                N->getValueType(0)));
1276 }
1277 
1278 SDValue DAGTypeLegalizer::PromoteIntRes_VSCALE(SDNode *N) {
1279   EVT VT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
1280 
1281   APInt MulImm = cast<ConstantSDNode>(N->getOperand(0))->getAPIntValue();
1282   return DAG.getVScale(SDLoc(N), VT, MulImm.sextOrSelf(VT.getSizeInBits()));
1283 }
1284 
1285 SDValue DAGTypeLegalizer::PromoteIntRes_VAARG(SDNode *N) {
1286   SDValue Chain = N->getOperand(0); // Get the chain.
1287   SDValue Ptr = N->getOperand(1); // Get the pointer.
1288   EVT VT = N->getValueType(0);
1289   SDLoc dl(N);
1290 
1291   MVT RegVT = TLI.getRegisterType(*DAG.getContext(), VT);
1292   unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), VT);
1293   // The argument is passed as NumRegs registers of type RegVT.
1294 
1295   SmallVector<SDValue, 8> Parts(NumRegs);
1296   for (unsigned i = 0; i < NumRegs; ++i) {
1297     Parts[i] = DAG.getVAArg(RegVT, dl, Chain, Ptr, N->getOperand(2),
1298                             N->getConstantOperandVal(3));
1299     Chain = Parts[i].getValue(1);
1300   }
1301 
1302   // Handle endianness of the load.
1303   if (DAG.getDataLayout().isBigEndian())
1304     std::reverse(Parts.begin(), Parts.end());
1305 
1306   // Assemble the parts in the promoted type.
1307   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
1308   SDValue Res = DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, Parts[0]);
1309   for (unsigned i = 1; i < NumRegs; ++i) {
1310     SDValue Part = DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, Parts[i]);
1311     // Shift it to the right position and "or" it in.
1312     Part = DAG.getNode(ISD::SHL, dl, NVT, Part,
1313                        DAG.getConstant(i * RegVT.getSizeInBits(), dl,
1314                                        TLI.getPointerTy(DAG.getDataLayout())));
1315     Res = DAG.getNode(ISD::OR, dl, NVT, Res, Part);
1316   }
1317 
1318   // Modified the chain result - switch anything that used the old chain to
1319   // use the new one.
1320   ReplaceValueWith(SDValue(N, 1), Chain);
1321 
1322   return Res;
1323 }
1324 
1325 //===----------------------------------------------------------------------===//
1326 //  Integer Operand Promotion
1327 //===----------------------------------------------------------------------===//
1328 
1329 /// PromoteIntegerOperand - This method is called when the specified operand of
1330 /// the specified node is found to need promotion.  At this point, all of the
1331 /// result types of the node are known to be legal, but other operands of the
1332 /// node may need promotion or expansion as well as the specified one.
1333 bool DAGTypeLegalizer::PromoteIntegerOperand(SDNode *N, unsigned OpNo) {
1334   LLVM_DEBUG(dbgs() << "Promote integer operand: "; N->dump(&DAG);
1335              dbgs() << "\n");
1336   SDValue Res = SDValue();
1337   if (CustomLowerNode(N, N->getOperand(OpNo).getValueType(), false)) {
1338     LLVM_DEBUG(dbgs() << "Node has been custom lowered, done\n");
1339     return false;
1340   }
1341 
1342   switch (N->getOpcode()) {
1343     default:
1344   #ifndef NDEBUG
1345     dbgs() << "PromoteIntegerOperand Op #" << OpNo << ": ";
1346     N->dump(&DAG); dbgs() << "\n";
1347   #endif
1348     llvm_unreachable("Do not know how to promote this operator's operand!");
1349 
1350   case ISD::ANY_EXTEND:   Res = PromoteIntOp_ANY_EXTEND(N); break;
1351   case ISD::ATOMIC_STORE:
1352     Res = PromoteIntOp_ATOMIC_STORE(cast<AtomicSDNode>(N));
1353     break;
1354   case ISD::BITCAST:      Res = PromoteIntOp_BITCAST(N); break;
1355   case ISD::BR_CC:        Res = PromoteIntOp_BR_CC(N, OpNo); break;
1356   case ISD::BRCOND:       Res = PromoteIntOp_BRCOND(N, OpNo); break;
1357   case ISD::BUILD_PAIR:   Res = PromoteIntOp_BUILD_PAIR(N); break;
1358   case ISD::BUILD_VECTOR: Res = PromoteIntOp_BUILD_VECTOR(N); break;
1359   case ISD::CONCAT_VECTORS: Res = PromoteIntOp_CONCAT_VECTORS(N); break;
1360   case ISD::EXTRACT_VECTOR_ELT: Res = PromoteIntOp_EXTRACT_VECTOR_ELT(N); break;
1361   case ISD::INSERT_VECTOR_ELT:
1362                           Res = PromoteIntOp_INSERT_VECTOR_ELT(N, OpNo);break;
1363   case ISD::SCALAR_TO_VECTOR:
1364                           Res = PromoteIntOp_SCALAR_TO_VECTOR(N); break;
1365   case ISD::SPLAT_VECTOR:
1366                           Res = PromoteIntOp_SPLAT_VECTOR(N); break;
1367   case ISD::VSELECT:
1368   case ISD::SELECT:       Res = PromoteIntOp_SELECT(N, OpNo); break;
1369   case ISD::SELECT_CC:    Res = PromoteIntOp_SELECT_CC(N, OpNo); break;
1370   case ISD::SETCC:        Res = PromoteIntOp_SETCC(N, OpNo); break;
1371   case ISD::SIGN_EXTEND:  Res = PromoteIntOp_SIGN_EXTEND(N); break;
1372   case ISD::SINT_TO_FP:   Res = PromoteIntOp_SINT_TO_FP(N); break;
1373   case ISD::STRICT_SINT_TO_FP: Res = PromoteIntOp_STRICT_SINT_TO_FP(N); break;
1374   case ISD::STORE:        Res = PromoteIntOp_STORE(cast<StoreSDNode>(N),
1375                                                    OpNo); break;
1376   case ISD::MSTORE:       Res = PromoteIntOp_MSTORE(cast<MaskedStoreSDNode>(N),
1377                                                     OpNo); break;
1378   case ISD::MLOAD:        Res = PromoteIntOp_MLOAD(cast<MaskedLoadSDNode>(N),
1379                                                     OpNo); break;
1380   case ISD::MGATHER:  Res = PromoteIntOp_MGATHER(cast<MaskedGatherSDNode>(N),
1381                                                  OpNo); break;
1382   case ISD::MSCATTER: Res = PromoteIntOp_MSCATTER(cast<MaskedScatterSDNode>(N),
1383                                                   OpNo); break;
1384   case ISD::TRUNCATE:     Res = PromoteIntOp_TRUNCATE(N); break;
1385   case ISD::FP16_TO_FP:
1386   case ISD::UINT_TO_FP:   Res = PromoteIntOp_UINT_TO_FP(N); break;
1387   case ISD::STRICT_UINT_TO_FP:  Res = PromoteIntOp_STRICT_UINT_TO_FP(N); break;
1388   case ISD::ZERO_EXTEND:  Res = PromoteIntOp_ZERO_EXTEND(N); break;
1389   case ISD::EXTRACT_SUBVECTOR: Res = PromoteIntOp_EXTRACT_SUBVECTOR(N); break;
1390 
1391   case ISD::SHL:
1392   case ISD::SRA:
1393   case ISD::SRL:
1394   case ISD::ROTL:
1395   case ISD::ROTR: Res = PromoteIntOp_Shift(N); break;
1396 
1397   case ISD::ADDCARRY:
1398   case ISD::SUBCARRY: Res = PromoteIntOp_ADDSUBCARRY(N, OpNo); break;
1399 
1400   case ISD::FRAMEADDR:
1401   case ISD::RETURNADDR: Res = PromoteIntOp_FRAMERETURNADDR(N); break;
1402 
1403   case ISD::PREFETCH: Res = PromoteIntOp_PREFETCH(N, OpNo); break;
1404 
1405   case ISD::SMULFIX:
1406   case ISD::SMULFIXSAT:
1407   case ISD::UMULFIX:
1408   case ISD::UMULFIXSAT:
1409   case ISD::SDIVFIX:
1410   case ISD::SDIVFIXSAT:
1411   case ISD::UDIVFIX:
1412   case ISD::UDIVFIXSAT: Res = PromoteIntOp_FIX(N); break;
1413 
1414   case ISD::FPOWI: Res = PromoteIntOp_FPOWI(N); break;
1415 
1416   case ISD::VECREDUCE_ADD:
1417   case ISD::VECREDUCE_MUL:
1418   case ISD::VECREDUCE_AND:
1419   case ISD::VECREDUCE_OR:
1420   case ISD::VECREDUCE_XOR:
1421   case ISD::VECREDUCE_SMAX:
1422   case ISD::VECREDUCE_SMIN:
1423   case ISD::VECREDUCE_UMAX:
1424   case ISD::VECREDUCE_UMIN: Res = PromoteIntOp_VECREDUCE(N); break;
1425   }
1426 
1427   // If the result is null, the sub-method took care of registering results etc.
1428   if (!Res.getNode()) return false;
1429 
1430   // If the result is N, the sub-method updated N in place.  Tell the legalizer
1431   // core about this.
1432   if (Res.getNode() == N)
1433     return true;
1434 
1435   const bool IsStrictFp = N->isStrictFPOpcode();
1436   assert(Res.getValueType() == N->getValueType(0) &&
1437          N->getNumValues() == (IsStrictFp ? 2 : 1) &&
1438          "Invalid operand expansion");
1439   LLVM_DEBUG(dbgs() << "Replacing: "; N->dump(&DAG); dbgs() << "     with: ";
1440              Res.dump());
1441 
1442   ReplaceValueWith(SDValue(N, 0), Res);
1443   if (IsStrictFp)
1444     ReplaceValueWith(SDValue(N, 1), SDValue(Res.getNode(), 1));
1445 
1446   return false;
1447 }
1448 
1449 /// PromoteSetCCOperands - Promote the operands of a comparison.  This code is
1450 /// shared among BR_CC, SELECT_CC, and SETCC handlers.
1451 void DAGTypeLegalizer::PromoteSetCCOperands(SDValue &NewLHS,SDValue &NewRHS,
1452                                             ISD::CondCode CCCode) {
1453   // We have to insert explicit sign or zero extends. Note that we could
1454   // insert sign extends for ALL conditions. For those operations where either
1455   // zero or sign extension would be valid, use SExtOrZExtPromotedInteger
1456   // which will choose the cheapest for the target.
1457   switch (CCCode) {
1458   default: llvm_unreachable("Unknown integer comparison!");
1459   case ISD::SETEQ:
1460   case ISD::SETNE: {
1461     SDValue OpL = GetPromotedInteger(NewLHS);
1462     SDValue OpR = GetPromotedInteger(NewRHS);
1463 
1464     // We would prefer to promote the comparison operand with sign extension.
1465     // If the width of OpL/OpR excluding the duplicated sign bits is no greater
1466     // than the width of NewLHS/NewRH, we can avoid inserting real truncate
1467     // instruction, which is redundant eventually.
1468     unsigned OpLEffectiveBits =
1469         OpL.getScalarValueSizeInBits() - DAG.ComputeNumSignBits(OpL) + 1;
1470     unsigned OpREffectiveBits =
1471         OpR.getScalarValueSizeInBits() - DAG.ComputeNumSignBits(OpR) + 1;
1472     if (OpLEffectiveBits <= NewLHS.getScalarValueSizeInBits() &&
1473         OpREffectiveBits <= NewRHS.getScalarValueSizeInBits()) {
1474       NewLHS = OpL;
1475       NewRHS = OpR;
1476     } else {
1477       NewLHS = SExtOrZExtPromotedInteger(NewLHS);
1478       NewRHS = SExtOrZExtPromotedInteger(NewRHS);
1479     }
1480     break;
1481   }
1482   case ISD::SETUGE:
1483   case ISD::SETUGT:
1484   case ISD::SETULE:
1485   case ISD::SETULT:
1486     NewLHS = SExtOrZExtPromotedInteger(NewLHS);
1487     NewRHS = SExtOrZExtPromotedInteger(NewRHS);
1488     break;
1489   case ISD::SETGE:
1490   case ISD::SETGT:
1491   case ISD::SETLT:
1492   case ISD::SETLE:
1493     NewLHS = SExtPromotedInteger(NewLHS);
1494     NewRHS = SExtPromotedInteger(NewRHS);
1495     break;
1496   }
1497 }
1498 
1499 SDValue DAGTypeLegalizer::PromoteIntOp_ANY_EXTEND(SDNode *N) {
1500   SDValue Op = GetPromotedInteger(N->getOperand(0));
1501   return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), N->getValueType(0), Op);
1502 }
1503 
1504 SDValue DAGTypeLegalizer::PromoteIntOp_ATOMIC_STORE(AtomicSDNode *N) {
1505   SDValue Op2 = GetPromotedInteger(N->getOperand(2));
1506   return DAG.getAtomic(N->getOpcode(), SDLoc(N), N->getMemoryVT(),
1507                        N->getChain(), N->getBasePtr(), Op2, N->getMemOperand());
1508 }
1509 
1510 SDValue DAGTypeLegalizer::PromoteIntOp_BITCAST(SDNode *N) {
1511   // This should only occur in unusual situations like bitcasting to an
1512   // x86_fp80, so just turn it into a store+load
1513   return CreateStackStoreLoad(N->getOperand(0), N->getValueType(0));
1514 }
1515 
1516 SDValue DAGTypeLegalizer::PromoteIntOp_BR_CC(SDNode *N, unsigned OpNo) {
1517   assert(OpNo == 2 && "Don't know how to promote this operand!");
1518 
1519   SDValue LHS = N->getOperand(2);
1520   SDValue RHS = N->getOperand(3);
1521   PromoteSetCCOperands(LHS, RHS, cast<CondCodeSDNode>(N->getOperand(1))->get());
1522 
1523   // The chain (Op#0), CC (#1) and basic block destination (Op#4) are always
1524   // legal types.
1525   return SDValue(DAG.UpdateNodeOperands(N, N->getOperand(0),
1526                                 N->getOperand(1), LHS, RHS, N->getOperand(4)),
1527                  0);
1528 }
1529 
1530 SDValue DAGTypeLegalizer::PromoteIntOp_BRCOND(SDNode *N, unsigned OpNo) {
1531   assert(OpNo == 1 && "only know how to promote condition");
1532 
1533   // Promote all the way up to the canonical SetCC type.
1534   SDValue Cond = PromoteTargetBoolean(N->getOperand(1), MVT::Other);
1535 
1536   // The chain (Op#0) and basic block destination (Op#2) are always legal types.
1537   return SDValue(DAG.UpdateNodeOperands(N, N->getOperand(0), Cond,
1538                                         N->getOperand(2)), 0);
1539 }
1540 
1541 SDValue DAGTypeLegalizer::PromoteIntOp_BUILD_PAIR(SDNode *N) {
1542   // Since the result type is legal, the operands must promote to it.
1543   EVT OVT = N->getOperand(0).getValueType();
1544   SDValue Lo = ZExtPromotedInteger(N->getOperand(0));
1545   SDValue Hi = GetPromotedInteger(N->getOperand(1));
1546   assert(Lo.getValueType() == N->getValueType(0) && "Operand over promoted?");
1547   SDLoc dl(N);
1548 
1549   Hi = DAG.getNode(ISD::SHL, dl, N->getValueType(0), Hi,
1550                    DAG.getConstant(OVT.getSizeInBits(), dl,
1551                                    TLI.getPointerTy(DAG.getDataLayout())));
1552   return DAG.getNode(ISD::OR, dl, N->getValueType(0), Lo, Hi);
1553 }
1554 
1555 SDValue DAGTypeLegalizer::PromoteIntOp_BUILD_VECTOR(SDNode *N) {
1556   // The vector type is legal but the element type is not.  This implies
1557   // that the vector is a power-of-two in length and that the element
1558   // type does not have a strange size (eg: it is not i1).
1559   EVT VecVT = N->getValueType(0);
1560   unsigned NumElts = VecVT.getVectorNumElements();
1561   assert(!((NumElts & 1) && (!TLI.isTypeLegal(VecVT))) &&
1562          "Legal vector of one illegal element?");
1563 
1564   // Promote the inserted value.  The type does not need to match the
1565   // vector element type.  Check that any extra bits introduced will be
1566   // truncated away.
1567   assert(N->getOperand(0).getValueSizeInBits() >=
1568          N->getValueType(0).getScalarSizeInBits() &&
1569          "Type of inserted value narrower than vector element type!");
1570 
1571   SmallVector<SDValue, 16> NewOps;
1572   for (unsigned i = 0; i < NumElts; ++i)
1573     NewOps.push_back(GetPromotedInteger(N->getOperand(i)));
1574 
1575   return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0);
1576 }
1577 
1578 SDValue DAGTypeLegalizer::PromoteIntOp_INSERT_VECTOR_ELT(SDNode *N,
1579                                                          unsigned OpNo) {
1580   if (OpNo == 1) {
1581     // Promote the inserted value.  This is valid because the type does not
1582     // have to match the vector element type.
1583 
1584     // Check that any extra bits introduced will be truncated away.
1585     assert(N->getOperand(1).getValueSizeInBits() >=
1586            N->getValueType(0).getScalarSizeInBits() &&
1587            "Type of inserted value narrower than vector element type!");
1588     return SDValue(DAG.UpdateNodeOperands(N, N->getOperand(0),
1589                                   GetPromotedInteger(N->getOperand(1)),
1590                                   N->getOperand(2)),
1591                    0);
1592   }
1593 
1594   assert(OpNo == 2 && "Different operand and result vector types?");
1595 
1596   // Promote the index.
1597   SDValue Idx = DAG.getZExtOrTrunc(N->getOperand(2), SDLoc(N),
1598                                    TLI.getVectorIdxTy(DAG.getDataLayout()));
1599   return SDValue(DAG.UpdateNodeOperands(N, N->getOperand(0),
1600                                 N->getOperand(1), Idx), 0);
1601 }
1602 
1603 SDValue DAGTypeLegalizer::PromoteIntOp_SCALAR_TO_VECTOR(SDNode *N) {
1604   // Integer SCALAR_TO_VECTOR operands are implicitly truncated, so just promote
1605   // the operand in place.
1606   return SDValue(DAG.UpdateNodeOperands(N,
1607                                 GetPromotedInteger(N->getOperand(0))), 0);
1608 }
1609 
1610 SDValue DAGTypeLegalizer::PromoteIntOp_SPLAT_VECTOR(SDNode *N) {
1611   // Integer SPLAT_VECTOR operands are implicitly truncated, so just promote the
1612   // operand in place.
1613   return SDValue(
1614       DAG.UpdateNodeOperands(N, GetPromotedInteger(N->getOperand(0))), 0);
1615 }
1616 
1617 SDValue DAGTypeLegalizer::PromoteIntOp_SELECT(SDNode *N, unsigned OpNo) {
1618   assert(OpNo == 0 && "Only know how to promote the condition!");
1619   SDValue Cond = N->getOperand(0);
1620   EVT OpTy = N->getOperand(1).getValueType();
1621 
1622   if (N->getOpcode() == ISD::VSELECT)
1623     if (SDValue Res = WidenVSELECTAndMask(N))
1624       return Res;
1625 
1626   // Promote all the way up to the canonical SetCC type.
1627   EVT OpVT = N->getOpcode() == ISD::SELECT ? OpTy.getScalarType() : OpTy;
1628   Cond = PromoteTargetBoolean(Cond, OpVT);
1629 
1630   return SDValue(DAG.UpdateNodeOperands(N, Cond, N->getOperand(1),
1631                                         N->getOperand(2)), 0);
1632 }
1633 
1634 SDValue DAGTypeLegalizer::PromoteIntOp_SELECT_CC(SDNode *N, unsigned OpNo) {
1635   assert(OpNo == 0 && "Don't know how to promote this operand!");
1636 
1637   SDValue LHS = N->getOperand(0);
1638   SDValue RHS = N->getOperand(1);
1639   PromoteSetCCOperands(LHS, RHS, cast<CondCodeSDNode>(N->getOperand(4))->get());
1640 
1641   // The CC (#4) and the possible return values (#2 and #3) have legal types.
1642   return SDValue(DAG.UpdateNodeOperands(N, LHS, RHS, N->getOperand(2),
1643                                 N->getOperand(3), N->getOperand(4)), 0);
1644 }
1645 
1646 SDValue DAGTypeLegalizer::PromoteIntOp_SETCC(SDNode *N, unsigned OpNo) {
1647   assert(OpNo == 0 && "Don't know how to promote this operand!");
1648 
1649   SDValue LHS = N->getOperand(0);
1650   SDValue RHS = N->getOperand(1);
1651   PromoteSetCCOperands(LHS, RHS, cast<CondCodeSDNode>(N->getOperand(2))->get());
1652 
1653   // The CC (#2) is always legal.
1654   return SDValue(DAG.UpdateNodeOperands(N, LHS, RHS, N->getOperand(2)), 0);
1655 }
1656 
1657 SDValue DAGTypeLegalizer::PromoteIntOp_Shift(SDNode *N) {
1658   return SDValue(DAG.UpdateNodeOperands(N, N->getOperand(0),
1659                                 ZExtPromotedInteger(N->getOperand(1))), 0);
1660 }
1661 
1662 SDValue DAGTypeLegalizer::PromoteIntOp_SIGN_EXTEND(SDNode *N) {
1663   SDValue Op = GetPromotedInteger(N->getOperand(0));
1664   SDLoc dl(N);
1665   Op = DAG.getNode(ISD::ANY_EXTEND, dl, N->getValueType(0), Op);
1666   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, Op.getValueType(),
1667                      Op, DAG.getValueType(N->getOperand(0).getValueType()));
1668 }
1669 
1670 SDValue DAGTypeLegalizer::PromoteIntOp_SINT_TO_FP(SDNode *N) {
1671   return SDValue(DAG.UpdateNodeOperands(N,
1672                                 SExtPromotedInteger(N->getOperand(0))), 0);
1673 }
1674 
1675 SDValue DAGTypeLegalizer::PromoteIntOp_STRICT_SINT_TO_FP(SDNode *N) {
1676   return SDValue(DAG.UpdateNodeOperands(N, N->getOperand(0),
1677                                 SExtPromotedInteger(N->getOperand(1))), 0);
1678 }
1679 
1680 SDValue DAGTypeLegalizer::PromoteIntOp_STORE(StoreSDNode *N, unsigned OpNo){
1681   assert(ISD::isUNINDEXEDStore(N) && "Indexed store during type legalization!");
1682   SDValue Ch = N->getChain(), Ptr = N->getBasePtr();
1683   SDLoc dl(N);
1684 
1685   SDValue Val = GetPromotedInteger(N->getValue());  // Get promoted value.
1686 
1687   // Truncate the value and store the result.
1688   return DAG.getTruncStore(Ch, dl, Val, Ptr,
1689                            N->getMemoryVT(), N->getMemOperand());
1690 }
1691 
1692 SDValue DAGTypeLegalizer::PromoteIntOp_MSTORE(MaskedStoreSDNode *N,
1693                                               unsigned OpNo) {
1694 
1695   SDValue DataOp = N->getValue();
1696   EVT DataVT = DataOp.getValueType();
1697   SDValue Mask = N->getMask();
1698   SDLoc dl(N);
1699 
1700   bool TruncateStore = false;
1701   if (OpNo == 4) {
1702     Mask = PromoteTargetBoolean(Mask, DataVT);
1703     // Update in place.
1704     SmallVector<SDValue, 4> NewOps(N->op_begin(), N->op_end());
1705     NewOps[4] = Mask;
1706     return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0);
1707   } else { // Data operand
1708     assert(OpNo == 1 && "Unexpected operand for promotion");
1709     DataOp = GetPromotedInteger(DataOp);
1710     TruncateStore = true;
1711   }
1712 
1713   return DAG.getMaskedStore(N->getChain(), dl, DataOp, N->getBasePtr(),
1714                             N->getOffset(), Mask, N->getMemoryVT(),
1715                             N->getMemOperand(), N->getAddressingMode(),
1716                             TruncateStore, N->isCompressingStore());
1717 }
1718 
1719 SDValue DAGTypeLegalizer::PromoteIntOp_MLOAD(MaskedLoadSDNode *N,
1720                                              unsigned OpNo) {
1721   assert(OpNo == 3 && "Only know how to promote the mask!");
1722   EVT DataVT = N->getValueType(0);
1723   SDValue Mask = PromoteTargetBoolean(N->getOperand(OpNo), DataVT);
1724   SmallVector<SDValue, 4> NewOps(N->op_begin(), N->op_end());
1725   NewOps[OpNo] = Mask;
1726   SDNode *Res = DAG.UpdateNodeOperands(N, NewOps);
1727   if (Res == N)
1728     return SDValue(Res, 0);
1729 
1730   // Update triggered CSE, do our own replacement since caller can't.
1731   ReplaceValueWith(SDValue(N, 0), SDValue(Res, 0));
1732   ReplaceValueWith(SDValue(N, 1), SDValue(Res, 1));
1733   return SDValue();
1734 }
1735 
1736 SDValue DAGTypeLegalizer::PromoteIntOp_MGATHER(MaskedGatherSDNode *N,
1737                                                unsigned OpNo) {
1738 
1739   SmallVector<SDValue, 5> NewOps(N->op_begin(), N->op_end());
1740   if (OpNo == 2) {
1741     // The Mask
1742     EVT DataVT = N->getValueType(0);
1743     NewOps[OpNo] = PromoteTargetBoolean(N->getOperand(OpNo), DataVT);
1744   } else if (OpNo == 4) {
1745     // The Index
1746     if (N->isIndexSigned())
1747       // Need to sign extend the index since the bits will likely be used.
1748       NewOps[OpNo] = SExtPromotedInteger(N->getOperand(OpNo));
1749     else
1750       NewOps[OpNo] = ZExtPromotedInteger(N->getOperand(OpNo));
1751   } else
1752     NewOps[OpNo] = GetPromotedInteger(N->getOperand(OpNo));
1753 
1754   SDNode *Res = DAG.UpdateNodeOperands(N, NewOps);
1755   if (Res == N)
1756     return SDValue(Res, 0);
1757 
1758   // Update triggered CSE, do our own replacement since caller can't.
1759   ReplaceValueWith(SDValue(N, 0), SDValue(Res, 0));
1760   ReplaceValueWith(SDValue(N, 1), SDValue(Res, 1));
1761   return SDValue();
1762 }
1763 
1764 SDValue DAGTypeLegalizer::PromoteIntOp_MSCATTER(MaskedScatterSDNode *N,
1765                                                 unsigned OpNo) {
1766   SmallVector<SDValue, 5> NewOps(N->op_begin(), N->op_end());
1767   if (OpNo == 2) {
1768     // The Mask
1769     EVT DataVT = N->getValue().getValueType();
1770     NewOps[OpNo] = PromoteTargetBoolean(N->getOperand(OpNo), DataVT);
1771   } else if (OpNo == 4) {
1772     // The Index
1773     if (N->isIndexSigned())
1774       // Need to sign extend the index since the bits will likely be used.
1775       NewOps[OpNo] = SExtPromotedInteger(N->getOperand(OpNo));
1776     else
1777       NewOps[OpNo] = ZExtPromotedInteger(N->getOperand(OpNo));
1778   } else
1779     NewOps[OpNo] = GetPromotedInteger(N->getOperand(OpNo));
1780   return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0);
1781 }
1782 
1783 SDValue DAGTypeLegalizer::PromoteIntOp_TRUNCATE(SDNode *N) {
1784   SDValue Op = GetPromotedInteger(N->getOperand(0));
1785   return DAG.getNode(ISD::TRUNCATE, SDLoc(N), N->getValueType(0), Op);
1786 }
1787 
1788 SDValue DAGTypeLegalizer::PromoteIntOp_UINT_TO_FP(SDNode *N) {
1789   return SDValue(DAG.UpdateNodeOperands(N,
1790                                 ZExtPromotedInteger(N->getOperand(0))), 0);
1791 }
1792 
1793 SDValue DAGTypeLegalizer::PromoteIntOp_STRICT_UINT_TO_FP(SDNode *N) {
1794   return SDValue(DAG.UpdateNodeOperands(N, N->getOperand(0),
1795                                 ZExtPromotedInteger(N->getOperand(1))), 0);
1796 }
1797 
1798 SDValue DAGTypeLegalizer::PromoteIntOp_ZERO_EXTEND(SDNode *N) {
1799   SDLoc dl(N);
1800   SDValue Op = GetPromotedInteger(N->getOperand(0));
1801   Op = DAG.getNode(ISD::ANY_EXTEND, dl, N->getValueType(0), Op);
1802   return DAG.getZeroExtendInReg(Op, dl, N->getOperand(0).getValueType());
1803 }
1804 
1805 SDValue DAGTypeLegalizer::PromoteIntOp_ADDSUBCARRY(SDNode *N, unsigned OpNo) {
1806   assert(OpNo == 2 && "Don't know how to promote this operand!");
1807 
1808   SDValue LHS = N->getOperand(0);
1809   SDValue RHS = N->getOperand(1);
1810   SDValue Carry = N->getOperand(2);
1811   SDLoc DL(N);
1812 
1813   Carry = PromoteTargetBoolean(Carry, LHS.getValueType());
1814 
1815   return SDValue(DAG.UpdateNodeOperands(N, LHS, RHS, Carry), 0);
1816 }
1817 
1818 SDValue DAGTypeLegalizer::PromoteIntOp_FIX(SDNode *N) {
1819   SDValue Op2 = ZExtPromotedInteger(N->getOperand(2));
1820   return SDValue(
1821       DAG.UpdateNodeOperands(N, N->getOperand(0), N->getOperand(1), Op2), 0);
1822 }
1823 
1824 SDValue DAGTypeLegalizer::PromoteIntOp_FRAMERETURNADDR(SDNode *N) {
1825   // Promote the RETURNADDR/FRAMEADDR argument to a supported integer width.
1826   SDValue Op = ZExtPromotedInteger(N->getOperand(0));
1827   return SDValue(DAG.UpdateNodeOperands(N, Op), 0);
1828 }
1829 
1830 SDValue DAGTypeLegalizer::PromoteIntOp_PREFETCH(SDNode *N, unsigned OpNo) {
1831   assert(OpNo > 1 && "Don't know how to promote this operand!");
1832   // Promote the rw, locality, and cache type arguments to a supported integer
1833   // width.
1834   SDValue Op2 = ZExtPromotedInteger(N->getOperand(2));
1835   SDValue Op3 = ZExtPromotedInteger(N->getOperand(3));
1836   SDValue Op4 = ZExtPromotedInteger(N->getOperand(4));
1837   return SDValue(DAG.UpdateNodeOperands(N, N->getOperand(0), N->getOperand(1),
1838                                         Op2, Op3, Op4),
1839                  0);
1840 }
1841 
1842 SDValue DAGTypeLegalizer::PromoteIntOp_FPOWI(SDNode *N) {
1843   SDValue Op = SExtPromotedInteger(N->getOperand(1));
1844   return SDValue(DAG.UpdateNodeOperands(N, N->getOperand(0), Op), 0);
1845 }
1846 
1847 SDValue DAGTypeLegalizer::PromoteIntOp_VECREDUCE(SDNode *N) {
1848   SDLoc dl(N);
1849   SDValue Op;
1850   switch (N->getOpcode()) {
1851   default: llvm_unreachable("Expected integer vector reduction");
1852   case ISD::VECREDUCE_ADD:
1853   case ISD::VECREDUCE_MUL:
1854   case ISD::VECREDUCE_AND:
1855   case ISD::VECREDUCE_OR:
1856   case ISD::VECREDUCE_XOR:
1857     Op = GetPromotedInteger(N->getOperand(0));
1858     break;
1859   case ISD::VECREDUCE_SMAX:
1860   case ISD::VECREDUCE_SMIN:
1861     Op = SExtPromotedInteger(N->getOperand(0));
1862     break;
1863   case ISD::VECREDUCE_UMAX:
1864   case ISD::VECREDUCE_UMIN:
1865     Op = ZExtPromotedInteger(N->getOperand(0));
1866     break;
1867   }
1868 
1869   EVT EltVT = Op.getValueType().getVectorElementType();
1870   EVT VT = N->getValueType(0);
1871   if (VT.bitsGE(EltVT))
1872     return DAG.getNode(N->getOpcode(), SDLoc(N), VT, Op);
1873 
1874   // Result size must be >= element size. If this is not the case after
1875   // promotion, also promote the result type and then truncate.
1876   SDValue Reduce = DAG.getNode(N->getOpcode(), dl, EltVT, Op);
1877   return DAG.getNode(ISD::TRUNCATE, dl, VT, Reduce);
1878 }
1879 
1880 //===----------------------------------------------------------------------===//
1881 //  Integer Result Expansion
1882 //===----------------------------------------------------------------------===//
1883 
1884 /// ExpandIntegerResult - This method is called when the specified result of the
1885 /// specified node is found to need expansion.  At this point, the node may also
1886 /// have invalid operands or may have other results that need promotion, we just
1887 /// know that (at least) one result needs expansion.
1888 void DAGTypeLegalizer::ExpandIntegerResult(SDNode *N, unsigned ResNo) {
1889   LLVM_DEBUG(dbgs() << "Expand integer result: "; N->dump(&DAG);
1890              dbgs() << "\n");
1891   SDValue Lo, Hi;
1892   Lo = Hi = SDValue();
1893 
1894   // See if the target wants to custom expand this node.
1895   if (CustomLowerNode(N, N->getValueType(ResNo), true))
1896     return;
1897 
1898   switch (N->getOpcode()) {
1899   default:
1900 #ifndef NDEBUG
1901     dbgs() << "ExpandIntegerResult #" << ResNo << ": ";
1902     N->dump(&DAG); dbgs() << "\n";
1903 #endif
1904     report_fatal_error("Do not know how to expand the result of this "
1905                        "operator!");
1906 
1907   case ISD::MERGE_VALUES: SplitRes_MERGE_VALUES(N, ResNo, Lo, Hi); break;
1908   case ISD::SELECT:       SplitRes_SELECT(N, Lo, Hi); break;
1909   case ISD::SELECT_CC:    SplitRes_SELECT_CC(N, Lo, Hi); break;
1910   case ISD::UNDEF:        SplitRes_UNDEF(N, Lo, Hi); break;
1911   case ISD::FREEZE:       SplitRes_FREEZE(N, Lo, Hi); break;
1912 
1913   case ISD::BITCAST:            ExpandRes_BITCAST(N, Lo, Hi); break;
1914   case ISD::BUILD_PAIR:         ExpandRes_BUILD_PAIR(N, Lo, Hi); break;
1915   case ISD::EXTRACT_ELEMENT:    ExpandRes_EXTRACT_ELEMENT(N, Lo, Hi); break;
1916   case ISD::EXTRACT_VECTOR_ELT: ExpandRes_EXTRACT_VECTOR_ELT(N, Lo, Hi); break;
1917   case ISD::VAARG:              ExpandRes_VAARG(N, Lo, Hi); break;
1918 
1919   case ISD::ANY_EXTEND:  ExpandIntRes_ANY_EXTEND(N, Lo, Hi); break;
1920   case ISD::AssertSext:  ExpandIntRes_AssertSext(N, Lo, Hi); break;
1921   case ISD::AssertZext:  ExpandIntRes_AssertZext(N, Lo, Hi); break;
1922   case ISD::BITREVERSE:  ExpandIntRes_BITREVERSE(N, Lo, Hi); break;
1923   case ISD::BSWAP:       ExpandIntRes_BSWAP(N, Lo, Hi); break;
1924   case ISD::Constant:    ExpandIntRes_Constant(N, Lo, Hi); break;
1925   case ISD::ABS:         ExpandIntRes_ABS(N, Lo, Hi); break;
1926   case ISD::CTLZ_ZERO_UNDEF:
1927   case ISD::CTLZ:        ExpandIntRes_CTLZ(N, Lo, Hi); break;
1928   case ISD::CTPOP:       ExpandIntRes_CTPOP(N, Lo, Hi); break;
1929   case ISD::CTTZ_ZERO_UNDEF:
1930   case ISD::CTTZ:        ExpandIntRes_CTTZ(N, Lo, Hi); break;
1931   case ISD::FLT_ROUNDS_: ExpandIntRes_FLT_ROUNDS(N, Lo, Hi); break;
1932   case ISD::STRICT_FP_TO_SINT:
1933   case ISD::FP_TO_SINT:  ExpandIntRes_FP_TO_SINT(N, Lo, Hi); break;
1934   case ISD::STRICT_FP_TO_UINT:
1935   case ISD::FP_TO_UINT:  ExpandIntRes_FP_TO_UINT(N, Lo, Hi); break;
1936   case ISD::STRICT_LLROUND:
1937   case ISD::STRICT_LLRINT:
1938   case ISD::LLROUND:
1939   case ISD::LLRINT:      ExpandIntRes_LLROUND_LLRINT(N, Lo, Hi); break;
1940   case ISD::LOAD:        ExpandIntRes_LOAD(cast<LoadSDNode>(N), Lo, Hi); break;
1941   case ISD::MUL:         ExpandIntRes_MUL(N, Lo, Hi); break;
1942   case ISD::READCYCLECOUNTER: ExpandIntRes_READCYCLECOUNTER(N, Lo, Hi); break;
1943   case ISD::SDIV:        ExpandIntRes_SDIV(N, Lo, Hi); break;
1944   case ISD::SIGN_EXTEND: ExpandIntRes_SIGN_EXTEND(N, Lo, Hi); break;
1945   case ISD::SIGN_EXTEND_INREG: ExpandIntRes_SIGN_EXTEND_INREG(N, Lo, Hi); break;
1946   case ISD::SREM:        ExpandIntRes_SREM(N, Lo, Hi); break;
1947   case ISD::TRUNCATE:    ExpandIntRes_TRUNCATE(N, Lo, Hi); break;
1948   case ISD::UDIV:        ExpandIntRes_UDIV(N, Lo, Hi); break;
1949   case ISD::UREM:        ExpandIntRes_UREM(N, Lo, Hi); break;
1950   case ISD::ZERO_EXTEND: ExpandIntRes_ZERO_EXTEND(N, Lo, Hi); break;
1951   case ISD::ATOMIC_LOAD: ExpandIntRes_ATOMIC_LOAD(N, Lo, Hi); break;
1952 
1953   case ISD::ATOMIC_LOAD_ADD:
1954   case ISD::ATOMIC_LOAD_SUB:
1955   case ISD::ATOMIC_LOAD_AND:
1956   case ISD::ATOMIC_LOAD_CLR:
1957   case ISD::ATOMIC_LOAD_OR:
1958   case ISD::ATOMIC_LOAD_XOR:
1959   case ISD::ATOMIC_LOAD_NAND:
1960   case ISD::ATOMIC_LOAD_MIN:
1961   case ISD::ATOMIC_LOAD_MAX:
1962   case ISD::ATOMIC_LOAD_UMIN:
1963   case ISD::ATOMIC_LOAD_UMAX:
1964   case ISD::ATOMIC_SWAP:
1965   case ISD::ATOMIC_CMP_SWAP: {
1966     std::pair<SDValue, SDValue> Tmp = ExpandAtomic(N);
1967     SplitInteger(Tmp.first, Lo, Hi);
1968     ReplaceValueWith(SDValue(N, 1), Tmp.second);
1969     break;
1970   }
1971   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
1972     AtomicSDNode *AN = cast<AtomicSDNode>(N);
1973     SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::Other);
1974     SDValue Tmp = DAG.getAtomicCmpSwap(
1975         ISD::ATOMIC_CMP_SWAP, SDLoc(N), AN->getMemoryVT(), VTs,
1976         N->getOperand(0), N->getOperand(1), N->getOperand(2), N->getOperand(3),
1977         AN->getMemOperand());
1978 
1979     // Expanding to the strong ATOMIC_CMP_SWAP node means we can determine
1980     // success simply by comparing the loaded value against the ingoing
1981     // comparison.
1982     SDValue Success = DAG.getSetCC(SDLoc(N), N->getValueType(1), Tmp,
1983                                    N->getOperand(2), ISD::SETEQ);
1984 
1985     SplitInteger(Tmp, Lo, Hi);
1986     ReplaceValueWith(SDValue(N, 1), Success);
1987     ReplaceValueWith(SDValue(N, 2), Tmp.getValue(1));
1988     break;
1989   }
1990 
1991   case ISD::AND:
1992   case ISD::OR:
1993   case ISD::XOR: ExpandIntRes_Logical(N, Lo, Hi); break;
1994 
1995   case ISD::UMAX:
1996   case ISD::SMAX:
1997   case ISD::UMIN:
1998   case ISD::SMIN: ExpandIntRes_MINMAX(N, Lo, Hi); break;
1999 
2000   case ISD::ADD:
2001   case ISD::SUB: ExpandIntRes_ADDSUB(N, Lo, Hi); break;
2002 
2003   case ISD::ADDC:
2004   case ISD::SUBC: ExpandIntRes_ADDSUBC(N, Lo, Hi); break;
2005 
2006   case ISD::ADDE:
2007   case ISD::SUBE: ExpandIntRes_ADDSUBE(N, Lo, Hi); break;
2008 
2009   case ISD::ADDCARRY:
2010   case ISD::SUBCARRY: ExpandIntRes_ADDSUBCARRY(N, Lo, Hi); break;
2011 
2012   case ISD::SHL:
2013   case ISD::SRA:
2014   case ISD::SRL: ExpandIntRes_Shift(N, Lo, Hi); break;
2015 
2016   case ISD::SADDO:
2017   case ISD::SSUBO: ExpandIntRes_SADDSUBO(N, Lo, Hi); break;
2018   case ISD::UADDO:
2019   case ISD::USUBO: ExpandIntRes_UADDSUBO(N, Lo, Hi); break;
2020   case ISD::UMULO:
2021   case ISD::SMULO: ExpandIntRes_XMULO(N, Lo, Hi); break;
2022 
2023   case ISD::SADDSAT:
2024   case ISD::UADDSAT:
2025   case ISD::SSUBSAT:
2026   case ISD::USUBSAT: ExpandIntRes_ADDSUBSAT(N, Lo, Hi); break;
2027 
2028   case ISD::SMULFIX:
2029   case ISD::SMULFIXSAT:
2030   case ISD::UMULFIX:
2031   case ISD::UMULFIXSAT: ExpandIntRes_MULFIX(N, Lo, Hi); break;
2032 
2033   case ISD::SDIVFIX:
2034   case ISD::SDIVFIXSAT:
2035   case ISD::UDIVFIX:
2036   case ISD::UDIVFIXSAT: ExpandIntRes_DIVFIX(N, Lo, Hi); break;
2037 
2038   case ISD::VECREDUCE_ADD:
2039   case ISD::VECREDUCE_MUL:
2040   case ISD::VECREDUCE_AND:
2041   case ISD::VECREDUCE_OR:
2042   case ISD::VECREDUCE_XOR:
2043   case ISD::VECREDUCE_SMAX:
2044   case ISD::VECREDUCE_SMIN:
2045   case ISD::VECREDUCE_UMAX:
2046   case ISD::VECREDUCE_UMIN: ExpandIntRes_VECREDUCE(N, Lo, Hi); break;
2047   }
2048 
2049   // If Lo/Hi is null, the sub-method took care of registering results etc.
2050   if (Lo.getNode())
2051     SetExpandedInteger(SDValue(N, ResNo), Lo, Hi);
2052 }
2053 
2054 /// Lower an atomic node to the appropriate builtin call.
2055 std::pair <SDValue, SDValue> DAGTypeLegalizer::ExpandAtomic(SDNode *Node) {
2056   unsigned Opc = Node->getOpcode();
2057   MVT VT = cast<AtomicSDNode>(Node)->getMemoryVT().getSimpleVT();
2058   RTLIB::Libcall LC = RTLIB::getSYNC(Opc, VT);
2059   assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unexpected atomic op or value type!");
2060 
2061   EVT RetVT = Node->getValueType(0);
2062   SmallVector<SDValue, 4> Ops(Node->op_begin() + 1, Node->op_end());
2063   TargetLowering::MakeLibCallOptions CallOptions;
2064   return TLI.makeLibCall(DAG, LC, RetVT, Ops, CallOptions, SDLoc(Node),
2065                          Node->getOperand(0));
2066 }
2067 
2068 /// N is a shift by a value that needs to be expanded,
2069 /// and the shift amount is a constant 'Amt'.  Expand the operation.
2070 void DAGTypeLegalizer::ExpandShiftByConstant(SDNode *N, const APInt &Amt,
2071                                              SDValue &Lo, SDValue &Hi) {
2072   SDLoc DL(N);
2073   // Expand the incoming operand to be shifted, so that we have its parts
2074   SDValue InL, InH;
2075   GetExpandedInteger(N->getOperand(0), InL, InH);
2076 
2077   // Though Amt shouldn't usually be 0, it's possible. E.g. when legalization
2078   // splitted a vector shift, like this: <op1, op2> SHL <0, 2>.
2079   if (!Amt) {
2080     Lo = InL;
2081     Hi = InH;
2082     return;
2083   }
2084 
2085   EVT NVT = InL.getValueType();
2086   unsigned VTBits = N->getValueType(0).getSizeInBits();
2087   unsigned NVTBits = NVT.getSizeInBits();
2088   EVT ShTy = N->getOperand(1).getValueType();
2089 
2090   if (N->getOpcode() == ISD::SHL) {
2091     if (Amt.ugt(VTBits)) {
2092       Lo = Hi = DAG.getConstant(0, DL, NVT);
2093     } else if (Amt.ugt(NVTBits)) {
2094       Lo = DAG.getConstant(0, DL, NVT);
2095       Hi = DAG.getNode(ISD::SHL, DL,
2096                        NVT, InL, DAG.getConstant(Amt - NVTBits, DL, ShTy));
2097     } else if (Amt == NVTBits) {
2098       Lo = DAG.getConstant(0, DL, NVT);
2099       Hi = InL;
2100     } else {
2101       Lo = DAG.getNode(ISD::SHL, DL, NVT, InL, DAG.getConstant(Amt, DL, ShTy));
2102       Hi = DAG.getNode(ISD::OR, DL, NVT,
2103                        DAG.getNode(ISD::SHL, DL, NVT, InH,
2104                                    DAG.getConstant(Amt, DL, ShTy)),
2105                        DAG.getNode(ISD::SRL, DL, NVT, InL,
2106                                    DAG.getConstant(-Amt + NVTBits, DL, ShTy)));
2107     }
2108     return;
2109   }
2110 
2111   if (N->getOpcode() == ISD::SRL) {
2112     if (Amt.ugt(VTBits)) {
2113       Lo = Hi = DAG.getConstant(0, DL, NVT);
2114     } else if (Amt.ugt(NVTBits)) {
2115       Lo = DAG.getNode(ISD::SRL, DL,
2116                        NVT, InH, DAG.getConstant(Amt - NVTBits, DL, ShTy));
2117       Hi = DAG.getConstant(0, DL, NVT);
2118     } else if (Amt == NVTBits) {
2119       Lo = InH;
2120       Hi = DAG.getConstant(0, DL, NVT);
2121     } else {
2122       Lo = DAG.getNode(ISD::OR, DL, NVT,
2123                        DAG.getNode(ISD::SRL, DL, NVT, InL,
2124                                    DAG.getConstant(Amt, DL, ShTy)),
2125                        DAG.getNode(ISD::SHL, DL, NVT, InH,
2126                                    DAG.getConstant(-Amt + NVTBits, DL, ShTy)));
2127       Hi = DAG.getNode(ISD::SRL, DL, NVT, InH, DAG.getConstant(Amt, DL, ShTy));
2128     }
2129     return;
2130   }
2131 
2132   assert(N->getOpcode() == ISD::SRA && "Unknown shift!");
2133   if (Amt.ugt(VTBits)) {
2134     Hi = Lo = DAG.getNode(ISD::SRA, DL, NVT, InH,
2135                           DAG.getConstant(NVTBits - 1, DL, ShTy));
2136   } else if (Amt.ugt(NVTBits)) {
2137     Lo = DAG.getNode(ISD::SRA, DL, NVT, InH,
2138                      DAG.getConstant(Amt - NVTBits, DL, ShTy));
2139     Hi = DAG.getNode(ISD::SRA, DL, NVT, InH,
2140                      DAG.getConstant(NVTBits - 1, DL, ShTy));
2141   } else if (Amt == NVTBits) {
2142     Lo = InH;
2143     Hi = DAG.getNode(ISD::SRA, DL, NVT, InH,
2144                      DAG.getConstant(NVTBits - 1, DL, ShTy));
2145   } else {
2146     Lo = DAG.getNode(ISD::OR, DL, NVT,
2147                      DAG.getNode(ISD::SRL, DL, NVT, InL,
2148                                  DAG.getConstant(Amt, DL, ShTy)),
2149                      DAG.getNode(ISD::SHL, DL, NVT, InH,
2150                                  DAG.getConstant(-Amt + NVTBits, DL, ShTy)));
2151     Hi = DAG.getNode(ISD::SRA, DL, NVT, InH, DAG.getConstant(Amt, DL, ShTy));
2152   }
2153 }
2154 
2155 /// ExpandShiftWithKnownAmountBit - Try to determine whether we can simplify
2156 /// this shift based on knowledge of the high bit of the shift amount.  If we
2157 /// can tell this, we know that it is >= 32 or < 32, without knowing the actual
2158 /// shift amount.
2159 bool DAGTypeLegalizer::
2160 ExpandShiftWithKnownAmountBit(SDNode *N, SDValue &Lo, SDValue &Hi) {
2161   SDValue Amt = N->getOperand(1);
2162   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
2163   EVT ShTy = Amt.getValueType();
2164   unsigned ShBits = ShTy.getScalarSizeInBits();
2165   unsigned NVTBits = NVT.getScalarSizeInBits();
2166   assert(isPowerOf2_32(NVTBits) &&
2167          "Expanded integer type size not a power of two!");
2168   SDLoc dl(N);
2169 
2170   APInt HighBitMask = APInt::getHighBitsSet(ShBits, ShBits - Log2_32(NVTBits));
2171   KnownBits Known = DAG.computeKnownBits(N->getOperand(1));
2172 
2173   // If we don't know anything about the high bits, exit.
2174   if (((Known.Zero|Known.One) & HighBitMask) == 0)
2175     return false;
2176 
2177   // Get the incoming operand to be shifted.
2178   SDValue InL, InH;
2179   GetExpandedInteger(N->getOperand(0), InL, InH);
2180 
2181   // If we know that any of the high bits of the shift amount are one, then we
2182   // can do this as a couple of simple shifts.
2183   if (Known.One.intersects(HighBitMask)) {
2184     // Mask out the high bit, which we know is set.
2185     Amt = DAG.getNode(ISD::AND, dl, ShTy, Amt,
2186                       DAG.getConstant(~HighBitMask, dl, ShTy));
2187 
2188     switch (N->getOpcode()) {
2189     default: llvm_unreachable("Unknown shift");
2190     case ISD::SHL:
2191       Lo = DAG.getConstant(0, dl, NVT);              // Low part is zero.
2192       Hi = DAG.getNode(ISD::SHL, dl, NVT, InL, Amt); // High part from Lo part.
2193       return true;
2194     case ISD::SRL:
2195       Hi = DAG.getConstant(0, dl, NVT);              // Hi part is zero.
2196       Lo = DAG.getNode(ISD::SRL, dl, NVT, InH, Amt); // Lo part from Hi part.
2197       return true;
2198     case ISD::SRA:
2199       Hi = DAG.getNode(ISD::SRA, dl, NVT, InH,       // Sign extend high part.
2200                        DAG.getConstant(NVTBits - 1, dl, ShTy));
2201       Lo = DAG.getNode(ISD::SRA, dl, NVT, InH, Amt); // Lo part from Hi part.
2202       return true;
2203     }
2204   }
2205 
2206   // If we know that all of the high bits of the shift amount are zero, then we
2207   // can do this as a couple of simple shifts.
2208   if (HighBitMask.isSubsetOf(Known.Zero)) {
2209     // Calculate 31-x. 31 is used instead of 32 to avoid creating an undefined
2210     // shift if x is zero.  We can use XOR here because x is known to be smaller
2211     // than 32.
2212     SDValue Amt2 = DAG.getNode(ISD::XOR, dl, ShTy, Amt,
2213                                DAG.getConstant(NVTBits - 1, dl, ShTy));
2214 
2215     unsigned Op1, Op2;
2216     switch (N->getOpcode()) {
2217     default: llvm_unreachable("Unknown shift");
2218     case ISD::SHL:  Op1 = ISD::SHL; Op2 = ISD::SRL; break;
2219     case ISD::SRL:
2220     case ISD::SRA:  Op1 = ISD::SRL; Op2 = ISD::SHL; break;
2221     }
2222 
2223     // When shifting right the arithmetic for Lo and Hi is swapped.
2224     if (N->getOpcode() != ISD::SHL)
2225       std::swap(InL, InH);
2226 
2227     // Use a little trick to get the bits that move from Lo to Hi. First
2228     // shift by one bit.
2229     SDValue Sh1 = DAG.getNode(Op2, dl, NVT, InL, DAG.getConstant(1, dl, ShTy));
2230     // Then compute the remaining shift with amount-1.
2231     SDValue Sh2 = DAG.getNode(Op2, dl, NVT, Sh1, Amt2);
2232 
2233     Lo = DAG.getNode(N->getOpcode(), dl, NVT, InL, Amt);
2234     Hi = DAG.getNode(ISD::OR, dl, NVT, DAG.getNode(Op1, dl, NVT, InH, Amt),Sh2);
2235 
2236     if (N->getOpcode() != ISD::SHL)
2237       std::swap(Hi, Lo);
2238     return true;
2239   }
2240 
2241   return false;
2242 }
2243 
2244 /// ExpandShiftWithUnknownAmountBit - Fully general expansion of integer shift
2245 /// of any size.
2246 bool DAGTypeLegalizer::
2247 ExpandShiftWithUnknownAmountBit(SDNode *N, SDValue &Lo, SDValue &Hi) {
2248   SDValue Amt = N->getOperand(1);
2249   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
2250   EVT ShTy = Amt.getValueType();
2251   unsigned NVTBits = NVT.getSizeInBits();
2252   assert(isPowerOf2_32(NVTBits) &&
2253          "Expanded integer type size not a power of two!");
2254   SDLoc dl(N);
2255 
2256   // Get the incoming operand to be shifted.
2257   SDValue InL, InH;
2258   GetExpandedInteger(N->getOperand(0), InL, InH);
2259 
2260   SDValue NVBitsNode = DAG.getConstant(NVTBits, dl, ShTy);
2261   SDValue AmtExcess = DAG.getNode(ISD::SUB, dl, ShTy, Amt, NVBitsNode);
2262   SDValue AmtLack = DAG.getNode(ISD::SUB, dl, ShTy, NVBitsNode, Amt);
2263   SDValue isShort = DAG.getSetCC(dl, getSetCCResultType(ShTy),
2264                                  Amt, NVBitsNode, ISD::SETULT);
2265   SDValue isZero = DAG.getSetCC(dl, getSetCCResultType(ShTy),
2266                                 Amt, DAG.getConstant(0, dl, ShTy),
2267                                 ISD::SETEQ);
2268 
2269   SDValue LoS, HiS, LoL, HiL;
2270   switch (N->getOpcode()) {
2271   default: llvm_unreachable("Unknown shift");
2272   case ISD::SHL:
2273     // Short: ShAmt < NVTBits
2274     LoS = DAG.getNode(ISD::SHL, dl, NVT, InL, Amt);
2275     HiS = DAG.getNode(ISD::OR, dl, NVT,
2276                       DAG.getNode(ISD::SHL, dl, NVT, InH, Amt),
2277                       DAG.getNode(ISD::SRL, dl, NVT, InL, AmtLack));
2278 
2279     // Long: ShAmt >= NVTBits
2280     LoL = DAG.getConstant(0, dl, NVT);                    // Lo part is zero.
2281     HiL = DAG.getNode(ISD::SHL, dl, NVT, InL, AmtExcess); // Hi from Lo part.
2282 
2283     Lo = DAG.getSelect(dl, NVT, isShort, LoS, LoL);
2284     Hi = DAG.getSelect(dl, NVT, isZero, InH,
2285                        DAG.getSelect(dl, NVT, isShort, HiS, HiL));
2286     return true;
2287   case ISD::SRL:
2288     // Short: ShAmt < NVTBits
2289     HiS = DAG.getNode(ISD::SRL, dl, NVT, InH, Amt);
2290     LoS = DAG.getNode(ISD::OR, dl, NVT,
2291                       DAG.getNode(ISD::SRL, dl, NVT, InL, Amt),
2292     // FIXME: If Amt is zero, the following shift generates an undefined result
2293     // on some architectures.
2294                       DAG.getNode(ISD::SHL, dl, NVT, InH, AmtLack));
2295 
2296     // Long: ShAmt >= NVTBits
2297     HiL = DAG.getConstant(0, dl, NVT);                    // Hi part is zero.
2298     LoL = DAG.getNode(ISD::SRL, dl, NVT, InH, AmtExcess); // Lo from Hi part.
2299 
2300     Lo = DAG.getSelect(dl, NVT, isZero, InL,
2301                        DAG.getSelect(dl, NVT, isShort, LoS, LoL));
2302     Hi = DAG.getSelect(dl, NVT, isShort, HiS, HiL);
2303     return true;
2304   case ISD::SRA:
2305     // Short: ShAmt < NVTBits
2306     HiS = DAG.getNode(ISD::SRA, dl, NVT, InH, Amt);
2307     LoS = DAG.getNode(ISD::OR, dl, NVT,
2308                       DAG.getNode(ISD::SRL, dl, NVT, InL, Amt),
2309                       DAG.getNode(ISD::SHL, dl, NVT, InH, AmtLack));
2310 
2311     // Long: ShAmt >= NVTBits
2312     HiL = DAG.getNode(ISD::SRA, dl, NVT, InH,             // Sign of Hi part.
2313                       DAG.getConstant(NVTBits - 1, dl, ShTy));
2314     LoL = DAG.getNode(ISD::SRA, dl, NVT, InH, AmtExcess); // Lo from Hi part.
2315 
2316     Lo = DAG.getSelect(dl, NVT, isZero, InL,
2317                        DAG.getSelect(dl, NVT, isShort, LoS, LoL));
2318     Hi = DAG.getSelect(dl, NVT, isShort, HiS, HiL);
2319     return true;
2320   }
2321 }
2322 
2323 static std::pair<ISD::CondCode, ISD::NodeType> getExpandedMinMaxOps(int Op) {
2324 
2325   switch (Op) {
2326     default: llvm_unreachable("invalid min/max opcode");
2327     case ISD::SMAX:
2328       return std::make_pair(ISD::SETGT, ISD::UMAX);
2329     case ISD::UMAX:
2330       return std::make_pair(ISD::SETUGT, ISD::UMAX);
2331     case ISD::SMIN:
2332       return std::make_pair(ISD::SETLT, ISD::UMIN);
2333     case ISD::UMIN:
2334       return std::make_pair(ISD::SETULT, ISD::UMIN);
2335   }
2336 }
2337 
2338 void DAGTypeLegalizer::ExpandIntRes_MINMAX(SDNode *N,
2339                                            SDValue &Lo, SDValue &Hi) {
2340   SDLoc DL(N);
2341   ISD::NodeType LoOpc;
2342   ISD::CondCode CondC;
2343   std::tie(CondC, LoOpc) = getExpandedMinMaxOps(N->getOpcode());
2344 
2345   // Expand the subcomponents.
2346   SDValue LHSL, LHSH, RHSL, RHSH;
2347   GetExpandedInteger(N->getOperand(0), LHSL, LHSH);
2348   GetExpandedInteger(N->getOperand(1), RHSL, RHSH);
2349 
2350   // Value types
2351   EVT NVT = LHSL.getValueType();
2352   EVT CCT = getSetCCResultType(NVT);
2353 
2354   // Hi part is always the same op
2355   Hi = DAG.getNode(N->getOpcode(), DL, NVT, {LHSH, RHSH});
2356 
2357   // We need to know whether to select Lo part that corresponds to 'winning'
2358   // Hi part or if Hi parts are equal.
2359   SDValue IsHiLeft = DAG.getSetCC(DL, CCT, LHSH, RHSH, CondC);
2360   SDValue IsHiEq = DAG.getSetCC(DL, CCT, LHSH, RHSH, ISD::SETEQ);
2361 
2362   // Lo part corresponding to the 'winning' Hi part
2363   SDValue LoCmp = DAG.getSelect(DL, NVT, IsHiLeft, LHSL, RHSL);
2364 
2365   // Recursed Lo part if Hi parts are equal, this uses unsigned version
2366   SDValue LoMinMax = DAG.getNode(LoOpc, DL, NVT, {LHSL, RHSL});
2367 
2368   Lo = DAG.getSelect(DL, NVT, IsHiEq, LoMinMax, LoCmp);
2369 }
2370 
2371 void DAGTypeLegalizer::ExpandIntRes_ADDSUB(SDNode *N,
2372                                            SDValue &Lo, SDValue &Hi) {
2373   SDLoc dl(N);
2374   // Expand the subcomponents.
2375   SDValue LHSL, LHSH, RHSL, RHSH;
2376   GetExpandedInteger(N->getOperand(0), LHSL, LHSH);
2377   GetExpandedInteger(N->getOperand(1), RHSL, RHSH);
2378 
2379   EVT NVT = LHSL.getValueType();
2380   SDValue LoOps[2] = { LHSL, RHSL };
2381   SDValue HiOps[3] = { LHSH, RHSH };
2382 
2383   bool HasOpCarry = TLI.isOperationLegalOrCustom(
2384       N->getOpcode() == ISD::ADD ? ISD::ADDCARRY : ISD::SUBCARRY,
2385       TLI.getTypeToExpandTo(*DAG.getContext(), NVT));
2386   if (HasOpCarry) {
2387     SDVTList VTList = DAG.getVTList(NVT, getSetCCResultType(NVT));
2388     if (N->getOpcode() == ISD::ADD) {
2389       Lo = DAG.getNode(ISD::UADDO, dl, VTList, LoOps);
2390       HiOps[2] = Lo.getValue(1);
2391       Hi = DAG.getNode(ISD::ADDCARRY, dl, VTList, HiOps);
2392     } else {
2393       Lo = DAG.getNode(ISD::USUBO, dl, VTList, LoOps);
2394       HiOps[2] = Lo.getValue(1);
2395       Hi = DAG.getNode(ISD::SUBCARRY, dl, VTList, HiOps);
2396     }
2397     return;
2398   }
2399 
2400   // Do not generate ADDC/ADDE or SUBC/SUBE if the target does not support
2401   // them.  TODO: Teach operation legalization how to expand unsupported
2402   // ADDC/ADDE/SUBC/SUBE.  The problem is that these operations generate
2403   // a carry of type MVT::Glue, but there doesn't seem to be any way to
2404   // generate a value of this type in the expanded code sequence.
2405   bool hasCarry =
2406     TLI.isOperationLegalOrCustom(N->getOpcode() == ISD::ADD ?
2407                                    ISD::ADDC : ISD::SUBC,
2408                                  TLI.getTypeToExpandTo(*DAG.getContext(), NVT));
2409 
2410   if (hasCarry) {
2411     SDVTList VTList = DAG.getVTList(NVT, MVT::Glue);
2412     if (N->getOpcode() == ISD::ADD) {
2413       Lo = DAG.getNode(ISD::ADDC, dl, VTList, LoOps);
2414       HiOps[2] = Lo.getValue(1);
2415       Hi = DAG.getNode(ISD::ADDE, dl, VTList, HiOps);
2416     } else {
2417       Lo = DAG.getNode(ISD::SUBC, dl, VTList, LoOps);
2418       HiOps[2] = Lo.getValue(1);
2419       Hi = DAG.getNode(ISD::SUBE, dl, VTList, HiOps);
2420     }
2421     return;
2422   }
2423 
2424   bool hasOVF =
2425     TLI.isOperationLegalOrCustom(N->getOpcode() == ISD::ADD ?
2426                                    ISD::UADDO : ISD::USUBO,
2427                                  TLI.getTypeToExpandTo(*DAG.getContext(), NVT));
2428   TargetLoweringBase::BooleanContent BoolType = TLI.getBooleanContents(NVT);
2429 
2430   if (hasOVF) {
2431     EVT OvfVT = getSetCCResultType(NVT);
2432     SDVTList VTList = DAG.getVTList(NVT, OvfVT);
2433     int RevOpc;
2434     if (N->getOpcode() == ISD::ADD) {
2435       RevOpc = ISD::SUB;
2436       Lo = DAG.getNode(ISD::UADDO, dl, VTList, LoOps);
2437       Hi = DAG.getNode(ISD::ADD, dl, NVT, makeArrayRef(HiOps, 2));
2438     } else {
2439       RevOpc = ISD::ADD;
2440       Lo = DAG.getNode(ISD::USUBO, dl, VTList, LoOps);
2441       Hi = DAG.getNode(ISD::SUB, dl, NVT, makeArrayRef(HiOps, 2));
2442     }
2443     SDValue OVF = Lo.getValue(1);
2444 
2445     switch (BoolType) {
2446     case TargetLoweringBase::UndefinedBooleanContent:
2447       OVF = DAG.getNode(ISD::AND, dl, OvfVT, DAG.getConstant(1, dl, OvfVT), OVF);
2448       LLVM_FALLTHROUGH;
2449     case TargetLoweringBase::ZeroOrOneBooleanContent:
2450       OVF = DAG.getZExtOrTrunc(OVF, dl, NVT);
2451       Hi = DAG.getNode(N->getOpcode(), dl, NVT, Hi, OVF);
2452       break;
2453     case TargetLoweringBase::ZeroOrNegativeOneBooleanContent:
2454       OVF = DAG.getSExtOrTrunc(OVF, dl, NVT);
2455       Hi = DAG.getNode(RevOpc, dl, NVT, Hi, OVF);
2456     }
2457     return;
2458   }
2459 
2460   if (N->getOpcode() == ISD::ADD) {
2461     Lo = DAG.getNode(ISD::ADD, dl, NVT, LoOps);
2462     Hi = DAG.getNode(ISD::ADD, dl, NVT, makeArrayRef(HiOps, 2));
2463     SDValue Cmp1 = DAG.getSetCC(dl, getSetCCResultType(NVT), Lo, LoOps[0],
2464                                 ISD::SETULT);
2465 
2466     if (BoolType == TargetLoweringBase::ZeroOrOneBooleanContent) {
2467       SDValue Carry = DAG.getZExtOrTrunc(Cmp1, dl, NVT);
2468       Hi = DAG.getNode(ISD::ADD, dl, NVT, Hi, Carry);
2469       return;
2470     }
2471 
2472     SDValue Carry1 = DAG.getSelect(dl, NVT, Cmp1,
2473                                    DAG.getConstant(1, dl, NVT),
2474                                    DAG.getConstant(0, dl, NVT));
2475     SDValue Cmp2 = DAG.getSetCC(dl, getSetCCResultType(NVT), Lo, LoOps[1],
2476                                 ISD::SETULT);
2477     SDValue Carry2 = DAG.getSelect(dl, NVT, Cmp2,
2478                                    DAG.getConstant(1, dl, NVT), Carry1);
2479     Hi = DAG.getNode(ISD::ADD, dl, NVT, Hi, Carry2);
2480   } else {
2481     Lo = DAG.getNode(ISD::SUB, dl, NVT, LoOps);
2482     Hi = DAG.getNode(ISD::SUB, dl, NVT, makeArrayRef(HiOps, 2));
2483     SDValue Cmp =
2484       DAG.getSetCC(dl, getSetCCResultType(LoOps[0].getValueType()),
2485                    LoOps[0], LoOps[1], ISD::SETULT);
2486 
2487     SDValue Borrow;
2488     if (BoolType == TargetLoweringBase::ZeroOrOneBooleanContent)
2489       Borrow = DAG.getZExtOrTrunc(Cmp, dl, NVT);
2490     else
2491       Borrow = DAG.getSelect(dl, NVT, Cmp, DAG.getConstant(1, dl, NVT),
2492                              DAG.getConstant(0, dl, NVT));
2493 
2494     Hi = DAG.getNode(ISD::SUB, dl, NVT, Hi, Borrow);
2495   }
2496 }
2497 
2498 void DAGTypeLegalizer::ExpandIntRes_ADDSUBC(SDNode *N,
2499                                             SDValue &Lo, SDValue &Hi) {
2500   // Expand the subcomponents.
2501   SDValue LHSL, LHSH, RHSL, RHSH;
2502   SDLoc dl(N);
2503   GetExpandedInteger(N->getOperand(0), LHSL, LHSH);
2504   GetExpandedInteger(N->getOperand(1), RHSL, RHSH);
2505   SDVTList VTList = DAG.getVTList(LHSL.getValueType(), MVT::Glue);
2506   SDValue LoOps[2] = { LHSL, RHSL };
2507   SDValue HiOps[3] = { LHSH, RHSH };
2508 
2509   if (N->getOpcode() == ISD::ADDC) {
2510     Lo = DAG.getNode(ISD::ADDC, dl, VTList, LoOps);
2511     HiOps[2] = Lo.getValue(1);
2512     Hi = DAG.getNode(ISD::ADDE, dl, VTList, HiOps);
2513   } else {
2514     Lo = DAG.getNode(ISD::SUBC, dl, VTList, LoOps);
2515     HiOps[2] = Lo.getValue(1);
2516     Hi = DAG.getNode(ISD::SUBE, dl, VTList, HiOps);
2517   }
2518 
2519   // Legalized the flag result - switch anything that used the old flag to
2520   // use the new one.
2521   ReplaceValueWith(SDValue(N, 1), Hi.getValue(1));
2522 }
2523 
2524 void DAGTypeLegalizer::ExpandIntRes_ADDSUBE(SDNode *N,
2525                                             SDValue &Lo, SDValue &Hi) {
2526   // Expand the subcomponents.
2527   SDValue LHSL, LHSH, RHSL, RHSH;
2528   SDLoc dl(N);
2529   GetExpandedInteger(N->getOperand(0), LHSL, LHSH);
2530   GetExpandedInteger(N->getOperand(1), RHSL, RHSH);
2531   SDVTList VTList = DAG.getVTList(LHSL.getValueType(), MVT::Glue);
2532   SDValue LoOps[3] = { LHSL, RHSL, N->getOperand(2) };
2533   SDValue HiOps[3] = { LHSH, RHSH };
2534 
2535   Lo = DAG.getNode(N->getOpcode(), dl, VTList, LoOps);
2536   HiOps[2] = Lo.getValue(1);
2537   Hi = DAG.getNode(N->getOpcode(), dl, VTList, HiOps);
2538 
2539   // Legalized the flag result - switch anything that used the old flag to
2540   // use the new one.
2541   ReplaceValueWith(SDValue(N, 1), Hi.getValue(1));
2542 }
2543 
2544 void DAGTypeLegalizer::ExpandIntRes_UADDSUBO(SDNode *N,
2545                                              SDValue &Lo, SDValue &Hi) {
2546   SDValue LHS = N->getOperand(0);
2547   SDValue RHS = N->getOperand(1);
2548   SDLoc dl(N);
2549 
2550   SDValue Ovf;
2551 
2552   unsigned CarryOp, NoCarryOp;
2553   ISD::CondCode Cond;
2554   switch(N->getOpcode()) {
2555     case ISD::UADDO:
2556       CarryOp = ISD::ADDCARRY;
2557       NoCarryOp = ISD::ADD;
2558       Cond = ISD::SETULT;
2559       break;
2560     case ISD::USUBO:
2561       CarryOp = ISD::SUBCARRY;
2562       NoCarryOp = ISD::SUB;
2563       Cond = ISD::SETUGT;
2564       break;
2565     default:
2566       llvm_unreachable("Node has unexpected Opcode");
2567   }
2568 
2569   bool HasCarryOp = TLI.isOperationLegalOrCustom(
2570       CarryOp, TLI.getTypeToExpandTo(*DAG.getContext(), LHS.getValueType()));
2571 
2572   if (HasCarryOp) {
2573     // Expand the subcomponents.
2574     SDValue LHSL, LHSH, RHSL, RHSH;
2575     GetExpandedInteger(LHS, LHSL, LHSH);
2576     GetExpandedInteger(RHS, RHSL, RHSH);
2577     SDVTList VTList = DAG.getVTList(LHSL.getValueType(), N->getValueType(1));
2578     SDValue LoOps[2] = { LHSL, RHSL };
2579     SDValue HiOps[3] = { LHSH, RHSH };
2580 
2581     Lo = DAG.getNode(N->getOpcode(), dl, VTList, LoOps);
2582     HiOps[2] = Lo.getValue(1);
2583     Hi = DAG.getNode(CarryOp, dl, VTList, HiOps);
2584 
2585     Ovf = Hi.getValue(1);
2586   } else {
2587     // Expand the result by simply replacing it with the equivalent
2588     // non-overflow-checking operation.
2589     SDValue Sum = DAG.getNode(NoCarryOp, dl, LHS.getValueType(), LHS, RHS);
2590     SplitInteger(Sum, Lo, Hi);
2591 
2592     // Calculate the overflow: addition overflows iff a + b < a, and subtraction
2593     // overflows iff a - b > a.
2594     Ovf = DAG.getSetCC(dl, N->getValueType(1), Sum, LHS, Cond);
2595   }
2596 
2597   // Legalized the flag result - switch anything that used the old flag to
2598   // use the new one.
2599   ReplaceValueWith(SDValue(N, 1), Ovf);
2600 }
2601 
2602 void DAGTypeLegalizer::ExpandIntRes_ADDSUBCARRY(SDNode *N,
2603                                                 SDValue &Lo, SDValue &Hi) {
2604   // Expand the subcomponents.
2605   SDValue LHSL, LHSH, RHSL, RHSH;
2606   SDLoc dl(N);
2607   GetExpandedInteger(N->getOperand(0), LHSL, LHSH);
2608   GetExpandedInteger(N->getOperand(1), RHSL, RHSH);
2609   SDVTList VTList = DAG.getVTList(LHSL.getValueType(), N->getValueType(1));
2610   SDValue LoOps[3] = { LHSL, RHSL, N->getOperand(2) };
2611   SDValue HiOps[3] = { LHSH, RHSH, SDValue() };
2612 
2613   Lo = DAG.getNode(N->getOpcode(), dl, VTList, LoOps);
2614   HiOps[2] = Lo.getValue(1);
2615   Hi = DAG.getNode(N->getOpcode(), dl, VTList, HiOps);
2616 
2617   // Legalized the flag result - switch anything that used the old flag to
2618   // use the new one.
2619   ReplaceValueWith(SDValue(N, 1), Hi.getValue(1));
2620 }
2621 
2622 void DAGTypeLegalizer::ExpandIntRes_ANY_EXTEND(SDNode *N,
2623                                                SDValue &Lo, SDValue &Hi) {
2624   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
2625   SDLoc dl(N);
2626   SDValue Op = N->getOperand(0);
2627   if (Op.getValueType().bitsLE(NVT)) {
2628     // The low part is any extension of the input (which degenerates to a copy).
2629     Lo = DAG.getNode(ISD::ANY_EXTEND, dl, NVT, Op);
2630     Hi = DAG.getUNDEF(NVT);   // The high part is undefined.
2631   } else {
2632     // For example, extension of an i48 to an i64.  The operand type necessarily
2633     // promotes to the result type, so will end up being expanded too.
2634     assert(getTypeAction(Op.getValueType()) ==
2635            TargetLowering::TypePromoteInteger &&
2636            "Only know how to promote this result!");
2637     SDValue Res = GetPromotedInteger(Op);
2638     assert(Res.getValueType() == N->getValueType(0) &&
2639            "Operand over promoted?");
2640     // Split the promoted operand.  This will simplify when it is expanded.
2641     SplitInteger(Res, Lo, Hi);
2642   }
2643 }
2644 
2645 void DAGTypeLegalizer::ExpandIntRes_AssertSext(SDNode *N,
2646                                                SDValue &Lo, SDValue &Hi) {
2647   SDLoc dl(N);
2648   GetExpandedInteger(N->getOperand(0), Lo, Hi);
2649   EVT NVT = Lo.getValueType();
2650   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
2651   unsigned NVTBits = NVT.getSizeInBits();
2652   unsigned EVTBits = EVT.getSizeInBits();
2653 
2654   if (NVTBits < EVTBits) {
2655     Hi = DAG.getNode(ISD::AssertSext, dl, NVT, Hi,
2656                      DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(),
2657                                                         EVTBits - NVTBits)));
2658   } else {
2659     Lo = DAG.getNode(ISD::AssertSext, dl, NVT, Lo, DAG.getValueType(EVT));
2660     // The high part replicates the sign bit of Lo, make it explicit.
2661     Hi = DAG.getNode(ISD::SRA, dl, NVT, Lo,
2662                      DAG.getConstant(NVTBits - 1, dl,
2663                                      TLI.getPointerTy(DAG.getDataLayout())));
2664   }
2665 }
2666 
2667 void DAGTypeLegalizer::ExpandIntRes_AssertZext(SDNode *N,
2668                                                SDValue &Lo, SDValue &Hi) {
2669   SDLoc dl(N);
2670   GetExpandedInteger(N->getOperand(0), Lo, Hi);
2671   EVT NVT = Lo.getValueType();
2672   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
2673   unsigned NVTBits = NVT.getSizeInBits();
2674   unsigned EVTBits = EVT.getSizeInBits();
2675 
2676   if (NVTBits < EVTBits) {
2677     Hi = DAG.getNode(ISD::AssertZext, dl, NVT, Hi,
2678                      DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(),
2679                                                         EVTBits - NVTBits)));
2680   } else {
2681     Lo = DAG.getNode(ISD::AssertZext, dl, NVT, Lo, DAG.getValueType(EVT));
2682     // The high part must be zero, make it explicit.
2683     Hi = DAG.getConstant(0, dl, NVT);
2684   }
2685 }
2686 
2687 void DAGTypeLegalizer::ExpandIntRes_BITREVERSE(SDNode *N,
2688                                                SDValue &Lo, SDValue &Hi) {
2689   SDLoc dl(N);
2690   GetExpandedInteger(N->getOperand(0), Hi, Lo);  // Note swapped operands.
2691   Lo = DAG.getNode(ISD::BITREVERSE, dl, Lo.getValueType(), Lo);
2692   Hi = DAG.getNode(ISD::BITREVERSE, dl, Hi.getValueType(), Hi);
2693 }
2694 
2695 void DAGTypeLegalizer::ExpandIntRes_BSWAP(SDNode *N,
2696                                           SDValue &Lo, SDValue &Hi) {
2697   SDLoc dl(N);
2698   GetExpandedInteger(N->getOperand(0), Hi, Lo);  // Note swapped operands.
2699   Lo = DAG.getNode(ISD::BSWAP, dl, Lo.getValueType(), Lo);
2700   Hi = DAG.getNode(ISD::BSWAP, dl, Hi.getValueType(), Hi);
2701 }
2702 
2703 void DAGTypeLegalizer::ExpandIntRes_Constant(SDNode *N,
2704                                              SDValue &Lo, SDValue &Hi) {
2705   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
2706   unsigned NBitWidth = NVT.getSizeInBits();
2707   auto Constant = cast<ConstantSDNode>(N);
2708   const APInt &Cst = Constant->getAPIntValue();
2709   bool IsTarget = Constant->isTargetOpcode();
2710   bool IsOpaque = Constant->isOpaque();
2711   SDLoc dl(N);
2712   Lo = DAG.getConstant(Cst.trunc(NBitWidth), dl, NVT, IsTarget, IsOpaque);
2713   Hi = DAG.getConstant(Cst.lshr(NBitWidth).trunc(NBitWidth), dl, NVT, IsTarget,
2714                        IsOpaque);
2715 }
2716 
2717 void DAGTypeLegalizer::ExpandIntRes_ABS(SDNode *N, SDValue &Lo, SDValue &Hi) {
2718   SDLoc dl(N);
2719 
2720   // abs(HiLo) -> (Hi < 0 ? -HiLo : HiLo)
2721   EVT VT = N->getValueType(0);
2722   SDValue N0 = N->getOperand(0);
2723   SDValue Neg = DAG.getNode(ISD::SUB, dl, VT,
2724                             DAG.getConstant(0, dl, VT), N0);
2725   SDValue NegLo, NegHi;
2726   SplitInteger(Neg, NegLo, NegHi);
2727 
2728   GetExpandedInteger(N0, Lo, Hi);
2729   EVT NVT = Lo.getValueType();
2730   SDValue HiIsNeg = DAG.getSetCC(dl, getSetCCResultType(NVT),
2731                                  DAG.getConstant(0, dl, NVT), Hi, ISD::SETGT);
2732   Lo = DAG.getSelect(dl, NVT, HiIsNeg, NegLo, Lo);
2733   Hi = DAG.getSelect(dl, NVT, HiIsNeg, NegHi, Hi);
2734 }
2735 
2736 void DAGTypeLegalizer::ExpandIntRes_CTLZ(SDNode *N,
2737                                          SDValue &Lo, SDValue &Hi) {
2738   SDLoc dl(N);
2739   // ctlz (HiLo) -> Hi != 0 ? ctlz(Hi) : (ctlz(Lo)+32)
2740   GetExpandedInteger(N->getOperand(0), Lo, Hi);
2741   EVT NVT = Lo.getValueType();
2742 
2743   SDValue HiNotZero = DAG.getSetCC(dl, getSetCCResultType(NVT), Hi,
2744                                    DAG.getConstant(0, dl, NVT), ISD::SETNE);
2745 
2746   SDValue LoLZ = DAG.getNode(N->getOpcode(), dl, NVT, Lo);
2747   SDValue HiLZ = DAG.getNode(ISD::CTLZ_ZERO_UNDEF, dl, NVT, Hi);
2748 
2749   Lo = DAG.getSelect(dl, NVT, HiNotZero, HiLZ,
2750                      DAG.getNode(ISD::ADD, dl, NVT, LoLZ,
2751                                  DAG.getConstant(NVT.getSizeInBits(), dl,
2752                                                  NVT)));
2753   Hi = DAG.getConstant(0, dl, NVT);
2754 }
2755 
2756 void DAGTypeLegalizer::ExpandIntRes_CTPOP(SDNode *N,
2757                                           SDValue &Lo, SDValue &Hi) {
2758   SDLoc dl(N);
2759   // ctpop(HiLo) -> ctpop(Hi)+ctpop(Lo)
2760   GetExpandedInteger(N->getOperand(0), Lo, Hi);
2761   EVT NVT = Lo.getValueType();
2762   Lo = DAG.getNode(ISD::ADD, dl, NVT, DAG.getNode(ISD::CTPOP, dl, NVT, Lo),
2763                    DAG.getNode(ISD::CTPOP, dl, NVT, Hi));
2764   Hi = DAG.getConstant(0, dl, NVT);
2765 }
2766 
2767 void DAGTypeLegalizer::ExpandIntRes_CTTZ(SDNode *N,
2768                                          SDValue &Lo, SDValue &Hi) {
2769   SDLoc dl(N);
2770   // cttz (HiLo) -> Lo != 0 ? cttz(Lo) : (cttz(Hi)+32)
2771   GetExpandedInteger(N->getOperand(0), Lo, Hi);
2772   EVT NVT = Lo.getValueType();
2773 
2774   SDValue LoNotZero = DAG.getSetCC(dl, getSetCCResultType(NVT), Lo,
2775                                    DAG.getConstant(0, dl, NVT), ISD::SETNE);
2776 
2777   SDValue LoLZ = DAG.getNode(ISD::CTTZ_ZERO_UNDEF, dl, NVT, Lo);
2778   SDValue HiLZ = DAG.getNode(N->getOpcode(), dl, NVT, Hi);
2779 
2780   Lo = DAG.getSelect(dl, NVT, LoNotZero, LoLZ,
2781                      DAG.getNode(ISD::ADD, dl, NVT, HiLZ,
2782                                  DAG.getConstant(NVT.getSizeInBits(), dl,
2783                                                  NVT)));
2784   Hi = DAG.getConstant(0, dl, NVT);
2785 }
2786 
2787 void DAGTypeLegalizer::ExpandIntRes_FLT_ROUNDS(SDNode *N, SDValue &Lo,
2788                                                SDValue &Hi) {
2789   SDLoc dl(N);
2790   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
2791   unsigned NBitWidth = NVT.getSizeInBits();
2792 
2793   EVT ShiftAmtTy = TLI.getShiftAmountTy(NVT, DAG.getDataLayout());
2794   Lo = DAG.getNode(ISD::FLT_ROUNDS_, dl, {NVT, MVT::Other}, N->getOperand(0));
2795   SDValue Chain = Lo.getValue(1);
2796   // The high part is the sign of Lo, as -1 is a valid value for FLT_ROUNDS
2797   Hi = DAG.getNode(ISD::SRA, dl, NVT, Lo,
2798                    DAG.getConstant(NBitWidth - 1, dl, ShiftAmtTy));
2799 
2800   // Legalize the chain result - switch anything that used the old chain to
2801   // use the new one.
2802   ReplaceValueWith(SDValue(N, 1), Chain);
2803 }
2804 
2805 void DAGTypeLegalizer::ExpandIntRes_FP_TO_SINT(SDNode *N, SDValue &Lo,
2806                                                SDValue &Hi) {
2807   SDLoc dl(N);
2808   EVT VT = N->getValueType(0);
2809 
2810   bool IsStrict = N->isStrictFPOpcode();
2811   SDValue Chain = IsStrict ? N->getOperand(0) : SDValue();
2812   SDValue Op = N->getOperand(IsStrict ? 1 : 0);
2813   if (getTypeAction(Op.getValueType()) == TargetLowering::TypePromoteFloat)
2814     Op = GetPromotedFloat(Op);
2815 
2816   if (getTypeAction(Op.getValueType()) == TargetLowering::TypeSoftPromoteHalf) {
2817     EVT NFPVT = TLI.getTypeToTransformTo(*DAG.getContext(), Op.getValueType());
2818     Op = GetSoftPromotedHalf(Op);
2819     Op = DAG.getNode(ISD::FP16_TO_FP, dl, NFPVT, Op);
2820   }
2821 
2822   RTLIB::Libcall LC = RTLIB::getFPTOSINT(Op.getValueType(), VT);
2823   assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unexpected fp-to-sint conversion!");
2824   TargetLowering::MakeLibCallOptions CallOptions;
2825   CallOptions.setSExt(true);
2826   std::pair<SDValue, SDValue> Tmp = TLI.makeLibCall(DAG, LC, VT, Op,
2827                                                     CallOptions, dl, Chain);
2828   SplitInteger(Tmp.first, Lo, Hi);
2829 
2830   if (IsStrict)
2831     ReplaceValueWith(SDValue(N, 1), Tmp.second);
2832 }
2833 
2834 void DAGTypeLegalizer::ExpandIntRes_FP_TO_UINT(SDNode *N, SDValue &Lo,
2835                                                SDValue &Hi) {
2836   SDLoc dl(N);
2837   EVT VT = N->getValueType(0);
2838 
2839   bool IsStrict = N->isStrictFPOpcode();
2840   SDValue Chain = IsStrict ? N->getOperand(0) : SDValue();
2841   SDValue Op = N->getOperand(IsStrict ? 1 : 0);
2842   if (getTypeAction(Op.getValueType()) == TargetLowering::TypePromoteFloat)
2843     Op = GetPromotedFloat(Op);
2844 
2845   if (getTypeAction(Op.getValueType()) == TargetLowering::TypeSoftPromoteHalf) {
2846     EVT NFPVT = TLI.getTypeToTransformTo(*DAG.getContext(), Op.getValueType());
2847     Op = GetSoftPromotedHalf(Op);
2848     Op = DAG.getNode(ISD::FP16_TO_FP, dl, NFPVT, Op);
2849   }
2850 
2851   RTLIB::Libcall LC = RTLIB::getFPTOUINT(Op.getValueType(), VT);
2852   assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unexpected fp-to-uint conversion!");
2853   TargetLowering::MakeLibCallOptions CallOptions;
2854   std::pair<SDValue, SDValue> Tmp = TLI.makeLibCall(DAG, LC, VT, Op,
2855                                                     CallOptions, dl, Chain);
2856   SplitInteger(Tmp.first, Lo, Hi);
2857 
2858   if (IsStrict)
2859     ReplaceValueWith(SDValue(N, 1), Tmp.second);
2860 }
2861 
2862 void DAGTypeLegalizer::ExpandIntRes_LLROUND_LLRINT(SDNode *N, SDValue &Lo,
2863                                                    SDValue &Hi) {
2864   SDValue Op = N->getOperand(N->isStrictFPOpcode() ? 1 : 0);
2865 
2866   assert(getTypeAction(Op.getValueType()) != TargetLowering::TypePromoteFloat &&
2867          "Input type needs to be promoted!");
2868 
2869   EVT VT = Op.getValueType();
2870 
2871   RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
2872   if (N->getOpcode() == ISD::LLROUND ||
2873       N->getOpcode() == ISD::STRICT_LLROUND) {
2874     if (VT == MVT::f32)
2875       LC = RTLIB::LLROUND_F32;
2876     else if (VT == MVT::f64)
2877       LC = RTLIB::LLROUND_F64;
2878     else if (VT == MVT::f80)
2879       LC = RTLIB::LLROUND_F80;
2880     else if (VT == MVT::f128)
2881       LC = RTLIB::LLROUND_F128;
2882     else if (VT == MVT::ppcf128)
2883       LC = RTLIB::LLROUND_PPCF128;
2884     assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unexpected llround input type!");
2885   } else if (N->getOpcode() == ISD::LLRINT ||
2886              N->getOpcode() == ISD::STRICT_LLRINT) {
2887     if (VT == MVT::f32)
2888       LC = RTLIB::LLRINT_F32;
2889     else if (VT == MVT::f64)
2890       LC = RTLIB::LLRINT_F64;
2891     else if (VT == MVT::f80)
2892       LC = RTLIB::LLRINT_F80;
2893     else if (VT == MVT::f128)
2894       LC = RTLIB::LLRINT_F128;
2895     else if (VT == MVT::ppcf128)
2896       LC = RTLIB::LLRINT_PPCF128;
2897     assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unexpected llrint input type!");
2898   } else
2899     llvm_unreachable("Unexpected opcode!");
2900 
2901   SDLoc dl(N);
2902   EVT RetVT = N->getValueType(0);
2903   SDValue Chain = N->isStrictFPOpcode() ? N->getOperand(0) : SDValue();
2904 
2905   TargetLowering::MakeLibCallOptions CallOptions;
2906   CallOptions.setSExt(true);
2907   std::pair<SDValue, SDValue> Tmp = TLI.makeLibCall(DAG, LC, RetVT,
2908                                                     Op, CallOptions, dl,
2909                                                     Chain);
2910   SplitInteger(Tmp.first, Lo, Hi);
2911 
2912   if (N->isStrictFPOpcode())
2913     ReplaceValueWith(SDValue(N, 1), Tmp.second);
2914 }
2915 
2916 void DAGTypeLegalizer::ExpandIntRes_LOAD(LoadSDNode *N,
2917                                          SDValue &Lo, SDValue &Hi) {
2918   if (N->isAtomic()) {
2919     // It's typical to have larger CAS than atomic load instructions.
2920     SDLoc dl(N);
2921     EVT VT = N->getMemoryVT();
2922     SDVTList VTs = DAG.getVTList(VT, MVT::i1, MVT::Other);
2923     SDValue Zero = DAG.getConstant(0, dl, VT);
2924     SDValue Swap = DAG.getAtomicCmpSwap(
2925         ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, dl,
2926         VT, VTs, N->getOperand(0),
2927         N->getOperand(1), Zero, Zero, N->getMemOperand());
2928     ReplaceValueWith(SDValue(N, 0), Swap.getValue(0));
2929     ReplaceValueWith(SDValue(N, 1), Swap.getValue(2));
2930     return;
2931   }
2932 
2933   if (ISD::isNormalLoad(N)) {
2934     ExpandRes_NormalLoad(N, Lo, Hi);
2935     return;
2936   }
2937 
2938   assert(ISD::isUNINDEXEDLoad(N) && "Indexed load during type legalization!");
2939 
2940   EVT VT = N->getValueType(0);
2941   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), VT);
2942   SDValue Ch  = N->getChain();
2943   SDValue Ptr = N->getBasePtr();
2944   ISD::LoadExtType ExtType = N->getExtensionType();
2945   MachineMemOperand::Flags MMOFlags = N->getMemOperand()->getFlags();
2946   AAMDNodes AAInfo = N->getAAInfo();
2947   SDLoc dl(N);
2948 
2949   assert(NVT.isByteSized() && "Expanded type not byte sized!");
2950 
2951   if (N->getMemoryVT().bitsLE(NVT)) {
2952     EVT MemVT = N->getMemoryVT();
2953 
2954     Lo = DAG.getExtLoad(ExtType, dl, NVT, Ch, Ptr, N->getPointerInfo(), MemVT,
2955                         N->getOriginalAlign(), MMOFlags, AAInfo);
2956 
2957     // Remember the chain.
2958     Ch = Lo.getValue(1);
2959 
2960     if (ExtType == ISD::SEXTLOAD) {
2961       // The high part is obtained by SRA'ing all but one of the bits of the
2962       // lo part.
2963       unsigned LoSize = Lo.getValueSizeInBits();
2964       Hi = DAG.getNode(ISD::SRA, dl, NVT, Lo,
2965                        DAG.getConstant(LoSize - 1, dl,
2966                                        TLI.getPointerTy(DAG.getDataLayout())));
2967     } else if (ExtType == ISD::ZEXTLOAD) {
2968       // The high part is just a zero.
2969       Hi = DAG.getConstant(0, dl, NVT);
2970     } else {
2971       assert(ExtType == ISD::EXTLOAD && "Unknown extload!");
2972       // The high part is undefined.
2973       Hi = DAG.getUNDEF(NVT);
2974     }
2975   } else if (DAG.getDataLayout().isLittleEndian()) {
2976     // Little-endian - low bits are at low addresses.
2977     Lo = DAG.getLoad(NVT, dl, Ch, Ptr, N->getPointerInfo(),
2978                      N->getOriginalAlign(), MMOFlags, AAInfo);
2979 
2980     unsigned ExcessBits =
2981       N->getMemoryVT().getSizeInBits() - NVT.getSizeInBits();
2982     EVT NEVT = EVT::getIntegerVT(*DAG.getContext(), ExcessBits);
2983 
2984     // Increment the pointer to the other half.
2985     unsigned IncrementSize = NVT.getSizeInBits()/8;
2986     Ptr = DAG.getMemBasePlusOffset(Ptr, IncrementSize, dl);
2987     Hi = DAG.getExtLoad(ExtType, dl, NVT, Ch, Ptr,
2988                         N->getPointerInfo().getWithOffset(IncrementSize), NEVT,
2989                         N->getOriginalAlign(), MMOFlags, AAInfo);
2990 
2991     // Build a factor node to remember that this load is independent of the
2992     // other one.
2993     Ch = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1),
2994                      Hi.getValue(1));
2995   } else {
2996     // Big-endian - high bits are at low addresses.  Favor aligned loads at
2997     // the cost of some bit-fiddling.
2998     EVT MemVT = N->getMemoryVT();
2999     unsigned EBytes = MemVT.getStoreSize();
3000     unsigned IncrementSize = NVT.getSizeInBits()/8;
3001     unsigned ExcessBits = (EBytes - IncrementSize)*8;
3002 
3003     // Load both the high bits and maybe some of the low bits.
3004     Hi = DAG.getExtLoad(ExtType, dl, NVT, Ch, Ptr, N->getPointerInfo(),
3005                         EVT::getIntegerVT(*DAG.getContext(),
3006                                           MemVT.getSizeInBits() - ExcessBits),
3007                         N->getOriginalAlign(), MMOFlags, AAInfo);
3008 
3009     // Increment the pointer to the other half.
3010     Ptr = DAG.getMemBasePlusOffset(Ptr, IncrementSize, dl);
3011     // Load the rest of the low bits.
3012     Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, NVT, Ch, Ptr,
3013                         N->getPointerInfo().getWithOffset(IncrementSize),
3014                         EVT::getIntegerVT(*DAG.getContext(), ExcessBits),
3015                         N->getOriginalAlign(), MMOFlags, AAInfo);
3016 
3017     // Build a factor node to remember that this load is independent of the
3018     // other one.
3019     Ch = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1),
3020                      Hi.getValue(1));
3021 
3022     if (ExcessBits < NVT.getSizeInBits()) {
3023       // Transfer low bits from the bottom of Hi to the top of Lo.
3024       Lo = DAG.getNode(
3025           ISD::OR, dl, NVT, Lo,
3026           DAG.getNode(ISD::SHL, dl, NVT, Hi,
3027                       DAG.getConstant(ExcessBits, dl,
3028                                       TLI.getPointerTy(DAG.getDataLayout()))));
3029       // Move high bits to the right position in Hi.
3030       Hi = DAG.getNode(ExtType == ISD::SEXTLOAD ? ISD::SRA : ISD::SRL, dl, NVT,
3031                        Hi,
3032                        DAG.getConstant(NVT.getSizeInBits() - ExcessBits, dl,
3033                                        TLI.getPointerTy(DAG.getDataLayout())));
3034     }
3035   }
3036 
3037   // Legalize the chain result - switch anything that used the old chain to
3038   // use the new one.
3039   ReplaceValueWith(SDValue(N, 1), Ch);
3040 }
3041 
3042 void DAGTypeLegalizer::ExpandIntRes_Logical(SDNode *N,
3043                                             SDValue &Lo, SDValue &Hi) {
3044   SDLoc dl(N);
3045   SDValue LL, LH, RL, RH;
3046   GetExpandedInteger(N->getOperand(0), LL, LH);
3047   GetExpandedInteger(N->getOperand(1), RL, RH);
3048   Lo = DAG.getNode(N->getOpcode(), dl, LL.getValueType(), LL, RL);
3049   Hi = DAG.getNode(N->getOpcode(), dl, LL.getValueType(), LH, RH);
3050 }
3051 
3052 void DAGTypeLegalizer::ExpandIntRes_MUL(SDNode *N,
3053                                         SDValue &Lo, SDValue &Hi) {
3054   EVT VT = N->getValueType(0);
3055   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), VT);
3056   SDLoc dl(N);
3057 
3058   SDValue LL, LH, RL, RH;
3059   GetExpandedInteger(N->getOperand(0), LL, LH);
3060   GetExpandedInteger(N->getOperand(1), RL, RH);
3061 
3062   if (TLI.expandMUL(N, Lo, Hi, NVT, DAG,
3063                     TargetLowering::MulExpansionKind::OnlyLegalOrCustom,
3064                     LL, LH, RL, RH))
3065     return;
3066 
3067   // If nothing else, we can make a libcall.
3068   RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
3069   if (VT == MVT::i16)
3070     LC = RTLIB::MUL_I16;
3071   else if (VT == MVT::i32)
3072     LC = RTLIB::MUL_I32;
3073   else if (VT == MVT::i64)
3074     LC = RTLIB::MUL_I64;
3075   else if (VT == MVT::i128)
3076     LC = RTLIB::MUL_I128;
3077 
3078   if (LC == RTLIB::UNKNOWN_LIBCALL || !TLI.getLibcallName(LC)) {
3079     // We'll expand the multiplication by brute force because we have no other
3080     // options. This is a trivially-generalized version of the code from
3081     // Hacker's Delight (itself derived from Knuth's Algorithm M from section
3082     // 4.3.1).
3083     unsigned Bits = NVT.getSizeInBits();
3084     unsigned HalfBits = Bits >> 1;
3085     SDValue Mask = DAG.getConstant(APInt::getLowBitsSet(Bits, HalfBits), dl,
3086                                    NVT);
3087     SDValue LLL = DAG.getNode(ISD::AND, dl, NVT, LL, Mask);
3088     SDValue RLL = DAG.getNode(ISD::AND, dl, NVT, RL, Mask);
3089 
3090     SDValue T = DAG.getNode(ISD::MUL, dl, NVT, LLL, RLL);
3091     SDValue TL = DAG.getNode(ISD::AND, dl, NVT, T, Mask);
3092 
3093     EVT ShiftAmtTy = TLI.getShiftAmountTy(NVT, DAG.getDataLayout());
3094     if (APInt::getMaxValue(ShiftAmtTy.getSizeInBits()).ult(HalfBits)) {
3095       // The type from TLI is too small to fit the shift amount we want.
3096       // Override it with i32. The shift will have to be legalized.
3097       ShiftAmtTy = MVT::i32;
3098     }
3099     SDValue Shift = DAG.getConstant(HalfBits, dl, ShiftAmtTy);
3100     SDValue TH = DAG.getNode(ISD::SRL, dl, NVT, T, Shift);
3101     SDValue LLH = DAG.getNode(ISD::SRL, dl, NVT, LL, Shift);
3102     SDValue RLH = DAG.getNode(ISD::SRL, dl, NVT, RL, Shift);
3103 
3104     SDValue U = DAG.getNode(ISD::ADD, dl, NVT,
3105                             DAG.getNode(ISD::MUL, dl, NVT, LLH, RLL), TH);
3106     SDValue UL = DAG.getNode(ISD::AND, dl, NVT, U, Mask);
3107     SDValue UH = DAG.getNode(ISD::SRL, dl, NVT, U, Shift);
3108 
3109     SDValue V = DAG.getNode(ISD::ADD, dl, NVT,
3110                             DAG.getNode(ISD::MUL, dl, NVT, LLL, RLH), UL);
3111     SDValue VH = DAG.getNode(ISD::SRL, dl, NVT, V, Shift);
3112 
3113     SDValue W = DAG.getNode(ISD::ADD, dl, NVT,
3114                             DAG.getNode(ISD::MUL, dl, NVT, LLH, RLH),
3115                             DAG.getNode(ISD::ADD, dl, NVT, UH, VH));
3116     Lo = DAG.getNode(ISD::ADD, dl, NVT, TL,
3117                      DAG.getNode(ISD::SHL, dl, NVT, V, Shift));
3118 
3119     Hi = DAG.getNode(ISD::ADD, dl, NVT, W,
3120                      DAG.getNode(ISD::ADD, dl, NVT,
3121                                  DAG.getNode(ISD::MUL, dl, NVT, RH, LL),
3122                                  DAG.getNode(ISD::MUL, dl, NVT, RL, LH)));
3123     return;
3124   }
3125 
3126   SDValue Ops[2] = { N->getOperand(0), N->getOperand(1) };
3127   TargetLowering::MakeLibCallOptions CallOptions;
3128   CallOptions.setSExt(true);
3129   SplitInteger(TLI.makeLibCall(DAG, LC, VT, Ops, CallOptions, dl).first,
3130                Lo, Hi);
3131 }
3132 
3133 void DAGTypeLegalizer::ExpandIntRes_READCYCLECOUNTER(SDNode *N, SDValue &Lo,
3134                                                      SDValue &Hi) {
3135   SDLoc DL(N);
3136   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
3137   SDVTList VTs = DAG.getVTList(NVT, NVT, MVT::Other);
3138   SDValue R = DAG.getNode(N->getOpcode(), DL, VTs, N->getOperand(0));
3139   Lo = R.getValue(0);
3140   Hi = R.getValue(1);
3141   ReplaceValueWith(SDValue(N, 1), R.getValue(2));
3142 }
3143 
3144 void DAGTypeLegalizer::ExpandIntRes_ADDSUBSAT(SDNode *N, SDValue &Lo,
3145                                               SDValue &Hi) {
3146   SDValue Result = TLI.expandAddSubSat(N, DAG);
3147   SplitInteger(Result, Lo, Hi);
3148 }
3149 
3150 /// This performs an expansion of the integer result for a fixed point
3151 /// multiplication. The default expansion performs rounding down towards
3152 /// negative infinity, though targets that do care about rounding should specify
3153 /// a target hook for rounding and provide their own expansion or lowering of
3154 /// fixed point multiplication to be consistent with rounding.
3155 void DAGTypeLegalizer::ExpandIntRes_MULFIX(SDNode *N, SDValue &Lo,
3156                                            SDValue &Hi) {
3157   SDLoc dl(N);
3158   EVT VT = N->getValueType(0);
3159   unsigned VTSize = VT.getScalarSizeInBits();
3160   SDValue LHS = N->getOperand(0);
3161   SDValue RHS = N->getOperand(1);
3162   uint64_t Scale = N->getConstantOperandVal(2);
3163   bool Saturating = (N->getOpcode() == ISD::SMULFIXSAT ||
3164                      N->getOpcode() == ISD::UMULFIXSAT);
3165   bool Signed = (N->getOpcode() == ISD::SMULFIX ||
3166                  N->getOpcode() == ISD::SMULFIXSAT);
3167 
3168   // Handle special case when scale is equal to zero.
3169   if (!Scale) {
3170     SDValue Result;
3171     if (!Saturating) {
3172       Result = DAG.getNode(ISD::MUL, dl, VT, LHS, RHS);
3173     } else {
3174       EVT BoolVT = getSetCCResultType(VT);
3175       unsigned MulOp = Signed ? ISD::SMULO : ISD::UMULO;
3176       Result = DAG.getNode(MulOp, dl, DAG.getVTList(VT, BoolVT), LHS, RHS);
3177       SDValue Product = Result.getValue(0);
3178       SDValue Overflow = Result.getValue(1);
3179       if (Signed) {
3180         APInt MinVal = APInt::getSignedMinValue(VTSize);
3181         APInt MaxVal = APInt::getSignedMaxValue(VTSize);
3182         SDValue SatMin = DAG.getConstant(MinVal, dl, VT);
3183         SDValue SatMax = DAG.getConstant(MaxVal, dl, VT);
3184         SDValue Zero = DAG.getConstant(0, dl, VT);
3185         SDValue ProdNeg = DAG.getSetCC(dl, BoolVT, Product, Zero, ISD::SETLT);
3186         Result = DAG.getSelect(dl, VT, ProdNeg, SatMax, SatMin);
3187         Result = DAG.getSelect(dl, VT, Overflow, Result, Product);
3188       } else {
3189         // For unsigned multiplication, we only need to check the max since we
3190         // can't really overflow towards zero.
3191         APInt MaxVal = APInt::getMaxValue(VTSize);
3192         SDValue SatMax = DAG.getConstant(MaxVal, dl, VT);
3193         Result = DAG.getSelect(dl, VT, Overflow, SatMax, Product);
3194       }
3195     }
3196     SplitInteger(Result, Lo, Hi);
3197     return;
3198   }
3199 
3200   // For SMULFIX[SAT] we only expect to find Scale<VTSize, but this assert will
3201   // cover for unhandled cases below, while still being valid for UMULFIX[SAT].
3202   assert(Scale <= VTSize && "Scale can't be larger than the value type size.");
3203 
3204   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), VT);
3205   SDValue LL, LH, RL, RH;
3206   GetExpandedInteger(LHS, LL, LH);
3207   GetExpandedInteger(RHS, RL, RH);
3208   SmallVector<SDValue, 4> Result;
3209 
3210   unsigned LoHiOp = Signed ? ISD::SMUL_LOHI : ISD::UMUL_LOHI;
3211   if (!TLI.expandMUL_LOHI(LoHiOp, VT, dl, LHS, RHS, Result, NVT, DAG,
3212                           TargetLowering::MulExpansionKind::OnlyLegalOrCustom,
3213                           LL, LH, RL, RH)) {
3214     report_fatal_error("Unable to expand MUL_FIX using MUL_LOHI.");
3215     return;
3216   }
3217 
3218   unsigned NVTSize = NVT.getScalarSizeInBits();
3219   assert((VTSize == NVTSize * 2) && "Expected the new value type to be half "
3220                                     "the size of the current value type");
3221   EVT ShiftTy = TLI.getShiftAmountTy(NVT, DAG.getDataLayout());
3222 
3223   // After getting the multiplication result in 4 parts, we need to perform a
3224   // shift right by the amount of the scale to get the result in that scale.
3225   //
3226   // Let's say we multiply 2 64 bit numbers. The resulting value can be held in
3227   // 128 bits that are cut into 4 32-bit parts:
3228   //
3229   //      HH       HL       LH       LL
3230   //  |---32---|---32---|---32---|---32---|
3231   // 128      96       64       32        0
3232   //
3233   //                    |------VTSize-----|
3234   //
3235   //                             |NVTSize-|
3236   //
3237   // The resulting Lo and Hi would normally be in LL and LH after the shift. But
3238   // to avoid unneccessary shifting of all 4 parts, we can adjust the shift
3239   // amount and get Lo and Hi using two funnel shifts. Or for the special case
3240   // when Scale is a multiple of NVTSize we can just pick the result without
3241   // shifting.
3242   uint64_t Part0 = Scale / NVTSize; // Part holding lowest bit needed.
3243   if (Scale % NVTSize) {
3244     SDValue ShiftAmount = DAG.getConstant(Scale % NVTSize, dl, ShiftTy);
3245     Lo = DAG.getNode(ISD::FSHR, dl, NVT, Result[Part0 + 1], Result[Part0],
3246                      ShiftAmount);
3247     Hi = DAG.getNode(ISD::FSHR, dl, NVT, Result[Part0 + 2], Result[Part0 + 1],
3248                      ShiftAmount);
3249   } else {
3250     Lo = Result[Part0];
3251     Hi = Result[Part0 + 1];
3252   }
3253 
3254   // Unless saturation is requested we are done. The result is in <Hi,Lo>.
3255   if (!Saturating)
3256     return;
3257 
3258   // Can not overflow when there is no integer part.
3259   if (Scale == VTSize)
3260     return;
3261 
3262   // To handle saturation we must check for overflow in the multiplication.
3263   //
3264   // Unsigned overflow happened if the upper (VTSize - Scale) bits (of Result)
3265   // aren't all zeroes.
3266   //
3267   // Signed overflow happened if the upper (VTSize - Scale + 1) bits (of Result)
3268   // aren't all ones or all zeroes.
3269   //
3270   // We cannot overflow past HH when multiplying 2 ints of size VTSize, so the
3271   // highest bit of HH determines saturation direction in the event of signed
3272   // saturation.
3273 
3274   SDValue ResultHL = Result[2];
3275   SDValue ResultHH = Result[3];
3276 
3277   SDValue SatMax, SatMin;
3278   SDValue NVTZero = DAG.getConstant(0, dl, NVT);
3279   SDValue NVTNeg1 = DAG.getConstant(-1, dl, NVT);
3280   EVT BoolNVT = getSetCCResultType(NVT);
3281 
3282   if (!Signed) {
3283     if (Scale < NVTSize) {
3284       // Overflow happened if ((HH | (HL >> Scale)) != 0).
3285       SDValue HLAdjusted = DAG.getNode(ISD::SRL, dl, NVT, ResultHL,
3286                                        DAG.getConstant(Scale, dl, ShiftTy));
3287       SDValue Tmp = DAG.getNode(ISD::OR, dl, NVT, HLAdjusted, ResultHH);
3288       SatMax = DAG.getSetCC(dl, BoolNVT, Tmp, NVTZero, ISD::SETNE);
3289     } else if (Scale == NVTSize) {
3290       // Overflow happened if (HH != 0).
3291       SatMax = DAG.getSetCC(dl, BoolNVT, ResultHH, NVTZero, ISD::SETNE);
3292     } else if (Scale < VTSize) {
3293       // Overflow happened if ((HH >> (Scale - NVTSize)) != 0).
3294       SDValue HLAdjusted = DAG.getNode(ISD::SRL, dl, NVT, ResultHL,
3295                                        DAG.getConstant(Scale - NVTSize, dl,
3296                                                        ShiftTy));
3297       SatMax = DAG.getSetCC(dl, BoolNVT, HLAdjusted, NVTZero, ISD::SETNE);
3298     } else
3299       llvm_unreachable("Scale must be less or equal to VTSize for UMULFIXSAT"
3300                        "(and saturation can't happen with Scale==VTSize).");
3301 
3302     Hi = DAG.getSelect(dl, NVT, SatMax, NVTNeg1, Hi);
3303     Lo = DAG.getSelect(dl, NVT, SatMax, NVTNeg1, Lo);
3304     return;
3305   }
3306 
3307   if (Scale < NVTSize) {
3308     // The number of overflow bits we can check are VTSize - Scale + 1 (we
3309     // include the sign bit). If these top bits are > 0, then we overflowed past
3310     // the max value. If these top bits are < -1, then we overflowed past the
3311     // min value. Otherwise, we did not overflow.
3312     unsigned OverflowBits = VTSize - Scale + 1;
3313     assert(OverflowBits <= VTSize && OverflowBits > NVTSize &&
3314            "Extent of overflow bits must start within HL");
3315     SDValue HLHiMask = DAG.getConstant(
3316         APInt::getHighBitsSet(NVTSize, OverflowBits - NVTSize), dl, NVT);
3317     SDValue HLLoMask = DAG.getConstant(
3318         APInt::getLowBitsSet(NVTSize, VTSize - OverflowBits), dl, NVT);
3319     // We overflow max if HH > 0 or (HH == 0 && HL > HLLoMask).
3320     SDValue HHGT0 = DAG.getSetCC(dl, BoolNVT, ResultHH, NVTZero, ISD::SETGT);
3321     SDValue HHEQ0 = DAG.getSetCC(dl, BoolNVT, ResultHH, NVTZero, ISD::SETEQ);
3322     SDValue HLUGT = DAG.getSetCC(dl, BoolNVT, ResultHL, HLLoMask, ISD::SETUGT);
3323     SatMax = DAG.getNode(ISD::OR, dl, BoolNVT, HHGT0,
3324                          DAG.getNode(ISD::AND, dl, BoolNVT, HHEQ0, HLUGT));
3325     // We overflow min if HH < -1 or (HH == -1 && HL < HLHiMask).
3326     SDValue HHLT = DAG.getSetCC(dl, BoolNVT, ResultHH, NVTNeg1, ISD::SETLT);
3327     SDValue HHEQ = DAG.getSetCC(dl, BoolNVT, ResultHH, NVTNeg1, ISD::SETEQ);
3328     SDValue HLULT = DAG.getSetCC(dl, BoolNVT, ResultHL, HLHiMask, ISD::SETULT);
3329     SatMin = DAG.getNode(ISD::OR, dl, BoolNVT, HHLT,
3330                          DAG.getNode(ISD::AND, dl, BoolNVT, HHEQ, HLULT));
3331   } else if (Scale == NVTSize) {
3332     // We overflow max if HH > 0 or (HH == 0 && HL sign bit is 1).
3333     SDValue HHGT0 = DAG.getSetCC(dl, BoolNVT, ResultHH, NVTZero, ISD::SETGT);
3334     SDValue HHEQ0 = DAG.getSetCC(dl, BoolNVT, ResultHH, NVTZero, ISD::SETEQ);
3335     SDValue HLNeg = DAG.getSetCC(dl, BoolNVT, ResultHL, NVTZero, ISD::SETLT);
3336     SatMax = DAG.getNode(ISD::OR, dl, BoolNVT, HHGT0,
3337                          DAG.getNode(ISD::AND, dl, BoolNVT, HHEQ0, HLNeg));
3338     // We overflow min if HH < -1 or (HH == -1 && HL sign bit is 0).
3339     SDValue HHLT = DAG.getSetCC(dl, BoolNVT, ResultHH, NVTNeg1, ISD::SETLT);
3340     SDValue HHEQ = DAG.getSetCC(dl, BoolNVT, ResultHH, NVTNeg1, ISD::SETEQ);
3341     SDValue HLPos = DAG.getSetCC(dl, BoolNVT, ResultHL, NVTZero, ISD::SETGE);
3342     SatMin = DAG.getNode(ISD::OR, dl, BoolNVT, HHLT,
3343                          DAG.getNode(ISD::AND, dl, BoolNVT, HHEQ, HLPos));
3344   } else if (Scale < VTSize) {
3345     // This is similar to the case when we saturate if Scale < NVTSize, but we
3346     // only need to check HH.
3347     unsigned OverflowBits = VTSize - Scale + 1;
3348     SDValue HHHiMask = DAG.getConstant(
3349         APInt::getHighBitsSet(NVTSize, OverflowBits), dl, NVT);
3350     SDValue HHLoMask = DAG.getConstant(
3351         APInt::getLowBitsSet(NVTSize, NVTSize - OverflowBits), dl, NVT);
3352     SatMax = DAG.getSetCC(dl, BoolNVT, ResultHH, HHLoMask, ISD::SETGT);
3353     SatMin = DAG.getSetCC(dl, BoolNVT, ResultHH, HHHiMask, ISD::SETLT);
3354   } else
3355     llvm_unreachable("Illegal scale for signed fixed point mul.");
3356 
3357   // Saturate to signed maximum.
3358   APInt MaxHi = APInt::getSignedMaxValue(NVTSize);
3359   APInt MaxLo = APInt::getAllOnesValue(NVTSize);
3360   Hi = DAG.getSelect(dl, NVT, SatMax, DAG.getConstant(MaxHi, dl, NVT), Hi);
3361   Lo = DAG.getSelect(dl, NVT, SatMax, DAG.getConstant(MaxLo, dl, NVT), Lo);
3362   // Saturate to signed minimum.
3363   APInt MinHi = APInt::getSignedMinValue(NVTSize);
3364   Hi = DAG.getSelect(dl, NVT, SatMin, DAG.getConstant(MinHi, dl, NVT), Hi);
3365   Lo = DAG.getSelect(dl, NVT, SatMin, NVTZero, Lo);
3366 }
3367 
3368 void DAGTypeLegalizer::ExpandIntRes_DIVFIX(SDNode *N, SDValue &Lo,
3369                                            SDValue &Hi) {
3370   SDLoc dl(N);
3371   // Try expanding in the existing type first.
3372   SDValue Res = TLI.expandFixedPointDiv(N->getOpcode(), dl, N->getOperand(0),
3373                                         N->getOperand(1),
3374                                         N->getConstantOperandVal(2), DAG);
3375 
3376   if (!Res)
3377     Res = earlyExpandDIVFIX(N, N->getOperand(0), N->getOperand(1),
3378                             N->getConstantOperandVal(2), TLI, DAG);
3379   SplitInteger(Res, Lo, Hi);
3380 }
3381 
3382 void DAGTypeLegalizer::ExpandIntRes_SADDSUBO(SDNode *Node,
3383                                              SDValue &Lo, SDValue &Hi) {
3384   SDValue LHS = Node->getOperand(0);
3385   SDValue RHS = Node->getOperand(1);
3386   SDLoc dl(Node);
3387 
3388   // Expand the result by simply replacing it with the equivalent
3389   // non-overflow-checking operation.
3390   SDValue Sum = DAG.getNode(Node->getOpcode() == ISD::SADDO ?
3391                             ISD::ADD : ISD::SUB, dl, LHS.getValueType(),
3392                             LHS, RHS);
3393   SplitInteger(Sum, Lo, Hi);
3394 
3395   // Compute the overflow.
3396   //
3397   //   LHSSign -> LHS >= 0
3398   //   RHSSign -> RHS >= 0
3399   //   SumSign -> Sum >= 0
3400   //
3401   //   Add:
3402   //   Overflow -> (LHSSign == RHSSign) && (LHSSign != SumSign)
3403   //   Sub:
3404   //   Overflow -> (LHSSign != RHSSign) && (LHSSign != SumSign)
3405   //
3406   EVT OType = Node->getValueType(1);
3407   SDValue Zero = DAG.getConstant(0, dl, LHS.getValueType());
3408 
3409   SDValue LHSSign = DAG.getSetCC(dl, OType, LHS, Zero, ISD::SETGE);
3410   SDValue RHSSign = DAG.getSetCC(dl, OType, RHS, Zero, ISD::SETGE);
3411   SDValue SignsMatch = DAG.getSetCC(dl, OType, LHSSign, RHSSign,
3412                                     Node->getOpcode() == ISD::SADDO ?
3413                                     ISD::SETEQ : ISD::SETNE);
3414 
3415   SDValue SumSign = DAG.getSetCC(dl, OType, Sum, Zero, ISD::SETGE);
3416   SDValue SumSignNE = DAG.getSetCC(dl, OType, LHSSign, SumSign, ISD::SETNE);
3417 
3418   SDValue Cmp = DAG.getNode(ISD::AND, dl, OType, SignsMatch, SumSignNE);
3419 
3420   // Use the calculated overflow everywhere.
3421   ReplaceValueWith(SDValue(Node, 1), Cmp);
3422 }
3423 
3424 void DAGTypeLegalizer::ExpandIntRes_SDIV(SDNode *N,
3425                                          SDValue &Lo, SDValue &Hi) {
3426   EVT VT = N->getValueType(0);
3427   SDLoc dl(N);
3428   SDValue Ops[2] = { N->getOperand(0), N->getOperand(1) };
3429 
3430   if (TLI.getOperationAction(ISD::SDIVREM, VT) == TargetLowering::Custom) {
3431     SDValue Res = DAG.getNode(ISD::SDIVREM, dl, DAG.getVTList(VT, VT), Ops);
3432     SplitInteger(Res.getValue(0), Lo, Hi);
3433     return;
3434   }
3435 
3436   RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
3437   if (VT == MVT::i16)
3438     LC = RTLIB::SDIV_I16;
3439   else if (VT == MVT::i32)
3440     LC = RTLIB::SDIV_I32;
3441   else if (VT == MVT::i64)
3442     LC = RTLIB::SDIV_I64;
3443   else if (VT == MVT::i128)
3444     LC = RTLIB::SDIV_I128;
3445   assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unsupported SDIV!");
3446 
3447   TargetLowering::MakeLibCallOptions CallOptions;
3448   CallOptions.setSExt(true);
3449   SplitInteger(TLI.makeLibCall(DAG, LC, VT, Ops, CallOptions, dl).first, Lo, Hi);
3450 }
3451 
3452 void DAGTypeLegalizer::ExpandIntRes_Shift(SDNode *N,
3453                                           SDValue &Lo, SDValue &Hi) {
3454   EVT VT = N->getValueType(0);
3455   SDLoc dl(N);
3456 
3457   // If we can emit an efficient shift operation, do so now.  Check to see if
3458   // the RHS is a constant.
3459   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N->getOperand(1)))
3460     return ExpandShiftByConstant(N, CN->getAPIntValue(), Lo, Hi);
3461 
3462   // If we can determine that the high bit of the shift is zero or one, even if
3463   // the low bits are variable, emit this shift in an optimized form.
3464   if (ExpandShiftWithKnownAmountBit(N, Lo, Hi))
3465     return;
3466 
3467   // If this target supports shift_PARTS, use it.  First, map to the _PARTS opc.
3468   unsigned PartsOpc;
3469   if (N->getOpcode() == ISD::SHL) {
3470     PartsOpc = ISD::SHL_PARTS;
3471   } else if (N->getOpcode() == ISD::SRL) {
3472     PartsOpc = ISD::SRL_PARTS;
3473   } else {
3474     assert(N->getOpcode() == ISD::SRA && "Unknown shift!");
3475     PartsOpc = ISD::SRA_PARTS;
3476   }
3477 
3478   // Next check to see if the target supports this SHL_PARTS operation or if it
3479   // will custom expand it. Don't lower this to SHL_PARTS when we optimise for
3480   // size, but create a libcall instead.
3481   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), VT);
3482   TargetLowering::LegalizeAction Action = TLI.getOperationAction(PartsOpc, NVT);
3483   const bool LegalOrCustom =
3484     (Action == TargetLowering::Legal && TLI.isTypeLegal(NVT)) ||
3485     Action == TargetLowering::Custom;
3486 
3487   if (LegalOrCustom && TLI.shouldExpandShift(DAG, N)) {
3488     // Expand the subcomponents.
3489     SDValue LHSL, LHSH;
3490     GetExpandedInteger(N->getOperand(0), LHSL, LHSH);
3491     EVT VT = LHSL.getValueType();
3492 
3493     // If the shift amount operand is coming from a vector legalization it may
3494     // have an illegal type.  Fix that first by casting the operand, otherwise
3495     // the new SHL_PARTS operation would need further legalization.
3496     SDValue ShiftOp = N->getOperand(1);
3497     EVT ShiftTy = TLI.getShiftAmountTy(VT, DAG.getDataLayout());
3498     assert(ShiftTy.getScalarSizeInBits() >=
3499            Log2_32_Ceil(VT.getScalarSizeInBits()) &&
3500            "ShiftAmountTy is too small to cover the range of this type!");
3501     if (ShiftOp.getValueType() != ShiftTy)
3502       ShiftOp = DAG.getZExtOrTrunc(ShiftOp, dl, ShiftTy);
3503 
3504     SDValue Ops[] = { LHSL, LHSH, ShiftOp };
3505     Lo = DAG.getNode(PartsOpc, dl, DAG.getVTList(VT, VT), Ops);
3506     Hi = Lo.getValue(1);
3507     return;
3508   }
3509 
3510   // Otherwise, emit a libcall.
3511   RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
3512   bool isSigned;
3513   if (N->getOpcode() == ISD::SHL) {
3514     isSigned = false; /*sign irrelevant*/
3515     if (VT == MVT::i16)
3516       LC = RTLIB::SHL_I16;
3517     else if (VT == MVT::i32)
3518       LC = RTLIB::SHL_I32;
3519     else if (VT == MVT::i64)
3520       LC = RTLIB::SHL_I64;
3521     else if (VT == MVT::i128)
3522       LC = RTLIB::SHL_I128;
3523   } else if (N->getOpcode() == ISD::SRL) {
3524     isSigned = false;
3525     if (VT == MVT::i16)
3526       LC = RTLIB::SRL_I16;
3527     else if (VT == MVT::i32)
3528       LC = RTLIB::SRL_I32;
3529     else if (VT == MVT::i64)
3530       LC = RTLIB::SRL_I64;
3531     else if (VT == MVT::i128)
3532       LC = RTLIB::SRL_I128;
3533   } else {
3534     assert(N->getOpcode() == ISD::SRA && "Unknown shift!");
3535     isSigned = true;
3536     if (VT == MVT::i16)
3537       LC = RTLIB::SRA_I16;
3538     else if (VT == MVT::i32)
3539       LC = RTLIB::SRA_I32;
3540     else if (VT == MVT::i64)
3541       LC = RTLIB::SRA_I64;
3542     else if (VT == MVT::i128)
3543       LC = RTLIB::SRA_I128;
3544   }
3545 
3546   if (LC != RTLIB::UNKNOWN_LIBCALL && TLI.getLibcallName(LC)) {
3547     SDValue Ops[2] = { N->getOperand(0), N->getOperand(1) };
3548     TargetLowering::MakeLibCallOptions CallOptions;
3549     CallOptions.setSExt(isSigned);
3550     SplitInteger(TLI.makeLibCall(DAG, LC, VT, Ops, CallOptions, dl).first, Lo, Hi);
3551     return;
3552   }
3553 
3554   if (!ExpandShiftWithUnknownAmountBit(N, Lo, Hi))
3555     llvm_unreachable("Unsupported shift!");
3556 }
3557 
3558 void DAGTypeLegalizer::ExpandIntRes_SIGN_EXTEND(SDNode *N,
3559                                                 SDValue &Lo, SDValue &Hi) {
3560   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
3561   SDLoc dl(N);
3562   SDValue Op = N->getOperand(0);
3563   if (Op.getValueType().bitsLE(NVT)) {
3564     // The low part is sign extension of the input (degenerates to a copy).
3565     Lo = DAG.getNode(ISD::SIGN_EXTEND, dl, NVT, N->getOperand(0));
3566     // The high part is obtained by SRA'ing all but one of the bits of low part.
3567     unsigned LoSize = NVT.getSizeInBits();
3568     Hi = DAG.getNode(
3569         ISD::SRA, dl, NVT, Lo,
3570         DAG.getConstant(LoSize - 1, dl, TLI.getPointerTy(DAG.getDataLayout())));
3571   } else {
3572     // For example, extension of an i48 to an i64.  The operand type necessarily
3573     // promotes to the result type, so will end up being expanded too.
3574     assert(getTypeAction(Op.getValueType()) ==
3575            TargetLowering::TypePromoteInteger &&
3576            "Only know how to promote this result!");
3577     SDValue Res = GetPromotedInteger(Op);
3578     assert(Res.getValueType() == N->getValueType(0) &&
3579            "Operand over promoted?");
3580     // Split the promoted operand.  This will simplify when it is expanded.
3581     SplitInteger(Res, Lo, Hi);
3582     unsigned ExcessBits = Op.getValueSizeInBits() - NVT.getSizeInBits();
3583     Hi = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, Hi.getValueType(), Hi,
3584                      DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(),
3585                                                         ExcessBits)));
3586   }
3587 }
3588 
3589 void DAGTypeLegalizer::
3590 ExpandIntRes_SIGN_EXTEND_INREG(SDNode *N, SDValue &Lo, SDValue &Hi) {
3591   SDLoc dl(N);
3592   GetExpandedInteger(N->getOperand(0), Lo, Hi);
3593   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
3594 
3595   if (EVT.bitsLE(Lo.getValueType())) {
3596     // sext_inreg the low part if needed.
3597     Lo = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, Lo.getValueType(), Lo,
3598                      N->getOperand(1));
3599 
3600     // The high part gets the sign extension from the lo-part.  This handles
3601     // things like sextinreg V:i64 from i8.
3602     Hi = DAG.getNode(ISD::SRA, dl, Hi.getValueType(), Lo,
3603                      DAG.getConstant(Hi.getValueSizeInBits() - 1, dl,
3604                                      TLI.getPointerTy(DAG.getDataLayout())));
3605   } else {
3606     // For example, extension of an i48 to an i64.  Leave the low part alone,
3607     // sext_inreg the high part.
3608     unsigned ExcessBits = EVT.getSizeInBits() - Lo.getValueSizeInBits();
3609     Hi = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, Hi.getValueType(), Hi,
3610                      DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(),
3611                                                         ExcessBits)));
3612   }
3613 }
3614 
3615 void DAGTypeLegalizer::ExpandIntRes_SREM(SDNode *N,
3616                                          SDValue &Lo, SDValue &Hi) {
3617   EVT VT = N->getValueType(0);
3618   SDLoc dl(N);
3619   SDValue Ops[2] = { N->getOperand(0), N->getOperand(1) };
3620 
3621   if (TLI.getOperationAction(ISD::SDIVREM, VT) == TargetLowering::Custom) {
3622     SDValue Res = DAG.getNode(ISD::SDIVREM, dl, DAG.getVTList(VT, VT), Ops);
3623     SplitInteger(Res.getValue(1), Lo, Hi);
3624     return;
3625   }
3626 
3627   RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
3628   if (VT == MVT::i16)
3629     LC = RTLIB::SREM_I16;
3630   else if (VT == MVT::i32)
3631     LC = RTLIB::SREM_I32;
3632   else if (VT == MVT::i64)
3633     LC = RTLIB::SREM_I64;
3634   else if (VT == MVT::i128)
3635     LC = RTLIB::SREM_I128;
3636   assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unsupported SREM!");
3637 
3638   TargetLowering::MakeLibCallOptions CallOptions;
3639   CallOptions.setSExt(true);
3640   SplitInteger(TLI.makeLibCall(DAG, LC, VT, Ops, CallOptions, dl).first, Lo, Hi);
3641 }
3642 
3643 void DAGTypeLegalizer::ExpandIntRes_TRUNCATE(SDNode *N,
3644                                              SDValue &Lo, SDValue &Hi) {
3645   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
3646   SDLoc dl(N);
3647   Lo = DAG.getNode(ISD::TRUNCATE, dl, NVT, N->getOperand(0));
3648   Hi = DAG.getNode(ISD::SRL, dl, N->getOperand(0).getValueType(),
3649                    N->getOperand(0),
3650                    DAG.getConstant(NVT.getSizeInBits(), dl,
3651                                    TLI.getPointerTy(DAG.getDataLayout())));
3652   Hi = DAG.getNode(ISD::TRUNCATE, dl, NVT, Hi);
3653 }
3654 
3655 void DAGTypeLegalizer::ExpandIntRes_XMULO(SDNode *N,
3656                                           SDValue &Lo, SDValue &Hi) {
3657   EVT VT = N->getValueType(0);
3658   SDLoc dl(N);
3659 
3660   if (N->getOpcode() == ISD::UMULO) {
3661     // This section expands the operation into the following sequence of
3662     // instructions. `iNh` here refers to a type which has half the bit width of
3663     // the type the original operation operated on.
3664     //
3665     // %0 = %LHS.HI != 0 && %RHS.HI != 0
3666     // %1 = { iNh, i1 } @umul.with.overflow.iNh(iNh %LHS.HI, iNh %RHS.LO)
3667     // %2 = { iNh, i1 } @umul.with.overflow.iNh(iNh %RHS.HI, iNh %LHS.LO)
3668     // %3 = mul nuw iN (%LHS.LOW as iN), (%RHS.LOW as iN)
3669     // %4 = add iN (%1.0 as iN) << Nh, (%2.0 as iN) << Nh
3670     // %5 = { iN, i1 } @uadd.with.overflow.iN( %4, %3 )
3671     //
3672     // %res = { %5.0, %0 || %1.1 || %2.1 || %5.1 }
3673     SDValue LHS = N->getOperand(0), RHS = N->getOperand(1);
3674     SDValue LHSHigh, LHSLow, RHSHigh, RHSLow;
3675     SplitInteger(LHS, LHSLow, LHSHigh);
3676     SplitInteger(RHS, RHSLow, RHSHigh);
3677     EVT HalfVT = LHSLow.getValueType()
3678       , BitVT = N->getValueType(1);
3679     SDVTList VTHalfMulO = DAG.getVTList(HalfVT, BitVT);
3680     SDVTList VTFullAddO = DAG.getVTList(VT, BitVT);
3681 
3682     SDValue HalfZero = DAG.getConstant(0, dl, HalfVT);
3683     SDValue Overflow = DAG.getNode(ISD::AND, dl, BitVT,
3684       DAG.getSetCC(dl, BitVT, LHSHigh, HalfZero, ISD::SETNE),
3685       DAG.getSetCC(dl, BitVT, RHSHigh, HalfZero, ISD::SETNE));
3686 
3687     SDValue One = DAG.getNode(ISD::UMULO, dl, VTHalfMulO, LHSHigh, RHSLow);
3688     Overflow = DAG.getNode(ISD::OR, dl, BitVT, Overflow, One.getValue(1));
3689     SDValue OneInHigh = DAG.getNode(ISD::BUILD_PAIR, dl, VT, HalfZero,
3690                                     One.getValue(0));
3691 
3692     SDValue Two = DAG.getNode(ISD::UMULO, dl, VTHalfMulO, RHSHigh, LHSLow);
3693     Overflow = DAG.getNode(ISD::OR, dl, BitVT, Overflow, Two.getValue(1));
3694     SDValue TwoInHigh = DAG.getNode(ISD::BUILD_PAIR, dl, VT, HalfZero,
3695                                     Two.getValue(0));
3696 
3697     // Cannot use `UMUL_LOHI` directly, because some 32-bit targets (ARM) do not
3698     // know how to expand `i64,i64 = umul_lohi a, b` and abort (why isn’t this
3699     // operation recursively legalized?).
3700     //
3701     // Many backends understand this pattern and will convert into LOHI
3702     // themselves, if applicable.
3703     SDValue Three = DAG.getNode(ISD::MUL, dl, VT,
3704       DAG.getNode(ISD::ZERO_EXTEND, dl, VT, LHSLow),
3705       DAG.getNode(ISD::ZERO_EXTEND, dl, VT, RHSLow));
3706     SDValue Four = DAG.getNode(ISD::ADD, dl, VT, OneInHigh, TwoInHigh);
3707     SDValue Five = DAG.getNode(ISD::UADDO, dl, VTFullAddO, Three, Four);
3708     Overflow = DAG.getNode(ISD::OR, dl, BitVT, Overflow, Five.getValue(1));
3709     SplitInteger(Five, Lo, Hi);
3710     ReplaceValueWith(SDValue(N, 1), Overflow);
3711     return;
3712   }
3713 
3714   Type *RetTy = VT.getTypeForEVT(*DAG.getContext());
3715   EVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
3716   Type *PtrTy = PtrVT.getTypeForEVT(*DAG.getContext());
3717 
3718   // Replace this with a libcall that will check overflow.
3719   RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
3720   if (VT == MVT::i32)
3721     LC = RTLIB::MULO_I32;
3722   else if (VT == MVT::i64)
3723     LC = RTLIB::MULO_I64;
3724   else if (VT == MVT::i128)
3725     LC = RTLIB::MULO_I128;
3726   assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unsupported XMULO!");
3727 
3728   SDValue Temp = DAG.CreateStackTemporary(PtrVT);
3729   // Temporary for the overflow value, default it to zero.
3730   SDValue Chain =
3731       DAG.getStore(DAG.getEntryNode(), dl, DAG.getConstant(0, dl, PtrVT), Temp,
3732                    MachinePointerInfo());
3733 
3734   TargetLowering::ArgListTy Args;
3735   TargetLowering::ArgListEntry Entry;
3736   for (const SDValue &Op : N->op_values()) {
3737     EVT ArgVT = Op.getValueType();
3738     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
3739     Entry.Node = Op;
3740     Entry.Ty = ArgTy;
3741     Entry.IsSExt = true;
3742     Entry.IsZExt = false;
3743     Args.push_back(Entry);
3744   }
3745 
3746   // Also pass the address of the overflow check.
3747   Entry.Node = Temp;
3748   Entry.Ty = PtrTy->getPointerTo();
3749   Entry.IsSExt = true;
3750   Entry.IsZExt = false;
3751   Args.push_back(Entry);
3752 
3753   SDValue Func = DAG.getExternalSymbol(TLI.getLibcallName(LC), PtrVT);
3754 
3755   TargetLowering::CallLoweringInfo CLI(DAG);
3756   CLI.setDebugLoc(dl)
3757       .setChain(Chain)
3758       .setLibCallee(TLI.getLibcallCallingConv(LC), RetTy, Func, std::move(Args))
3759       .setSExtResult();
3760 
3761   std::pair<SDValue, SDValue> CallInfo = TLI.LowerCallTo(CLI);
3762 
3763   SplitInteger(CallInfo.first, Lo, Hi);
3764   SDValue Temp2 =
3765       DAG.getLoad(PtrVT, dl, CallInfo.second, Temp, MachinePointerInfo());
3766   SDValue Ofl = DAG.getSetCC(dl, N->getValueType(1), Temp2,
3767                              DAG.getConstant(0, dl, PtrVT),
3768                              ISD::SETNE);
3769   // Use the overflow from the libcall everywhere.
3770   ReplaceValueWith(SDValue(N, 1), Ofl);
3771 }
3772 
3773 void DAGTypeLegalizer::ExpandIntRes_UDIV(SDNode *N,
3774                                          SDValue &Lo, SDValue &Hi) {
3775   EVT VT = N->getValueType(0);
3776   SDLoc dl(N);
3777   SDValue Ops[2] = { N->getOperand(0), N->getOperand(1) };
3778 
3779   if (TLI.getOperationAction(ISD::UDIVREM, VT) == TargetLowering::Custom) {
3780     SDValue Res = DAG.getNode(ISD::UDIVREM, dl, DAG.getVTList(VT, VT), Ops);
3781     SplitInteger(Res.getValue(0), Lo, Hi);
3782     return;
3783   }
3784 
3785   RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
3786   if (VT == MVT::i16)
3787     LC = RTLIB::UDIV_I16;
3788   else if (VT == MVT::i32)
3789     LC = RTLIB::UDIV_I32;
3790   else if (VT == MVT::i64)
3791     LC = RTLIB::UDIV_I64;
3792   else if (VT == MVT::i128)
3793     LC = RTLIB::UDIV_I128;
3794   assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unsupported UDIV!");
3795 
3796   TargetLowering::MakeLibCallOptions CallOptions;
3797   SplitInteger(TLI.makeLibCall(DAG, LC, VT, Ops, CallOptions, dl).first, Lo, Hi);
3798 }
3799 
3800 void DAGTypeLegalizer::ExpandIntRes_UREM(SDNode *N,
3801                                          SDValue &Lo, SDValue &Hi) {
3802   EVT VT = N->getValueType(0);
3803   SDLoc dl(N);
3804   SDValue Ops[2] = { N->getOperand(0), N->getOperand(1) };
3805 
3806   if (TLI.getOperationAction(ISD::UDIVREM, VT) == TargetLowering::Custom) {
3807     SDValue Res = DAG.getNode(ISD::UDIVREM, dl, DAG.getVTList(VT, VT), Ops);
3808     SplitInteger(Res.getValue(1), Lo, Hi);
3809     return;
3810   }
3811 
3812   RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
3813   if (VT == MVT::i16)
3814     LC = RTLIB::UREM_I16;
3815   else if (VT == MVT::i32)
3816     LC = RTLIB::UREM_I32;
3817   else if (VT == MVT::i64)
3818     LC = RTLIB::UREM_I64;
3819   else if (VT == MVT::i128)
3820     LC = RTLIB::UREM_I128;
3821   assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unsupported UREM!");
3822 
3823   TargetLowering::MakeLibCallOptions CallOptions;
3824   SplitInteger(TLI.makeLibCall(DAG, LC, VT, Ops, CallOptions, dl).first, Lo, Hi);
3825 }
3826 
3827 void DAGTypeLegalizer::ExpandIntRes_ZERO_EXTEND(SDNode *N,
3828                                                 SDValue &Lo, SDValue &Hi) {
3829   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
3830   SDLoc dl(N);
3831   SDValue Op = N->getOperand(0);
3832   if (Op.getValueType().bitsLE(NVT)) {
3833     // The low part is zero extension of the input (degenerates to a copy).
3834     Lo = DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N->getOperand(0));
3835     Hi = DAG.getConstant(0, dl, NVT);   // The high part is just a zero.
3836   } else {
3837     // For example, extension of an i48 to an i64.  The operand type necessarily
3838     // promotes to the result type, so will end up being expanded too.
3839     assert(getTypeAction(Op.getValueType()) ==
3840            TargetLowering::TypePromoteInteger &&
3841            "Only know how to promote this result!");
3842     SDValue Res = GetPromotedInteger(Op);
3843     assert(Res.getValueType() == N->getValueType(0) &&
3844            "Operand over promoted?");
3845     // Split the promoted operand.  This will simplify when it is expanded.
3846     SplitInteger(Res, Lo, Hi);
3847     unsigned ExcessBits = Op.getValueSizeInBits() - NVT.getSizeInBits();
3848     Hi = DAG.getZeroExtendInReg(Hi, dl,
3849                                 EVT::getIntegerVT(*DAG.getContext(),
3850                                                   ExcessBits));
3851   }
3852 }
3853 
3854 void DAGTypeLegalizer::ExpandIntRes_ATOMIC_LOAD(SDNode *N,
3855                                                 SDValue &Lo, SDValue &Hi) {
3856   SDLoc dl(N);
3857   EVT VT = cast<AtomicSDNode>(N)->getMemoryVT();
3858   SDVTList VTs = DAG.getVTList(VT, MVT::i1, MVT::Other);
3859   SDValue Zero = DAG.getConstant(0, dl, VT);
3860   SDValue Swap = DAG.getAtomicCmpSwap(
3861       ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, dl,
3862       cast<AtomicSDNode>(N)->getMemoryVT(), VTs, N->getOperand(0),
3863       N->getOperand(1), Zero, Zero, cast<AtomicSDNode>(N)->getMemOperand());
3864 
3865   ReplaceValueWith(SDValue(N, 0), Swap.getValue(0));
3866   ReplaceValueWith(SDValue(N, 1), Swap.getValue(2));
3867 }
3868 
3869 void DAGTypeLegalizer::ExpandIntRes_VECREDUCE(SDNode *N,
3870                                               SDValue &Lo, SDValue &Hi) {
3871   // TODO For VECREDUCE_(AND|OR|XOR) we could split the vector and calculate
3872   // both halves independently.
3873   SDValue Res = TLI.expandVecReduce(N, DAG);
3874   SplitInteger(Res, Lo, Hi);
3875 }
3876 
3877 //===----------------------------------------------------------------------===//
3878 //  Integer Operand Expansion
3879 //===----------------------------------------------------------------------===//
3880 
3881 /// ExpandIntegerOperand - This method is called when the specified operand of
3882 /// the specified node is found to need expansion.  At this point, all of the
3883 /// result types of the node are known to be legal, but other operands of the
3884 /// node may need promotion or expansion as well as the specified one.
3885 bool DAGTypeLegalizer::ExpandIntegerOperand(SDNode *N, unsigned OpNo) {
3886   LLVM_DEBUG(dbgs() << "Expand integer operand: "; N->dump(&DAG);
3887              dbgs() << "\n");
3888   SDValue Res = SDValue();
3889 
3890   if (CustomLowerNode(N, N->getOperand(OpNo).getValueType(), false))
3891     return false;
3892 
3893   switch (N->getOpcode()) {
3894   default:
3895   #ifndef NDEBUG
3896     dbgs() << "ExpandIntegerOperand Op #" << OpNo << ": ";
3897     N->dump(&DAG); dbgs() << "\n";
3898   #endif
3899     report_fatal_error("Do not know how to expand this operator's operand!");
3900 
3901   case ISD::BITCAST:           Res = ExpandOp_BITCAST(N); break;
3902   case ISD::BR_CC:             Res = ExpandIntOp_BR_CC(N); break;
3903   case ISD::BUILD_VECTOR:      Res = ExpandOp_BUILD_VECTOR(N); break;
3904   case ISD::EXTRACT_ELEMENT:   Res = ExpandOp_EXTRACT_ELEMENT(N); break;
3905   case ISD::INSERT_VECTOR_ELT: Res = ExpandOp_INSERT_VECTOR_ELT(N); break;
3906   case ISD::SCALAR_TO_VECTOR:  Res = ExpandOp_SCALAR_TO_VECTOR(N); break;
3907   case ISD::SELECT_CC:         Res = ExpandIntOp_SELECT_CC(N); break;
3908   case ISD::SETCC:             Res = ExpandIntOp_SETCC(N); break;
3909   case ISD::SETCCCARRY:        Res = ExpandIntOp_SETCCCARRY(N); break;
3910   case ISD::STRICT_SINT_TO_FP:
3911   case ISD::SINT_TO_FP:        Res = ExpandIntOp_SINT_TO_FP(N); break;
3912   case ISD::STORE:   Res = ExpandIntOp_STORE(cast<StoreSDNode>(N), OpNo); break;
3913   case ISD::TRUNCATE:          Res = ExpandIntOp_TRUNCATE(N); break;
3914   case ISD::STRICT_UINT_TO_FP:
3915   case ISD::UINT_TO_FP:        Res = ExpandIntOp_UINT_TO_FP(N); break;
3916 
3917   case ISD::SHL:
3918   case ISD::SRA:
3919   case ISD::SRL:
3920   case ISD::ROTL:
3921   case ISD::ROTR:              Res = ExpandIntOp_Shift(N); break;
3922   case ISD::RETURNADDR:
3923   case ISD::FRAMEADDR:         Res = ExpandIntOp_RETURNADDR(N); break;
3924 
3925   case ISD::ATOMIC_STORE:      Res = ExpandIntOp_ATOMIC_STORE(N); break;
3926   }
3927 
3928   // If the result is null, the sub-method took care of registering results etc.
3929   if (!Res.getNode()) return false;
3930 
3931   // If the result is N, the sub-method updated N in place.  Tell the legalizer
3932   // core about this.
3933   if (Res.getNode() == N)
3934     return true;
3935 
3936   assert(Res.getValueType() == N->getValueType(0) && N->getNumValues() == 1 &&
3937          "Invalid operand expansion");
3938 
3939   ReplaceValueWith(SDValue(N, 0), Res);
3940   return false;
3941 }
3942 
3943 /// IntegerExpandSetCCOperands - Expand the operands of a comparison.  This code
3944 /// is shared among BR_CC, SELECT_CC, and SETCC handlers.
3945 void DAGTypeLegalizer::IntegerExpandSetCCOperands(SDValue &NewLHS,
3946                                                   SDValue &NewRHS,
3947                                                   ISD::CondCode &CCCode,
3948                                                   const SDLoc &dl) {
3949   SDValue LHSLo, LHSHi, RHSLo, RHSHi;
3950   GetExpandedInteger(NewLHS, LHSLo, LHSHi);
3951   GetExpandedInteger(NewRHS, RHSLo, RHSHi);
3952 
3953   if (CCCode == ISD::SETEQ || CCCode == ISD::SETNE) {
3954     if (RHSLo == RHSHi) {
3955       if (ConstantSDNode *RHSCST = dyn_cast<ConstantSDNode>(RHSLo)) {
3956         if (RHSCST->isAllOnesValue()) {
3957           // Equality comparison to -1.
3958           NewLHS = DAG.getNode(ISD::AND, dl,
3959                                LHSLo.getValueType(), LHSLo, LHSHi);
3960           NewRHS = RHSLo;
3961           return;
3962         }
3963       }
3964     }
3965 
3966     NewLHS = DAG.getNode(ISD::XOR, dl, LHSLo.getValueType(), LHSLo, RHSLo);
3967     NewRHS = DAG.getNode(ISD::XOR, dl, LHSLo.getValueType(), LHSHi, RHSHi);
3968     NewLHS = DAG.getNode(ISD::OR, dl, NewLHS.getValueType(), NewLHS, NewRHS);
3969     NewRHS = DAG.getConstant(0, dl, NewLHS.getValueType());
3970     return;
3971   }
3972 
3973   // If this is a comparison of the sign bit, just look at the top part.
3974   // X > -1,  x < 0
3975   if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(NewRHS))
3976     if ((CCCode == ISD::SETLT && CST->isNullValue()) ||     // X < 0
3977         (CCCode == ISD::SETGT && CST->isAllOnesValue())) {  // X > -1
3978       NewLHS = LHSHi;
3979       NewRHS = RHSHi;
3980       return;
3981     }
3982 
3983   // FIXME: This generated code sucks.
3984   ISD::CondCode LowCC;
3985   switch (CCCode) {
3986   default: llvm_unreachable("Unknown integer setcc!");
3987   case ISD::SETLT:
3988   case ISD::SETULT: LowCC = ISD::SETULT; break;
3989   case ISD::SETGT:
3990   case ISD::SETUGT: LowCC = ISD::SETUGT; break;
3991   case ISD::SETLE:
3992   case ISD::SETULE: LowCC = ISD::SETULE; break;
3993   case ISD::SETGE:
3994   case ISD::SETUGE: LowCC = ISD::SETUGE; break;
3995   }
3996 
3997   // LoCmp = lo(op1) < lo(op2)   // Always unsigned comparison
3998   // HiCmp = hi(op1) < hi(op2)   // Signedness depends on operands
3999   // dest  = hi(op1) == hi(op2) ? LoCmp : HiCmp;
4000 
4001   // NOTE: on targets without efficient SELECT of bools, we can always use
4002   // this identity: (B1 ? B2 : B3) --> (B1 & B2)|(!B1&B3)
4003   TargetLowering::DAGCombinerInfo DagCombineInfo(DAG, AfterLegalizeTypes, true,
4004                                                  nullptr);
4005   SDValue LoCmp, HiCmp;
4006   if (TLI.isTypeLegal(LHSLo.getValueType()) &&
4007       TLI.isTypeLegal(RHSLo.getValueType()))
4008     LoCmp = TLI.SimplifySetCC(getSetCCResultType(LHSLo.getValueType()), LHSLo,
4009                               RHSLo, LowCC, false, DagCombineInfo, dl);
4010   if (!LoCmp.getNode())
4011     LoCmp = DAG.getSetCC(dl, getSetCCResultType(LHSLo.getValueType()), LHSLo,
4012                          RHSLo, LowCC);
4013   if (TLI.isTypeLegal(LHSHi.getValueType()) &&
4014       TLI.isTypeLegal(RHSHi.getValueType()))
4015     HiCmp = TLI.SimplifySetCC(getSetCCResultType(LHSHi.getValueType()), LHSHi,
4016                               RHSHi, CCCode, false, DagCombineInfo, dl);
4017   if (!HiCmp.getNode())
4018     HiCmp =
4019         DAG.getNode(ISD::SETCC, dl, getSetCCResultType(LHSHi.getValueType()),
4020                     LHSHi, RHSHi, DAG.getCondCode(CCCode));
4021 
4022   ConstantSDNode *LoCmpC = dyn_cast<ConstantSDNode>(LoCmp.getNode());
4023   ConstantSDNode *HiCmpC = dyn_cast<ConstantSDNode>(HiCmp.getNode());
4024 
4025   bool EqAllowed = (CCCode == ISD::SETLE || CCCode == ISD::SETGE ||
4026                     CCCode == ISD::SETUGE || CCCode == ISD::SETULE);
4027 
4028   if ((EqAllowed && (HiCmpC && HiCmpC->isNullValue())) ||
4029       (!EqAllowed && ((HiCmpC && (HiCmpC->getAPIntValue() == 1)) ||
4030                       (LoCmpC && LoCmpC->isNullValue())))) {
4031     // For LE / GE, if high part is known false, ignore the low part.
4032     // For LT / GT: if low part is known false, return the high part.
4033     //              if high part is known true, ignore the low part.
4034     NewLHS = HiCmp;
4035     NewRHS = SDValue();
4036     return;
4037   }
4038 
4039   if (LHSHi == RHSHi) {
4040     // Comparing the low bits is enough.
4041     NewLHS = LoCmp;
4042     NewRHS = SDValue();
4043     return;
4044   }
4045 
4046   // Lower with SETCCCARRY if the target supports it.
4047   EVT HiVT = LHSHi.getValueType();
4048   EVT ExpandVT = TLI.getTypeToExpandTo(*DAG.getContext(), HiVT);
4049   bool HasSETCCCARRY = TLI.isOperationLegalOrCustom(ISD::SETCCCARRY, ExpandVT);
4050 
4051   // FIXME: Make all targets support this, then remove the other lowering.
4052   if (HasSETCCCARRY) {
4053     // SETCCCARRY can detect < and >= directly. For > and <=, flip
4054     // operands and condition code.
4055     bool FlipOperands = false;
4056     switch (CCCode) {
4057     case ISD::SETGT:  CCCode = ISD::SETLT;  FlipOperands = true; break;
4058     case ISD::SETUGT: CCCode = ISD::SETULT; FlipOperands = true; break;
4059     case ISD::SETLE:  CCCode = ISD::SETGE;  FlipOperands = true; break;
4060     case ISD::SETULE: CCCode = ISD::SETUGE; FlipOperands = true; break;
4061     default: break;
4062     }
4063     if (FlipOperands) {
4064       std::swap(LHSLo, RHSLo);
4065       std::swap(LHSHi, RHSHi);
4066     }
4067     // Perform a wide subtraction, feeding the carry from the low part into
4068     // SETCCCARRY. The SETCCCARRY operation is essentially looking at the high
4069     // part of the result of LHS - RHS. It is negative iff LHS < RHS. It is
4070     // zero or positive iff LHS >= RHS.
4071     EVT LoVT = LHSLo.getValueType();
4072     SDVTList VTList = DAG.getVTList(LoVT, getSetCCResultType(LoVT));
4073     SDValue LowCmp = DAG.getNode(ISD::USUBO, dl, VTList, LHSLo, RHSLo);
4074     SDValue Res = DAG.getNode(ISD::SETCCCARRY, dl, getSetCCResultType(HiVT),
4075                               LHSHi, RHSHi, LowCmp.getValue(1),
4076                               DAG.getCondCode(CCCode));
4077     NewLHS = Res;
4078     NewRHS = SDValue();
4079     return;
4080   }
4081 
4082   NewLHS = TLI.SimplifySetCC(getSetCCResultType(HiVT), LHSHi, RHSHi, ISD::SETEQ,
4083                              false, DagCombineInfo, dl);
4084   if (!NewLHS.getNode())
4085     NewLHS =
4086         DAG.getSetCC(dl, getSetCCResultType(HiVT), LHSHi, RHSHi, ISD::SETEQ);
4087   NewLHS = DAG.getSelect(dl, LoCmp.getValueType(), NewLHS, LoCmp, HiCmp);
4088   NewRHS = SDValue();
4089 }
4090 
4091 SDValue DAGTypeLegalizer::ExpandIntOp_BR_CC(SDNode *N) {
4092   SDValue NewLHS = N->getOperand(2), NewRHS = N->getOperand(3);
4093   ISD::CondCode CCCode = cast<CondCodeSDNode>(N->getOperand(1))->get();
4094   IntegerExpandSetCCOperands(NewLHS, NewRHS, CCCode, SDLoc(N));
4095 
4096   // If ExpandSetCCOperands returned a scalar, we need to compare the result
4097   // against zero to select between true and false values.
4098   if (!NewRHS.getNode()) {
4099     NewRHS = DAG.getConstant(0, SDLoc(N), NewLHS.getValueType());
4100     CCCode = ISD::SETNE;
4101   }
4102 
4103   // Update N to have the operands specified.
4104   return SDValue(DAG.UpdateNodeOperands(N, N->getOperand(0),
4105                                 DAG.getCondCode(CCCode), NewLHS, NewRHS,
4106                                 N->getOperand(4)), 0);
4107 }
4108 
4109 SDValue DAGTypeLegalizer::ExpandIntOp_SELECT_CC(SDNode *N) {
4110   SDValue NewLHS = N->getOperand(0), NewRHS = N->getOperand(1);
4111   ISD::CondCode CCCode = cast<CondCodeSDNode>(N->getOperand(4))->get();
4112   IntegerExpandSetCCOperands(NewLHS, NewRHS, CCCode, SDLoc(N));
4113 
4114   // If ExpandSetCCOperands returned a scalar, we need to compare the result
4115   // against zero to select between true and false values.
4116   if (!NewRHS.getNode()) {
4117     NewRHS = DAG.getConstant(0, SDLoc(N), NewLHS.getValueType());
4118     CCCode = ISD::SETNE;
4119   }
4120 
4121   // Update N to have the operands specified.
4122   return SDValue(DAG.UpdateNodeOperands(N, NewLHS, NewRHS,
4123                                 N->getOperand(2), N->getOperand(3),
4124                                 DAG.getCondCode(CCCode)), 0);
4125 }
4126 
4127 SDValue DAGTypeLegalizer::ExpandIntOp_SETCC(SDNode *N) {
4128   SDValue NewLHS = N->getOperand(0), NewRHS = N->getOperand(1);
4129   ISD::CondCode CCCode = cast<CondCodeSDNode>(N->getOperand(2))->get();
4130   IntegerExpandSetCCOperands(NewLHS, NewRHS, CCCode, SDLoc(N));
4131 
4132   // If ExpandSetCCOperands returned a scalar, use it.
4133   if (!NewRHS.getNode()) {
4134     assert(NewLHS.getValueType() == N->getValueType(0) &&
4135            "Unexpected setcc expansion!");
4136     return NewLHS;
4137   }
4138 
4139   // Otherwise, update N to have the operands specified.
4140   return SDValue(
4141       DAG.UpdateNodeOperands(N, NewLHS, NewRHS, DAG.getCondCode(CCCode)), 0);
4142 }
4143 
4144 SDValue DAGTypeLegalizer::ExpandIntOp_SETCCCARRY(SDNode *N) {
4145   SDValue LHS = N->getOperand(0);
4146   SDValue RHS = N->getOperand(1);
4147   SDValue Carry = N->getOperand(2);
4148   SDValue Cond = N->getOperand(3);
4149   SDLoc dl = SDLoc(N);
4150 
4151   SDValue LHSLo, LHSHi, RHSLo, RHSHi;
4152   GetExpandedInteger(LHS, LHSLo, LHSHi);
4153   GetExpandedInteger(RHS, RHSLo, RHSHi);
4154 
4155   // Expand to a SUBE for the low part and a smaller SETCCCARRY for the high.
4156   SDVTList VTList = DAG.getVTList(LHSLo.getValueType(), Carry.getValueType());
4157   SDValue LowCmp = DAG.getNode(ISD::SUBCARRY, dl, VTList, LHSLo, RHSLo, Carry);
4158   return DAG.getNode(ISD::SETCCCARRY, dl, N->getValueType(0), LHSHi, RHSHi,
4159                      LowCmp.getValue(1), Cond);
4160 }
4161 
4162 SDValue DAGTypeLegalizer::ExpandIntOp_Shift(SDNode *N) {
4163   // The value being shifted is legal, but the shift amount is too big.
4164   // It follows that either the result of the shift is undefined, or the
4165   // upper half of the shift amount is zero.  Just use the lower half.
4166   SDValue Lo, Hi;
4167   GetExpandedInteger(N->getOperand(1), Lo, Hi);
4168   return SDValue(DAG.UpdateNodeOperands(N, N->getOperand(0), Lo), 0);
4169 }
4170 
4171 SDValue DAGTypeLegalizer::ExpandIntOp_RETURNADDR(SDNode *N) {
4172   // The argument of RETURNADDR / FRAMEADDR builtin is 32 bit contant.  This
4173   // surely makes pretty nice problems on 8/16 bit targets. Just truncate this
4174   // constant to valid type.
4175   SDValue Lo, Hi;
4176   GetExpandedInteger(N->getOperand(0), Lo, Hi);
4177   return SDValue(DAG.UpdateNodeOperands(N, Lo), 0);
4178 }
4179 
4180 SDValue DAGTypeLegalizer::ExpandIntOp_SINT_TO_FP(SDNode *N) {
4181   bool IsStrict = N->isStrictFPOpcode();
4182   SDValue Chain = IsStrict ? N->getOperand(0) : SDValue();
4183   SDValue Op = N->getOperand(IsStrict ? 1 : 0);
4184   EVT DstVT = N->getValueType(0);
4185   RTLIB::Libcall LC = RTLIB::getSINTTOFP(Op.getValueType(), DstVT);
4186   assert(LC != RTLIB::UNKNOWN_LIBCALL &&
4187          "Don't know how to expand this SINT_TO_FP!");
4188   TargetLowering::MakeLibCallOptions CallOptions;
4189   CallOptions.setSExt(true);
4190   std::pair<SDValue, SDValue> Tmp =
4191       TLI.makeLibCall(DAG, LC, DstVT, Op, CallOptions, SDLoc(N), Chain);
4192 
4193   if (!IsStrict)
4194     return Tmp.first;
4195 
4196   ReplaceValueWith(SDValue(N, 1), Tmp.second);
4197   ReplaceValueWith(SDValue(N, 0), Tmp.first);
4198   return SDValue();
4199 }
4200 
4201 SDValue DAGTypeLegalizer::ExpandIntOp_STORE(StoreSDNode *N, unsigned OpNo) {
4202   if (N->isAtomic()) {
4203     // It's typical to have larger CAS than atomic store instructions.
4204     SDLoc dl(N);
4205     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
4206                                  N->getMemoryVT(),
4207                                  N->getOperand(0), N->getOperand(2),
4208                                  N->getOperand(1),
4209                                  N->getMemOperand());
4210     return Swap.getValue(1);
4211   }
4212   if (ISD::isNormalStore(N))
4213     return ExpandOp_NormalStore(N, OpNo);
4214 
4215   assert(ISD::isUNINDEXEDStore(N) && "Indexed store during type legalization!");
4216   assert(OpNo == 1 && "Can only expand the stored value so far");
4217 
4218   EVT VT = N->getOperand(1).getValueType();
4219   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), VT);
4220   SDValue Ch  = N->getChain();
4221   SDValue Ptr = N->getBasePtr();
4222   MachineMemOperand::Flags MMOFlags = N->getMemOperand()->getFlags();
4223   AAMDNodes AAInfo = N->getAAInfo();
4224   SDLoc dl(N);
4225   SDValue Lo, Hi;
4226 
4227   assert(NVT.isByteSized() && "Expanded type not byte sized!");
4228 
4229   if (N->getMemoryVT().bitsLE(NVT)) {
4230     GetExpandedInteger(N->getValue(), Lo, Hi);
4231     return DAG.getTruncStore(Ch, dl, Lo, Ptr, N->getPointerInfo(),
4232                              N->getMemoryVT(), N->getOriginalAlign(), MMOFlags,
4233                              AAInfo);
4234   }
4235 
4236   if (DAG.getDataLayout().isLittleEndian()) {
4237     // Little-endian - low bits are at low addresses.
4238     GetExpandedInteger(N->getValue(), Lo, Hi);
4239 
4240     Lo = DAG.getStore(Ch, dl, Lo, Ptr, N->getPointerInfo(),
4241                       N->getOriginalAlign(), MMOFlags, AAInfo);
4242 
4243     unsigned ExcessBits =
4244       N->getMemoryVT().getSizeInBits() - NVT.getSizeInBits();
4245     EVT NEVT = EVT::getIntegerVT(*DAG.getContext(), ExcessBits);
4246 
4247     // Increment the pointer to the other half.
4248     unsigned IncrementSize = NVT.getSizeInBits()/8;
4249     Ptr = DAG.getObjectPtrOffset(dl, Ptr, IncrementSize);
4250     Hi = DAG.getTruncStore(Ch, dl, Hi, Ptr,
4251                            N->getPointerInfo().getWithOffset(IncrementSize),
4252                            NEVT, N->getOriginalAlign(), MMOFlags, AAInfo);
4253     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo, Hi);
4254   }
4255 
4256   // Big-endian - high bits are at low addresses.  Favor aligned stores at
4257   // the cost of some bit-fiddling.
4258   GetExpandedInteger(N->getValue(), Lo, Hi);
4259 
4260   EVT ExtVT = N->getMemoryVT();
4261   unsigned EBytes = ExtVT.getStoreSize();
4262   unsigned IncrementSize = NVT.getSizeInBits()/8;
4263   unsigned ExcessBits = (EBytes - IncrementSize)*8;
4264   EVT HiVT = EVT::getIntegerVT(*DAG.getContext(),
4265                                ExtVT.getSizeInBits() - ExcessBits);
4266 
4267   if (ExcessBits < NVT.getSizeInBits()) {
4268     // Transfer high bits from the top of Lo to the bottom of Hi.
4269     Hi = DAG.getNode(ISD::SHL, dl, NVT, Hi,
4270                      DAG.getConstant(NVT.getSizeInBits() - ExcessBits, dl,
4271                                      TLI.getPointerTy(DAG.getDataLayout())));
4272     Hi = DAG.getNode(
4273         ISD::OR, dl, NVT, Hi,
4274         DAG.getNode(ISD::SRL, dl, NVT, Lo,
4275                     DAG.getConstant(ExcessBits, dl,
4276                                     TLI.getPointerTy(DAG.getDataLayout()))));
4277   }
4278 
4279   // Store both the high bits and maybe some of the low bits.
4280   Hi = DAG.getTruncStore(Ch, dl, Hi, Ptr, N->getPointerInfo(), HiVT,
4281                          N->getOriginalAlign(), MMOFlags, AAInfo);
4282 
4283   // Increment the pointer to the other half.
4284   Ptr = DAG.getObjectPtrOffset(dl, Ptr, IncrementSize);
4285   // Store the lowest ExcessBits bits in the second half.
4286   Lo = DAG.getTruncStore(Ch, dl, Lo, Ptr,
4287                          N->getPointerInfo().getWithOffset(IncrementSize),
4288                          EVT::getIntegerVT(*DAG.getContext(), ExcessBits),
4289                          N->getOriginalAlign(), MMOFlags, AAInfo);
4290   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo, Hi);
4291 }
4292 
4293 SDValue DAGTypeLegalizer::ExpandIntOp_TRUNCATE(SDNode *N) {
4294   SDValue InL, InH;
4295   GetExpandedInteger(N->getOperand(0), InL, InH);
4296   // Just truncate the low part of the source.
4297   return DAG.getNode(ISD::TRUNCATE, SDLoc(N), N->getValueType(0), InL);
4298 }
4299 
4300 SDValue DAGTypeLegalizer::ExpandIntOp_UINT_TO_FP(SDNode *N) {
4301   bool IsStrict = N->isStrictFPOpcode();
4302   SDValue Chain = IsStrict ? N->getOperand(0) : SDValue();
4303   SDValue Op = N->getOperand(IsStrict ? 1 : 0);
4304   EVT DstVT = N->getValueType(0);
4305   RTLIB::Libcall LC = RTLIB::getUINTTOFP(Op.getValueType(), DstVT);
4306   assert(LC != RTLIB::UNKNOWN_LIBCALL &&
4307          "Don't know how to expand this UINT_TO_FP!");
4308   TargetLowering::MakeLibCallOptions CallOptions;
4309   CallOptions.setSExt(true);
4310   std::pair<SDValue, SDValue> Tmp =
4311       TLI.makeLibCall(DAG, LC, DstVT, Op, CallOptions, SDLoc(N), Chain);
4312 
4313   if (!IsStrict)
4314     return Tmp.first;
4315 
4316   ReplaceValueWith(SDValue(N, 1), Tmp.second);
4317   ReplaceValueWith(SDValue(N, 0), Tmp.first);
4318   return SDValue();
4319 }
4320 
4321 SDValue DAGTypeLegalizer::ExpandIntOp_ATOMIC_STORE(SDNode *N) {
4322   SDLoc dl(N);
4323   SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
4324                                cast<AtomicSDNode>(N)->getMemoryVT(),
4325                                N->getOperand(0),
4326                                N->getOperand(1), N->getOperand(2),
4327                                cast<AtomicSDNode>(N)->getMemOperand());
4328   return Swap.getValue(1);
4329 }
4330 
4331 
4332 SDValue DAGTypeLegalizer::PromoteIntRes_EXTRACT_SUBVECTOR(SDNode *N) {
4333 
4334   EVT OutVT = N->getValueType(0);
4335   EVT NOutVT = TLI.getTypeToTransformTo(*DAG.getContext(), OutVT);
4336   assert(NOutVT.isVector() && "This type must be promoted to a vector type");
4337   EVT NOutVTElem = NOutVT.getVectorElementType();
4338 
4339   SDLoc dl(N);
4340   SDValue BaseIdx = N->getOperand(1);
4341 
4342   // TODO: We may be able to use this for types other than scalable
4343   // vectors and fix those tests that expect BUILD_VECTOR to be used
4344   if (OutVT.isScalableVector()) {
4345     SDValue InOp0 = N->getOperand(0);
4346     EVT InVT = InOp0.getValueType();
4347 
4348     // Promote operands and see if this is handled by target lowering,
4349     // Otherwise, use the BUILD_VECTOR approach below
4350     if (getTypeAction(InVT) == TargetLowering::TypePromoteInteger) {
4351       // Collect the (promoted) operands
4352       SDValue Ops[] = { GetPromotedInteger(InOp0), BaseIdx };
4353 
4354       EVT PromEltVT = Ops[0].getValueType().getVectorElementType();
4355       assert(PromEltVT.bitsLE(NOutVTElem) &&
4356              "Promoted operand has an element type greater than result");
4357 
4358       EVT ExtVT = NOutVT.changeVectorElementType(PromEltVT);
4359       SDValue Ext = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(N), ExtVT, Ops);
4360       return DAG.getNode(ISD::ANY_EXTEND, dl, NOutVT, Ext);
4361     }
4362   }
4363 
4364   if (OutVT.isScalableVector())
4365     report_fatal_error("Unable to promote scalable types using BUILD_VECTOR");
4366 
4367   SDValue InOp0 = N->getOperand(0);
4368   if (getTypeAction(InOp0.getValueType()) == TargetLowering::TypePromoteInteger)
4369     InOp0 = GetPromotedInteger(N->getOperand(0));
4370 
4371   EVT InVT = InOp0.getValueType();
4372 
4373   unsigned OutNumElems = OutVT.getVectorNumElements();
4374   SmallVector<SDValue, 8> Ops;
4375   Ops.reserve(OutNumElems);
4376   for (unsigned i = 0; i != OutNumElems; ++i) {
4377 
4378     // Extract the element from the original vector.
4379     SDValue Index = DAG.getNode(ISD::ADD, dl, BaseIdx.getValueType(),
4380       BaseIdx, DAG.getConstant(i, dl, BaseIdx.getValueType()));
4381     SDValue Ext = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
4382       InVT.getVectorElementType(), N->getOperand(0), Index);
4383 
4384     SDValue Op = DAG.getAnyExtOrTrunc(Ext, dl, NOutVTElem);
4385     // Insert the converted element to the new vector.
4386     Ops.push_back(Op);
4387   }
4388 
4389   return DAG.getBuildVector(NOutVT, dl, Ops);
4390 }
4391 
4392 
4393 SDValue DAGTypeLegalizer::PromoteIntRes_VECTOR_SHUFFLE(SDNode *N) {
4394   ShuffleVectorSDNode *SV = cast<ShuffleVectorSDNode>(N);
4395   EVT VT = N->getValueType(0);
4396   SDLoc dl(N);
4397 
4398   ArrayRef<int> NewMask = SV->getMask().slice(0, VT.getVectorNumElements());
4399 
4400   SDValue V0 = GetPromotedInteger(N->getOperand(0));
4401   SDValue V1 = GetPromotedInteger(N->getOperand(1));
4402   EVT OutVT = V0.getValueType();
4403 
4404   return DAG.getVectorShuffle(OutVT, dl, V0, V1, NewMask);
4405 }
4406 
4407 
4408 SDValue DAGTypeLegalizer::PromoteIntRes_BUILD_VECTOR(SDNode *N) {
4409   EVT OutVT = N->getValueType(0);
4410   EVT NOutVT = TLI.getTypeToTransformTo(*DAG.getContext(), OutVT);
4411   assert(NOutVT.isVector() && "This type must be promoted to a vector type");
4412   unsigned NumElems = N->getNumOperands();
4413   EVT NOutVTElem = NOutVT.getVectorElementType();
4414 
4415   SDLoc dl(N);
4416 
4417   SmallVector<SDValue, 8> Ops;
4418   Ops.reserve(NumElems);
4419   for (unsigned i = 0; i != NumElems; ++i) {
4420     SDValue Op;
4421     // BUILD_VECTOR integer operand types are allowed to be larger than the
4422     // result's element type. This may still be true after the promotion. For
4423     // example, we might be promoting (<v?i1> = BV <i32>, <i32>, ...) to
4424     // (v?i16 = BV <i32>, <i32>, ...), and we can't any_extend <i32> to <i16>.
4425     if (N->getOperand(i).getValueType().bitsLT(NOutVTElem))
4426       Op = DAG.getNode(ISD::ANY_EXTEND, dl, NOutVTElem, N->getOperand(i));
4427     else
4428       Op = N->getOperand(i);
4429     Ops.push_back(Op);
4430   }
4431 
4432   return DAG.getBuildVector(NOutVT, dl, Ops);
4433 }
4434 
4435 SDValue DAGTypeLegalizer::PromoteIntRes_SCALAR_TO_VECTOR(SDNode *N) {
4436 
4437   SDLoc dl(N);
4438 
4439   assert(!N->getOperand(0).getValueType().isVector() &&
4440          "Input must be a scalar");
4441 
4442   EVT OutVT = N->getValueType(0);
4443   EVT NOutVT = TLI.getTypeToTransformTo(*DAG.getContext(), OutVT);
4444   assert(NOutVT.isVector() && "This type must be promoted to a vector type");
4445   EVT NOutVTElem = NOutVT.getVectorElementType();
4446 
4447   SDValue Op = DAG.getNode(ISD::ANY_EXTEND, dl, NOutVTElem, N->getOperand(0));
4448 
4449   return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NOutVT, Op);
4450 }
4451 
4452 SDValue DAGTypeLegalizer::PromoteIntRes_SPLAT_VECTOR(SDNode *N) {
4453   SDLoc dl(N);
4454 
4455   SDValue SplatVal = N->getOperand(0);
4456 
4457   assert(!SplatVal.getValueType().isVector() && "Input must be a scalar");
4458 
4459   EVT OutVT = N->getValueType(0);
4460   EVT NOutVT = TLI.getTypeToTransformTo(*DAG.getContext(), OutVT);
4461   assert(NOutVT.isVector() && "Type must be promoted to a vector type");
4462   EVT NOutElemVT = NOutVT.getVectorElementType();
4463 
4464   SDValue Op = DAG.getNode(ISD::ANY_EXTEND, dl, NOutElemVT, SplatVal);
4465 
4466   return DAG.getNode(ISD::SPLAT_VECTOR, dl, NOutVT, Op);
4467 }
4468 
4469 SDValue DAGTypeLegalizer::PromoteIntRes_CONCAT_VECTORS(SDNode *N) {
4470   SDLoc dl(N);
4471 
4472   EVT OutVT = N->getValueType(0);
4473   EVT NOutVT = TLI.getTypeToTransformTo(*DAG.getContext(), OutVT);
4474   assert(NOutVT.isVector() && "This type must be promoted to a vector type");
4475 
4476   EVT OutElemTy = NOutVT.getVectorElementType();
4477 
4478   unsigned NumElem = N->getOperand(0).getValueType().getVectorNumElements();
4479   unsigned NumOutElem = NOutVT.getVectorNumElements();
4480   unsigned NumOperands = N->getNumOperands();
4481   assert(NumElem * NumOperands == NumOutElem &&
4482          "Unexpected number of elements");
4483 
4484   // Take the elements from the first vector.
4485   SmallVector<SDValue, 8> Ops(NumOutElem);
4486   for (unsigned i = 0; i < NumOperands; ++i) {
4487     SDValue Op = N->getOperand(i);
4488     if (getTypeAction(Op.getValueType()) == TargetLowering::TypePromoteInteger)
4489       Op = GetPromotedInteger(Op);
4490     EVT SclrTy = Op.getValueType().getVectorElementType();
4491     assert(NumElem == Op.getValueType().getVectorNumElements() &&
4492            "Unexpected number of elements");
4493 
4494     for (unsigned j = 0; j < NumElem; ++j) {
4495       SDValue Ext = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SclrTy, Op,
4496                                 DAG.getVectorIdxConstant(j, dl));
4497       Ops[i * NumElem + j] = DAG.getAnyExtOrTrunc(Ext, dl, OutElemTy);
4498     }
4499   }
4500 
4501   return DAG.getBuildVector(NOutVT, dl, Ops);
4502 }
4503 
4504 SDValue DAGTypeLegalizer::PromoteIntRes_EXTEND_VECTOR_INREG(SDNode *N) {
4505   EVT VT = N->getValueType(0);
4506   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), VT);
4507   assert(NVT.isVector() && "This type must be promoted to a vector type");
4508 
4509   SDLoc dl(N);
4510 
4511   // For operands whose TypeAction is to promote, extend the promoted node
4512   // appropriately (ZERO_EXTEND or SIGN_EXTEND) from the original pre-promotion
4513   // type, and then construct a new *_EXTEND_VECTOR_INREG node to the promote-to
4514   // type..
4515   if (getTypeAction(N->getOperand(0).getValueType())
4516       == TargetLowering::TypePromoteInteger) {
4517     SDValue Promoted;
4518 
4519     switch(N->getOpcode()) {
4520       case ISD::SIGN_EXTEND_VECTOR_INREG:
4521         Promoted = SExtPromotedInteger(N->getOperand(0));
4522         break;
4523       case ISD::ZERO_EXTEND_VECTOR_INREG:
4524         Promoted = ZExtPromotedInteger(N->getOperand(0));
4525         break;
4526       case ISD::ANY_EXTEND_VECTOR_INREG:
4527         Promoted = GetPromotedInteger(N->getOperand(0));
4528         break;
4529       default:
4530         llvm_unreachable("Node has unexpected Opcode");
4531     }
4532     return DAG.getNode(N->getOpcode(), dl, NVT, Promoted);
4533   }
4534 
4535   // Directly extend to the appropriate transform-to type.
4536   return DAG.getNode(N->getOpcode(), dl, NVT, N->getOperand(0));
4537 }
4538 
4539 SDValue DAGTypeLegalizer::PromoteIntRes_INSERT_VECTOR_ELT(SDNode *N) {
4540   EVT OutVT = N->getValueType(0);
4541   EVT NOutVT = TLI.getTypeToTransformTo(*DAG.getContext(), OutVT);
4542   assert(NOutVT.isVector() && "This type must be promoted to a vector type");
4543 
4544   EVT NOutVTElem = NOutVT.getVectorElementType();
4545 
4546   SDLoc dl(N);
4547   SDValue V0 = GetPromotedInteger(N->getOperand(0));
4548 
4549   SDValue ConvElem = DAG.getNode(ISD::ANY_EXTEND, dl,
4550     NOutVTElem, N->getOperand(1));
4551   return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, NOutVT,
4552     V0, ConvElem, N->getOperand(2));
4553 }
4554 
4555 SDValue DAGTypeLegalizer::PromoteIntRes_VECREDUCE(SDNode *N) {
4556   // The VECREDUCE result size may be larger than the element size, so
4557   // we can simply change the result type.
4558   SDLoc dl(N);
4559   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
4560   return DAG.getNode(N->getOpcode(), dl, NVT, N->getOperand(0));
4561 }
4562 
4563 SDValue DAGTypeLegalizer::PromoteIntOp_EXTRACT_VECTOR_ELT(SDNode *N) {
4564   SDLoc dl(N);
4565   SDValue V0 = GetPromotedInteger(N->getOperand(0));
4566   SDValue V1 = DAG.getZExtOrTrunc(N->getOperand(1), dl,
4567                                   TLI.getVectorIdxTy(DAG.getDataLayout()));
4568   SDValue Ext = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
4569     V0->getValueType(0).getScalarType(), V0, V1);
4570 
4571   // EXTRACT_VECTOR_ELT can return types which are wider than the incoming
4572   // element types. If this is the case then we need to expand the outgoing
4573   // value and not truncate it.
4574   return DAG.getAnyExtOrTrunc(Ext, dl, N->getValueType(0));
4575 }
4576 
4577 SDValue DAGTypeLegalizer::PromoteIntOp_EXTRACT_SUBVECTOR(SDNode *N) {
4578   SDLoc dl(N);
4579   SDValue V0 = GetPromotedInteger(N->getOperand(0));
4580   MVT InVT = V0.getValueType().getSimpleVT();
4581   MVT OutVT = MVT::getVectorVT(InVT.getVectorElementType(),
4582                                N->getValueType(0).getVectorNumElements());
4583   SDValue Ext = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, OutVT, V0, N->getOperand(1));
4584   return DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), Ext);
4585 }
4586 
4587 SDValue DAGTypeLegalizer::PromoteIntOp_CONCAT_VECTORS(SDNode *N) {
4588   SDLoc dl(N);
4589   unsigned NumElems = N->getNumOperands();
4590 
4591   EVT RetSclrTy = N->getValueType(0).getVectorElementType();
4592 
4593   SmallVector<SDValue, 8> NewOps;
4594   NewOps.reserve(NumElems);
4595 
4596   // For each incoming vector
4597   for (unsigned VecIdx = 0; VecIdx != NumElems; ++VecIdx) {
4598     SDValue Incoming = GetPromotedInteger(N->getOperand(VecIdx));
4599     EVT SclrTy = Incoming->getValueType(0).getVectorElementType();
4600     unsigned NumElem = Incoming->getValueType(0).getVectorNumElements();
4601 
4602     for (unsigned i=0; i<NumElem; ++i) {
4603       // Extract element from incoming vector
4604       SDValue Ex = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SclrTy, Incoming,
4605                                DAG.getVectorIdxConstant(i, dl));
4606       SDValue Tr = DAG.getNode(ISD::TRUNCATE, dl, RetSclrTy, Ex);
4607       NewOps.push_back(Tr);
4608     }
4609   }
4610 
4611   return DAG.getBuildVector(N->getValueType(0), dl, NewOps);
4612 }
4613