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