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