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