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