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