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