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