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