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