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