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