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