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