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