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