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