xref: /freebsd-src/contrib/llvm-project/llvm/lib/CodeGen/SelectionDAG/LegalizeDAG.cpp (revision 753f127f3ace09432b2baeffd71a308760641a62)
1 //===- LegalizeDAG.cpp - Implement SelectionDAG::Legalize -----------------===//
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 the SelectionDAG::Legalize method.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "llvm/ADT/APFloat.h"
14 #include "llvm/ADT/APInt.h"
15 #include "llvm/ADT/ArrayRef.h"
16 #include "llvm/ADT/FloatingPointMode.h"
17 #include "llvm/ADT/SetVector.h"
18 #include "llvm/ADT/SmallPtrSet.h"
19 #include "llvm/ADT/SmallSet.h"
20 #include "llvm/ADT/SmallVector.h"
21 #include "llvm/Analysis/TargetLibraryInfo.h"
22 #include "llvm/CodeGen/ISDOpcodes.h"
23 #include "llvm/CodeGen/MachineFunction.h"
24 #include "llvm/CodeGen/MachineJumpTableInfo.h"
25 #include "llvm/CodeGen/MachineMemOperand.h"
26 #include "llvm/CodeGen/RuntimeLibcalls.h"
27 #include "llvm/CodeGen/SelectionDAG.h"
28 #include "llvm/CodeGen/SelectionDAGNodes.h"
29 #include "llvm/CodeGen/TargetFrameLowering.h"
30 #include "llvm/CodeGen/TargetLowering.h"
31 #include "llvm/CodeGen/TargetSubtargetInfo.h"
32 #include "llvm/CodeGen/ValueTypes.h"
33 #include "llvm/IR/CallingConv.h"
34 #include "llvm/IR/Constants.h"
35 #include "llvm/IR/DataLayout.h"
36 #include "llvm/IR/DerivedTypes.h"
37 #include "llvm/IR/Function.h"
38 #include "llvm/IR/Metadata.h"
39 #include "llvm/IR/Type.h"
40 #include "llvm/Support/Casting.h"
41 #include "llvm/Support/Compiler.h"
42 #include "llvm/Support/Debug.h"
43 #include "llvm/Support/ErrorHandling.h"
44 #include "llvm/Support/MachineValueType.h"
45 #include "llvm/Support/MathExtras.h"
46 #include "llvm/Support/raw_ostream.h"
47 #include "llvm/Target/TargetMachine.h"
48 #include "llvm/Target/TargetOptions.h"
49 #include <cassert>
50 #include <cstdint>
51 #include <tuple>
52 #include <utility>
53 
54 using namespace llvm;
55 
56 #define DEBUG_TYPE "legalizedag"
57 
58 namespace {
59 
60 /// Keeps track of state when getting the sign of a floating-point value as an
61 /// integer.
62 struct FloatSignAsInt {
63   EVT FloatVT;
64   SDValue Chain;
65   SDValue FloatPtr;
66   SDValue IntPtr;
67   MachinePointerInfo IntPointerInfo;
68   MachinePointerInfo FloatPointerInfo;
69   SDValue IntValue;
70   APInt SignMask;
71   uint8_t SignBit;
72 };
73 
74 //===----------------------------------------------------------------------===//
75 /// This takes an arbitrary SelectionDAG as input and
76 /// hacks on it until the target machine can handle it.  This involves
77 /// eliminating value sizes the machine cannot handle (promoting small sizes to
78 /// large sizes or splitting up large values into small values) as well as
79 /// eliminating operations the machine cannot handle.
80 ///
81 /// This code also does a small amount of optimization and recognition of idioms
82 /// as part of its processing.  For example, if a target does not support a
83 /// 'setcc' instruction efficiently, but does support 'brcc' instruction, this
84 /// will attempt merge setcc and brc instructions into brcc's.
85 class SelectionDAGLegalize {
86   const TargetMachine &TM;
87   const TargetLowering &TLI;
88   SelectionDAG &DAG;
89 
90   /// The set of nodes which have already been legalized. We hold a
91   /// reference to it in order to update as necessary on node deletion.
92   SmallPtrSetImpl<SDNode *> &LegalizedNodes;
93 
94   /// A set of all the nodes updated during legalization.
95   SmallSetVector<SDNode *, 16> *UpdatedNodes;
96 
97   EVT getSetCCResultType(EVT VT) const {
98     return TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
99   }
100 
101   // Libcall insertion helpers.
102 
103 public:
104   SelectionDAGLegalize(SelectionDAG &DAG,
105                        SmallPtrSetImpl<SDNode *> &LegalizedNodes,
106                        SmallSetVector<SDNode *, 16> *UpdatedNodes = nullptr)
107       : TM(DAG.getTarget()), TLI(DAG.getTargetLoweringInfo()), DAG(DAG),
108         LegalizedNodes(LegalizedNodes), UpdatedNodes(UpdatedNodes) {}
109 
110   /// Legalizes the given operation.
111   void LegalizeOp(SDNode *Node);
112 
113 private:
114   SDValue OptimizeFloatStore(StoreSDNode *ST);
115 
116   void LegalizeLoadOps(SDNode *Node);
117   void LegalizeStoreOps(SDNode *Node);
118 
119   /// Some targets cannot handle a variable
120   /// insertion index for the INSERT_VECTOR_ELT instruction.  In this case, it
121   /// is necessary to spill the vector being inserted into to memory, perform
122   /// the insert there, and then read the result back.
123   SDValue PerformInsertVectorEltInMemory(SDValue Vec, SDValue Val, SDValue Idx,
124                                          const SDLoc &dl);
125   SDValue ExpandINSERT_VECTOR_ELT(SDValue Vec, SDValue Val, SDValue Idx,
126                                   const SDLoc &dl);
127 
128   /// Return a vector shuffle operation which
129   /// performs the same shuffe in terms of order or result bytes, but on a type
130   /// whose vector element type is narrower than the original shuffle type.
131   /// e.g. <v4i32> <0, 1, 0, 1> -> v8i16 <0, 1, 2, 3, 0, 1, 2, 3>
132   SDValue ShuffleWithNarrowerEltType(EVT NVT, EVT VT, const SDLoc &dl,
133                                      SDValue N1, SDValue N2,
134                                      ArrayRef<int> Mask) const;
135 
136   SDValue ExpandLibCall(RTLIB::Libcall LC, SDNode *Node, bool isSigned);
137 
138   void ExpandFPLibCall(SDNode *Node, RTLIB::Libcall LC,
139                        SmallVectorImpl<SDValue> &Results);
140   void ExpandFPLibCall(SDNode *Node, RTLIB::Libcall Call_F32,
141                        RTLIB::Libcall Call_F64, RTLIB::Libcall Call_F80,
142                        RTLIB::Libcall Call_F128,
143                        RTLIB::Libcall Call_PPCF128,
144                        SmallVectorImpl<SDValue> &Results);
145   SDValue ExpandIntLibCall(SDNode *Node, bool isSigned, RTLIB::Libcall Call_I8,
146                            RTLIB::Libcall Call_I16, RTLIB::Libcall Call_I32,
147                            RTLIB::Libcall Call_I64, RTLIB::Libcall Call_I128,
148                            RTLIB::Libcall Call_IEXT);
149   void ExpandArgFPLibCall(SDNode *Node,
150                           RTLIB::Libcall Call_F32, RTLIB::Libcall Call_F64,
151                           RTLIB::Libcall Call_F80, RTLIB::Libcall Call_F128,
152                           RTLIB::Libcall Call_PPCF128,
153                           SmallVectorImpl<SDValue> &Results);
154   void ExpandDivRemLibCall(SDNode *Node, SmallVectorImpl<SDValue> &Results);
155   void ExpandSinCosLibCall(SDNode *Node, SmallVectorImpl<SDValue> &Results);
156 
157   SDValue EmitStackConvert(SDValue SrcOp, EVT SlotVT, EVT DestVT,
158                            const SDLoc &dl);
159   SDValue EmitStackConvert(SDValue SrcOp, EVT SlotVT, EVT DestVT,
160                            const SDLoc &dl, SDValue ChainIn);
161   SDValue ExpandBUILD_VECTOR(SDNode *Node);
162   SDValue ExpandSPLAT_VECTOR(SDNode *Node);
163   SDValue ExpandSCALAR_TO_VECTOR(SDNode *Node);
164   void ExpandDYNAMIC_STACKALLOC(SDNode *Node,
165                                 SmallVectorImpl<SDValue> &Results);
166   void getSignAsIntValue(FloatSignAsInt &State, const SDLoc &DL,
167                          SDValue Value) const;
168   SDValue modifySignAsInt(const FloatSignAsInt &State, const SDLoc &DL,
169                           SDValue NewIntValue) const;
170   SDValue ExpandFCOPYSIGN(SDNode *Node) const;
171   SDValue ExpandFABS(SDNode *Node) const;
172   SDValue ExpandFNEG(SDNode *Node) const;
173   SDValue ExpandLegalINT_TO_FP(SDNode *Node, SDValue &Chain);
174   void PromoteLegalINT_TO_FP(SDNode *N, const SDLoc &dl,
175                              SmallVectorImpl<SDValue> &Results);
176   void PromoteLegalFP_TO_INT(SDNode *N, const SDLoc &dl,
177                              SmallVectorImpl<SDValue> &Results);
178   SDValue PromoteLegalFP_TO_INT_SAT(SDNode *Node, const SDLoc &dl);
179 
180   SDValue ExpandPARITY(SDValue Op, const SDLoc &dl);
181 
182   SDValue ExpandExtractFromVectorThroughStack(SDValue Op);
183   SDValue ExpandInsertToVectorThroughStack(SDValue Op);
184   SDValue ExpandVectorBuildThroughStack(SDNode* Node);
185 
186   SDValue ExpandConstantFP(ConstantFPSDNode *CFP, bool UseCP);
187   SDValue ExpandConstant(ConstantSDNode *CP);
188 
189   // if ExpandNode returns false, LegalizeOp falls back to ConvertNodeToLibcall
190   bool ExpandNode(SDNode *Node);
191   void ConvertNodeToLibcall(SDNode *Node);
192   void PromoteNode(SDNode *Node);
193 
194 public:
195   // Node replacement helpers
196 
197   void ReplacedNode(SDNode *N) {
198     LegalizedNodes.erase(N);
199     if (UpdatedNodes)
200       UpdatedNodes->insert(N);
201   }
202 
203   void ReplaceNode(SDNode *Old, SDNode *New) {
204     LLVM_DEBUG(dbgs() << " ... replacing: "; Old->dump(&DAG);
205                dbgs() << "     with:      "; New->dump(&DAG));
206 
207     assert(Old->getNumValues() == New->getNumValues() &&
208            "Replacing one node with another that produces a different number "
209            "of values!");
210     DAG.ReplaceAllUsesWith(Old, New);
211     if (UpdatedNodes)
212       UpdatedNodes->insert(New);
213     ReplacedNode(Old);
214   }
215 
216   void ReplaceNode(SDValue Old, SDValue New) {
217     LLVM_DEBUG(dbgs() << " ... replacing: "; Old->dump(&DAG);
218                dbgs() << "     with:      "; New->dump(&DAG));
219 
220     DAG.ReplaceAllUsesWith(Old, New);
221     if (UpdatedNodes)
222       UpdatedNodes->insert(New.getNode());
223     ReplacedNode(Old.getNode());
224   }
225 
226   void ReplaceNode(SDNode *Old, const SDValue *New) {
227     LLVM_DEBUG(dbgs() << " ... replacing: "; Old->dump(&DAG));
228 
229     DAG.ReplaceAllUsesWith(Old, New);
230     for (unsigned i = 0, e = Old->getNumValues(); i != e; ++i) {
231       LLVM_DEBUG(dbgs() << (i == 0 ? "     with:      " : "      and:      ");
232                  New[i]->dump(&DAG));
233       if (UpdatedNodes)
234         UpdatedNodes->insert(New[i].getNode());
235     }
236     ReplacedNode(Old);
237   }
238 
239   void ReplaceNodeWithValue(SDValue Old, SDValue New) {
240     LLVM_DEBUG(dbgs() << " ... replacing: "; Old->dump(&DAG);
241                dbgs() << "     with:      "; New->dump(&DAG));
242 
243     DAG.ReplaceAllUsesOfValueWith(Old, New);
244     if (UpdatedNodes)
245       UpdatedNodes->insert(New.getNode());
246     ReplacedNode(Old.getNode());
247   }
248 };
249 
250 } // end anonymous namespace
251 
252 /// Return a vector shuffle operation which
253 /// performs the same shuffle in terms of order or result bytes, but on a type
254 /// whose vector element type is narrower than the original shuffle type.
255 /// e.g. <v4i32> <0, 1, 0, 1> -> v8i16 <0, 1, 2, 3, 0, 1, 2, 3>
256 SDValue SelectionDAGLegalize::ShuffleWithNarrowerEltType(
257     EVT NVT, EVT VT, const SDLoc &dl, SDValue N1, SDValue N2,
258     ArrayRef<int> Mask) const {
259   unsigned NumMaskElts = VT.getVectorNumElements();
260   unsigned NumDestElts = NVT.getVectorNumElements();
261   unsigned NumEltsGrowth = NumDestElts / NumMaskElts;
262 
263   assert(NumEltsGrowth && "Cannot promote to vector type with fewer elts!");
264 
265   if (NumEltsGrowth == 1)
266     return DAG.getVectorShuffle(NVT, dl, N1, N2, Mask);
267 
268   SmallVector<int, 8> NewMask;
269   for (unsigned i = 0; i != NumMaskElts; ++i) {
270     int Idx = Mask[i];
271     for (unsigned j = 0; j != NumEltsGrowth; ++j) {
272       if (Idx < 0)
273         NewMask.push_back(-1);
274       else
275         NewMask.push_back(Idx * NumEltsGrowth + j);
276     }
277   }
278   assert(NewMask.size() == NumDestElts && "Non-integer NumEltsGrowth?");
279   assert(TLI.isShuffleMaskLegal(NewMask, NVT) && "Shuffle not legal?");
280   return DAG.getVectorShuffle(NVT, dl, N1, N2, NewMask);
281 }
282 
283 /// Expands the ConstantFP node to an integer constant or
284 /// a load from the constant pool.
285 SDValue
286 SelectionDAGLegalize::ExpandConstantFP(ConstantFPSDNode *CFP, bool UseCP) {
287   bool Extend = false;
288   SDLoc dl(CFP);
289 
290   // If a FP immediate is precise when represented as a float and if the
291   // target can do an extending load from float to double, we put it into
292   // the constant pool as a float, even if it's is statically typed as a
293   // double.  This shrinks FP constants and canonicalizes them for targets where
294   // an FP extending load is the same cost as a normal load (such as on the x87
295   // fp stack or PPC FP unit).
296   EVT VT = CFP->getValueType(0);
297   ConstantFP *LLVMC = const_cast<ConstantFP*>(CFP->getConstantFPValue());
298   if (!UseCP) {
299     assert((VT == MVT::f64 || VT == MVT::f32) && "Invalid type expansion");
300     return DAG.getConstant(LLVMC->getValueAPF().bitcastToAPInt(), dl,
301                            (VT == MVT::f64) ? MVT::i64 : MVT::i32);
302   }
303 
304   APFloat APF = CFP->getValueAPF();
305   EVT OrigVT = VT;
306   EVT SVT = VT;
307 
308   // We don't want to shrink SNaNs. Converting the SNaN back to its real type
309   // can cause it to be changed into a QNaN on some platforms (e.g. on SystemZ).
310   if (!APF.isSignaling()) {
311     while (SVT != MVT::f32 && SVT != MVT::f16) {
312       SVT = (MVT::SimpleValueType)(SVT.getSimpleVT().SimpleTy - 1);
313       if (ConstantFPSDNode::isValueValidForType(SVT, APF) &&
314           // Only do this if the target has a native EXTLOAD instruction from
315           // smaller type.
316           TLI.isLoadExtLegal(ISD::EXTLOAD, OrigVT, SVT) &&
317           TLI.ShouldShrinkFPConstant(OrigVT)) {
318         Type *SType = SVT.getTypeForEVT(*DAG.getContext());
319         LLVMC = cast<ConstantFP>(ConstantExpr::getFPTrunc(LLVMC, SType));
320         VT = SVT;
321         Extend = true;
322       }
323     }
324   }
325 
326   SDValue CPIdx =
327       DAG.getConstantPool(LLVMC, TLI.getPointerTy(DAG.getDataLayout()));
328   Align Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlign();
329   if (Extend) {
330     SDValue Result = DAG.getExtLoad(
331         ISD::EXTLOAD, dl, OrigVT, DAG.getEntryNode(), CPIdx,
332         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), VT,
333         Alignment);
334     return Result;
335   }
336   SDValue Result = DAG.getLoad(
337       OrigVT, dl, DAG.getEntryNode(), CPIdx,
338       MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), Alignment);
339   return Result;
340 }
341 
342 /// Expands the Constant node to a load from the constant pool.
343 SDValue SelectionDAGLegalize::ExpandConstant(ConstantSDNode *CP) {
344   SDLoc dl(CP);
345   EVT VT = CP->getValueType(0);
346   SDValue CPIdx = DAG.getConstantPool(CP->getConstantIntValue(),
347                                       TLI.getPointerTy(DAG.getDataLayout()));
348   Align Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlign();
349   SDValue Result = DAG.getLoad(
350       VT, dl, DAG.getEntryNode(), CPIdx,
351       MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), Alignment);
352   return Result;
353 }
354 
355 /// Some target cannot handle a variable insertion index for the
356 /// INSERT_VECTOR_ELT instruction.  In this case, it
357 /// is necessary to spill the vector being inserted into to memory, perform
358 /// the insert there, and then read the result back.
359 SDValue SelectionDAGLegalize::PerformInsertVectorEltInMemory(SDValue Vec,
360                                                              SDValue Val,
361                                                              SDValue Idx,
362                                                              const SDLoc &dl) {
363   SDValue Tmp1 = Vec;
364   SDValue Tmp2 = Val;
365   SDValue Tmp3 = Idx;
366 
367   // If the target doesn't support this, we have to spill the input vector
368   // to a temporary stack slot, update the element, then reload it.  This is
369   // badness.  We could also load the value into a vector register (either
370   // with a "move to register" or "extload into register" instruction, then
371   // permute it into place, if the idx is a constant and if the idx is
372   // supported by the target.
373   EVT VT    = Tmp1.getValueType();
374   EVT EltVT = VT.getVectorElementType();
375   SDValue StackPtr = DAG.CreateStackTemporary(VT);
376 
377   int SPFI = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
378 
379   // Store the vector.
380   SDValue Ch = DAG.getStore(
381       DAG.getEntryNode(), dl, Tmp1, StackPtr,
382       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI));
383 
384   SDValue StackPtr2 = TLI.getVectorElementPointer(DAG, StackPtr, VT, Tmp3);
385 
386   // Store the scalar value.
387   Ch = DAG.getTruncStore(
388       Ch, dl, Tmp2, StackPtr2,
389       MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()), EltVT);
390   // Load the updated vector.
391   return DAG.getLoad(VT, dl, Ch, StackPtr, MachinePointerInfo::getFixedStack(
392                                                DAG.getMachineFunction(), SPFI));
393 }
394 
395 SDValue SelectionDAGLegalize::ExpandINSERT_VECTOR_ELT(SDValue Vec, SDValue Val,
396                                                       SDValue Idx,
397                                                       const SDLoc &dl) {
398   if (ConstantSDNode *InsertPos = dyn_cast<ConstantSDNode>(Idx)) {
399     // SCALAR_TO_VECTOR requires that the type of the value being inserted
400     // match the element type of the vector being created, except for
401     // integers in which case the inserted value can be over width.
402     EVT EltVT = Vec.getValueType().getVectorElementType();
403     if (Val.getValueType() == EltVT ||
404         (EltVT.isInteger() && Val.getValueType().bitsGE(EltVT))) {
405       SDValue ScVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
406                                   Vec.getValueType(), Val);
407 
408       unsigned NumElts = Vec.getValueType().getVectorNumElements();
409       // We generate a shuffle of InVec and ScVec, so the shuffle mask
410       // should be 0,1,2,3,4,5... with the appropriate element replaced with
411       // elt 0 of the RHS.
412       SmallVector<int, 8> ShufOps;
413       for (unsigned i = 0; i != NumElts; ++i)
414         ShufOps.push_back(i != InsertPos->getZExtValue() ? i : NumElts);
415 
416       return DAG.getVectorShuffle(Vec.getValueType(), dl, Vec, ScVec, ShufOps);
417     }
418   }
419   return PerformInsertVectorEltInMemory(Vec, Val, Idx, dl);
420 }
421 
422 SDValue SelectionDAGLegalize::OptimizeFloatStore(StoreSDNode* ST) {
423   if (!ISD::isNormalStore(ST))
424     return SDValue();
425 
426   LLVM_DEBUG(dbgs() << "Optimizing float store operations\n");
427   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
428   // FIXME: move this to the DAG Combiner!  Note that we can't regress due
429   // to phase ordering between legalized code and the dag combiner.  This
430   // probably means that we need to integrate dag combiner and legalizer
431   // together.
432   // We generally can't do this one for long doubles.
433   SDValue Chain = ST->getChain();
434   SDValue Ptr = ST->getBasePtr();
435   SDValue Value = ST->getValue();
436   MachineMemOperand::Flags MMOFlags = ST->getMemOperand()->getFlags();
437   AAMDNodes AAInfo = ST->getAAInfo();
438   SDLoc dl(ST);
439 
440   // Don't optimise TargetConstantFP
441   if (Value.getOpcode() == ISD::TargetConstantFP)
442     return SDValue();
443 
444   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
445     if (CFP->getValueType(0) == MVT::f32 &&
446         TLI.isTypeLegal(MVT::i32)) {
447       SDValue Con = DAG.getConstant(CFP->getValueAPF().
448                                       bitcastToAPInt().zextOrTrunc(32),
449                                     SDLoc(CFP), MVT::i32);
450       return DAG.getStore(Chain, dl, Con, Ptr, ST->getPointerInfo(),
451                           ST->getOriginalAlign(), MMOFlags, AAInfo);
452     }
453 
454     if (CFP->getValueType(0) == MVT::f64) {
455       // If this target supports 64-bit registers, do a single 64-bit store.
456       if (TLI.isTypeLegal(MVT::i64)) {
457         SDValue Con = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
458                                       zextOrTrunc(64), SDLoc(CFP), MVT::i64);
459         return DAG.getStore(Chain, dl, Con, Ptr, ST->getPointerInfo(),
460                             ST->getOriginalAlign(), MMOFlags, AAInfo);
461       }
462 
463       if (TLI.isTypeLegal(MVT::i32) && !ST->isVolatile()) {
464         // Otherwise, if the target supports 32-bit registers, use 2 32-bit
465         // stores.  If the target supports neither 32- nor 64-bits, this
466         // xform is certainly not worth it.
467         const APInt &IntVal = CFP->getValueAPF().bitcastToAPInt();
468         SDValue Lo = DAG.getConstant(IntVal.trunc(32), dl, MVT::i32);
469         SDValue Hi = DAG.getConstant(IntVal.lshr(32).trunc(32), dl, MVT::i32);
470         if (DAG.getDataLayout().isBigEndian())
471           std::swap(Lo, Hi);
472 
473         Lo = DAG.getStore(Chain, dl, Lo, Ptr, ST->getPointerInfo(),
474                           ST->getOriginalAlign(), MMOFlags, AAInfo);
475         Ptr = DAG.getMemBasePlusOffset(Ptr, TypeSize::Fixed(4), dl);
476         Hi = DAG.getStore(Chain, dl, Hi, Ptr,
477                           ST->getPointerInfo().getWithOffset(4),
478                           ST->getOriginalAlign(), MMOFlags, AAInfo);
479 
480         return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo, Hi);
481       }
482     }
483   }
484   return SDValue();
485 }
486 
487 void SelectionDAGLegalize::LegalizeStoreOps(SDNode *Node) {
488   StoreSDNode *ST = cast<StoreSDNode>(Node);
489   SDValue Chain = ST->getChain();
490   SDValue Ptr = ST->getBasePtr();
491   SDLoc dl(Node);
492 
493   MachineMemOperand::Flags MMOFlags = ST->getMemOperand()->getFlags();
494   AAMDNodes AAInfo = ST->getAAInfo();
495 
496   if (!ST->isTruncatingStore()) {
497     LLVM_DEBUG(dbgs() << "Legalizing store operation\n");
498     if (SDNode *OptStore = OptimizeFloatStore(ST).getNode()) {
499       ReplaceNode(ST, OptStore);
500       return;
501     }
502 
503     SDValue Value = ST->getValue();
504     MVT VT = Value.getSimpleValueType();
505     switch (TLI.getOperationAction(ISD::STORE, VT)) {
506     default: llvm_unreachable("This action is not supported yet!");
507     case TargetLowering::Legal: {
508       // If this is an unaligned store and the target doesn't support it,
509       // expand it.
510       EVT MemVT = ST->getMemoryVT();
511       const DataLayout &DL = DAG.getDataLayout();
512       if (!TLI.allowsMemoryAccessForAlignment(*DAG.getContext(), DL, MemVT,
513                                               *ST->getMemOperand())) {
514         LLVM_DEBUG(dbgs() << "Expanding unsupported unaligned store\n");
515         SDValue Result = TLI.expandUnalignedStore(ST, DAG);
516         ReplaceNode(SDValue(ST, 0), Result);
517       } else
518         LLVM_DEBUG(dbgs() << "Legal store\n");
519       break;
520     }
521     case TargetLowering::Custom: {
522       LLVM_DEBUG(dbgs() << "Trying custom lowering\n");
523       SDValue Res = TLI.LowerOperation(SDValue(Node, 0), DAG);
524       if (Res && Res != SDValue(Node, 0))
525         ReplaceNode(SDValue(Node, 0), Res);
526       return;
527     }
528     case TargetLowering::Promote: {
529       MVT NVT = TLI.getTypeToPromoteTo(ISD::STORE, VT);
530       assert(NVT.getSizeInBits() == VT.getSizeInBits() &&
531              "Can only promote stores to same size type");
532       Value = DAG.getNode(ISD::BITCAST, dl, NVT, Value);
533       SDValue Result = DAG.getStore(Chain, dl, Value, Ptr, ST->getPointerInfo(),
534                                     ST->getOriginalAlign(), MMOFlags, AAInfo);
535       ReplaceNode(SDValue(Node, 0), Result);
536       break;
537     }
538     }
539     return;
540   }
541 
542   LLVM_DEBUG(dbgs() << "Legalizing truncating store operations\n");
543   SDValue Value = ST->getValue();
544   EVT StVT = ST->getMemoryVT();
545   TypeSize StWidth = StVT.getSizeInBits();
546   TypeSize StSize = StVT.getStoreSizeInBits();
547   auto &DL = DAG.getDataLayout();
548 
549   if (StWidth != StSize) {
550     // Promote to a byte-sized store with upper bits zero if not
551     // storing an integral number of bytes.  For example, promote
552     // TRUNCSTORE:i1 X -> TRUNCSTORE:i8 (and X, 1)
553     EVT NVT = EVT::getIntegerVT(*DAG.getContext(), StSize.getFixedSize());
554     Value = DAG.getZeroExtendInReg(Value, dl, StVT);
555     SDValue Result =
556         DAG.getTruncStore(Chain, dl, Value, Ptr, ST->getPointerInfo(), NVT,
557                           ST->getOriginalAlign(), MMOFlags, AAInfo);
558     ReplaceNode(SDValue(Node, 0), Result);
559   } else if (!StVT.isVector() && !isPowerOf2_64(StWidth.getFixedSize())) {
560     // If not storing a power-of-2 number of bits, expand as two stores.
561     assert(!StVT.isVector() && "Unsupported truncstore!");
562     unsigned StWidthBits = StWidth.getFixedSize();
563     unsigned LogStWidth = Log2_32(StWidthBits);
564     assert(LogStWidth < 32);
565     unsigned RoundWidth = 1 << LogStWidth;
566     assert(RoundWidth < StWidthBits);
567     unsigned ExtraWidth = StWidthBits - RoundWidth;
568     assert(ExtraWidth < RoundWidth);
569     assert(!(RoundWidth % 8) && !(ExtraWidth % 8) &&
570            "Store size not an integral number of bytes!");
571     EVT RoundVT = EVT::getIntegerVT(*DAG.getContext(), RoundWidth);
572     EVT ExtraVT = EVT::getIntegerVT(*DAG.getContext(), ExtraWidth);
573     SDValue Lo, Hi;
574     unsigned IncrementSize;
575 
576     if (DL.isLittleEndian()) {
577       // TRUNCSTORE:i24 X -> TRUNCSTORE:i16 X, TRUNCSTORE@+2:i8 (srl X, 16)
578       // Store the bottom RoundWidth bits.
579       Lo = DAG.getTruncStore(Chain, dl, Value, Ptr, ST->getPointerInfo(),
580                              RoundVT, ST->getOriginalAlign(), MMOFlags, AAInfo);
581 
582       // Store the remaining ExtraWidth bits.
583       IncrementSize = RoundWidth / 8;
584       Ptr = DAG.getMemBasePlusOffset(Ptr, TypeSize::Fixed(IncrementSize), dl);
585       Hi = DAG.getNode(
586           ISD::SRL, dl, Value.getValueType(), Value,
587           DAG.getConstant(RoundWidth, dl,
588                           TLI.getShiftAmountTy(Value.getValueType(), DL)));
589       Hi = DAG.getTruncStore(Chain, dl, Hi, Ptr,
590                              ST->getPointerInfo().getWithOffset(IncrementSize),
591                              ExtraVT, ST->getOriginalAlign(), MMOFlags, AAInfo);
592     } else {
593       // Big endian - avoid unaligned stores.
594       // TRUNCSTORE:i24 X -> TRUNCSTORE:i16 (srl X, 8), TRUNCSTORE@+2:i8 X
595       // Store the top RoundWidth bits.
596       Hi = DAG.getNode(
597           ISD::SRL, dl, Value.getValueType(), Value,
598           DAG.getConstant(ExtraWidth, dl,
599                           TLI.getShiftAmountTy(Value.getValueType(), DL)));
600       Hi = DAG.getTruncStore(Chain, dl, Hi, Ptr, ST->getPointerInfo(), RoundVT,
601                              ST->getOriginalAlign(), MMOFlags, AAInfo);
602 
603       // Store the remaining ExtraWidth bits.
604       IncrementSize = RoundWidth / 8;
605       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
606                         DAG.getConstant(IncrementSize, dl,
607                                         Ptr.getValueType()));
608       Lo = DAG.getTruncStore(Chain, dl, Value, Ptr,
609                              ST->getPointerInfo().getWithOffset(IncrementSize),
610                              ExtraVT, ST->getOriginalAlign(), MMOFlags, AAInfo);
611     }
612 
613     // The order of the stores doesn't matter.
614     SDValue Result = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo, Hi);
615     ReplaceNode(SDValue(Node, 0), Result);
616   } else {
617     switch (TLI.getTruncStoreAction(ST->getValue().getValueType(), StVT)) {
618     default: llvm_unreachable("This action is not supported yet!");
619     case TargetLowering::Legal: {
620       EVT MemVT = ST->getMemoryVT();
621       // If this is an unaligned store and the target doesn't support it,
622       // expand it.
623       if (!TLI.allowsMemoryAccessForAlignment(*DAG.getContext(), DL, MemVT,
624                                               *ST->getMemOperand())) {
625         SDValue Result = TLI.expandUnalignedStore(ST, DAG);
626         ReplaceNode(SDValue(ST, 0), Result);
627       }
628       break;
629     }
630     case TargetLowering::Custom: {
631       SDValue Res = TLI.LowerOperation(SDValue(Node, 0), DAG);
632       if (Res && Res != SDValue(Node, 0))
633         ReplaceNode(SDValue(Node, 0), Res);
634       return;
635     }
636     case TargetLowering::Expand:
637       assert(!StVT.isVector() &&
638              "Vector Stores are handled in LegalizeVectorOps");
639 
640       SDValue Result;
641 
642       // TRUNCSTORE:i16 i32 -> STORE i16
643       if (TLI.isTypeLegal(StVT)) {
644         Value = DAG.getNode(ISD::TRUNCATE, dl, StVT, Value);
645         Result = DAG.getStore(Chain, dl, Value, Ptr, ST->getPointerInfo(),
646                               ST->getOriginalAlign(), MMOFlags, AAInfo);
647       } else {
648         // The in-memory type isn't legal. Truncate to the type it would promote
649         // to, and then do a truncstore.
650         Value = DAG.getNode(ISD::TRUNCATE, dl,
651                             TLI.getTypeToTransformTo(*DAG.getContext(), StVT),
652                             Value);
653         Result =
654             DAG.getTruncStore(Chain, dl, Value, Ptr, ST->getPointerInfo(), StVT,
655                               ST->getOriginalAlign(), MMOFlags, AAInfo);
656       }
657 
658       ReplaceNode(SDValue(Node, 0), Result);
659       break;
660     }
661   }
662 }
663 
664 void SelectionDAGLegalize::LegalizeLoadOps(SDNode *Node) {
665   LoadSDNode *LD = cast<LoadSDNode>(Node);
666   SDValue Chain = LD->getChain();  // The chain.
667   SDValue Ptr = LD->getBasePtr();  // The base pointer.
668   SDValue Value;                   // The value returned by the load op.
669   SDLoc dl(Node);
670 
671   ISD::LoadExtType ExtType = LD->getExtensionType();
672   if (ExtType == ISD::NON_EXTLOAD) {
673     LLVM_DEBUG(dbgs() << "Legalizing non-extending load operation\n");
674     MVT VT = Node->getSimpleValueType(0);
675     SDValue RVal = SDValue(Node, 0);
676     SDValue RChain = SDValue(Node, 1);
677 
678     switch (TLI.getOperationAction(Node->getOpcode(), VT)) {
679     default: llvm_unreachable("This action is not supported yet!");
680     case TargetLowering::Legal: {
681       EVT MemVT = LD->getMemoryVT();
682       const DataLayout &DL = DAG.getDataLayout();
683       // If this is an unaligned load and the target doesn't support it,
684       // expand it.
685       if (!TLI.allowsMemoryAccessForAlignment(*DAG.getContext(), DL, MemVT,
686                                               *LD->getMemOperand())) {
687         std::tie(RVal, RChain) = TLI.expandUnalignedLoad(LD, DAG);
688       }
689       break;
690     }
691     case TargetLowering::Custom:
692       if (SDValue Res = TLI.LowerOperation(RVal, DAG)) {
693         RVal = Res;
694         RChain = Res.getValue(1);
695       }
696       break;
697 
698     case TargetLowering::Promote: {
699       MVT NVT = TLI.getTypeToPromoteTo(Node->getOpcode(), VT);
700       assert(NVT.getSizeInBits() == VT.getSizeInBits() &&
701              "Can only promote loads to same size type");
702 
703       SDValue Res = DAG.getLoad(NVT, dl, Chain, Ptr, LD->getMemOperand());
704       RVal = DAG.getNode(ISD::BITCAST, dl, VT, Res);
705       RChain = Res.getValue(1);
706       break;
707     }
708     }
709     if (RChain.getNode() != Node) {
710       assert(RVal.getNode() != Node && "Load must be completely replaced");
711       DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 0), RVal);
712       DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), RChain);
713       if (UpdatedNodes) {
714         UpdatedNodes->insert(RVal.getNode());
715         UpdatedNodes->insert(RChain.getNode());
716       }
717       ReplacedNode(Node);
718     }
719     return;
720   }
721 
722   LLVM_DEBUG(dbgs() << "Legalizing extending load operation\n");
723   EVT SrcVT = LD->getMemoryVT();
724   TypeSize SrcWidth = SrcVT.getSizeInBits();
725   MachineMemOperand::Flags MMOFlags = LD->getMemOperand()->getFlags();
726   AAMDNodes AAInfo = LD->getAAInfo();
727 
728   if (SrcWidth != SrcVT.getStoreSizeInBits() &&
729       // Some targets pretend to have an i1 loading operation, and actually
730       // load an i8.  This trick is correct for ZEXTLOAD because the top 7
731       // bits are guaranteed to be zero; it helps the optimizers understand
732       // that these bits are zero.  It is also useful for EXTLOAD, since it
733       // tells the optimizers that those bits are undefined.  It would be
734       // nice to have an effective generic way of getting these benefits...
735       // Until such a way is found, don't insist on promoting i1 here.
736       (SrcVT != MVT::i1 ||
737        TLI.getLoadExtAction(ExtType, Node->getValueType(0), MVT::i1) ==
738          TargetLowering::Promote)) {
739     // Promote to a byte-sized load if not loading an integral number of
740     // bytes.  For example, promote EXTLOAD:i20 -> EXTLOAD:i24.
741     unsigned NewWidth = SrcVT.getStoreSizeInBits();
742     EVT NVT = EVT::getIntegerVT(*DAG.getContext(), NewWidth);
743     SDValue Ch;
744 
745     // The extra bits are guaranteed to be zero, since we stored them that
746     // way.  A zext load from NVT thus automatically gives zext from SrcVT.
747 
748     ISD::LoadExtType NewExtType =
749       ExtType == ISD::ZEXTLOAD ? ISD::ZEXTLOAD : ISD::EXTLOAD;
750 
751     SDValue Result = DAG.getExtLoad(NewExtType, dl, Node->getValueType(0),
752                                     Chain, Ptr, LD->getPointerInfo(), NVT,
753                                     LD->getOriginalAlign(), MMOFlags, AAInfo);
754 
755     Ch = Result.getValue(1); // The chain.
756 
757     if (ExtType == ISD::SEXTLOAD)
758       // Having the top bits zero doesn't help when sign extending.
759       Result = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl,
760                            Result.getValueType(),
761                            Result, DAG.getValueType(SrcVT));
762     else if (ExtType == ISD::ZEXTLOAD || NVT == Result.getValueType())
763       // All the top bits are guaranteed to be zero - inform the optimizers.
764       Result = DAG.getNode(ISD::AssertZext, dl,
765                            Result.getValueType(), Result,
766                            DAG.getValueType(SrcVT));
767 
768     Value = Result;
769     Chain = Ch;
770   } else if (!isPowerOf2_64(SrcWidth.getKnownMinSize())) {
771     // If not loading a power-of-2 number of bits, expand as two loads.
772     assert(!SrcVT.isVector() && "Unsupported extload!");
773     unsigned SrcWidthBits = SrcWidth.getFixedSize();
774     unsigned LogSrcWidth = Log2_32(SrcWidthBits);
775     assert(LogSrcWidth < 32);
776     unsigned RoundWidth = 1 << LogSrcWidth;
777     assert(RoundWidth < SrcWidthBits);
778     unsigned ExtraWidth = SrcWidthBits - RoundWidth;
779     assert(ExtraWidth < RoundWidth);
780     assert(!(RoundWidth % 8) && !(ExtraWidth % 8) &&
781            "Load size not an integral number of bytes!");
782     EVT RoundVT = EVT::getIntegerVT(*DAG.getContext(), RoundWidth);
783     EVT ExtraVT = EVT::getIntegerVT(*DAG.getContext(), ExtraWidth);
784     SDValue Lo, Hi, Ch;
785     unsigned IncrementSize;
786     auto &DL = DAG.getDataLayout();
787 
788     if (DL.isLittleEndian()) {
789       // EXTLOAD:i24 -> ZEXTLOAD:i16 | (shl EXTLOAD@+2:i8, 16)
790       // Load the bottom RoundWidth bits.
791       Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, Node->getValueType(0), Chain, Ptr,
792                           LD->getPointerInfo(), RoundVT, LD->getOriginalAlign(),
793                           MMOFlags, AAInfo);
794 
795       // Load the remaining ExtraWidth bits.
796       IncrementSize = RoundWidth / 8;
797       Ptr = DAG.getMemBasePlusOffset(Ptr, TypeSize::Fixed(IncrementSize), dl);
798       Hi = DAG.getExtLoad(ExtType, dl, Node->getValueType(0), Chain, Ptr,
799                           LD->getPointerInfo().getWithOffset(IncrementSize),
800                           ExtraVT, LD->getOriginalAlign(), MMOFlags, AAInfo);
801 
802       // Build a factor node to remember that this load is independent of
803       // the other one.
804       Ch = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1),
805                        Hi.getValue(1));
806 
807       // Move the top bits to the right place.
808       Hi = DAG.getNode(
809           ISD::SHL, dl, Hi.getValueType(), Hi,
810           DAG.getConstant(RoundWidth, dl,
811                           TLI.getShiftAmountTy(Hi.getValueType(), DL)));
812 
813       // Join the hi and lo parts.
814       Value = DAG.getNode(ISD::OR, dl, Node->getValueType(0), Lo, Hi);
815     } else {
816       // Big endian - avoid unaligned loads.
817       // EXTLOAD:i24 -> (shl EXTLOAD:i16, 8) | ZEXTLOAD@+2:i8
818       // Load the top RoundWidth bits.
819       Hi = DAG.getExtLoad(ExtType, dl, Node->getValueType(0), Chain, Ptr,
820                           LD->getPointerInfo(), RoundVT, LD->getOriginalAlign(),
821                           MMOFlags, AAInfo);
822 
823       // Load the remaining ExtraWidth bits.
824       IncrementSize = RoundWidth / 8;
825       Ptr = DAG.getMemBasePlusOffset(Ptr, TypeSize::Fixed(IncrementSize), dl);
826       Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, Node->getValueType(0), Chain, Ptr,
827                           LD->getPointerInfo().getWithOffset(IncrementSize),
828                           ExtraVT, LD->getOriginalAlign(), MMOFlags, AAInfo);
829 
830       // Build a factor node to remember that this load is independent of
831       // the other one.
832       Ch = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1),
833                        Hi.getValue(1));
834 
835       // Move the top bits to the right place.
836       Hi = DAG.getNode(
837           ISD::SHL, dl, Hi.getValueType(), Hi,
838           DAG.getConstant(ExtraWidth, dl,
839                           TLI.getShiftAmountTy(Hi.getValueType(), DL)));
840 
841       // Join the hi and lo parts.
842       Value = DAG.getNode(ISD::OR, dl, Node->getValueType(0), Lo, Hi);
843     }
844 
845     Chain = Ch;
846   } else {
847     bool isCustom = false;
848     switch (TLI.getLoadExtAction(ExtType, Node->getValueType(0),
849                                  SrcVT.getSimpleVT())) {
850     default: llvm_unreachable("This action is not supported yet!");
851     case TargetLowering::Custom:
852       isCustom = true;
853       LLVM_FALLTHROUGH;
854     case TargetLowering::Legal:
855       Value = SDValue(Node, 0);
856       Chain = SDValue(Node, 1);
857 
858       if (isCustom) {
859         if (SDValue Res = TLI.LowerOperation(SDValue(Node, 0), DAG)) {
860           Value = Res;
861           Chain = Res.getValue(1);
862         }
863       } else {
864         // If this is an unaligned load and the target doesn't support it,
865         // expand it.
866         EVT MemVT = LD->getMemoryVT();
867         const DataLayout &DL = DAG.getDataLayout();
868         if (!TLI.allowsMemoryAccess(*DAG.getContext(), DL, MemVT,
869                                     *LD->getMemOperand())) {
870           std::tie(Value, Chain) = TLI.expandUnalignedLoad(LD, DAG);
871         }
872       }
873       break;
874 
875     case TargetLowering::Expand: {
876       EVT DestVT = Node->getValueType(0);
877       if (!TLI.isLoadExtLegal(ISD::EXTLOAD, DestVT, SrcVT)) {
878         // If the source type is not legal, see if there is a legal extload to
879         // an intermediate type that we can then extend further.
880         EVT LoadVT = TLI.getRegisterType(SrcVT.getSimpleVT());
881         if (TLI.isTypeLegal(SrcVT) || // Same as SrcVT == LoadVT?
882             TLI.isLoadExtLegal(ExtType, LoadVT, SrcVT)) {
883           // If we are loading a legal type, this is a non-extload followed by a
884           // full extend.
885           ISD::LoadExtType MidExtType =
886               (LoadVT == SrcVT) ? ISD::NON_EXTLOAD : ExtType;
887 
888           SDValue Load = DAG.getExtLoad(MidExtType, dl, LoadVT, Chain, Ptr,
889                                         SrcVT, LD->getMemOperand());
890           unsigned ExtendOp =
891               ISD::getExtForLoadExtType(SrcVT.isFloatingPoint(), ExtType);
892           Value = DAG.getNode(ExtendOp, dl, Node->getValueType(0), Load);
893           Chain = Load.getValue(1);
894           break;
895         }
896 
897         // Handle the special case of fp16 extloads. EXTLOAD doesn't have the
898         // normal undefined upper bits behavior to allow using an in-reg extend
899         // with the illegal FP type, so load as an integer and do the
900         // from-integer conversion.
901         if (SrcVT.getScalarType() == MVT::f16) {
902           EVT ISrcVT = SrcVT.changeTypeToInteger();
903           EVT IDestVT = DestVT.changeTypeToInteger();
904           EVT ILoadVT = TLI.getRegisterType(IDestVT.getSimpleVT());
905 
906           SDValue Result = DAG.getExtLoad(ISD::ZEXTLOAD, dl, ILoadVT, Chain,
907                                           Ptr, ISrcVT, LD->getMemOperand());
908           Value = DAG.getNode(ISD::FP16_TO_FP, dl, DestVT, Result);
909           Chain = Result.getValue(1);
910           break;
911         }
912       }
913 
914       assert(!SrcVT.isVector() &&
915              "Vector Loads are handled in LegalizeVectorOps");
916 
917       // FIXME: This does not work for vectors on most targets.  Sign-
918       // and zero-extend operations are currently folded into extending
919       // loads, whether they are legal or not, and then we end up here
920       // without any support for legalizing them.
921       assert(ExtType != ISD::EXTLOAD &&
922              "EXTLOAD should always be supported!");
923       // Turn the unsupported load into an EXTLOAD followed by an
924       // explicit zero/sign extend inreg.
925       SDValue Result = DAG.getExtLoad(ISD::EXTLOAD, dl,
926                                       Node->getValueType(0),
927                                       Chain, Ptr, SrcVT,
928                                       LD->getMemOperand());
929       SDValue ValRes;
930       if (ExtType == ISD::SEXTLOAD)
931         ValRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl,
932                              Result.getValueType(),
933                              Result, DAG.getValueType(SrcVT));
934       else
935         ValRes = DAG.getZeroExtendInReg(Result, dl, SrcVT);
936       Value = ValRes;
937       Chain = Result.getValue(1);
938       break;
939     }
940     }
941   }
942 
943   // Since loads produce two values, make sure to remember that we legalized
944   // both of them.
945   if (Chain.getNode() != Node) {
946     assert(Value.getNode() != Node && "Load must be completely replaced");
947     DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 0), Value);
948     DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), Chain);
949     if (UpdatedNodes) {
950       UpdatedNodes->insert(Value.getNode());
951       UpdatedNodes->insert(Chain.getNode());
952     }
953     ReplacedNode(Node);
954   }
955 }
956 
957 /// Return a legal replacement for the given operation, with all legal operands.
958 void SelectionDAGLegalize::LegalizeOp(SDNode *Node) {
959   LLVM_DEBUG(dbgs() << "\nLegalizing: "; Node->dump(&DAG));
960 
961   // Allow illegal target nodes and illegal registers.
962   if (Node->getOpcode() == ISD::TargetConstant ||
963       Node->getOpcode() == ISD::Register)
964     return;
965 
966 #ifndef NDEBUG
967   for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
968     assert(TLI.getTypeAction(*DAG.getContext(), Node->getValueType(i)) ==
969              TargetLowering::TypeLegal &&
970            "Unexpected illegal type!");
971 
972   for (const SDValue &Op : Node->op_values())
973     assert((TLI.getTypeAction(*DAG.getContext(), Op.getValueType()) ==
974               TargetLowering::TypeLegal ||
975             Op.getOpcode() == ISD::TargetConstant ||
976             Op.getOpcode() == ISD::Register) &&
977             "Unexpected illegal type!");
978 #endif
979 
980   // Figure out the correct action; the way to query this varies by opcode
981   TargetLowering::LegalizeAction Action = TargetLowering::Legal;
982   bool SimpleFinishLegalizing = true;
983   switch (Node->getOpcode()) {
984   case ISD::INTRINSIC_W_CHAIN:
985   case ISD::INTRINSIC_WO_CHAIN:
986   case ISD::INTRINSIC_VOID:
987   case ISD::STACKSAVE:
988     Action = TLI.getOperationAction(Node->getOpcode(), MVT::Other);
989     break;
990   case ISD::GET_DYNAMIC_AREA_OFFSET:
991     Action = TLI.getOperationAction(Node->getOpcode(),
992                                     Node->getValueType(0));
993     break;
994   case ISD::VAARG:
995     Action = TLI.getOperationAction(Node->getOpcode(),
996                                     Node->getValueType(0));
997     if (Action != TargetLowering::Promote)
998       Action = TLI.getOperationAction(Node->getOpcode(), MVT::Other);
999     break;
1000   case ISD::FP_TO_FP16:
1001   case ISD::FP_TO_BF16:
1002   case ISD::SINT_TO_FP:
1003   case ISD::UINT_TO_FP:
1004   case ISD::EXTRACT_VECTOR_ELT:
1005   case ISD::LROUND:
1006   case ISD::LLROUND:
1007   case ISD::LRINT:
1008   case ISD::LLRINT:
1009     Action = TLI.getOperationAction(Node->getOpcode(),
1010                                     Node->getOperand(0).getValueType());
1011     break;
1012   case ISD::STRICT_FP_TO_FP16:
1013   case ISD::STRICT_SINT_TO_FP:
1014   case ISD::STRICT_UINT_TO_FP:
1015   case ISD::STRICT_LRINT:
1016   case ISD::STRICT_LLRINT:
1017   case ISD::STRICT_LROUND:
1018   case ISD::STRICT_LLROUND:
1019     // These pseudo-ops are the same as the other STRICT_ ops except
1020     // they are registered with setOperationAction() using the input type
1021     // instead of the output type.
1022     Action = TLI.getOperationAction(Node->getOpcode(),
1023                                     Node->getOperand(1).getValueType());
1024     break;
1025   case ISD::SIGN_EXTEND_INREG: {
1026     EVT InnerType = cast<VTSDNode>(Node->getOperand(1))->getVT();
1027     Action = TLI.getOperationAction(Node->getOpcode(), InnerType);
1028     break;
1029   }
1030   case ISD::ATOMIC_STORE:
1031     Action = TLI.getOperationAction(Node->getOpcode(),
1032                                     Node->getOperand(2).getValueType());
1033     break;
1034   case ISD::SELECT_CC:
1035   case ISD::STRICT_FSETCC:
1036   case ISD::STRICT_FSETCCS:
1037   case ISD::SETCC:
1038   case ISD::VP_SETCC:
1039   case ISD::BR_CC: {
1040     unsigned Opc = Node->getOpcode();
1041     unsigned CCOperand = Opc == ISD::SELECT_CC                         ? 4
1042                          : Opc == ISD::STRICT_FSETCC                   ? 3
1043                          : Opc == ISD::STRICT_FSETCCS                  ? 3
1044                          : (Opc == ISD::SETCC || Opc == ISD::VP_SETCC) ? 2
1045                                                                        : 1;
1046     unsigned CompareOperand = Opc == ISD::BR_CC            ? 2
1047                               : Opc == ISD::STRICT_FSETCC  ? 1
1048                               : Opc == ISD::STRICT_FSETCCS ? 1
1049                                                            : 0;
1050     MVT OpVT = Node->getOperand(CompareOperand).getSimpleValueType();
1051     ISD::CondCode CCCode =
1052         cast<CondCodeSDNode>(Node->getOperand(CCOperand))->get();
1053     Action = TLI.getCondCodeAction(CCCode, OpVT);
1054     if (Action == TargetLowering::Legal) {
1055       if (Node->getOpcode() == ISD::SELECT_CC)
1056         Action = TLI.getOperationAction(Node->getOpcode(),
1057                                         Node->getValueType(0));
1058       else
1059         Action = TLI.getOperationAction(Node->getOpcode(), OpVT);
1060     }
1061     break;
1062   }
1063   case ISD::LOAD:
1064   case ISD::STORE:
1065     // FIXME: Model these properly.  LOAD and STORE are complicated, and
1066     // STORE expects the unlegalized operand in some cases.
1067     SimpleFinishLegalizing = false;
1068     break;
1069   case ISD::CALLSEQ_START:
1070   case ISD::CALLSEQ_END:
1071     // FIXME: This shouldn't be necessary.  These nodes have special properties
1072     // dealing with the recursive nature of legalization.  Removing this
1073     // special case should be done as part of making LegalizeDAG non-recursive.
1074     SimpleFinishLegalizing = false;
1075     break;
1076   case ISD::EXTRACT_ELEMENT:
1077   case ISD::FLT_ROUNDS_:
1078   case ISD::MERGE_VALUES:
1079   case ISD::EH_RETURN:
1080   case ISD::FRAME_TO_ARGS_OFFSET:
1081   case ISD::EH_DWARF_CFA:
1082   case ISD::EH_SJLJ_SETJMP:
1083   case ISD::EH_SJLJ_LONGJMP:
1084   case ISD::EH_SJLJ_SETUP_DISPATCH:
1085     // These operations lie about being legal: when they claim to be legal,
1086     // they should actually be expanded.
1087     Action = TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0));
1088     if (Action == TargetLowering::Legal)
1089       Action = TargetLowering::Expand;
1090     break;
1091   case ISD::INIT_TRAMPOLINE:
1092   case ISD::ADJUST_TRAMPOLINE:
1093   case ISD::FRAMEADDR:
1094   case ISD::RETURNADDR:
1095   case ISD::ADDROFRETURNADDR:
1096   case ISD::SPONENTRY:
1097     // These operations lie about being legal: when they claim to be legal,
1098     // they should actually be custom-lowered.
1099     Action = TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0));
1100     if (Action == TargetLowering::Legal)
1101       Action = TargetLowering::Custom;
1102     break;
1103   case ISD::READCYCLECOUNTER:
1104     // READCYCLECOUNTER returns an i64, even if type legalization might have
1105     // expanded that to several smaller types.
1106     Action = TLI.getOperationAction(Node->getOpcode(), MVT::i64);
1107     break;
1108   case ISD::READ_REGISTER:
1109   case ISD::WRITE_REGISTER:
1110     // Named register is legal in the DAG, but blocked by register name
1111     // selection if not implemented by target (to chose the correct register)
1112     // They'll be converted to Copy(To/From)Reg.
1113     Action = TargetLowering::Legal;
1114     break;
1115   case ISD::UBSANTRAP:
1116     Action = TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0));
1117     if (Action == TargetLowering::Expand) {
1118       // replace ISD::UBSANTRAP with ISD::TRAP
1119       SDValue NewVal;
1120       NewVal = DAG.getNode(ISD::TRAP, SDLoc(Node), Node->getVTList(),
1121                            Node->getOperand(0));
1122       ReplaceNode(Node, NewVal.getNode());
1123       LegalizeOp(NewVal.getNode());
1124       return;
1125     }
1126     break;
1127   case ISD::DEBUGTRAP:
1128     Action = TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0));
1129     if (Action == TargetLowering::Expand) {
1130       // replace ISD::DEBUGTRAP with ISD::TRAP
1131       SDValue NewVal;
1132       NewVal = DAG.getNode(ISD::TRAP, SDLoc(Node), Node->getVTList(),
1133                            Node->getOperand(0));
1134       ReplaceNode(Node, NewVal.getNode());
1135       LegalizeOp(NewVal.getNode());
1136       return;
1137     }
1138     break;
1139   case ISD::SADDSAT:
1140   case ISD::UADDSAT:
1141   case ISD::SSUBSAT:
1142   case ISD::USUBSAT:
1143   case ISD::SSHLSAT:
1144   case ISD::USHLSAT:
1145   case ISD::FP_TO_SINT_SAT:
1146   case ISD::FP_TO_UINT_SAT:
1147     Action = TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0));
1148     break;
1149   case ISD::SMULFIX:
1150   case ISD::SMULFIXSAT:
1151   case ISD::UMULFIX:
1152   case ISD::UMULFIXSAT:
1153   case ISD::SDIVFIX:
1154   case ISD::SDIVFIXSAT:
1155   case ISD::UDIVFIX:
1156   case ISD::UDIVFIXSAT: {
1157     unsigned Scale = Node->getConstantOperandVal(2);
1158     Action = TLI.getFixedPointOperationAction(Node->getOpcode(),
1159                                               Node->getValueType(0), Scale);
1160     break;
1161   }
1162   case ISD::MSCATTER:
1163     Action = TLI.getOperationAction(Node->getOpcode(),
1164                     cast<MaskedScatterSDNode>(Node)->getValue().getValueType());
1165     break;
1166   case ISD::MSTORE:
1167     Action = TLI.getOperationAction(Node->getOpcode(),
1168                     cast<MaskedStoreSDNode>(Node)->getValue().getValueType());
1169     break;
1170   case ISD::VP_SCATTER:
1171     Action = TLI.getOperationAction(
1172         Node->getOpcode(),
1173         cast<VPScatterSDNode>(Node)->getValue().getValueType());
1174     break;
1175   case ISD::VP_STORE:
1176     Action = TLI.getOperationAction(
1177         Node->getOpcode(),
1178         cast<VPStoreSDNode>(Node)->getValue().getValueType());
1179     break;
1180   case ISD::EXPERIMENTAL_VP_STRIDED_STORE:
1181     Action = TLI.getOperationAction(
1182         Node->getOpcode(),
1183         cast<VPStridedStoreSDNode>(Node)->getValue().getValueType());
1184     break;
1185   case ISD::VECREDUCE_FADD:
1186   case ISD::VECREDUCE_FMUL:
1187   case ISD::VECREDUCE_ADD:
1188   case ISD::VECREDUCE_MUL:
1189   case ISD::VECREDUCE_AND:
1190   case ISD::VECREDUCE_OR:
1191   case ISD::VECREDUCE_XOR:
1192   case ISD::VECREDUCE_SMAX:
1193   case ISD::VECREDUCE_SMIN:
1194   case ISD::VECREDUCE_UMAX:
1195   case ISD::VECREDUCE_UMIN:
1196   case ISD::VECREDUCE_FMAX:
1197   case ISD::VECREDUCE_FMIN:
1198   case ISD::IS_FPCLASS:
1199     Action = TLI.getOperationAction(
1200         Node->getOpcode(), Node->getOperand(0).getValueType());
1201     break;
1202   case ISD::VECREDUCE_SEQ_FADD:
1203   case ISD::VECREDUCE_SEQ_FMUL:
1204   case ISD::VP_REDUCE_FADD:
1205   case ISD::VP_REDUCE_FMUL:
1206   case ISD::VP_REDUCE_ADD:
1207   case ISD::VP_REDUCE_MUL:
1208   case ISD::VP_REDUCE_AND:
1209   case ISD::VP_REDUCE_OR:
1210   case ISD::VP_REDUCE_XOR:
1211   case ISD::VP_REDUCE_SMAX:
1212   case ISD::VP_REDUCE_SMIN:
1213   case ISD::VP_REDUCE_UMAX:
1214   case ISD::VP_REDUCE_UMIN:
1215   case ISD::VP_REDUCE_FMAX:
1216   case ISD::VP_REDUCE_FMIN:
1217   case ISD::VP_REDUCE_SEQ_FADD:
1218   case ISD::VP_REDUCE_SEQ_FMUL:
1219     Action = TLI.getOperationAction(
1220         Node->getOpcode(), Node->getOperand(1).getValueType());
1221     break;
1222   default:
1223     if (Node->getOpcode() >= ISD::BUILTIN_OP_END) {
1224       Action = TLI.getCustomOperationAction(*Node);
1225     } else {
1226       Action = TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0));
1227     }
1228     break;
1229   }
1230 
1231   if (SimpleFinishLegalizing) {
1232     SDNode *NewNode = Node;
1233     switch (Node->getOpcode()) {
1234     default: break;
1235     case ISD::SHL:
1236     case ISD::SRL:
1237     case ISD::SRA:
1238     case ISD::ROTL:
1239     case ISD::ROTR: {
1240       // Legalizing shifts/rotates requires adjusting the shift amount
1241       // to the appropriate width.
1242       SDValue Op0 = Node->getOperand(0);
1243       SDValue Op1 = Node->getOperand(1);
1244       if (!Op1.getValueType().isVector()) {
1245         SDValue SAO = DAG.getShiftAmountOperand(Op0.getValueType(), Op1);
1246         // The getShiftAmountOperand() may create a new operand node or
1247         // return the existing one. If new operand is created we need
1248         // to update the parent node.
1249         // Do not try to legalize SAO here! It will be automatically legalized
1250         // in the next round.
1251         if (SAO != Op1)
1252           NewNode = DAG.UpdateNodeOperands(Node, Op0, SAO);
1253       }
1254     }
1255     break;
1256     case ISD::FSHL:
1257     case ISD::FSHR:
1258     case ISD::SRL_PARTS:
1259     case ISD::SRA_PARTS:
1260     case ISD::SHL_PARTS: {
1261       // Legalizing shifts/rotates requires adjusting the shift amount
1262       // to the appropriate width.
1263       SDValue Op0 = Node->getOperand(0);
1264       SDValue Op1 = Node->getOperand(1);
1265       SDValue Op2 = Node->getOperand(2);
1266       if (!Op2.getValueType().isVector()) {
1267         SDValue SAO = DAG.getShiftAmountOperand(Op0.getValueType(), Op2);
1268         // The getShiftAmountOperand() may create a new operand node or
1269         // return the existing one. If new operand is created we need
1270         // to update the parent node.
1271         if (SAO != Op2)
1272           NewNode = DAG.UpdateNodeOperands(Node, Op0, Op1, SAO);
1273       }
1274       break;
1275     }
1276     }
1277 
1278     if (NewNode != Node) {
1279       ReplaceNode(Node, NewNode);
1280       Node = NewNode;
1281     }
1282     switch (Action) {
1283     case TargetLowering::Legal:
1284       LLVM_DEBUG(dbgs() << "Legal node: nothing to do\n");
1285       return;
1286     case TargetLowering::Custom:
1287       LLVM_DEBUG(dbgs() << "Trying custom legalization\n");
1288       // FIXME: The handling for custom lowering with multiple results is
1289       // a complete mess.
1290       if (SDValue Res = TLI.LowerOperation(SDValue(Node, 0), DAG)) {
1291         if (!(Res.getNode() != Node || Res.getResNo() != 0))
1292           return;
1293 
1294         if (Node->getNumValues() == 1) {
1295           // Verify the new types match the original. Glue is waived because
1296           // ISD::ADDC can be legalized by replacing Glue with an integer type.
1297           assert((Res.getValueType() == Node->getValueType(0) ||
1298                   Node->getValueType(0) == MVT::Glue) &&
1299                  "Type mismatch for custom legalized operation");
1300           LLVM_DEBUG(dbgs() << "Successfully custom legalized node\n");
1301           // We can just directly replace this node with the lowered value.
1302           ReplaceNode(SDValue(Node, 0), Res);
1303           return;
1304         }
1305 
1306         SmallVector<SDValue, 8> ResultVals;
1307         for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i) {
1308           // Verify the new types match the original. Glue is waived because
1309           // ISD::ADDC can be legalized by replacing Glue with an integer type.
1310           assert((Res->getValueType(i) == Node->getValueType(i) ||
1311                   Node->getValueType(i) == MVT::Glue) &&
1312                  "Type mismatch for custom legalized operation");
1313           ResultVals.push_back(Res.getValue(i));
1314         }
1315         LLVM_DEBUG(dbgs() << "Successfully custom legalized node\n");
1316         ReplaceNode(Node, ResultVals.data());
1317         return;
1318       }
1319       LLVM_DEBUG(dbgs() << "Could not custom legalize node\n");
1320       LLVM_FALLTHROUGH;
1321     case TargetLowering::Expand:
1322       if (ExpandNode(Node))
1323         return;
1324       LLVM_FALLTHROUGH;
1325     case TargetLowering::LibCall:
1326       ConvertNodeToLibcall(Node);
1327       return;
1328     case TargetLowering::Promote:
1329       PromoteNode(Node);
1330       return;
1331     }
1332   }
1333 
1334   switch (Node->getOpcode()) {
1335   default:
1336 #ifndef NDEBUG
1337     dbgs() << "NODE: ";
1338     Node->dump( &DAG);
1339     dbgs() << "\n";
1340 #endif
1341     llvm_unreachable("Do not know how to legalize this operator!");
1342 
1343   case ISD::CALLSEQ_START:
1344   case ISD::CALLSEQ_END:
1345     break;
1346   case ISD::LOAD:
1347     return LegalizeLoadOps(Node);
1348   case ISD::STORE:
1349     return LegalizeStoreOps(Node);
1350   }
1351 }
1352 
1353 SDValue SelectionDAGLegalize::ExpandExtractFromVectorThroughStack(SDValue Op) {
1354   SDValue Vec = Op.getOperand(0);
1355   SDValue Idx = Op.getOperand(1);
1356   SDLoc dl(Op);
1357 
1358   // Before we generate a new store to a temporary stack slot, see if there is
1359   // already one that we can use. There often is because when we scalarize
1360   // vector operations (using SelectionDAG::UnrollVectorOp for example) a whole
1361   // series of EXTRACT_VECTOR_ELT nodes are generated, one for each element in
1362   // the vector. If all are expanded here, we don't want one store per vector
1363   // element.
1364 
1365   // Caches for hasPredecessorHelper
1366   SmallPtrSet<const SDNode *, 32> Visited;
1367   SmallVector<const SDNode *, 16> Worklist;
1368   Visited.insert(Op.getNode());
1369   Worklist.push_back(Idx.getNode());
1370   SDValue StackPtr, Ch;
1371   for (SDNode *User : Vec.getNode()->uses()) {
1372     if (StoreSDNode *ST = dyn_cast<StoreSDNode>(User)) {
1373       if (ST->isIndexed() || ST->isTruncatingStore() ||
1374           ST->getValue() != Vec)
1375         continue;
1376 
1377       // Make sure that nothing else could have stored into the destination of
1378       // this store.
1379       if (!ST->getChain().reachesChainWithoutSideEffects(DAG.getEntryNode()))
1380         continue;
1381 
1382       // If the index is dependent on the store we will introduce a cycle when
1383       // creating the load (the load uses the index, and by replacing the chain
1384       // we will make the index dependent on the load). Also, the store might be
1385       // dependent on the extractelement and introduce a cycle when creating
1386       // the load.
1387       if (SDNode::hasPredecessorHelper(ST, Visited, Worklist) ||
1388           ST->hasPredecessor(Op.getNode()))
1389         continue;
1390 
1391       StackPtr = ST->getBasePtr();
1392       Ch = SDValue(ST, 0);
1393       break;
1394     }
1395   }
1396 
1397   EVT VecVT = Vec.getValueType();
1398 
1399   if (!Ch.getNode()) {
1400     // Store the value to a temporary stack slot, then LOAD the returned part.
1401     StackPtr = DAG.CreateStackTemporary(VecVT);
1402     Ch = DAG.getStore(DAG.getEntryNode(), dl, Vec, StackPtr,
1403                       MachinePointerInfo());
1404   }
1405 
1406   SDValue NewLoad;
1407 
1408   if (Op.getValueType().isVector()) {
1409     StackPtr = TLI.getVectorSubVecPointer(DAG, StackPtr, VecVT,
1410                                           Op.getValueType(), Idx);
1411     NewLoad =
1412         DAG.getLoad(Op.getValueType(), dl, Ch, StackPtr, MachinePointerInfo());
1413   } else {
1414     StackPtr = TLI.getVectorElementPointer(DAG, StackPtr, VecVT, Idx);
1415     NewLoad = DAG.getExtLoad(ISD::EXTLOAD, dl, Op.getValueType(), Ch, StackPtr,
1416                              MachinePointerInfo(),
1417                              VecVT.getVectorElementType());
1418   }
1419 
1420   // Replace the chain going out of the store, by the one out of the load.
1421   DAG.ReplaceAllUsesOfValueWith(Ch, SDValue(NewLoad.getNode(), 1));
1422 
1423   // We introduced a cycle though, so update the loads operands, making sure
1424   // to use the original store's chain as an incoming chain.
1425   SmallVector<SDValue, 6> NewLoadOperands(NewLoad->op_begin(),
1426                                           NewLoad->op_end());
1427   NewLoadOperands[0] = Ch;
1428   NewLoad =
1429       SDValue(DAG.UpdateNodeOperands(NewLoad.getNode(), NewLoadOperands), 0);
1430   return NewLoad;
1431 }
1432 
1433 SDValue SelectionDAGLegalize::ExpandInsertToVectorThroughStack(SDValue Op) {
1434   assert(Op.getValueType().isVector() && "Non-vector insert subvector!");
1435 
1436   SDValue Vec  = Op.getOperand(0);
1437   SDValue Part = Op.getOperand(1);
1438   SDValue Idx  = Op.getOperand(2);
1439   SDLoc dl(Op);
1440 
1441   // Store the value to a temporary stack slot, then LOAD the returned part.
1442   EVT VecVT = Vec.getValueType();
1443   EVT SubVecVT = Part.getValueType();
1444   SDValue StackPtr = DAG.CreateStackTemporary(VecVT);
1445   int FI = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
1446   MachinePointerInfo PtrInfo =
1447       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
1448 
1449   // First store the whole vector.
1450   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, Vec, StackPtr, PtrInfo);
1451 
1452   // Then store the inserted part.
1453   SDValue SubStackPtr =
1454       TLI.getVectorSubVecPointer(DAG, StackPtr, VecVT, SubVecVT, Idx);
1455 
1456   // Store the subvector.
1457   Ch = DAG.getStore(
1458       Ch, dl, Part, SubStackPtr,
1459       MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()));
1460 
1461   // Finally, load the updated vector.
1462   return DAG.getLoad(Op.getValueType(), dl, Ch, StackPtr, PtrInfo);
1463 }
1464 
1465 SDValue SelectionDAGLegalize::ExpandVectorBuildThroughStack(SDNode* Node) {
1466   assert((Node->getOpcode() == ISD::BUILD_VECTOR ||
1467           Node->getOpcode() == ISD::CONCAT_VECTORS) &&
1468          "Unexpected opcode!");
1469 
1470   // We can't handle this case efficiently.  Allocate a sufficiently
1471   // aligned object on the stack, store each operand into it, then load
1472   // the result as a vector.
1473   // Create the stack frame object.
1474   EVT VT = Node->getValueType(0);
1475   EVT MemVT = isa<BuildVectorSDNode>(Node) ? VT.getVectorElementType()
1476                                            : Node->getOperand(0).getValueType();
1477   SDLoc dl(Node);
1478   SDValue FIPtr = DAG.CreateStackTemporary(VT);
1479   int FI = cast<FrameIndexSDNode>(FIPtr.getNode())->getIndex();
1480   MachinePointerInfo PtrInfo =
1481       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
1482 
1483   // Emit a store of each element to the stack slot.
1484   SmallVector<SDValue, 8> Stores;
1485   unsigned TypeByteSize = MemVT.getSizeInBits() / 8;
1486   assert(TypeByteSize > 0 && "Vector element type too small for stack store!");
1487 
1488   // If the destination vector element type of a BUILD_VECTOR is narrower than
1489   // the source element type, only store the bits necessary.
1490   bool Truncate = isa<BuildVectorSDNode>(Node) &&
1491                   MemVT.bitsLT(Node->getOperand(0).getValueType());
1492 
1493   // Store (in the right endianness) the elements to memory.
1494   for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) {
1495     // Ignore undef elements.
1496     if (Node->getOperand(i).isUndef()) continue;
1497 
1498     unsigned Offset = TypeByteSize*i;
1499 
1500     SDValue Idx = DAG.getMemBasePlusOffset(FIPtr, TypeSize::Fixed(Offset), dl);
1501 
1502     if (Truncate)
1503       Stores.push_back(DAG.getTruncStore(DAG.getEntryNode(), dl,
1504                                          Node->getOperand(i), Idx,
1505                                          PtrInfo.getWithOffset(Offset), MemVT));
1506     else
1507       Stores.push_back(DAG.getStore(DAG.getEntryNode(), dl, Node->getOperand(i),
1508                                     Idx, PtrInfo.getWithOffset(Offset)));
1509   }
1510 
1511   SDValue StoreChain;
1512   if (!Stores.empty())    // Not all undef elements?
1513     StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
1514   else
1515     StoreChain = DAG.getEntryNode();
1516 
1517   // Result is a load from the stack slot.
1518   return DAG.getLoad(VT, dl, StoreChain, FIPtr, PtrInfo);
1519 }
1520 
1521 /// Bitcast a floating-point value to an integer value. Only bitcast the part
1522 /// containing the sign bit if the target has no integer value capable of
1523 /// holding all bits of the floating-point value.
1524 void SelectionDAGLegalize::getSignAsIntValue(FloatSignAsInt &State,
1525                                              const SDLoc &DL,
1526                                              SDValue Value) const {
1527   EVT FloatVT = Value.getValueType();
1528   unsigned NumBits = FloatVT.getScalarSizeInBits();
1529   State.FloatVT = FloatVT;
1530   EVT IVT = EVT::getIntegerVT(*DAG.getContext(), NumBits);
1531   // Convert to an integer of the same size.
1532   if (TLI.isTypeLegal(IVT)) {
1533     State.IntValue = DAG.getNode(ISD::BITCAST, DL, IVT, Value);
1534     State.SignMask = APInt::getSignMask(NumBits);
1535     State.SignBit = NumBits - 1;
1536     return;
1537   }
1538 
1539   auto &DataLayout = DAG.getDataLayout();
1540   // Store the float to memory, then load the sign part out as an integer.
1541   MVT LoadTy = TLI.getRegisterType(*DAG.getContext(), MVT::i8);
1542   // First create a temporary that is aligned for both the load and store.
1543   SDValue StackPtr = DAG.CreateStackTemporary(FloatVT, LoadTy);
1544   int FI = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
1545   // Then store the float to it.
1546   State.FloatPtr = StackPtr;
1547   MachineFunction &MF = DAG.getMachineFunction();
1548   State.FloatPointerInfo = MachinePointerInfo::getFixedStack(MF, FI);
1549   State.Chain = DAG.getStore(DAG.getEntryNode(), DL, Value, State.FloatPtr,
1550                              State.FloatPointerInfo);
1551 
1552   SDValue IntPtr;
1553   if (DataLayout.isBigEndian()) {
1554     assert(FloatVT.isByteSized() && "Unsupported floating point type!");
1555     // Load out a legal integer with the same sign bit as the float.
1556     IntPtr = StackPtr;
1557     State.IntPointerInfo = State.FloatPointerInfo;
1558   } else {
1559     // Advance the pointer so that the loaded byte will contain the sign bit.
1560     unsigned ByteOffset = (NumBits / 8) - 1;
1561     IntPtr =
1562         DAG.getMemBasePlusOffset(StackPtr, TypeSize::Fixed(ByteOffset), DL);
1563     State.IntPointerInfo = MachinePointerInfo::getFixedStack(MF, FI,
1564                                                              ByteOffset);
1565   }
1566 
1567   State.IntPtr = IntPtr;
1568   State.IntValue = DAG.getExtLoad(ISD::EXTLOAD, DL, LoadTy, State.Chain, IntPtr,
1569                                   State.IntPointerInfo, MVT::i8);
1570   State.SignMask = APInt::getOneBitSet(LoadTy.getScalarSizeInBits(), 7);
1571   State.SignBit = 7;
1572 }
1573 
1574 /// Replace the integer value produced by getSignAsIntValue() with a new value
1575 /// and cast the result back to a floating-point type.
1576 SDValue SelectionDAGLegalize::modifySignAsInt(const FloatSignAsInt &State,
1577                                               const SDLoc &DL,
1578                                               SDValue NewIntValue) const {
1579   if (!State.Chain)
1580     return DAG.getNode(ISD::BITCAST, DL, State.FloatVT, NewIntValue);
1581 
1582   // Override the part containing the sign bit in the value stored on the stack.
1583   SDValue Chain = DAG.getTruncStore(State.Chain, DL, NewIntValue, State.IntPtr,
1584                                     State.IntPointerInfo, MVT::i8);
1585   return DAG.getLoad(State.FloatVT, DL, Chain, State.FloatPtr,
1586                      State.FloatPointerInfo);
1587 }
1588 
1589 SDValue SelectionDAGLegalize::ExpandFCOPYSIGN(SDNode *Node) const {
1590   SDLoc DL(Node);
1591   SDValue Mag = Node->getOperand(0);
1592   SDValue Sign = Node->getOperand(1);
1593 
1594   // Get sign bit into an integer value.
1595   FloatSignAsInt SignAsInt;
1596   getSignAsIntValue(SignAsInt, DL, Sign);
1597 
1598   EVT IntVT = SignAsInt.IntValue.getValueType();
1599   SDValue SignMask = DAG.getConstant(SignAsInt.SignMask, DL, IntVT);
1600   SDValue SignBit = DAG.getNode(ISD::AND, DL, IntVT, SignAsInt.IntValue,
1601                                 SignMask);
1602 
1603   // If FABS is legal transform FCOPYSIGN(x, y) => sign(x) ? -FABS(x) : FABS(X)
1604   EVT FloatVT = Mag.getValueType();
1605   if (TLI.isOperationLegalOrCustom(ISD::FABS, FloatVT) &&
1606       TLI.isOperationLegalOrCustom(ISD::FNEG, FloatVT)) {
1607     SDValue AbsValue = DAG.getNode(ISD::FABS, DL, FloatVT, Mag);
1608     SDValue NegValue = DAG.getNode(ISD::FNEG, DL, FloatVT, AbsValue);
1609     SDValue Cond = DAG.getSetCC(DL, getSetCCResultType(IntVT), SignBit,
1610                                 DAG.getConstant(0, DL, IntVT), ISD::SETNE);
1611     return DAG.getSelect(DL, FloatVT, Cond, NegValue, AbsValue);
1612   }
1613 
1614   // Transform Mag value to integer, and clear the sign bit.
1615   FloatSignAsInt MagAsInt;
1616   getSignAsIntValue(MagAsInt, DL, Mag);
1617   EVT MagVT = MagAsInt.IntValue.getValueType();
1618   SDValue ClearSignMask = DAG.getConstant(~MagAsInt.SignMask, DL, MagVT);
1619   SDValue ClearedSign = DAG.getNode(ISD::AND, DL, MagVT, MagAsInt.IntValue,
1620                                     ClearSignMask);
1621 
1622   // Get the signbit at the right position for MagAsInt.
1623   int ShiftAmount = SignAsInt.SignBit - MagAsInt.SignBit;
1624   EVT ShiftVT = IntVT;
1625   if (SignBit.getScalarValueSizeInBits() <
1626       ClearedSign.getScalarValueSizeInBits()) {
1627     SignBit = DAG.getNode(ISD::ZERO_EXTEND, DL, MagVT, SignBit);
1628     ShiftVT = MagVT;
1629   }
1630   if (ShiftAmount > 0) {
1631     SDValue ShiftCnst = DAG.getConstant(ShiftAmount, DL, ShiftVT);
1632     SignBit = DAG.getNode(ISD::SRL, DL, ShiftVT, SignBit, ShiftCnst);
1633   } else if (ShiftAmount < 0) {
1634     SDValue ShiftCnst = DAG.getConstant(-ShiftAmount, DL, ShiftVT);
1635     SignBit = DAG.getNode(ISD::SHL, DL, ShiftVT, SignBit, ShiftCnst);
1636   }
1637   if (SignBit.getScalarValueSizeInBits() >
1638       ClearedSign.getScalarValueSizeInBits()) {
1639     SignBit = DAG.getNode(ISD::TRUNCATE, DL, MagVT, SignBit);
1640   }
1641 
1642   // Store the part with the modified sign and convert back to float.
1643   SDValue CopiedSign = DAG.getNode(ISD::OR, DL, MagVT, ClearedSign, SignBit);
1644   return modifySignAsInt(MagAsInt, DL, CopiedSign);
1645 }
1646 
1647 SDValue SelectionDAGLegalize::ExpandFNEG(SDNode *Node) const {
1648   // Get the sign bit as an integer.
1649   SDLoc DL(Node);
1650   FloatSignAsInt SignAsInt;
1651   getSignAsIntValue(SignAsInt, DL, Node->getOperand(0));
1652   EVT IntVT = SignAsInt.IntValue.getValueType();
1653 
1654   // Flip the sign.
1655   SDValue SignMask = DAG.getConstant(SignAsInt.SignMask, DL, IntVT);
1656   SDValue SignFlip =
1657       DAG.getNode(ISD::XOR, DL, IntVT, SignAsInt.IntValue, SignMask);
1658 
1659   // Convert back to float.
1660   return modifySignAsInt(SignAsInt, DL, SignFlip);
1661 }
1662 
1663 SDValue SelectionDAGLegalize::ExpandFABS(SDNode *Node) const {
1664   SDLoc DL(Node);
1665   SDValue Value = Node->getOperand(0);
1666 
1667   // Transform FABS(x) => FCOPYSIGN(x, 0.0) if FCOPYSIGN is legal.
1668   EVT FloatVT = Value.getValueType();
1669   if (TLI.isOperationLegalOrCustom(ISD::FCOPYSIGN, FloatVT)) {
1670     SDValue Zero = DAG.getConstantFP(0.0, DL, FloatVT);
1671     return DAG.getNode(ISD::FCOPYSIGN, DL, FloatVT, Value, Zero);
1672   }
1673 
1674   // Transform value to integer, clear the sign bit and transform back.
1675   FloatSignAsInt ValueAsInt;
1676   getSignAsIntValue(ValueAsInt, DL, Value);
1677   EVT IntVT = ValueAsInt.IntValue.getValueType();
1678   SDValue ClearSignMask = DAG.getConstant(~ValueAsInt.SignMask, DL, IntVT);
1679   SDValue ClearedSign = DAG.getNode(ISD::AND, DL, IntVT, ValueAsInt.IntValue,
1680                                     ClearSignMask);
1681   return modifySignAsInt(ValueAsInt, DL, ClearedSign);
1682 }
1683 
1684 void SelectionDAGLegalize::ExpandDYNAMIC_STACKALLOC(SDNode* Node,
1685                                            SmallVectorImpl<SDValue> &Results) {
1686   Register SPReg = TLI.getStackPointerRegisterToSaveRestore();
1687   assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
1688           " not tell us which reg is the stack pointer!");
1689   SDLoc dl(Node);
1690   EVT VT = Node->getValueType(0);
1691   SDValue Tmp1 = SDValue(Node, 0);
1692   SDValue Tmp2 = SDValue(Node, 1);
1693   SDValue Tmp3 = Node->getOperand(2);
1694   SDValue Chain = Tmp1.getOperand(0);
1695 
1696   // Chain the dynamic stack allocation so that it doesn't modify the stack
1697   // pointer when other instructions are using the stack.
1698   Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl);
1699 
1700   SDValue Size  = Tmp2.getOperand(1);
1701   SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
1702   Chain = SP.getValue(1);
1703   Align Alignment = cast<ConstantSDNode>(Tmp3)->getAlignValue();
1704   const TargetFrameLowering *TFL = DAG.getSubtarget().getFrameLowering();
1705   unsigned Opc =
1706     TFL->getStackGrowthDirection() == TargetFrameLowering::StackGrowsUp ?
1707     ISD::ADD : ISD::SUB;
1708 
1709   Align StackAlign = TFL->getStackAlign();
1710   Tmp1 = DAG.getNode(Opc, dl, VT, SP, Size);       // Value
1711   if (Alignment > StackAlign)
1712     Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
1713                        DAG.getConstant(-Alignment.value(), dl, VT));
1714   Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1);     // Output chain
1715 
1716   Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
1717                             DAG.getIntPtrConstant(0, dl, true), SDValue(), dl);
1718 
1719   Results.push_back(Tmp1);
1720   Results.push_back(Tmp2);
1721 }
1722 
1723 /// Emit a store/load combination to the stack.  This stores
1724 /// SrcOp to a stack slot of type SlotVT, truncating it if needed.  It then does
1725 /// a load from the stack slot to DestVT, extending it if needed.
1726 /// The resultant code need not be legal.
1727 SDValue SelectionDAGLegalize::EmitStackConvert(SDValue SrcOp, EVT SlotVT,
1728                                                EVT DestVT, const SDLoc &dl) {
1729   return EmitStackConvert(SrcOp, SlotVT, DestVT, dl, DAG.getEntryNode());
1730 }
1731 
1732 SDValue SelectionDAGLegalize::EmitStackConvert(SDValue SrcOp, EVT SlotVT,
1733                                                EVT DestVT, const SDLoc &dl,
1734                                                SDValue Chain) {
1735   EVT SrcVT = SrcOp.getValueType();
1736   Type *DestType = DestVT.getTypeForEVT(*DAG.getContext());
1737   Align DestAlign = DAG.getDataLayout().getPrefTypeAlign(DestType);
1738 
1739   // Don't convert with stack if the load/store is expensive.
1740   if ((SrcVT.bitsGT(SlotVT) &&
1741        !TLI.isTruncStoreLegalOrCustom(SrcOp.getValueType(), SlotVT)) ||
1742       (SlotVT.bitsLT(DestVT) &&
1743        !TLI.isLoadExtLegalOrCustom(ISD::EXTLOAD, DestVT, SlotVT)))
1744     return SDValue();
1745 
1746   // Create the stack frame object.
1747   Align SrcAlign = DAG.getDataLayout().getPrefTypeAlign(
1748       SrcOp.getValueType().getTypeForEVT(*DAG.getContext()));
1749   SDValue FIPtr = DAG.CreateStackTemporary(SlotVT.getStoreSize(), SrcAlign);
1750 
1751   FrameIndexSDNode *StackPtrFI = cast<FrameIndexSDNode>(FIPtr);
1752   int SPFI = StackPtrFI->getIndex();
1753   MachinePointerInfo PtrInfo =
1754       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI);
1755 
1756   // Emit a store to the stack slot.  Use a truncstore if the input value is
1757   // later than DestVT.
1758   SDValue Store;
1759 
1760   if (SrcVT.bitsGT(SlotVT))
1761     Store = DAG.getTruncStore(Chain, dl, SrcOp, FIPtr, PtrInfo,
1762                               SlotVT, SrcAlign);
1763   else {
1764     assert(SrcVT.bitsEq(SlotVT) && "Invalid store");
1765     Store = DAG.getStore(Chain, dl, SrcOp, FIPtr, PtrInfo, SrcAlign);
1766   }
1767 
1768   // Result is a load from the stack slot.
1769   if (SlotVT.bitsEq(DestVT))
1770     return DAG.getLoad(DestVT, dl, Store, FIPtr, PtrInfo, DestAlign);
1771 
1772   assert(SlotVT.bitsLT(DestVT) && "Unknown extension!");
1773   return DAG.getExtLoad(ISD::EXTLOAD, dl, DestVT, Store, FIPtr, PtrInfo, SlotVT,
1774                         DestAlign);
1775 }
1776 
1777 SDValue SelectionDAGLegalize::ExpandSCALAR_TO_VECTOR(SDNode *Node) {
1778   SDLoc dl(Node);
1779   // Create a vector sized/aligned stack slot, store the value to element #0,
1780   // then load the whole vector back out.
1781   SDValue StackPtr = DAG.CreateStackTemporary(Node->getValueType(0));
1782 
1783   FrameIndexSDNode *StackPtrFI = cast<FrameIndexSDNode>(StackPtr);
1784   int SPFI = StackPtrFI->getIndex();
1785 
1786   SDValue Ch = DAG.getTruncStore(
1787       DAG.getEntryNode(), dl, Node->getOperand(0), StackPtr,
1788       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI),
1789       Node->getValueType(0).getVectorElementType());
1790   return DAG.getLoad(
1791       Node->getValueType(0), dl, Ch, StackPtr,
1792       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI));
1793 }
1794 
1795 static bool
1796 ExpandBVWithShuffles(SDNode *Node, SelectionDAG &DAG,
1797                      const TargetLowering &TLI, SDValue &Res) {
1798   unsigned NumElems = Node->getNumOperands();
1799   SDLoc dl(Node);
1800   EVT VT = Node->getValueType(0);
1801 
1802   // Try to group the scalars into pairs, shuffle the pairs together, then
1803   // shuffle the pairs of pairs together, etc. until the vector has
1804   // been built. This will work only if all of the necessary shuffle masks
1805   // are legal.
1806 
1807   // We do this in two phases; first to check the legality of the shuffles,
1808   // and next, assuming that all shuffles are legal, to create the new nodes.
1809   for (int Phase = 0; Phase < 2; ++Phase) {
1810     SmallVector<std::pair<SDValue, SmallVector<int, 16>>, 16> IntermedVals,
1811                                                               NewIntermedVals;
1812     for (unsigned i = 0; i < NumElems; ++i) {
1813       SDValue V = Node->getOperand(i);
1814       if (V.isUndef())
1815         continue;
1816 
1817       SDValue Vec;
1818       if (Phase)
1819         Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, V);
1820       IntermedVals.push_back(std::make_pair(Vec, SmallVector<int, 16>(1, i)));
1821     }
1822 
1823     while (IntermedVals.size() > 2) {
1824       NewIntermedVals.clear();
1825       for (unsigned i = 0, e = (IntermedVals.size() & ~1u); i < e; i += 2) {
1826         // This vector and the next vector are shuffled together (simply to
1827         // append the one to the other).
1828         SmallVector<int, 16> ShuffleVec(NumElems, -1);
1829 
1830         SmallVector<int, 16> FinalIndices;
1831         FinalIndices.reserve(IntermedVals[i].second.size() +
1832                              IntermedVals[i+1].second.size());
1833 
1834         int k = 0;
1835         for (unsigned j = 0, f = IntermedVals[i].second.size(); j != f;
1836              ++j, ++k) {
1837           ShuffleVec[k] = j;
1838           FinalIndices.push_back(IntermedVals[i].second[j]);
1839         }
1840         for (unsigned j = 0, f = IntermedVals[i+1].second.size(); j != f;
1841              ++j, ++k) {
1842           ShuffleVec[k] = NumElems + j;
1843           FinalIndices.push_back(IntermedVals[i+1].second[j]);
1844         }
1845 
1846         SDValue Shuffle;
1847         if (Phase)
1848           Shuffle = DAG.getVectorShuffle(VT, dl, IntermedVals[i].first,
1849                                          IntermedVals[i+1].first,
1850                                          ShuffleVec);
1851         else if (!TLI.isShuffleMaskLegal(ShuffleVec, VT))
1852           return false;
1853         NewIntermedVals.push_back(
1854             std::make_pair(Shuffle, std::move(FinalIndices)));
1855       }
1856 
1857       // If we had an odd number of defined values, then append the last
1858       // element to the array of new vectors.
1859       if ((IntermedVals.size() & 1) != 0)
1860         NewIntermedVals.push_back(IntermedVals.back());
1861 
1862       IntermedVals.swap(NewIntermedVals);
1863     }
1864 
1865     assert(IntermedVals.size() <= 2 && IntermedVals.size() > 0 &&
1866            "Invalid number of intermediate vectors");
1867     SDValue Vec1 = IntermedVals[0].first;
1868     SDValue Vec2;
1869     if (IntermedVals.size() > 1)
1870       Vec2 = IntermedVals[1].first;
1871     else if (Phase)
1872       Vec2 = DAG.getUNDEF(VT);
1873 
1874     SmallVector<int, 16> ShuffleVec(NumElems, -1);
1875     for (unsigned i = 0, e = IntermedVals[0].second.size(); i != e; ++i)
1876       ShuffleVec[IntermedVals[0].second[i]] = i;
1877     for (unsigned i = 0, e = IntermedVals[1].second.size(); i != e; ++i)
1878       ShuffleVec[IntermedVals[1].second[i]] = NumElems + i;
1879 
1880     if (Phase)
1881       Res = DAG.getVectorShuffle(VT, dl, Vec1, Vec2, ShuffleVec);
1882     else if (!TLI.isShuffleMaskLegal(ShuffleVec, VT))
1883       return false;
1884   }
1885 
1886   return true;
1887 }
1888 
1889 /// Expand a BUILD_VECTOR node on targets that don't
1890 /// support the operation, but do support the resultant vector type.
1891 SDValue SelectionDAGLegalize::ExpandBUILD_VECTOR(SDNode *Node) {
1892   unsigned NumElems = Node->getNumOperands();
1893   SDValue Value1, Value2;
1894   SDLoc dl(Node);
1895   EVT VT = Node->getValueType(0);
1896   EVT OpVT = Node->getOperand(0).getValueType();
1897   EVT EltVT = VT.getVectorElementType();
1898 
1899   // If the only non-undef value is the low element, turn this into a
1900   // SCALAR_TO_VECTOR node.  If this is { X, X, X, X }, determine X.
1901   bool isOnlyLowElement = true;
1902   bool MoreThanTwoValues = false;
1903   bool isConstant = true;
1904   for (unsigned i = 0; i < NumElems; ++i) {
1905     SDValue V = Node->getOperand(i);
1906     if (V.isUndef())
1907       continue;
1908     if (i > 0)
1909       isOnlyLowElement = false;
1910     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
1911       isConstant = false;
1912 
1913     if (!Value1.getNode()) {
1914       Value1 = V;
1915     } else if (!Value2.getNode()) {
1916       if (V != Value1)
1917         Value2 = V;
1918     } else if (V != Value1 && V != Value2) {
1919       MoreThanTwoValues = true;
1920     }
1921   }
1922 
1923   if (!Value1.getNode())
1924     return DAG.getUNDEF(VT);
1925 
1926   if (isOnlyLowElement)
1927     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Node->getOperand(0));
1928 
1929   // If all elements are constants, create a load from the constant pool.
1930   if (isConstant) {
1931     SmallVector<Constant*, 16> CV;
1932     for (unsigned i = 0, e = NumElems; i != e; ++i) {
1933       if (ConstantFPSDNode *V =
1934           dyn_cast<ConstantFPSDNode>(Node->getOperand(i))) {
1935         CV.push_back(const_cast<ConstantFP *>(V->getConstantFPValue()));
1936       } else if (ConstantSDNode *V =
1937                  dyn_cast<ConstantSDNode>(Node->getOperand(i))) {
1938         if (OpVT==EltVT)
1939           CV.push_back(const_cast<ConstantInt *>(V->getConstantIntValue()));
1940         else {
1941           // If OpVT and EltVT don't match, EltVT is not legal and the
1942           // element values have been promoted/truncated earlier.  Undo this;
1943           // we don't want a v16i8 to become a v16i32 for example.
1944           const ConstantInt *CI = V->getConstantIntValue();
1945           CV.push_back(ConstantInt::get(EltVT.getTypeForEVT(*DAG.getContext()),
1946                                         CI->getZExtValue()));
1947         }
1948       } else {
1949         assert(Node->getOperand(i).isUndef());
1950         Type *OpNTy = EltVT.getTypeForEVT(*DAG.getContext());
1951         CV.push_back(UndefValue::get(OpNTy));
1952       }
1953     }
1954     Constant *CP = ConstantVector::get(CV);
1955     SDValue CPIdx =
1956         DAG.getConstantPool(CP, TLI.getPointerTy(DAG.getDataLayout()));
1957     Align Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlign();
1958     return DAG.getLoad(
1959         VT, dl, DAG.getEntryNode(), CPIdx,
1960         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
1961         Alignment);
1962   }
1963 
1964   SmallSet<SDValue, 16> DefinedValues;
1965   for (unsigned i = 0; i < NumElems; ++i) {
1966     if (Node->getOperand(i).isUndef())
1967       continue;
1968     DefinedValues.insert(Node->getOperand(i));
1969   }
1970 
1971   if (TLI.shouldExpandBuildVectorWithShuffles(VT, DefinedValues.size())) {
1972     if (!MoreThanTwoValues) {
1973       SmallVector<int, 8> ShuffleVec(NumElems, -1);
1974       for (unsigned i = 0; i < NumElems; ++i) {
1975         SDValue V = Node->getOperand(i);
1976         if (V.isUndef())
1977           continue;
1978         ShuffleVec[i] = V == Value1 ? 0 : NumElems;
1979       }
1980       if (TLI.isShuffleMaskLegal(ShuffleVec, Node->getValueType(0))) {
1981         // Get the splatted value into the low element of a vector register.
1982         SDValue Vec1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value1);
1983         SDValue Vec2;
1984         if (Value2.getNode())
1985           Vec2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value2);
1986         else
1987           Vec2 = DAG.getUNDEF(VT);
1988 
1989         // Return shuffle(LowValVec, undef, <0,0,0,0>)
1990         return DAG.getVectorShuffle(VT, dl, Vec1, Vec2, ShuffleVec);
1991       }
1992     } else {
1993       SDValue Res;
1994       if (ExpandBVWithShuffles(Node, DAG, TLI, Res))
1995         return Res;
1996     }
1997   }
1998 
1999   // Otherwise, we can't handle this case efficiently.
2000   return ExpandVectorBuildThroughStack(Node);
2001 }
2002 
2003 SDValue SelectionDAGLegalize::ExpandSPLAT_VECTOR(SDNode *Node) {
2004   SDLoc DL(Node);
2005   EVT VT = Node->getValueType(0);
2006   SDValue SplatVal = Node->getOperand(0);
2007 
2008   return DAG.getSplatBuildVector(VT, DL, SplatVal);
2009 }
2010 
2011 // Expand a node into a call to a libcall.  If the result value
2012 // does not fit into a register, return the lo part and set the hi part to the
2013 // by-reg argument.  If it does fit into a single register, return the result
2014 // and leave the Hi part unset.
2015 SDValue SelectionDAGLegalize::ExpandLibCall(RTLIB::Libcall LC, SDNode *Node,
2016                                             bool isSigned) {
2017   TargetLowering::ArgListTy Args;
2018   TargetLowering::ArgListEntry Entry;
2019   for (const SDValue &Op : Node->op_values()) {
2020     EVT ArgVT = Op.getValueType();
2021     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
2022     Entry.Node = Op;
2023     Entry.Ty = ArgTy;
2024     Entry.IsSExt = TLI.shouldSignExtendTypeInLibCall(ArgVT, isSigned);
2025     Entry.IsZExt = !TLI.shouldSignExtendTypeInLibCall(ArgVT, isSigned);
2026     Args.push_back(Entry);
2027   }
2028   SDValue Callee = DAG.getExternalSymbol(TLI.getLibcallName(LC),
2029                                          TLI.getPointerTy(DAG.getDataLayout()));
2030 
2031   EVT RetVT = Node->getValueType(0);
2032   Type *RetTy = RetVT.getTypeForEVT(*DAG.getContext());
2033 
2034   // By default, the input chain to this libcall is the entry node of the
2035   // function. If the libcall is going to be emitted as a tail call then
2036   // TLI.isUsedByReturnOnly will change it to the right chain if the return
2037   // node which is being folded has a non-entry input chain.
2038   SDValue InChain = DAG.getEntryNode();
2039 
2040   // isTailCall may be true since the callee does not reference caller stack
2041   // frame. Check if it's in the right position and that the return types match.
2042   SDValue TCChain = InChain;
2043   const Function &F = DAG.getMachineFunction().getFunction();
2044   bool isTailCall =
2045       TLI.isInTailCallPosition(DAG, Node, TCChain) &&
2046       (RetTy == F.getReturnType() || F.getReturnType()->isVoidTy());
2047   if (isTailCall)
2048     InChain = TCChain;
2049 
2050   TargetLowering::CallLoweringInfo CLI(DAG);
2051   bool signExtend = TLI.shouldSignExtendTypeInLibCall(RetVT, isSigned);
2052   CLI.setDebugLoc(SDLoc(Node))
2053       .setChain(InChain)
2054       .setLibCallee(TLI.getLibcallCallingConv(LC), RetTy, Callee,
2055                     std::move(Args))
2056       .setTailCall(isTailCall)
2057       .setSExtResult(signExtend)
2058       .setZExtResult(!signExtend)
2059       .setIsPostTypeLegalization(true);
2060 
2061   std::pair<SDValue, SDValue> CallInfo = TLI.LowerCallTo(CLI);
2062 
2063   if (!CallInfo.second.getNode()) {
2064     LLVM_DEBUG(dbgs() << "Created tailcall: "; DAG.getRoot().dump(&DAG));
2065     // It's a tailcall, return the chain (which is the DAG root).
2066     return DAG.getRoot();
2067   }
2068 
2069   LLVM_DEBUG(dbgs() << "Created libcall: "; CallInfo.first.dump(&DAG));
2070   return CallInfo.first;
2071 }
2072 
2073 void SelectionDAGLegalize::ExpandFPLibCall(SDNode* Node,
2074                                            RTLIB::Libcall LC,
2075                                            SmallVectorImpl<SDValue> &Results) {
2076   if (LC == RTLIB::UNKNOWN_LIBCALL)
2077     llvm_unreachable("Can't create an unknown libcall!");
2078 
2079   if (Node->isStrictFPOpcode()) {
2080     EVT RetVT = Node->getValueType(0);
2081     SmallVector<SDValue, 4> Ops(drop_begin(Node->ops()));
2082     TargetLowering::MakeLibCallOptions CallOptions;
2083     // FIXME: This doesn't support tail calls.
2084     std::pair<SDValue, SDValue> Tmp = TLI.makeLibCall(DAG, LC, RetVT,
2085                                                       Ops, CallOptions,
2086                                                       SDLoc(Node),
2087                                                       Node->getOperand(0));
2088     Results.push_back(Tmp.first);
2089     Results.push_back(Tmp.second);
2090   } else {
2091     SDValue Tmp = ExpandLibCall(LC, Node, false);
2092     Results.push_back(Tmp);
2093   }
2094 }
2095 
2096 /// Expand the node to a libcall based on the result type.
2097 void SelectionDAGLegalize::ExpandFPLibCall(SDNode* Node,
2098                                            RTLIB::Libcall Call_F32,
2099                                            RTLIB::Libcall Call_F64,
2100                                            RTLIB::Libcall Call_F80,
2101                                            RTLIB::Libcall Call_F128,
2102                                            RTLIB::Libcall Call_PPCF128,
2103                                            SmallVectorImpl<SDValue> &Results) {
2104   RTLIB::Libcall LC = RTLIB::getFPLibCall(Node->getSimpleValueType(0),
2105                                           Call_F32, Call_F64, Call_F80,
2106                                           Call_F128, Call_PPCF128);
2107   ExpandFPLibCall(Node, LC, Results);
2108 }
2109 
2110 SDValue SelectionDAGLegalize::ExpandIntLibCall(
2111     SDNode *Node, bool isSigned, RTLIB::Libcall Call_I8,
2112     RTLIB::Libcall Call_I16, RTLIB::Libcall Call_I32, RTLIB::Libcall Call_I64,
2113     RTLIB::Libcall Call_I128, RTLIB::Libcall Call_IEXT) {
2114   RTLIB::Libcall LC;
2115   switch (Node->getSimpleValueType(0).SimpleTy) {
2116 
2117   default:
2118     LC = Call_IEXT;
2119     break;
2120 
2121   case MVT::i8:   LC = Call_I8; break;
2122   case MVT::i16:  LC = Call_I16; break;
2123   case MVT::i32:  LC = Call_I32; break;
2124   case MVT::i64:  LC = Call_I64; break;
2125   case MVT::i128: LC = Call_I128; break;
2126   }
2127   return ExpandLibCall(LC, Node, isSigned);
2128 }
2129 
2130 /// Expand the node to a libcall based on first argument type (for instance
2131 /// lround and its variant).
2132 void SelectionDAGLegalize::ExpandArgFPLibCall(SDNode* Node,
2133                                             RTLIB::Libcall Call_F32,
2134                                             RTLIB::Libcall Call_F64,
2135                                             RTLIB::Libcall Call_F80,
2136                                             RTLIB::Libcall Call_F128,
2137                                             RTLIB::Libcall Call_PPCF128,
2138                                             SmallVectorImpl<SDValue> &Results) {
2139   EVT InVT = Node->getOperand(Node->isStrictFPOpcode() ? 1 : 0).getValueType();
2140   RTLIB::Libcall LC = RTLIB::getFPLibCall(InVT.getSimpleVT(),
2141                                           Call_F32, Call_F64, Call_F80,
2142                                           Call_F128, Call_PPCF128);
2143   ExpandFPLibCall(Node, LC, Results);
2144 }
2145 
2146 /// Issue libcalls to __{u}divmod to compute div / rem pairs.
2147 void
2148 SelectionDAGLegalize::ExpandDivRemLibCall(SDNode *Node,
2149                                           SmallVectorImpl<SDValue> &Results) {
2150   unsigned Opcode = Node->getOpcode();
2151   bool isSigned = Opcode == ISD::SDIVREM;
2152 
2153   RTLIB::Libcall LC;
2154   switch (Node->getSimpleValueType(0).SimpleTy) {
2155 
2156   default:
2157     LC = isSigned ? RTLIB::SDIVREM_IEXT : RTLIB::UDIVREM_IEXT;
2158     break;
2159 
2160   case MVT::i8:   LC= isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
2161   case MVT::i16:  LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
2162   case MVT::i32:  LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
2163   case MVT::i64:  LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
2164   case MVT::i128: LC= isSigned ? RTLIB::SDIVREM_I128:RTLIB::UDIVREM_I128; break;
2165   }
2166 
2167   // The input chain to this libcall is the entry node of the function.
2168   // Legalizing the call will automatically add the previous call to the
2169   // dependence.
2170   SDValue InChain = DAG.getEntryNode();
2171 
2172   EVT RetVT = Node->getValueType(0);
2173   Type *RetTy = RetVT.getTypeForEVT(*DAG.getContext());
2174 
2175   TargetLowering::ArgListTy Args;
2176   TargetLowering::ArgListEntry Entry;
2177   for (const SDValue &Op : Node->op_values()) {
2178     EVT ArgVT = Op.getValueType();
2179     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
2180     Entry.Node = Op;
2181     Entry.Ty = ArgTy;
2182     Entry.IsSExt = isSigned;
2183     Entry.IsZExt = !isSigned;
2184     Args.push_back(Entry);
2185   }
2186 
2187   // Also pass the return address of the remainder.
2188   SDValue FIPtr = DAG.CreateStackTemporary(RetVT);
2189   Entry.Node = FIPtr;
2190   Entry.Ty = RetTy->getPointerTo();
2191   Entry.IsSExt = isSigned;
2192   Entry.IsZExt = !isSigned;
2193   Args.push_back(Entry);
2194 
2195   SDValue Callee = DAG.getExternalSymbol(TLI.getLibcallName(LC),
2196                                          TLI.getPointerTy(DAG.getDataLayout()));
2197 
2198   SDLoc dl(Node);
2199   TargetLowering::CallLoweringInfo CLI(DAG);
2200   CLI.setDebugLoc(dl)
2201       .setChain(InChain)
2202       .setLibCallee(TLI.getLibcallCallingConv(LC), RetTy, Callee,
2203                     std::move(Args))
2204       .setSExtResult(isSigned)
2205       .setZExtResult(!isSigned);
2206 
2207   std::pair<SDValue, SDValue> CallInfo = TLI.LowerCallTo(CLI);
2208 
2209   // Remainder is loaded back from the stack frame.
2210   SDValue Rem =
2211       DAG.getLoad(RetVT, dl, CallInfo.second, FIPtr, MachinePointerInfo());
2212   Results.push_back(CallInfo.first);
2213   Results.push_back(Rem);
2214 }
2215 
2216 /// Return true if sincos libcall is available.
2217 static bool isSinCosLibcallAvailable(SDNode *Node, const TargetLowering &TLI) {
2218   RTLIB::Libcall LC;
2219   switch (Node->getSimpleValueType(0).SimpleTy) {
2220   default: llvm_unreachable("Unexpected request for libcall!");
2221   case MVT::f32:     LC = RTLIB::SINCOS_F32; break;
2222   case MVT::f64:     LC = RTLIB::SINCOS_F64; break;
2223   case MVT::f80:     LC = RTLIB::SINCOS_F80; break;
2224   case MVT::f128:    LC = RTLIB::SINCOS_F128; break;
2225   case MVT::ppcf128: LC = RTLIB::SINCOS_PPCF128; break;
2226   }
2227   return TLI.getLibcallName(LC) != nullptr;
2228 }
2229 
2230 /// Only issue sincos libcall if both sin and cos are needed.
2231 static bool useSinCos(SDNode *Node) {
2232   unsigned OtherOpcode = Node->getOpcode() == ISD::FSIN
2233     ? ISD::FCOS : ISD::FSIN;
2234 
2235   SDValue Op0 = Node->getOperand(0);
2236   for (const SDNode *User : Op0.getNode()->uses()) {
2237     if (User == Node)
2238       continue;
2239     // The other user might have been turned into sincos already.
2240     if (User->getOpcode() == OtherOpcode || User->getOpcode() == ISD::FSINCOS)
2241       return true;
2242   }
2243   return false;
2244 }
2245 
2246 /// Issue libcalls to sincos to compute sin / cos pairs.
2247 void
2248 SelectionDAGLegalize::ExpandSinCosLibCall(SDNode *Node,
2249                                           SmallVectorImpl<SDValue> &Results) {
2250   RTLIB::Libcall LC;
2251   switch (Node->getSimpleValueType(0).SimpleTy) {
2252   default: llvm_unreachable("Unexpected request for libcall!");
2253   case MVT::f32:     LC = RTLIB::SINCOS_F32; break;
2254   case MVT::f64:     LC = RTLIB::SINCOS_F64; break;
2255   case MVT::f80:     LC = RTLIB::SINCOS_F80; break;
2256   case MVT::f128:    LC = RTLIB::SINCOS_F128; break;
2257   case MVT::ppcf128: LC = RTLIB::SINCOS_PPCF128; break;
2258   }
2259 
2260   // The input chain to this libcall is the entry node of the function.
2261   // Legalizing the call will automatically add the previous call to the
2262   // dependence.
2263   SDValue InChain = DAG.getEntryNode();
2264 
2265   EVT RetVT = Node->getValueType(0);
2266   Type *RetTy = RetVT.getTypeForEVT(*DAG.getContext());
2267 
2268   TargetLowering::ArgListTy Args;
2269   TargetLowering::ArgListEntry Entry;
2270 
2271   // Pass the argument.
2272   Entry.Node = Node->getOperand(0);
2273   Entry.Ty = RetTy;
2274   Entry.IsSExt = false;
2275   Entry.IsZExt = false;
2276   Args.push_back(Entry);
2277 
2278   // Pass the return address of sin.
2279   SDValue SinPtr = DAG.CreateStackTemporary(RetVT);
2280   Entry.Node = SinPtr;
2281   Entry.Ty = RetTy->getPointerTo();
2282   Entry.IsSExt = false;
2283   Entry.IsZExt = false;
2284   Args.push_back(Entry);
2285 
2286   // Also pass the return address of the cos.
2287   SDValue CosPtr = DAG.CreateStackTemporary(RetVT);
2288   Entry.Node = CosPtr;
2289   Entry.Ty = RetTy->getPointerTo();
2290   Entry.IsSExt = false;
2291   Entry.IsZExt = false;
2292   Args.push_back(Entry);
2293 
2294   SDValue Callee = DAG.getExternalSymbol(TLI.getLibcallName(LC),
2295                                          TLI.getPointerTy(DAG.getDataLayout()));
2296 
2297   SDLoc dl(Node);
2298   TargetLowering::CallLoweringInfo CLI(DAG);
2299   CLI.setDebugLoc(dl).setChain(InChain).setLibCallee(
2300       TLI.getLibcallCallingConv(LC), Type::getVoidTy(*DAG.getContext()), Callee,
2301       std::move(Args));
2302 
2303   std::pair<SDValue, SDValue> CallInfo = TLI.LowerCallTo(CLI);
2304 
2305   Results.push_back(
2306       DAG.getLoad(RetVT, dl, CallInfo.second, SinPtr, MachinePointerInfo()));
2307   Results.push_back(
2308       DAG.getLoad(RetVT, dl, CallInfo.second, CosPtr, MachinePointerInfo()));
2309 }
2310 
2311 /// This function is responsible for legalizing a
2312 /// INT_TO_FP operation of the specified operand when the target requests that
2313 /// we expand it.  At this point, we know that the result and operand types are
2314 /// legal for the target.
2315 SDValue SelectionDAGLegalize::ExpandLegalINT_TO_FP(SDNode *Node,
2316                                                    SDValue &Chain) {
2317   bool isSigned = (Node->getOpcode() == ISD::STRICT_SINT_TO_FP ||
2318                    Node->getOpcode() == ISD::SINT_TO_FP);
2319   EVT DestVT = Node->getValueType(0);
2320   SDLoc dl(Node);
2321   unsigned OpNo = Node->isStrictFPOpcode() ? 1 : 0;
2322   SDValue Op0 = Node->getOperand(OpNo);
2323   EVT SrcVT = Op0.getValueType();
2324 
2325   // TODO: Should any fast-math-flags be set for the created nodes?
2326   LLVM_DEBUG(dbgs() << "Legalizing INT_TO_FP\n");
2327   if (SrcVT == MVT::i32 && TLI.isTypeLegal(MVT::f64) &&
2328       (DestVT.bitsLE(MVT::f64) ||
2329        TLI.isOperationLegal(Node->isStrictFPOpcode() ? ISD::STRICT_FP_EXTEND
2330                                                      : ISD::FP_EXTEND,
2331                             DestVT))) {
2332     LLVM_DEBUG(dbgs() << "32-bit [signed|unsigned] integer to float/double "
2333                          "expansion\n");
2334 
2335     // Get the stack frame index of a 8 byte buffer.
2336     SDValue StackSlot = DAG.CreateStackTemporary(MVT::f64);
2337 
2338     SDValue Lo = Op0;
2339     // if signed map to unsigned space
2340     if (isSigned) {
2341       // Invert sign bit (signed to unsigned mapping).
2342       Lo = DAG.getNode(ISD::XOR, dl, MVT::i32, Lo,
2343                        DAG.getConstant(0x80000000u, dl, MVT::i32));
2344     }
2345     // Initial hi portion of constructed double.
2346     SDValue Hi = DAG.getConstant(0x43300000u, dl, MVT::i32);
2347 
2348     // If this a big endian target, swap the lo and high data.
2349     if (DAG.getDataLayout().isBigEndian())
2350       std::swap(Lo, Hi);
2351 
2352     SDValue MemChain = DAG.getEntryNode();
2353 
2354     // Store the lo of the constructed double.
2355     SDValue Store1 = DAG.getStore(MemChain, dl, Lo, StackSlot,
2356                                   MachinePointerInfo());
2357     // Store the hi of the constructed double.
2358     SDValue HiPtr = DAG.getMemBasePlusOffset(StackSlot, TypeSize::Fixed(4), dl);
2359     SDValue Store2 =
2360         DAG.getStore(MemChain, dl, Hi, HiPtr, MachinePointerInfo());
2361     MemChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Store1, Store2);
2362 
2363     // load the constructed double
2364     SDValue Load =
2365         DAG.getLoad(MVT::f64, dl, MemChain, StackSlot, MachinePointerInfo());
2366     // FP constant to bias correct the final result
2367     SDValue Bias = DAG.getConstantFP(isSigned ?
2368                                      BitsToDouble(0x4330000080000000ULL) :
2369                                      BitsToDouble(0x4330000000000000ULL),
2370                                      dl, MVT::f64);
2371     // Subtract the bias and get the final result.
2372     SDValue Sub;
2373     SDValue Result;
2374     if (Node->isStrictFPOpcode()) {
2375       Sub = DAG.getNode(ISD::STRICT_FSUB, dl, {MVT::f64, MVT::Other},
2376                         {Node->getOperand(0), Load, Bias});
2377       Chain = Sub.getValue(1);
2378       if (DestVT != Sub.getValueType()) {
2379         std::pair<SDValue, SDValue> ResultPair;
2380         ResultPair =
2381             DAG.getStrictFPExtendOrRound(Sub, Chain, dl, DestVT);
2382         Result = ResultPair.first;
2383         Chain = ResultPair.second;
2384       }
2385       else
2386         Result = Sub;
2387     } else {
2388       Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Load, Bias);
2389       Result = DAG.getFPExtendOrRound(Sub, dl, DestVT);
2390     }
2391     return Result;
2392   }
2393 
2394   if (isSigned)
2395     return SDValue();
2396 
2397   // TODO: Generalize this for use with other types.
2398   if (((SrcVT == MVT::i32 || SrcVT == MVT::i64) && DestVT == MVT::f32) ||
2399       (SrcVT == MVT::i64 && DestVT == MVT::f64)) {
2400     LLVM_DEBUG(dbgs() << "Converting unsigned i32/i64 to f32/f64\n");
2401     // For unsigned conversions, convert them to signed conversions using the
2402     // algorithm from the x86_64 __floatundisf in compiler_rt. That method
2403     // should be valid for i32->f32 as well.
2404 
2405     // More generally this transform should be valid if there are 3 more bits
2406     // in the integer type than the significand. Rounding uses the first bit
2407     // after the width of the significand and the OR of all bits after that. So
2408     // we need to be able to OR the shifted out bit into one of the bits that
2409     // participate in the OR.
2410 
2411     // TODO: This really should be implemented using a branch rather than a
2412     // select.  We happen to get lucky and machinesink does the right
2413     // thing most of the time.  This would be a good candidate for a
2414     // pseudo-op, or, even better, for whole-function isel.
2415     EVT SetCCVT = getSetCCResultType(SrcVT);
2416 
2417     SDValue SignBitTest = DAG.getSetCC(
2418         dl, SetCCVT, Op0, DAG.getConstant(0, dl, SrcVT), ISD::SETLT);
2419 
2420     EVT ShiftVT = TLI.getShiftAmountTy(SrcVT, DAG.getDataLayout());
2421     SDValue ShiftConst = DAG.getConstant(1, dl, ShiftVT);
2422     SDValue Shr = DAG.getNode(ISD::SRL, dl, SrcVT, Op0, ShiftConst);
2423     SDValue AndConst = DAG.getConstant(1, dl, SrcVT);
2424     SDValue And = DAG.getNode(ISD::AND, dl, SrcVT, Op0, AndConst);
2425     SDValue Or = DAG.getNode(ISD::OR, dl, SrcVT, And, Shr);
2426 
2427     SDValue Slow, Fast;
2428     if (Node->isStrictFPOpcode()) {
2429       // In strict mode, we must avoid spurious exceptions, and therefore
2430       // must make sure to only emit a single STRICT_SINT_TO_FP.
2431       SDValue InCvt = DAG.getSelect(dl, SrcVT, SignBitTest, Or, Op0);
2432       Fast = DAG.getNode(ISD::STRICT_SINT_TO_FP, dl, { DestVT, MVT::Other },
2433                          { Node->getOperand(0), InCvt });
2434       Slow = DAG.getNode(ISD::STRICT_FADD, dl, { DestVT, MVT::Other },
2435                          { Fast.getValue(1), Fast, Fast });
2436       Chain = Slow.getValue(1);
2437       // The STRICT_SINT_TO_FP inherits the exception mode from the
2438       // incoming STRICT_UINT_TO_FP node; the STRICT_FADD node can
2439       // never raise any exception.
2440       SDNodeFlags Flags;
2441       Flags.setNoFPExcept(Node->getFlags().hasNoFPExcept());
2442       Fast->setFlags(Flags);
2443       Flags.setNoFPExcept(true);
2444       Slow->setFlags(Flags);
2445     } else {
2446       SDValue SignCvt = DAG.getNode(ISD::SINT_TO_FP, dl, DestVT, Or);
2447       Slow = DAG.getNode(ISD::FADD, dl, DestVT, SignCvt, SignCvt);
2448       Fast = DAG.getNode(ISD::SINT_TO_FP, dl, DestVT, Op0);
2449     }
2450 
2451     return DAG.getSelect(dl, DestVT, SignBitTest, Slow, Fast);
2452   }
2453 
2454   // Don't expand it if there isn't cheap fadd.
2455   if (!TLI.isOperationLegalOrCustom(
2456           Node->isStrictFPOpcode() ? ISD::STRICT_FADD : ISD::FADD, DestVT))
2457     return SDValue();
2458 
2459   // The following optimization is valid only if every value in SrcVT (when
2460   // treated as signed) is representable in DestVT.  Check that the mantissa
2461   // size of DestVT is >= than the number of bits in SrcVT -1.
2462   assert(APFloat::semanticsPrecision(DAG.EVTToAPFloatSemantics(DestVT)) >=
2463              SrcVT.getSizeInBits() - 1 &&
2464          "Cannot perform lossless SINT_TO_FP!");
2465 
2466   SDValue Tmp1;
2467   if (Node->isStrictFPOpcode()) {
2468     Tmp1 = DAG.getNode(ISD::STRICT_SINT_TO_FP, dl, { DestVT, MVT::Other },
2469                        { Node->getOperand(0), Op0 });
2470   } else
2471     Tmp1 = DAG.getNode(ISD::SINT_TO_FP, dl, DestVT, Op0);
2472 
2473   SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(SrcVT), Op0,
2474                                  DAG.getConstant(0, dl, SrcVT), ISD::SETLT);
2475   SDValue Zero = DAG.getIntPtrConstant(0, dl),
2476           Four = DAG.getIntPtrConstant(4, dl);
2477   SDValue CstOffset = DAG.getSelect(dl, Zero.getValueType(),
2478                                     SignSet, Four, Zero);
2479 
2480   // If the sign bit of the integer is set, the large number will be treated
2481   // as a negative number.  To counteract this, the dynamic code adds an
2482   // offset depending on the data type.
2483   uint64_t FF;
2484   switch (SrcVT.getSimpleVT().SimpleTy) {
2485   default:
2486     return SDValue();
2487   case MVT::i8 : FF = 0x43800000ULL; break;  // 2^8  (as a float)
2488   case MVT::i16: FF = 0x47800000ULL; break;  // 2^16 (as a float)
2489   case MVT::i32: FF = 0x4F800000ULL; break;  // 2^32 (as a float)
2490   case MVT::i64: FF = 0x5F800000ULL; break;  // 2^64 (as a float)
2491   }
2492   if (DAG.getDataLayout().isLittleEndian())
2493     FF <<= 32;
2494   Constant *FudgeFactor = ConstantInt::get(
2495                                        Type::getInt64Ty(*DAG.getContext()), FF);
2496 
2497   SDValue CPIdx =
2498       DAG.getConstantPool(FudgeFactor, TLI.getPointerTy(DAG.getDataLayout()));
2499   Align Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlign();
2500   CPIdx = DAG.getNode(ISD::ADD, dl, CPIdx.getValueType(), CPIdx, CstOffset);
2501   Alignment = commonAlignment(Alignment, 4);
2502   SDValue FudgeInReg;
2503   if (DestVT == MVT::f32)
2504     FudgeInReg = DAG.getLoad(
2505         MVT::f32, dl, DAG.getEntryNode(), CPIdx,
2506         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
2507         Alignment);
2508   else {
2509     SDValue Load = DAG.getExtLoad(
2510         ISD::EXTLOAD, dl, DestVT, DAG.getEntryNode(), CPIdx,
2511         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()), MVT::f32,
2512         Alignment);
2513     HandleSDNode Handle(Load);
2514     LegalizeOp(Load.getNode());
2515     FudgeInReg = Handle.getValue();
2516   }
2517 
2518   if (Node->isStrictFPOpcode()) {
2519     SDValue Result = DAG.getNode(ISD::STRICT_FADD, dl, { DestVT, MVT::Other },
2520                                  { Tmp1.getValue(1), Tmp1, FudgeInReg });
2521     Chain = Result.getValue(1);
2522     return Result;
2523   }
2524 
2525   return DAG.getNode(ISD::FADD, dl, DestVT, Tmp1, FudgeInReg);
2526 }
2527 
2528 /// This function is responsible for legalizing a
2529 /// *INT_TO_FP operation of the specified operand when the target requests that
2530 /// we promote it.  At this point, we know that the result and operand types are
2531 /// legal for the target, and that there is a legal UINT_TO_FP or SINT_TO_FP
2532 /// operation that takes a larger input.
2533 void SelectionDAGLegalize::PromoteLegalINT_TO_FP(
2534     SDNode *N, const SDLoc &dl, SmallVectorImpl<SDValue> &Results) {
2535   bool IsStrict = N->isStrictFPOpcode();
2536   bool IsSigned = N->getOpcode() == ISD::SINT_TO_FP ||
2537                   N->getOpcode() == ISD::STRICT_SINT_TO_FP;
2538   EVT DestVT = N->getValueType(0);
2539   SDValue LegalOp = N->getOperand(IsStrict ? 1 : 0);
2540   unsigned UIntOp = IsStrict ? ISD::STRICT_UINT_TO_FP : ISD::UINT_TO_FP;
2541   unsigned SIntOp = IsStrict ? ISD::STRICT_SINT_TO_FP : ISD::SINT_TO_FP;
2542 
2543   // First step, figure out the appropriate *INT_TO_FP operation to use.
2544   EVT NewInTy = LegalOp.getValueType();
2545 
2546   unsigned OpToUse = 0;
2547 
2548   // Scan for the appropriate larger type to use.
2549   while (true) {
2550     NewInTy = (MVT::SimpleValueType)(NewInTy.getSimpleVT().SimpleTy+1);
2551     assert(NewInTy.isInteger() && "Ran out of possibilities!");
2552 
2553     // If the target supports SINT_TO_FP of this type, use it.
2554     if (TLI.isOperationLegalOrCustom(SIntOp, NewInTy)) {
2555       OpToUse = SIntOp;
2556       break;
2557     }
2558     if (IsSigned)
2559       continue;
2560 
2561     // If the target supports UINT_TO_FP of this type, use it.
2562     if (TLI.isOperationLegalOrCustom(UIntOp, NewInTy)) {
2563       OpToUse = UIntOp;
2564       break;
2565     }
2566 
2567     // Otherwise, try a larger type.
2568   }
2569 
2570   // Okay, we found the operation and type to use.  Zero extend our input to the
2571   // desired type then run the operation on it.
2572   if (IsStrict) {
2573     SDValue Res =
2574         DAG.getNode(OpToUse, dl, {DestVT, MVT::Other},
2575                     {N->getOperand(0),
2576                      DAG.getNode(IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
2577                                  dl, NewInTy, LegalOp)});
2578     Results.push_back(Res);
2579     Results.push_back(Res.getValue(1));
2580     return;
2581   }
2582 
2583   Results.push_back(
2584       DAG.getNode(OpToUse, dl, DestVT,
2585                   DAG.getNode(IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
2586                               dl, NewInTy, LegalOp)));
2587 }
2588 
2589 /// This function is responsible for legalizing a
2590 /// FP_TO_*INT operation of the specified operand when the target requests that
2591 /// we promote it.  At this point, we know that the result and operand types are
2592 /// legal for the target, and that there is a legal FP_TO_UINT or FP_TO_SINT
2593 /// operation that returns a larger result.
2594 void SelectionDAGLegalize::PromoteLegalFP_TO_INT(SDNode *N, const SDLoc &dl,
2595                                                  SmallVectorImpl<SDValue> &Results) {
2596   bool IsStrict = N->isStrictFPOpcode();
2597   bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT ||
2598                   N->getOpcode() == ISD::STRICT_FP_TO_SINT;
2599   EVT DestVT = N->getValueType(0);
2600   SDValue LegalOp = N->getOperand(IsStrict ? 1 : 0);
2601   // First step, figure out the appropriate FP_TO*INT operation to use.
2602   EVT NewOutTy = DestVT;
2603 
2604   unsigned OpToUse = 0;
2605 
2606   // Scan for the appropriate larger type to use.
2607   while (true) {
2608     NewOutTy = (MVT::SimpleValueType)(NewOutTy.getSimpleVT().SimpleTy+1);
2609     assert(NewOutTy.isInteger() && "Ran out of possibilities!");
2610 
2611     // A larger signed type can hold all unsigned values of the requested type,
2612     // so using FP_TO_SINT is valid
2613     OpToUse = IsStrict ? ISD::STRICT_FP_TO_SINT : ISD::FP_TO_SINT;
2614     if (TLI.isOperationLegalOrCustom(OpToUse, NewOutTy))
2615       break;
2616 
2617     // However, if the value may be < 0.0, we *must* use some FP_TO_SINT.
2618     OpToUse = IsStrict ? ISD::STRICT_FP_TO_UINT : ISD::FP_TO_UINT;
2619     if (!IsSigned && TLI.isOperationLegalOrCustom(OpToUse, NewOutTy))
2620       break;
2621 
2622     // Otherwise, try a larger type.
2623   }
2624 
2625   // Okay, we found the operation and type to use.
2626   SDValue Operation;
2627   if (IsStrict) {
2628     SDVTList VTs = DAG.getVTList(NewOutTy, MVT::Other);
2629     Operation = DAG.getNode(OpToUse, dl, VTs, N->getOperand(0), LegalOp);
2630   } else
2631     Operation = DAG.getNode(OpToUse, dl, NewOutTy, LegalOp);
2632 
2633   // Truncate the result of the extended FP_TO_*INT operation to the desired
2634   // size.
2635   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, DestVT, Operation);
2636   Results.push_back(Trunc);
2637   if (IsStrict)
2638     Results.push_back(Operation.getValue(1));
2639 }
2640 
2641 /// Promote FP_TO_*INT_SAT operation to a larger result type. At this point
2642 /// the result and operand types are legal and there must be a legal
2643 /// FP_TO_*INT_SAT operation for a larger result type.
2644 SDValue SelectionDAGLegalize::PromoteLegalFP_TO_INT_SAT(SDNode *Node,
2645                                                         const SDLoc &dl) {
2646   unsigned Opcode = Node->getOpcode();
2647 
2648   // Scan for the appropriate larger type to use.
2649   EVT NewOutTy = Node->getValueType(0);
2650   while (true) {
2651     NewOutTy = (MVT::SimpleValueType)(NewOutTy.getSimpleVT().SimpleTy + 1);
2652     assert(NewOutTy.isInteger() && "Ran out of possibilities!");
2653 
2654     if (TLI.isOperationLegalOrCustom(Opcode, NewOutTy))
2655       break;
2656   }
2657 
2658   // Saturation width is determined by second operand, so we don't have to
2659   // perform any fixup and can directly truncate the result.
2660   SDValue Result = DAG.getNode(Opcode, dl, NewOutTy, Node->getOperand(0),
2661                                Node->getOperand(1));
2662   return DAG.getNode(ISD::TRUNCATE, dl, Node->getValueType(0), Result);
2663 }
2664 
2665 /// Open code the operations for PARITY of the specified operation.
2666 SDValue SelectionDAGLegalize::ExpandPARITY(SDValue Op, const SDLoc &dl) {
2667   EVT VT = Op.getValueType();
2668   EVT ShVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout());
2669   unsigned Sz = VT.getScalarSizeInBits();
2670 
2671   // If CTPOP is legal, use it. Otherwise use shifts and xor.
2672   SDValue Result;
2673   if (TLI.isOperationLegalOrPromote(ISD::CTPOP, VT)) {
2674     Result = DAG.getNode(ISD::CTPOP, dl, VT, Op);
2675   } else {
2676     Result = Op;
2677     for (unsigned i = Log2_32_Ceil(Sz); i != 0;) {
2678       SDValue Shift = DAG.getNode(ISD::SRL, dl, VT, Result,
2679                                   DAG.getConstant(1ULL << (--i), dl, ShVT));
2680       Result = DAG.getNode(ISD::XOR, dl, VT, Result, Shift);
2681     }
2682   }
2683 
2684   return DAG.getNode(ISD::AND, dl, VT, Result, DAG.getConstant(1, dl, VT));
2685 }
2686 
2687 bool SelectionDAGLegalize::ExpandNode(SDNode *Node) {
2688   LLVM_DEBUG(dbgs() << "Trying to expand node\n");
2689   SmallVector<SDValue, 8> Results;
2690   SDLoc dl(Node);
2691   SDValue Tmp1, Tmp2, Tmp3, Tmp4;
2692   bool NeedInvert;
2693   switch (Node->getOpcode()) {
2694   case ISD::ABS:
2695     if ((Tmp1 = TLI.expandABS(Node, DAG)))
2696       Results.push_back(Tmp1);
2697     break;
2698   case ISD::CTPOP:
2699     if ((Tmp1 = TLI.expandCTPOP(Node, DAG)))
2700       Results.push_back(Tmp1);
2701     break;
2702   case ISD::CTLZ:
2703   case ISD::CTLZ_ZERO_UNDEF:
2704     if ((Tmp1 = TLI.expandCTLZ(Node, DAG)))
2705       Results.push_back(Tmp1);
2706     break;
2707   case ISD::CTTZ:
2708   case ISD::CTTZ_ZERO_UNDEF:
2709     if ((Tmp1 = TLI.expandCTTZ(Node, DAG)))
2710       Results.push_back(Tmp1);
2711     break;
2712   case ISD::BITREVERSE:
2713     if ((Tmp1 = TLI.expandBITREVERSE(Node, DAG)))
2714       Results.push_back(Tmp1);
2715     break;
2716   case ISD::BSWAP:
2717     if ((Tmp1 = TLI.expandBSWAP(Node, DAG)))
2718       Results.push_back(Tmp1);
2719     break;
2720   case ISD::PARITY:
2721     Results.push_back(ExpandPARITY(Node->getOperand(0), dl));
2722     break;
2723   case ISD::FRAMEADDR:
2724   case ISD::RETURNADDR:
2725   case ISD::FRAME_TO_ARGS_OFFSET:
2726     Results.push_back(DAG.getConstant(0, dl, Node->getValueType(0)));
2727     break;
2728   case ISD::EH_DWARF_CFA: {
2729     SDValue CfaArg = DAG.getSExtOrTrunc(Node->getOperand(0), dl,
2730                                         TLI.getPointerTy(DAG.getDataLayout()));
2731     SDValue Offset = DAG.getNode(ISD::ADD, dl,
2732                                  CfaArg.getValueType(),
2733                                  DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET, dl,
2734                                              CfaArg.getValueType()),
2735                                  CfaArg);
2736     SDValue FA = DAG.getNode(
2737         ISD::FRAMEADDR, dl, TLI.getPointerTy(DAG.getDataLayout()),
2738         DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout())));
2739     Results.push_back(DAG.getNode(ISD::ADD, dl, FA.getValueType(),
2740                                   FA, Offset));
2741     break;
2742   }
2743   case ISD::FLT_ROUNDS_:
2744     Results.push_back(DAG.getConstant(1, dl, Node->getValueType(0)));
2745     Results.push_back(Node->getOperand(0));
2746     break;
2747   case ISD::EH_RETURN:
2748   case ISD::EH_LABEL:
2749   case ISD::PREFETCH:
2750   case ISD::VAEND:
2751   case ISD::EH_SJLJ_LONGJMP:
2752     // If the target didn't expand these, there's nothing to do, so just
2753     // preserve the chain and be done.
2754     Results.push_back(Node->getOperand(0));
2755     break;
2756   case ISD::READCYCLECOUNTER:
2757     // If the target didn't expand this, just return 'zero' and preserve the
2758     // chain.
2759     Results.append(Node->getNumValues() - 1,
2760                    DAG.getConstant(0, dl, Node->getValueType(0)));
2761     Results.push_back(Node->getOperand(0));
2762     break;
2763   case ISD::EH_SJLJ_SETJMP:
2764     // If the target didn't expand this, just return 'zero' and preserve the
2765     // chain.
2766     Results.push_back(DAG.getConstant(0, dl, MVT::i32));
2767     Results.push_back(Node->getOperand(0));
2768     break;
2769   case ISD::ATOMIC_LOAD: {
2770     // There is no libcall for atomic load; fake it with ATOMIC_CMP_SWAP.
2771     SDValue Zero = DAG.getConstant(0, dl, Node->getValueType(0));
2772     SDVTList VTs = DAG.getVTList(Node->getValueType(0), MVT::Other);
2773     SDValue Swap = DAG.getAtomicCmpSwap(
2774         ISD::ATOMIC_CMP_SWAP, dl, cast<AtomicSDNode>(Node)->getMemoryVT(), VTs,
2775         Node->getOperand(0), Node->getOperand(1), Zero, Zero,
2776         cast<AtomicSDNode>(Node)->getMemOperand());
2777     Results.push_back(Swap.getValue(0));
2778     Results.push_back(Swap.getValue(1));
2779     break;
2780   }
2781   case ISD::ATOMIC_STORE: {
2782     // There is no libcall for atomic store; fake it with ATOMIC_SWAP.
2783     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
2784                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
2785                                  Node->getOperand(0),
2786                                  Node->getOperand(1), Node->getOperand(2),
2787                                  cast<AtomicSDNode>(Node)->getMemOperand());
2788     Results.push_back(Swap.getValue(1));
2789     break;
2790   }
2791   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
2792     // Expanding an ATOMIC_CMP_SWAP_WITH_SUCCESS produces an ATOMIC_CMP_SWAP and
2793     // splits out the success value as a comparison. Expanding the resulting
2794     // ATOMIC_CMP_SWAP will produce a libcall.
2795     SDVTList VTs = DAG.getVTList(Node->getValueType(0), MVT::Other);
2796     SDValue Res = DAG.getAtomicCmpSwap(
2797         ISD::ATOMIC_CMP_SWAP, dl, cast<AtomicSDNode>(Node)->getMemoryVT(), VTs,
2798         Node->getOperand(0), Node->getOperand(1), Node->getOperand(2),
2799         Node->getOperand(3), cast<MemSDNode>(Node)->getMemOperand());
2800 
2801     SDValue ExtRes = Res;
2802     SDValue LHS = Res;
2803     SDValue RHS = Node->getOperand(1);
2804 
2805     EVT AtomicType = cast<AtomicSDNode>(Node)->getMemoryVT();
2806     EVT OuterType = Node->getValueType(0);
2807     switch (TLI.getExtendForAtomicOps()) {
2808     case ISD::SIGN_EXTEND:
2809       LHS = DAG.getNode(ISD::AssertSext, dl, OuterType, Res,
2810                         DAG.getValueType(AtomicType));
2811       RHS = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, OuterType,
2812                         Node->getOperand(2), DAG.getValueType(AtomicType));
2813       ExtRes = LHS;
2814       break;
2815     case ISD::ZERO_EXTEND:
2816       LHS = DAG.getNode(ISD::AssertZext, dl, OuterType, Res,
2817                         DAG.getValueType(AtomicType));
2818       RHS = DAG.getZeroExtendInReg(Node->getOperand(2), dl, AtomicType);
2819       ExtRes = LHS;
2820       break;
2821     case ISD::ANY_EXTEND:
2822       LHS = DAG.getZeroExtendInReg(Res, dl, AtomicType);
2823       RHS = DAG.getZeroExtendInReg(Node->getOperand(2), dl, AtomicType);
2824       break;
2825     default:
2826       llvm_unreachable("Invalid atomic op extension");
2827     }
2828 
2829     SDValue Success =
2830         DAG.getSetCC(dl, Node->getValueType(1), LHS, RHS, ISD::SETEQ);
2831 
2832     Results.push_back(ExtRes.getValue(0));
2833     Results.push_back(Success);
2834     Results.push_back(Res.getValue(1));
2835     break;
2836   }
2837   case ISD::DYNAMIC_STACKALLOC:
2838     ExpandDYNAMIC_STACKALLOC(Node, Results);
2839     break;
2840   case ISD::MERGE_VALUES:
2841     for (unsigned i = 0; i < Node->getNumValues(); i++)
2842       Results.push_back(Node->getOperand(i));
2843     break;
2844   case ISD::UNDEF: {
2845     EVT VT = Node->getValueType(0);
2846     if (VT.isInteger())
2847       Results.push_back(DAG.getConstant(0, dl, VT));
2848     else {
2849       assert(VT.isFloatingPoint() && "Unknown value type!");
2850       Results.push_back(DAG.getConstantFP(0, dl, VT));
2851     }
2852     break;
2853   }
2854   case ISD::STRICT_FP_ROUND:
2855     // When strict mode is enforced we can't do expansion because it
2856     // does not honor the "strict" properties. Only libcall is allowed.
2857     if (TLI.isStrictFPEnabled())
2858       break;
2859     // We might as well mutate to FP_ROUND when FP_ROUND operation is legal
2860     // since this operation is more efficient than stack operation.
2861     if (TLI.getStrictFPOperationAction(Node->getOpcode(),
2862                                        Node->getValueType(0))
2863         == TargetLowering::Legal)
2864       break;
2865     // We fall back to use stack operation when the FP_ROUND operation
2866     // isn't available.
2867     if ((Tmp1 = EmitStackConvert(Node->getOperand(1), Node->getValueType(0),
2868                                  Node->getValueType(0), dl,
2869                                  Node->getOperand(0)))) {
2870       ReplaceNode(Node, Tmp1.getNode());
2871       LLVM_DEBUG(dbgs() << "Successfully expanded STRICT_FP_ROUND node\n");
2872       return true;
2873     }
2874     break;
2875   case ISD::FP_ROUND:
2876   case ISD::BITCAST:
2877     if ((Tmp1 = EmitStackConvert(Node->getOperand(0), Node->getValueType(0),
2878                                  Node->getValueType(0), dl)))
2879       Results.push_back(Tmp1);
2880     break;
2881   case ISD::STRICT_FP_EXTEND:
2882     // When strict mode is enforced we can't do expansion because it
2883     // does not honor the "strict" properties. Only libcall is allowed.
2884     if (TLI.isStrictFPEnabled())
2885       break;
2886     // We might as well mutate to FP_EXTEND when FP_EXTEND operation is legal
2887     // since this operation is more efficient than stack operation.
2888     if (TLI.getStrictFPOperationAction(Node->getOpcode(),
2889                                        Node->getValueType(0))
2890         == TargetLowering::Legal)
2891       break;
2892     // We fall back to use stack operation when the FP_EXTEND operation
2893     // isn't available.
2894     if ((Tmp1 = EmitStackConvert(
2895              Node->getOperand(1), Node->getOperand(1).getValueType(),
2896              Node->getValueType(0), dl, Node->getOperand(0)))) {
2897       ReplaceNode(Node, Tmp1.getNode());
2898       LLVM_DEBUG(dbgs() << "Successfully expanded STRICT_FP_EXTEND node\n");
2899       return true;
2900     }
2901     break;
2902   case ISD::FP_EXTEND:
2903     if ((Tmp1 = EmitStackConvert(Node->getOperand(0),
2904                                  Node->getOperand(0).getValueType(),
2905                                  Node->getValueType(0), dl)))
2906       Results.push_back(Tmp1);
2907     break;
2908   case ISD::BF16_TO_FP: {
2909     // Always expand bf16 to f32 casts, they lower to ext + shift.
2910     SDValue Op = DAG.getNode(ISD::BITCAST, dl, MVT::i16, Node->getOperand(0));
2911     Op = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op);
2912     Op = DAG.getNode(
2913         ISD::SHL, dl, MVT::i32, Op,
2914         DAG.getConstant(16, dl,
2915                         TLI.getShiftAmountTy(MVT::i32, DAG.getDataLayout())));
2916     Op = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Op);
2917     Results.push_back(Op);
2918     break;
2919   }
2920   case ISD::SIGN_EXTEND_INREG: {
2921     EVT ExtraVT = cast<VTSDNode>(Node->getOperand(1))->getVT();
2922     EVT VT = Node->getValueType(0);
2923 
2924     // An in-register sign-extend of a boolean is a negation:
2925     // 'true' (1) sign-extended is -1.
2926     // 'false' (0) sign-extended is 0.
2927     // However, we must mask the high bits of the source operand because the
2928     // SIGN_EXTEND_INREG does not guarantee that the high bits are already zero.
2929 
2930     // TODO: Do this for vectors too?
2931     if (ExtraVT.isScalarInteger() && ExtraVT.getSizeInBits() == 1) {
2932       SDValue One = DAG.getConstant(1, dl, VT);
2933       SDValue And = DAG.getNode(ISD::AND, dl, VT, Node->getOperand(0), One);
2934       SDValue Zero = DAG.getConstant(0, dl, VT);
2935       SDValue Neg = DAG.getNode(ISD::SUB, dl, VT, Zero, And);
2936       Results.push_back(Neg);
2937       break;
2938     }
2939 
2940     // NOTE: we could fall back on load/store here too for targets without
2941     // SRA.  However, it is doubtful that any exist.
2942     EVT ShiftAmountTy = TLI.getShiftAmountTy(VT, DAG.getDataLayout());
2943     unsigned BitsDiff = VT.getScalarSizeInBits() -
2944                         ExtraVT.getScalarSizeInBits();
2945     SDValue ShiftCst = DAG.getConstant(BitsDiff, dl, ShiftAmountTy);
2946     Tmp1 = DAG.getNode(ISD::SHL, dl, Node->getValueType(0),
2947                        Node->getOperand(0), ShiftCst);
2948     Tmp1 = DAG.getNode(ISD::SRA, dl, Node->getValueType(0), Tmp1, ShiftCst);
2949     Results.push_back(Tmp1);
2950     break;
2951   }
2952   case ISD::UINT_TO_FP:
2953   case ISD::STRICT_UINT_TO_FP:
2954     if (TLI.expandUINT_TO_FP(Node, Tmp1, Tmp2, DAG)) {
2955       Results.push_back(Tmp1);
2956       if (Node->isStrictFPOpcode())
2957         Results.push_back(Tmp2);
2958       break;
2959     }
2960     LLVM_FALLTHROUGH;
2961   case ISD::SINT_TO_FP:
2962   case ISD::STRICT_SINT_TO_FP:
2963     if ((Tmp1 = ExpandLegalINT_TO_FP(Node, Tmp2))) {
2964       Results.push_back(Tmp1);
2965       if (Node->isStrictFPOpcode())
2966         Results.push_back(Tmp2);
2967     }
2968     break;
2969   case ISD::FP_TO_SINT:
2970     if (TLI.expandFP_TO_SINT(Node, Tmp1, DAG))
2971       Results.push_back(Tmp1);
2972     break;
2973   case ISD::STRICT_FP_TO_SINT:
2974     if (TLI.expandFP_TO_SINT(Node, Tmp1, DAG)) {
2975       ReplaceNode(Node, Tmp1.getNode());
2976       LLVM_DEBUG(dbgs() << "Successfully expanded STRICT_FP_TO_SINT node\n");
2977       return true;
2978     }
2979     break;
2980   case ISD::FP_TO_UINT:
2981     if (TLI.expandFP_TO_UINT(Node, Tmp1, Tmp2, DAG))
2982       Results.push_back(Tmp1);
2983     break;
2984   case ISD::STRICT_FP_TO_UINT:
2985     if (TLI.expandFP_TO_UINT(Node, Tmp1, Tmp2, DAG)) {
2986       // Relink the chain.
2987       DAG.ReplaceAllUsesOfValueWith(SDValue(Node,1), Tmp2);
2988       // Replace the new UINT result.
2989       ReplaceNodeWithValue(SDValue(Node, 0), Tmp1);
2990       LLVM_DEBUG(dbgs() << "Successfully expanded STRICT_FP_TO_UINT node\n");
2991       return true;
2992     }
2993     break;
2994   case ISD::FP_TO_SINT_SAT:
2995   case ISD::FP_TO_UINT_SAT:
2996     Results.push_back(TLI.expandFP_TO_INT_SAT(Node, DAG));
2997     break;
2998   case ISD::VAARG:
2999     Results.push_back(DAG.expandVAArg(Node));
3000     Results.push_back(Results[0].getValue(1));
3001     break;
3002   case ISD::VACOPY:
3003     Results.push_back(DAG.expandVACopy(Node));
3004     break;
3005   case ISD::EXTRACT_VECTOR_ELT:
3006     if (Node->getOperand(0).getValueType().getVectorNumElements() == 1)
3007       // This must be an access of the only element.  Return it.
3008       Tmp1 = DAG.getNode(ISD::BITCAST, dl, Node->getValueType(0),
3009                          Node->getOperand(0));
3010     else
3011       Tmp1 = ExpandExtractFromVectorThroughStack(SDValue(Node, 0));
3012     Results.push_back(Tmp1);
3013     break;
3014   case ISD::EXTRACT_SUBVECTOR:
3015     Results.push_back(ExpandExtractFromVectorThroughStack(SDValue(Node, 0)));
3016     break;
3017   case ISD::INSERT_SUBVECTOR:
3018     Results.push_back(ExpandInsertToVectorThroughStack(SDValue(Node, 0)));
3019     break;
3020   case ISD::CONCAT_VECTORS:
3021     Results.push_back(ExpandVectorBuildThroughStack(Node));
3022     break;
3023   case ISD::SCALAR_TO_VECTOR:
3024     Results.push_back(ExpandSCALAR_TO_VECTOR(Node));
3025     break;
3026   case ISD::INSERT_VECTOR_ELT:
3027     Results.push_back(ExpandINSERT_VECTOR_ELT(Node->getOperand(0),
3028                                               Node->getOperand(1),
3029                                               Node->getOperand(2), dl));
3030     break;
3031   case ISD::VECTOR_SHUFFLE: {
3032     SmallVector<int, 32> NewMask;
3033     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Node)->getMask();
3034 
3035     EVT VT = Node->getValueType(0);
3036     EVT EltVT = VT.getVectorElementType();
3037     SDValue Op0 = Node->getOperand(0);
3038     SDValue Op1 = Node->getOperand(1);
3039     if (!TLI.isTypeLegal(EltVT)) {
3040       EVT NewEltVT = TLI.getTypeToTransformTo(*DAG.getContext(), EltVT);
3041 
3042       // BUILD_VECTOR operands are allowed to be wider than the element type.
3043       // But if NewEltVT is smaller that EltVT the BUILD_VECTOR does not accept
3044       // it.
3045       if (NewEltVT.bitsLT(EltVT)) {
3046         // Convert shuffle node.
3047         // If original node was v4i64 and the new EltVT is i32,
3048         // cast operands to v8i32 and re-build the mask.
3049 
3050         // Calculate new VT, the size of the new VT should be equal to original.
3051         EVT NewVT =
3052             EVT::getVectorVT(*DAG.getContext(), NewEltVT,
3053                              VT.getSizeInBits() / NewEltVT.getSizeInBits());
3054         assert(NewVT.bitsEq(VT));
3055 
3056         // cast operands to new VT
3057         Op0 = DAG.getNode(ISD::BITCAST, dl, NewVT, Op0);
3058         Op1 = DAG.getNode(ISD::BITCAST, dl, NewVT, Op1);
3059 
3060         // Convert the shuffle mask
3061         unsigned int factor =
3062                          NewVT.getVectorNumElements()/VT.getVectorNumElements();
3063 
3064         // EltVT gets smaller
3065         assert(factor > 0);
3066 
3067         for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
3068           if (Mask[i] < 0) {
3069             for (unsigned fi = 0; fi < factor; ++fi)
3070               NewMask.push_back(Mask[i]);
3071           }
3072           else {
3073             for (unsigned fi = 0; fi < factor; ++fi)
3074               NewMask.push_back(Mask[i]*factor+fi);
3075           }
3076         }
3077         Mask = NewMask;
3078         VT = NewVT;
3079       }
3080       EltVT = NewEltVT;
3081     }
3082     unsigned NumElems = VT.getVectorNumElements();
3083     SmallVector<SDValue, 16> Ops;
3084     for (unsigned i = 0; i != NumElems; ++i) {
3085       if (Mask[i] < 0) {
3086         Ops.push_back(DAG.getUNDEF(EltVT));
3087         continue;
3088       }
3089       unsigned Idx = Mask[i];
3090       if (Idx < NumElems)
3091         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Op0,
3092                                   DAG.getVectorIdxConstant(Idx, dl)));
3093       else
3094         Ops.push_back(
3095             DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Op1,
3096                         DAG.getVectorIdxConstant(Idx - NumElems, dl)));
3097     }
3098 
3099     Tmp1 = DAG.getBuildVector(VT, dl, Ops);
3100     // We may have changed the BUILD_VECTOR type. Cast it back to the Node type.
3101     Tmp1 = DAG.getNode(ISD::BITCAST, dl, Node->getValueType(0), Tmp1);
3102     Results.push_back(Tmp1);
3103     break;
3104   }
3105   case ISD::VECTOR_SPLICE: {
3106     Results.push_back(TLI.expandVectorSplice(Node, DAG));
3107     break;
3108   }
3109   case ISD::EXTRACT_ELEMENT: {
3110     EVT OpTy = Node->getOperand(0).getValueType();
3111     if (cast<ConstantSDNode>(Node->getOperand(1))->getZExtValue()) {
3112       // 1 -> Hi
3113       Tmp1 = DAG.getNode(ISD::SRL, dl, OpTy, Node->getOperand(0),
3114                          DAG.getConstant(OpTy.getSizeInBits() / 2, dl,
3115                                          TLI.getShiftAmountTy(
3116                                              Node->getOperand(0).getValueType(),
3117                                              DAG.getDataLayout())));
3118       Tmp1 = DAG.getNode(ISD::TRUNCATE, dl, Node->getValueType(0), Tmp1);
3119     } else {
3120       // 0 -> Lo
3121       Tmp1 = DAG.getNode(ISD::TRUNCATE, dl, Node->getValueType(0),
3122                          Node->getOperand(0));
3123     }
3124     Results.push_back(Tmp1);
3125     break;
3126   }
3127   case ISD::STACKSAVE:
3128     // Expand to CopyFromReg if the target set
3129     // StackPointerRegisterToSaveRestore.
3130     if (Register SP = TLI.getStackPointerRegisterToSaveRestore()) {
3131       Results.push_back(DAG.getCopyFromReg(Node->getOperand(0), dl, SP,
3132                                            Node->getValueType(0)));
3133       Results.push_back(Results[0].getValue(1));
3134     } else {
3135       Results.push_back(DAG.getUNDEF(Node->getValueType(0)));
3136       Results.push_back(Node->getOperand(0));
3137     }
3138     break;
3139   case ISD::STACKRESTORE:
3140     // Expand to CopyToReg if the target set
3141     // StackPointerRegisterToSaveRestore.
3142     if (Register SP = TLI.getStackPointerRegisterToSaveRestore()) {
3143       Results.push_back(DAG.getCopyToReg(Node->getOperand(0), dl, SP,
3144                                          Node->getOperand(1)));
3145     } else {
3146       Results.push_back(Node->getOperand(0));
3147     }
3148     break;
3149   case ISD::GET_DYNAMIC_AREA_OFFSET:
3150     Results.push_back(DAG.getConstant(0, dl, Node->getValueType(0)));
3151     Results.push_back(Results[0].getValue(0));
3152     break;
3153   case ISD::FCOPYSIGN:
3154     Results.push_back(ExpandFCOPYSIGN(Node));
3155     break;
3156   case ISD::FNEG:
3157     Results.push_back(ExpandFNEG(Node));
3158     break;
3159   case ISD::FABS:
3160     Results.push_back(ExpandFABS(Node));
3161     break;
3162   case ISD::IS_FPCLASS: {
3163     auto CNode = cast<ConstantSDNode>(Node->getOperand(1));
3164     auto Test = static_cast<FPClassTest>(CNode->getZExtValue());
3165     if (SDValue Expanded =
3166             TLI.expandIS_FPCLASS(Node->getValueType(0), Node->getOperand(0),
3167                                  Test, Node->getFlags(), SDLoc(Node), DAG))
3168       Results.push_back(Expanded);
3169     break;
3170   }
3171   case ISD::SMIN:
3172   case ISD::SMAX:
3173   case ISD::UMIN:
3174   case ISD::UMAX: {
3175     // Expand Y = MAX(A, B) -> Y = (A > B) ? A : B
3176     ISD::CondCode Pred;
3177     switch (Node->getOpcode()) {
3178     default: llvm_unreachable("How did we get here?");
3179     case ISD::SMAX: Pred = ISD::SETGT; break;
3180     case ISD::SMIN: Pred = ISD::SETLT; break;
3181     case ISD::UMAX: Pred = ISD::SETUGT; break;
3182     case ISD::UMIN: Pred = ISD::SETULT; break;
3183     }
3184     Tmp1 = Node->getOperand(0);
3185     Tmp2 = Node->getOperand(1);
3186     Tmp1 = DAG.getSelectCC(dl, Tmp1, Tmp2, Tmp1, Tmp2, Pred);
3187     Results.push_back(Tmp1);
3188     break;
3189   }
3190   case ISD::FMINNUM:
3191   case ISD::FMAXNUM: {
3192     if (SDValue Expanded = TLI.expandFMINNUM_FMAXNUM(Node, DAG))
3193       Results.push_back(Expanded);
3194     break;
3195   }
3196   case ISD::FSIN:
3197   case ISD::FCOS: {
3198     EVT VT = Node->getValueType(0);
3199     // Turn fsin / fcos into ISD::FSINCOS node if there are a pair of fsin /
3200     // fcos which share the same operand and both are used.
3201     if ((TLI.isOperationLegalOrCustom(ISD::FSINCOS, VT) ||
3202          isSinCosLibcallAvailable(Node, TLI))
3203         && useSinCos(Node)) {
3204       SDVTList VTs = DAG.getVTList(VT, VT);
3205       Tmp1 = DAG.getNode(ISD::FSINCOS, dl, VTs, Node->getOperand(0));
3206       if (Node->getOpcode() == ISD::FCOS)
3207         Tmp1 = Tmp1.getValue(1);
3208       Results.push_back(Tmp1);
3209     }
3210     break;
3211   }
3212   case ISD::FMAD:
3213     llvm_unreachable("Illegal fmad should never be formed");
3214 
3215   case ISD::FP16_TO_FP:
3216     if (Node->getValueType(0) != MVT::f32) {
3217       // We can extend to types bigger than f32 in two steps without changing
3218       // the result. Since "f16 -> f32" is much more commonly available, give
3219       // CodeGen the option of emitting that before resorting to a libcall.
3220       SDValue Res =
3221           DAG.getNode(ISD::FP16_TO_FP, dl, MVT::f32, Node->getOperand(0));
3222       Results.push_back(
3223           DAG.getNode(ISD::FP_EXTEND, dl, Node->getValueType(0), Res));
3224     }
3225     break;
3226   case ISD::STRICT_FP16_TO_FP:
3227     if (Node->getValueType(0) != MVT::f32) {
3228       // We can extend to types bigger than f32 in two steps without changing
3229       // the result. Since "f16 -> f32" is much more commonly available, give
3230       // CodeGen the option of emitting that before resorting to a libcall.
3231       SDValue Res =
3232           DAG.getNode(ISD::STRICT_FP16_TO_FP, dl, {MVT::f32, MVT::Other},
3233                       {Node->getOperand(0), Node->getOperand(1)});
3234       Res = DAG.getNode(ISD::STRICT_FP_EXTEND, dl,
3235                         {Node->getValueType(0), MVT::Other},
3236                         {Res.getValue(1), Res});
3237       Results.push_back(Res);
3238       Results.push_back(Res.getValue(1));
3239     }
3240     break;
3241   case ISD::FP_TO_FP16:
3242     LLVM_DEBUG(dbgs() << "Legalizing FP_TO_FP16\n");
3243     if (!TLI.useSoftFloat() && TM.Options.UnsafeFPMath) {
3244       SDValue Op = Node->getOperand(0);
3245       MVT SVT = Op.getSimpleValueType();
3246       if ((SVT == MVT::f64 || SVT == MVT::f80) &&
3247           TLI.isOperationLegalOrCustom(ISD::FP_TO_FP16, MVT::f32)) {
3248         // Under fastmath, we can expand this node into a fround followed by
3249         // a float-half conversion.
3250         SDValue FloatVal = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, Op,
3251                                        DAG.getIntPtrConstant(0, dl));
3252         Results.push_back(
3253             DAG.getNode(ISD::FP_TO_FP16, dl, Node->getValueType(0), FloatVal));
3254       }
3255     }
3256     break;
3257   case ISD::ConstantFP: {
3258     ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Node);
3259     // Check to see if this FP immediate is already legal.
3260     // If this is a legal constant, turn it into a TargetConstantFP node.
3261     if (!TLI.isFPImmLegal(CFP->getValueAPF(), Node->getValueType(0),
3262                           DAG.shouldOptForSize()))
3263       Results.push_back(ExpandConstantFP(CFP, true));
3264     break;
3265   }
3266   case ISD::Constant: {
3267     ConstantSDNode *CP = cast<ConstantSDNode>(Node);
3268     Results.push_back(ExpandConstant(CP));
3269     break;
3270   }
3271   case ISD::FSUB: {
3272     EVT VT = Node->getValueType(0);
3273     if (TLI.isOperationLegalOrCustom(ISD::FADD, VT) &&
3274         TLI.isOperationLegalOrCustom(ISD::FNEG, VT)) {
3275       const SDNodeFlags Flags = Node->getFlags();
3276       Tmp1 = DAG.getNode(ISD::FNEG, dl, VT, Node->getOperand(1));
3277       Tmp1 = DAG.getNode(ISD::FADD, dl, VT, Node->getOperand(0), Tmp1, Flags);
3278       Results.push_back(Tmp1);
3279     }
3280     break;
3281   }
3282   case ISD::SUB: {
3283     EVT VT = Node->getValueType(0);
3284     assert(TLI.isOperationLegalOrCustom(ISD::ADD, VT) &&
3285            TLI.isOperationLegalOrCustom(ISD::XOR, VT) &&
3286            "Don't know how to expand this subtraction!");
3287     Tmp1 = DAG.getNOT(dl, Node->getOperand(1), VT);
3288     Tmp1 = DAG.getNode(ISD::ADD, dl, VT, Tmp1, DAG.getConstant(1, dl, VT));
3289     Results.push_back(DAG.getNode(ISD::ADD, dl, VT, Node->getOperand(0), Tmp1));
3290     break;
3291   }
3292   case ISD::UREM:
3293   case ISD::SREM:
3294     if (TLI.expandREM(Node, Tmp1, DAG))
3295       Results.push_back(Tmp1);
3296     break;
3297   case ISD::UDIV:
3298   case ISD::SDIV: {
3299     bool isSigned = Node->getOpcode() == ISD::SDIV;
3300     unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM;
3301     EVT VT = Node->getValueType(0);
3302     if (TLI.isOperationLegalOrCustom(DivRemOpc, VT)) {
3303       SDVTList VTs = DAG.getVTList(VT, VT);
3304       Tmp1 = DAG.getNode(DivRemOpc, dl, VTs, Node->getOperand(0),
3305                          Node->getOperand(1));
3306       Results.push_back(Tmp1);
3307     }
3308     break;
3309   }
3310   case ISD::MULHU:
3311   case ISD::MULHS: {
3312     unsigned ExpandOpcode =
3313         Node->getOpcode() == ISD::MULHU ? ISD::UMUL_LOHI : ISD::SMUL_LOHI;
3314     EVT VT = Node->getValueType(0);
3315     SDVTList VTs = DAG.getVTList(VT, VT);
3316 
3317     Tmp1 = DAG.getNode(ExpandOpcode, dl, VTs, Node->getOperand(0),
3318                        Node->getOperand(1));
3319     Results.push_back(Tmp1.getValue(1));
3320     break;
3321   }
3322   case ISD::UMUL_LOHI:
3323   case ISD::SMUL_LOHI: {
3324     SDValue LHS = Node->getOperand(0);
3325     SDValue RHS = Node->getOperand(1);
3326     MVT VT = LHS.getSimpleValueType();
3327     unsigned MULHOpcode =
3328         Node->getOpcode() == ISD::UMUL_LOHI ? ISD::MULHU : ISD::MULHS;
3329 
3330     if (TLI.isOperationLegalOrCustom(MULHOpcode, VT)) {
3331       Results.push_back(DAG.getNode(ISD::MUL, dl, VT, LHS, RHS));
3332       Results.push_back(DAG.getNode(MULHOpcode, dl, VT, LHS, RHS));
3333       break;
3334     }
3335 
3336     SmallVector<SDValue, 4> Halves;
3337     EVT HalfType = EVT(VT).getHalfSizedIntegerVT(*DAG.getContext());
3338     assert(TLI.isTypeLegal(HalfType));
3339     if (TLI.expandMUL_LOHI(Node->getOpcode(), VT, dl, LHS, RHS, Halves,
3340                            HalfType, DAG,
3341                            TargetLowering::MulExpansionKind::Always)) {
3342       for (unsigned i = 0; i < 2; ++i) {
3343         SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Halves[2 * i]);
3344         SDValue Hi = DAG.getNode(ISD::ANY_EXTEND, dl, VT, Halves[2 * i + 1]);
3345         SDValue Shift = DAG.getConstant(
3346             HalfType.getScalarSizeInBits(), dl,
3347             TLI.getShiftAmountTy(HalfType, DAG.getDataLayout()));
3348         Hi = DAG.getNode(ISD::SHL, dl, VT, Hi, Shift);
3349         Results.push_back(DAG.getNode(ISD::OR, dl, VT, Lo, Hi));
3350       }
3351       break;
3352     }
3353     break;
3354   }
3355   case ISD::MUL: {
3356     EVT VT = Node->getValueType(0);
3357     SDVTList VTs = DAG.getVTList(VT, VT);
3358     // See if multiply or divide can be lowered using two-result operations.
3359     // We just need the low half of the multiply; try both the signed
3360     // and unsigned forms. If the target supports both SMUL_LOHI and
3361     // UMUL_LOHI, form a preference by checking which forms of plain
3362     // MULH it supports.
3363     bool HasSMUL_LOHI = TLI.isOperationLegalOrCustom(ISD::SMUL_LOHI, VT);
3364     bool HasUMUL_LOHI = TLI.isOperationLegalOrCustom(ISD::UMUL_LOHI, VT);
3365     bool HasMULHS = TLI.isOperationLegalOrCustom(ISD::MULHS, VT);
3366     bool HasMULHU = TLI.isOperationLegalOrCustom(ISD::MULHU, VT);
3367     unsigned OpToUse = 0;
3368     if (HasSMUL_LOHI && !HasMULHS) {
3369       OpToUse = ISD::SMUL_LOHI;
3370     } else if (HasUMUL_LOHI && !HasMULHU) {
3371       OpToUse = ISD::UMUL_LOHI;
3372     } else if (HasSMUL_LOHI) {
3373       OpToUse = ISD::SMUL_LOHI;
3374     } else if (HasUMUL_LOHI) {
3375       OpToUse = ISD::UMUL_LOHI;
3376     }
3377     if (OpToUse) {
3378       Results.push_back(DAG.getNode(OpToUse, dl, VTs, Node->getOperand(0),
3379                                     Node->getOperand(1)));
3380       break;
3381     }
3382 
3383     SDValue Lo, Hi;
3384     EVT HalfType = VT.getHalfSizedIntegerVT(*DAG.getContext());
3385     if (TLI.isOperationLegalOrCustom(ISD::ZERO_EXTEND, VT) &&
3386         TLI.isOperationLegalOrCustom(ISD::ANY_EXTEND, VT) &&
3387         TLI.isOperationLegalOrCustom(ISD::SHL, VT) &&
3388         TLI.isOperationLegalOrCustom(ISD::OR, VT) &&
3389         TLI.expandMUL(Node, Lo, Hi, HalfType, DAG,
3390                       TargetLowering::MulExpansionKind::OnlyLegalOrCustom)) {
3391       Lo = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Lo);
3392       Hi = DAG.getNode(ISD::ANY_EXTEND, dl, VT, Hi);
3393       SDValue Shift =
3394           DAG.getConstant(HalfType.getSizeInBits(), dl,
3395                           TLI.getShiftAmountTy(HalfType, DAG.getDataLayout()));
3396       Hi = DAG.getNode(ISD::SHL, dl, VT, Hi, Shift);
3397       Results.push_back(DAG.getNode(ISD::OR, dl, VT, Lo, Hi));
3398     }
3399     break;
3400   }
3401   case ISD::FSHL:
3402   case ISD::FSHR:
3403     if (SDValue Expanded = TLI.expandFunnelShift(Node, DAG))
3404       Results.push_back(Expanded);
3405     break;
3406   case ISD::ROTL:
3407   case ISD::ROTR:
3408     if (SDValue Expanded = TLI.expandROT(Node, true /*AllowVectorOps*/, DAG))
3409       Results.push_back(Expanded);
3410     break;
3411   case ISD::SADDSAT:
3412   case ISD::UADDSAT:
3413   case ISD::SSUBSAT:
3414   case ISD::USUBSAT:
3415     Results.push_back(TLI.expandAddSubSat(Node, DAG));
3416     break;
3417   case ISD::SSHLSAT:
3418   case ISD::USHLSAT:
3419     Results.push_back(TLI.expandShlSat(Node, DAG));
3420     break;
3421   case ISD::SMULFIX:
3422   case ISD::SMULFIXSAT:
3423   case ISD::UMULFIX:
3424   case ISD::UMULFIXSAT:
3425     Results.push_back(TLI.expandFixedPointMul(Node, DAG));
3426     break;
3427   case ISD::SDIVFIX:
3428   case ISD::SDIVFIXSAT:
3429   case ISD::UDIVFIX:
3430   case ISD::UDIVFIXSAT:
3431     if (SDValue V = TLI.expandFixedPointDiv(Node->getOpcode(), SDLoc(Node),
3432                                             Node->getOperand(0),
3433                                             Node->getOperand(1),
3434                                             Node->getConstantOperandVal(2),
3435                                             DAG)) {
3436       Results.push_back(V);
3437       break;
3438     }
3439     // FIXME: We might want to retry here with a wider type if we fail, if that
3440     // type is legal.
3441     // FIXME: Technically, so long as we only have sdivfixes where BW+Scale is
3442     // <= 128 (which is the case for all of the default Embedded-C types),
3443     // we will only get here with types and scales that we could always expand
3444     // if we were allowed to generate libcalls to division functions of illegal
3445     // type. But we cannot do that.
3446     llvm_unreachable("Cannot expand DIVFIX!");
3447   case ISD::ADDCARRY:
3448   case ISD::SUBCARRY: {
3449     SDValue LHS = Node->getOperand(0);
3450     SDValue RHS = Node->getOperand(1);
3451     SDValue Carry = Node->getOperand(2);
3452 
3453     bool IsAdd = Node->getOpcode() == ISD::ADDCARRY;
3454 
3455     // Initial add of the 2 operands.
3456     unsigned Op = IsAdd ? ISD::ADD : ISD::SUB;
3457     EVT VT = LHS.getValueType();
3458     SDValue Sum = DAG.getNode(Op, dl, VT, LHS, RHS);
3459 
3460     // Initial check for overflow.
3461     EVT CarryType = Node->getValueType(1);
3462     EVT SetCCType = getSetCCResultType(Node->getValueType(0));
3463     ISD::CondCode CC = IsAdd ? ISD::SETULT : ISD::SETUGT;
3464     SDValue Overflow = DAG.getSetCC(dl, SetCCType, Sum, LHS, CC);
3465 
3466     // Add of the sum and the carry.
3467     SDValue One = DAG.getConstant(1, dl, VT);
3468     SDValue CarryExt =
3469         DAG.getNode(ISD::AND, dl, VT, DAG.getZExtOrTrunc(Carry, dl, VT), One);
3470     SDValue Sum2 = DAG.getNode(Op, dl, VT, Sum, CarryExt);
3471 
3472     // Second check for overflow. If we are adding, we can only overflow if the
3473     // initial sum is all 1s ang the carry is set, resulting in a new sum of 0.
3474     // If we are subtracting, we can only overflow if the initial sum is 0 and
3475     // the carry is set, resulting in a new sum of all 1s.
3476     SDValue Zero = DAG.getConstant(0, dl, VT);
3477     SDValue Overflow2 =
3478         IsAdd ? DAG.getSetCC(dl, SetCCType, Sum2, Zero, ISD::SETEQ)
3479               : DAG.getSetCC(dl, SetCCType, Sum, Zero, ISD::SETEQ);
3480     Overflow2 = DAG.getNode(ISD::AND, dl, SetCCType, Overflow2,
3481                             DAG.getZExtOrTrunc(Carry, dl, SetCCType));
3482 
3483     SDValue ResultCarry =
3484         DAG.getNode(ISD::OR, dl, SetCCType, Overflow, Overflow2);
3485 
3486     Results.push_back(Sum2);
3487     Results.push_back(DAG.getBoolExtOrTrunc(ResultCarry, dl, CarryType, VT));
3488     break;
3489   }
3490   case ISD::SADDO:
3491   case ISD::SSUBO: {
3492     SDValue Result, Overflow;
3493     TLI.expandSADDSUBO(Node, Result, Overflow, DAG);
3494     Results.push_back(Result);
3495     Results.push_back(Overflow);
3496     break;
3497   }
3498   case ISD::UADDO:
3499   case ISD::USUBO: {
3500     SDValue Result, Overflow;
3501     TLI.expandUADDSUBO(Node, Result, Overflow, DAG);
3502     Results.push_back(Result);
3503     Results.push_back(Overflow);
3504     break;
3505   }
3506   case ISD::UMULO:
3507   case ISD::SMULO: {
3508     SDValue Result, Overflow;
3509     if (TLI.expandMULO(Node, Result, Overflow, DAG)) {
3510       Results.push_back(Result);
3511       Results.push_back(Overflow);
3512     }
3513     break;
3514   }
3515   case ISD::BUILD_PAIR: {
3516     EVT PairTy = Node->getValueType(0);
3517     Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, dl, PairTy, Node->getOperand(0));
3518     Tmp2 = DAG.getNode(ISD::ANY_EXTEND, dl, PairTy, Node->getOperand(1));
3519     Tmp2 = DAG.getNode(
3520         ISD::SHL, dl, PairTy, Tmp2,
3521         DAG.getConstant(PairTy.getSizeInBits() / 2, dl,
3522                         TLI.getShiftAmountTy(PairTy, DAG.getDataLayout())));
3523     Results.push_back(DAG.getNode(ISD::OR, dl, PairTy, Tmp1, Tmp2));
3524     break;
3525   }
3526   case ISD::SELECT:
3527     Tmp1 = Node->getOperand(0);
3528     Tmp2 = Node->getOperand(1);
3529     Tmp3 = Node->getOperand(2);
3530     if (Tmp1.getOpcode() == ISD::SETCC) {
3531       Tmp1 = DAG.getSelectCC(dl, Tmp1.getOperand(0), Tmp1.getOperand(1),
3532                              Tmp2, Tmp3,
3533                              cast<CondCodeSDNode>(Tmp1.getOperand(2))->get());
3534     } else {
3535       Tmp1 = DAG.getSelectCC(dl, Tmp1,
3536                              DAG.getConstant(0, dl, Tmp1.getValueType()),
3537                              Tmp2, Tmp3, ISD::SETNE);
3538     }
3539     Tmp1->setFlags(Node->getFlags());
3540     Results.push_back(Tmp1);
3541     break;
3542   case ISD::BR_JT: {
3543     SDValue Chain = Node->getOperand(0);
3544     SDValue Table = Node->getOperand(1);
3545     SDValue Index = Node->getOperand(2);
3546 
3547     const DataLayout &TD = DAG.getDataLayout();
3548     EVT PTy = TLI.getPointerTy(TD);
3549 
3550     unsigned EntrySize =
3551       DAG.getMachineFunction().getJumpTableInfo()->getEntrySize(TD);
3552 
3553     // For power-of-two jumptable entry sizes convert multiplication to a shift.
3554     // This transformation needs to be done here since otherwise the MIPS
3555     // backend will end up emitting a three instruction multiply sequence
3556     // instead of a single shift and MSP430 will call a runtime function.
3557     if (llvm::isPowerOf2_32(EntrySize))
3558       Index = DAG.getNode(
3559           ISD::SHL, dl, Index.getValueType(), Index,
3560           DAG.getConstant(llvm::Log2_32(EntrySize), dl, Index.getValueType()));
3561     else
3562       Index = DAG.getNode(ISD::MUL, dl, Index.getValueType(), Index,
3563                           DAG.getConstant(EntrySize, dl, Index.getValueType()));
3564     SDValue Addr = DAG.getNode(ISD::ADD, dl, Index.getValueType(),
3565                                Index, Table);
3566 
3567     EVT MemVT = EVT::getIntegerVT(*DAG.getContext(), EntrySize * 8);
3568     SDValue LD = DAG.getExtLoad(
3569         ISD::SEXTLOAD, dl, PTy, Chain, Addr,
3570         MachinePointerInfo::getJumpTable(DAG.getMachineFunction()), MemVT);
3571     Addr = LD;
3572     if (TLI.isJumpTableRelative()) {
3573       // For PIC, the sequence is:
3574       // BRIND(load(Jumptable + index) + RelocBase)
3575       // RelocBase can be JumpTable, GOT or some sort of global base.
3576       Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr,
3577                           TLI.getPICJumpTableRelocBase(Table, DAG));
3578     }
3579 
3580     Tmp1 = TLI.expandIndirectJTBranch(dl, LD.getValue(1), Addr, DAG);
3581     Results.push_back(Tmp1);
3582     break;
3583   }
3584   case ISD::BRCOND:
3585     // Expand brcond's setcc into its constituent parts and create a BR_CC
3586     // Node.
3587     Tmp1 = Node->getOperand(0);
3588     Tmp2 = Node->getOperand(1);
3589     if (Tmp2.getOpcode() == ISD::SETCC &&
3590         TLI.isOperationLegalOrCustom(ISD::BR_CC,
3591                                      Tmp2.getOperand(0).getValueType())) {
3592       Tmp1 = DAG.getNode(ISD::BR_CC, dl, MVT::Other, Tmp1, Tmp2.getOperand(2),
3593                          Tmp2.getOperand(0), Tmp2.getOperand(1),
3594                          Node->getOperand(2));
3595     } else {
3596       // We test only the i1 bit.  Skip the AND if UNDEF or another AND.
3597       if (Tmp2.isUndef() ||
3598           (Tmp2.getOpcode() == ISD::AND &&
3599            isa<ConstantSDNode>(Tmp2.getOperand(1)) &&
3600            cast<ConstantSDNode>(Tmp2.getOperand(1))->getZExtValue() == 1))
3601         Tmp3 = Tmp2;
3602       else
3603         Tmp3 = DAG.getNode(ISD::AND, dl, Tmp2.getValueType(), Tmp2,
3604                            DAG.getConstant(1, dl, Tmp2.getValueType()));
3605       Tmp1 = DAG.getNode(ISD::BR_CC, dl, MVT::Other, Tmp1,
3606                          DAG.getCondCode(ISD::SETNE), Tmp3,
3607                          DAG.getConstant(0, dl, Tmp3.getValueType()),
3608                          Node->getOperand(2));
3609     }
3610     Results.push_back(Tmp1);
3611     break;
3612   case ISD::SETCC:
3613   case ISD::VP_SETCC:
3614   case ISD::STRICT_FSETCC:
3615   case ISD::STRICT_FSETCCS: {
3616     bool IsVP = Node->getOpcode() == ISD::VP_SETCC;
3617     bool IsStrict = Node->getOpcode() == ISD::STRICT_FSETCC ||
3618                     Node->getOpcode() == ISD::STRICT_FSETCCS;
3619     bool IsSignaling = Node->getOpcode() == ISD::STRICT_FSETCCS;
3620     SDValue Chain = IsStrict ? Node->getOperand(0) : SDValue();
3621     unsigned Offset = IsStrict ? 1 : 0;
3622     Tmp1 = Node->getOperand(0 + Offset);
3623     Tmp2 = Node->getOperand(1 + Offset);
3624     Tmp3 = Node->getOperand(2 + Offset);
3625     SDValue Mask, EVL;
3626     if (IsVP) {
3627       Mask = Node->getOperand(3 + Offset);
3628       EVL = Node->getOperand(4 + Offset);
3629     }
3630     bool Legalized = TLI.LegalizeSetCCCondCode(
3631         DAG, Node->getValueType(0), Tmp1, Tmp2, Tmp3, Mask, EVL, NeedInvert, dl,
3632         Chain, IsSignaling);
3633 
3634     if (Legalized) {
3635       // If we expanded the SETCC by swapping LHS and RHS, or by inverting the
3636       // condition code, create a new SETCC node.
3637       if (Tmp3.getNode()) {
3638         if (IsStrict) {
3639           Tmp1 = DAG.getNode(Node->getOpcode(), dl, Node->getVTList(),
3640                              {Chain, Tmp1, Tmp2, Tmp3}, Node->getFlags());
3641           Chain = Tmp1.getValue(1);
3642         } else if (IsVP) {
3643           Tmp1 = DAG.getNode(Node->getOpcode(), dl, Node->getValueType(0),
3644                              {Tmp1, Tmp2, Tmp3, Mask, EVL}, Node->getFlags());
3645         } else {
3646           Tmp1 = DAG.getNode(Node->getOpcode(), dl, Node->getValueType(0), Tmp1,
3647                              Tmp2, Tmp3, Node->getFlags());
3648         }
3649       }
3650 
3651       // If we expanded the SETCC by inverting the condition code, then wrap
3652       // the existing SETCC in a NOT to restore the intended condition.
3653       if (NeedInvert) {
3654         if (!IsVP)
3655           Tmp1 = DAG.getLogicalNOT(dl, Tmp1, Tmp1->getValueType(0));
3656         else
3657           Tmp1 =
3658               DAG.getVPLogicalNOT(dl, Tmp1, Mask, EVL, Tmp1->getValueType(0));
3659       }
3660 
3661       Results.push_back(Tmp1);
3662       if (IsStrict)
3663         Results.push_back(Chain);
3664 
3665       break;
3666     }
3667 
3668     // FIXME: It seems Legalized is false iff CCCode is Legal. I don't
3669     // understand if this code is useful for strict nodes.
3670     assert(!IsStrict && "Don't know how to expand for strict nodes.");
3671 
3672     // Otherwise, SETCC for the given comparison type must be completely
3673     // illegal; expand it into a SELECT_CC.
3674     // FIXME: This drops the mask/evl for VP_SETCC.
3675     EVT VT = Node->getValueType(0);
3676     EVT Tmp1VT = Tmp1.getValueType();
3677     Tmp1 = DAG.getNode(ISD::SELECT_CC, dl, VT, Tmp1, Tmp2,
3678                        DAG.getBoolConstant(true, dl, VT, Tmp1VT),
3679                        DAG.getBoolConstant(false, dl, VT, Tmp1VT), Tmp3);
3680     Tmp1->setFlags(Node->getFlags());
3681     Results.push_back(Tmp1);
3682     break;
3683   }
3684   case ISD::SELECT_CC: {
3685     // TODO: need to add STRICT_SELECT_CC and STRICT_SELECT_CCS
3686     Tmp1 = Node->getOperand(0);   // LHS
3687     Tmp2 = Node->getOperand(1);   // RHS
3688     Tmp3 = Node->getOperand(2);   // True
3689     Tmp4 = Node->getOperand(3);   // False
3690     EVT VT = Node->getValueType(0);
3691     SDValue Chain;
3692     SDValue CC = Node->getOperand(4);
3693     ISD::CondCode CCOp = cast<CondCodeSDNode>(CC)->get();
3694 
3695     if (TLI.isCondCodeLegalOrCustom(CCOp, Tmp1.getSimpleValueType())) {
3696       // If the condition code is legal, then we need to expand this
3697       // node using SETCC and SELECT.
3698       EVT CmpVT = Tmp1.getValueType();
3699       assert(!TLI.isOperationExpand(ISD::SELECT, VT) &&
3700              "Cannot expand ISD::SELECT_CC when ISD::SELECT also needs to be "
3701              "expanded.");
3702       EVT CCVT = getSetCCResultType(CmpVT);
3703       SDValue Cond = DAG.getNode(ISD::SETCC, dl, CCVT, Tmp1, Tmp2, CC, Node->getFlags());
3704       Results.push_back(DAG.getSelect(dl, VT, Cond, Tmp3, Tmp4));
3705       break;
3706     }
3707 
3708     // SELECT_CC is legal, so the condition code must not be.
3709     bool Legalized = false;
3710     // Try to legalize by inverting the condition.  This is for targets that
3711     // might support an ordered version of a condition, but not the unordered
3712     // version (or vice versa).
3713     ISD::CondCode InvCC = ISD::getSetCCInverse(CCOp, Tmp1.getValueType());
3714     if (TLI.isCondCodeLegalOrCustom(InvCC, Tmp1.getSimpleValueType())) {
3715       // Use the new condition code and swap true and false
3716       Legalized = true;
3717       Tmp1 = DAG.getSelectCC(dl, Tmp1, Tmp2, Tmp4, Tmp3, InvCC);
3718       Tmp1->setFlags(Node->getFlags());
3719     } else {
3720       // If The inverse is not legal, then try to swap the arguments using
3721       // the inverse condition code.
3722       ISD::CondCode SwapInvCC = ISD::getSetCCSwappedOperands(InvCC);
3723       if (TLI.isCondCodeLegalOrCustom(SwapInvCC, Tmp1.getSimpleValueType())) {
3724         // The swapped inverse condition is legal, so swap true and false,
3725         // lhs and rhs.
3726         Legalized = true;
3727         Tmp1 = DAG.getSelectCC(dl, Tmp2, Tmp1, Tmp4, Tmp3, SwapInvCC);
3728         Tmp1->setFlags(Node->getFlags());
3729       }
3730     }
3731 
3732     if (!Legalized) {
3733       Legalized = TLI.LegalizeSetCCCondCode(
3734           DAG, getSetCCResultType(Tmp1.getValueType()), Tmp1, Tmp2, CC,
3735           /*Mask*/ SDValue(), /*EVL*/ SDValue(), NeedInvert, dl, Chain);
3736 
3737       assert(Legalized && "Can't legalize SELECT_CC with legal condition!");
3738 
3739       // If we expanded the SETCC by inverting the condition code, then swap
3740       // the True/False operands to match.
3741       if (NeedInvert)
3742         std::swap(Tmp3, Tmp4);
3743 
3744       // If we expanded the SETCC by swapping LHS and RHS, or by inverting the
3745       // condition code, create a new SELECT_CC node.
3746       if (CC.getNode()) {
3747         Tmp1 = DAG.getNode(ISD::SELECT_CC, dl, Node->getValueType(0),
3748                            Tmp1, Tmp2, Tmp3, Tmp4, CC);
3749       } else {
3750         Tmp2 = DAG.getConstant(0, dl, Tmp1.getValueType());
3751         CC = DAG.getCondCode(ISD::SETNE);
3752         Tmp1 = DAG.getNode(ISD::SELECT_CC, dl, Node->getValueType(0), Tmp1,
3753                            Tmp2, Tmp3, Tmp4, CC);
3754       }
3755       Tmp1->setFlags(Node->getFlags());
3756     }
3757     Results.push_back(Tmp1);
3758     break;
3759   }
3760   case ISD::BR_CC: {
3761     // TODO: need to add STRICT_BR_CC and STRICT_BR_CCS
3762     SDValue Chain;
3763     Tmp1 = Node->getOperand(0);              // Chain
3764     Tmp2 = Node->getOperand(2);              // LHS
3765     Tmp3 = Node->getOperand(3);              // RHS
3766     Tmp4 = Node->getOperand(1);              // CC
3767 
3768     bool Legalized = TLI.LegalizeSetCCCondCode(
3769         DAG, getSetCCResultType(Tmp2.getValueType()), Tmp2, Tmp3, Tmp4,
3770         /*Mask*/ SDValue(), /*EVL*/ SDValue(), NeedInvert, dl, Chain);
3771     (void)Legalized;
3772     assert(Legalized && "Can't legalize BR_CC with legal condition!");
3773 
3774     // If we expanded the SETCC by swapping LHS and RHS, create a new BR_CC
3775     // node.
3776     if (Tmp4.getNode()) {
3777       assert(!NeedInvert && "Don't know how to invert BR_CC!");
3778 
3779       Tmp1 = DAG.getNode(ISD::BR_CC, dl, Node->getValueType(0), Tmp1,
3780                          Tmp4, Tmp2, Tmp3, Node->getOperand(4));
3781     } else {
3782       Tmp3 = DAG.getConstant(0, dl, Tmp2.getValueType());
3783       Tmp4 = DAG.getCondCode(NeedInvert ? ISD::SETEQ : ISD::SETNE);
3784       Tmp1 = DAG.getNode(ISD::BR_CC, dl, Node->getValueType(0), Tmp1, Tmp4,
3785                          Tmp2, Tmp3, Node->getOperand(4));
3786     }
3787     Results.push_back(Tmp1);
3788     break;
3789   }
3790   case ISD::BUILD_VECTOR:
3791     Results.push_back(ExpandBUILD_VECTOR(Node));
3792     break;
3793   case ISD::SPLAT_VECTOR:
3794     Results.push_back(ExpandSPLAT_VECTOR(Node));
3795     break;
3796   case ISD::SRA:
3797   case ISD::SRL:
3798   case ISD::SHL: {
3799     // Scalarize vector SRA/SRL/SHL.
3800     EVT VT = Node->getValueType(0);
3801     assert(VT.isVector() && "Unable to legalize non-vector shift");
3802     assert(TLI.isTypeLegal(VT.getScalarType())&& "Element type must be legal");
3803     unsigned NumElem = VT.getVectorNumElements();
3804 
3805     SmallVector<SDValue, 8> Scalars;
3806     for (unsigned Idx = 0; Idx < NumElem; Idx++) {
3807       SDValue Ex =
3808           DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT.getScalarType(),
3809                       Node->getOperand(0), DAG.getVectorIdxConstant(Idx, dl));
3810       SDValue Sh =
3811           DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT.getScalarType(),
3812                       Node->getOperand(1), DAG.getVectorIdxConstant(Idx, dl));
3813       Scalars.push_back(DAG.getNode(Node->getOpcode(), dl,
3814                                     VT.getScalarType(), Ex, Sh));
3815     }
3816 
3817     SDValue Result = DAG.getBuildVector(Node->getValueType(0), dl, Scalars);
3818     Results.push_back(Result);
3819     break;
3820   }
3821   case ISD::VECREDUCE_FADD:
3822   case ISD::VECREDUCE_FMUL:
3823   case ISD::VECREDUCE_ADD:
3824   case ISD::VECREDUCE_MUL:
3825   case ISD::VECREDUCE_AND:
3826   case ISD::VECREDUCE_OR:
3827   case ISD::VECREDUCE_XOR:
3828   case ISD::VECREDUCE_SMAX:
3829   case ISD::VECREDUCE_SMIN:
3830   case ISD::VECREDUCE_UMAX:
3831   case ISD::VECREDUCE_UMIN:
3832   case ISD::VECREDUCE_FMAX:
3833   case ISD::VECREDUCE_FMIN:
3834     Results.push_back(TLI.expandVecReduce(Node, DAG));
3835     break;
3836   case ISD::GLOBAL_OFFSET_TABLE:
3837   case ISD::GlobalAddress:
3838   case ISD::GlobalTLSAddress:
3839   case ISD::ExternalSymbol:
3840   case ISD::ConstantPool:
3841   case ISD::JumpTable:
3842   case ISD::INTRINSIC_W_CHAIN:
3843   case ISD::INTRINSIC_WO_CHAIN:
3844   case ISD::INTRINSIC_VOID:
3845     // FIXME: Custom lowering for these operations shouldn't return null!
3846     // Return true so that we don't call ConvertNodeToLibcall which also won't
3847     // do anything.
3848     return true;
3849   }
3850 
3851   if (!TLI.isStrictFPEnabled() && Results.empty() && Node->isStrictFPOpcode()) {
3852     // FIXME: We were asked to expand a strict floating-point operation,
3853     // but there is currently no expansion implemented that would preserve
3854     // the "strict" properties.  For now, we just fall back to the non-strict
3855     // version if that is legal on the target.  The actual mutation of the
3856     // operation will happen in SelectionDAGISel::DoInstructionSelection.
3857     switch (Node->getOpcode()) {
3858     default:
3859       if (TLI.getStrictFPOperationAction(Node->getOpcode(),
3860                                          Node->getValueType(0))
3861           == TargetLowering::Legal)
3862         return true;
3863       break;
3864     case ISD::STRICT_FSUB: {
3865       if (TLI.getStrictFPOperationAction(
3866               ISD::STRICT_FSUB, Node->getValueType(0)) == TargetLowering::Legal)
3867         return true;
3868       if (TLI.getStrictFPOperationAction(
3869               ISD::STRICT_FADD, Node->getValueType(0)) != TargetLowering::Legal)
3870         break;
3871 
3872       EVT VT = Node->getValueType(0);
3873       const SDNodeFlags Flags = Node->getFlags();
3874       SDValue Neg = DAG.getNode(ISD::FNEG, dl, VT, Node->getOperand(2), Flags);
3875       SDValue Fadd = DAG.getNode(ISD::STRICT_FADD, dl, Node->getVTList(),
3876                                  {Node->getOperand(0), Node->getOperand(1), Neg},
3877                          Flags);
3878 
3879       Results.push_back(Fadd);
3880       Results.push_back(Fadd.getValue(1));
3881       break;
3882     }
3883     case ISD::STRICT_SINT_TO_FP:
3884     case ISD::STRICT_UINT_TO_FP:
3885     case ISD::STRICT_LRINT:
3886     case ISD::STRICT_LLRINT:
3887     case ISD::STRICT_LROUND:
3888     case ISD::STRICT_LLROUND:
3889       // These are registered by the operand type instead of the value
3890       // type. Reflect that here.
3891       if (TLI.getStrictFPOperationAction(Node->getOpcode(),
3892                                          Node->getOperand(1).getValueType())
3893           == TargetLowering::Legal)
3894         return true;
3895       break;
3896     }
3897   }
3898 
3899   // Replace the original node with the legalized result.
3900   if (Results.empty()) {
3901     LLVM_DEBUG(dbgs() << "Cannot expand node\n");
3902     return false;
3903   }
3904 
3905   LLVM_DEBUG(dbgs() << "Successfully expanded node\n");
3906   ReplaceNode(Node, Results.data());
3907   return true;
3908 }
3909 
3910 void SelectionDAGLegalize::ConvertNodeToLibcall(SDNode *Node) {
3911   LLVM_DEBUG(dbgs() << "Trying to convert node to libcall\n");
3912   SmallVector<SDValue, 8> Results;
3913   SDLoc dl(Node);
3914   // FIXME: Check flags on the node to see if we can use a finite call.
3915   unsigned Opc = Node->getOpcode();
3916   switch (Opc) {
3917   case ISD::ATOMIC_FENCE: {
3918     // If the target didn't lower this, lower it to '__sync_synchronize()' call
3919     // FIXME: handle "fence singlethread" more efficiently.
3920     TargetLowering::ArgListTy Args;
3921 
3922     TargetLowering::CallLoweringInfo CLI(DAG);
3923     CLI.setDebugLoc(dl)
3924         .setChain(Node->getOperand(0))
3925         .setLibCallee(
3926             CallingConv::C, Type::getVoidTy(*DAG.getContext()),
3927             DAG.getExternalSymbol("__sync_synchronize",
3928                                   TLI.getPointerTy(DAG.getDataLayout())),
3929             std::move(Args));
3930 
3931     std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
3932 
3933     Results.push_back(CallResult.second);
3934     break;
3935   }
3936   // By default, atomic intrinsics are marked Legal and lowered. Targets
3937   // which don't support them directly, however, may want libcalls, in which
3938   // case they mark them Expand, and we get here.
3939   case ISD::ATOMIC_SWAP:
3940   case ISD::ATOMIC_LOAD_ADD:
3941   case ISD::ATOMIC_LOAD_SUB:
3942   case ISD::ATOMIC_LOAD_AND:
3943   case ISD::ATOMIC_LOAD_CLR:
3944   case ISD::ATOMIC_LOAD_OR:
3945   case ISD::ATOMIC_LOAD_XOR:
3946   case ISD::ATOMIC_LOAD_NAND:
3947   case ISD::ATOMIC_LOAD_MIN:
3948   case ISD::ATOMIC_LOAD_MAX:
3949   case ISD::ATOMIC_LOAD_UMIN:
3950   case ISD::ATOMIC_LOAD_UMAX:
3951   case ISD::ATOMIC_CMP_SWAP: {
3952     MVT VT = cast<AtomicSDNode>(Node)->getMemoryVT().getSimpleVT();
3953     AtomicOrdering Order = cast<AtomicSDNode>(Node)->getMergedOrdering();
3954     RTLIB::Libcall LC = RTLIB::getOUTLINE_ATOMIC(Opc, Order, VT);
3955     EVT RetVT = Node->getValueType(0);
3956     TargetLowering::MakeLibCallOptions CallOptions;
3957     SmallVector<SDValue, 4> Ops;
3958     if (TLI.getLibcallName(LC)) {
3959       // If outline atomic available, prepare its arguments and expand.
3960       Ops.append(Node->op_begin() + 2, Node->op_end());
3961       Ops.push_back(Node->getOperand(1));
3962 
3963     } else {
3964       LC = RTLIB::getSYNC(Opc, VT);
3965       assert(LC != RTLIB::UNKNOWN_LIBCALL &&
3966              "Unexpected atomic op or value type!");
3967       // Arguments for expansion to sync libcall
3968       Ops.append(Node->op_begin() + 1, Node->op_end());
3969     }
3970     std::pair<SDValue, SDValue> Tmp = TLI.makeLibCall(DAG, LC, RetVT,
3971                                                       Ops, CallOptions,
3972                                                       SDLoc(Node),
3973                                                       Node->getOperand(0));
3974     Results.push_back(Tmp.first);
3975     Results.push_back(Tmp.second);
3976     break;
3977   }
3978   case ISD::TRAP: {
3979     // If this operation is not supported, lower it to 'abort()' call
3980     TargetLowering::ArgListTy Args;
3981     TargetLowering::CallLoweringInfo CLI(DAG);
3982     CLI.setDebugLoc(dl)
3983         .setChain(Node->getOperand(0))
3984         .setLibCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()),
3985                       DAG.getExternalSymbol(
3986                           "abort", TLI.getPointerTy(DAG.getDataLayout())),
3987                       std::move(Args));
3988     std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
3989 
3990     Results.push_back(CallResult.second);
3991     break;
3992   }
3993   case ISD::FMINNUM:
3994   case ISD::STRICT_FMINNUM:
3995     ExpandFPLibCall(Node, RTLIB::FMIN_F32, RTLIB::FMIN_F64,
3996                     RTLIB::FMIN_F80, RTLIB::FMIN_F128,
3997                     RTLIB::FMIN_PPCF128, Results);
3998     break;
3999   case ISD::FMAXNUM:
4000   case ISD::STRICT_FMAXNUM:
4001     ExpandFPLibCall(Node, RTLIB::FMAX_F32, RTLIB::FMAX_F64,
4002                     RTLIB::FMAX_F80, RTLIB::FMAX_F128,
4003                     RTLIB::FMAX_PPCF128, Results);
4004     break;
4005   case ISD::FSQRT:
4006   case ISD::STRICT_FSQRT:
4007     ExpandFPLibCall(Node, RTLIB::SQRT_F32, RTLIB::SQRT_F64,
4008                     RTLIB::SQRT_F80, RTLIB::SQRT_F128,
4009                     RTLIB::SQRT_PPCF128, Results);
4010     break;
4011   case ISD::FCBRT:
4012     ExpandFPLibCall(Node, RTLIB::CBRT_F32, RTLIB::CBRT_F64,
4013                     RTLIB::CBRT_F80, RTLIB::CBRT_F128,
4014                     RTLIB::CBRT_PPCF128, Results);
4015     break;
4016   case ISD::FSIN:
4017   case ISD::STRICT_FSIN:
4018     ExpandFPLibCall(Node, RTLIB::SIN_F32, RTLIB::SIN_F64,
4019                     RTLIB::SIN_F80, RTLIB::SIN_F128,
4020                     RTLIB::SIN_PPCF128, Results);
4021     break;
4022   case ISD::FCOS:
4023   case ISD::STRICT_FCOS:
4024     ExpandFPLibCall(Node, RTLIB::COS_F32, RTLIB::COS_F64,
4025                     RTLIB::COS_F80, RTLIB::COS_F128,
4026                     RTLIB::COS_PPCF128, Results);
4027     break;
4028   case ISD::FSINCOS:
4029     // Expand into sincos libcall.
4030     ExpandSinCosLibCall(Node, Results);
4031     break;
4032   case ISD::FLOG:
4033   case ISD::STRICT_FLOG:
4034     ExpandFPLibCall(Node, RTLIB::LOG_F32, RTLIB::LOG_F64, RTLIB::LOG_F80,
4035                     RTLIB::LOG_F128, RTLIB::LOG_PPCF128, Results);
4036     break;
4037   case ISD::FLOG2:
4038   case ISD::STRICT_FLOG2:
4039     ExpandFPLibCall(Node, RTLIB::LOG2_F32, RTLIB::LOG2_F64, RTLIB::LOG2_F80,
4040                     RTLIB::LOG2_F128, RTLIB::LOG2_PPCF128, Results);
4041     break;
4042   case ISD::FLOG10:
4043   case ISD::STRICT_FLOG10:
4044     ExpandFPLibCall(Node, RTLIB::LOG10_F32, RTLIB::LOG10_F64, RTLIB::LOG10_F80,
4045                     RTLIB::LOG10_F128, RTLIB::LOG10_PPCF128, Results);
4046     break;
4047   case ISD::FEXP:
4048   case ISD::STRICT_FEXP:
4049     ExpandFPLibCall(Node, RTLIB::EXP_F32, RTLIB::EXP_F64, RTLIB::EXP_F80,
4050                     RTLIB::EXP_F128, RTLIB::EXP_PPCF128, Results);
4051     break;
4052   case ISD::FEXP2:
4053   case ISD::STRICT_FEXP2:
4054     ExpandFPLibCall(Node, RTLIB::EXP2_F32, RTLIB::EXP2_F64, RTLIB::EXP2_F80,
4055                     RTLIB::EXP2_F128, RTLIB::EXP2_PPCF128, Results);
4056     break;
4057   case ISD::FTRUNC:
4058   case ISD::STRICT_FTRUNC:
4059     ExpandFPLibCall(Node, RTLIB::TRUNC_F32, RTLIB::TRUNC_F64,
4060                     RTLIB::TRUNC_F80, RTLIB::TRUNC_F128,
4061                     RTLIB::TRUNC_PPCF128, Results);
4062     break;
4063   case ISD::FFLOOR:
4064   case ISD::STRICT_FFLOOR:
4065     ExpandFPLibCall(Node, RTLIB::FLOOR_F32, RTLIB::FLOOR_F64,
4066                     RTLIB::FLOOR_F80, RTLIB::FLOOR_F128,
4067                     RTLIB::FLOOR_PPCF128, Results);
4068     break;
4069   case ISD::FCEIL:
4070   case ISD::STRICT_FCEIL:
4071     ExpandFPLibCall(Node, RTLIB::CEIL_F32, RTLIB::CEIL_F64,
4072                     RTLIB::CEIL_F80, RTLIB::CEIL_F128,
4073                     RTLIB::CEIL_PPCF128, Results);
4074     break;
4075   case ISD::FRINT:
4076   case ISD::STRICT_FRINT:
4077     ExpandFPLibCall(Node, RTLIB::RINT_F32, RTLIB::RINT_F64,
4078                     RTLIB::RINT_F80, RTLIB::RINT_F128,
4079                     RTLIB::RINT_PPCF128, Results);
4080     break;
4081   case ISD::FNEARBYINT:
4082   case ISD::STRICT_FNEARBYINT:
4083     ExpandFPLibCall(Node, RTLIB::NEARBYINT_F32,
4084                     RTLIB::NEARBYINT_F64,
4085                     RTLIB::NEARBYINT_F80,
4086                     RTLIB::NEARBYINT_F128,
4087                     RTLIB::NEARBYINT_PPCF128, Results);
4088     break;
4089   case ISD::FROUND:
4090   case ISD::STRICT_FROUND:
4091     ExpandFPLibCall(Node, RTLIB::ROUND_F32,
4092                     RTLIB::ROUND_F64,
4093                     RTLIB::ROUND_F80,
4094                     RTLIB::ROUND_F128,
4095                     RTLIB::ROUND_PPCF128, Results);
4096     break;
4097   case ISD::FROUNDEVEN:
4098   case ISD::STRICT_FROUNDEVEN:
4099     ExpandFPLibCall(Node, RTLIB::ROUNDEVEN_F32,
4100                     RTLIB::ROUNDEVEN_F64,
4101                     RTLIB::ROUNDEVEN_F80,
4102                     RTLIB::ROUNDEVEN_F128,
4103                     RTLIB::ROUNDEVEN_PPCF128, Results);
4104     break;
4105   case ISD::FPOWI:
4106   case ISD::STRICT_FPOWI: {
4107     RTLIB::Libcall LC = RTLIB::getPOWI(Node->getSimpleValueType(0));
4108     assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unexpected fpowi.");
4109     if (!TLI.getLibcallName(LC)) {
4110       // Some targets don't have a powi libcall; use pow instead.
4111       if (Node->isStrictFPOpcode()) {
4112         SDValue Exponent =
4113             DAG.getNode(ISD::STRICT_SINT_TO_FP, SDLoc(Node),
4114                         {Node->getValueType(0), Node->getValueType(1)},
4115                         {Node->getOperand(0), Node->getOperand(2)});
4116         SDValue FPOW =
4117             DAG.getNode(ISD::STRICT_FPOW, SDLoc(Node),
4118                         {Node->getValueType(0), Node->getValueType(1)},
4119                         {Exponent.getValue(1), Node->getOperand(1), Exponent});
4120         Results.push_back(FPOW);
4121         Results.push_back(FPOW.getValue(1));
4122       } else {
4123         SDValue Exponent =
4124             DAG.getNode(ISD::SINT_TO_FP, SDLoc(Node), Node->getValueType(0),
4125                         Node->getOperand(1));
4126         Results.push_back(DAG.getNode(ISD::FPOW, SDLoc(Node),
4127                                       Node->getValueType(0),
4128                                       Node->getOperand(0), Exponent));
4129       }
4130       break;
4131     }
4132     unsigned Offset = Node->isStrictFPOpcode() ? 1 : 0;
4133     bool ExponentHasSizeOfInt =
4134         DAG.getLibInfo().getIntSize() ==
4135         Node->getOperand(1 + Offset).getValueType().getSizeInBits();
4136     if (!ExponentHasSizeOfInt) {
4137       // If the exponent does not match with sizeof(int) a libcall to
4138       // RTLIB::POWI would use the wrong type for the argument.
4139       DAG.getContext()->emitError("POWI exponent does not match sizeof(int)");
4140       Results.push_back(DAG.getUNDEF(Node->getValueType(0)));
4141       break;
4142     }
4143     ExpandFPLibCall(Node, LC, Results);
4144     break;
4145   }
4146   case ISD::FPOW:
4147   case ISD::STRICT_FPOW:
4148     ExpandFPLibCall(Node, RTLIB::POW_F32, RTLIB::POW_F64, RTLIB::POW_F80,
4149                     RTLIB::POW_F128, RTLIB::POW_PPCF128, Results);
4150     break;
4151   case ISD::LROUND:
4152   case ISD::STRICT_LROUND:
4153     ExpandArgFPLibCall(Node, RTLIB::LROUND_F32,
4154                        RTLIB::LROUND_F64, RTLIB::LROUND_F80,
4155                        RTLIB::LROUND_F128,
4156                        RTLIB::LROUND_PPCF128, Results);
4157     break;
4158   case ISD::LLROUND:
4159   case ISD::STRICT_LLROUND:
4160     ExpandArgFPLibCall(Node, RTLIB::LLROUND_F32,
4161                        RTLIB::LLROUND_F64, RTLIB::LLROUND_F80,
4162                        RTLIB::LLROUND_F128,
4163                        RTLIB::LLROUND_PPCF128, Results);
4164     break;
4165   case ISD::LRINT:
4166   case ISD::STRICT_LRINT:
4167     ExpandArgFPLibCall(Node, RTLIB::LRINT_F32,
4168                        RTLIB::LRINT_F64, RTLIB::LRINT_F80,
4169                        RTLIB::LRINT_F128,
4170                        RTLIB::LRINT_PPCF128, Results);
4171     break;
4172   case ISD::LLRINT:
4173   case ISD::STRICT_LLRINT:
4174     ExpandArgFPLibCall(Node, RTLIB::LLRINT_F32,
4175                        RTLIB::LLRINT_F64, RTLIB::LLRINT_F80,
4176                        RTLIB::LLRINT_F128,
4177                        RTLIB::LLRINT_PPCF128, Results);
4178     break;
4179   case ISD::FDIV:
4180   case ISD::STRICT_FDIV:
4181     ExpandFPLibCall(Node, RTLIB::DIV_F32, RTLIB::DIV_F64,
4182                     RTLIB::DIV_F80, RTLIB::DIV_F128,
4183                     RTLIB::DIV_PPCF128, Results);
4184     break;
4185   case ISD::FREM:
4186   case ISD::STRICT_FREM:
4187     ExpandFPLibCall(Node, RTLIB::REM_F32, RTLIB::REM_F64,
4188                     RTLIB::REM_F80, RTLIB::REM_F128,
4189                     RTLIB::REM_PPCF128, Results);
4190     break;
4191   case ISD::FMA:
4192   case ISD::STRICT_FMA:
4193     ExpandFPLibCall(Node, RTLIB::FMA_F32, RTLIB::FMA_F64,
4194                     RTLIB::FMA_F80, RTLIB::FMA_F128,
4195                     RTLIB::FMA_PPCF128, Results);
4196     break;
4197   case ISD::FADD:
4198   case ISD::STRICT_FADD:
4199     ExpandFPLibCall(Node, RTLIB::ADD_F32, RTLIB::ADD_F64,
4200                     RTLIB::ADD_F80, RTLIB::ADD_F128,
4201                     RTLIB::ADD_PPCF128, Results);
4202     break;
4203   case ISD::FMUL:
4204   case ISD::STRICT_FMUL:
4205     ExpandFPLibCall(Node, RTLIB::MUL_F32, RTLIB::MUL_F64,
4206                     RTLIB::MUL_F80, RTLIB::MUL_F128,
4207                     RTLIB::MUL_PPCF128, Results);
4208     break;
4209   case ISD::FP16_TO_FP:
4210     if (Node->getValueType(0) == MVT::f32) {
4211       Results.push_back(ExpandLibCall(RTLIB::FPEXT_F16_F32, Node, false));
4212     }
4213     break;
4214   case ISD::STRICT_FP16_TO_FP: {
4215     if (Node->getValueType(0) == MVT::f32) {
4216       TargetLowering::MakeLibCallOptions CallOptions;
4217       std::pair<SDValue, SDValue> Tmp = TLI.makeLibCall(
4218           DAG, RTLIB::FPEXT_F16_F32, MVT::f32, Node->getOperand(1), CallOptions,
4219           SDLoc(Node), Node->getOperand(0));
4220       Results.push_back(Tmp.first);
4221       Results.push_back(Tmp.second);
4222     }
4223     break;
4224   }
4225   case ISD::FP_TO_FP16: {
4226     RTLIB::Libcall LC =
4227         RTLIB::getFPROUND(Node->getOperand(0).getValueType(), MVT::f16);
4228     assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unable to expand fp_to_fp16");
4229     Results.push_back(ExpandLibCall(LC, Node, false));
4230     break;
4231   }
4232   case ISD::FP_TO_BF16: {
4233     RTLIB::Libcall LC =
4234         RTLIB::getFPROUND(Node->getOperand(0).getValueType(), MVT::bf16);
4235     assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unable to expand fp_to_bf16");
4236     Results.push_back(ExpandLibCall(LC, Node, false));
4237     break;
4238   }
4239   case ISD::STRICT_SINT_TO_FP:
4240   case ISD::STRICT_UINT_TO_FP:
4241   case ISD::SINT_TO_FP:
4242   case ISD::UINT_TO_FP: {
4243     // TODO - Common the code with DAGTypeLegalizer::SoftenFloatRes_XINT_TO_FP
4244     bool IsStrict = Node->isStrictFPOpcode();
4245     bool Signed = Node->getOpcode() == ISD::SINT_TO_FP ||
4246                   Node->getOpcode() == ISD::STRICT_SINT_TO_FP;
4247     EVT SVT = Node->getOperand(IsStrict ? 1 : 0).getValueType();
4248     EVT RVT = Node->getValueType(0);
4249     EVT NVT = EVT();
4250     SDLoc dl(Node);
4251 
4252     // Even if the input is legal, no libcall may exactly match, eg. we don't
4253     // have i1 -> fp conversions. So, it needs to be promoted to a larger type,
4254     // eg: i13 -> fp. Then, look for an appropriate libcall.
4255     RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
4256     for (unsigned t = MVT::FIRST_INTEGER_VALUETYPE;
4257          t <= MVT::LAST_INTEGER_VALUETYPE && LC == RTLIB::UNKNOWN_LIBCALL;
4258          ++t) {
4259       NVT = (MVT::SimpleValueType)t;
4260       // The source needs to big enough to hold the operand.
4261       if (NVT.bitsGE(SVT))
4262         LC = Signed ? RTLIB::getSINTTOFP(NVT, RVT)
4263                     : RTLIB::getUINTTOFP(NVT, RVT);
4264     }
4265     assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unable to legalize as libcall");
4266 
4267     SDValue Chain = IsStrict ? Node->getOperand(0) : SDValue();
4268     // Sign/zero extend the argument if the libcall takes a larger type.
4269     SDValue Op = DAG.getNode(Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, dl,
4270                              NVT, Node->getOperand(IsStrict ? 1 : 0));
4271     TargetLowering::MakeLibCallOptions CallOptions;
4272     CallOptions.setSExt(Signed);
4273     std::pair<SDValue, SDValue> Tmp =
4274         TLI.makeLibCall(DAG, LC, RVT, Op, CallOptions, dl, Chain);
4275     Results.push_back(Tmp.first);
4276     if (IsStrict)
4277       Results.push_back(Tmp.second);
4278     break;
4279   }
4280   case ISD::FP_TO_SINT:
4281   case ISD::FP_TO_UINT:
4282   case ISD::STRICT_FP_TO_SINT:
4283   case ISD::STRICT_FP_TO_UINT: {
4284     // TODO - Common the code with DAGTypeLegalizer::SoftenFloatOp_FP_TO_XINT.
4285     bool IsStrict = Node->isStrictFPOpcode();
4286     bool Signed = Node->getOpcode() == ISD::FP_TO_SINT ||
4287                   Node->getOpcode() == ISD::STRICT_FP_TO_SINT;
4288 
4289     SDValue Op = Node->getOperand(IsStrict ? 1 : 0);
4290     EVT SVT = Op.getValueType();
4291     EVT RVT = Node->getValueType(0);
4292     EVT NVT = EVT();
4293     SDLoc dl(Node);
4294 
4295     // Even if the result is legal, no libcall may exactly match, eg. we don't
4296     // have fp -> i1 conversions. So, it needs to be promoted to a larger type,
4297     // eg: fp -> i32. Then, look for an appropriate libcall.
4298     RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
4299     for (unsigned IntVT = MVT::FIRST_INTEGER_VALUETYPE;
4300          IntVT <= MVT::LAST_INTEGER_VALUETYPE && LC == RTLIB::UNKNOWN_LIBCALL;
4301          ++IntVT) {
4302       NVT = (MVT::SimpleValueType)IntVT;
4303       // The type needs to big enough to hold the result.
4304       if (NVT.bitsGE(RVT))
4305         LC = Signed ? RTLIB::getFPTOSINT(SVT, NVT)
4306                     : RTLIB::getFPTOUINT(SVT, NVT);
4307     }
4308     assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unable to legalize as libcall");
4309 
4310     SDValue Chain = IsStrict ? Node->getOperand(0) : SDValue();
4311     TargetLowering::MakeLibCallOptions CallOptions;
4312     std::pair<SDValue, SDValue> Tmp =
4313         TLI.makeLibCall(DAG, LC, NVT, Op, CallOptions, dl, Chain);
4314 
4315     // Truncate the result if the libcall returns a larger type.
4316     Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, RVT, Tmp.first));
4317     if (IsStrict)
4318       Results.push_back(Tmp.second);
4319     break;
4320   }
4321 
4322   case ISD::FP_ROUND:
4323   case ISD::STRICT_FP_ROUND: {
4324     // X = FP_ROUND(Y, TRUNC)
4325     // TRUNC is a flag, which is always an integer that is zero or one.
4326     // If TRUNC is 0, this is a normal rounding, if it is 1, this FP_ROUND
4327     // is known to not change the value of Y.
4328     // We can only expand it into libcall if the TRUNC is 0.
4329     bool IsStrict = Node->isStrictFPOpcode();
4330     SDValue Op = Node->getOperand(IsStrict ? 1 : 0);
4331     SDValue Chain = IsStrict ? Node->getOperand(0) : SDValue();
4332     EVT VT = Node->getValueType(0);
4333     assert(cast<ConstantSDNode>(Node->getOperand(IsStrict ? 2 : 1))->isZero() &&
4334            "Unable to expand as libcall if it is not normal rounding");
4335 
4336     RTLIB::Libcall LC = RTLIB::getFPROUND(Op.getValueType(), VT);
4337     assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unable to legalize as libcall");
4338 
4339     TargetLowering::MakeLibCallOptions CallOptions;
4340     std::pair<SDValue, SDValue> Tmp =
4341         TLI.makeLibCall(DAG, LC, VT, Op, CallOptions, SDLoc(Node), Chain);
4342     Results.push_back(Tmp.first);
4343     if (IsStrict)
4344       Results.push_back(Tmp.second);
4345     break;
4346   }
4347   case ISD::FP_EXTEND: {
4348     Results.push_back(
4349         ExpandLibCall(RTLIB::getFPEXT(Node->getOperand(0).getValueType(),
4350                                       Node->getValueType(0)),
4351                       Node, false));
4352     break;
4353   }
4354   case ISD::STRICT_FP_EXTEND:
4355   case ISD::STRICT_FP_TO_FP16: {
4356     RTLIB::Libcall LC =
4357         Node->getOpcode() == ISD::STRICT_FP_TO_FP16
4358             ? RTLIB::getFPROUND(Node->getOperand(1).getValueType(), MVT::f16)
4359             : RTLIB::getFPEXT(Node->getOperand(1).getValueType(),
4360                               Node->getValueType(0));
4361     assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unable to legalize as libcall");
4362 
4363     TargetLowering::MakeLibCallOptions CallOptions;
4364     std::pair<SDValue, SDValue> Tmp =
4365         TLI.makeLibCall(DAG, LC, Node->getValueType(0), Node->getOperand(1),
4366                         CallOptions, SDLoc(Node), Node->getOperand(0));
4367     Results.push_back(Tmp.first);
4368     Results.push_back(Tmp.second);
4369     break;
4370   }
4371   case ISD::FSUB:
4372   case ISD::STRICT_FSUB:
4373     ExpandFPLibCall(Node, RTLIB::SUB_F32, RTLIB::SUB_F64,
4374                     RTLIB::SUB_F80, RTLIB::SUB_F128,
4375                     RTLIB::SUB_PPCF128, Results);
4376     break;
4377   case ISD::SREM:
4378     Results.push_back(ExpandIntLibCall(
4379         Node, true, RTLIB::SREM_I8, RTLIB::SREM_I16, RTLIB::SREM_I32,
4380         RTLIB::SREM_I64, RTLIB::SREM_I128, RTLIB::SREM_IEXT));
4381     break;
4382   case ISD::UREM:
4383     Results.push_back(ExpandIntLibCall(
4384         Node, false, RTLIB::UREM_I8, RTLIB::UREM_I16, RTLIB::UREM_I32,
4385         RTLIB::UREM_I64, RTLIB::UREM_I128, RTLIB::UREM_IEXT));
4386     break;
4387   case ISD::SDIV:
4388     Results.push_back(ExpandIntLibCall(
4389         Node, true, RTLIB::SDIV_I8, RTLIB::SDIV_I16, RTLIB::SDIV_I32,
4390         RTLIB::SDIV_I64, RTLIB::SDIV_I128, RTLIB::SDIV_IEXT));
4391     break;
4392   case ISD::UDIV:
4393     Results.push_back(ExpandIntLibCall(
4394         Node, false, RTLIB::UDIV_I8, RTLIB::UDIV_I16, RTLIB::UDIV_I32,
4395         RTLIB::UDIV_I64, RTLIB::UDIV_I128, RTLIB::UDIV_IEXT));
4396     break;
4397   case ISD::SDIVREM:
4398   case ISD::UDIVREM:
4399     // Expand into divrem libcall
4400     ExpandDivRemLibCall(Node, Results);
4401     break;
4402   case ISD::MUL:
4403     Results.push_back(ExpandIntLibCall(
4404         Node, false, RTLIB::MUL_I8, RTLIB::MUL_I16, RTLIB::MUL_I32,
4405         RTLIB::MUL_I64, RTLIB::MUL_I128, RTLIB::MUL_IEXT));
4406     break;
4407   case ISD::CTLZ_ZERO_UNDEF:
4408     switch (Node->getSimpleValueType(0).SimpleTy) {
4409     default:
4410       llvm_unreachable("LibCall explicitly requested, but not available");
4411     case MVT::i32:
4412       Results.push_back(ExpandLibCall(RTLIB::CTLZ_I32, Node, false));
4413       break;
4414     case MVT::i64:
4415       Results.push_back(ExpandLibCall(RTLIB::CTLZ_I64, Node, false));
4416       break;
4417     case MVT::i128:
4418       Results.push_back(ExpandLibCall(RTLIB::CTLZ_I128, Node, false));
4419       break;
4420     }
4421     break;
4422   }
4423 
4424   // Replace the original node with the legalized result.
4425   if (!Results.empty()) {
4426     LLVM_DEBUG(dbgs() << "Successfully converted node to libcall\n");
4427     ReplaceNode(Node, Results.data());
4428   } else
4429     LLVM_DEBUG(dbgs() << "Could not convert node to libcall\n");
4430 }
4431 
4432 // Determine the vector type to use in place of an original scalar element when
4433 // promoting equally sized vectors.
4434 static MVT getPromotedVectorElementType(const TargetLowering &TLI,
4435                                         MVT EltVT, MVT NewEltVT) {
4436   unsigned OldEltsPerNewElt = EltVT.getSizeInBits() / NewEltVT.getSizeInBits();
4437   MVT MidVT = MVT::getVectorVT(NewEltVT, OldEltsPerNewElt);
4438   assert(TLI.isTypeLegal(MidVT) && "unexpected");
4439   return MidVT;
4440 }
4441 
4442 void SelectionDAGLegalize::PromoteNode(SDNode *Node) {
4443   LLVM_DEBUG(dbgs() << "Trying to promote node\n");
4444   SmallVector<SDValue, 8> Results;
4445   MVT OVT = Node->getSimpleValueType(0);
4446   if (Node->getOpcode() == ISD::UINT_TO_FP ||
4447       Node->getOpcode() == ISD::SINT_TO_FP ||
4448       Node->getOpcode() == ISD::SETCC ||
4449       Node->getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
4450       Node->getOpcode() == ISD::INSERT_VECTOR_ELT) {
4451     OVT = Node->getOperand(0).getSimpleValueType();
4452   }
4453   if (Node->getOpcode() == ISD::STRICT_UINT_TO_FP ||
4454       Node->getOpcode() == ISD::STRICT_SINT_TO_FP ||
4455       Node->getOpcode() == ISD::STRICT_FSETCC ||
4456       Node->getOpcode() == ISD::STRICT_FSETCCS)
4457     OVT = Node->getOperand(1).getSimpleValueType();
4458   if (Node->getOpcode() == ISD::BR_CC ||
4459       Node->getOpcode() == ISD::SELECT_CC)
4460     OVT = Node->getOperand(2).getSimpleValueType();
4461   MVT NVT = TLI.getTypeToPromoteTo(Node->getOpcode(), OVT);
4462   SDLoc dl(Node);
4463   SDValue Tmp1, Tmp2, Tmp3, Tmp4;
4464   switch (Node->getOpcode()) {
4465   case ISD::CTTZ:
4466   case ISD::CTTZ_ZERO_UNDEF:
4467   case ISD::CTLZ:
4468   case ISD::CTLZ_ZERO_UNDEF:
4469   case ISD::CTPOP:
4470     // Zero extend the argument unless its cttz, then use any_extend.
4471     if (Node->getOpcode() == ISD::CTTZ ||
4472         Node->getOpcode() == ISD::CTTZ_ZERO_UNDEF)
4473       Tmp1 = DAG.getNode(ISD::ANY_EXTEND, dl, NVT, Node->getOperand(0));
4474     else
4475       Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, Node->getOperand(0));
4476 
4477     if (Node->getOpcode() == ISD::CTTZ) {
4478       // The count is the same in the promoted type except if the original
4479       // value was zero.  This can be handled by setting the bit just off
4480       // the top of the original type.
4481       auto TopBit = APInt::getOneBitSet(NVT.getSizeInBits(),
4482                                         OVT.getSizeInBits());
4483       Tmp1 = DAG.getNode(ISD::OR, dl, NVT, Tmp1,
4484                          DAG.getConstant(TopBit, dl, NVT));
4485     }
4486     // Perform the larger operation. For CTPOP and CTTZ_ZERO_UNDEF, this is
4487     // already the correct result.
4488     Tmp1 = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1);
4489     if (Node->getOpcode() == ISD::CTLZ ||
4490         Node->getOpcode() == ISD::CTLZ_ZERO_UNDEF) {
4491       // Tmp1 = Tmp1 - (sizeinbits(NVT) - sizeinbits(Old VT))
4492       Tmp1 = DAG.getNode(ISD::SUB, dl, NVT, Tmp1,
4493                           DAG.getConstant(NVT.getSizeInBits() -
4494                                           OVT.getSizeInBits(), dl, NVT));
4495     }
4496     Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, OVT, Tmp1));
4497     break;
4498   case ISD::BITREVERSE:
4499   case ISD::BSWAP: {
4500     unsigned DiffBits = NVT.getSizeInBits() - OVT.getSizeInBits();
4501     Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, Node->getOperand(0));
4502     Tmp1 = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1);
4503     Tmp1 = DAG.getNode(
4504         ISD::SRL, dl, NVT, Tmp1,
4505         DAG.getConstant(DiffBits, dl,
4506                         TLI.getShiftAmountTy(NVT, DAG.getDataLayout())));
4507 
4508     Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, OVT, Tmp1));
4509     break;
4510   }
4511   case ISD::FP_TO_UINT:
4512   case ISD::STRICT_FP_TO_UINT:
4513   case ISD::FP_TO_SINT:
4514   case ISD::STRICT_FP_TO_SINT:
4515     PromoteLegalFP_TO_INT(Node, dl, Results);
4516     break;
4517   case ISD::FP_TO_UINT_SAT:
4518   case ISD::FP_TO_SINT_SAT:
4519     Results.push_back(PromoteLegalFP_TO_INT_SAT(Node, dl));
4520     break;
4521   case ISD::UINT_TO_FP:
4522   case ISD::STRICT_UINT_TO_FP:
4523   case ISD::SINT_TO_FP:
4524   case ISD::STRICT_SINT_TO_FP:
4525     PromoteLegalINT_TO_FP(Node, dl, Results);
4526     break;
4527   case ISD::VAARG: {
4528     SDValue Chain = Node->getOperand(0); // Get the chain.
4529     SDValue Ptr = Node->getOperand(1); // Get the pointer.
4530 
4531     unsigned TruncOp;
4532     if (OVT.isVector()) {
4533       TruncOp = ISD::BITCAST;
4534     } else {
4535       assert(OVT.isInteger()
4536         && "VAARG promotion is supported only for vectors or integer types");
4537       TruncOp = ISD::TRUNCATE;
4538     }
4539 
4540     // Perform the larger operation, then convert back
4541     Tmp1 = DAG.getVAArg(NVT, dl, Chain, Ptr, Node->getOperand(2),
4542              Node->getConstantOperandVal(3));
4543     Chain = Tmp1.getValue(1);
4544 
4545     Tmp2 = DAG.getNode(TruncOp, dl, OVT, Tmp1);
4546 
4547     // Modified the chain result - switch anything that used the old chain to
4548     // use the new one.
4549     DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 0), Tmp2);
4550     DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), Chain);
4551     if (UpdatedNodes) {
4552       UpdatedNodes->insert(Tmp2.getNode());
4553       UpdatedNodes->insert(Chain.getNode());
4554     }
4555     ReplacedNode(Node);
4556     break;
4557   }
4558   case ISD::MUL:
4559   case ISD::SDIV:
4560   case ISD::SREM:
4561   case ISD::UDIV:
4562   case ISD::UREM:
4563   case ISD::AND:
4564   case ISD::OR:
4565   case ISD::XOR: {
4566     unsigned ExtOp, TruncOp;
4567     if (OVT.isVector()) {
4568       ExtOp   = ISD::BITCAST;
4569       TruncOp = ISD::BITCAST;
4570     } else {
4571       assert(OVT.isInteger() && "Cannot promote logic operation");
4572 
4573       switch (Node->getOpcode()) {
4574       default:
4575         ExtOp = ISD::ANY_EXTEND;
4576         break;
4577       case ISD::SDIV:
4578       case ISD::SREM:
4579         ExtOp = ISD::SIGN_EXTEND;
4580         break;
4581       case ISD::UDIV:
4582       case ISD::UREM:
4583         ExtOp = ISD::ZERO_EXTEND;
4584         break;
4585       }
4586       TruncOp = ISD::TRUNCATE;
4587     }
4588     // Promote each of the values to the new type.
4589     Tmp1 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(0));
4590     Tmp2 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(1));
4591     // Perform the larger operation, then convert back
4592     Tmp1 = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1, Tmp2);
4593     Results.push_back(DAG.getNode(TruncOp, dl, OVT, Tmp1));
4594     break;
4595   }
4596   case ISD::UMUL_LOHI:
4597   case ISD::SMUL_LOHI: {
4598     // Promote to a multiply in a wider integer type.
4599     unsigned ExtOp = Node->getOpcode() == ISD::UMUL_LOHI ? ISD::ZERO_EXTEND
4600                                                          : ISD::SIGN_EXTEND;
4601     Tmp1 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(0));
4602     Tmp2 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(1));
4603     Tmp1 = DAG.getNode(ISD::MUL, dl, NVT, Tmp1, Tmp2);
4604 
4605     auto &DL = DAG.getDataLayout();
4606     unsigned OriginalSize = OVT.getScalarSizeInBits();
4607     Tmp2 = DAG.getNode(
4608         ISD::SRL, dl, NVT, Tmp1,
4609         DAG.getConstant(OriginalSize, dl, TLI.getScalarShiftAmountTy(DL, NVT)));
4610     Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, OVT, Tmp1));
4611     Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, OVT, Tmp2));
4612     break;
4613   }
4614   case ISD::SELECT: {
4615     unsigned ExtOp, TruncOp;
4616     if (Node->getValueType(0).isVector() ||
4617         Node->getValueType(0).getSizeInBits() == NVT.getSizeInBits()) {
4618       ExtOp   = ISD::BITCAST;
4619       TruncOp = ISD::BITCAST;
4620     } else if (Node->getValueType(0).isInteger()) {
4621       ExtOp   = ISD::ANY_EXTEND;
4622       TruncOp = ISD::TRUNCATE;
4623     } else {
4624       ExtOp   = ISD::FP_EXTEND;
4625       TruncOp = ISD::FP_ROUND;
4626     }
4627     Tmp1 = Node->getOperand(0);
4628     // Promote each of the values to the new type.
4629     Tmp2 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(1));
4630     Tmp3 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(2));
4631     // Perform the larger operation, then round down.
4632     Tmp1 = DAG.getSelect(dl, NVT, Tmp1, Tmp2, Tmp3);
4633     Tmp1->setFlags(Node->getFlags());
4634     if (TruncOp != ISD::FP_ROUND)
4635       Tmp1 = DAG.getNode(TruncOp, dl, Node->getValueType(0), Tmp1);
4636     else
4637       Tmp1 = DAG.getNode(TruncOp, dl, Node->getValueType(0), Tmp1,
4638                          DAG.getIntPtrConstant(0, dl));
4639     Results.push_back(Tmp1);
4640     break;
4641   }
4642   case ISD::VECTOR_SHUFFLE: {
4643     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Node)->getMask();
4644 
4645     // Cast the two input vectors.
4646     Tmp1 = DAG.getNode(ISD::BITCAST, dl, NVT, Node->getOperand(0));
4647     Tmp2 = DAG.getNode(ISD::BITCAST, dl, NVT, Node->getOperand(1));
4648 
4649     // Convert the shuffle mask to the right # elements.
4650     Tmp1 = ShuffleWithNarrowerEltType(NVT, OVT, dl, Tmp1, Tmp2, Mask);
4651     Tmp1 = DAG.getNode(ISD::BITCAST, dl, OVT, Tmp1);
4652     Results.push_back(Tmp1);
4653     break;
4654   }
4655   case ISD::VECTOR_SPLICE: {
4656     Tmp1 = DAG.getNode(ISD::ANY_EXTEND, dl, NVT, Node->getOperand(0));
4657     Tmp2 = DAG.getNode(ISD::ANY_EXTEND, dl, NVT, Node->getOperand(1));
4658     Tmp3 = DAG.getNode(ISD::VECTOR_SPLICE, dl, NVT, Tmp1, Tmp2,
4659                        Node->getOperand(2));
4660     Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, OVT, Tmp3));
4661     break;
4662   }
4663   case ISD::SELECT_CC: {
4664     SDValue Cond = Node->getOperand(4);
4665     ISD::CondCode CCCode = cast<CondCodeSDNode>(Cond)->get();
4666     // Type of the comparison operands.
4667     MVT CVT = Node->getSimpleValueType(0);
4668     assert(CVT == OVT && "not handled");
4669 
4670     unsigned ExtOp = ISD::FP_EXTEND;
4671     if (NVT.isInteger()) {
4672       ExtOp = isSignedIntSetCC(CCCode) ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4673     }
4674 
4675     // Promote the comparison operands, if needed.
4676     if (TLI.isCondCodeLegal(CCCode, CVT)) {
4677       Tmp1 = Node->getOperand(0);
4678       Tmp2 = Node->getOperand(1);
4679     } else {
4680       Tmp1 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(0));
4681       Tmp2 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(1));
4682     }
4683     // Cast the true/false operands.
4684     Tmp3 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(2));
4685     Tmp4 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(3));
4686 
4687     Tmp1 = DAG.getNode(ISD::SELECT_CC, dl, NVT, {Tmp1, Tmp2, Tmp3, Tmp4, Cond},
4688                        Node->getFlags());
4689 
4690     // Cast the result back to the original type.
4691     if (ExtOp != ISD::FP_EXTEND)
4692       Tmp1 = DAG.getNode(ISD::TRUNCATE, dl, OVT, Tmp1);
4693     else
4694       Tmp1 = DAG.getNode(ISD::FP_ROUND, dl, OVT, Tmp1,
4695                          DAG.getIntPtrConstant(0, dl));
4696 
4697     Results.push_back(Tmp1);
4698     break;
4699   }
4700   case ISD::SETCC:
4701   case ISD::STRICT_FSETCC:
4702   case ISD::STRICT_FSETCCS: {
4703     unsigned ExtOp = ISD::FP_EXTEND;
4704     if (NVT.isInteger()) {
4705       ISD::CondCode CCCode = cast<CondCodeSDNode>(Node->getOperand(2))->get();
4706       ExtOp = isSignedIntSetCC(CCCode) ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4707     }
4708     if (Node->isStrictFPOpcode()) {
4709       SDValue InChain = Node->getOperand(0);
4710       std::tie(Tmp1, std::ignore) =
4711           DAG.getStrictFPExtendOrRound(Node->getOperand(1), InChain, dl, NVT);
4712       std::tie(Tmp2, std::ignore) =
4713           DAG.getStrictFPExtendOrRound(Node->getOperand(2), InChain, dl, NVT);
4714       SmallVector<SDValue, 2> TmpChains = {Tmp1.getValue(1), Tmp2.getValue(1)};
4715       SDValue OutChain = DAG.getTokenFactor(dl, TmpChains);
4716       SDVTList VTs = DAG.getVTList(Node->getValueType(0), MVT::Other);
4717       Results.push_back(DAG.getNode(Node->getOpcode(), dl, VTs,
4718                                     {OutChain, Tmp1, Tmp2, Node->getOperand(3)},
4719                                     Node->getFlags()));
4720       Results.push_back(Results.back().getValue(1));
4721       break;
4722     }
4723     Tmp1 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(0));
4724     Tmp2 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(1));
4725     Results.push_back(DAG.getNode(ISD::SETCC, dl, Node->getValueType(0), Tmp1,
4726                                   Tmp2, Node->getOperand(2), Node->getFlags()));
4727     break;
4728   }
4729   case ISD::BR_CC: {
4730     unsigned ExtOp = ISD::FP_EXTEND;
4731     if (NVT.isInteger()) {
4732       ISD::CondCode CCCode =
4733         cast<CondCodeSDNode>(Node->getOperand(1))->get();
4734       ExtOp = isSignedIntSetCC(CCCode) ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4735     }
4736     Tmp1 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(2));
4737     Tmp2 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(3));
4738     Results.push_back(DAG.getNode(ISD::BR_CC, dl, Node->getValueType(0),
4739                                   Node->getOperand(0), Node->getOperand(1),
4740                                   Tmp1, Tmp2, Node->getOperand(4)));
4741     break;
4742   }
4743   case ISD::FADD:
4744   case ISD::FSUB:
4745   case ISD::FMUL:
4746   case ISD::FDIV:
4747   case ISD::FREM:
4748   case ISD::FMINNUM:
4749   case ISD::FMAXNUM:
4750   case ISD::FPOW:
4751     Tmp1 = DAG.getNode(ISD::FP_EXTEND, dl, NVT, Node->getOperand(0));
4752     Tmp2 = DAG.getNode(ISD::FP_EXTEND, dl, NVT, Node->getOperand(1));
4753     Tmp3 = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1, Tmp2,
4754                        Node->getFlags());
4755     Results.push_back(DAG.getNode(ISD::FP_ROUND, dl, OVT,
4756                                   Tmp3, DAG.getIntPtrConstant(0, dl)));
4757     break;
4758   case ISD::STRICT_FADD:
4759   case ISD::STRICT_FSUB:
4760   case ISD::STRICT_FMUL:
4761   case ISD::STRICT_FDIV:
4762   case ISD::STRICT_FMINNUM:
4763   case ISD::STRICT_FMAXNUM:
4764   case ISD::STRICT_FREM:
4765   case ISD::STRICT_FPOW:
4766     Tmp1 = DAG.getNode(ISD::STRICT_FP_EXTEND, dl, {NVT, MVT::Other},
4767                        {Node->getOperand(0), Node->getOperand(1)});
4768     Tmp2 = DAG.getNode(ISD::STRICT_FP_EXTEND, dl, {NVT, MVT::Other},
4769                        {Node->getOperand(0), Node->getOperand(2)});
4770     Tmp3 = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Tmp1.getValue(1),
4771                        Tmp2.getValue(1));
4772     Tmp1 = DAG.getNode(Node->getOpcode(), dl, {NVT, MVT::Other},
4773                        {Tmp3, Tmp1, Tmp2});
4774     Tmp1 = DAG.getNode(ISD::STRICT_FP_ROUND, dl, {OVT, MVT::Other},
4775                        {Tmp1.getValue(1), Tmp1, DAG.getIntPtrConstant(0, dl)});
4776     Results.push_back(Tmp1);
4777     Results.push_back(Tmp1.getValue(1));
4778     break;
4779   case ISD::FMA:
4780     Tmp1 = DAG.getNode(ISD::FP_EXTEND, dl, NVT, Node->getOperand(0));
4781     Tmp2 = DAG.getNode(ISD::FP_EXTEND, dl, NVT, Node->getOperand(1));
4782     Tmp3 = DAG.getNode(ISD::FP_EXTEND, dl, NVT, Node->getOperand(2));
4783     Results.push_back(
4784         DAG.getNode(ISD::FP_ROUND, dl, OVT,
4785                     DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1, Tmp2, Tmp3),
4786                     DAG.getIntPtrConstant(0, dl)));
4787     break;
4788   case ISD::STRICT_FMA:
4789     Tmp1 = DAG.getNode(ISD::STRICT_FP_EXTEND, dl, {NVT, MVT::Other},
4790                        {Node->getOperand(0), Node->getOperand(1)});
4791     Tmp2 = DAG.getNode(ISD::STRICT_FP_EXTEND, dl, {NVT, MVT::Other},
4792                        {Node->getOperand(0), Node->getOperand(2)});
4793     Tmp3 = DAG.getNode(ISD::STRICT_FP_EXTEND, dl, {NVT, MVT::Other},
4794                        {Node->getOperand(0), Node->getOperand(3)});
4795     Tmp4 = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Tmp1.getValue(1),
4796                        Tmp2.getValue(1), Tmp3.getValue(1));
4797     Tmp4 = DAG.getNode(Node->getOpcode(), dl, {NVT, MVT::Other},
4798                        {Tmp4, Tmp1, Tmp2, Tmp3});
4799     Tmp4 = DAG.getNode(ISD::STRICT_FP_ROUND, dl, {OVT, MVT::Other},
4800                        {Tmp4.getValue(1), Tmp4, DAG.getIntPtrConstant(0, dl)});
4801     Results.push_back(Tmp4);
4802     Results.push_back(Tmp4.getValue(1));
4803     break;
4804   case ISD::FCOPYSIGN:
4805   case ISD::FPOWI: {
4806     Tmp1 = DAG.getNode(ISD::FP_EXTEND, dl, NVT, Node->getOperand(0));
4807     Tmp2 = Node->getOperand(1);
4808     Tmp3 = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1, Tmp2);
4809 
4810     // fcopysign doesn't change anything but the sign bit, so
4811     //   (fp_round (fcopysign (fpext a), b))
4812     // is as precise as
4813     //   (fp_round (fpext a))
4814     // which is a no-op. Mark it as a TRUNCating FP_ROUND.
4815     const bool isTrunc = (Node->getOpcode() == ISD::FCOPYSIGN);
4816     Results.push_back(DAG.getNode(ISD::FP_ROUND, dl, OVT,
4817                                   Tmp3, DAG.getIntPtrConstant(isTrunc, dl)));
4818     break;
4819   }
4820   case ISD::STRICT_FPOWI:
4821     Tmp1 = DAG.getNode(ISD::STRICT_FP_EXTEND, dl, {NVT, MVT::Other},
4822                        {Node->getOperand(0), Node->getOperand(1)});
4823     Tmp2 = DAG.getNode(Node->getOpcode(), dl, {NVT, MVT::Other},
4824                        {Tmp1.getValue(1), Tmp1, Node->getOperand(2)});
4825     Tmp3 = DAG.getNode(ISD::STRICT_FP_ROUND, dl, {OVT, MVT::Other},
4826                        {Tmp2.getValue(1), Tmp2, DAG.getIntPtrConstant(0, dl)});
4827     Results.push_back(Tmp3);
4828     Results.push_back(Tmp3.getValue(1));
4829     break;
4830   case ISD::FFLOOR:
4831   case ISD::FCEIL:
4832   case ISD::FRINT:
4833   case ISD::FNEARBYINT:
4834   case ISD::FROUND:
4835   case ISD::FROUNDEVEN:
4836   case ISD::FTRUNC:
4837   case ISD::FNEG:
4838   case ISD::FSQRT:
4839   case ISD::FSIN:
4840   case ISD::FCOS:
4841   case ISD::FLOG:
4842   case ISD::FLOG2:
4843   case ISD::FLOG10:
4844   case ISD::FABS:
4845   case ISD::FEXP:
4846   case ISD::FEXP2:
4847     Tmp1 = DAG.getNode(ISD::FP_EXTEND, dl, NVT, Node->getOperand(0));
4848     Tmp2 = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1);
4849     Results.push_back(DAG.getNode(ISD::FP_ROUND, dl, OVT,
4850                                   Tmp2, DAG.getIntPtrConstant(0, dl)));
4851     break;
4852   case ISD::STRICT_FFLOOR:
4853   case ISD::STRICT_FCEIL:
4854   case ISD::STRICT_FRINT:
4855   case ISD::STRICT_FNEARBYINT:
4856   case ISD::STRICT_FROUND:
4857   case ISD::STRICT_FROUNDEVEN:
4858   case ISD::STRICT_FTRUNC:
4859   case ISD::STRICT_FSQRT:
4860   case ISD::STRICT_FSIN:
4861   case ISD::STRICT_FCOS:
4862   case ISD::STRICT_FLOG:
4863   case ISD::STRICT_FLOG2:
4864   case ISD::STRICT_FLOG10:
4865   case ISD::STRICT_FEXP:
4866   case ISD::STRICT_FEXP2:
4867     Tmp1 = DAG.getNode(ISD::STRICT_FP_EXTEND, dl, {NVT, MVT::Other},
4868                        {Node->getOperand(0), Node->getOperand(1)});
4869     Tmp2 = DAG.getNode(Node->getOpcode(), dl, {NVT, MVT::Other},
4870                        {Tmp1.getValue(1), Tmp1});
4871     Tmp3 = DAG.getNode(ISD::STRICT_FP_ROUND, dl, {OVT, MVT::Other},
4872                        {Tmp2.getValue(1), Tmp2, DAG.getIntPtrConstant(0, dl)});
4873     Results.push_back(Tmp3);
4874     Results.push_back(Tmp3.getValue(1));
4875     break;
4876   case ISD::BUILD_VECTOR: {
4877     MVT EltVT = OVT.getVectorElementType();
4878     MVT NewEltVT = NVT.getVectorElementType();
4879 
4880     // Handle bitcasts to a different vector type with the same total bit size
4881     //
4882     // e.g. v2i64 = build_vector i64:x, i64:y => v4i32
4883     //  =>
4884     //  v4i32 = concat_vectors (v2i32 (bitcast i64:x)), (v2i32 (bitcast i64:y))
4885 
4886     assert(NVT.isVector() && OVT.getSizeInBits() == NVT.getSizeInBits() &&
4887            "Invalid promote type for build_vector");
4888     assert(NewEltVT.bitsLT(EltVT) && "not handled");
4889 
4890     MVT MidVT = getPromotedVectorElementType(TLI, EltVT, NewEltVT);
4891 
4892     SmallVector<SDValue, 8> NewOps;
4893     for (unsigned I = 0, E = Node->getNumOperands(); I != E; ++I) {
4894       SDValue Op = Node->getOperand(I);
4895       NewOps.push_back(DAG.getNode(ISD::BITCAST, SDLoc(Op), MidVT, Op));
4896     }
4897 
4898     SDLoc SL(Node);
4899     SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, SL, NVT, NewOps);
4900     SDValue CvtVec = DAG.getNode(ISD::BITCAST, SL, OVT, Concat);
4901     Results.push_back(CvtVec);
4902     break;
4903   }
4904   case ISD::EXTRACT_VECTOR_ELT: {
4905     MVT EltVT = OVT.getVectorElementType();
4906     MVT NewEltVT = NVT.getVectorElementType();
4907 
4908     // Handle bitcasts to a different vector type with the same total bit size.
4909     //
4910     // e.g. v2i64 = extract_vector_elt x:v2i64, y:i32
4911     //  =>
4912     //  v4i32:castx = bitcast x:v2i64
4913     //
4914     // i64 = bitcast
4915     //   (v2i32 build_vector (i32 (extract_vector_elt castx, (2 * y))),
4916     //                       (i32 (extract_vector_elt castx, (2 * y + 1)))
4917     //
4918 
4919     assert(NVT.isVector() && OVT.getSizeInBits() == NVT.getSizeInBits() &&
4920            "Invalid promote type for extract_vector_elt");
4921     assert(NewEltVT.bitsLT(EltVT) && "not handled");
4922 
4923     MVT MidVT = getPromotedVectorElementType(TLI, EltVT, NewEltVT);
4924     unsigned NewEltsPerOldElt = MidVT.getVectorNumElements();
4925 
4926     SDValue Idx = Node->getOperand(1);
4927     EVT IdxVT = Idx.getValueType();
4928     SDLoc SL(Node);
4929     SDValue Factor = DAG.getConstant(NewEltsPerOldElt, SL, IdxVT);
4930     SDValue NewBaseIdx = DAG.getNode(ISD::MUL, SL, IdxVT, Idx, Factor);
4931 
4932     SDValue CastVec = DAG.getNode(ISD::BITCAST, SL, NVT, Node->getOperand(0));
4933 
4934     SmallVector<SDValue, 8> NewOps;
4935     for (unsigned I = 0; I < NewEltsPerOldElt; ++I) {
4936       SDValue IdxOffset = DAG.getConstant(I, SL, IdxVT);
4937       SDValue TmpIdx = DAG.getNode(ISD::ADD, SL, IdxVT, NewBaseIdx, IdxOffset);
4938 
4939       SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, NewEltVT,
4940                                 CastVec, TmpIdx);
4941       NewOps.push_back(Elt);
4942     }
4943 
4944     SDValue NewVec = DAG.getBuildVector(MidVT, SL, NewOps);
4945     Results.push_back(DAG.getNode(ISD::BITCAST, SL, EltVT, NewVec));
4946     break;
4947   }
4948   case ISD::INSERT_VECTOR_ELT: {
4949     MVT EltVT = OVT.getVectorElementType();
4950     MVT NewEltVT = NVT.getVectorElementType();
4951 
4952     // Handle bitcasts to a different vector type with the same total bit size
4953     //
4954     // e.g. v2i64 = insert_vector_elt x:v2i64, y:i64, z:i32
4955     //  =>
4956     //  v4i32:castx = bitcast x:v2i64
4957     //  v2i32:casty = bitcast y:i64
4958     //
4959     // v2i64 = bitcast
4960     //   (v4i32 insert_vector_elt
4961     //       (v4i32 insert_vector_elt v4i32:castx,
4962     //                                (extract_vector_elt casty, 0), 2 * z),
4963     //        (extract_vector_elt casty, 1), (2 * z + 1))
4964 
4965     assert(NVT.isVector() && OVT.getSizeInBits() == NVT.getSizeInBits() &&
4966            "Invalid promote type for insert_vector_elt");
4967     assert(NewEltVT.bitsLT(EltVT) && "not handled");
4968 
4969     MVT MidVT = getPromotedVectorElementType(TLI, EltVT, NewEltVT);
4970     unsigned NewEltsPerOldElt = MidVT.getVectorNumElements();
4971 
4972     SDValue Val = Node->getOperand(1);
4973     SDValue Idx = Node->getOperand(2);
4974     EVT IdxVT = Idx.getValueType();
4975     SDLoc SL(Node);
4976 
4977     SDValue Factor = DAG.getConstant(NewEltsPerOldElt, SDLoc(), IdxVT);
4978     SDValue NewBaseIdx = DAG.getNode(ISD::MUL, SL, IdxVT, Idx, Factor);
4979 
4980     SDValue CastVec = DAG.getNode(ISD::BITCAST, SL, NVT, Node->getOperand(0));
4981     SDValue CastVal = DAG.getNode(ISD::BITCAST, SL, MidVT, Val);
4982 
4983     SDValue NewVec = CastVec;
4984     for (unsigned I = 0; I < NewEltsPerOldElt; ++I) {
4985       SDValue IdxOffset = DAG.getConstant(I, SL, IdxVT);
4986       SDValue InEltIdx = DAG.getNode(ISD::ADD, SL, IdxVT, NewBaseIdx, IdxOffset);
4987 
4988       SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, NewEltVT,
4989                                 CastVal, IdxOffset);
4990 
4991       NewVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, NVT,
4992                            NewVec, Elt, InEltIdx);
4993     }
4994 
4995     Results.push_back(DAG.getNode(ISD::BITCAST, SL, OVT, NewVec));
4996     break;
4997   }
4998   case ISD::SCALAR_TO_VECTOR: {
4999     MVT EltVT = OVT.getVectorElementType();
5000     MVT NewEltVT = NVT.getVectorElementType();
5001 
5002     // Handle bitcasts to different vector type with the same total bit size.
5003     //
5004     // e.g. v2i64 = scalar_to_vector x:i64
5005     //   =>
5006     //  concat_vectors (v2i32 bitcast x:i64), (v2i32 undef)
5007     //
5008 
5009     MVT MidVT = getPromotedVectorElementType(TLI, EltVT, NewEltVT);
5010     SDValue Val = Node->getOperand(0);
5011     SDLoc SL(Node);
5012 
5013     SDValue CastVal = DAG.getNode(ISD::BITCAST, SL, MidVT, Val);
5014     SDValue Undef = DAG.getUNDEF(MidVT);
5015 
5016     SmallVector<SDValue, 8> NewElts;
5017     NewElts.push_back(CastVal);
5018     for (unsigned I = 1, NElts = OVT.getVectorNumElements(); I != NElts; ++I)
5019       NewElts.push_back(Undef);
5020 
5021     SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, SL, NVT, NewElts);
5022     SDValue CvtVec = DAG.getNode(ISD::BITCAST, SL, OVT, Concat);
5023     Results.push_back(CvtVec);
5024     break;
5025   }
5026   case ISD::ATOMIC_SWAP: {
5027     AtomicSDNode *AM = cast<AtomicSDNode>(Node);
5028     SDLoc SL(Node);
5029     SDValue CastVal = DAG.getNode(ISD::BITCAST, SL, NVT, AM->getVal());
5030     assert(NVT.getSizeInBits() == OVT.getSizeInBits() &&
5031            "unexpected promotion type");
5032     assert(AM->getMemoryVT().getSizeInBits() == NVT.getSizeInBits() &&
5033            "unexpected atomic_swap with illegal type");
5034 
5035     SDValue NewAtomic
5036       = DAG.getAtomic(ISD::ATOMIC_SWAP, SL, NVT,
5037                       DAG.getVTList(NVT, MVT::Other),
5038                       { AM->getChain(), AM->getBasePtr(), CastVal },
5039                       AM->getMemOperand());
5040     Results.push_back(DAG.getNode(ISD::BITCAST, SL, OVT, NewAtomic));
5041     Results.push_back(NewAtomic.getValue(1));
5042     break;
5043   }
5044   }
5045 
5046   // Replace the original node with the legalized result.
5047   if (!Results.empty()) {
5048     LLVM_DEBUG(dbgs() << "Successfully promoted node\n");
5049     ReplaceNode(Node, Results.data());
5050   } else
5051     LLVM_DEBUG(dbgs() << "Could not promote node\n");
5052 }
5053 
5054 /// This is the entry point for the file.
5055 void SelectionDAG::Legalize() {
5056   AssignTopologicalOrder();
5057 
5058   SmallPtrSet<SDNode *, 16> LegalizedNodes;
5059   // Use a delete listener to remove nodes which were deleted during
5060   // legalization from LegalizeNodes. This is needed to handle the situation
5061   // where a new node is allocated by the object pool to the same address of a
5062   // previously deleted node.
5063   DAGNodeDeletedListener DeleteListener(
5064       *this,
5065       [&LegalizedNodes](SDNode *N, SDNode *E) { LegalizedNodes.erase(N); });
5066 
5067   SelectionDAGLegalize Legalizer(*this, LegalizedNodes);
5068 
5069   // Visit all the nodes. We start in topological order, so that we see
5070   // nodes with their original operands intact. Legalization can produce
5071   // new nodes which may themselves need to be legalized. Iterate until all
5072   // nodes have been legalized.
5073   while (true) {
5074     bool AnyLegalized = false;
5075     for (auto NI = allnodes_end(); NI != allnodes_begin();) {
5076       --NI;
5077 
5078       SDNode *N = &*NI;
5079       if (N->use_empty() && N != getRoot().getNode()) {
5080         ++NI;
5081         DeleteNode(N);
5082         continue;
5083       }
5084 
5085       if (LegalizedNodes.insert(N).second) {
5086         AnyLegalized = true;
5087         Legalizer.LegalizeOp(N);
5088 
5089         if (N->use_empty() && N != getRoot().getNode()) {
5090           ++NI;
5091           DeleteNode(N);
5092         }
5093       }
5094     }
5095     if (!AnyLegalized)
5096       break;
5097 
5098   }
5099 
5100   // Remove dead nodes now.
5101   RemoveDeadNodes();
5102 }
5103 
5104 bool SelectionDAG::LegalizeOp(SDNode *N,
5105                               SmallSetVector<SDNode *, 16> &UpdatedNodes) {
5106   SmallPtrSet<SDNode *, 16> LegalizedNodes;
5107   SelectionDAGLegalize Legalizer(*this, LegalizedNodes, &UpdatedNodes);
5108 
5109   // Directly insert the node in question, and legalize it. This will recurse
5110   // as needed through operands.
5111   LegalizedNodes.insert(N);
5112   Legalizer.LegalizeOp(N);
5113 
5114   return LegalizedNodes.count(N);
5115 }
5116