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