LegalizeDAG.cpp revision edb1e670375bd251199ce2fe2286aa446723ccb6
1//===-- LegalizeDAG.cpp - Implement SelectionDAG::Legalize ----------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the SelectionDAG::Legalize method.
11//
12//===----------------------------------------------------------------------===//
13
14#include "llvm/CodeGen/SelectionDAG.h"
15#include "llvm/CodeGen/MachineFunction.h"
16#include "llvm/CodeGen/MachineFrameInfo.h"
17#include "llvm/CodeGen/MachineJumpTableInfo.h"
18#include "llvm/CodeGen/MachineModuleInfo.h"
19#include "llvm/CodeGen/PseudoSourceValue.h"
20#include "llvm/Target/TargetFrameInfo.h"
21#include "llvm/Target/TargetLowering.h"
22#include "llvm/Target/TargetData.h"
23#include "llvm/Target/TargetMachine.h"
24#include "llvm/Target/TargetOptions.h"
25#include "llvm/Target/TargetSubtarget.h"
26#include "llvm/CallingConv.h"
27#include "llvm/Constants.h"
28#include "llvm/DerivedTypes.h"
29#include "llvm/Support/CommandLine.h"
30#include "llvm/Support/Compiler.h"
31#include "llvm/Support/MathExtras.h"
32#include "llvm/ADT/DenseMap.h"
33#include "llvm/ADT/SmallVector.h"
34#include "llvm/ADT/SmallPtrSet.h"
35#include <map>
36using namespace llvm;
37
38//===----------------------------------------------------------------------===//
39/// SelectionDAGLegalize - This takes an arbitrary SelectionDAG as input and
40/// hacks on it until the target machine can handle it.  This involves
41/// eliminating value sizes the machine cannot handle (promoting small sizes to
42/// large sizes or splitting up large values into small values) as well as
43/// eliminating operations the machine cannot handle.
44///
45/// This code also does a small amount of optimization and recognition of idioms
46/// as part of its processing.  For example, if a target does not support a
47/// 'setcc' instruction efficiently, but does support 'brcc' instruction, this
48/// will attempt merge setcc and brc instructions into brcc's.
49///
50namespace {
51class VISIBILITY_HIDDEN SelectionDAGLegalize {
52  TargetLowering &TLI;
53  SelectionDAG &DAG;
54  bool TypesNeedLegalizing;
55
56  // Libcall insertion helpers.
57
58  /// LastCALLSEQ_END - This keeps track of the CALLSEQ_END node that has been
59  /// legalized.  We use this to ensure that calls are properly serialized
60  /// against each other, including inserted libcalls.
61  SDValue LastCALLSEQ_END;
62
63  /// IsLegalizingCall - This member is used *only* for purposes of providing
64  /// helpful assertions that a libcall isn't created while another call is
65  /// being legalized (which could lead to non-serialized call sequences).
66  bool IsLegalizingCall;
67
68  enum LegalizeAction {
69    Legal,      // The target natively supports this operation.
70    Promote,    // This operation should be executed in a larger type.
71    Expand      // Try to expand this to other ops, otherwise use a libcall.
72  };
73
74  /// ValueTypeActions - This is a bitvector that contains two bits for each
75  /// value type, where the two bits correspond to the LegalizeAction enum.
76  /// This can be queried with "getTypeAction(VT)".
77  TargetLowering::ValueTypeActionImpl ValueTypeActions;
78
79  /// LegalizedNodes - For nodes that are of legal width, and that have more
80  /// than one use, this map indicates what regularized operand to use.  This
81  /// allows us to avoid legalizing the same thing more than once.
82  DenseMap<SDValue, SDValue> LegalizedNodes;
83
84  /// PromotedNodes - For nodes that are below legal width, and that have more
85  /// than one use, this map indicates what promoted value to use.  This allows
86  /// us to avoid promoting the same thing more than once.
87  DenseMap<SDValue, SDValue> PromotedNodes;
88
89  /// ExpandedNodes - For nodes that need to be expanded this map indicates
90  /// which operands are the expanded version of the input.  This allows
91  /// us to avoid expanding the same node more than once.
92  DenseMap<SDValue, std::pair<SDValue, SDValue> > ExpandedNodes;
93
94  /// SplitNodes - For vector nodes that need to be split, this map indicates
95  /// which operands are the split version of the input.  This allows us
96  /// to avoid splitting the same node more than once.
97  std::map<SDValue, std::pair<SDValue, SDValue> > SplitNodes;
98
99  /// ScalarizedNodes - For nodes that need to be converted from vector types to
100  /// scalar types, this contains the mapping of ones we have already
101  /// processed to the result.
102  std::map<SDValue, SDValue> ScalarizedNodes;
103
104  /// WidenNodes - For nodes that need to be widened from one vector type to
105  /// another, this contains the mapping of those that we have already widen.
106  /// This allows us to avoid widening more than once.
107  std::map<SDValue, SDValue> WidenNodes;
108
109  void AddLegalizedOperand(SDValue From, SDValue To) {
110    LegalizedNodes.insert(std::make_pair(From, To));
111    // If someone requests legalization of the new node, return itself.
112    if (From != To)
113      LegalizedNodes.insert(std::make_pair(To, To));
114  }
115  void AddPromotedOperand(SDValue From, SDValue To) {
116    bool isNew = PromotedNodes.insert(std::make_pair(From, To)).second;
117    assert(isNew && "Got into the map somehow?");
118    isNew = isNew;
119    // If someone requests legalization of the new node, return itself.
120    LegalizedNodes.insert(std::make_pair(To, To));
121  }
122  void AddWidenedOperand(SDValue From, SDValue To) {
123    bool isNew = WidenNodes.insert(std::make_pair(From, To)).second;
124    assert(isNew && "Got into the map somehow?");
125    isNew = isNew;
126    // If someone requests legalization of the new node, return itself.
127    LegalizedNodes.insert(std::make_pair(To, To));
128  }
129
130public:
131  explicit SelectionDAGLegalize(SelectionDAG &DAG, bool TypesNeedLegalizing);
132
133  /// getTypeAction - Return how we should legalize values of this type, either
134  /// it is already legal or we need to expand it into multiple registers of
135  /// smaller integer type, or we need to promote it to a larger type.
136  LegalizeAction getTypeAction(MVT VT) const {
137    return (LegalizeAction)ValueTypeActions.getTypeAction(VT);
138  }
139
140  /// isTypeLegal - Return true if this type is legal on this target.
141  ///
142  bool isTypeLegal(MVT VT) const {
143    return getTypeAction(VT) == Legal;
144  }
145
146  void LegalizeDAG();
147
148private:
149  /// HandleOp - Legalize, Promote, or Expand the specified operand as
150  /// appropriate for its type.
151  void HandleOp(SDValue Op);
152
153  /// LegalizeOp - We know that the specified value has a legal type.
154  /// Recursively ensure that the operands have legal types, then return the
155  /// result.
156  SDValue LegalizeOp(SDValue O);
157
158  /// UnrollVectorOp - We know that the given vector has a legal type, however
159  /// the operation it performs is not legal and is an operation that we have
160  /// no way of lowering.  "Unroll" the vector, splitting out the scalars and
161  /// operating on each element individually.
162  SDValue UnrollVectorOp(SDValue O);
163
164  /// PerformInsertVectorEltInMemory - Some target cannot handle a variable
165  /// insertion index for the INSERT_VECTOR_ELT instruction.  In this case, it
166  /// is necessary to spill the vector being inserted into to memory, perform
167  /// the insert there, and then read the result back.
168  SDValue PerformInsertVectorEltInMemory(SDValue Vec, SDValue Val,
169                                           SDValue Idx);
170
171  /// PromoteOp - Given an operation that produces a value in an invalid type,
172  /// promote it to compute the value into a larger type.  The produced value
173  /// will have the correct bits for the low portion of the register, but no
174  /// guarantee is made about the top bits: it may be zero, sign-extended, or
175  /// garbage.
176  SDValue PromoteOp(SDValue O);
177
178  /// ExpandOp - Expand the specified SDValue into its two component pieces
179  /// Lo&Hi.  Note that the Op MUST be an expanded type.  As a result of this,
180  /// the LegalizedNodes map is filled in for any results that are not expanded,
181  /// the ExpandedNodes map is filled in for any results that are expanded, and
182  /// the Lo/Hi values are returned.   This applies to integer types and Vector
183  /// types.
184  void ExpandOp(SDValue O, SDValue &Lo, SDValue &Hi);
185
186  /// WidenVectorOp - Widen a vector operation to a wider type given by WidenVT
187  /// (e.g., v3i32 to v4i32).  The produced value will have the correct value
188  /// for the existing elements but no guarantee is made about the new elements
189  /// at the end of the vector: it may be zero, ones, or garbage. This is useful
190  /// when we have an instruction operating on an illegal vector type and we
191  /// want to widen it to do the computation on a legal wider vector type.
192  SDValue WidenVectorOp(SDValue Op, MVT WidenVT);
193
194  /// SplitVectorOp - Given an operand of vector type, break it down into
195  /// two smaller values.
196  void SplitVectorOp(SDValue O, SDValue &Lo, SDValue &Hi);
197
198  /// ScalarizeVectorOp - Given an operand of single-element vector type
199  /// (e.g. v1f32), convert it into the equivalent operation that returns a
200  /// scalar (e.g. f32) value.
201  SDValue ScalarizeVectorOp(SDValue O);
202
203  /// Useful 16 element vector type that is used to pass operands for widening.
204  typedef SmallVector<SDValue, 16> SDValueVector;
205
206  /// LoadWidenVectorOp - Load a vector for a wider type. Returns true if
207  /// the LdChain contains a single load and false if it contains a token
208  /// factor for multiple loads. It takes
209  ///   Result:  location to return the result
210  ///   LdChain: location to return the load chain
211  ///   Op:      load operation to widen
212  ///   NVT:     widen vector result type we want for the load
213  bool LoadWidenVectorOp(SDValue& Result, SDValue& LdChain,
214                         SDValue Op, MVT NVT);
215
216  /// Helper genWidenVectorLoads - Helper function to generate a set of
217  /// loads to load a vector with a resulting wider type. It takes
218  ///   LdChain: list of chains for the load we have generated
219  ///   Chain:   incoming chain for the ld vector
220  ///   BasePtr: base pointer to load from
221  ///   SV:      memory disambiguation source value
222  ///   SVOffset:  memory disambiugation offset
223  ///   Alignment: alignment of the memory
224  ///   isVolatile: volatile load
225  ///   LdWidth:    width of memory that we want to load
226  ///   ResType:    the wider result result type for the resulting loaded vector
227  SDValue genWidenVectorLoads(SDValueVector& LdChain, SDValue Chain,
228                                SDValue BasePtr, const Value *SV,
229                                int SVOffset, unsigned Alignment,
230                                bool isVolatile, unsigned LdWidth,
231                                MVT ResType);
232
233  /// StoreWidenVectorOp - Stores a widen vector into non widen memory
234  /// location. It takes
235  ///     ST:      store node that we want to replace
236  ///     Chain:   incoming store chain
237  ///     BasePtr: base address of where we want to store into
238  SDValue StoreWidenVectorOp(StoreSDNode *ST, SDValue Chain,
239                               SDValue BasePtr);
240
241  /// Helper genWidenVectorStores - Helper function to generate a set of
242  /// stores to store a widen vector into non widen memory
243  // It takes
244  //   StChain: list of chains for the stores we have generated
245  //   Chain:   incoming chain for the ld vector
246  //   BasePtr: base pointer to load from
247  //   SV:      memory disambiguation source value
248  //   SVOffset:   memory disambiugation offset
249  //   Alignment:  alignment of the memory
250  //   isVolatile: volatile lod
251  //   ValOp:   value to store
252  //   StWidth: width of memory that we want to store
253  void genWidenVectorStores(SDValueVector& StChain, SDValue Chain,
254                            SDValue BasePtr, const Value *SV,
255                            int SVOffset, unsigned Alignment,
256                            bool isVolatile, SDValue ValOp,
257                            unsigned StWidth);
258
259  /// isShuffleLegal - Return non-null if a vector shuffle is legal with the
260  /// specified mask and type.  Targets can specify exactly which masks they
261  /// support and the code generator is tasked with not creating illegal masks.
262  ///
263  /// Note that this will also return true for shuffles that are promoted to a
264  /// different type.
265  ///
266  /// If this is a legal shuffle, this method returns the (possibly promoted)
267  /// build_vector Mask.  If it's not a legal shuffle, it returns null.
268  SDNode *isShuffleLegal(MVT VT, SDValue Mask) const;
269
270  bool LegalizeAllNodesNotLeadingTo(SDNode *N, SDNode *Dest,
271                                    SmallPtrSet<SDNode*, 32> &NodesLeadingTo);
272
273  void LegalizeSetCCOperands(SDValue &LHS, SDValue &RHS, SDValue &CC);
274  void LegalizeSetCCCondCode(MVT VT, SDValue &LHS, SDValue &RHS, SDValue &CC);
275  void LegalizeSetCC(MVT VT, SDValue &LHS, SDValue &RHS, SDValue &CC) {
276    LegalizeSetCCOperands(LHS, RHS, CC);
277    LegalizeSetCCCondCode(VT, LHS, RHS, CC);
278  }
279
280  SDValue ExpandLibCall(RTLIB::Libcall LC, SDNode *Node, bool isSigned,
281                          SDValue &Hi);
282  SDValue ExpandIntToFP(bool isSigned, MVT DestTy, SDValue Source);
283
284  SDValue EmitStackConvert(SDValue SrcOp, MVT SlotVT, MVT DestVT);
285  SDValue ExpandBUILD_VECTOR(SDNode *Node);
286  SDValue ExpandSCALAR_TO_VECTOR(SDNode *Node);
287  SDValue LegalizeINT_TO_FP(SDValue Result, bool isSigned, MVT DestTy, SDValue Op);
288  SDValue ExpandLegalINT_TO_FP(bool isSigned, SDValue LegalOp, MVT DestVT);
289  SDValue PromoteLegalINT_TO_FP(SDValue LegalOp, MVT DestVT, bool isSigned);
290  SDValue PromoteLegalFP_TO_INT(SDValue LegalOp, MVT DestVT, bool isSigned);
291
292  SDValue ExpandBSWAP(SDValue Op);
293  SDValue ExpandBitCount(unsigned Opc, SDValue Op);
294  bool ExpandShift(unsigned Opc, SDValue Op, SDValue Amt,
295                   SDValue &Lo, SDValue &Hi);
296  void ExpandShiftParts(unsigned NodeOp, SDValue Op, SDValue Amt,
297                        SDValue &Lo, SDValue &Hi);
298
299  SDValue ExpandEXTRACT_SUBVECTOR(SDValue Op);
300  SDValue ExpandEXTRACT_VECTOR_ELT(SDValue Op);
301
302  // Returns the legalized (truncated or extended) shift amount.
303  SDValue LegalizeShiftAmount(SDValue ShiftAmt);
304};
305}
306
307/// isVectorShuffleLegal - Return true if a vector shuffle is legal with the
308/// specified mask and type.  Targets can specify exactly which masks they
309/// support and the code generator is tasked with not creating illegal masks.
310///
311/// Note that this will also return true for shuffles that are promoted to a
312/// different type.
313SDNode *SelectionDAGLegalize::isShuffleLegal(MVT VT, SDValue Mask) const {
314  switch (TLI.getOperationAction(ISD::VECTOR_SHUFFLE, VT)) {
315  default: return 0;
316  case TargetLowering::Legal:
317  case TargetLowering::Custom:
318    break;
319  case TargetLowering::Promote: {
320    // If this is promoted to a different type, convert the shuffle mask and
321    // ask if it is legal in the promoted type!
322    MVT NVT = TLI.getTypeToPromoteTo(ISD::VECTOR_SHUFFLE, VT);
323    MVT EltVT = NVT.getVectorElementType();
324
325    // If we changed # elements, change the shuffle mask.
326    unsigned NumEltsGrowth =
327      NVT.getVectorNumElements() / VT.getVectorNumElements();
328    assert(NumEltsGrowth && "Cannot promote to vector type with fewer elts!");
329    if (NumEltsGrowth > 1) {
330      // Renumber the elements.
331      SmallVector<SDValue, 8> Ops;
332      for (unsigned i = 0, e = Mask.getNumOperands(); i != e; ++i) {
333        SDValue InOp = Mask.getOperand(i);
334        for (unsigned j = 0; j != NumEltsGrowth; ++j) {
335          if (InOp.getOpcode() == ISD::UNDEF)
336            Ops.push_back(DAG.getNode(ISD::UNDEF, EltVT));
337          else {
338            unsigned InEltNo = cast<ConstantSDNode>(InOp)->getZExtValue();
339            Ops.push_back(DAG.getConstant(InEltNo*NumEltsGrowth+j, EltVT));
340          }
341        }
342      }
343      Mask = DAG.getNode(ISD::BUILD_VECTOR, NVT, &Ops[0], Ops.size());
344    }
345    VT = NVT;
346    break;
347  }
348  }
349  return TLI.isShuffleMaskLegal(Mask, VT) ? Mask.getNode() : 0;
350}
351
352SelectionDAGLegalize::SelectionDAGLegalize(SelectionDAG &dag, bool types)
353  : TLI(dag.getTargetLoweringInfo()), DAG(dag), TypesNeedLegalizing(types),
354    ValueTypeActions(TLI.getValueTypeActions()) {
355  assert(MVT::LAST_VALUETYPE <= 32 &&
356         "Too many value types for ValueTypeActions to hold!");
357}
358
359void SelectionDAGLegalize::LegalizeDAG() {
360  LastCALLSEQ_END = DAG.getEntryNode();
361  IsLegalizingCall = false;
362
363  // The legalize process is inherently a bottom-up recursive process (users
364  // legalize their uses before themselves).  Given infinite stack space, we
365  // could just start legalizing on the root and traverse the whole graph.  In
366  // practice however, this causes us to run out of stack space on large basic
367  // blocks.  To avoid this problem, compute an ordering of the nodes where each
368  // node is only legalized after all of its operands are legalized.
369  DAG.AssignTopologicalOrder();
370  for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
371       E = prior(DAG.allnodes_end()); I != next(E); ++I)
372    HandleOp(SDValue(I, 0));
373
374  // Finally, it's possible the root changed.  Get the new root.
375  SDValue OldRoot = DAG.getRoot();
376  assert(LegalizedNodes.count(OldRoot) && "Root didn't get legalized?");
377  DAG.setRoot(LegalizedNodes[OldRoot]);
378
379  ExpandedNodes.clear();
380  LegalizedNodes.clear();
381  PromotedNodes.clear();
382  SplitNodes.clear();
383  ScalarizedNodes.clear();
384  WidenNodes.clear();
385
386  // Remove dead nodes now.
387  DAG.RemoveDeadNodes();
388}
389
390
391/// FindCallEndFromCallStart - Given a chained node that is part of a call
392/// sequence, find the CALLSEQ_END node that terminates the call sequence.
393static SDNode *FindCallEndFromCallStart(SDNode *Node) {
394  if (Node->getOpcode() == ISD::CALLSEQ_END)
395    return Node;
396  if (Node->use_empty())
397    return 0;   // No CallSeqEnd
398
399  // The chain is usually at the end.
400  SDValue TheChain(Node, Node->getNumValues()-1);
401  if (TheChain.getValueType() != MVT::Other) {
402    // Sometimes it's at the beginning.
403    TheChain = SDValue(Node, 0);
404    if (TheChain.getValueType() != MVT::Other) {
405      // Otherwise, hunt for it.
406      for (unsigned i = 1, e = Node->getNumValues(); i != e; ++i)
407        if (Node->getValueType(i) == MVT::Other) {
408          TheChain = SDValue(Node, i);
409          break;
410        }
411
412      // Otherwise, we walked into a node without a chain.
413      if (TheChain.getValueType() != MVT::Other)
414        return 0;
415    }
416  }
417
418  for (SDNode::use_iterator UI = Node->use_begin(),
419       E = Node->use_end(); UI != E; ++UI) {
420
421    // Make sure to only follow users of our token chain.
422    SDNode *User = *UI;
423    for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i)
424      if (User->getOperand(i) == TheChain)
425        if (SDNode *Result = FindCallEndFromCallStart(User))
426          return Result;
427  }
428  return 0;
429}
430
431/// FindCallStartFromCallEnd - Given a chained node that is part of a call
432/// sequence, find the CALLSEQ_START node that initiates the call sequence.
433static SDNode *FindCallStartFromCallEnd(SDNode *Node) {
434  assert(Node && "Didn't find callseq_start for a call??");
435  if (Node->getOpcode() == ISD::CALLSEQ_START) return Node;
436
437  assert(Node->getOperand(0).getValueType() == MVT::Other &&
438         "Node doesn't have a token chain argument!");
439  return FindCallStartFromCallEnd(Node->getOperand(0).getNode());
440}
441
442/// LegalizeAllNodesNotLeadingTo - Recursively walk the uses of N, looking to
443/// see if any uses can reach Dest.  If no dest operands can get to dest,
444/// legalize them, legalize ourself, and return false, otherwise, return true.
445///
446/// Keep track of the nodes we fine that actually do lead to Dest in
447/// NodesLeadingTo.  This avoids retraversing them exponential number of times.
448///
449bool SelectionDAGLegalize::LegalizeAllNodesNotLeadingTo(SDNode *N, SDNode *Dest,
450                                     SmallPtrSet<SDNode*, 32> &NodesLeadingTo) {
451  if (N == Dest) return true;  // N certainly leads to Dest :)
452
453  // If we've already processed this node and it does lead to Dest, there is no
454  // need to reprocess it.
455  if (NodesLeadingTo.count(N)) return true;
456
457  // If the first result of this node has been already legalized, then it cannot
458  // reach N.
459  switch (getTypeAction(N->getValueType(0))) {
460  case Legal:
461    if (LegalizedNodes.count(SDValue(N, 0))) return false;
462    break;
463  case Promote:
464    if (PromotedNodes.count(SDValue(N, 0))) return false;
465    break;
466  case Expand:
467    if (ExpandedNodes.count(SDValue(N, 0))) return false;
468    break;
469  }
470
471  // Okay, this node has not already been legalized.  Check and legalize all
472  // operands.  If none lead to Dest, then we can legalize this node.
473  bool OperandsLeadToDest = false;
474  for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
475    OperandsLeadToDest |=     // If an operand leads to Dest, so do we.
476      LegalizeAllNodesNotLeadingTo(N->getOperand(i).getNode(), Dest, NodesLeadingTo);
477
478  if (OperandsLeadToDest) {
479    NodesLeadingTo.insert(N);
480    return true;
481  }
482
483  // Okay, this node looks safe, legalize it and return false.
484  HandleOp(SDValue(N, 0));
485  return false;
486}
487
488/// HandleOp - Legalize, Promote, Widen, or Expand the specified operand as
489/// appropriate for its type.
490void SelectionDAGLegalize::HandleOp(SDValue Op) {
491  MVT VT = Op.getValueType();
492  assert((TypesNeedLegalizing || getTypeAction(VT) == Legal) &&
493         "Illegal type introduced after type legalization?");
494  switch (getTypeAction(VT)) {
495  default: assert(0 && "Bad type action!");
496  case Legal:   (void)LegalizeOp(Op); break;
497  case Promote:
498    if (!VT.isVector()) {
499      (void)PromoteOp(Op);
500      break;
501    }
502    else  {
503      // See if we can widen otherwise use Expand to either scalarize or split
504      MVT WidenVT = TLI.getWidenVectorType(VT);
505      if (WidenVT != MVT::Other) {
506        (void) WidenVectorOp(Op, WidenVT);
507        break;
508      }
509      // else fall thru to expand since we can't widen the vector
510    }
511  case Expand:
512    if (!VT.isVector()) {
513      // If this is an illegal scalar, expand it into its two component
514      // pieces.
515      SDValue X, Y;
516      if (Op.getOpcode() == ISD::TargetConstant)
517        break;  // Allow illegal target nodes.
518      ExpandOp(Op, X, Y);
519    } else if (VT.getVectorNumElements() == 1) {
520      // If this is an illegal single element vector, convert it to a
521      // scalar operation.
522      (void)ScalarizeVectorOp(Op);
523    } else {
524      // This is an illegal multiple element vector.
525      // Split it in half and legalize both parts.
526      SDValue X, Y;
527      SplitVectorOp(Op, X, Y);
528    }
529    break;
530  }
531}
532
533/// ExpandConstantFP - Expands the ConstantFP node to an integer constant or
534/// a load from the constant pool.
535static SDValue ExpandConstantFP(ConstantFPSDNode *CFP, bool UseCP,
536                                  SelectionDAG &DAG, TargetLowering &TLI) {
537  bool Extend = false;
538
539  // If a FP immediate is precise when represented as a float and if the
540  // target can do an extending load from float to double, we put it into
541  // the constant pool as a float, even if it's is statically typed as a
542  // double.  This shrinks FP constants and canonicalizes them for targets where
543  // an FP extending load is the same cost as a normal load (such as on the x87
544  // fp stack or PPC FP unit).
545  MVT VT = CFP->getValueType(0);
546  ConstantFP *LLVMC = const_cast<ConstantFP*>(CFP->getConstantFPValue());
547  if (!UseCP) {
548    if (VT!=MVT::f64 && VT!=MVT::f32)
549      assert(0 && "Invalid type expansion");
550    return DAG.getConstant(LLVMC->getValueAPF().bitcastToAPInt(),
551                           (VT == MVT::f64) ? MVT::i64 : MVT::i32);
552  }
553
554  MVT OrigVT = VT;
555  MVT SVT = VT;
556  while (SVT != MVT::f32) {
557    SVT = (MVT::SimpleValueType)(SVT.getSimpleVT() - 1);
558    if (CFP->isValueValidForType(SVT, CFP->getValueAPF()) &&
559        // Only do this if the target has a native EXTLOAD instruction from
560        // smaller type.
561        TLI.isLoadExtLegal(ISD::EXTLOAD, SVT) &&
562        TLI.ShouldShrinkFPConstant(OrigVT)) {
563      const Type *SType = SVT.getTypeForMVT();
564      LLVMC = cast<ConstantFP>(ConstantExpr::getFPTrunc(LLVMC, SType));
565      VT = SVT;
566      Extend = true;
567    }
568  }
569
570  SDValue CPIdx = DAG.getConstantPool(LLVMC, TLI.getPointerTy());
571  unsigned Alignment = 1 << cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
572  if (Extend)
573    return DAG.getExtLoad(ISD::EXTLOAD, OrigVT, DAG.getEntryNode(),
574                          CPIdx, PseudoSourceValue::getConstantPool(),
575                          0, VT, false, Alignment);
576  return DAG.getLoad(OrigVT, DAG.getEntryNode(), CPIdx,
577                     PseudoSourceValue::getConstantPool(), 0, false, Alignment);
578}
579
580
581/// ExpandFCOPYSIGNToBitwiseOps - Expands fcopysign to a series of bitwise
582/// operations.
583static
584SDValue ExpandFCOPYSIGNToBitwiseOps(SDNode *Node, MVT NVT,
585                                    SelectionDAG &DAG, TargetLowering &TLI) {
586  MVT VT = Node->getValueType(0);
587  MVT SrcVT = Node->getOperand(1).getValueType();
588  assert((SrcVT == MVT::f32 || SrcVT == MVT::f64) &&
589         "fcopysign expansion only supported for f32 and f64");
590  MVT SrcNVT = (SrcVT == MVT::f64) ? MVT::i64 : MVT::i32;
591
592  // First get the sign bit of second operand.
593  SDValue Mask1 = (SrcVT == MVT::f64)
594    ? DAG.getConstantFP(BitsToDouble(1ULL << 63), SrcVT)
595    : DAG.getConstantFP(BitsToFloat(1U << 31), SrcVT);
596  Mask1 = DAG.getNode(ISD::BIT_CONVERT, SrcNVT, Mask1);
597  SDValue SignBit= DAG.getNode(ISD::BIT_CONVERT, SrcNVT, Node->getOperand(1));
598  SignBit = DAG.getNode(ISD::AND, SrcNVT, SignBit, Mask1);
599  // Shift right or sign-extend it if the two operands have different types.
600  int SizeDiff = SrcNVT.getSizeInBits() - NVT.getSizeInBits();
601  if (SizeDiff > 0) {
602    SignBit = DAG.getNode(ISD::SRL, SrcNVT, SignBit,
603                          DAG.getConstant(SizeDiff, TLI.getShiftAmountTy()));
604    SignBit = DAG.getNode(ISD::TRUNCATE, NVT, SignBit);
605  } else if (SizeDiff < 0) {
606    SignBit = DAG.getNode(ISD::ZERO_EXTEND, NVT, SignBit);
607    SignBit = DAG.getNode(ISD::SHL, NVT, SignBit,
608                          DAG.getConstant(-SizeDiff, TLI.getShiftAmountTy()));
609  }
610
611  // Clear the sign bit of first operand.
612  SDValue Mask2 = (VT == MVT::f64)
613    ? DAG.getConstantFP(BitsToDouble(~(1ULL << 63)), VT)
614    : DAG.getConstantFP(BitsToFloat(~(1U << 31)), VT);
615  Mask2 = DAG.getNode(ISD::BIT_CONVERT, NVT, Mask2);
616  SDValue Result = DAG.getNode(ISD::BIT_CONVERT, NVT, Node->getOperand(0));
617  Result = DAG.getNode(ISD::AND, NVT, Result, Mask2);
618
619  // Or the value with the sign bit.
620  Result = DAG.getNode(ISD::OR, NVT, Result, SignBit);
621  return Result;
622}
623
624/// ExpandUnalignedStore - Expands an unaligned store to 2 half-size stores.
625static
626SDValue ExpandUnalignedStore(StoreSDNode *ST, SelectionDAG &DAG,
627                             TargetLowering &TLI) {
628  SDValue Chain = ST->getChain();
629  SDValue Ptr = ST->getBasePtr();
630  SDValue Val = ST->getValue();
631  MVT VT = Val.getValueType();
632  int Alignment = ST->getAlignment();
633  int SVOffset = ST->getSrcValueOffset();
634  if (ST->getMemoryVT().isFloatingPoint() ||
635      ST->getMemoryVT().isVector()) {
636    MVT intVT = MVT::getIntegerVT(VT.getSizeInBits());
637    if (TLI.isTypeLegal(intVT)) {
638      // Expand to a bitconvert of the value to the integer type of the
639      // same size, then a (misaligned) int store.
640      // FIXME: Does not handle truncating floating point stores!
641      SDValue Result = DAG.getNode(ISD::BIT_CONVERT, intVT, Val);
642      return DAG.getStore(Chain, Result, Ptr, ST->getSrcValue(),
643                          SVOffset, ST->isVolatile(), Alignment);
644    } else {
645      // Do a (aligned) store to a stack slot, then copy from the stack slot
646      // to the final destination using (unaligned) integer loads and stores.
647      MVT StoredVT = ST->getMemoryVT();
648      MVT RegVT =
649        TLI.getRegisterType(MVT::getIntegerVT(StoredVT.getSizeInBits()));
650      unsigned StoredBytes = StoredVT.getSizeInBits() / 8;
651      unsigned RegBytes = RegVT.getSizeInBits() / 8;
652      unsigned NumRegs = (StoredBytes + RegBytes - 1) / RegBytes;
653
654      // Make sure the stack slot is also aligned for the register type.
655      SDValue StackPtr = DAG.CreateStackTemporary(StoredVT, RegVT);
656
657      // Perform the original store, only redirected to the stack slot.
658      SDValue Store = DAG.getTruncStore(Chain, Val, StackPtr, NULL, 0,StoredVT);
659      SDValue Increment = DAG.getConstant(RegBytes, TLI.getPointerTy());
660      SmallVector<SDValue, 8> Stores;
661      unsigned Offset = 0;
662
663      // Do all but one copies using the full register width.
664      for (unsigned i = 1; i < NumRegs; i++) {
665        // Load one integer register's worth from the stack slot.
666        SDValue Load = DAG.getLoad(RegVT, Store, StackPtr, NULL, 0);
667        // Store it to the final location.  Remember the store.
668        Stores.push_back(DAG.getStore(Load.getValue(1), Load, Ptr,
669                                      ST->getSrcValue(), SVOffset + Offset,
670                                      ST->isVolatile(),
671                                      MinAlign(ST->getAlignment(), Offset)));
672        // Increment the pointers.
673        Offset += RegBytes;
674        StackPtr = DAG.getNode(ISD::ADD, StackPtr.getValueType(), StackPtr,
675                               Increment);
676        Ptr = DAG.getNode(ISD::ADD, Ptr.getValueType(), Ptr, Increment);
677      }
678
679      // The last store may be partial.  Do a truncating store.  On big-endian
680      // machines this requires an extending load from the stack slot to ensure
681      // that the bits are in the right place.
682      MVT MemVT = MVT::getIntegerVT(8 * (StoredBytes - Offset));
683
684      // Load from the stack slot.
685      SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, RegVT, Store, StackPtr,
686                                    NULL, 0, MemVT);
687
688      Stores.push_back(DAG.getTruncStore(Load.getValue(1), Load, Ptr,
689                                         ST->getSrcValue(), SVOffset + Offset,
690                                         MemVT, ST->isVolatile(),
691                                         MinAlign(ST->getAlignment(), Offset)));
692      // The order of the stores doesn't matter - say it with a TokenFactor.
693      return DAG.getNode(ISD::TokenFactor, MVT::Other, &Stores[0],
694                         Stores.size());
695    }
696  }
697  assert(ST->getMemoryVT().isInteger() &&
698         !ST->getMemoryVT().isVector() &&
699         "Unaligned store of unknown type.");
700  // Get the half-size VT
701  MVT NewStoredVT =
702    (MVT::SimpleValueType)(ST->getMemoryVT().getSimpleVT() - 1);
703  int NumBits = NewStoredVT.getSizeInBits();
704  int IncrementSize = NumBits / 8;
705
706  // Divide the stored value in two parts.
707  SDValue ShiftAmount = DAG.getConstant(NumBits, TLI.getShiftAmountTy());
708  SDValue Lo = Val;
709  SDValue Hi = DAG.getNode(ISD::SRL, VT, Val, ShiftAmount);
710
711  // Store the two parts
712  SDValue Store1, Store2;
713  Store1 = DAG.getTruncStore(Chain, TLI.isLittleEndian()?Lo:Hi, Ptr,
714                             ST->getSrcValue(), SVOffset, NewStoredVT,
715                             ST->isVolatile(), Alignment);
716  Ptr = DAG.getNode(ISD::ADD, Ptr.getValueType(), Ptr,
717                    DAG.getConstant(IncrementSize, TLI.getPointerTy()));
718  Alignment = MinAlign(Alignment, IncrementSize);
719  Store2 = DAG.getTruncStore(Chain, TLI.isLittleEndian()?Hi:Lo, Ptr,
720                             ST->getSrcValue(), SVOffset + IncrementSize,
721                             NewStoredVT, ST->isVolatile(), Alignment);
722
723  return DAG.getNode(ISD::TokenFactor, MVT::Other, Store1, Store2);
724}
725
726/// ExpandUnalignedLoad - Expands an unaligned load to 2 half-size loads.
727static
728SDValue ExpandUnalignedLoad(LoadSDNode *LD, SelectionDAG &DAG,
729                            TargetLowering &TLI) {
730  int SVOffset = LD->getSrcValueOffset();
731  SDValue Chain = LD->getChain();
732  SDValue Ptr = LD->getBasePtr();
733  MVT VT = LD->getValueType(0);
734  MVT LoadedVT = LD->getMemoryVT();
735  if (VT.isFloatingPoint() || VT.isVector()) {
736    MVT intVT = MVT::getIntegerVT(LoadedVT.getSizeInBits());
737    if (TLI.isTypeLegal(intVT)) {
738      // Expand to a (misaligned) integer load of the same size,
739      // then bitconvert to floating point or vector.
740      SDValue newLoad = DAG.getLoad(intVT, Chain, Ptr, LD->getSrcValue(),
741                                    SVOffset, LD->isVolatile(),
742                                    LD->getAlignment());
743      SDValue Result = DAG.getNode(ISD::BIT_CONVERT, LoadedVT, newLoad);
744      if (VT.isFloatingPoint() && LoadedVT != VT)
745        Result = DAG.getNode(ISD::FP_EXTEND, VT, Result);
746
747      SDValue Ops[] = { Result, Chain };
748      return DAG.getMergeValues(Ops, 2);
749    } else {
750      // Copy the value to a (aligned) stack slot using (unaligned) integer
751      // loads and stores, then do a (aligned) load from the stack slot.
752      MVT RegVT = TLI.getRegisterType(intVT);
753      unsigned LoadedBytes = LoadedVT.getSizeInBits() / 8;
754      unsigned RegBytes = RegVT.getSizeInBits() / 8;
755      unsigned NumRegs = (LoadedBytes + RegBytes - 1) / RegBytes;
756
757      // Make sure the stack slot is also aligned for the register type.
758      SDValue StackBase = DAG.CreateStackTemporary(LoadedVT, RegVT);
759
760      SDValue Increment = DAG.getConstant(RegBytes, TLI.getPointerTy());
761      SmallVector<SDValue, 8> Stores;
762      SDValue StackPtr = StackBase;
763      unsigned Offset = 0;
764
765      // Do all but one copies using the full register width.
766      for (unsigned i = 1; i < NumRegs; i++) {
767        // Load one integer register's worth from the original location.
768        SDValue Load = DAG.getLoad(RegVT, Chain, Ptr, LD->getSrcValue(),
769                                   SVOffset + Offset, LD->isVolatile(),
770                                   MinAlign(LD->getAlignment(), Offset));
771        // Follow the load with a store to the stack slot.  Remember the store.
772        Stores.push_back(DAG.getStore(Load.getValue(1), Load, StackPtr,
773                                      NULL, 0));
774        // Increment the pointers.
775        Offset += RegBytes;
776        Ptr = DAG.getNode(ISD::ADD, Ptr.getValueType(), Ptr, Increment);
777        StackPtr = DAG.getNode(ISD::ADD, StackPtr.getValueType(), StackPtr,
778                               Increment);
779      }
780
781      // The last copy may be partial.  Do an extending load.
782      MVT MemVT = MVT::getIntegerVT(8 * (LoadedBytes - Offset));
783      SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, RegVT, Chain, Ptr,
784                                    LD->getSrcValue(), SVOffset + Offset,
785                                    MemVT, LD->isVolatile(),
786                                    MinAlign(LD->getAlignment(), Offset));
787      // Follow the load with a store to the stack slot.  Remember the store.
788      // On big-endian machines this requires a truncating store to ensure
789      // that the bits end up in the right place.
790      Stores.push_back(DAG.getTruncStore(Load.getValue(1), Load, StackPtr,
791                                         NULL, 0, MemVT));
792
793      // The order of the stores doesn't matter - say it with a TokenFactor.
794      SDValue TF = DAG.getNode(ISD::TokenFactor, MVT::Other, &Stores[0],
795                               Stores.size());
796
797      // Finally, perform the original load only redirected to the stack slot.
798      Load = DAG.getExtLoad(LD->getExtensionType(), VT, TF, StackBase,
799                            NULL, 0, LoadedVT);
800
801      // Callers expect a MERGE_VALUES node.
802      SDValue Ops[] = { Load, TF };
803      return DAG.getMergeValues(Ops, 2);
804    }
805  }
806  assert(LoadedVT.isInteger() && !LoadedVT.isVector() &&
807         "Unaligned load of unsupported type.");
808
809  // Compute the new VT that is half the size of the old one.  This is an
810  // integer MVT.
811  unsigned NumBits = LoadedVT.getSizeInBits();
812  MVT NewLoadedVT;
813  NewLoadedVT = MVT::getIntegerVT(NumBits/2);
814  NumBits >>= 1;
815
816  unsigned Alignment = LD->getAlignment();
817  unsigned IncrementSize = NumBits / 8;
818  ISD::LoadExtType HiExtType = LD->getExtensionType();
819
820  // If the original load is NON_EXTLOAD, the hi part load must be ZEXTLOAD.
821  if (HiExtType == ISD::NON_EXTLOAD)
822    HiExtType = ISD::ZEXTLOAD;
823
824  // Load the value in two parts
825  SDValue Lo, Hi;
826  if (TLI.isLittleEndian()) {
827    Lo = DAG.getExtLoad(ISD::ZEXTLOAD, VT, Chain, Ptr, LD->getSrcValue(),
828                        SVOffset, NewLoadedVT, LD->isVolatile(), Alignment);
829    Ptr = DAG.getNode(ISD::ADD, Ptr.getValueType(), Ptr,
830                      DAG.getConstant(IncrementSize, TLI.getPointerTy()));
831    Hi = DAG.getExtLoad(HiExtType, VT, Chain, Ptr, LD->getSrcValue(),
832                        SVOffset + IncrementSize, NewLoadedVT, LD->isVolatile(),
833                        MinAlign(Alignment, IncrementSize));
834  } else {
835    Hi = DAG.getExtLoad(HiExtType, VT, Chain, Ptr, LD->getSrcValue(), SVOffset,
836                        NewLoadedVT,LD->isVolatile(), Alignment);
837    Ptr = DAG.getNode(ISD::ADD, Ptr.getValueType(), Ptr,
838                      DAG.getConstant(IncrementSize, TLI.getPointerTy()));
839    Lo = DAG.getExtLoad(ISD::ZEXTLOAD, VT, Chain, Ptr, LD->getSrcValue(),
840                        SVOffset + IncrementSize, NewLoadedVT, LD->isVolatile(),
841                        MinAlign(Alignment, IncrementSize));
842  }
843
844  // aggregate the two parts
845  SDValue ShiftAmount = DAG.getConstant(NumBits, TLI.getShiftAmountTy());
846  SDValue Result = DAG.getNode(ISD::SHL, VT, Hi, ShiftAmount);
847  Result = DAG.getNode(ISD::OR, VT, Result, Lo);
848
849  SDValue TF = DAG.getNode(ISD::TokenFactor, MVT::Other, Lo.getValue(1),
850                             Hi.getValue(1));
851
852  SDValue Ops[] = { Result, TF };
853  return DAG.getMergeValues(Ops, 2);
854}
855
856/// UnrollVectorOp - We know that the given vector has a legal type, however
857/// the operation it performs is not legal and is an operation that we have
858/// no way of lowering.  "Unroll" the vector, splitting out the scalars and
859/// operating on each element individually.
860SDValue SelectionDAGLegalize::UnrollVectorOp(SDValue Op) {
861  MVT VT = Op.getValueType();
862  assert(isTypeLegal(VT) &&
863         "Caller should expand or promote operands that are not legal!");
864  assert(Op.getNode()->getNumValues() == 1 &&
865         "Can't unroll a vector with multiple results!");
866  unsigned NE = VT.getVectorNumElements();
867  MVT EltVT = VT.getVectorElementType();
868
869  SmallVector<SDValue, 8> Scalars;
870  SmallVector<SDValue, 4> Operands(Op.getNumOperands());
871  for (unsigned i = 0; i != NE; ++i) {
872    for (unsigned j = 0; j != Op.getNumOperands(); ++j) {
873      SDValue Operand = Op.getOperand(j);
874      MVT OperandVT = Operand.getValueType();
875      if (OperandVT.isVector()) {
876        // A vector operand; extract a single element.
877        MVT OperandEltVT = OperandVT.getVectorElementType();
878        Operands[j] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
879                                  OperandEltVT,
880                                  Operand,
881                                  DAG.getConstant(i, MVT::i32));
882      } else {
883        // A scalar operand; just use it as is.
884        Operands[j] = Operand;
885      }
886    }
887
888    switch (Op.getOpcode()) {
889    default:
890      Scalars.push_back(DAG.getNode(Op.getOpcode(), EltVT,
891                                    &Operands[0], Operands.size()));
892      break;
893    case ISD::SHL:
894    case ISD::SRA:
895    case ISD::SRL:
896      Scalars.push_back(DAG.getNode(Op.getOpcode(), EltVT, Operands[0],
897                                    LegalizeShiftAmount(Operands[1])));
898      break;
899    }
900  }
901
902  return DAG.getNode(ISD::BUILD_VECTOR, VT, &Scalars[0], Scalars.size());
903}
904
905/// GetFPLibCall - Return the right libcall for the given floating point type.
906static RTLIB::Libcall GetFPLibCall(MVT VT,
907                                   RTLIB::Libcall Call_F32,
908                                   RTLIB::Libcall Call_F64,
909                                   RTLIB::Libcall Call_F80,
910                                   RTLIB::Libcall Call_PPCF128) {
911  return
912    VT == MVT::f32 ? Call_F32 :
913    VT == MVT::f64 ? Call_F64 :
914    VT == MVT::f80 ? Call_F80 :
915    VT == MVT::ppcf128 ? Call_PPCF128 :
916    RTLIB::UNKNOWN_LIBCALL;
917}
918
919/// PerformInsertVectorEltInMemory - Some target cannot handle a variable
920/// insertion index for the INSERT_VECTOR_ELT instruction.  In this case, it
921/// is necessary to spill the vector being inserted into to memory, perform
922/// the insert there, and then read the result back.
923SDValue SelectionDAGLegalize::
924PerformInsertVectorEltInMemory(SDValue Vec, SDValue Val, SDValue Idx) {
925  SDValue Tmp1 = Vec;
926  SDValue Tmp2 = Val;
927  SDValue Tmp3 = Idx;
928
929  // If the target doesn't support this, we have to spill the input vector
930  // to a temporary stack slot, update the element, then reload it.  This is
931  // badness.  We could also load the value into a vector register (either
932  // with a "move to register" or "extload into register" instruction, then
933  // permute it into place, if the idx is a constant and if the idx is
934  // supported by the target.
935  MVT VT    = Tmp1.getValueType();
936  MVT EltVT = VT.getVectorElementType();
937  MVT IdxVT = Tmp3.getValueType();
938  MVT PtrVT = TLI.getPointerTy();
939  SDValue StackPtr = DAG.CreateStackTemporary(VT);
940
941  int SPFI = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
942
943  // Store the vector.
944  SDValue Ch = DAG.getStore(DAG.getEntryNode(), Tmp1, StackPtr,
945                            PseudoSourceValue::getFixedStack(SPFI), 0);
946
947  // Truncate or zero extend offset to target pointer type.
948  unsigned CastOpc = IdxVT.bitsGT(PtrVT) ? ISD::TRUNCATE : ISD::ZERO_EXTEND;
949  Tmp3 = DAG.getNode(CastOpc, PtrVT, Tmp3);
950  // Add the offset to the index.
951  unsigned EltSize = EltVT.getSizeInBits()/8;
952  Tmp3 = DAG.getNode(ISD::MUL, IdxVT, Tmp3,DAG.getConstant(EltSize, IdxVT));
953  SDValue StackPtr2 = DAG.getNode(ISD::ADD, IdxVT, Tmp3, StackPtr);
954  // Store the scalar value.
955  Ch = DAG.getTruncStore(Ch, Tmp2, StackPtr2,
956                         PseudoSourceValue::getFixedStack(SPFI), 0, EltVT);
957  // Load the updated vector.
958  return DAG.getLoad(VT, Ch, StackPtr,
959                     PseudoSourceValue::getFixedStack(SPFI), 0);
960}
961
962SDValue SelectionDAGLegalize::LegalizeShiftAmount(SDValue ShiftAmt) {
963  if (TLI.getShiftAmountTy().bitsLT(ShiftAmt.getValueType()))
964    return DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), ShiftAmt);
965
966  if (TLI.getShiftAmountTy().bitsGT(ShiftAmt.getValueType()))
967    return DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), ShiftAmt);
968
969  return ShiftAmt;
970}
971
972
973/// LegalizeOp - We know that the specified value has a legal type, and
974/// that its operands are legal.  Now ensure that the operation itself
975/// is legal, recursively ensuring that the operands' operations remain
976/// legal.
977SDValue SelectionDAGLegalize::LegalizeOp(SDValue Op) {
978  if (Op.getOpcode() == ISD::TargetConstant) // Allow illegal target nodes.
979    return Op;
980
981  assert(isTypeLegal(Op.getValueType()) &&
982         "Caller should expand or promote operands that are not legal!");
983  SDNode *Node = Op.getNode();
984
985  // If this operation defines any values that cannot be represented in a
986  // register on this target, make sure to expand or promote them.
987  if (Node->getNumValues() > 1) {
988    for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
989      if (getTypeAction(Node->getValueType(i)) != Legal) {
990        HandleOp(Op.getValue(i));
991        assert(LegalizedNodes.count(Op) &&
992               "Handling didn't add legal operands!");
993        return LegalizedNodes[Op];
994      }
995  }
996
997  // Note that LegalizeOp may be reentered even from single-use nodes, which
998  // means that we always must cache transformed nodes.
999  DenseMap<SDValue, SDValue>::iterator I = LegalizedNodes.find(Op);
1000  if (I != LegalizedNodes.end()) return I->second;
1001
1002  SDValue Tmp1, Tmp2, Tmp3, Tmp4;
1003  SDValue Result = Op;
1004  bool isCustom = false;
1005
1006  switch (Node->getOpcode()) {
1007  case ISD::FrameIndex:
1008  case ISD::EntryToken:
1009  case ISD::Register:
1010  case ISD::BasicBlock:
1011  case ISD::TargetFrameIndex:
1012  case ISD::TargetJumpTable:
1013  case ISD::TargetConstant:
1014  case ISD::TargetConstantFP:
1015  case ISD::TargetConstantPool:
1016  case ISD::TargetGlobalAddress:
1017  case ISD::TargetGlobalTLSAddress:
1018  case ISD::TargetExternalSymbol:
1019  case ISD::VALUETYPE:
1020  case ISD::SRCVALUE:
1021  case ISD::MEMOPERAND:
1022  case ISD::CONDCODE:
1023  case ISD::ARG_FLAGS:
1024    // Primitives must all be legal.
1025    assert(TLI.isOperationLegal(Node->getOpcode(), Node->getValueType(0)) &&
1026           "This must be legal!");
1027    break;
1028  default:
1029    if (Node->getOpcode() >= ISD::BUILTIN_OP_END) {
1030      // If this is a target node, legalize it by legalizing the operands then
1031      // passing it through.
1032      SmallVector<SDValue, 8> Ops;
1033      for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i)
1034        Ops.push_back(LegalizeOp(Node->getOperand(i)));
1035
1036      Result = DAG.UpdateNodeOperands(Result.getValue(0), &Ops[0], Ops.size());
1037
1038      for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
1039        AddLegalizedOperand(Op.getValue(i), Result.getValue(i));
1040      return Result.getValue(Op.getResNo());
1041    }
1042    // Otherwise this is an unhandled builtin node.  splat.
1043#ifndef NDEBUG
1044    cerr << "NODE: "; Node->dump(&DAG); cerr << "\n";
1045#endif
1046    assert(0 && "Do not know how to legalize this operator!");
1047    abort();
1048  case ISD::GLOBAL_OFFSET_TABLE:
1049  case ISD::GlobalAddress:
1050  case ISD::GlobalTLSAddress:
1051  case ISD::ExternalSymbol:
1052  case ISD::ConstantPool:
1053  case ISD::JumpTable: // Nothing to do.
1054    switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
1055    default: assert(0 && "This action is not supported yet!");
1056    case TargetLowering::Custom:
1057      Tmp1 = TLI.LowerOperation(Op, DAG);
1058      if (Tmp1.getNode()) Result = Tmp1;
1059      // FALLTHROUGH if the target doesn't want to lower this op after all.
1060    case TargetLowering::Legal:
1061      break;
1062    }
1063    break;
1064  case ISD::FRAMEADDR:
1065  case ISD::RETURNADDR:
1066    // The only option for these nodes is to custom lower them.  If the target
1067    // does not custom lower them, then return zero.
1068    Tmp1 = TLI.LowerOperation(Op, DAG);
1069    if (Tmp1.getNode())
1070      Result = Tmp1;
1071    else
1072      Result = DAG.getConstant(0, TLI.getPointerTy());
1073    break;
1074  case ISD::FRAME_TO_ARGS_OFFSET: {
1075    MVT VT = Node->getValueType(0);
1076    switch (TLI.getOperationAction(Node->getOpcode(), VT)) {
1077    default: assert(0 && "This action is not supported yet!");
1078    case TargetLowering::Custom:
1079      Result = TLI.LowerOperation(Op, DAG);
1080      if (Result.getNode()) break;
1081      // Fall Thru
1082    case TargetLowering::Legal:
1083      Result = DAG.getConstant(0, VT);
1084      break;
1085    }
1086    }
1087    break;
1088  case ISD::EXCEPTIONADDR: {
1089    Tmp1 = LegalizeOp(Node->getOperand(0));
1090    MVT VT = Node->getValueType(0);
1091    switch (TLI.getOperationAction(Node->getOpcode(), VT)) {
1092    default: assert(0 && "This action is not supported yet!");
1093    case TargetLowering::Expand: {
1094        unsigned Reg = TLI.getExceptionAddressRegister();
1095        Result = DAG.getCopyFromReg(Tmp1, Reg, VT);
1096      }
1097      break;
1098    case TargetLowering::Custom:
1099      Result = TLI.LowerOperation(Op, DAG);
1100      if (Result.getNode()) break;
1101      // Fall Thru
1102    case TargetLowering::Legal: {
1103      SDValue Ops[] = { DAG.getConstant(0, VT), Tmp1 };
1104      Result = DAG.getMergeValues(Ops, 2);
1105      break;
1106    }
1107    }
1108    }
1109    if (Result.getNode()->getNumValues() == 1) break;
1110
1111    assert(Result.getNode()->getNumValues() == 2 &&
1112           "Cannot return more than two values!");
1113
1114    // Since we produced two values, make sure to remember that we
1115    // legalized both of them.
1116    Tmp1 = LegalizeOp(Result);
1117    Tmp2 = LegalizeOp(Result.getValue(1));
1118    AddLegalizedOperand(Op.getValue(0), Tmp1);
1119    AddLegalizedOperand(Op.getValue(1), Tmp2);
1120    return Op.getResNo() ? Tmp2 : Tmp1;
1121  case ISD::EHSELECTION: {
1122    Tmp1 = LegalizeOp(Node->getOperand(0));
1123    Tmp2 = LegalizeOp(Node->getOperand(1));
1124    MVT VT = Node->getValueType(0);
1125    switch (TLI.getOperationAction(Node->getOpcode(), VT)) {
1126    default: assert(0 && "This action is not supported yet!");
1127    case TargetLowering::Expand: {
1128        unsigned Reg = TLI.getExceptionSelectorRegister();
1129        Result = DAG.getCopyFromReg(Tmp2, Reg, VT);
1130      }
1131      break;
1132    case TargetLowering::Custom:
1133      Result = TLI.LowerOperation(Op, DAG);
1134      if (Result.getNode()) break;
1135      // Fall Thru
1136    case TargetLowering::Legal: {
1137      SDValue Ops[] = { DAG.getConstant(0, VT), Tmp2 };
1138      Result = DAG.getMergeValues(Ops, 2);
1139      break;
1140    }
1141    }
1142    }
1143    if (Result.getNode()->getNumValues() == 1) break;
1144
1145    assert(Result.getNode()->getNumValues() == 2 &&
1146           "Cannot return more than two values!");
1147
1148    // Since we produced two values, make sure to remember that we
1149    // legalized both of them.
1150    Tmp1 = LegalizeOp(Result);
1151    Tmp2 = LegalizeOp(Result.getValue(1));
1152    AddLegalizedOperand(Op.getValue(0), Tmp1);
1153    AddLegalizedOperand(Op.getValue(1), Tmp2);
1154    return Op.getResNo() ? Tmp2 : Tmp1;
1155  case ISD::EH_RETURN: {
1156    MVT VT = Node->getValueType(0);
1157    // The only "good" option for this node is to custom lower it.
1158    switch (TLI.getOperationAction(Node->getOpcode(), VT)) {
1159    default: assert(0 && "This action is not supported at all!");
1160    case TargetLowering::Custom:
1161      Result = TLI.LowerOperation(Op, DAG);
1162      if (Result.getNode()) break;
1163      // Fall Thru
1164    case TargetLowering::Legal:
1165      // Target does not know, how to lower this, lower to noop
1166      Result = LegalizeOp(Node->getOperand(0));
1167      break;
1168    }
1169    }
1170    break;
1171  case ISD::AssertSext:
1172  case ISD::AssertZext:
1173    Tmp1 = LegalizeOp(Node->getOperand(0));
1174    Result = DAG.UpdateNodeOperands(Result, Tmp1, Node->getOperand(1));
1175    break;
1176  case ISD::MERGE_VALUES:
1177    // Legalize eliminates MERGE_VALUES nodes.
1178    Result = Node->getOperand(Op.getResNo());
1179    break;
1180  case ISD::CopyFromReg:
1181    Tmp1 = LegalizeOp(Node->getOperand(0));
1182    Result = Op.getValue(0);
1183    if (Node->getNumValues() == 2) {
1184      Result = DAG.UpdateNodeOperands(Result, Tmp1, Node->getOperand(1));
1185    } else {
1186      assert(Node->getNumValues() == 3 && "Invalid copyfromreg!");
1187      if (Node->getNumOperands() == 3) {
1188        Tmp2 = LegalizeOp(Node->getOperand(2));
1189        Result = DAG.UpdateNodeOperands(Result, Tmp1, Node->getOperand(1),Tmp2);
1190      } else {
1191        Result = DAG.UpdateNodeOperands(Result, Tmp1, Node->getOperand(1));
1192      }
1193      AddLegalizedOperand(Op.getValue(2), Result.getValue(2));
1194    }
1195    // Since CopyFromReg produces two values, make sure to remember that we
1196    // legalized both of them.
1197    AddLegalizedOperand(Op.getValue(0), Result);
1198    AddLegalizedOperand(Op.getValue(1), Result.getValue(1));
1199    return Result.getValue(Op.getResNo());
1200  case ISD::UNDEF: {
1201    MVT VT = Op.getValueType();
1202    switch (TLI.getOperationAction(ISD::UNDEF, VT)) {
1203    default: assert(0 && "This action is not supported yet!");
1204    case TargetLowering::Expand:
1205      if (VT.isInteger())
1206        Result = DAG.getConstant(0, VT);
1207      else if (VT.isFloatingPoint())
1208        Result = DAG.getConstantFP(APFloat(APInt(VT.getSizeInBits(), 0)),
1209                                   VT);
1210      else
1211        assert(0 && "Unknown value type!");
1212      break;
1213    case TargetLowering::Legal:
1214      break;
1215    }
1216    break;
1217  }
1218
1219  case ISD::INTRINSIC_W_CHAIN:
1220  case ISD::INTRINSIC_WO_CHAIN:
1221  case ISD::INTRINSIC_VOID: {
1222    SmallVector<SDValue, 8> Ops;
1223    for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i)
1224      Ops.push_back(LegalizeOp(Node->getOperand(i)));
1225    Result = DAG.UpdateNodeOperands(Result, &Ops[0], Ops.size());
1226
1227    // Allow the target to custom lower its intrinsics if it wants to.
1228    if (TLI.getOperationAction(Node->getOpcode(), MVT::Other) ==
1229        TargetLowering::Custom) {
1230      Tmp3 = TLI.LowerOperation(Result, DAG);
1231      if (Tmp3.getNode()) Result = Tmp3;
1232    }
1233
1234    if (Result.getNode()->getNumValues() == 1) break;
1235
1236    // Must have return value and chain result.
1237    assert(Result.getNode()->getNumValues() == 2 &&
1238           "Cannot return more than two values!");
1239
1240    // Since loads produce two values, make sure to remember that we
1241    // legalized both of them.
1242    AddLegalizedOperand(SDValue(Node, 0), Result.getValue(0));
1243    AddLegalizedOperand(SDValue(Node, 1), Result.getValue(1));
1244    return Result.getValue(Op.getResNo());
1245  }
1246
1247  case ISD::DBG_STOPPOINT:
1248    assert(Node->getNumOperands() == 1 && "Invalid DBG_STOPPOINT node!");
1249    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the input chain.
1250
1251    switch (TLI.getOperationAction(ISD::DBG_STOPPOINT, MVT::Other)) {
1252    case TargetLowering::Promote:
1253    default: assert(0 && "This action is not supported yet!");
1254    case TargetLowering::Expand: {
1255      MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
1256      bool useDEBUG_LOC = TLI.isOperationLegal(ISD::DEBUG_LOC, MVT::Other);
1257      bool useLABEL = TLI.isOperationLegal(ISD::DBG_LABEL, MVT::Other);
1258
1259      const DbgStopPointSDNode *DSP = cast<DbgStopPointSDNode>(Node);
1260      if (MMI && (useDEBUG_LOC || useLABEL)) {
1261        const CompileUnitDesc *CompileUnit = DSP->getCompileUnit();
1262        unsigned SrcFile = MMI->RecordSource(CompileUnit);
1263
1264        unsigned Line = DSP->getLine();
1265        unsigned Col = DSP->getColumn();
1266
1267        if (useDEBUG_LOC) {
1268          SDValue Ops[] = { Tmp1, DAG.getConstant(Line, MVT::i32),
1269                              DAG.getConstant(Col, MVT::i32),
1270                              DAG.getConstant(SrcFile, MVT::i32) };
1271          Result = DAG.getNode(ISD::DEBUG_LOC, MVT::Other, Ops, 4);
1272        } else {
1273          unsigned ID = MMI->RecordSourceLine(Line, Col, SrcFile);
1274          Result = DAG.getLabel(ISD::DBG_LABEL, Tmp1, ID);
1275        }
1276      } else {
1277        Result = Tmp1;  // chain
1278      }
1279      break;
1280    }
1281    case TargetLowering::Legal: {
1282      LegalizeAction Action = getTypeAction(Node->getOperand(1).getValueType());
1283      if (Action == Legal && Tmp1 == Node->getOperand(0))
1284        break;
1285
1286      SmallVector<SDValue, 8> Ops;
1287      Ops.push_back(Tmp1);
1288      if (Action == Legal) {
1289        Ops.push_back(Node->getOperand(1));  // line # must be legal.
1290        Ops.push_back(Node->getOperand(2));  // col # must be legal.
1291      } else {
1292        // Otherwise promote them.
1293        Ops.push_back(PromoteOp(Node->getOperand(1)));
1294        Ops.push_back(PromoteOp(Node->getOperand(2)));
1295      }
1296      Ops.push_back(Node->getOperand(3));  // filename must be legal.
1297      Ops.push_back(Node->getOperand(4));  // working dir # must be legal.
1298      Result = DAG.UpdateNodeOperands(Result, &Ops[0], Ops.size());
1299      break;
1300    }
1301    }
1302    break;
1303
1304  case ISD::DECLARE:
1305    assert(Node->getNumOperands() == 3 && "Invalid DECLARE node!");
1306    switch (TLI.getOperationAction(ISD::DECLARE, MVT::Other)) {
1307    default: assert(0 && "This action is not supported yet!");
1308    case TargetLowering::Legal:
1309      Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1310      Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the address.
1311      Tmp3 = LegalizeOp(Node->getOperand(2));  // Legalize the variable.
1312      Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3);
1313      break;
1314    case TargetLowering::Expand:
1315      Result = LegalizeOp(Node->getOperand(0));
1316      break;
1317    }
1318    break;
1319
1320  case ISD::DEBUG_LOC:
1321    assert(Node->getNumOperands() == 4 && "Invalid DEBUG_LOC node!");
1322    switch (TLI.getOperationAction(ISD::DEBUG_LOC, MVT::Other)) {
1323    default: assert(0 && "This action is not supported yet!");
1324    case TargetLowering::Legal: {
1325      LegalizeAction Action = getTypeAction(Node->getOperand(1).getValueType());
1326      Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1327      if (Action == Legal && Tmp1 == Node->getOperand(0))
1328        break;
1329      if (Action == Legal) {
1330        Tmp2 = Node->getOperand(1);
1331        Tmp3 = Node->getOperand(2);
1332        Tmp4 = Node->getOperand(3);
1333      } else {
1334        Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the line #.
1335        Tmp3 = LegalizeOp(Node->getOperand(2));  // Legalize the col #.
1336        Tmp4 = LegalizeOp(Node->getOperand(3));  // Legalize the source file id.
1337      }
1338      Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3, Tmp4);
1339      break;
1340    }
1341    }
1342    break;
1343
1344  case ISD::DBG_LABEL:
1345  case ISD::EH_LABEL:
1346    assert(Node->getNumOperands() == 1 && "Invalid LABEL node!");
1347    switch (TLI.getOperationAction(Node->getOpcode(), MVT::Other)) {
1348    default: assert(0 && "This action is not supported yet!");
1349    case TargetLowering::Legal:
1350      Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1351      Result = DAG.UpdateNodeOperands(Result, Tmp1);
1352      break;
1353    case TargetLowering::Expand:
1354      Result = LegalizeOp(Node->getOperand(0));
1355      break;
1356    }
1357    break;
1358
1359  case ISD::PREFETCH:
1360    assert(Node->getNumOperands() == 4 && "Invalid Prefetch node!");
1361    switch (TLI.getOperationAction(ISD::PREFETCH, MVT::Other)) {
1362    default: assert(0 && "This action is not supported yet!");
1363    case TargetLowering::Legal:
1364      Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1365      Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the address.
1366      Tmp3 = LegalizeOp(Node->getOperand(2));  // Legalize the rw specifier.
1367      Tmp4 = LegalizeOp(Node->getOperand(3));  // Legalize locality specifier.
1368      Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3, Tmp4);
1369      break;
1370    case TargetLowering::Expand:
1371      // It's a noop.
1372      Result = LegalizeOp(Node->getOperand(0));
1373      break;
1374    }
1375    break;
1376
1377  case ISD::MEMBARRIER: {
1378    assert(Node->getNumOperands() == 6 && "Invalid MemBarrier node!");
1379    switch (TLI.getOperationAction(ISD::MEMBARRIER, MVT::Other)) {
1380    default: assert(0 && "This action is not supported yet!");
1381    case TargetLowering::Legal: {
1382      SDValue Ops[6];
1383      Ops[0] = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1384      for (int x = 1; x < 6; ++x) {
1385        Ops[x] = Node->getOperand(x);
1386        if (!isTypeLegal(Ops[x].getValueType()))
1387          Ops[x] = PromoteOp(Ops[x]);
1388      }
1389      Result = DAG.UpdateNodeOperands(Result, &Ops[0], 6);
1390      break;
1391    }
1392    case TargetLowering::Expand:
1393      //There is no libgcc call for this op
1394      Result = Node->getOperand(0);  // Noop
1395    break;
1396    }
1397    break;
1398  }
1399
1400  case ISD::ATOMIC_CMP_SWAP_8:
1401  case ISD::ATOMIC_CMP_SWAP_16:
1402  case ISD::ATOMIC_CMP_SWAP_32:
1403  case ISD::ATOMIC_CMP_SWAP_64: {
1404    unsigned int num_operands = 4;
1405    assert(Node->getNumOperands() == num_operands && "Invalid Atomic node!");
1406    SDValue Ops[4];
1407    for (unsigned int x = 0; x < num_operands; ++x)
1408      Ops[x] = LegalizeOp(Node->getOperand(x));
1409    Result = DAG.UpdateNodeOperands(Result, &Ops[0], num_operands);
1410
1411    switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
1412      default: assert(0 && "This action is not supported yet!");
1413      case TargetLowering::Custom:
1414        Result = TLI.LowerOperation(Result, DAG);
1415        break;
1416      case TargetLowering::Legal:
1417        break;
1418    }
1419    AddLegalizedOperand(SDValue(Node, 0), Result.getValue(0));
1420    AddLegalizedOperand(SDValue(Node, 1), Result.getValue(1));
1421    return Result.getValue(Op.getResNo());
1422  }
1423  case ISD::ATOMIC_LOAD_ADD_8:
1424  case ISD::ATOMIC_LOAD_SUB_8:
1425  case ISD::ATOMIC_LOAD_AND_8:
1426  case ISD::ATOMIC_LOAD_OR_8:
1427  case ISD::ATOMIC_LOAD_XOR_8:
1428  case ISD::ATOMIC_LOAD_NAND_8:
1429  case ISD::ATOMIC_LOAD_MIN_8:
1430  case ISD::ATOMIC_LOAD_MAX_8:
1431  case ISD::ATOMIC_LOAD_UMIN_8:
1432  case ISD::ATOMIC_LOAD_UMAX_8:
1433  case ISD::ATOMIC_SWAP_8:
1434  case ISD::ATOMIC_LOAD_ADD_16:
1435  case ISD::ATOMIC_LOAD_SUB_16:
1436  case ISD::ATOMIC_LOAD_AND_16:
1437  case ISD::ATOMIC_LOAD_OR_16:
1438  case ISD::ATOMIC_LOAD_XOR_16:
1439  case ISD::ATOMIC_LOAD_NAND_16:
1440  case ISD::ATOMIC_LOAD_MIN_16:
1441  case ISD::ATOMIC_LOAD_MAX_16:
1442  case ISD::ATOMIC_LOAD_UMIN_16:
1443  case ISD::ATOMIC_LOAD_UMAX_16:
1444  case ISD::ATOMIC_SWAP_16:
1445  case ISD::ATOMIC_LOAD_ADD_32:
1446  case ISD::ATOMIC_LOAD_SUB_32:
1447  case ISD::ATOMIC_LOAD_AND_32:
1448  case ISD::ATOMIC_LOAD_OR_32:
1449  case ISD::ATOMIC_LOAD_XOR_32:
1450  case ISD::ATOMIC_LOAD_NAND_32:
1451  case ISD::ATOMIC_LOAD_MIN_32:
1452  case ISD::ATOMIC_LOAD_MAX_32:
1453  case ISD::ATOMIC_LOAD_UMIN_32:
1454  case ISD::ATOMIC_LOAD_UMAX_32:
1455  case ISD::ATOMIC_SWAP_32:
1456  case ISD::ATOMIC_LOAD_ADD_64:
1457  case ISD::ATOMIC_LOAD_SUB_64:
1458  case ISD::ATOMIC_LOAD_AND_64:
1459  case ISD::ATOMIC_LOAD_OR_64:
1460  case ISD::ATOMIC_LOAD_XOR_64:
1461  case ISD::ATOMIC_LOAD_NAND_64:
1462  case ISD::ATOMIC_LOAD_MIN_64:
1463  case ISD::ATOMIC_LOAD_MAX_64:
1464  case ISD::ATOMIC_LOAD_UMIN_64:
1465  case ISD::ATOMIC_LOAD_UMAX_64:
1466  case ISD::ATOMIC_SWAP_64: {
1467    unsigned int num_operands = 3;
1468    assert(Node->getNumOperands() == num_operands && "Invalid Atomic node!");
1469    SDValue Ops[3];
1470    for (unsigned int x = 0; x < num_operands; ++x)
1471      Ops[x] = LegalizeOp(Node->getOperand(x));
1472    Result = DAG.UpdateNodeOperands(Result, &Ops[0], num_operands);
1473
1474    switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
1475    default: assert(0 && "This action is not supported yet!");
1476    case TargetLowering::Custom:
1477      Result = TLI.LowerOperation(Result, DAG);
1478      break;
1479    case TargetLowering::Legal:
1480      break;
1481    }
1482    AddLegalizedOperand(SDValue(Node, 0), Result.getValue(0));
1483    AddLegalizedOperand(SDValue(Node, 1), Result.getValue(1));
1484    return Result.getValue(Op.getResNo());
1485  }
1486  case ISD::Constant: {
1487    ConstantSDNode *CN = cast<ConstantSDNode>(Node);
1488    unsigned opAction =
1489      TLI.getOperationAction(ISD::Constant, CN->getValueType(0));
1490
1491    // We know we don't need to expand constants here, constants only have one
1492    // value and we check that it is fine above.
1493
1494    if (opAction == TargetLowering::Custom) {
1495      Tmp1 = TLI.LowerOperation(Result, DAG);
1496      if (Tmp1.getNode())
1497        Result = Tmp1;
1498    }
1499    break;
1500  }
1501  case ISD::ConstantFP: {
1502    // Spill FP immediates to the constant pool if the target cannot directly
1503    // codegen them.  Targets often have some immediate values that can be
1504    // efficiently generated into an FP register without a load.  We explicitly
1505    // leave these constants as ConstantFP nodes for the target to deal with.
1506    ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Node);
1507
1508    switch (TLI.getOperationAction(ISD::ConstantFP, CFP->getValueType(0))) {
1509    default: assert(0 && "This action is not supported yet!");
1510    case TargetLowering::Legal:
1511      break;
1512    case TargetLowering::Custom:
1513      Tmp3 = TLI.LowerOperation(Result, DAG);
1514      if (Tmp3.getNode()) {
1515        Result = Tmp3;
1516        break;
1517      }
1518      // FALLTHROUGH
1519    case TargetLowering::Expand: {
1520      // Check to see if this FP immediate is already legal.
1521      bool isLegal = false;
1522      for (TargetLowering::legal_fpimm_iterator I = TLI.legal_fpimm_begin(),
1523             E = TLI.legal_fpimm_end(); I != E; ++I) {
1524        if (CFP->isExactlyValue(*I)) {
1525          isLegal = true;
1526          break;
1527        }
1528      }
1529      // If this is a legal constant, turn it into a TargetConstantFP node.
1530      if (isLegal)
1531        break;
1532      Result = ExpandConstantFP(CFP, true, DAG, TLI);
1533    }
1534    }
1535    break;
1536  }
1537  case ISD::TokenFactor:
1538    if (Node->getNumOperands() == 2) {
1539      Tmp1 = LegalizeOp(Node->getOperand(0));
1540      Tmp2 = LegalizeOp(Node->getOperand(1));
1541      Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
1542    } else if (Node->getNumOperands() == 3) {
1543      Tmp1 = LegalizeOp(Node->getOperand(0));
1544      Tmp2 = LegalizeOp(Node->getOperand(1));
1545      Tmp3 = LegalizeOp(Node->getOperand(2));
1546      Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3);
1547    } else {
1548      SmallVector<SDValue, 8> Ops;
1549      // Legalize the operands.
1550      for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i)
1551        Ops.push_back(LegalizeOp(Node->getOperand(i)));
1552      Result = DAG.UpdateNodeOperands(Result, &Ops[0], Ops.size());
1553    }
1554    break;
1555
1556  case ISD::FORMAL_ARGUMENTS:
1557  case ISD::CALL:
1558    // The only option for this is to custom lower it.
1559    Tmp3 = TLI.LowerOperation(Result.getValue(0), DAG);
1560    assert(Tmp3.getNode() && "Target didn't custom lower this node!");
1561    // A call within a calling sequence must be legalized to something
1562    // other than the normal CALLSEQ_END.  Violating this gets Legalize
1563    // into an infinite loop.
1564    assert ((!IsLegalizingCall ||
1565             Node->getOpcode() != ISD::CALL ||
1566             Tmp3.getNode()->getOpcode() != ISD::CALLSEQ_END) &&
1567            "Nested CALLSEQ_START..CALLSEQ_END not supported.");
1568
1569    // The number of incoming and outgoing values should match; unless the final
1570    // outgoing value is a flag.
1571    assert((Tmp3.getNode()->getNumValues() == Result.getNode()->getNumValues() ||
1572            (Tmp3.getNode()->getNumValues() == Result.getNode()->getNumValues() + 1 &&
1573             Tmp3.getNode()->getValueType(Tmp3.getNode()->getNumValues() - 1) ==
1574               MVT::Flag)) &&
1575           "Lowering call/formal_arguments produced unexpected # results!");
1576
1577    // Since CALL/FORMAL_ARGUMENTS nodes produce multiple values, make sure to
1578    // remember that we legalized all of them, so it doesn't get relegalized.
1579    for (unsigned i = 0, e = Tmp3.getNode()->getNumValues(); i != e; ++i) {
1580      if (Tmp3.getNode()->getValueType(i) == MVT::Flag)
1581        continue;
1582      Tmp1 = LegalizeOp(Tmp3.getValue(i));
1583      if (Op.getResNo() == i)
1584        Tmp2 = Tmp1;
1585      AddLegalizedOperand(SDValue(Node, i), Tmp1);
1586    }
1587    return Tmp2;
1588   case ISD::EXTRACT_SUBREG: {
1589      Tmp1 = LegalizeOp(Node->getOperand(0));
1590      ConstantSDNode *idx = dyn_cast<ConstantSDNode>(Node->getOperand(1));
1591      assert(idx && "Operand must be a constant");
1592      Tmp2 = DAG.getTargetConstant(idx->getAPIntValue(), idx->getValueType(0));
1593      Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
1594    }
1595    break;
1596  case ISD::INSERT_SUBREG: {
1597      Tmp1 = LegalizeOp(Node->getOperand(0));
1598      Tmp2 = LegalizeOp(Node->getOperand(1));
1599      ConstantSDNode *idx = dyn_cast<ConstantSDNode>(Node->getOperand(2));
1600      assert(idx && "Operand must be a constant");
1601      Tmp3 = DAG.getTargetConstant(idx->getAPIntValue(), idx->getValueType(0));
1602      Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3);
1603    }
1604    break;
1605  case ISD::BUILD_VECTOR:
1606    switch (TLI.getOperationAction(ISD::BUILD_VECTOR, Node->getValueType(0))) {
1607    default: assert(0 && "This action is not supported yet!");
1608    case TargetLowering::Custom:
1609      Tmp3 = TLI.LowerOperation(Result, DAG);
1610      if (Tmp3.getNode()) {
1611        Result = Tmp3;
1612        break;
1613      }
1614      // FALLTHROUGH
1615    case TargetLowering::Expand:
1616      Result = ExpandBUILD_VECTOR(Result.getNode());
1617      break;
1618    }
1619    break;
1620  case ISD::INSERT_VECTOR_ELT:
1621    Tmp1 = LegalizeOp(Node->getOperand(0));  // InVec
1622    Tmp3 = LegalizeOp(Node->getOperand(2));  // InEltNo
1623
1624    // The type of the value to insert may not be legal, even though the vector
1625    // type is legal.  Legalize/Promote accordingly.  We do not handle Expand
1626    // here.
1627    switch (getTypeAction(Node->getOperand(1).getValueType())) {
1628    default: assert(0 && "Cannot expand insert element operand");
1629    case Legal:   Tmp2 = LegalizeOp(Node->getOperand(1)); break;
1630    case Promote: Tmp2 = PromoteOp(Node->getOperand(1));  break;
1631    case Expand:
1632      // FIXME: An alternative would be to check to see if the target is not
1633      // going to custom lower this operation, we could bitcast to half elt
1634      // width and perform two inserts at that width, if that is legal.
1635      Tmp2 = Node->getOperand(1);
1636      break;
1637    }
1638    Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3);
1639
1640    switch (TLI.getOperationAction(ISD::INSERT_VECTOR_ELT,
1641                                   Node->getValueType(0))) {
1642    default: assert(0 && "This action is not supported yet!");
1643    case TargetLowering::Legal:
1644      break;
1645    case TargetLowering::Custom:
1646      Tmp4 = TLI.LowerOperation(Result, DAG);
1647      if (Tmp4.getNode()) {
1648        Result = Tmp4;
1649        break;
1650      }
1651      // FALLTHROUGH
1652    case TargetLowering::Promote:
1653      // Fall thru for vector case
1654    case TargetLowering::Expand: {
1655      // If the insert index is a constant, codegen this as a scalar_to_vector,
1656      // then a shuffle that inserts it into the right position in the vector.
1657      if (ConstantSDNode *InsertPos = dyn_cast<ConstantSDNode>(Tmp3)) {
1658        // SCALAR_TO_VECTOR requires that the type of the value being inserted
1659        // match the element type of the vector being created.
1660        if (Tmp2.getValueType() ==
1661            Op.getValueType().getVectorElementType()) {
1662          SDValue ScVec = DAG.getNode(ISD::SCALAR_TO_VECTOR,
1663                                        Tmp1.getValueType(), Tmp2);
1664
1665          unsigned NumElts = Tmp1.getValueType().getVectorNumElements();
1666          MVT ShufMaskVT =
1667            MVT::getIntVectorWithNumElements(NumElts);
1668          MVT ShufMaskEltVT = ShufMaskVT.getVectorElementType();
1669
1670          // We generate a shuffle of InVec and ScVec, so the shuffle mask
1671          // should be 0,1,2,3,4,5... with the appropriate element replaced with
1672          // elt 0 of the RHS.
1673          SmallVector<SDValue, 8> ShufOps;
1674          for (unsigned i = 0; i != NumElts; ++i) {
1675            if (i != InsertPos->getZExtValue())
1676              ShufOps.push_back(DAG.getConstant(i, ShufMaskEltVT));
1677            else
1678              ShufOps.push_back(DAG.getConstant(NumElts, ShufMaskEltVT));
1679          }
1680          SDValue ShufMask = DAG.getNode(ISD::BUILD_VECTOR, ShufMaskVT,
1681                                           &ShufOps[0], ShufOps.size());
1682
1683          Result = DAG.getNode(ISD::VECTOR_SHUFFLE, Tmp1.getValueType(),
1684                               Tmp1, ScVec, ShufMask);
1685          Result = LegalizeOp(Result);
1686          break;
1687        }
1688      }
1689      Result = PerformInsertVectorEltInMemory(Tmp1, Tmp2, Tmp3);
1690      break;
1691    }
1692    }
1693    break;
1694  case ISD::SCALAR_TO_VECTOR:
1695    if (!TLI.isTypeLegal(Node->getOperand(0).getValueType())) {
1696      Result = LegalizeOp(ExpandSCALAR_TO_VECTOR(Node));
1697      break;
1698    }
1699
1700    Tmp1 = LegalizeOp(Node->getOperand(0));  // InVal
1701    Result = DAG.UpdateNodeOperands(Result, Tmp1);
1702    switch (TLI.getOperationAction(ISD::SCALAR_TO_VECTOR,
1703                                   Node->getValueType(0))) {
1704    default: assert(0 && "This action is not supported yet!");
1705    case TargetLowering::Legal:
1706      break;
1707    case TargetLowering::Custom:
1708      Tmp3 = TLI.LowerOperation(Result, DAG);
1709      if (Tmp3.getNode()) {
1710        Result = Tmp3;
1711        break;
1712      }
1713      // FALLTHROUGH
1714    case TargetLowering::Expand:
1715      Result = LegalizeOp(ExpandSCALAR_TO_VECTOR(Node));
1716      break;
1717    }
1718    break;
1719  case ISD::VECTOR_SHUFFLE:
1720    Tmp1 = LegalizeOp(Node->getOperand(0));   // Legalize the input vectors,
1721    Tmp2 = LegalizeOp(Node->getOperand(1));   // but not the shuffle mask.
1722    Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Node->getOperand(2));
1723
1724    // Allow targets to custom lower the SHUFFLEs they support.
1725    switch (TLI.getOperationAction(ISD::VECTOR_SHUFFLE,Result.getValueType())) {
1726    default: assert(0 && "Unknown operation action!");
1727    case TargetLowering::Legal:
1728      assert(isShuffleLegal(Result.getValueType(), Node->getOperand(2)) &&
1729             "vector shuffle should not be created if not legal!");
1730      break;
1731    case TargetLowering::Custom:
1732      Tmp3 = TLI.LowerOperation(Result, DAG);
1733      if (Tmp3.getNode()) {
1734        Result = Tmp3;
1735        break;
1736      }
1737      // FALLTHROUGH
1738    case TargetLowering::Expand: {
1739      MVT VT = Node->getValueType(0);
1740      MVT EltVT = VT.getVectorElementType();
1741      MVT PtrVT = TLI.getPointerTy();
1742      SDValue Mask = Node->getOperand(2);
1743      unsigned NumElems = Mask.getNumOperands();
1744      SmallVector<SDValue,8> Ops;
1745      for (unsigned i = 0; i != NumElems; ++i) {
1746        SDValue Arg = Mask.getOperand(i);
1747        if (Arg.getOpcode() == ISD::UNDEF) {
1748          Ops.push_back(DAG.getNode(ISD::UNDEF, EltVT));
1749        } else {
1750          assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
1751          unsigned Idx = cast<ConstantSDNode>(Arg)->getZExtValue();
1752          if (Idx < NumElems)
1753            Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, EltVT, Tmp1,
1754                                      DAG.getConstant(Idx, PtrVT)));
1755          else
1756            Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, EltVT, Tmp2,
1757                                      DAG.getConstant(Idx - NumElems, PtrVT)));
1758        }
1759      }
1760      Result = DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
1761      break;
1762    }
1763    case TargetLowering::Promote: {
1764      // Change base type to a different vector type.
1765      MVT OVT = Node->getValueType(0);
1766      MVT NVT = TLI.getTypeToPromoteTo(Node->getOpcode(), OVT);
1767
1768      // Cast the two input vectors.
1769      Tmp1 = DAG.getNode(ISD::BIT_CONVERT, NVT, Tmp1);
1770      Tmp2 = DAG.getNode(ISD::BIT_CONVERT, NVT, Tmp2);
1771
1772      // Convert the shuffle mask to the right # elements.
1773      Tmp3 = SDValue(isShuffleLegal(OVT, Node->getOperand(2)), 0);
1774      assert(Tmp3.getNode() && "Shuffle not legal?");
1775      Result = DAG.getNode(ISD::VECTOR_SHUFFLE, NVT, Tmp1, Tmp2, Tmp3);
1776      Result = DAG.getNode(ISD::BIT_CONVERT, OVT, Result);
1777      break;
1778    }
1779    }
1780    break;
1781
1782  case ISD::EXTRACT_VECTOR_ELT:
1783    Tmp1 = Node->getOperand(0);
1784    Tmp2 = LegalizeOp(Node->getOperand(1));
1785    Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
1786    Result = ExpandEXTRACT_VECTOR_ELT(Result);
1787    break;
1788
1789  case ISD::EXTRACT_SUBVECTOR:
1790    Tmp1 = Node->getOperand(0);
1791    Tmp2 = LegalizeOp(Node->getOperand(1));
1792    Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
1793    Result = ExpandEXTRACT_SUBVECTOR(Result);
1794    break;
1795
1796  case ISD::CONCAT_VECTORS: {
1797    // Use extract/insert/build vector for now. We might try to be
1798    // more clever later.
1799    MVT PtrVT = TLI.getPointerTy();
1800    SmallVector<SDValue, 8> Ops;
1801    unsigned NumOperands = Node->getNumOperands();
1802    for (unsigned i=0; i < NumOperands; ++i) {
1803      SDValue SubOp = Node->getOperand(i);
1804      MVT VVT = SubOp.getNode()->getValueType(0);
1805      MVT EltVT = VVT.getVectorElementType();
1806      unsigned NumSubElem = VVT.getVectorNumElements();
1807      for (unsigned j=0; j < NumSubElem; ++j) {
1808        Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, EltVT, SubOp,
1809                                  DAG.getConstant(j, PtrVT)));
1810      }
1811    }
1812    return LegalizeOp(DAG.getNode(ISD::BUILD_VECTOR, Node->getValueType(0),
1813                      &Ops[0], Ops.size()));
1814  }
1815
1816  case ISD::CALLSEQ_START: {
1817    SDNode *CallEnd = FindCallEndFromCallStart(Node);
1818
1819    // Recursively Legalize all of the inputs of the call end that do not lead
1820    // to this call start.  This ensures that any libcalls that need be inserted
1821    // are inserted *before* the CALLSEQ_START.
1822    {SmallPtrSet<SDNode*, 32> NodesLeadingTo;
1823    for (unsigned i = 0, e = CallEnd->getNumOperands(); i != e; ++i)
1824      LegalizeAllNodesNotLeadingTo(CallEnd->getOperand(i).getNode(), Node,
1825                                   NodesLeadingTo);
1826    }
1827
1828    // Now that we legalized all of the inputs (which may have inserted
1829    // libcalls) create the new CALLSEQ_START node.
1830    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1831
1832    // Merge in the last call, to ensure that this call start after the last
1833    // call ended.
1834    if (LastCALLSEQ_END.getOpcode() != ISD::EntryToken) {
1835      Tmp1 = DAG.getNode(ISD::TokenFactor, MVT::Other, Tmp1, LastCALLSEQ_END);
1836      Tmp1 = LegalizeOp(Tmp1);
1837    }
1838
1839    // Do not try to legalize the target-specific arguments (#1+).
1840    if (Tmp1 != Node->getOperand(0)) {
1841      SmallVector<SDValue, 8> Ops(Node->op_begin(), Node->op_end());
1842      Ops[0] = Tmp1;
1843      Result = DAG.UpdateNodeOperands(Result, &Ops[0], Ops.size());
1844    }
1845
1846    // Remember that the CALLSEQ_START is legalized.
1847    AddLegalizedOperand(Op.getValue(0), Result);
1848    if (Node->getNumValues() == 2)    // If this has a flag result, remember it.
1849      AddLegalizedOperand(Op.getValue(1), Result.getValue(1));
1850
1851    // Now that the callseq_start and all of the non-call nodes above this call
1852    // sequence have been legalized, legalize the call itself.  During this
1853    // process, no libcalls can/will be inserted, guaranteeing that no calls
1854    // can overlap.
1855    assert(!IsLegalizingCall && "Inconsistent sequentialization of calls!");
1856    // Note that we are selecting this call!
1857    LastCALLSEQ_END = SDValue(CallEnd, 0);
1858    IsLegalizingCall = true;
1859
1860    // Legalize the call, starting from the CALLSEQ_END.
1861    LegalizeOp(LastCALLSEQ_END);
1862    assert(!IsLegalizingCall && "CALLSEQ_END should have cleared this!");
1863    return Result;
1864  }
1865  case ISD::CALLSEQ_END:
1866    // If the CALLSEQ_START node hasn't been legalized first, legalize it.  This
1867    // will cause this node to be legalized as well as handling libcalls right.
1868    if (LastCALLSEQ_END.getNode() != Node) {
1869      LegalizeOp(SDValue(FindCallStartFromCallEnd(Node), 0));
1870      DenseMap<SDValue, SDValue>::iterator I = LegalizedNodes.find(Op);
1871      assert(I != LegalizedNodes.end() &&
1872             "Legalizing the call start should have legalized this node!");
1873      return I->second;
1874    }
1875
1876    // Otherwise, the call start has been legalized and everything is going
1877    // according to plan.  Just legalize ourselves normally here.
1878    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1879    // Do not try to legalize the target-specific arguments (#1+), except for
1880    // an optional flag input.
1881    if (Node->getOperand(Node->getNumOperands()-1).getValueType() != MVT::Flag){
1882      if (Tmp1 != Node->getOperand(0)) {
1883        SmallVector<SDValue, 8> Ops(Node->op_begin(), Node->op_end());
1884        Ops[0] = Tmp1;
1885        Result = DAG.UpdateNodeOperands(Result, &Ops[0], Ops.size());
1886      }
1887    } else {
1888      Tmp2 = LegalizeOp(Node->getOperand(Node->getNumOperands()-1));
1889      if (Tmp1 != Node->getOperand(0) ||
1890          Tmp2 != Node->getOperand(Node->getNumOperands()-1)) {
1891        SmallVector<SDValue, 8> Ops(Node->op_begin(), Node->op_end());
1892        Ops[0] = Tmp1;
1893        Ops.back() = Tmp2;
1894        Result = DAG.UpdateNodeOperands(Result, &Ops[0], Ops.size());
1895      }
1896    }
1897    assert(IsLegalizingCall && "Call sequence imbalance between start/end?");
1898    // This finishes up call legalization.
1899    IsLegalizingCall = false;
1900
1901    // If the CALLSEQ_END node has a flag, remember that we legalized it.
1902    AddLegalizedOperand(SDValue(Node, 0), Result.getValue(0));
1903    if (Node->getNumValues() == 2)
1904      AddLegalizedOperand(SDValue(Node, 1), Result.getValue(1));
1905    return Result.getValue(Op.getResNo());
1906  case ISD::DYNAMIC_STACKALLOC: {
1907    MVT VT = Node->getValueType(0);
1908    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1909    Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the size.
1910    Tmp3 = LegalizeOp(Node->getOperand(2));  // Legalize the alignment.
1911    Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3);
1912
1913    Tmp1 = Result.getValue(0);
1914    Tmp2 = Result.getValue(1);
1915    switch (TLI.getOperationAction(Node->getOpcode(), VT)) {
1916    default: assert(0 && "This action is not supported yet!");
1917    case TargetLowering::Expand: {
1918      unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
1919      assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
1920             " not tell us which reg is the stack pointer!");
1921      SDValue Chain = Tmp1.getOperand(0);
1922
1923      // Chain the dynamic stack allocation so that it doesn't modify the stack
1924      // pointer when other instructions are using the stack.
1925      Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true));
1926
1927      SDValue Size  = Tmp2.getOperand(1);
1928      SDValue SP = DAG.getCopyFromReg(Chain, SPReg, VT);
1929      Chain = SP.getValue(1);
1930      unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
1931      unsigned StackAlign =
1932        TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
1933      if (Align > StackAlign)
1934        SP = DAG.getNode(ISD::AND, VT, SP,
1935                         DAG.getConstant(-(uint64_t)Align, VT));
1936      Tmp1 = DAG.getNode(ISD::SUB, VT, SP, Size);       // Value
1937      Chain = DAG.getCopyToReg(Chain, SPReg, Tmp1);     // Output chain
1938
1939      Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, true),
1940                                DAG.getIntPtrConstant(0, true), SDValue());
1941
1942      Tmp1 = LegalizeOp(Tmp1);
1943      Tmp2 = LegalizeOp(Tmp2);
1944      break;
1945    }
1946    case TargetLowering::Custom:
1947      Tmp3 = TLI.LowerOperation(Tmp1, DAG);
1948      if (Tmp3.getNode()) {
1949        Tmp1 = LegalizeOp(Tmp3);
1950        Tmp2 = LegalizeOp(Tmp3.getValue(1));
1951      }
1952      break;
1953    case TargetLowering::Legal:
1954      break;
1955    }
1956    // Since this op produce two values, make sure to remember that we
1957    // legalized both of them.
1958    AddLegalizedOperand(SDValue(Node, 0), Tmp1);
1959    AddLegalizedOperand(SDValue(Node, 1), Tmp2);
1960    return Op.getResNo() ? Tmp2 : Tmp1;
1961  }
1962  case ISD::INLINEASM: {
1963    SmallVector<SDValue, 8> Ops(Node->op_begin(), Node->op_end());
1964    bool Changed = false;
1965    // Legalize all of the operands of the inline asm, in case they are nodes
1966    // that need to be expanded or something.  Note we skip the asm string and
1967    // all of the TargetConstant flags.
1968    SDValue Op = LegalizeOp(Ops[0]);
1969    Changed = Op != Ops[0];
1970    Ops[0] = Op;
1971
1972    bool HasInFlag = Ops.back().getValueType() == MVT::Flag;
1973    for (unsigned i = 2, e = Ops.size()-HasInFlag; i < e; ) {
1974      unsigned NumVals = cast<ConstantSDNode>(Ops[i])->getZExtValue() >> 3;
1975      for (++i; NumVals; ++i, --NumVals) {
1976        SDValue Op = LegalizeOp(Ops[i]);
1977        if (Op != Ops[i]) {
1978          Changed = true;
1979          Ops[i] = Op;
1980        }
1981      }
1982    }
1983
1984    if (HasInFlag) {
1985      Op = LegalizeOp(Ops.back());
1986      Changed |= Op != Ops.back();
1987      Ops.back() = Op;
1988    }
1989
1990    if (Changed)
1991      Result = DAG.UpdateNodeOperands(Result, &Ops[0], Ops.size());
1992
1993    // INLINE asm returns a chain and flag, make sure to add both to the map.
1994    AddLegalizedOperand(SDValue(Node, 0), Result.getValue(0));
1995    AddLegalizedOperand(SDValue(Node, 1), Result.getValue(1));
1996    return Result.getValue(Op.getResNo());
1997  }
1998  case ISD::BR:
1999    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
2000    // Ensure that libcalls are emitted before a branch.
2001    Tmp1 = DAG.getNode(ISD::TokenFactor, MVT::Other, Tmp1, LastCALLSEQ_END);
2002    Tmp1 = LegalizeOp(Tmp1);
2003    LastCALLSEQ_END = DAG.getEntryNode();
2004
2005    Result = DAG.UpdateNodeOperands(Result, Tmp1, Node->getOperand(1));
2006    break;
2007  case ISD::BRIND:
2008    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
2009    // Ensure that libcalls are emitted before a branch.
2010    Tmp1 = DAG.getNode(ISD::TokenFactor, MVT::Other, Tmp1, LastCALLSEQ_END);
2011    Tmp1 = LegalizeOp(Tmp1);
2012    LastCALLSEQ_END = DAG.getEntryNode();
2013
2014    switch (getTypeAction(Node->getOperand(1).getValueType())) {
2015    default: assert(0 && "Indirect target must be legal type (pointer)!");
2016    case Legal:
2017      Tmp2 = LegalizeOp(Node->getOperand(1)); // Legalize the condition.
2018      break;
2019    }
2020    Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
2021    break;
2022  case ISD::BR_JT:
2023    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
2024    // Ensure that libcalls are emitted before a branch.
2025    Tmp1 = DAG.getNode(ISD::TokenFactor, MVT::Other, Tmp1, LastCALLSEQ_END);
2026    Tmp1 = LegalizeOp(Tmp1);
2027    LastCALLSEQ_END = DAG.getEntryNode();
2028
2029    Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the jumptable node.
2030    Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Node->getOperand(2));
2031
2032    switch (TLI.getOperationAction(ISD::BR_JT, MVT::Other)) {
2033    default: assert(0 && "This action is not supported yet!");
2034    case TargetLowering::Legal: break;
2035    case TargetLowering::Custom:
2036      Tmp1 = TLI.LowerOperation(Result, DAG);
2037      if (Tmp1.getNode()) Result = Tmp1;
2038      break;
2039    case TargetLowering::Expand: {
2040      SDValue Chain = Result.getOperand(0);
2041      SDValue Table = Result.getOperand(1);
2042      SDValue Index = Result.getOperand(2);
2043
2044      MVT PTy = TLI.getPointerTy();
2045      MachineFunction &MF = DAG.getMachineFunction();
2046      unsigned EntrySize = MF.getJumpTableInfo()->getEntrySize();
2047      Index= DAG.getNode(ISD::MUL, PTy, Index, DAG.getConstant(EntrySize, PTy));
2048      SDValue Addr = DAG.getNode(ISD::ADD, PTy, Index, Table);
2049
2050      MVT MemVT = MVT::getIntegerVT(EntrySize * 8);
2051      SDValue LD = DAG.getExtLoad(ISD::SEXTLOAD, PTy, Chain, Addr,
2052                                  PseudoSourceValue::getJumpTable(), 0, MemVT);
2053      Addr = LD;
2054      if (TLI.getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2055        // For PIC, the sequence is:
2056        // BRIND(load(Jumptable + index) + RelocBase)
2057        // RelocBase can be JumpTable, GOT or some sort of global base.
2058        Addr = DAG.getNode(ISD::ADD, PTy, Addr,
2059                           TLI.getPICJumpTableRelocBase(Table, DAG));
2060      }
2061      Result = DAG.getNode(ISD::BRIND, MVT::Other, LD.getValue(1), Addr);
2062    }
2063    }
2064    break;
2065  case ISD::BRCOND:
2066    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
2067    // Ensure that libcalls are emitted before a return.
2068    Tmp1 = DAG.getNode(ISD::TokenFactor, MVT::Other, Tmp1, LastCALLSEQ_END);
2069    Tmp1 = LegalizeOp(Tmp1);
2070    LastCALLSEQ_END = DAG.getEntryNode();
2071
2072    switch (getTypeAction(Node->getOperand(1).getValueType())) {
2073    case Expand: assert(0 && "It's impossible to expand bools");
2074    case Legal:
2075      Tmp2 = LegalizeOp(Node->getOperand(1)); // Legalize the condition.
2076      break;
2077    case Promote: {
2078      Tmp2 = PromoteOp(Node->getOperand(1));  // Promote the condition.
2079
2080      // The top bits of the promoted condition are not necessarily zero, ensure
2081      // that the value is properly zero extended.
2082      unsigned BitWidth = Tmp2.getValueSizeInBits();
2083      if (!DAG.MaskedValueIsZero(Tmp2,
2084                                 APInt::getHighBitsSet(BitWidth, BitWidth-1)))
2085        Tmp2 = DAG.getZeroExtendInReg(Tmp2, MVT::i1);
2086      break;
2087    }
2088    }
2089
2090    // Basic block destination (Op#2) is always legal.
2091    Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Node->getOperand(2));
2092
2093    switch (TLI.getOperationAction(ISD::BRCOND, MVT::Other)) {
2094    default: assert(0 && "This action is not supported yet!");
2095    case TargetLowering::Legal: break;
2096    case TargetLowering::Custom:
2097      Tmp1 = TLI.LowerOperation(Result, DAG);
2098      if (Tmp1.getNode()) Result = Tmp1;
2099      break;
2100    case TargetLowering::Expand:
2101      // Expand brcond's setcc into its constituent parts and create a BR_CC
2102      // Node.
2103      if (Tmp2.getOpcode() == ISD::SETCC) {
2104        Result = DAG.getNode(ISD::BR_CC, MVT::Other, Tmp1, Tmp2.getOperand(2),
2105                             Tmp2.getOperand(0), Tmp2.getOperand(1),
2106                             Node->getOperand(2));
2107      } else {
2108        Result = DAG.getNode(ISD::BR_CC, MVT::Other, Tmp1,
2109                             DAG.getCondCode(ISD::SETNE), Tmp2,
2110                             DAG.getConstant(0, Tmp2.getValueType()),
2111                             Node->getOperand(2));
2112      }
2113      break;
2114    }
2115    break;
2116  case ISD::BR_CC:
2117    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
2118    // Ensure that libcalls are emitted before a branch.
2119    Tmp1 = DAG.getNode(ISD::TokenFactor, MVT::Other, Tmp1, LastCALLSEQ_END);
2120    Tmp1 = LegalizeOp(Tmp1);
2121    Tmp2 = Node->getOperand(2);              // LHS
2122    Tmp3 = Node->getOperand(3);              // RHS
2123    Tmp4 = Node->getOperand(1);              // CC
2124
2125    LegalizeSetCC(TLI.getSetCCResultType(Tmp2), Tmp2, Tmp3, Tmp4);
2126    LastCALLSEQ_END = DAG.getEntryNode();
2127
2128    // If we didn't get both a LHS and RHS back from LegalizeSetCC,
2129    // the LHS is a legal SETCC itself.  In this case, we need to compare
2130    // the result against zero to select between true and false values.
2131    if (Tmp3.getNode() == 0) {
2132      Tmp3 = DAG.getConstant(0, Tmp2.getValueType());
2133      Tmp4 = DAG.getCondCode(ISD::SETNE);
2134    }
2135
2136    Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp4, Tmp2, Tmp3,
2137                                    Node->getOperand(4));
2138
2139    switch (TLI.getOperationAction(ISD::BR_CC, Tmp3.getValueType())) {
2140    default: assert(0 && "Unexpected action for BR_CC!");
2141    case TargetLowering::Legal: break;
2142    case TargetLowering::Custom:
2143      Tmp4 = TLI.LowerOperation(Result, DAG);
2144      if (Tmp4.getNode()) Result = Tmp4;
2145      break;
2146    }
2147    break;
2148  case ISD::LOAD: {
2149    LoadSDNode *LD = cast<LoadSDNode>(Node);
2150    Tmp1 = LegalizeOp(LD->getChain());   // Legalize the chain.
2151    Tmp2 = LegalizeOp(LD->getBasePtr()); // Legalize the base pointer.
2152
2153    ISD::LoadExtType ExtType = LD->getExtensionType();
2154    if (ExtType == ISD::NON_EXTLOAD) {
2155      MVT VT = Node->getValueType(0);
2156      Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, LD->getOffset());
2157      Tmp3 = Result.getValue(0);
2158      Tmp4 = Result.getValue(1);
2159
2160      switch (TLI.getOperationAction(Node->getOpcode(), VT)) {
2161      default: assert(0 && "This action is not supported yet!");
2162      case TargetLowering::Legal:
2163        // If this is an unaligned load and the target doesn't support it,
2164        // expand it.
2165        if (!TLI.allowsUnalignedMemoryAccesses()) {
2166          unsigned ABIAlignment = TLI.getTargetData()->
2167            getABITypeAlignment(LD->getMemoryVT().getTypeForMVT());
2168          if (LD->getAlignment() < ABIAlignment){
2169            Result = ExpandUnalignedLoad(cast<LoadSDNode>(Result.getNode()), DAG,
2170                                         TLI);
2171            Tmp3 = Result.getOperand(0);
2172            Tmp4 = Result.getOperand(1);
2173            Tmp3 = LegalizeOp(Tmp3);
2174            Tmp4 = LegalizeOp(Tmp4);
2175          }
2176        }
2177        break;
2178      case TargetLowering::Custom:
2179        Tmp1 = TLI.LowerOperation(Tmp3, DAG);
2180        if (Tmp1.getNode()) {
2181          Tmp3 = LegalizeOp(Tmp1);
2182          Tmp4 = LegalizeOp(Tmp1.getValue(1));
2183        }
2184        break;
2185      case TargetLowering::Promote: {
2186        // Only promote a load of vector type to another.
2187        assert(VT.isVector() && "Cannot promote this load!");
2188        // Change base type to a different vector type.
2189        MVT NVT = TLI.getTypeToPromoteTo(Node->getOpcode(), VT);
2190
2191        Tmp1 = DAG.getLoad(NVT, Tmp1, Tmp2, LD->getSrcValue(),
2192                           LD->getSrcValueOffset(),
2193                           LD->isVolatile(), LD->getAlignment());
2194        Tmp3 = LegalizeOp(DAG.getNode(ISD::BIT_CONVERT, VT, Tmp1));
2195        Tmp4 = LegalizeOp(Tmp1.getValue(1));
2196        break;
2197      }
2198      }
2199      // Since loads produce two values, make sure to remember that we
2200      // legalized both of them.
2201      AddLegalizedOperand(SDValue(Node, 0), Tmp3);
2202      AddLegalizedOperand(SDValue(Node, 1), Tmp4);
2203      return Op.getResNo() ? Tmp4 : Tmp3;
2204    } else {
2205      MVT SrcVT = LD->getMemoryVT();
2206      unsigned SrcWidth = SrcVT.getSizeInBits();
2207      int SVOffset = LD->getSrcValueOffset();
2208      unsigned Alignment = LD->getAlignment();
2209      bool isVolatile = LD->isVolatile();
2210
2211      if (SrcWidth != SrcVT.getStoreSizeInBits() &&
2212          // Some targets pretend to have an i1 loading operation, and actually
2213          // load an i8.  This trick is correct for ZEXTLOAD because the top 7
2214          // bits are guaranteed to be zero; it helps the optimizers understand
2215          // that these bits are zero.  It is also useful for EXTLOAD, since it
2216          // tells the optimizers that those bits are undefined.  It would be
2217          // nice to have an effective generic way of getting these benefits...
2218          // Until such a way is found, don't insist on promoting i1 here.
2219          (SrcVT != MVT::i1 ||
2220           TLI.getLoadExtAction(ExtType, MVT::i1) == TargetLowering::Promote)) {
2221        // Promote to a byte-sized load if not loading an integral number of
2222        // bytes.  For example, promote EXTLOAD:i20 -> EXTLOAD:i24.
2223        unsigned NewWidth = SrcVT.getStoreSizeInBits();
2224        MVT NVT = MVT::getIntegerVT(NewWidth);
2225        SDValue Ch;
2226
2227        // The extra bits are guaranteed to be zero, since we stored them that
2228        // way.  A zext load from NVT thus automatically gives zext from SrcVT.
2229
2230        ISD::LoadExtType NewExtType =
2231          ExtType == ISD::ZEXTLOAD ? ISD::ZEXTLOAD : ISD::EXTLOAD;
2232
2233        Result = DAG.getExtLoad(NewExtType, Node->getValueType(0),
2234                                Tmp1, Tmp2, LD->getSrcValue(), SVOffset,
2235                                NVT, isVolatile, Alignment);
2236
2237        Ch = Result.getValue(1); // The chain.
2238
2239        if (ExtType == ISD::SEXTLOAD)
2240          // Having the top bits zero doesn't help when sign extending.
2241          Result = DAG.getNode(ISD::SIGN_EXTEND_INREG, Result.getValueType(),
2242                               Result, DAG.getValueType(SrcVT));
2243        else if (ExtType == ISD::ZEXTLOAD || NVT == Result.getValueType())
2244          // All the top bits are guaranteed to be zero - inform the optimizers.
2245          Result = DAG.getNode(ISD::AssertZext, Result.getValueType(), Result,
2246                               DAG.getValueType(SrcVT));
2247
2248        Tmp1 = LegalizeOp(Result);
2249        Tmp2 = LegalizeOp(Ch);
2250      } else if (SrcWidth & (SrcWidth - 1)) {
2251        // If not loading a power-of-2 number of bits, expand as two loads.
2252        assert(SrcVT.isExtended() && !SrcVT.isVector() &&
2253               "Unsupported extload!");
2254        unsigned RoundWidth = 1 << Log2_32(SrcWidth);
2255        assert(RoundWidth < SrcWidth);
2256        unsigned ExtraWidth = SrcWidth - RoundWidth;
2257        assert(ExtraWidth < RoundWidth);
2258        assert(!(RoundWidth % 8) && !(ExtraWidth % 8) &&
2259               "Load size not an integral number of bytes!");
2260        MVT RoundVT = MVT::getIntegerVT(RoundWidth);
2261        MVT ExtraVT = MVT::getIntegerVT(ExtraWidth);
2262        SDValue Lo, Hi, Ch;
2263        unsigned IncrementSize;
2264
2265        if (TLI.isLittleEndian()) {
2266          // EXTLOAD:i24 -> ZEXTLOAD:i16 | (shl EXTLOAD@+2:i8, 16)
2267          // Load the bottom RoundWidth bits.
2268          Lo = DAG.getExtLoad(ISD::ZEXTLOAD, Node->getValueType(0), Tmp1, Tmp2,
2269                              LD->getSrcValue(), SVOffset, RoundVT, isVolatile,
2270                              Alignment);
2271
2272          // Load the remaining ExtraWidth bits.
2273          IncrementSize = RoundWidth / 8;
2274          Tmp2 = DAG.getNode(ISD::ADD, Tmp2.getValueType(), Tmp2,
2275                             DAG.getIntPtrConstant(IncrementSize));
2276          Hi = DAG.getExtLoad(ExtType, Node->getValueType(0), Tmp1, Tmp2,
2277                              LD->getSrcValue(), SVOffset + IncrementSize,
2278                              ExtraVT, isVolatile,
2279                              MinAlign(Alignment, IncrementSize));
2280
2281          // Build a factor node to remember that this load is independent of the
2282          // other one.
2283          Ch = DAG.getNode(ISD::TokenFactor, MVT::Other, Lo.getValue(1),
2284                           Hi.getValue(1));
2285
2286          // Move the top bits to the right place.
2287          Hi = DAG.getNode(ISD::SHL, Hi.getValueType(), Hi,
2288                           DAG.getConstant(RoundWidth, TLI.getShiftAmountTy()));
2289
2290          // Join the hi and lo parts.
2291          Result = DAG.getNode(ISD::OR, Node->getValueType(0), Lo, Hi);
2292        } else {
2293          // Big endian - avoid unaligned loads.
2294          // EXTLOAD:i24 -> (shl EXTLOAD:i16, 8) | ZEXTLOAD@+2:i8
2295          // Load the top RoundWidth bits.
2296          Hi = DAG.getExtLoad(ExtType, Node->getValueType(0), Tmp1, Tmp2,
2297                              LD->getSrcValue(), SVOffset, RoundVT, isVolatile,
2298                              Alignment);
2299
2300          // Load the remaining ExtraWidth bits.
2301          IncrementSize = RoundWidth / 8;
2302          Tmp2 = DAG.getNode(ISD::ADD, Tmp2.getValueType(), Tmp2,
2303                             DAG.getIntPtrConstant(IncrementSize));
2304          Lo = DAG.getExtLoad(ISD::ZEXTLOAD, Node->getValueType(0), Tmp1, Tmp2,
2305                              LD->getSrcValue(), SVOffset + IncrementSize,
2306                              ExtraVT, isVolatile,
2307                              MinAlign(Alignment, IncrementSize));
2308
2309          // Build a factor node to remember that this load is independent of the
2310          // other one.
2311          Ch = DAG.getNode(ISD::TokenFactor, MVT::Other, Lo.getValue(1),
2312                           Hi.getValue(1));
2313
2314          // Move the top bits to the right place.
2315          Hi = DAG.getNode(ISD::SHL, Hi.getValueType(), Hi,
2316                           DAG.getConstant(ExtraWidth, TLI.getShiftAmountTy()));
2317
2318          // Join the hi and lo parts.
2319          Result = DAG.getNode(ISD::OR, Node->getValueType(0), Lo, Hi);
2320        }
2321
2322        Tmp1 = LegalizeOp(Result);
2323        Tmp2 = LegalizeOp(Ch);
2324      } else {
2325        switch (TLI.getLoadExtAction(ExtType, SrcVT)) {
2326        default: assert(0 && "This action is not supported yet!");
2327        case TargetLowering::Custom:
2328          isCustom = true;
2329          // FALLTHROUGH
2330        case TargetLowering::Legal:
2331          Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, LD->getOffset());
2332          Tmp1 = Result.getValue(0);
2333          Tmp2 = Result.getValue(1);
2334
2335          if (isCustom) {
2336            Tmp3 = TLI.LowerOperation(Result, DAG);
2337            if (Tmp3.getNode()) {
2338              Tmp1 = LegalizeOp(Tmp3);
2339              Tmp2 = LegalizeOp(Tmp3.getValue(1));
2340            }
2341          } else {
2342            // If this is an unaligned load and the target doesn't support it,
2343            // expand it.
2344            if (!TLI.allowsUnalignedMemoryAccesses()) {
2345              unsigned ABIAlignment = TLI.getTargetData()->
2346                getABITypeAlignment(LD->getMemoryVT().getTypeForMVT());
2347              if (LD->getAlignment() < ABIAlignment){
2348                Result = ExpandUnalignedLoad(cast<LoadSDNode>(Result.getNode()), DAG,
2349                                             TLI);
2350                Tmp1 = Result.getOperand(0);
2351                Tmp2 = Result.getOperand(1);
2352                Tmp1 = LegalizeOp(Tmp1);
2353                Tmp2 = LegalizeOp(Tmp2);
2354              }
2355            }
2356          }
2357          break;
2358        case TargetLowering::Expand:
2359          // f64 = EXTLOAD f32 should expand to LOAD, FP_EXTEND
2360          if (SrcVT == MVT::f32 && Node->getValueType(0) == MVT::f64) {
2361            SDValue Load = DAG.getLoad(SrcVT, Tmp1, Tmp2, LD->getSrcValue(),
2362                                         LD->getSrcValueOffset(),
2363                                         LD->isVolatile(), LD->getAlignment());
2364            Result = DAG.getNode(ISD::FP_EXTEND, Node->getValueType(0), Load);
2365            Tmp1 = LegalizeOp(Result);  // Relegalize new nodes.
2366            Tmp2 = LegalizeOp(Load.getValue(1));
2367            break;
2368          }
2369          assert(ExtType != ISD::EXTLOAD &&"EXTLOAD should always be supported!");
2370          // Turn the unsupported load into an EXTLOAD followed by an explicit
2371          // zero/sign extend inreg.
2372          Result = DAG.getExtLoad(ISD::EXTLOAD, Node->getValueType(0),
2373                                  Tmp1, Tmp2, LD->getSrcValue(),
2374                                  LD->getSrcValueOffset(), SrcVT,
2375                                  LD->isVolatile(), LD->getAlignment());
2376          SDValue ValRes;
2377          if (ExtType == ISD::SEXTLOAD)
2378            ValRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, Result.getValueType(),
2379                                 Result, DAG.getValueType(SrcVT));
2380          else
2381            ValRes = DAG.getZeroExtendInReg(Result, SrcVT);
2382          Tmp1 = LegalizeOp(ValRes);  // Relegalize new nodes.
2383          Tmp2 = LegalizeOp(Result.getValue(1));  // Relegalize new nodes.
2384          break;
2385        }
2386      }
2387
2388      // Since loads produce two values, make sure to remember that we legalized
2389      // both of them.
2390      AddLegalizedOperand(SDValue(Node, 0), Tmp1);
2391      AddLegalizedOperand(SDValue(Node, 1), Tmp2);
2392      return Op.getResNo() ? Tmp2 : Tmp1;
2393    }
2394  }
2395  case ISD::EXTRACT_ELEMENT: {
2396    MVT OpTy = Node->getOperand(0).getValueType();
2397    switch (getTypeAction(OpTy)) {
2398    default: assert(0 && "EXTRACT_ELEMENT action for type unimplemented!");
2399    case Legal:
2400      if (cast<ConstantSDNode>(Node->getOperand(1))->getZExtValue()) {
2401        // 1 -> Hi
2402        Result = DAG.getNode(ISD::SRL, OpTy, Node->getOperand(0),
2403                             DAG.getConstant(OpTy.getSizeInBits()/2,
2404                                             TLI.getShiftAmountTy()));
2405        Result = DAG.getNode(ISD::TRUNCATE, Node->getValueType(0), Result);
2406      } else {
2407        // 0 -> Lo
2408        Result = DAG.getNode(ISD::TRUNCATE, Node->getValueType(0),
2409                             Node->getOperand(0));
2410      }
2411      break;
2412    case Expand:
2413      // Get both the low and high parts.
2414      ExpandOp(Node->getOperand(0), Tmp1, Tmp2);
2415      if (cast<ConstantSDNode>(Node->getOperand(1))->getZExtValue())
2416        Result = Tmp2;  // 1 -> Hi
2417      else
2418        Result = Tmp1;  // 0 -> Lo
2419      break;
2420    }
2421    break;
2422  }
2423
2424  case ISD::CopyToReg:
2425    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
2426
2427    assert(isTypeLegal(Node->getOperand(2).getValueType()) &&
2428           "Register type must be legal!");
2429    // Legalize the incoming value (must be a legal type).
2430    Tmp2 = LegalizeOp(Node->getOperand(2));
2431    if (Node->getNumValues() == 1) {
2432      Result = DAG.UpdateNodeOperands(Result, Tmp1, Node->getOperand(1), Tmp2);
2433    } else {
2434      assert(Node->getNumValues() == 2 && "Unknown CopyToReg");
2435      if (Node->getNumOperands() == 4) {
2436        Tmp3 = LegalizeOp(Node->getOperand(3));
2437        Result = DAG.UpdateNodeOperands(Result, Tmp1, Node->getOperand(1), Tmp2,
2438                                        Tmp3);
2439      } else {
2440        Result = DAG.UpdateNodeOperands(Result, Tmp1, Node->getOperand(1),Tmp2);
2441      }
2442
2443      // Since this produces two values, make sure to remember that we legalized
2444      // both of them.
2445      AddLegalizedOperand(SDValue(Node, 0), Result.getValue(0));
2446      AddLegalizedOperand(SDValue(Node, 1), Result.getValue(1));
2447      return Result;
2448    }
2449    break;
2450
2451  case ISD::RET:
2452    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
2453
2454    // Ensure that libcalls are emitted before a return.
2455    Tmp1 = DAG.getNode(ISD::TokenFactor, MVT::Other, Tmp1, LastCALLSEQ_END);
2456    Tmp1 = LegalizeOp(Tmp1);
2457    LastCALLSEQ_END = DAG.getEntryNode();
2458
2459    switch (Node->getNumOperands()) {
2460    case 3:  // ret val
2461      Tmp2 = Node->getOperand(1);
2462      Tmp3 = Node->getOperand(2);  // Signness
2463      switch (getTypeAction(Tmp2.getValueType())) {
2464      case Legal:
2465        Result = DAG.UpdateNodeOperands(Result, Tmp1, LegalizeOp(Tmp2), Tmp3);
2466        break;
2467      case Expand:
2468        if (!Tmp2.getValueType().isVector()) {
2469          SDValue Lo, Hi;
2470          ExpandOp(Tmp2, Lo, Hi);
2471
2472          // Big endian systems want the hi reg first.
2473          if (TLI.isBigEndian())
2474            std::swap(Lo, Hi);
2475
2476          if (Hi.getNode())
2477            Result = DAG.getNode(ISD::RET, MVT::Other, Tmp1, Lo, Tmp3, Hi,Tmp3);
2478          else
2479            Result = DAG.getNode(ISD::RET, MVT::Other, Tmp1, Lo, Tmp3);
2480          Result = LegalizeOp(Result);
2481        } else {
2482          SDNode *InVal = Tmp2.getNode();
2483          int InIx = Tmp2.getResNo();
2484          unsigned NumElems = InVal->getValueType(InIx).getVectorNumElements();
2485          MVT EVT = InVal->getValueType(InIx).getVectorElementType();
2486
2487          // Figure out if there is a simple type corresponding to this Vector
2488          // type.  If so, convert to the vector type.
2489          MVT TVT = MVT::getVectorVT(EVT, NumElems);
2490          if (TLI.isTypeLegal(TVT)) {
2491            // Turn this into a return of the vector type.
2492            Tmp2 = LegalizeOp(Tmp2);
2493            Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3);
2494          } else if (NumElems == 1) {
2495            // Turn this into a return of the scalar type.
2496            Tmp2 = ScalarizeVectorOp(Tmp2);
2497            Tmp2 = LegalizeOp(Tmp2);
2498            Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3);
2499
2500            // FIXME: Returns of gcc generic vectors smaller than a legal type
2501            // should be returned in integer registers!
2502
2503            // The scalarized value type may not be legal, e.g. it might require
2504            // promotion or expansion.  Relegalize the return.
2505            Result = LegalizeOp(Result);
2506          } else {
2507            // FIXME: Returns of gcc generic vectors larger than a legal vector
2508            // type should be returned by reference!
2509            SDValue Lo, Hi;
2510            SplitVectorOp(Tmp2, Lo, Hi);
2511            Result = DAG.getNode(ISD::RET, MVT::Other, Tmp1, Lo, Tmp3, Hi,Tmp3);
2512            Result = LegalizeOp(Result);
2513          }
2514        }
2515        break;
2516      case Promote:
2517        Tmp2 = PromoteOp(Node->getOperand(1));
2518        Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3);
2519        Result = LegalizeOp(Result);
2520        break;
2521      }
2522      break;
2523    case 1:  // ret void
2524      Result = DAG.UpdateNodeOperands(Result, Tmp1);
2525      break;
2526    default: { // ret <values>
2527      SmallVector<SDValue, 8> NewValues;
2528      NewValues.push_back(Tmp1);
2529      for (unsigned i = 1, e = Node->getNumOperands(); i < e; i += 2)
2530        switch (getTypeAction(Node->getOperand(i).getValueType())) {
2531        case Legal:
2532          NewValues.push_back(LegalizeOp(Node->getOperand(i)));
2533          NewValues.push_back(Node->getOperand(i+1));
2534          break;
2535        case Expand: {
2536          SDValue Lo, Hi;
2537          assert(!Node->getOperand(i).getValueType().isExtended() &&
2538                 "FIXME: TODO: implement returning non-legal vector types!");
2539          ExpandOp(Node->getOperand(i), Lo, Hi);
2540          NewValues.push_back(Lo);
2541          NewValues.push_back(Node->getOperand(i+1));
2542          if (Hi.getNode()) {
2543            NewValues.push_back(Hi);
2544            NewValues.push_back(Node->getOperand(i+1));
2545          }
2546          break;
2547        }
2548        case Promote:
2549          assert(0 && "Can't promote multiple return value yet!");
2550        }
2551
2552      if (NewValues.size() == Node->getNumOperands())
2553        Result = DAG.UpdateNodeOperands(Result, &NewValues[0],NewValues.size());
2554      else
2555        Result = DAG.getNode(ISD::RET, MVT::Other,
2556                             &NewValues[0], NewValues.size());
2557      break;
2558    }
2559    }
2560
2561    if (Result.getOpcode() == ISD::RET) {
2562      switch (TLI.getOperationAction(Result.getOpcode(), MVT::Other)) {
2563      default: assert(0 && "This action is not supported yet!");
2564      case TargetLowering::Legal: break;
2565      case TargetLowering::Custom:
2566        Tmp1 = TLI.LowerOperation(Result, DAG);
2567        if (Tmp1.getNode()) Result = Tmp1;
2568        break;
2569      }
2570    }
2571    break;
2572  case ISD::STORE: {
2573    StoreSDNode *ST = cast<StoreSDNode>(Node);
2574    Tmp1 = LegalizeOp(ST->getChain());    // Legalize the chain.
2575    Tmp2 = LegalizeOp(ST->getBasePtr());  // Legalize the pointer.
2576    int SVOffset = ST->getSrcValueOffset();
2577    unsigned Alignment = ST->getAlignment();
2578    bool isVolatile = ST->isVolatile();
2579
2580    if (!ST->isTruncatingStore()) {
2581      // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
2582      // FIXME: We shouldn't do this for TargetConstantFP's.
2583      // FIXME: move this to the DAG Combiner!  Note that we can't regress due
2584      // to phase ordering between legalized code and the dag combiner.  This
2585      // probably means that we need to integrate dag combiner and legalizer
2586      // together.
2587      // We generally can't do this one for long doubles.
2588      if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(ST->getValue())) {
2589        if (CFP->getValueType(0) == MVT::f32 &&
2590            getTypeAction(MVT::i32) == Legal) {
2591          Tmp3 = DAG.getConstant(CFP->getValueAPF().
2592                                          bitcastToAPInt().zextOrTrunc(32),
2593                                  MVT::i32);
2594          Result = DAG.getStore(Tmp1, Tmp3, Tmp2, ST->getSrcValue(),
2595                                SVOffset, isVolatile, Alignment);
2596          break;
2597        } else if (CFP->getValueType(0) == MVT::f64) {
2598          // If this target supports 64-bit registers, do a single 64-bit store.
2599          if (getTypeAction(MVT::i64) == Legal) {
2600            Tmp3 = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
2601                                     zextOrTrunc(64), MVT::i64);
2602            Result = DAG.getStore(Tmp1, Tmp3, Tmp2, ST->getSrcValue(),
2603                                  SVOffset, isVolatile, Alignment);
2604            break;
2605          } else if (getTypeAction(MVT::i32) == Legal && !ST->isVolatile()) {
2606            // Otherwise, if the target supports 32-bit registers, use 2 32-bit
2607            // stores.  If the target supports neither 32- nor 64-bits, this
2608            // xform is certainly not worth it.
2609            const APInt &IntVal =CFP->getValueAPF().bitcastToAPInt();
2610            SDValue Lo = DAG.getConstant(APInt(IntVal).trunc(32), MVT::i32);
2611            SDValue Hi = DAG.getConstant(IntVal.lshr(32).trunc(32), MVT::i32);
2612            if (TLI.isBigEndian()) std::swap(Lo, Hi);
2613
2614            Lo = DAG.getStore(Tmp1, Lo, Tmp2, ST->getSrcValue(),
2615                              SVOffset, isVolatile, Alignment);
2616            Tmp2 = DAG.getNode(ISD::ADD, Tmp2.getValueType(), Tmp2,
2617                               DAG.getIntPtrConstant(4));
2618            Hi = DAG.getStore(Tmp1, Hi, Tmp2, ST->getSrcValue(), SVOffset+4,
2619                              isVolatile, MinAlign(Alignment, 4U));
2620
2621            Result = DAG.getNode(ISD::TokenFactor, MVT::Other, Lo, Hi);
2622            break;
2623          }
2624        }
2625      }
2626
2627      switch (getTypeAction(ST->getMemoryVT())) {
2628      case Legal: {
2629        Tmp3 = LegalizeOp(ST->getValue());
2630        Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp3, Tmp2,
2631                                        ST->getOffset());
2632
2633        MVT VT = Tmp3.getValueType();
2634        switch (TLI.getOperationAction(ISD::STORE, VT)) {
2635        default: assert(0 && "This action is not supported yet!");
2636        case TargetLowering::Legal:
2637          // If this is an unaligned store and the target doesn't support it,
2638          // expand it.
2639          if (!TLI.allowsUnalignedMemoryAccesses()) {
2640            unsigned ABIAlignment = TLI.getTargetData()->
2641              getABITypeAlignment(ST->getMemoryVT().getTypeForMVT());
2642            if (ST->getAlignment() < ABIAlignment)
2643              Result = ExpandUnalignedStore(cast<StoreSDNode>(Result.getNode()), DAG,
2644                                            TLI);
2645          }
2646          break;
2647        case TargetLowering::Custom:
2648          Tmp1 = TLI.LowerOperation(Result, DAG);
2649          if (Tmp1.getNode()) Result = Tmp1;
2650          break;
2651        case TargetLowering::Promote:
2652          assert(VT.isVector() && "Unknown legal promote case!");
2653          Tmp3 = DAG.getNode(ISD::BIT_CONVERT,
2654                             TLI.getTypeToPromoteTo(ISD::STORE, VT), Tmp3);
2655          Result = DAG.getStore(Tmp1, Tmp3, Tmp2,
2656                                ST->getSrcValue(), SVOffset, isVolatile,
2657                                Alignment);
2658          break;
2659        }
2660        break;
2661      }
2662      case Promote:
2663        if (!ST->getMemoryVT().isVector()) {
2664          // Truncate the value and store the result.
2665          Tmp3 = PromoteOp(ST->getValue());
2666          Result = DAG.getTruncStore(Tmp1, Tmp3, Tmp2, ST->getSrcValue(),
2667                                     SVOffset, ST->getMemoryVT(),
2668                                     isVolatile, Alignment);
2669          break;
2670        }
2671        // Fall thru to expand for vector
2672      case Expand: {
2673        unsigned IncrementSize = 0;
2674        SDValue Lo, Hi;
2675
2676        // If this is a vector type, then we have to calculate the increment as
2677        // the product of the element size in bytes, and the number of elements
2678        // in the high half of the vector.
2679        if (ST->getValue().getValueType().isVector()) {
2680          SDNode *InVal = ST->getValue().getNode();
2681          int InIx = ST->getValue().getResNo();
2682          MVT InVT = InVal->getValueType(InIx);
2683          unsigned NumElems = InVT.getVectorNumElements();
2684          MVT EVT = InVT.getVectorElementType();
2685
2686          // Figure out if there is a simple type corresponding to this Vector
2687          // type.  If so, convert to the vector type.
2688          MVT TVT = MVT::getVectorVT(EVT, NumElems);
2689          if (TLI.isTypeLegal(TVT)) {
2690            // Turn this into a normal store of the vector type.
2691            Tmp3 = LegalizeOp(ST->getValue());
2692            Result = DAG.getStore(Tmp1, Tmp3, Tmp2, ST->getSrcValue(),
2693                                  SVOffset, isVolatile, Alignment);
2694            Result = LegalizeOp(Result);
2695            break;
2696          } else if (NumElems == 1) {
2697            // Turn this into a normal store of the scalar type.
2698            Tmp3 = ScalarizeVectorOp(ST->getValue());
2699            Result = DAG.getStore(Tmp1, Tmp3, Tmp2, ST->getSrcValue(),
2700                                  SVOffset, isVolatile, Alignment);
2701            // The scalarized value type may not be legal, e.g. it might require
2702            // promotion or expansion.  Relegalize the scalar store.
2703            Result = LegalizeOp(Result);
2704            break;
2705          } else {
2706            // Check if we have widen this node with another value
2707            std::map<SDValue, SDValue>::iterator I =
2708              WidenNodes.find(ST->getValue());
2709            if (I != WidenNodes.end()) {
2710              Result = StoreWidenVectorOp(ST, Tmp1, Tmp2);
2711              break;
2712            }
2713            else {
2714              SplitVectorOp(ST->getValue(), Lo, Hi);
2715              IncrementSize = Lo.getNode()->getValueType(0).getVectorNumElements() *
2716                              EVT.getSizeInBits()/8;
2717            }
2718          }
2719        } else {
2720          ExpandOp(ST->getValue(), Lo, Hi);
2721          IncrementSize = Hi.getNode() ? Hi.getValueType().getSizeInBits()/8 : 0;
2722
2723          if (Hi.getNode() && TLI.isBigEndian())
2724            std::swap(Lo, Hi);
2725        }
2726
2727        Lo = DAG.getStore(Tmp1, Lo, Tmp2, ST->getSrcValue(),
2728                          SVOffset, isVolatile, Alignment);
2729
2730        if (Hi.getNode() == NULL) {
2731          // Must be int <-> float one-to-one expansion.
2732          Result = Lo;
2733          break;
2734        }
2735
2736        Tmp2 = DAG.getNode(ISD::ADD, Tmp2.getValueType(), Tmp2,
2737                           DAG.getIntPtrConstant(IncrementSize));
2738        assert(isTypeLegal(Tmp2.getValueType()) &&
2739               "Pointers must be legal!");
2740        SVOffset += IncrementSize;
2741        Alignment = MinAlign(Alignment, IncrementSize);
2742        Hi = DAG.getStore(Tmp1, Hi, Tmp2, ST->getSrcValue(),
2743                          SVOffset, isVolatile, Alignment);
2744        Result = DAG.getNode(ISD::TokenFactor, MVT::Other, Lo, Hi);
2745        break;
2746      }  // case Expand
2747      }
2748    } else {
2749      switch (getTypeAction(ST->getValue().getValueType())) {
2750      case Legal:
2751        Tmp3 = LegalizeOp(ST->getValue());
2752        break;
2753      case Promote:
2754        if (!ST->getValue().getValueType().isVector()) {
2755          // We can promote the value, the truncstore will still take care of it.
2756          Tmp3 = PromoteOp(ST->getValue());
2757          break;
2758        }
2759        // Vector case falls through to expand
2760      case Expand:
2761        // Just store the low part.  This may become a non-trunc store, so make
2762        // sure to use getTruncStore, not UpdateNodeOperands below.
2763        ExpandOp(ST->getValue(), Tmp3, Tmp4);
2764        return DAG.getTruncStore(Tmp1, Tmp3, Tmp2, ST->getSrcValue(),
2765                                 SVOffset, MVT::i8, isVolatile, Alignment);
2766      }
2767
2768      MVT StVT = ST->getMemoryVT();
2769      unsigned StWidth = StVT.getSizeInBits();
2770
2771      if (StWidth != StVT.getStoreSizeInBits()) {
2772        // Promote to a byte-sized store with upper bits zero if not
2773        // storing an integral number of bytes.  For example, promote
2774        // TRUNCSTORE:i1 X -> TRUNCSTORE:i8 (and X, 1)
2775        MVT NVT = MVT::getIntegerVT(StVT.getStoreSizeInBits());
2776        Tmp3 = DAG.getZeroExtendInReg(Tmp3, StVT);
2777        Result = DAG.getTruncStore(Tmp1, Tmp3, Tmp2, ST->getSrcValue(),
2778                                   SVOffset, NVT, isVolatile, Alignment);
2779      } else if (StWidth & (StWidth - 1)) {
2780        // If not storing a power-of-2 number of bits, expand as two stores.
2781        assert(StVT.isExtended() && !StVT.isVector() &&
2782               "Unsupported truncstore!");
2783        unsigned RoundWidth = 1 << Log2_32(StWidth);
2784        assert(RoundWidth < StWidth);
2785        unsigned ExtraWidth = StWidth - RoundWidth;
2786        assert(ExtraWidth < RoundWidth);
2787        assert(!(RoundWidth % 8) && !(ExtraWidth % 8) &&
2788               "Store size not an integral number of bytes!");
2789        MVT RoundVT = MVT::getIntegerVT(RoundWidth);
2790        MVT ExtraVT = MVT::getIntegerVT(ExtraWidth);
2791        SDValue Lo, Hi;
2792        unsigned IncrementSize;
2793
2794        if (TLI.isLittleEndian()) {
2795          // TRUNCSTORE:i24 X -> TRUNCSTORE:i16 X, TRUNCSTORE@+2:i8 (srl X, 16)
2796          // Store the bottom RoundWidth bits.
2797          Lo = DAG.getTruncStore(Tmp1, Tmp3, Tmp2, ST->getSrcValue(),
2798                                 SVOffset, RoundVT,
2799                                 isVolatile, Alignment);
2800
2801          // Store the remaining ExtraWidth bits.
2802          IncrementSize = RoundWidth / 8;
2803          Tmp2 = DAG.getNode(ISD::ADD, Tmp2.getValueType(), Tmp2,
2804                             DAG.getIntPtrConstant(IncrementSize));
2805          Hi = DAG.getNode(ISD::SRL, Tmp3.getValueType(), Tmp3,
2806                           DAG.getConstant(RoundWidth, TLI.getShiftAmountTy()));
2807          Hi = DAG.getTruncStore(Tmp1, Hi, Tmp2, ST->getSrcValue(),
2808                                 SVOffset + IncrementSize, ExtraVT, isVolatile,
2809                                 MinAlign(Alignment, IncrementSize));
2810        } else {
2811          // Big endian - avoid unaligned stores.
2812          // TRUNCSTORE:i24 X -> TRUNCSTORE:i16 (srl X, 8), TRUNCSTORE@+2:i8 X
2813          // Store the top RoundWidth bits.
2814          Hi = DAG.getNode(ISD::SRL, Tmp3.getValueType(), Tmp3,
2815                           DAG.getConstant(ExtraWidth, TLI.getShiftAmountTy()));
2816          Hi = DAG.getTruncStore(Tmp1, Hi, Tmp2, ST->getSrcValue(), SVOffset,
2817                                 RoundVT, isVolatile, Alignment);
2818
2819          // Store the remaining ExtraWidth bits.
2820          IncrementSize = RoundWidth / 8;
2821          Tmp2 = DAG.getNode(ISD::ADD, Tmp2.getValueType(), Tmp2,
2822                             DAG.getIntPtrConstant(IncrementSize));
2823          Lo = DAG.getTruncStore(Tmp1, Tmp3, Tmp2, ST->getSrcValue(),
2824                                 SVOffset + IncrementSize, ExtraVT, isVolatile,
2825                                 MinAlign(Alignment, IncrementSize));
2826        }
2827
2828        // The order of the stores doesn't matter.
2829        Result = DAG.getNode(ISD::TokenFactor, MVT::Other, Lo, Hi);
2830      } else {
2831        if (Tmp1 != ST->getChain() || Tmp3 != ST->getValue() ||
2832            Tmp2 != ST->getBasePtr())
2833          Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp3, Tmp2,
2834                                          ST->getOffset());
2835
2836        switch (TLI.getTruncStoreAction(ST->getValue().getValueType(), StVT)) {
2837        default: assert(0 && "This action is not supported yet!");
2838        case TargetLowering::Legal:
2839          // If this is an unaligned store and the target doesn't support it,
2840          // expand it.
2841          if (!TLI.allowsUnalignedMemoryAccesses()) {
2842            unsigned ABIAlignment = TLI.getTargetData()->
2843              getABITypeAlignment(ST->getMemoryVT().getTypeForMVT());
2844            if (ST->getAlignment() < ABIAlignment)
2845              Result = ExpandUnalignedStore(cast<StoreSDNode>(Result.getNode()), DAG,
2846                                            TLI);
2847          }
2848          break;
2849        case TargetLowering::Custom:
2850          Result = TLI.LowerOperation(Result, DAG);
2851          break;
2852        case Expand:
2853          // TRUNCSTORE:i16 i32 -> STORE i16
2854          assert(isTypeLegal(StVT) && "Do not know how to expand this store!");
2855          Tmp3 = DAG.getNode(ISD::TRUNCATE, StVT, Tmp3);
2856          Result = DAG.getStore(Tmp1, Tmp3, Tmp2, ST->getSrcValue(), SVOffset,
2857                                isVolatile, Alignment);
2858          break;
2859        }
2860      }
2861    }
2862    break;
2863  }
2864  case ISD::PCMARKER:
2865    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
2866    Result = DAG.UpdateNodeOperands(Result, Tmp1, Node->getOperand(1));
2867    break;
2868  case ISD::STACKSAVE:
2869    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
2870    Result = DAG.UpdateNodeOperands(Result, Tmp1);
2871    Tmp1 = Result.getValue(0);
2872    Tmp2 = Result.getValue(1);
2873
2874    switch (TLI.getOperationAction(ISD::STACKSAVE, MVT::Other)) {
2875    default: assert(0 && "This action is not supported yet!");
2876    case TargetLowering::Legal: break;
2877    case TargetLowering::Custom:
2878      Tmp3 = TLI.LowerOperation(Result, DAG);
2879      if (Tmp3.getNode()) {
2880        Tmp1 = LegalizeOp(Tmp3);
2881        Tmp2 = LegalizeOp(Tmp3.getValue(1));
2882      }
2883      break;
2884    case TargetLowering::Expand:
2885      // Expand to CopyFromReg if the target set
2886      // StackPointerRegisterToSaveRestore.
2887      if (unsigned SP = TLI.getStackPointerRegisterToSaveRestore()) {
2888        Tmp1 = DAG.getCopyFromReg(Result.getOperand(0), SP,
2889                                  Node->getValueType(0));
2890        Tmp2 = Tmp1.getValue(1);
2891      } else {
2892        Tmp1 = DAG.getNode(ISD::UNDEF, Node->getValueType(0));
2893        Tmp2 = Node->getOperand(0);
2894      }
2895      break;
2896    }
2897
2898    // Since stacksave produce two values, make sure to remember that we
2899    // legalized both of them.
2900    AddLegalizedOperand(SDValue(Node, 0), Tmp1);
2901    AddLegalizedOperand(SDValue(Node, 1), Tmp2);
2902    return Op.getResNo() ? Tmp2 : Tmp1;
2903
2904  case ISD::STACKRESTORE:
2905    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
2906    Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the pointer.
2907    Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
2908
2909    switch (TLI.getOperationAction(ISD::STACKRESTORE, MVT::Other)) {
2910    default: assert(0 && "This action is not supported yet!");
2911    case TargetLowering::Legal: break;
2912    case TargetLowering::Custom:
2913      Tmp1 = TLI.LowerOperation(Result, DAG);
2914      if (Tmp1.getNode()) Result = Tmp1;
2915      break;
2916    case TargetLowering::Expand:
2917      // Expand to CopyToReg if the target set
2918      // StackPointerRegisterToSaveRestore.
2919      if (unsigned SP = TLI.getStackPointerRegisterToSaveRestore()) {
2920        Result = DAG.getCopyToReg(Tmp1, SP, Tmp2);
2921      } else {
2922        Result = Tmp1;
2923      }
2924      break;
2925    }
2926    break;
2927
2928  case ISD::READCYCLECOUNTER:
2929    Tmp1 = LegalizeOp(Node->getOperand(0)); // Legalize the chain
2930    Result = DAG.UpdateNodeOperands(Result, Tmp1);
2931    switch (TLI.getOperationAction(ISD::READCYCLECOUNTER,
2932                                   Node->getValueType(0))) {
2933    default: assert(0 && "This action is not supported yet!");
2934    case TargetLowering::Legal:
2935      Tmp1 = Result.getValue(0);
2936      Tmp2 = Result.getValue(1);
2937      break;
2938    case TargetLowering::Custom:
2939      Result = TLI.LowerOperation(Result, DAG);
2940      Tmp1 = LegalizeOp(Result.getValue(0));
2941      Tmp2 = LegalizeOp(Result.getValue(1));
2942      break;
2943    }
2944
2945    // Since rdcc produce two values, make sure to remember that we legalized
2946    // both of them.
2947    AddLegalizedOperand(SDValue(Node, 0), Tmp1);
2948    AddLegalizedOperand(SDValue(Node, 1), Tmp2);
2949    return Result;
2950
2951  case ISD::SELECT:
2952    switch (getTypeAction(Node->getOperand(0).getValueType())) {
2953    case Expand: assert(0 && "It's impossible to expand bools");
2954    case Legal:
2955      Tmp1 = LegalizeOp(Node->getOperand(0)); // Legalize the condition.
2956      break;
2957    case Promote: {
2958      assert(!Node->getOperand(0).getValueType().isVector() && "not possible");
2959      Tmp1 = PromoteOp(Node->getOperand(0));  // Promote the condition.
2960      // Make sure the condition is either zero or one.
2961      unsigned BitWidth = Tmp1.getValueSizeInBits();
2962      if (!DAG.MaskedValueIsZero(Tmp1,
2963                                 APInt::getHighBitsSet(BitWidth, BitWidth-1)))
2964        Tmp1 = DAG.getZeroExtendInReg(Tmp1, MVT::i1);
2965      break;
2966    }
2967    }
2968    Tmp2 = LegalizeOp(Node->getOperand(1));   // TrueVal
2969    Tmp3 = LegalizeOp(Node->getOperand(2));   // FalseVal
2970
2971    Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3);
2972
2973    switch (TLI.getOperationAction(ISD::SELECT, Tmp2.getValueType())) {
2974    default: assert(0 && "This action is not supported yet!");
2975    case TargetLowering::Legal: break;
2976    case TargetLowering::Custom: {
2977      Tmp1 = TLI.LowerOperation(Result, DAG);
2978      if (Tmp1.getNode()) Result = Tmp1;
2979      break;
2980    }
2981    case TargetLowering::Expand:
2982      if (Tmp1.getOpcode() == ISD::SETCC) {
2983        Result = DAG.getSelectCC(Tmp1.getOperand(0), Tmp1.getOperand(1),
2984                              Tmp2, Tmp3,
2985                              cast<CondCodeSDNode>(Tmp1.getOperand(2))->get());
2986      } else {
2987        Result = DAG.getSelectCC(Tmp1,
2988                                 DAG.getConstant(0, Tmp1.getValueType()),
2989                                 Tmp2, Tmp3, ISD::SETNE);
2990      }
2991      break;
2992    case TargetLowering::Promote: {
2993      MVT NVT =
2994        TLI.getTypeToPromoteTo(ISD::SELECT, Tmp2.getValueType());
2995      unsigned ExtOp, TruncOp;
2996      if (Tmp2.getValueType().isVector()) {
2997        ExtOp   = ISD::BIT_CONVERT;
2998        TruncOp = ISD::BIT_CONVERT;
2999      } else if (Tmp2.getValueType().isInteger()) {
3000        ExtOp   = ISD::ANY_EXTEND;
3001        TruncOp = ISD::TRUNCATE;
3002      } else {
3003        ExtOp   = ISD::FP_EXTEND;
3004        TruncOp = ISD::FP_ROUND;
3005      }
3006      // Promote each of the values to the new type.
3007      Tmp2 = DAG.getNode(ExtOp, NVT, Tmp2);
3008      Tmp3 = DAG.getNode(ExtOp, NVT, Tmp3);
3009      // Perform the larger operation, then round down.
3010      Result = DAG.getNode(ISD::SELECT, NVT, Tmp1, Tmp2,Tmp3);
3011      if (TruncOp != ISD::FP_ROUND)
3012        Result = DAG.getNode(TruncOp, Node->getValueType(0), Result);
3013      else
3014        Result = DAG.getNode(TruncOp, Node->getValueType(0), Result,
3015                             DAG.getIntPtrConstant(0));
3016      break;
3017    }
3018    }
3019    break;
3020  case ISD::SELECT_CC: {
3021    Tmp1 = Node->getOperand(0);               // LHS
3022    Tmp2 = Node->getOperand(1);               // RHS
3023    Tmp3 = LegalizeOp(Node->getOperand(2));   // True
3024    Tmp4 = LegalizeOp(Node->getOperand(3));   // False
3025    SDValue CC = Node->getOperand(4);
3026
3027    LegalizeSetCC(TLI.getSetCCResultType(Tmp1), Tmp1, Tmp2, CC);
3028
3029    // If we didn't get both a LHS and RHS back from LegalizeSetCC,
3030    // the LHS is a legal SETCC itself.  In this case, we need to compare
3031    // the result against zero to select between true and false values.
3032    if (Tmp2.getNode() == 0) {
3033      Tmp2 = DAG.getConstant(0, Tmp1.getValueType());
3034      CC = DAG.getCondCode(ISD::SETNE);
3035    }
3036    Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3, Tmp4, CC);
3037
3038    // Everything is legal, see if we should expand this op or something.
3039    switch (TLI.getOperationAction(ISD::SELECT_CC, Tmp3.getValueType())) {
3040    default: assert(0 && "This action is not supported yet!");
3041    case TargetLowering::Legal: break;
3042    case TargetLowering::Custom:
3043      Tmp1 = TLI.LowerOperation(Result, DAG);
3044      if (Tmp1.getNode()) Result = Tmp1;
3045      break;
3046    }
3047    break;
3048  }
3049  case ISD::SETCC:
3050    Tmp1 = Node->getOperand(0);
3051    Tmp2 = Node->getOperand(1);
3052    Tmp3 = Node->getOperand(2);
3053    LegalizeSetCC(Node->getValueType(0), Tmp1, Tmp2, Tmp3);
3054
3055    // If we had to Expand the SetCC operands into a SELECT node, then it may
3056    // not always be possible to return a true LHS & RHS.  In this case, just
3057    // return the value we legalized, returned in the LHS
3058    if (Tmp2.getNode() == 0) {
3059      Result = Tmp1;
3060      break;
3061    }
3062
3063    switch (TLI.getOperationAction(ISD::SETCC, Tmp1.getValueType())) {
3064    default: assert(0 && "Cannot handle this action for SETCC yet!");
3065    case TargetLowering::Custom:
3066      isCustom = true;
3067      // FALLTHROUGH.
3068    case TargetLowering::Legal:
3069      Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3);
3070      if (isCustom) {
3071        Tmp4 = TLI.LowerOperation(Result, DAG);
3072        if (Tmp4.getNode()) Result = Tmp4;
3073      }
3074      break;
3075    case TargetLowering::Promote: {
3076      // First step, figure out the appropriate operation to use.
3077      // Allow SETCC to not be supported for all legal data types
3078      // Mostly this targets FP
3079      MVT NewInTy = Node->getOperand(0).getValueType();
3080      MVT OldVT = NewInTy; OldVT = OldVT;
3081
3082      // Scan for the appropriate larger type to use.
3083      while (1) {
3084        NewInTy = (MVT::SimpleValueType)(NewInTy.getSimpleVT()+1);
3085
3086        assert(NewInTy.isInteger() == OldVT.isInteger() &&
3087               "Fell off of the edge of the integer world");
3088        assert(NewInTy.isFloatingPoint() == OldVT.isFloatingPoint() &&
3089               "Fell off of the edge of the floating point world");
3090
3091        // If the target supports SETCC of this type, use it.
3092        if (TLI.isOperationLegal(ISD::SETCC, NewInTy))
3093          break;
3094      }
3095      if (NewInTy.isInteger())
3096        assert(0 && "Cannot promote Legal Integer SETCC yet");
3097      else {
3098        Tmp1 = DAG.getNode(ISD::FP_EXTEND, NewInTy, Tmp1);
3099        Tmp2 = DAG.getNode(ISD::FP_EXTEND, NewInTy, Tmp2);
3100      }
3101      Tmp1 = LegalizeOp(Tmp1);
3102      Tmp2 = LegalizeOp(Tmp2);
3103      Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3);
3104      Result = LegalizeOp(Result);
3105      break;
3106    }
3107    case TargetLowering::Expand:
3108      // Expand a setcc node into a select_cc of the same condition, lhs, and
3109      // rhs that selects between const 1 (true) and const 0 (false).
3110      MVT VT = Node->getValueType(0);
3111      Result = DAG.getNode(ISD::SELECT_CC, VT, Tmp1, Tmp2,
3112                           DAG.getConstant(1, VT), DAG.getConstant(0, VT),
3113                           Tmp3);
3114      break;
3115    }
3116    break;
3117  case ISD::VSETCC: {
3118    Tmp1 = LegalizeOp(Node->getOperand(0));   // LHS
3119    Tmp2 = LegalizeOp(Node->getOperand(1));   // RHS
3120    SDValue CC = Node->getOperand(2);
3121
3122    Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, CC);
3123
3124    // Everything is legal, see if we should expand this op or something.
3125    switch (TLI.getOperationAction(ISD::VSETCC, Tmp1.getValueType())) {
3126    default: assert(0 && "This action is not supported yet!");
3127    case TargetLowering::Legal: break;
3128    case TargetLowering::Custom:
3129      Tmp1 = TLI.LowerOperation(Result, DAG);
3130      if (Tmp1.getNode()) Result = Tmp1;
3131      break;
3132    case TargetLowering::Expand: {
3133      // Unroll into a nasty set of scalar code for now.
3134      MVT VT = Node->getValueType(0);
3135      unsigned NumElems = VT.getVectorNumElements();
3136      MVT EltVT = VT.getVectorElementType();
3137      MVT TmpEltVT = Tmp1.getValueType().getVectorElementType();
3138      SmallVector<SDValue, 8> Ops(NumElems);
3139      for (unsigned i = 0; i < NumElems; ++i) {
3140        SDValue In1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, TmpEltVT,
3141                                  Tmp1, DAG.getIntPtrConstant(i));
3142        Ops[i] = DAG.getNode(ISD::SETCC, TLI.getSetCCResultType(In1), In1,
3143                              DAG.getNode(ISD::EXTRACT_VECTOR_ELT, TmpEltVT,
3144                                          Tmp2, DAG.getIntPtrConstant(i)),
3145                              CC);
3146        Ops[i] = DAG.getNode(ISD::SIGN_EXTEND, EltVT, Ops[i]);
3147      }
3148      Result = DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], NumElems);
3149      break;
3150    }
3151    }
3152    break;
3153  }
3154
3155  case ISD::SHL_PARTS:
3156  case ISD::SRA_PARTS:
3157  case ISD::SRL_PARTS: {
3158    SmallVector<SDValue, 8> Ops;
3159    bool Changed = false;
3160    for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) {
3161      Ops.push_back(LegalizeOp(Node->getOperand(i)));
3162      Changed |= Ops.back() != Node->getOperand(i);
3163    }
3164    if (Changed)
3165      Result = DAG.UpdateNodeOperands(Result, &Ops[0], Ops.size());
3166
3167    switch (TLI.getOperationAction(Node->getOpcode(),
3168                                   Node->getValueType(0))) {
3169    default: assert(0 && "This action is not supported yet!");
3170    case TargetLowering::Legal: break;
3171    case TargetLowering::Custom:
3172      Tmp1 = TLI.LowerOperation(Result, DAG);
3173      if (Tmp1.getNode()) {
3174        SDValue Tmp2, RetVal(0, 0);
3175        for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i) {
3176          Tmp2 = LegalizeOp(Tmp1.getValue(i));
3177          AddLegalizedOperand(SDValue(Node, i), Tmp2);
3178          if (i == Op.getResNo())
3179            RetVal = Tmp2;
3180        }
3181        assert(RetVal.getNode() && "Illegal result number");
3182        return RetVal;
3183      }
3184      break;
3185    }
3186
3187    // Since these produce multiple values, make sure to remember that we
3188    // legalized all of them.
3189    for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
3190      AddLegalizedOperand(SDValue(Node, i), Result.getValue(i));
3191    return Result.getValue(Op.getResNo());
3192  }
3193
3194    // Binary operators
3195  case ISD::ADD:
3196  case ISD::SUB:
3197  case ISD::MUL:
3198  case ISD::MULHS:
3199  case ISD::MULHU:
3200  case ISD::UDIV:
3201  case ISD::SDIV:
3202  case ISD::AND:
3203  case ISD::OR:
3204  case ISD::XOR:
3205  case ISD::SHL:
3206  case ISD::SRL:
3207  case ISD::SRA:
3208  case ISD::FADD:
3209  case ISD::FSUB:
3210  case ISD::FMUL:
3211  case ISD::FDIV:
3212  case ISD::FPOW:
3213    Tmp1 = LegalizeOp(Node->getOperand(0));   // LHS
3214    switch (getTypeAction(Node->getOperand(1).getValueType())) {
3215    case Expand: assert(0 && "Not possible");
3216    case Legal:
3217      Tmp2 = LegalizeOp(Node->getOperand(1)); // Legalize the RHS.
3218      break;
3219    case Promote:
3220      Tmp2 = PromoteOp(Node->getOperand(1));  // Promote the RHS.
3221      break;
3222    }
3223
3224    if ((Node->getOpcode() == ISD::SHL ||
3225         Node->getOpcode() == ISD::SRL ||
3226         Node->getOpcode() == ISD::SRA) &&
3227        !Node->getValueType(0).isVector()) {
3228      Tmp2 = LegalizeShiftAmount(Tmp2);
3229    }
3230
3231    Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
3232
3233    switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
3234    default: assert(0 && "BinOp legalize operation not supported");
3235    case TargetLowering::Legal: break;
3236    case TargetLowering::Custom:
3237      Tmp1 = TLI.LowerOperation(Result, DAG);
3238      if (Tmp1.getNode()) {
3239        Result = Tmp1;
3240        break;
3241      }
3242      // Fall through if the custom lower can't deal with the operation
3243    case TargetLowering::Expand: {
3244      MVT VT = Op.getValueType();
3245
3246      // See if multiply or divide can be lowered using two-result operations.
3247      SDVTList VTs = DAG.getVTList(VT, VT);
3248      if (Node->getOpcode() == ISD::MUL) {
3249        // We just need the low half of the multiply; try both the signed
3250        // and unsigned forms. If the target supports both SMUL_LOHI and
3251        // UMUL_LOHI, form a preference by checking which forms of plain
3252        // MULH it supports.
3253        bool HasSMUL_LOHI = TLI.isOperationLegal(ISD::SMUL_LOHI, VT);
3254        bool HasUMUL_LOHI = TLI.isOperationLegal(ISD::UMUL_LOHI, VT);
3255        bool HasMULHS = TLI.isOperationLegal(ISD::MULHS, VT);
3256        bool HasMULHU = TLI.isOperationLegal(ISD::MULHU, VT);
3257        unsigned OpToUse = 0;
3258        if (HasSMUL_LOHI && !HasMULHS) {
3259          OpToUse = ISD::SMUL_LOHI;
3260        } else if (HasUMUL_LOHI && !HasMULHU) {
3261          OpToUse = ISD::UMUL_LOHI;
3262        } else if (HasSMUL_LOHI) {
3263          OpToUse = ISD::SMUL_LOHI;
3264        } else if (HasUMUL_LOHI) {
3265          OpToUse = ISD::UMUL_LOHI;
3266        }
3267        if (OpToUse) {
3268          Result = SDValue(DAG.getNode(OpToUse, VTs, Tmp1, Tmp2).getNode(), 0);
3269          break;
3270        }
3271      }
3272      if (Node->getOpcode() == ISD::MULHS &&
3273          TLI.isOperationLegal(ISD::SMUL_LOHI, VT)) {
3274        Result = SDValue(DAG.getNode(ISD::SMUL_LOHI, VTs, Tmp1, Tmp2).getNode(),
3275                         1);
3276        break;
3277      }
3278      if (Node->getOpcode() == ISD::MULHU &&
3279          TLI.isOperationLegal(ISD::UMUL_LOHI, VT)) {
3280        Result = SDValue(DAG.getNode(ISD::UMUL_LOHI, VTs, Tmp1, Tmp2).getNode(),
3281                         1);
3282        break;
3283      }
3284      if (Node->getOpcode() == ISD::SDIV &&
3285          TLI.isOperationLegal(ISD::SDIVREM, VT)) {
3286        Result = SDValue(DAG.getNode(ISD::SDIVREM, VTs, Tmp1, Tmp2).getNode(),
3287                         0);
3288        break;
3289      }
3290      if (Node->getOpcode() == ISD::UDIV &&
3291          TLI.isOperationLegal(ISD::UDIVREM, VT)) {
3292        Result = SDValue(DAG.getNode(ISD::UDIVREM, VTs, Tmp1, Tmp2).getNode(),
3293                         0);
3294        break;
3295      }
3296
3297      // Check to see if we have a libcall for this operator.
3298      RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
3299      bool isSigned = false;
3300      switch (Node->getOpcode()) {
3301      case ISD::UDIV:
3302      case ISD::SDIV:
3303        if (VT == MVT::i32) {
3304          LC = Node->getOpcode() == ISD::UDIV
3305               ? RTLIB::UDIV_I32 : RTLIB::SDIV_I32;
3306          isSigned = Node->getOpcode() == ISD::SDIV;
3307        }
3308        break;
3309      case ISD::MUL:
3310        if (VT == MVT::i32)
3311          LC = RTLIB::MUL_I32;
3312        break;
3313      case ISD::FPOW:
3314        LC = GetFPLibCall(VT, RTLIB::POW_F32, RTLIB::POW_F64, RTLIB::POW_F80,
3315                          RTLIB::POW_PPCF128);
3316        break;
3317      default: break;
3318      }
3319      if (LC != RTLIB::UNKNOWN_LIBCALL) {
3320        SDValue Dummy;
3321        Result = ExpandLibCall(LC, Node, isSigned, Dummy);
3322        break;
3323      }
3324
3325      assert(Node->getValueType(0).isVector() &&
3326             "Cannot expand this binary operator!");
3327      // Expand the operation into a bunch of nasty scalar code.
3328      Result = LegalizeOp(UnrollVectorOp(Op));
3329      break;
3330    }
3331    case TargetLowering::Promote: {
3332      switch (Node->getOpcode()) {
3333      default:  assert(0 && "Do not know how to promote this BinOp!");
3334      case ISD::AND:
3335      case ISD::OR:
3336      case ISD::XOR: {
3337        MVT OVT = Node->getValueType(0);
3338        MVT NVT = TLI.getTypeToPromoteTo(Node->getOpcode(), OVT);
3339        assert(OVT.isVector() && "Cannot promote this BinOp!");
3340        // Bit convert each of the values to the new type.
3341        Tmp1 = DAG.getNode(ISD::BIT_CONVERT, NVT, Tmp1);
3342        Tmp2 = DAG.getNode(ISD::BIT_CONVERT, NVT, Tmp2);
3343        Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1, Tmp2);
3344        // Bit convert the result back the original type.
3345        Result = DAG.getNode(ISD::BIT_CONVERT, OVT, Result);
3346        break;
3347      }
3348      }
3349    }
3350    }
3351    break;
3352
3353  case ISD::SMUL_LOHI:
3354  case ISD::UMUL_LOHI:
3355  case ISD::SDIVREM:
3356  case ISD::UDIVREM:
3357    // These nodes will only be produced by target-specific lowering, so
3358    // they shouldn't be here if they aren't legal.
3359    assert(TLI.isOperationLegal(Node->getOpcode(), Node->getValueType(0)) &&
3360           "This must be legal!");
3361
3362    Tmp1 = LegalizeOp(Node->getOperand(0));   // LHS
3363    Tmp2 = LegalizeOp(Node->getOperand(1));   // RHS
3364    Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
3365    break;
3366
3367  case ISD::FCOPYSIGN:  // FCOPYSIGN does not require LHS/RHS to match type!
3368    Tmp1 = LegalizeOp(Node->getOperand(0));   // LHS
3369    switch (getTypeAction(Node->getOperand(1).getValueType())) {
3370      case Expand: assert(0 && "Not possible");
3371      case Legal:
3372        Tmp2 = LegalizeOp(Node->getOperand(1)); // Legalize the RHS.
3373        break;
3374      case Promote:
3375        Tmp2 = PromoteOp(Node->getOperand(1));  // Promote the RHS.
3376        break;
3377    }
3378
3379    Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
3380
3381    switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
3382    default: assert(0 && "Operation not supported");
3383    case TargetLowering::Custom:
3384      Tmp1 = TLI.LowerOperation(Result, DAG);
3385      if (Tmp1.getNode()) Result = Tmp1;
3386      break;
3387    case TargetLowering::Legal: break;
3388    case TargetLowering::Expand: {
3389      // If this target supports fabs/fneg natively and select is cheap,
3390      // do this efficiently.
3391      if (!TLI.isSelectExpensive() &&
3392          TLI.getOperationAction(ISD::FABS, Tmp1.getValueType()) ==
3393          TargetLowering::Legal &&
3394          TLI.getOperationAction(ISD::FNEG, Tmp1.getValueType()) ==
3395          TargetLowering::Legal) {
3396        // Get the sign bit of the RHS.
3397        MVT IVT =
3398          Tmp2.getValueType() == MVT::f32 ? MVT::i32 : MVT::i64;
3399        SDValue SignBit = DAG.getNode(ISD::BIT_CONVERT, IVT, Tmp2);
3400        SignBit = DAG.getSetCC(TLI.getSetCCResultType(SignBit),
3401                               SignBit, DAG.getConstant(0, IVT), ISD::SETLT);
3402        // Get the absolute value of the result.
3403        SDValue AbsVal = DAG.getNode(ISD::FABS, Tmp1.getValueType(), Tmp1);
3404        // Select between the nabs and abs value based on the sign bit of
3405        // the input.
3406        Result = DAG.getNode(ISD::SELECT, AbsVal.getValueType(), SignBit,
3407                             DAG.getNode(ISD::FNEG, AbsVal.getValueType(),
3408                                         AbsVal),
3409                             AbsVal);
3410        Result = LegalizeOp(Result);
3411        break;
3412      }
3413
3414      // Otherwise, do bitwise ops!
3415      MVT NVT =
3416        Node->getValueType(0) == MVT::f32 ? MVT::i32 : MVT::i64;
3417      Result = ExpandFCOPYSIGNToBitwiseOps(Node, NVT, DAG, TLI);
3418      Result = DAG.getNode(ISD::BIT_CONVERT, Node->getValueType(0), Result);
3419      Result = LegalizeOp(Result);
3420      break;
3421    }
3422    }
3423    break;
3424
3425  case ISD::ADDC:
3426  case ISD::SUBC:
3427    Tmp1 = LegalizeOp(Node->getOperand(0));
3428    Tmp2 = LegalizeOp(Node->getOperand(1));
3429    Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
3430    Tmp3 = Result.getValue(0);
3431    Tmp4 = Result.getValue(1);
3432
3433    switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
3434    default: assert(0 && "This action is not supported yet!");
3435    case TargetLowering::Legal:
3436      break;
3437    case TargetLowering::Custom:
3438      Tmp1 = TLI.LowerOperation(Tmp3, DAG);
3439      if (Tmp1.getNode() != NULL) {
3440        Tmp3 = LegalizeOp(Tmp1);
3441        Tmp4 = LegalizeOp(Tmp1.getValue(1));
3442      }
3443      break;
3444    }
3445    // Since this produces two values, make sure to remember that we legalized
3446    // both of them.
3447    AddLegalizedOperand(SDValue(Node, 0), Tmp3);
3448    AddLegalizedOperand(SDValue(Node, 1), Tmp4);
3449    return Op.getResNo() ? Tmp4 : Tmp3;
3450
3451  case ISD::ADDE:
3452  case ISD::SUBE:
3453    Tmp1 = LegalizeOp(Node->getOperand(0));
3454    Tmp2 = LegalizeOp(Node->getOperand(1));
3455    Tmp3 = LegalizeOp(Node->getOperand(2));
3456    Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3);
3457    Tmp3 = Result.getValue(0);
3458    Tmp4 = Result.getValue(1);
3459
3460    switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
3461    default: assert(0 && "This action is not supported yet!");
3462    case TargetLowering::Legal:
3463      break;
3464    case TargetLowering::Custom:
3465      Tmp1 = TLI.LowerOperation(Tmp3, DAG);
3466      if (Tmp1.getNode() != NULL) {
3467        Tmp3 = LegalizeOp(Tmp1);
3468        Tmp4 = LegalizeOp(Tmp1.getValue(1));
3469      }
3470      break;
3471    }
3472    // Since this produces two values, make sure to remember that we legalized
3473    // both of them.
3474    AddLegalizedOperand(SDValue(Node, 0), Tmp3);
3475    AddLegalizedOperand(SDValue(Node, 1), Tmp4);
3476    return Op.getResNo() ? Tmp4 : Tmp3;
3477
3478  case ISD::BUILD_PAIR: {
3479    MVT PairTy = Node->getValueType(0);
3480    // TODO: handle the case where the Lo and Hi operands are not of legal type
3481    Tmp1 = LegalizeOp(Node->getOperand(0));   // Lo
3482    Tmp2 = LegalizeOp(Node->getOperand(1));   // Hi
3483    switch (TLI.getOperationAction(ISD::BUILD_PAIR, PairTy)) {
3484    case TargetLowering::Promote:
3485    case TargetLowering::Custom:
3486      assert(0 && "Cannot promote/custom this yet!");
3487    case TargetLowering::Legal:
3488      if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1))
3489        Result = DAG.getNode(ISD::BUILD_PAIR, PairTy, Tmp1, Tmp2);
3490      break;
3491    case TargetLowering::Expand:
3492      Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, PairTy, Tmp1);
3493      Tmp2 = DAG.getNode(ISD::ANY_EXTEND, PairTy, Tmp2);
3494      Tmp2 = DAG.getNode(ISD::SHL, PairTy, Tmp2,
3495                         DAG.getConstant(PairTy.getSizeInBits()/2,
3496                                         TLI.getShiftAmountTy()));
3497      Result = DAG.getNode(ISD::OR, PairTy, Tmp1, Tmp2);
3498      break;
3499    }
3500    break;
3501  }
3502
3503  case ISD::UREM:
3504  case ISD::SREM:
3505  case ISD::FREM:
3506    Tmp1 = LegalizeOp(Node->getOperand(0));   // LHS
3507    Tmp2 = LegalizeOp(Node->getOperand(1));   // RHS
3508
3509    switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
3510    case TargetLowering::Promote: assert(0 && "Cannot promote this yet!");
3511    case TargetLowering::Custom:
3512      isCustom = true;
3513      // FALLTHROUGH
3514    case TargetLowering::Legal:
3515      Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
3516      if (isCustom) {
3517        Tmp1 = TLI.LowerOperation(Result, DAG);
3518        if (Tmp1.getNode()) Result = Tmp1;
3519      }
3520      break;
3521    case TargetLowering::Expand: {
3522      unsigned DivOpc= (Node->getOpcode() == ISD::UREM) ? ISD::UDIV : ISD::SDIV;
3523      bool isSigned = DivOpc == ISD::SDIV;
3524      MVT VT = Node->getValueType(0);
3525
3526      // See if remainder can be lowered using two-result operations.
3527      SDVTList VTs = DAG.getVTList(VT, VT);
3528      if (Node->getOpcode() == ISD::SREM &&
3529          TLI.isOperationLegal(ISD::SDIVREM, VT)) {
3530        Result = SDValue(DAG.getNode(ISD::SDIVREM, VTs, Tmp1, Tmp2).getNode(), 1);
3531        break;
3532      }
3533      if (Node->getOpcode() == ISD::UREM &&
3534          TLI.isOperationLegal(ISD::UDIVREM, VT)) {
3535        Result = SDValue(DAG.getNode(ISD::UDIVREM, VTs, Tmp1, Tmp2).getNode(), 1);
3536        break;
3537      }
3538
3539      if (VT.isInteger()) {
3540        if (TLI.getOperationAction(DivOpc, VT) ==
3541            TargetLowering::Legal) {
3542          // X % Y -> X-X/Y*Y
3543          Result = DAG.getNode(DivOpc, VT, Tmp1, Tmp2);
3544          Result = DAG.getNode(ISD::MUL, VT, Result, Tmp2);
3545          Result = DAG.getNode(ISD::SUB, VT, Tmp1, Result);
3546        } else if (VT.isVector()) {
3547          Result = LegalizeOp(UnrollVectorOp(Op));
3548        } else {
3549          assert(VT == MVT::i32 &&
3550                 "Cannot expand this binary operator!");
3551          RTLIB::Libcall LC = Node->getOpcode() == ISD::UREM
3552            ? RTLIB::UREM_I32 : RTLIB::SREM_I32;
3553          SDValue Dummy;
3554          Result = ExpandLibCall(LC, Node, isSigned, Dummy);
3555        }
3556      } else {
3557        assert(VT.isFloatingPoint() &&
3558               "remainder op must have integer or floating-point type");
3559        if (VT.isVector()) {
3560          Result = LegalizeOp(UnrollVectorOp(Op));
3561        } else {
3562          // Floating point mod -> fmod libcall.
3563          RTLIB::Libcall LC = GetFPLibCall(VT, RTLIB::REM_F32, RTLIB::REM_F64,
3564                                           RTLIB::REM_F80, RTLIB::REM_PPCF128);
3565          SDValue Dummy;
3566          Result = ExpandLibCall(LC, Node, false/*sign irrelevant*/, Dummy);
3567        }
3568      }
3569      break;
3570    }
3571    }
3572    break;
3573  case ISD::VAARG: {
3574    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
3575    Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the pointer.
3576
3577    MVT VT = Node->getValueType(0);
3578    switch (TLI.getOperationAction(Node->getOpcode(), MVT::Other)) {
3579    default: assert(0 && "This action is not supported yet!");
3580    case TargetLowering::Custom:
3581      isCustom = true;
3582      // FALLTHROUGH
3583    case TargetLowering::Legal:
3584      Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Node->getOperand(2));
3585      Result = Result.getValue(0);
3586      Tmp1 = Result.getValue(1);
3587
3588      if (isCustom) {
3589        Tmp2 = TLI.LowerOperation(Result, DAG);
3590        if (Tmp2.getNode()) {
3591          Result = LegalizeOp(Tmp2);
3592          Tmp1 = LegalizeOp(Tmp2.getValue(1));
3593        }
3594      }
3595      break;
3596    case TargetLowering::Expand: {
3597      const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
3598      SDValue VAList = DAG.getLoad(TLI.getPointerTy(), Tmp1, Tmp2, V, 0);
3599      // Increment the pointer, VAList, to the next vaarg
3600      Tmp3 = DAG.getNode(ISD::ADD, TLI.getPointerTy(), VAList,
3601        DAG.getConstant(TLI.getTargetData()->getABITypeSize(VT.getTypeForMVT()),
3602                        TLI.getPointerTy()));
3603      // Store the incremented VAList to the legalized pointer
3604      Tmp3 = DAG.getStore(VAList.getValue(1), Tmp3, Tmp2, V, 0);
3605      // Load the actual argument out of the pointer VAList
3606      Result = DAG.getLoad(VT, Tmp3, VAList, NULL, 0);
3607      Tmp1 = LegalizeOp(Result.getValue(1));
3608      Result = LegalizeOp(Result);
3609      break;
3610    }
3611    }
3612    // Since VAARG produces two values, make sure to remember that we
3613    // legalized both of them.
3614    AddLegalizedOperand(SDValue(Node, 0), Result);
3615    AddLegalizedOperand(SDValue(Node, 1), Tmp1);
3616    return Op.getResNo() ? Tmp1 : Result;
3617  }
3618
3619  case ISD::VACOPY:
3620    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
3621    Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the dest pointer.
3622    Tmp3 = LegalizeOp(Node->getOperand(2));  // Legalize the source pointer.
3623
3624    switch (TLI.getOperationAction(ISD::VACOPY, MVT::Other)) {
3625    default: assert(0 && "This action is not supported yet!");
3626    case TargetLowering::Custom:
3627      isCustom = true;
3628      // FALLTHROUGH
3629    case TargetLowering::Legal:
3630      Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3,
3631                                      Node->getOperand(3), Node->getOperand(4));
3632      if (isCustom) {
3633        Tmp1 = TLI.LowerOperation(Result, DAG);
3634        if (Tmp1.getNode()) Result = Tmp1;
3635      }
3636      break;
3637    case TargetLowering::Expand:
3638      // This defaults to loading a pointer from the input and storing it to the
3639      // output, returning the chain.
3640      const Value *VD = cast<SrcValueSDNode>(Node->getOperand(3))->getValue();
3641      const Value *VS = cast<SrcValueSDNode>(Node->getOperand(4))->getValue();
3642      Tmp4 = DAG.getLoad(TLI.getPointerTy(), Tmp1, Tmp3, VS, 0);
3643      Result = DAG.getStore(Tmp4.getValue(1), Tmp4, Tmp2, VD, 0);
3644      break;
3645    }
3646    break;
3647
3648  case ISD::VAEND:
3649    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
3650    Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the pointer.
3651
3652    switch (TLI.getOperationAction(ISD::VAEND, MVT::Other)) {
3653    default: assert(0 && "This action is not supported yet!");
3654    case TargetLowering::Custom:
3655      isCustom = true;
3656      // FALLTHROUGH
3657    case TargetLowering::Legal:
3658      Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Node->getOperand(2));
3659      if (isCustom) {
3660        Tmp1 = TLI.LowerOperation(Tmp1, DAG);
3661        if (Tmp1.getNode()) Result = Tmp1;
3662      }
3663      break;
3664    case TargetLowering::Expand:
3665      Result = Tmp1; // Default to a no-op, return the chain
3666      break;
3667    }
3668    break;
3669
3670  case ISD::VASTART:
3671    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
3672    Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the pointer.
3673
3674    Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Node->getOperand(2));
3675
3676    switch (TLI.getOperationAction(ISD::VASTART, MVT::Other)) {
3677    default: assert(0 && "This action is not supported yet!");
3678    case TargetLowering::Legal: break;
3679    case TargetLowering::Custom:
3680      Tmp1 = TLI.LowerOperation(Result, DAG);
3681      if (Tmp1.getNode()) Result = Tmp1;
3682      break;
3683    }
3684    break;
3685
3686  case ISD::ROTL:
3687  case ISD::ROTR:
3688    Tmp1 = LegalizeOp(Node->getOperand(0));   // LHS
3689    Tmp2 = LegalizeOp(Node->getOperand(1));   // RHS
3690    Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
3691    switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
3692    default:
3693      assert(0 && "ROTL/ROTR legalize operation not supported");
3694      break;
3695    case TargetLowering::Legal:
3696      break;
3697    case TargetLowering::Custom:
3698      Tmp1 = TLI.LowerOperation(Result, DAG);
3699      if (Tmp1.getNode()) Result = Tmp1;
3700      break;
3701    case TargetLowering::Promote:
3702      assert(0 && "Do not know how to promote ROTL/ROTR");
3703      break;
3704    case TargetLowering::Expand:
3705      assert(0 && "Do not know how to expand ROTL/ROTR");
3706      break;
3707    }
3708    break;
3709
3710  case ISD::BSWAP:
3711    Tmp1 = LegalizeOp(Node->getOperand(0));   // Op
3712    switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
3713    case TargetLowering::Custom:
3714      assert(0 && "Cannot custom legalize this yet!");
3715    case TargetLowering::Legal:
3716      Result = DAG.UpdateNodeOperands(Result, Tmp1);
3717      break;
3718    case TargetLowering::Promote: {
3719      MVT OVT = Tmp1.getValueType();
3720      MVT NVT = TLI.getTypeToPromoteTo(Node->getOpcode(), OVT);
3721      unsigned DiffBits = NVT.getSizeInBits() - OVT.getSizeInBits();
3722
3723      Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, NVT, Tmp1);
3724      Tmp1 = DAG.getNode(ISD::BSWAP, NVT, Tmp1);
3725      Result = DAG.getNode(ISD::SRL, NVT, Tmp1,
3726                           DAG.getConstant(DiffBits, TLI.getShiftAmountTy()));
3727      break;
3728    }
3729    case TargetLowering::Expand:
3730      Result = ExpandBSWAP(Tmp1);
3731      break;
3732    }
3733    break;
3734
3735  case ISD::CTPOP:
3736  case ISD::CTTZ:
3737  case ISD::CTLZ:
3738    Tmp1 = LegalizeOp(Node->getOperand(0));   // Op
3739    switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
3740    case TargetLowering::Custom:
3741    case TargetLowering::Legal:
3742      Result = DAG.UpdateNodeOperands(Result, Tmp1);
3743      if (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0)) ==
3744          TargetLowering::Custom) {
3745        Tmp1 = TLI.LowerOperation(Result, DAG);
3746        if (Tmp1.getNode()) {
3747          Result = Tmp1;
3748        }
3749      }
3750      break;
3751    case TargetLowering::Promote: {
3752      MVT OVT = Tmp1.getValueType();
3753      MVT NVT = TLI.getTypeToPromoteTo(Node->getOpcode(), OVT);
3754
3755      // Zero extend the argument.
3756      Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, NVT, Tmp1);
3757      // Perform the larger operation, then subtract if needed.
3758      Tmp1 = DAG.getNode(Node->getOpcode(), Node->getValueType(0), Tmp1);
3759      switch (Node->getOpcode()) {
3760      case ISD::CTPOP:
3761        Result = Tmp1;
3762        break;
3763      case ISD::CTTZ:
3764        //if Tmp1 == sizeinbits(NVT) then Tmp1 = sizeinbits(Old VT)
3765        Tmp2 = DAG.getSetCC(TLI.getSetCCResultType(Tmp1), Tmp1,
3766                            DAG.getConstant(NVT.getSizeInBits(), NVT),
3767                            ISD::SETEQ);
3768        Result = DAG.getNode(ISD::SELECT, NVT, Tmp2,
3769                             DAG.getConstant(OVT.getSizeInBits(), NVT), Tmp1);
3770        break;
3771      case ISD::CTLZ:
3772        // Tmp1 = Tmp1 - (sizeinbits(NVT) - sizeinbits(Old VT))
3773        Result = DAG.getNode(ISD::SUB, NVT, Tmp1,
3774                             DAG.getConstant(NVT.getSizeInBits() -
3775                                             OVT.getSizeInBits(), NVT));
3776        break;
3777      }
3778      break;
3779    }
3780    case TargetLowering::Expand:
3781      Result = ExpandBitCount(Node->getOpcode(), Tmp1);
3782      break;
3783    }
3784    break;
3785
3786    // Unary operators
3787  case ISD::FABS:
3788  case ISD::FNEG:
3789  case ISD::FSQRT:
3790  case ISD::FSIN:
3791  case ISD::FCOS:
3792  case ISD::FLOG:
3793  case ISD::FLOG2:
3794  case ISD::FLOG10:
3795  case ISD::FEXP:
3796  case ISD::FEXP2:
3797  case ISD::FTRUNC:
3798  case ISD::FFLOOR:
3799  case ISD::FCEIL:
3800  case ISD::FRINT:
3801  case ISD::FNEARBYINT:
3802    Tmp1 = LegalizeOp(Node->getOperand(0));
3803    switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
3804    case TargetLowering::Promote:
3805    case TargetLowering::Custom:
3806     isCustom = true;
3807     // FALLTHROUGH
3808    case TargetLowering::Legal:
3809      Result = DAG.UpdateNodeOperands(Result, Tmp1);
3810      if (isCustom) {
3811        Tmp1 = TLI.LowerOperation(Result, DAG);
3812        if (Tmp1.getNode()) Result = Tmp1;
3813      }
3814      break;
3815    case TargetLowering::Expand:
3816      switch (Node->getOpcode()) {
3817      default: assert(0 && "Unreachable!");
3818      case ISD::FNEG:
3819        // Expand Y = FNEG(X) ->  Y = SUB -0.0, X
3820        Tmp2 = DAG.getConstantFP(-0.0, Node->getValueType(0));
3821        Result = DAG.getNode(ISD::FSUB, Node->getValueType(0), Tmp2, Tmp1);
3822        break;
3823      case ISD::FABS: {
3824        // Expand Y = FABS(X) -> Y = (X >u 0.0) ? X : fneg(X).
3825        MVT VT = Node->getValueType(0);
3826        Tmp2 = DAG.getConstantFP(0.0, VT);
3827        Tmp2 = DAG.getSetCC(TLI.getSetCCResultType(Tmp1), Tmp1, Tmp2,
3828                            ISD::SETUGT);
3829        Tmp3 = DAG.getNode(ISD::FNEG, VT, Tmp1);
3830        Result = DAG.getNode(ISD::SELECT, VT, Tmp2, Tmp1, Tmp3);
3831        break;
3832      }
3833      case ISD::FSQRT:
3834      case ISD::FSIN:
3835      case ISD::FCOS:
3836      case ISD::FLOG:
3837      case ISD::FLOG2:
3838      case ISD::FLOG10:
3839      case ISD::FEXP:
3840      case ISD::FEXP2:
3841      case ISD::FTRUNC:
3842      case ISD::FFLOOR:
3843      case ISD::FCEIL:
3844      case ISD::FRINT:
3845      case ISD::FNEARBYINT: {
3846        MVT VT = Node->getValueType(0);
3847
3848        // Expand unsupported unary vector operators by unrolling them.
3849        if (VT.isVector()) {
3850          Result = LegalizeOp(UnrollVectorOp(Op));
3851          break;
3852        }
3853
3854        RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
3855        switch(Node->getOpcode()) {
3856        case ISD::FSQRT:
3857          LC = GetFPLibCall(VT, RTLIB::SQRT_F32, RTLIB::SQRT_F64,
3858                            RTLIB::SQRT_F80, RTLIB::SQRT_PPCF128);
3859          break;
3860        case ISD::FSIN:
3861          LC = GetFPLibCall(VT, RTLIB::SIN_F32, RTLIB::SIN_F64,
3862                            RTLIB::SIN_F80, RTLIB::SIN_PPCF128);
3863          break;
3864        case ISD::FCOS:
3865          LC = GetFPLibCall(VT, RTLIB::COS_F32, RTLIB::COS_F64,
3866                            RTLIB::COS_F80, RTLIB::COS_PPCF128);
3867          break;
3868        case ISD::FLOG:
3869          LC = GetFPLibCall(VT, RTLIB::LOG_F32, RTLIB::LOG_F64,
3870                            RTLIB::LOG_F80, RTLIB::LOG_PPCF128);
3871          break;
3872        case ISD::FLOG2:
3873          LC = GetFPLibCall(VT, RTLIB::LOG2_F32, RTLIB::LOG2_F64,
3874                            RTLIB::LOG2_F80, RTLIB::LOG2_PPCF128);
3875          break;
3876        case ISD::FLOG10:
3877          LC = GetFPLibCall(VT, RTLIB::LOG10_F32, RTLIB::LOG10_F64,
3878                            RTLIB::LOG10_F80, RTLIB::LOG10_PPCF128);
3879          break;
3880        case ISD::FEXP:
3881          LC = GetFPLibCall(VT, RTLIB::EXP_F32, RTLIB::EXP_F64,
3882                            RTLIB::EXP_F80, RTLIB::EXP_PPCF128);
3883          break;
3884        case ISD::FEXP2:
3885          LC = GetFPLibCall(VT, RTLIB::EXP2_F32, RTLIB::EXP2_F64,
3886                            RTLIB::EXP2_F80, RTLIB::EXP2_PPCF128);
3887          break;
3888        case ISD::FTRUNC:
3889          LC = GetFPLibCall(VT, RTLIB::TRUNC_F32, RTLIB::TRUNC_F64,
3890                            RTLIB::TRUNC_F80, RTLIB::TRUNC_PPCF128);
3891          break;
3892        case ISD::FFLOOR:
3893          LC = GetFPLibCall(VT, RTLIB::FLOOR_F32, RTLIB::FLOOR_F64,
3894                            RTLIB::FLOOR_F80, RTLIB::FLOOR_PPCF128);
3895          break;
3896        case ISD::FCEIL:
3897          LC = GetFPLibCall(VT, RTLIB::CEIL_F32, RTLIB::CEIL_F64,
3898                            RTLIB::CEIL_F80, RTLIB::CEIL_PPCF128);
3899          break;
3900        case ISD::FRINT:
3901          LC = GetFPLibCall(VT, RTLIB::RINT_F32, RTLIB::RINT_F64,
3902                            RTLIB::RINT_F80, RTLIB::RINT_PPCF128);
3903          break;
3904        case ISD::FNEARBYINT:
3905          LC = GetFPLibCall(VT, RTLIB::NEARBYINT_F32, RTLIB::NEARBYINT_F64,
3906                            RTLIB::NEARBYINT_F80, RTLIB::NEARBYINT_PPCF128);
3907          break;
3908      break;
3909        default: assert(0 && "Unreachable!");
3910        }
3911        SDValue Dummy;
3912        Result = ExpandLibCall(LC, Node, false/*sign irrelevant*/, Dummy);
3913        break;
3914      }
3915      }
3916      break;
3917    }
3918    break;
3919  case ISD::FPOWI: {
3920    MVT VT = Node->getValueType(0);
3921
3922    // Expand unsupported unary vector operators by unrolling them.
3923    if (VT.isVector()) {
3924      Result = LegalizeOp(UnrollVectorOp(Op));
3925      break;
3926    }
3927
3928    // We always lower FPOWI into a libcall.  No target support for it yet.
3929    RTLIB::Libcall LC = GetFPLibCall(VT, RTLIB::POWI_F32, RTLIB::POWI_F64,
3930                                     RTLIB::POWI_F80, RTLIB::POWI_PPCF128);
3931    SDValue Dummy;
3932    Result = ExpandLibCall(LC, Node, false/*sign irrelevant*/, Dummy);
3933    break;
3934  }
3935  case ISD::BIT_CONVERT:
3936    if (!isTypeLegal(Node->getOperand(0).getValueType())) {
3937      Result = EmitStackConvert(Node->getOperand(0), Node->getValueType(0),
3938                                Node->getValueType(0));
3939    } else if (Op.getOperand(0).getValueType().isVector()) {
3940      // The input has to be a vector type, we have to either scalarize it, pack
3941      // it, or convert it based on whether the input vector type is legal.
3942      SDNode *InVal = Node->getOperand(0).getNode();
3943      int InIx = Node->getOperand(0).getResNo();
3944      unsigned NumElems = InVal->getValueType(InIx).getVectorNumElements();
3945      MVT EVT = InVal->getValueType(InIx).getVectorElementType();
3946
3947      // Figure out if there is a simple type corresponding to this Vector
3948      // type.  If so, convert to the vector type.
3949      MVT TVT = MVT::getVectorVT(EVT, NumElems);
3950      if (TLI.isTypeLegal(TVT)) {
3951        // Turn this into a bit convert of the vector input.
3952        Result = DAG.getNode(ISD::BIT_CONVERT, Node->getValueType(0),
3953                             LegalizeOp(Node->getOperand(0)));
3954        break;
3955      } else if (NumElems == 1) {
3956        // Turn this into a bit convert of the scalar input.
3957        Result = DAG.getNode(ISD::BIT_CONVERT, Node->getValueType(0),
3958                             ScalarizeVectorOp(Node->getOperand(0)));
3959        break;
3960      } else {
3961        // FIXME: UNIMP!  Store then reload
3962        assert(0 && "Cast from unsupported vector type not implemented yet!");
3963      }
3964    } else {
3965      switch (TLI.getOperationAction(ISD::BIT_CONVERT,
3966                                     Node->getOperand(0).getValueType())) {
3967      default: assert(0 && "Unknown operation action!");
3968      case TargetLowering::Expand:
3969        Result = EmitStackConvert(Node->getOperand(0), Node->getValueType(0),
3970                                  Node->getValueType(0));
3971        break;
3972      case TargetLowering::Legal:
3973        Tmp1 = LegalizeOp(Node->getOperand(0));
3974        Result = DAG.UpdateNodeOperands(Result, Tmp1);
3975        break;
3976      }
3977    }
3978    break;
3979  case ISD::CONVERT_RNDSAT: {
3980    ISD::CvtCode CvtCode = cast<CvtRndSatSDNode>(Node)->getCvtCode();
3981    switch (CvtCode) {
3982    default: assert(0 && "Unknown cvt code!");
3983    case ISD::CVT_SF:
3984    case ISD::CVT_UF:
3985    case ISD::CVT_FF:
3986      break;
3987    case ISD::CVT_FS:
3988    case ISD::CVT_FU:
3989    case ISD::CVT_SS:
3990    case ISD::CVT_SU:
3991    case ISD::CVT_US:
3992    case ISD::CVT_UU: {
3993      SDValue DTyOp = Node->getOperand(1);
3994      SDValue STyOp = Node->getOperand(2);
3995      SDValue RndOp = Node->getOperand(3);
3996      SDValue SatOp = Node->getOperand(4);
3997      switch (getTypeAction(Node->getOperand(0).getValueType())) {
3998      case Expand: assert(0 && "Shouldn't need to expand other operators here!");
3999      case Legal:
4000        Tmp1 = LegalizeOp(Node->getOperand(0));
4001        Result = DAG.UpdateNodeOperands(Result, Tmp1, DTyOp, STyOp,
4002                                        RndOp, SatOp);
4003        if (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0)) ==
4004            TargetLowering::Custom) {
4005          Tmp1 = TLI.LowerOperation(Result, DAG);
4006          if (Tmp1.getNode()) Result = Tmp1;
4007        }
4008        break;
4009      case Promote:
4010        Result = PromoteOp(Node->getOperand(0));
4011        // For FP, make Op1 a i32
4012
4013        Result = DAG.getConvertRndSat(Op.getValueType(), Result,
4014                                      DTyOp, STyOp, RndOp, SatOp, CvtCode);
4015        break;
4016      }
4017      break;
4018    }
4019    } // end switch CvtCode
4020    break;
4021  }
4022    // Conversion operators.  The source and destination have different types.
4023  case ISD::SINT_TO_FP:
4024  case ISD::UINT_TO_FP: {
4025    bool isSigned = Node->getOpcode() == ISD::SINT_TO_FP;
4026    Result = LegalizeINT_TO_FP(Result, isSigned,
4027                               Node->getValueType(0), Node->getOperand(0));
4028    break;
4029  }
4030  case ISD::TRUNCATE:
4031    switch (getTypeAction(Node->getOperand(0).getValueType())) {
4032    case Legal:
4033      Tmp1 = LegalizeOp(Node->getOperand(0));
4034      switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
4035      default: assert(0 && "Unknown TRUNCATE legalization operation action!");
4036      case TargetLowering::Custom:
4037        isCustom = true;
4038        // FALLTHROUGH
4039      case TargetLowering::Legal:
4040        Result = DAG.UpdateNodeOperands(Result, Tmp1);
4041        if (isCustom) {
4042          Tmp1 = TLI.LowerOperation(Result, DAG);
4043          if (Tmp1.getNode()) Result = Tmp1;
4044        }
4045        break;
4046      case TargetLowering::Expand:
4047        assert(Result.getValueType().isVector() && "must be vector type");
4048        // Unroll the truncate.  We should do better.
4049        Result = LegalizeOp(UnrollVectorOp(Result));
4050      }
4051      break;
4052    case Expand:
4053      ExpandOp(Node->getOperand(0), Tmp1, Tmp2);
4054
4055      // Since the result is legal, we should just be able to truncate the low
4056      // part of the source.
4057      Result = DAG.getNode(ISD::TRUNCATE, Node->getValueType(0), Tmp1);
4058      break;
4059    case Promote:
4060      Result = PromoteOp(Node->getOperand(0));
4061      Result = DAG.getNode(ISD::TRUNCATE, Op.getValueType(), Result);
4062      break;
4063    }
4064    break;
4065
4066  case ISD::FP_TO_SINT:
4067  case ISD::FP_TO_UINT:
4068    switch (getTypeAction(Node->getOperand(0).getValueType())) {
4069    case Legal:
4070      Tmp1 = LegalizeOp(Node->getOperand(0));
4071
4072      switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))){
4073      default: assert(0 && "Unknown operation action!");
4074      case TargetLowering::Custom:
4075        isCustom = true;
4076        // FALLTHROUGH
4077      case TargetLowering::Legal:
4078        Result = DAG.UpdateNodeOperands(Result, Tmp1);
4079        if (isCustom) {
4080          Tmp1 = TLI.LowerOperation(Result, DAG);
4081          if (Tmp1.getNode()) Result = Tmp1;
4082        }
4083        break;
4084      case TargetLowering::Promote:
4085        Result = PromoteLegalFP_TO_INT(Tmp1, Node->getValueType(0),
4086                                       Node->getOpcode() == ISD::FP_TO_SINT);
4087        break;
4088      case TargetLowering::Expand:
4089        if (Node->getOpcode() == ISD::FP_TO_UINT) {
4090          SDValue True, False;
4091          MVT VT =  Node->getOperand(0).getValueType();
4092          MVT NVT = Node->getValueType(0);
4093          const uint64_t zero[] = {0, 0};
4094          APFloat apf = APFloat(APInt(VT.getSizeInBits(), 2, zero));
4095          APInt x = APInt::getSignBit(NVT.getSizeInBits());
4096          (void)apf.convertFromAPInt(x, false, APFloat::rmNearestTiesToEven);
4097          Tmp2 = DAG.getConstantFP(apf, VT);
4098          Tmp3 = DAG.getSetCC(TLI.getSetCCResultType(Node->getOperand(0)),
4099                            Node->getOperand(0), Tmp2, ISD::SETLT);
4100          True = DAG.getNode(ISD::FP_TO_SINT, NVT, Node->getOperand(0));
4101          False = DAG.getNode(ISD::FP_TO_SINT, NVT,
4102                              DAG.getNode(ISD::FSUB, VT, Node->getOperand(0),
4103                                          Tmp2));
4104          False = DAG.getNode(ISD::XOR, NVT, False,
4105                              DAG.getConstant(x, NVT));
4106          Result = DAG.getNode(ISD::SELECT, NVT, Tmp3, True, False);
4107          break;
4108        } else {
4109          assert(0 && "Do not know how to expand FP_TO_SINT yet!");
4110        }
4111        break;
4112      }
4113      break;
4114    case Expand: {
4115      MVT VT = Op.getValueType();
4116      MVT OVT = Node->getOperand(0).getValueType();
4117      // Convert ppcf128 to i32
4118      if (OVT == MVT::ppcf128 && VT == MVT::i32) {
4119        if (Node->getOpcode() == ISD::FP_TO_SINT) {
4120          Result = DAG.getNode(ISD::FP_ROUND_INREG, MVT::ppcf128,
4121                               Node->getOperand(0), DAG.getValueType(MVT::f64));
4122          Result = DAG.getNode(ISD::FP_ROUND, MVT::f64, Result,
4123                               DAG.getIntPtrConstant(1));
4124          Result = DAG.getNode(ISD::FP_TO_SINT, VT, Result);
4125        } else {
4126          const uint64_t TwoE31[] = {0x41e0000000000000LL, 0};
4127          APFloat apf = APFloat(APInt(128, 2, TwoE31));
4128          Tmp2 = DAG.getConstantFP(apf, OVT);
4129          //  X>=2^31 ? (int)(X-2^31)+0x80000000 : (int)X
4130          // FIXME: generated code sucks.
4131          Result = DAG.getNode(ISD::SELECT_CC, VT, Node->getOperand(0), Tmp2,
4132                               DAG.getNode(ISD::ADD, MVT::i32,
4133                                 DAG.getNode(ISD::FP_TO_SINT, VT,
4134                                   DAG.getNode(ISD::FSUB, OVT,
4135                                                 Node->getOperand(0), Tmp2)),
4136                                 DAG.getConstant(0x80000000, MVT::i32)),
4137                               DAG.getNode(ISD::FP_TO_SINT, VT,
4138                                           Node->getOperand(0)),
4139                               DAG.getCondCode(ISD::SETGE));
4140        }
4141        break;
4142      }
4143      // Convert f32 / f64 to i32 / i64 / i128.
4144      RTLIB::Libcall LC = (Node->getOpcode() == ISD::FP_TO_SINT) ?
4145        RTLIB::getFPTOSINT(OVT, VT) : RTLIB::getFPTOUINT(OVT, VT);
4146      assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unexpectd fp-to-int conversion!");
4147      SDValue Dummy;
4148      Result = ExpandLibCall(LC, Node, false/*sign irrelevant*/, Dummy);
4149      break;
4150    }
4151    case Promote:
4152      Tmp1 = PromoteOp(Node->getOperand(0));
4153      Result = DAG.UpdateNodeOperands(Result, LegalizeOp(Tmp1));
4154      Result = LegalizeOp(Result);
4155      break;
4156    }
4157    break;
4158
4159  case ISD::FP_EXTEND: {
4160    MVT DstVT = Op.getValueType();
4161    MVT SrcVT = Op.getOperand(0).getValueType();
4162    if (TLI.getConvertAction(SrcVT, DstVT) == TargetLowering::Expand) {
4163      // The only other way we can lower this is to turn it into a STORE,
4164      // LOAD pair, targetting a temporary location (a stack slot).
4165      Result = EmitStackConvert(Node->getOperand(0), SrcVT, DstVT);
4166      break;
4167    }
4168    switch (getTypeAction(Node->getOperand(0).getValueType())) {
4169    case Expand: assert(0 && "Shouldn't need to expand other operators here!");
4170    case Legal:
4171      Tmp1 = LegalizeOp(Node->getOperand(0));
4172      Result = DAG.UpdateNodeOperands(Result, Tmp1);
4173      break;
4174    case Promote:
4175      Tmp1 = PromoteOp(Node->getOperand(0));
4176      Result = DAG.getNode(ISD::FP_EXTEND, Op.getValueType(), Tmp1);
4177      break;
4178    }
4179    break;
4180  }
4181  case ISD::FP_ROUND: {
4182    MVT DstVT = Op.getValueType();
4183    MVT SrcVT = Op.getOperand(0).getValueType();
4184    if (TLI.getConvertAction(SrcVT, DstVT) == TargetLowering::Expand) {
4185      if (SrcVT == MVT::ppcf128) {
4186        SDValue Lo;
4187        ExpandOp(Node->getOperand(0), Lo, Result);
4188        // Round it the rest of the way (e.g. to f32) if needed.
4189        if (DstVT!=MVT::f64)
4190          Result = DAG.getNode(ISD::FP_ROUND, DstVT, Result, Op.getOperand(1));
4191        break;
4192      }
4193      // The only other way we can lower this is to turn it into a STORE,
4194      // LOAD pair, targetting a temporary location (a stack slot).
4195      Result = EmitStackConvert(Node->getOperand(0), DstVT, DstVT);
4196      break;
4197    }
4198    switch (getTypeAction(Node->getOperand(0).getValueType())) {
4199    case Expand: assert(0 && "Shouldn't need to expand other operators here!");
4200    case Legal:
4201      Tmp1 = LegalizeOp(Node->getOperand(0));
4202      Result = DAG.UpdateNodeOperands(Result, Tmp1, Node->getOperand(1));
4203      break;
4204    case Promote:
4205      Tmp1 = PromoteOp(Node->getOperand(0));
4206      Result = DAG.getNode(ISD::FP_ROUND, Op.getValueType(), Tmp1,
4207                           Node->getOperand(1));
4208      break;
4209    }
4210    break;
4211  }
4212  case ISD::ANY_EXTEND:
4213  case ISD::ZERO_EXTEND:
4214  case ISD::SIGN_EXTEND:
4215    switch (getTypeAction(Node->getOperand(0).getValueType())) {
4216    case Expand: assert(0 && "Shouldn't need to expand other operators here!");
4217    case Legal:
4218      Tmp1 = LegalizeOp(Node->getOperand(0));
4219      Result = DAG.UpdateNodeOperands(Result, Tmp1);
4220      if (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0)) ==
4221          TargetLowering::Custom) {
4222        Tmp1 = TLI.LowerOperation(Result, DAG);
4223        if (Tmp1.getNode()) Result = Tmp1;
4224      }
4225      break;
4226    case Promote:
4227      switch (Node->getOpcode()) {
4228      case ISD::ANY_EXTEND:
4229        Tmp1 = PromoteOp(Node->getOperand(0));
4230        Result = DAG.getNode(ISD::ANY_EXTEND, Op.getValueType(), Tmp1);
4231        break;
4232      case ISD::ZERO_EXTEND:
4233        Result = PromoteOp(Node->getOperand(0));
4234        Result = DAG.getNode(ISD::ANY_EXTEND, Op.getValueType(), Result);
4235        Result = DAG.getZeroExtendInReg(Result,
4236                                        Node->getOperand(0).getValueType());
4237        break;
4238      case ISD::SIGN_EXTEND:
4239        Result = PromoteOp(Node->getOperand(0));
4240        Result = DAG.getNode(ISD::ANY_EXTEND, Op.getValueType(), Result);
4241        Result = DAG.getNode(ISD::SIGN_EXTEND_INREG, Result.getValueType(),
4242                             Result,
4243                          DAG.getValueType(Node->getOperand(0).getValueType()));
4244        break;
4245      }
4246    }
4247    break;
4248  case ISD::FP_ROUND_INREG:
4249  case ISD::SIGN_EXTEND_INREG: {
4250    Tmp1 = LegalizeOp(Node->getOperand(0));
4251    MVT ExtraVT = cast<VTSDNode>(Node->getOperand(1))->getVT();
4252
4253    // If this operation is not supported, convert it to a shl/shr or load/store
4254    // pair.
4255    switch (TLI.getOperationAction(Node->getOpcode(), ExtraVT)) {
4256    default: assert(0 && "This action not supported for this op yet!");
4257    case TargetLowering::Legal:
4258      Result = DAG.UpdateNodeOperands(Result, Tmp1, Node->getOperand(1));
4259      break;
4260    case TargetLowering::Expand:
4261      // If this is an integer extend and shifts are supported, do that.
4262      if (Node->getOpcode() == ISD::SIGN_EXTEND_INREG) {
4263        // NOTE: we could fall back on load/store here too for targets without
4264        // SAR.  However, it is doubtful that any exist.
4265        unsigned BitsDiff = Node->getValueType(0).getSizeInBits() -
4266                            ExtraVT.getSizeInBits();
4267        SDValue ShiftCst = DAG.getConstant(BitsDiff, TLI.getShiftAmountTy());
4268        Result = DAG.getNode(ISD::SHL, Node->getValueType(0),
4269                             Node->getOperand(0), ShiftCst);
4270        Result = DAG.getNode(ISD::SRA, Node->getValueType(0),
4271                             Result, ShiftCst);
4272      } else if (Node->getOpcode() == ISD::FP_ROUND_INREG) {
4273        // The only way we can lower this is to turn it into a TRUNCSTORE,
4274        // EXTLOAD pair, targetting a temporary location (a stack slot).
4275
4276        // NOTE: there is a choice here between constantly creating new stack
4277        // slots and always reusing the same one.  We currently always create
4278        // new ones, as reuse may inhibit scheduling.
4279        Result = EmitStackConvert(Node->getOperand(0), ExtraVT,
4280                                  Node->getValueType(0));
4281      } else {
4282        assert(0 && "Unknown op");
4283      }
4284      break;
4285    }
4286    break;
4287  }
4288  case ISD::TRAMPOLINE: {
4289    SDValue Ops[6];
4290    for (unsigned i = 0; i != 6; ++i)
4291      Ops[i] = LegalizeOp(Node->getOperand(i));
4292    Result = DAG.UpdateNodeOperands(Result, Ops, 6);
4293    // The only option for this node is to custom lower it.
4294    Result = TLI.LowerOperation(Result, DAG);
4295    assert(Result.getNode() && "Should always custom lower!");
4296
4297    // Since trampoline produces two values, make sure to remember that we
4298    // legalized both of them.
4299    Tmp1 = LegalizeOp(Result.getValue(1));
4300    Result = LegalizeOp(Result);
4301    AddLegalizedOperand(SDValue(Node, 0), Result);
4302    AddLegalizedOperand(SDValue(Node, 1), Tmp1);
4303    return Op.getResNo() ? Tmp1 : Result;
4304  }
4305  case ISD::FLT_ROUNDS_: {
4306    MVT VT = Node->getValueType(0);
4307    switch (TLI.getOperationAction(Node->getOpcode(), VT)) {
4308    default: assert(0 && "This action not supported for this op yet!");
4309    case TargetLowering::Custom:
4310      Result = TLI.LowerOperation(Op, DAG);
4311      if (Result.getNode()) break;
4312      // Fall Thru
4313    case TargetLowering::Legal:
4314      // If this operation is not supported, lower it to constant 1
4315      Result = DAG.getConstant(1, VT);
4316      break;
4317    }
4318    break;
4319  }
4320  case ISD::TRAP: {
4321    MVT VT = Node->getValueType(0);
4322    switch (TLI.getOperationAction(Node->getOpcode(), VT)) {
4323    default: assert(0 && "This action not supported for this op yet!");
4324    case TargetLowering::Legal:
4325      Tmp1 = LegalizeOp(Node->getOperand(0));
4326      Result = DAG.UpdateNodeOperands(Result, Tmp1);
4327      break;
4328    case TargetLowering::Custom:
4329      Result = TLI.LowerOperation(Op, DAG);
4330      if (Result.getNode()) break;
4331      // Fall Thru
4332    case TargetLowering::Expand:
4333      // If this operation is not supported, lower it to 'abort()' call
4334      Tmp1 = LegalizeOp(Node->getOperand(0));
4335      TargetLowering::ArgListTy Args;
4336      std::pair<SDValue,SDValue> CallResult =
4337        TLI.LowerCallTo(Tmp1, Type::VoidTy,
4338                        false, false, false, false, CallingConv::C, false,
4339                        DAG.getExternalSymbol("abort", TLI.getPointerTy()),
4340                        Args, DAG);
4341      Result = CallResult.second;
4342      break;
4343    }
4344    break;
4345  }
4346
4347  case ISD::SADDO:
4348  case ISD::SSUBO: {
4349    MVT VT = Node->getValueType(0);
4350    switch (TLI.getOperationAction(Node->getOpcode(), VT)) {
4351    default: assert(0 && "This action not supported for this op yet!");
4352    case TargetLowering::Custom:
4353      Result = TLI.LowerOperation(Op, DAG);
4354      if (Result.getNode()) break;
4355      // FALLTHROUGH
4356    case TargetLowering::Legal: {
4357      SDValue LHS = LegalizeOp(Node->getOperand(0));
4358      SDValue RHS = LegalizeOp(Node->getOperand(1));
4359
4360      SDValue Sum = DAG.getNode(Node->getOpcode() == ISD::SADDO ?
4361                                ISD::ADD : ISD::SUB, LHS.getValueType(),
4362                                LHS, RHS);
4363      MVT OType = Node->getValueType(1);
4364
4365      SDValue Zero = DAG.getConstant(0, LHS.getValueType());
4366
4367      //   LHSSign -> LHS >= 0
4368      //   RHSSign -> RHS >= 0
4369      //   SumSign -> Sum >= 0
4370      //
4371      //   Add:
4372      //   Overflow -> (LHSSign == RHSSign) && (LHSSign != SumSign)
4373      //   Sub:
4374      //   Overflow -> (LHSSign != RHSSign) && (LHSSign != SumSign)
4375      //
4376      SDValue LHSSign = DAG.getSetCC(OType, LHS, Zero, ISD::SETGE);
4377      SDValue RHSSign = DAG.getSetCC(OType, RHS, Zero, ISD::SETGE);
4378      SDValue SignsMatch = DAG.getSetCC(OType, LHSSign, RHSSign,
4379                                        Node->getOpcode() == ISD::SADDO ?
4380                                        ISD::SETEQ : ISD::SETNE);
4381
4382      SDValue SumSign = DAG.getSetCC(OType, Sum, Zero, ISD::SETGE);
4383      SDValue SumSignNE = DAG.getSetCC(OType, LHSSign, SumSign, ISD::SETNE);
4384
4385      SDValue Cmp = DAG.getNode(ISD::AND, OType, SignsMatch, SumSignNE);
4386
4387      MVT ValueVTs[] = { LHS.getValueType(), OType };
4388      SDValue Ops[] = { Sum, Cmp };
4389
4390      Result = DAG.getNode(ISD::MERGE_VALUES, DAG.getVTList(&ValueVTs[0], 2),
4391                           &Ops[0], 2);
4392      SDNode *RNode = Result.getNode();
4393      DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 0), SDValue(RNode, 0));
4394      DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(RNode, 1));
4395      break;
4396    }
4397    }
4398
4399    break;
4400  }
4401  case ISD::UADDO:
4402  case ISD::USUBO: {
4403    MVT VT = Node->getValueType(0);
4404    switch (TLI.getOperationAction(Node->getOpcode(), VT)) {
4405    default: assert(0 && "This action not supported for this op yet!");
4406    case TargetLowering::Custom:
4407      Result = TLI.LowerOperation(Op, DAG);
4408      if (Result.getNode()) break;
4409      // FALLTHROUGH
4410    case TargetLowering::Legal: {
4411      SDValue LHS = LegalizeOp(Node->getOperand(0));
4412      SDValue RHS = LegalizeOp(Node->getOperand(1));
4413
4414      SDValue Sum = DAG.getNode(Node->getOpcode() == ISD::UADDO ?
4415                                ISD::ADD : ISD::SUB, LHS.getValueType(),
4416                                LHS, RHS);
4417      MVT OType = Node->getValueType(1);
4418      SDValue Cmp = DAG.getSetCC(OType, Sum, LHS,
4419                                 Node->getOpcode () == ISD::UADDO ?
4420                                 ISD::SETULT : ISD::SETUGT);
4421
4422      MVT ValueVTs[] = { LHS.getValueType(), OType };
4423      SDValue Ops[] = { Sum, Cmp };
4424
4425      Result = DAG.getNode(ISD::MERGE_VALUES, DAG.getVTList(&ValueVTs[0], 2),
4426                           &Ops[0], 2);
4427      SDNode *RNode = Result.getNode();
4428      DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 0), SDValue(RNode, 0));
4429      DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(RNode, 1));
4430      break;
4431    }
4432    }
4433
4434    break;
4435  }
4436  case ISD::SMULO:
4437  case ISD::UMULO: {
4438    MVT VT = Node->getValueType(0);
4439    switch (TLI.getOperationAction(Node->getOpcode(), VT)) {
4440    default: assert(0 && "This action is not supported at all!");
4441    case TargetLowering::Custom:
4442      Result = TLI.LowerOperation(Op, DAG);
4443      if (Result.getNode()) break;
4444      // Fall Thru
4445    case TargetLowering::Legal:
4446      // FIXME: According to Hacker's Delight, this can be implemented in
4447      // target independent lowering, but it would be inefficient, since it
4448      // requires a division + a branch.
4449      assert(0 && "Target independent lowering is not supported for SMULO/UMULO!");
4450    break;
4451    }
4452    break;
4453  }
4454
4455  }
4456
4457  assert(Result.getValueType() == Op.getValueType() &&
4458         "Bad legalization!");
4459
4460  // Make sure that the generated code is itself legal.
4461  if (Result != Op)
4462    Result = LegalizeOp(Result);
4463
4464  // Note that LegalizeOp may be reentered even from single-use nodes, which
4465  // means that we always must cache transformed nodes.
4466  AddLegalizedOperand(Op, Result);
4467  return Result;
4468}
4469
4470/// PromoteOp - Given an operation that produces a value in an invalid type,
4471/// promote it to compute the value into a larger type.  The produced value will
4472/// have the correct bits for the low portion of the register, but no guarantee
4473/// is made about the top bits: it may be zero, sign-extended, or garbage.
4474SDValue SelectionDAGLegalize::PromoteOp(SDValue Op) {
4475  MVT VT = Op.getValueType();
4476  MVT NVT = TLI.getTypeToTransformTo(VT);
4477  assert(getTypeAction(VT) == Promote &&
4478         "Caller should expand or legalize operands that are not promotable!");
4479  assert(NVT.bitsGT(VT) && NVT.isInteger() == VT.isInteger() &&
4480         "Cannot promote to smaller type!");
4481
4482  SDValue Tmp1, Tmp2, Tmp3;
4483  SDValue Result;
4484  SDNode *Node = Op.getNode();
4485
4486  DenseMap<SDValue, SDValue>::iterator I = PromotedNodes.find(Op);
4487  if (I != PromotedNodes.end()) return I->second;
4488
4489  switch (Node->getOpcode()) {
4490  case ISD::CopyFromReg:
4491    assert(0 && "CopyFromReg must be legal!");
4492  default:
4493#ifndef NDEBUG
4494    cerr << "NODE: "; Node->dump(&DAG); cerr << "\n";
4495#endif
4496    assert(0 && "Do not know how to promote this operator!");
4497    abort();
4498  case ISD::UNDEF:
4499    Result = DAG.getNode(ISD::UNDEF, NVT);
4500    break;
4501  case ISD::Constant:
4502    if (VT != MVT::i1)
4503      Result = DAG.getNode(ISD::SIGN_EXTEND, NVT, Op);
4504    else
4505      Result = DAG.getNode(ISD::ZERO_EXTEND, NVT, Op);
4506    assert(isa<ConstantSDNode>(Result) && "Didn't constant fold zext?");
4507    break;
4508  case ISD::ConstantFP:
4509    Result = DAG.getNode(ISD::FP_EXTEND, NVT, Op);
4510    assert(isa<ConstantFPSDNode>(Result) && "Didn't constant fold fp_extend?");
4511    break;
4512
4513  case ISD::SETCC:
4514    assert(isTypeLegal(TLI.getSetCCResultType(Node->getOperand(0)))
4515           && "SetCC type is not legal??");
4516    Result = DAG.getNode(ISD::SETCC,
4517                         TLI.getSetCCResultType(Node->getOperand(0)),
4518                         Node->getOperand(0), Node->getOperand(1),
4519                         Node->getOperand(2));
4520    break;
4521
4522  case ISD::TRUNCATE:
4523    switch (getTypeAction(Node->getOperand(0).getValueType())) {
4524    case Legal:
4525      Result = LegalizeOp(Node->getOperand(0));
4526      assert(Result.getValueType().bitsGE(NVT) &&
4527             "This truncation doesn't make sense!");
4528      if (Result.getValueType().bitsGT(NVT))    // Truncate to NVT instead of VT
4529        Result = DAG.getNode(ISD::TRUNCATE, NVT, Result);
4530      break;
4531    case Promote:
4532      // The truncation is not required, because we don't guarantee anything
4533      // about high bits anyway.
4534      Result = PromoteOp(Node->getOperand(0));
4535      break;
4536    case Expand:
4537      ExpandOp(Node->getOperand(0), Tmp1, Tmp2);
4538      // Truncate the low part of the expanded value to the result type
4539      Result = DAG.getNode(ISD::TRUNCATE, NVT, Tmp1);
4540    }
4541    break;
4542  case ISD::SIGN_EXTEND:
4543  case ISD::ZERO_EXTEND:
4544  case ISD::ANY_EXTEND:
4545    switch (getTypeAction(Node->getOperand(0).getValueType())) {
4546    case Expand: assert(0 && "BUG: Smaller reg should have been promoted!");
4547    case Legal:
4548      // Input is legal?  Just do extend all the way to the larger type.
4549      Result = DAG.getNode(Node->getOpcode(), NVT, Node->getOperand(0));
4550      break;
4551    case Promote:
4552      // Promote the reg if it's smaller.
4553      Result = PromoteOp(Node->getOperand(0));
4554      // The high bits are not guaranteed to be anything.  Insert an extend.
4555      if (Node->getOpcode() == ISD::SIGN_EXTEND)
4556        Result = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Result,
4557                         DAG.getValueType(Node->getOperand(0).getValueType()));
4558      else if (Node->getOpcode() == ISD::ZERO_EXTEND)
4559        Result = DAG.getZeroExtendInReg(Result,
4560                                        Node->getOperand(0).getValueType());
4561      break;
4562    }
4563    break;
4564  case ISD::CONVERT_RNDSAT: {
4565    ISD::CvtCode CvtCode = cast<CvtRndSatSDNode>(Node)->getCvtCode();
4566    assert ((CvtCode == ISD::CVT_SS || CvtCode == ISD::CVT_SU ||
4567             CvtCode == ISD::CVT_US || CvtCode == ISD::CVT_UU ||
4568             CvtCode == ISD::CVT_SF || CvtCode == ISD::CVT_UF) &&
4569            "can only promote integers");
4570    Result = DAG.getConvertRndSat(NVT, Node->getOperand(0),
4571                                  Node->getOperand(1), Node->getOperand(2),
4572                                  Node->getOperand(3), Node->getOperand(4),
4573                                  CvtCode);
4574    break;
4575
4576  }
4577  case ISD::BIT_CONVERT:
4578    Result = EmitStackConvert(Node->getOperand(0), Node->getValueType(0),
4579                              Node->getValueType(0));
4580    Result = PromoteOp(Result);
4581    break;
4582
4583  case ISD::FP_EXTEND:
4584    assert(0 && "Case not implemented.  Dynamically dead with 2 FP types!");
4585  case ISD::FP_ROUND:
4586    switch (getTypeAction(Node->getOperand(0).getValueType())) {
4587    case Expand: assert(0 && "BUG: Cannot expand FP regs!");
4588    case Promote:  assert(0 && "Unreachable with 2 FP types!");
4589    case Legal:
4590      if (Node->getConstantOperandVal(1) == 0) {
4591        // Input is legal?  Do an FP_ROUND_INREG.
4592        Result = DAG.getNode(ISD::FP_ROUND_INREG, NVT, Node->getOperand(0),
4593                             DAG.getValueType(VT));
4594      } else {
4595        // Just remove the truncate, it isn't affecting the value.
4596        Result = DAG.getNode(ISD::FP_ROUND, NVT, Node->getOperand(0),
4597                             Node->getOperand(1));
4598      }
4599      break;
4600    }
4601    break;
4602  case ISD::SINT_TO_FP:
4603  case ISD::UINT_TO_FP:
4604    switch (getTypeAction(Node->getOperand(0).getValueType())) {
4605    case Legal:
4606      // No extra round required here.
4607      Result = DAG.getNode(Node->getOpcode(), NVT, Node->getOperand(0));
4608      break;
4609
4610    case Promote:
4611      Result = PromoteOp(Node->getOperand(0));
4612      if (Node->getOpcode() == ISD::SINT_TO_FP)
4613        Result = DAG.getNode(ISD::SIGN_EXTEND_INREG, Result.getValueType(),
4614                             Result,
4615                         DAG.getValueType(Node->getOperand(0).getValueType()));
4616      else
4617        Result = DAG.getZeroExtendInReg(Result,
4618                                        Node->getOperand(0).getValueType());
4619      // No extra round required here.
4620      Result = DAG.getNode(Node->getOpcode(), NVT, Result);
4621      break;
4622    case Expand:
4623      Result = ExpandIntToFP(Node->getOpcode() == ISD::SINT_TO_FP, NVT,
4624                             Node->getOperand(0));
4625      // Round if we cannot tolerate excess precision.
4626      if (NoExcessFPPrecision)
4627        Result = DAG.getNode(ISD::FP_ROUND_INREG, NVT, Result,
4628                             DAG.getValueType(VT));
4629      break;
4630    }
4631    break;
4632
4633  case ISD::SIGN_EXTEND_INREG:
4634    Result = PromoteOp(Node->getOperand(0));
4635    Result = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Result,
4636                         Node->getOperand(1));
4637    break;
4638  case ISD::FP_TO_SINT:
4639  case ISD::FP_TO_UINT:
4640    switch (getTypeAction(Node->getOperand(0).getValueType())) {
4641    case Legal:
4642    case Expand:
4643      Tmp1 = Node->getOperand(0);
4644      break;
4645    case Promote:
4646      // The input result is prerounded, so we don't have to do anything
4647      // special.
4648      Tmp1 = PromoteOp(Node->getOperand(0));
4649      break;
4650    }
4651    // If we're promoting a UINT to a larger size, check to see if the new node
4652    // will be legal.  If it isn't, check to see if FP_TO_SINT is legal, since
4653    // we can use that instead.  This allows us to generate better code for
4654    // FP_TO_UINT for small destination sizes on targets where FP_TO_UINT is not
4655    // legal, such as PowerPC.
4656    if (Node->getOpcode() == ISD::FP_TO_UINT &&
4657        !TLI.isOperationLegal(ISD::FP_TO_UINT, NVT) &&
4658        (TLI.isOperationLegal(ISD::FP_TO_SINT, NVT) ||
4659         TLI.getOperationAction(ISD::FP_TO_SINT, NVT)==TargetLowering::Custom)){
4660      Result = DAG.getNode(ISD::FP_TO_SINT, NVT, Tmp1);
4661    } else {
4662      Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1);
4663    }
4664    break;
4665
4666  case ISD::FABS:
4667  case ISD::FNEG:
4668    Tmp1 = PromoteOp(Node->getOperand(0));
4669    assert(Tmp1.getValueType() == NVT);
4670    Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1);
4671    // NOTE: we do not have to do any extra rounding here for
4672    // NoExcessFPPrecision, because we know the input will have the appropriate
4673    // precision, and these operations don't modify precision at all.
4674    break;
4675
4676  case ISD::FLOG:
4677  case ISD::FLOG2:
4678  case ISD::FLOG10:
4679  case ISD::FEXP:
4680  case ISD::FEXP2:
4681  case ISD::FSQRT:
4682  case ISD::FSIN:
4683  case ISD::FCOS:
4684  case ISD::FTRUNC:
4685  case ISD::FFLOOR:
4686  case ISD::FCEIL:
4687  case ISD::FRINT:
4688  case ISD::FNEARBYINT:
4689    Tmp1 = PromoteOp(Node->getOperand(0));
4690    assert(Tmp1.getValueType() == NVT);
4691    Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1);
4692    if (NoExcessFPPrecision)
4693      Result = DAG.getNode(ISD::FP_ROUND_INREG, NVT, Result,
4694                           DAG.getValueType(VT));
4695    break;
4696
4697  case ISD::FPOW:
4698  case ISD::FPOWI: {
4699    // Promote f32 pow(i) to f64 pow(i).  Note that this could insert a libcall
4700    // directly as well, which may be better.
4701    Tmp1 = PromoteOp(Node->getOperand(0));
4702    Tmp2 = Node->getOperand(1);
4703    if (Node->getOpcode() == ISD::FPOW)
4704      Tmp2 = PromoteOp(Tmp2);
4705    assert(Tmp1.getValueType() == NVT);
4706    Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1, Tmp2);
4707    if (NoExcessFPPrecision)
4708      Result = DAG.getNode(ISD::FP_ROUND_INREG, NVT, Result,
4709                           DAG.getValueType(VT));
4710    break;
4711  }
4712
4713  case ISD::ATOMIC_CMP_SWAP_8:
4714  case ISD::ATOMIC_CMP_SWAP_16:
4715  case ISD::ATOMIC_CMP_SWAP_32:
4716  case ISD::ATOMIC_CMP_SWAP_64: {
4717    AtomicSDNode* AtomNode = cast<AtomicSDNode>(Node);
4718    Tmp2 = PromoteOp(Node->getOperand(2));
4719    Tmp3 = PromoteOp(Node->getOperand(3));
4720    Result = DAG.getAtomic(Node->getOpcode(), AtomNode->getChain(),
4721                           AtomNode->getBasePtr(), Tmp2, Tmp3,
4722                           AtomNode->getSrcValue(),
4723                           AtomNode->getAlignment());
4724    // Remember that we legalized the chain.
4725    AddLegalizedOperand(Op.getValue(1), LegalizeOp(Result.getValue(1)));
4726    break;
4727  }
4728  case ISD::ATOMIC_LOAD_ADD_8:
4729  case ISD::ATOMIC_LOAD_SUB_8:
4730  case ISD::ATOMIC_LOAD_AND_8:
4731  case ISD::ATOMIC_LOAD_OR_8:
4732  case ISD::ATOMIC_LOAD_XOR_8:
4733  case ISD::ATOMIC_LOAD_NAND_8:
4734  case ISD::ATOMIC_LOAD_MIN_8:
4735  case ISD::ATOMIC_LOAD_MAX_8:
4736  case ISD::ATOMIC_LOAD_UMIN_8:
4737  case ISD::ATOMIC_LOAD_UMAX_8:
4738  case ISD::ATOMIC_SWAP_8:
4739  case ISD::ATOMIC_LOAD_ADD_16:
4740  case ISD::ATOMIC_LOAD_SUB_16:
4741  case ISD::ATOMIC_LOAD_AND_16:
4742  case ISD::ATOMIC_LOAD_OR_16:
4743  case ISD::ATOMIC_LOAD_XOR_16:
4744  case ISD::ATOMIC_LOAD_NAND_16:
4745  case ISD::ATOMIC_LOAD_MIN_16:
4746  case ISD::ATOMIC_LOAD_MAX_16:
4747  case ISD::ATOMIC_LOAD_UMIN_16:
4748  case ISD::ATOMIC_LOAD_UMAX_16:
4749  case ISD::ATOMIC_SWAP_16:
4750  case ISD::ATOMIC_LOAD_ADD_32:
4751  case ISD::ATOMIC_LOAD_SUB_32:
4752  case ISD::ATOMIC_LOAD_AND_32:
4753  case ISD::ATOMIC_LOAD_OR_32:
4754  case ISD::ATOMIC_LOAD_XOR_32:
4755  case ISD::ATOMIC_LOAD_NAND_32:
4756  case ISD::ATOMIC_LOAD_MIN_32:
4757  case ISD::ATOMIC_LOAD_MAX_32:
4758  case ISD::ATOMIC_LOAD_UMIN_32:
4759  case ISD::ATOMIC_LOAD_UMAX_32:
4760  case ISD::ATOMIC_SWAP_32:
4761  case ISD::ATOMIC_LOAD_ADD_64:
4762  case ISD::ATOMIC_LOAD_SUB_64:
4763  case ISD::ATOMIC_LOAD_AND_64:
4764  case ISD::ATOMIC_LOAD_OR_64:
4765  case ISD::ATOMIC_LOAD_XOR_64:
4766  case ISD::ATOMIC_LOAD_NAND_64:
4767  case ISD::ATOMIC_LOAD_MIN_64:
4768  case ISD::ATOMIC_LOAD_MAX_64:
4769  case ISD::ATOMIC_LOAD_UMIN_64:
4770  case ISD::ATOMIC_LOAD_UMAX_64:
4771  case ISD::ATOMIC_SWAP_64: {
4772    AtomicSDNode* AtomNode = cast<AtomicSDNode>(Node);
4773    Tmp2 = PromoteOp(Node->getOperand(2));
4774    Result = DAG.getAtomic(Node->getOpcode(), AtomNode->getChain(),
4775                           AtomNode->getBasePtr(), Tmp2,
4776                           AtomNode->getSrcValue(),
4777                           AtomNode->getAlignment());
4778    // Remember that we legalized the chain.
4779    AddLegalizedOperand(Op.getValue(1), LegalizeOp(Result.getValue(1)));
4780    break;
4781  }
4782
4783  case ISD::AND:
4784  case ISD::OR:
4785  case ISD::XOR:
4786  case ISD::ADD:
4787  case ISD::SUB:
4788  case ISD::MUL:
4789    // The input may have strange things in the top bits of the registers, but
4790    // these operations don't care.  They may have weird bits going out, but
4791    // that too is okay if they are integer operations.
4792    Tmp1 = PromoteOp(Node->getOperand(0));
4793    Tmp2 = PromoteOp(Node->getOperand(1));
4794    assert(Tmp1.getValueType() == NVT && Tmp2.getValueType() == NVT);
4795    Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1, Tmp2);
4796    break;
4797  case ISD::FADD:
4798  case ISD::FSUB:
4799  case ISD::FMUL:
4800    Tmp1 = PromoteOp(Node->getOperand(0));
4801    Tmp2 = PromoteOp(Node->getOperand(1));
4802    assert(Tmp1.getValueType() == NVT && Tmp2.getValueType() == NVT);
4803    Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1, Tmp2);
4804
4805    // Floating point operations will give excess precision that we may not be
4806    // able to tolerate.  If we DO allow excess precision, just leave it,
4807    // otherwise excise it.
4808    // FIXME: Why would we need to round FP ops more than integer ones?
4809    //     Is Round(Add(Add(A,B),C)) != Round(Add(Round(Add(A,B)), C))
4810    if (NoExcessFPPrecision)
4811      Result = DAG.getNode(ISD::FP_ROUND_INREG, NVT, Result,
4812                           DAG.getValueType(VT));
4813    break;
4814
4815  case ISD::SDIV:
4816  case ISD::SREM:
4817    // These operators require that their input be sign extended.
4818    Tmp1 = PromoteOp(Node->getOperand(0));
4819    Tmp2 = PromoteOp(Node->getOperand(1));
4820    if (NVT.isInteger()) {
4821      Tmp1 = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Tmp1,
4822                         DAG.getValueType(VT));
4823      Tmp2 = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Tmp2,
4824                         DAG.getValueType(VT));
4825    }
4826    Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1, Tmp2);
4827
4828    // Perform FP_ROUND: this is probably overly pessimistic.
4829    if (NVT.isFloatingPoint() && NoExcessFPPrecision)
4830      Result = DAG.getNode(ISD::FP_ROUND_INREG, NVT, Result,
4831                           DAG.getValueType(VT));
4832    break;
4833  case ISD::FDIV:
4834  case ISD::FREM:
4835  case ISD::FCOPYSIGN:
4836    // These operators require that their input be fp extended.
4837    switch (getTypeAction(Node->getOperand(0).getValueType())) {
4838    case Expand: assert(0 && "not implemented");
4839    case Legal:   Tmp1 = LegalizeOp(Node->getOperand(0)); break;
4840    case Promote: Tmp1 = PromoteOp(Node->getOperand(0));  break;
4841    }
4842    switch (getTypeAction(Node->getOperand(1).getValueType())) {
4843    case Expand: assert(0 && "not implemented");
4844    case Legal:   Tmp2 = LegalizeOp(Node->getOperand(1)); break;
4845    case Promote: Tmp2 = PromoteOp(Node->getOperand(1)); break;
4846    }
4847    Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1, Tmp2);
4848
4849    // Perform FP_ROUND: this is probably overly pessimistic.
4850    if (NoExcessFPPrecision && Node->getOpcode() != ISD::FCOPYSIGN)
4851      Result = DAG.getNode(ISD::FP_ROUND_INREG, NVT, Result,
4852                           DAG.getValueType(VT));
4853    break;
4854
4855  case ISD::UDIV:
4856  case ISD::UREM:
4857    // These operators require that their input be zero extended.
4858    Tmp1 = PromoteOp(Node->getOperand(0));
4859    Tmp2 = PromoteOp(Node->getOperand(1));
4860    assert(NVT.isInteger() && "Operators don't apply to FP!");
4861    Tmp1 = DAG.getZeroExtendInReg(Tmp1, VT);
4862    Tmp2 = DAG.getZeroExtendInReg(Tmp2, VT);
4863    Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1, Tmp2);
4864    break;
4865
4866  case ISD::SHL:
4867    Tmp1 = PromoteOp(Node->getOperand(0));
4868    Result = DAG.getNode(ISD::SHL, NVT, Tmp1, Node->getOperand(1));
4869    break;
4870  case ISD::SRA:
4871    // The input value must be properly sign extended.
4872    Tmp1 = PromoteOp(Node->getOperand(0));
4873    Tmp1 = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Tmp1,
4874                       DAG.getValueType(VT));
4875    Result = DAG.getNode(ISD::SRA, NVT, Tmp1, Node->getOperand(1));
4876    break;
4877  case ISD::SRL:
4878    // The input value must be properly zero extended.
4879    Tmp1 = PromoteOp(Node->getOperand(0));
4880    Tmp1 = DAG.getZeroExtendInReg(Tmp1, VT);
4881    Result = DAG.getNode(ISD::SRL, NVT, Tmp1, Node->getOperand(1));
4882    break;
4883
4884  case ISD::VAARG:
4885    Tmp1 = Node->getOperand(0);   // Get the chain.
4886    Tmp2 = Node->getOperand(1);   // Get the pointer.
4887    if (TLI.getOperationAction(ISD::VAARG, VT) == TargetLowering::Custom) {
4888      Tmp3 = DAG.getVAArg(VT, Tmp1, Tmp2, Node->getOperand(2));
4889      Result = TLI.LowerOperation(Tmp3, DAG);
4890    } else {
4891      const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
4892      SDValue VAList = DAG.getLoad(TLI.getPointerTy(), Tmp1, Tmp2, V, 0);
4893      // Increment the pointer, VAList, to the next vaarg
4894      Tmp3 = DAG.getNode(ISD::ADD, TLI.getPointerTy(), VAList,
4895                         DAG.getConstant(VT.getSizeInBits()/8,
4896                                         TLI.getPointerTy()));
4897      // Store the incremented VAList to the legalized pointer
4898      Tmp3 = DAG.getStore(VAList.getValue(1), Tmp3, Tmp2, V, 0);
4899      // Load the actual argument out of the pointer VAList
4900      Result = DAG.getExtLoad(ISD::EXTLOAD, NVT, Tmp3, VAList, NULL, 0, VT);
4901    }
4902    // Remember that we legalized the chain.
4903    AddLegalizedOperand(Op.getValue(1), LegalizeOp(Result.getValue(1)));
4904    break;
4905
4906  case ISD::LOAD: {
4907    LoadSDNode *LD = cast<LoadSDNode>(Node);
4908    ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(Node)
4909      ? ISD::EXTLOAD : LD->getExtensionType();
4910    Result = DAG.getExtLoad(ExtType, NVT,
4911                            LD->getChain(), LD->getBasePtr(),
4912                            LD->getSrcValue(), LD->getSrcValueOffset(),
4913                            LD->getMemoryVT(),
4914                            LD->isVolatile(),
4915                            LD->getAlignment());
4916    // Remember that we legalized the chain.
4917    AddLegalizedOperand(Op.getValue(1), LegalizeOp(Result.getValue(1)));
4918    break;
4919  }
4920  case ISD::SELECT: {
4921    Tmp2 = PromoteOp(Node->getOperand(1));   // Legalize the op0
4922    Tmp3 = PromoteOp(Node->getOperand(2));   // Legalize the op1
4923
4924    MVT VT2 = Tmp2.getValueType();
4925    assert(VT2 == Tmp3.getValueType()
4926           && "PromoteOp SELECT: Operands 2 and 3 ValueTypes don't match");
4927    // Ensure that the resulting node is at least the same size as the operands'
4928    // value types, because we cannot assume that TLI.getSetCCValueType() is
4929    // constant.
4930    Result = DAG.getNode(ISD::SELECT, VT2, Node->getOperand(0), Tmp2, Tmp3);
4931    break;
4932  }
4933  case ISD::SELECT_CC:
4934    Tmp2 = PromoteOp(Node->getOperand(2));   // True
4935    Tmp3 = PromoteOp(Node->getOperand(3));   // False
4936    Result = DAG.getNode(ISD::SELECT_CC, NVT, Node->getOperand(0),
4937                         Node->getOperand(1), Tmp2, Tmp3, Node->getOperand(4));
4938    break;
4939  case ISD::BSWAP:
4940    Tmp1 = Node->getOperand(0);
4941    Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, NVT, Tmp1);
4942    Tmp1 = DAG.getNode(ISD::BSWAP, NVT, Tmp1);
4943    Result = DAG.getNode(ISD::SRL, NVT, Tmp1,
4944                         DAG.getConstant(NVT.getSizeInBits() -
4945                                         VT.getSizeInBits(),
4946                                         TLI.getShiftAmountTy()));
4947    break;
4948  case ISD::CTPOP:
4949  case ISD::CTTZ:
4950  case ISD::CTLZ:
4951    // Zero extend the argument
4952    Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, NVT, Node->getOperand(0));
4953    // Perform the larger operation, then subtract if needed.
4954    Tmp1 = DAG.getNode(Node->getOpcode(), NVT, Tmp1);
4955    switch(Node->getOpcode()) {
4956    case ISD::CTPOP:
4957      Result = Tmp1;
4958      break;
4959    case ISD::CTTZ:
4960      // if Tmp1 == sizeinbits(NVT) then Tmp1 = sizeinbits(Old VT)
4961      Tmp2 = DAG.getSetCC(TLI.getSetCCResultType(Tmp1), Tmp1,
4962                          DAG.getConstant(NVT.getSizeInBits(), NVT),
4963                          ISD::SETEQ);
4964      Result = DAG.getNode(ISD::SELECT, NVT, Tmp2,
4965                           DAG.getConstant(VT.getSizeInBits(), NVT), Tmp1);
4966      break;
4967    case ISD::CTLZ:
4968      //Tmp1 = Tmp1 - (sizeinbits(NVT) - sizeinbits(Old VT))
4969      Result = DAG.getNode(ISD::SUB, NVT, Tmp1,
4970                           DAG.getConstant(NVT.getSizeInBits() -
4971                                           VT.getSizeInBits(), NVT));
4972      break;
4973    }
4974    break;
4975  case ISD::EXTRACT_SUBVECTOR:
4976    Result = PromoteOp(ExpandEXTRACT_SUBVECTOR(Op));
4977    break;
4978  case ISD::EXTRACT_VECTOR_ELT:
4979    Result = PromoteOp(ExpandEXTRACT_VECTOR_ELT(Op));
4980    break;
4981  }
4982
4983  assert(Result.getNode() && "Didn't set a result!");
4984
4985  // Make sure the result is itself legal.
4986  Result = LegalizeOp(Result);
4987
4988  // Remember that we promoted this!
4989  AddPromotedOperand(Op, Result);
4990  return Result;
4991}
4992
4993/// ExpandEXTRACT_VECTOR_ELT - Expand an EXTRACT_VECTOR_ELT operation into
4994/// a legal EXTRACT_VECTOR_ELT operation, scalar code, or memory traffic,
4995/// based on the vector type. The return type of this matches the element type
4996/// of the vector, which may not be legal for the target.
4997SDValue SelectionDAGLegalize::ExpandEXTRACT_VECTOR_ELT(SDValue Op) {
4998  // We know that operand #0 is the Vec vector.  If the index is a constant
4999  // or if the invec is a supported hardware type, we can use it.  Otherwise,
5000  // lower to a store then an indexed load.
5001  SDValue Vec = Op.getOperand(0);
5002  SDValue Idx = Op.getOperand(1);
5003
5004  MVT TVT = Vec.getValueType();
5005  unsigned NumElems = TVT.getVectorNumElements();
5006
5007  switch (TLI.getOperationAction(ISD::EXTRACT_VECTOR_ELT, TVT)) {
5008  default: assert(0 && "This action is not supported yet!");
5009  case TargetLowering::Custom: {
5010    Vec = LegalizeOp(Vec);
5011    Op = DAG.UpdateNodeOperands(Op, Vec, Idx);
5012    SDValue Tmp3 = TLI.LowerOperation(Op, DAG);
5013    if (Tmp3.getNode())
5014      return Tmp3;
5015    break;
5016  }
5017  case TargetLowering::Legal:
5018    if (isTypeLegal(TVT)) {
5019      Vec = LegalizeOp(Vec);
5020      Op = DAG.UpdateNodeOperands(Op, Vec, Idx);
5021      return Op;
5022    }
5023    break;
5024  case TargetLowering::Promote:
5025    assert(TVT.isVector() && "not vector type");
5026    // fall thru to expand since vectors are by default are promote
5027  case TargetLowering::Expand:
5028    break;
5029  }
5030
5031  if (NumElems == 1) {
5032    // This must be an access of the only element.  Return it.
5033    Op = ScalarizeVectorOp(Vec);
5034  } else if (!TLI.isTypeLegal(TVT) && isa<ConstantSDNode>(Idx)) {
5035    unsigned NumLoElts =  1 << Log2_32(NumElems-1);
5036    ConstantSDNode *CIdx = cast<ConstantSDNode>(Idx);
5037    SDValue Lo, Hi;
5038    SplitVectorOp(Vec, Lo, Hi);
5039    if (CIdx->getZExtValue() < NumLoElts) {
5040      Vec = Lo;
5041    } else {
5042      Vec = Hi;
5043      Idx = DAG.getConstant(CIdx->getZExtValue() - NumLoElts,
5044                            Idx.getValueType());
5045    }
5046
5047    // It's now an extract from the appropriate high or low part.  Recurse.
5048    Op = DAG.UpdateNodeOperands(Op, Vec, Idx);
5049    Op = ExpandEXTRACT_VECTOR_ELT(Op);
5050  } else {
5051    // Store the value to a temporary stack slot, then LOAD the scalar
5052    // element back out.
5053    SDValue StackPtr = DAG.CreateStackTemporary(Vec.getValueType());
5054    SDValue Ch = DAG.getStore(DAG.getEntryNode(), Vec, StackPtr, NULL, 0);
5055
5056    // Add the offset to the index.
5057    unsigned EltSize = Op.getValueType().getSizeInBits()/8;
5058    Idx = DAG.getNode(ISD::MUL, Idx.getValueType(), Idx,
5059                      DAG.getConstant(EltSize, Idx.getValueType()));
5060
5061    if (Idx.getValueType().bitsGT(TLI.getPointerTy()))
5062      Idx = DAG.getNode(ISD::TRUNCATE, TLI.getPointerTy(), Idx);
5063    else
5064      Idx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(), Idx);
5065
5066    StackPtr = DAG.getNode(ISD::ADD, Idx.getValueType(), Idx, StackPtr);
5067
5068    Op = DAG.getLoad(Op.getValueType(), Ch, StackPtr, NULL, 0);
5069  }
5070  return Op;
5071}
5072
5073/// ExpandEXTRACT_SUBVECTOR - Expand a EXTRACT_SUBVECTOR operation.  For now
5074/// we assume the operation can be split if it is not already legal.
5075SDValue SelectionDAGLegalize::ExpandEXTRACT_SUBVECTOR(SDValue Op) {
5076  // We know that operand #0 is the Vec vector.  For now we assume the index
5077  // is a constant and that the extracted result is a supported hardware type.
5078  SDValue Vec = Op.getOperand(0);
5079  SDValue Idx = LegalizeOp(Op.getOperand(1));
5080
5081  unsigned NumElems = Vec.getValueType().getVectorNumElements();
5082
5083  if (NumElems == Op.getValueType().getVectorNumElements()) {
5084    // This must be an access of the desired vector length.  Return it.
5085    return Vec;
5086  }
5087
5088  ConstantSDNode *CIdx = cast<ConstantSDNode>(Idx);
5089  SDValue Lo, Hi;
5090  SplitVectorOp(Vec, Lo, Hi);
5091  if (CIdx->getZExtValue() < NumElems/2) {
5092    Vec = Lo;
5093  } else {
5094    Vec = Hi;
5095    Idx = DAG.getConstant(CIdx->getZExtValue() - NumElems/2,
5096                          Idx.getValueType());
5097  }
5098
5099  // It's now an extract from the appropriate high or low part.  Recurse.
5100  Op = DAG.UpdateNodeOperands(Op, Vec, Idx);
5101  return ExpandEXTRACT_SUBVECTOR(Op);
5102}
5103
5104/// LegalizeSetCCOperands - Attempts to create a legal LHS and RHS for a SETCC
5105/// with condition CC on the current target.  This usually involves legalizing
5106/// or promoting the arguments.  In the case where LHS and RHS must be expanded,
5107/// there may be no choice but to create a new SetCC node to represent the
5108/// legalized value of setcc lhs, rhs.  In this case, the value is returned in
5109/// LHS, and the SDValue returned in RHS has a nil SDNode value.
5110void SelectionDAGLegalize::LegalizeSetCCOperands(SDValue &LHS,
5111                                                 SDValue &RHS,
5112                                                 SDValue &CC) {
5113  SDValue Tmp1, Tmp2, Tmp3, Result;
5114
5115  switch (getTypeAction(LHS.getValueType())) {
5116  case Legal:
5117    Tmp1 = LegalizeOp(LHS);   // LHS
5118    Tmp2 = LegalizeOp(RHS);   // RHS
5119    break;
5120  case Promote:
5121    Tmp1 = PromoteOp(LHS);   // LHS
5122    Tmp2 = PromoteOp(RHS);   // RHS
5123
5124    // If this is an FP compare, the operands have already been extended.
5125    if (LHS.getValueType().isInteger()) {
5126      MVT VT = LHS.getValueType();
5127      MVT NVT = TLI.getTypeToTransformTo(VT);
5128
5129      // Otherwise, we have to insert explicit sign or zero extends.  Note
5130      // that we could insert sign extends for ALL conditions, but zero extend
5131      // is cheaper on many machines (an AND instead of two shifts), so prefer
5132      // it.
5133      switch (cast<CondCodeSDNode>(CC)->get()) {
5134      default: assert(0 && "Unknown integer comparison!");
5135      case ISD::SETEQ:
5136      case ISD::SETNE:
5137      case ISD::SETUGE:
5138      case ISD::SETUGT:
5139      case ISD::SETULE:
5140      case ISD::SETULT:
5141        // ALL of these operations will work if we either sign or zero extend
5142        // the operands (including the unsigned comparisons!).  Zero extend is
5143        // usually a simpler/cheaper operation, so prefer it.
5144        Tmp1 = DAG.getZeroExtendInReg(Tmp1, VT);
5145        Tmp2 = DAG.getZeroExtendInReg(Tmp2, VT);
5146        break;
5147      case ISD::SETGE:
5148      case ISD::SETGT:
5149      case ISD::SETLT:
5150      case ISD::SETLE:
5151        Tmp1 = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Tmp1,
5152                           DAG.getValueType(VT));
5153        Tmp2 = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Tmp2,
5154                           DAG.getValueType(VT));
5155        Tmp1 = LegalizeOp(Tmp1); // Relegalize new nodes.
5156        Tmp2 = LegalizeOp(Tmp2); // Relegalize new nodes.
5157        break;
5158      }
5159    }
5160    break;
5161  case Expand: {
5162    MVT VT = LHS.getValueType();
5163    if (VT == MVT::f32 || VT == MVT::f64) {
5164      // Expand into one or more soft-fp libcall(s).
5165      RTLIB::Libcall LC1 = RTLIB::UNKNOWN_LIBCALL, LC2 = RTLIB::UNKNOWN_LIBCALL;
5166      switch (cast<CondCodeSDNode>(CC)->get()) {
5167      case ISD::SETEQ:
5168      case ISD::SETOEQ:
5169        LC1 = (VT == MVT::f32) ? RTLIB::OEQ_F32 : RTLIB::OEQ_F64;
5170        break;
5171      case ISD::SETNE:
5172      case ISD::SETUNE:
5173        LC1 = (VT == MVT::f32) ? RTLIB::UNE_F32 : RTLIB::UNE_F64;
5174        break;
5175      case ISD::SETGE:
5176      case ISD::SETOGE:
5177        LC1 = (VT == MVT::f32) ? RTLIB::OGE_F32 : RTLIB::OGE_F64;
5178        break;
5179      case ISD::SETLT:
5180      case ISD::SETOLT:
5181        LC1 = (VT == MVT::f32) ? RTLIB::OLT_F32 : RTLIB::OLT_F64;
5182        break;
5183      case ISD::SETLE:
5184      case ISD::SETOLE:
5185        LC1 = (VT == MVT::f32) ? RTLIB::OLE_F32 : RTLIB::OLE_F64;
5186        break;
5187      case ISD::SETGT:
5188      case ISD::SETOGT:
5189        LC1 = (VT == MVT::f32) ? RTLIB::OGT_F32 : RTLIB::OGT_F64;
5190        break;
5191      case ISD::SETUO:
5192        LC1 = (VT == MVT::f32) ? RTLIB::UO_F32 : RTLIB::UO_F64;
5193        break;
5194      case ISD::SETO:
5195        LC1 = (VT == MVT::f32) ? RTLIB::O_F32 : RTLIB::O_F64;
5196        break;
5197      default:
5198        LC1 = (VT == MVT::f32) ? RTLIB::UO_F32 : RTLIB::UO_F64;
5199        switch (cast<CondCodeSDNode>(CC)->get()) {
5200        case ISD::SETONE:
5201          // SETONE = SETOLT | SETOGT
5202          LC1 = (VT == MVT::f32) ? RTLIB::OLT_F32 : RTLIB::OLT_F64;
5203          // Fallthrough
5204        case ISD::SETUGT:
5205          LC2 = (VT == MVT::f32) ? RTLIB::OGT_F32 : RTLIB::OGT_F64;
5206          break;
5207        case ISD::SETUGE:
5208          LC2 = (VT == MVT::f32) ? RTLIB::OGE_F32 : RTLIB::OGE_F64;
5209          break;
5210        case ISD::SETULT:
5211          LC2 = (VT == MVT::f32) ? RTLIB::OLT_F32 : RTLIB::OLT_F64;
5212          break;
5213        case ISD::SETULE:
5214          LC2 = (VT == MVT::f32) ? RTLIB::OLE_F32 : RTLIB::OLE_F64;
5215          break;
5216        case ISD::SETUEQ:
5217          LC2 = (VT == MVT::f32) ? RTLIB::OEQ_F32 : RTLIB::OEQ_F64;
5218          break;
5219        default: assert(0 && "Unsupported FP setcc!");
5220        }
5221      }
5222
5223      SDValue Dummy;
5224      SDValue Ops[2] = { LHS, RHS };
5225      Tmp1 = ExpandLibCall(LC1, DAG.getMergeValues(Ops, 2).getNode(),
5226                           false /*sign irrelevant*/, Dummy);
5227      Tmp2 = DAG.getConstant(0, MVT::i32);
5228      CC = DAG.getCondCode(TLI.getCmpLibcallCC(LC1));
5229      if (LC2 != RTLIB::UNKNOWN_LIBCALL) {
5230        Tmp1 = DAG.getNode(ISD::SETCC, TLI.getSetCCResultType(Tmp1), Tmp1, Tmp2,
5231                           CC);
5232        LHS = ExpandLibCall(LC2, DAG.getMergeValues(Ops, 2).getNode(),
5233                            false /*sign irrelevant*/, Dummy);
5234        Tmp2 = DAG.getNode(ISD::SETCC, TLI.getSetCCResultType(LHS), LHS, Tmp2,
5235                           DAG.getCondCode(TLI.getCmpLibcallCC(LC2)));
5236        Tmp1 = DAG.getNode(ISD::OR, Tmp1.getValueType(), Tmp1, Tmp2);
5237        Tmp2 = SDValue();
5238      }
5239      LHS = LegalizeOp(Tmp1);
5240      RHS = Tmp2;
5241      return;
5242    }
5243
5244    SDValue LHSLo, LHSHi, RHSLo, RHSHi;
5245    ExpandOp(LHS, LHSLo, LHSHi);
5246    ExpandOp(RHS, RHSLo, RHSHi);
5247    ISD::CondCode CCCode = cast<CondCodeSDNode>(CC)->get();
5248
5249    if (VT==MVT::ppcf128) {
5250      // FIXME:  This generated code sucks.  We want to generate
5251      //         FCMPU crN, hi1, hi2
5252      //         BNE crN, L:
5253      //         FCMPU crN, lo1, lo2
5254      // The following can be improved, but not that much.
5255      Tmp1 = DAG.getSetCC(TLI.getSetCCResultType(LHSHi), LHSHi, RHSHi,
5256                                                         ISD::SETOEQ);
5257      Tmp2 = DAG.getSetCC(TLI.getSetCCResultType(LHSLo), LHSLo, RHSLo, CCCode);
5258      Tmp3 = DAG.getNode(ISD::AND, Tmp1.getValueType(), Tmp1, Tmp2);
5259      Tmp1 = DAG.getSetCC(TLI.getSetCCResultType(LHSHi), LHSHi, RHSHi,
5260                                                         ISD::SETUNE);
5261      Tmp2 = DAG.getSetCC(TLI.getSetCCResultType(LHSHi), LHSHi, RHSHi, CCCode);
5262      Tmp1 = DAG.getNode(ISD::AND, Tmp1.getValueType(), Tmp1, Tmp2);
5263      Tmp1 = DAG.getNode(ISD::OR, Tmp1.getValueType(), Tmp1, Tmp3);
5264      Tmp2 = SDValue();
5265      break;
5266    }
5267
5268    switch (CCCode) {
5269    case ISD::SETEQ:
5270    case ISD::SETNE:
5271      if (RHSLo == RHSHi)
5272        if (ConstantSDNode *RHSCST = dyn_cast<ConstantSDNode>(RHSLo))
5273          if (RHSCST->isAllOnesValue()) {
5274            // Comparison to -1.
5275            Tmp1 = DAG.getNode(ISD::AND, LHSLo.getValueType(), LHSLo, LHSHi);
5276            Tmp2 = RHSLo;
5277            break;
5278          }
5279
5280      Tmp1 = DAG.getNode(ISD::XOR, LHSLo.getValueType(), LHSLo, RHSLo);
5281      Tmp2 = DAG.getNode(ISD::XOR, LHSLo.getValueType(), LHSHi, RHSHi);
5282      Tmp1 = DAG.getNode(ISD::OR, Tmp1.getValueType(), Tmp1, Tmp2);
5283      Tmp2 = DAG.getConstant(0, Tmp1.getValueType());
5284      break;
5285    default:
5286      // If this is a comparison of the sign bit, just look at the top part.
5287      // X > -1,  x < 0
5288      if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(RHS))
5289        if ((cast<CondCodeSDNode>(CC)->get() == ISD::SETLT &&
5290             CST->isNullValue()) ||               // X < 0
5291            (cast<CondCodeSDNode>(CC)->get() == ISD::SETGT &&
5292             CST->isAllOnesValue())) {            // X > -1
5293          Tmp1 = LHSHi;
5294          Tmp2 = RHSHi;
5295          break;
5296        }
5297
5298      // FIXME: This generated code sucks.
5299      ISD::CondCode LowCC;
5300      switch (CCCode) {
5301      default: assert(0 && "Unknown integer setcc!");
5302      case ISD::SETLT:
5303      case ISD::SETULT: LowCC = ISD::SETULT; break;
5304      case ISD::SETGT:
5305      case ISD::SETUGT: LowCC = ISD::SETUGT; break;
5306      case ISD::SETLE:
5307      case ISD::SETULE: LowCC = ISD::SETULE; break;
5308      case ISD::SETGE:
5309      case ISD::SETUGE: LowCC = ISD::SETUGE; break;
5310      }
5311
5312      // Tmp1 = lo(op1) < lo(op2)   // Always unsigned comparison
5313      // Tmp2 = hi(op1) < hi(op2)   // Signedness depends on operands
5314      // dest = hi(op1) == hi(op2) ? Tmp1 : Tmp2;
5315
5316      // NOTE: on targets without efficient SELECT of bools, we can always use
5317      // this identity: (B1 ? B2 : B3) --> (B1 & B2)|(!B1&B3)
5318      TargetLowering::DAGCombinerInfo DagCombineInfo(DAG, false, true, NULL);
5319      Tmp1 = TLI.SimplifySetCC(TLI.getSetCCResultType(LHSLo), LHSLo, RHSLo,
5320                               LowCC, false, DagCombineInfo);
5321      if (!Tmp1.getNode())
5322        Tmp1 = DAG.getSetCC(TLI.getSetCCResultType(LHSLo), LHSLo, RHSLo, LowCC);
5323      Tmp2 = TLI.SimplifySetCC(TLI.getSetCCResultType(LHSHi), LHSHi, RHSHi,
5324                               CCCode, false, DagCombineInfo);
5325      if (!Tmp2.getNode())
5326        Tmp2 = DAG.getNode(ISD::SETCC, TLI.getSetCCResultType(LHSHi), LHSHi,
5327                           RHSHi,CC);
5328
5329      ConstantSDNode *Tmp1C = dyn_cast<ConstantSDNode>(Tmp1.getNode());
5330      ConstantSDNode *Tmp2C = dyn_cast<ConstantSDNode>(Tmp2.getNode());
5331      if ((Tmp1C && Tmp1C->isNullValue()) ||
5332          (Tmp2C && Tmp2C->isNullValue() &&
5333           (CCCode == ISD::SETLE || CCCode == ISD::SETGE ||
5334            CCCode == ISD::SETUGE || CCCode == ISD::SETULE)) ||
5335          (Tmp2C && Tmp2C->getAPIntValue() == 1 &&
5336           (CCCode == ISD::SETLT || CCCode == ISD::SETGT ||
5337            CCCode == ISD::SETUGT || CCCode == ISD::SETULT))) {
5338        // low part is known false, returns high part.
5339        // For LE / GE, if high part is known false, ignore the low part.
5340        // For LT / GT, if high part is known true, ignore the low part.
5341        Tmp1 = Tmp2;
5342        Tmp2 = SDValue();
5343      } else {
5344        Result = TLI.SimplifySetCC(TLI.getSetCCResultType(LHSHi), LHSHi, RHSHi,
5345                                   ISD::SETEQ, false, DagCombineInfo);
5346        if (!Result.getNode())
5347          Result=DAG.getSetCC(TLI.getSetCCResultType(LHSHi), LHSHi, RHSHi,
5348                              ISD::SETEQ);
5349        Result = LegalizeOp(DAG.getNode(ISD::SELECT, Tmp1.getValueType(),
5350                                        Result, Tmp1, Tmp2));
5351        Tmp1 = Result;
5352        Tmp2 = SDValue();
5353      }
5354    }
5355  }
5356  }
5357  LHS = Tmp1;
5358  RHS = Tmp2;
5359}
5360
5361/// LegalizeSetCCCondCode - Legalize a SETCC with given LHS and RHS and
5362/// condition code CC on the current target. This routine assumes LHS and rHS
5363/// have already been legalized by LegalizeSetCCOperands. It expands SETCC with
5364/// illegal condition code into AND / OR of multiple SETCC values.
5365void SelectionDAGLegalize::LegalizeSetCCCondCode(MVT VT,
5366                                                 SDValue &LHS, SDValue &RHS,
5367                                                 SDValue &CC) {
5368  MVT OpVT = LHS.getValueType();
5369  ISD::CondCode CCCode = cast<CondCodeSDNode>(CC)->get();
5370  switch (TLI.getCondCodeAction(CCCode, OpVT)) {
5371  default: assert(0 && "Unknown condition code action!");
5372  case TargetLowering::Legal:
5373    // Nothing to do.
5374    break;
5375  case TargetLowering::Expand: {
5376    ISD::CondCode CC1 = ISD::SETCC_INVALID, CC2 = ISD::SETCC_INVALID;
5377    unsigned Opc = 0;
5378    switch (CCCode) {
5379    default: assert(0 && "Don't know how to expand this condition!"); abort();
5380    case ISD::SETOEQ: CC1 = ISD::SETEQ; CC2 = ISD::SETO;  Opc = ISD::AND; break;
5381    case ISD::SETOGT: CC1 = ISD::SETGT; CC2 = ISD::SETO;  Opc = ISD::AND; break;
5382    case ISD::SETOGE: CC1 = ISD::SETGE; CC2 = ISD::SETO;  Opc = ISD::AND; break;
5383    case ISD::SETOLT: CC1 = ISD::SETLT; CC2 = ISD::SETO;  Opc = ISD::AND; break;
5384    case ISD::SETOLE: CC1 = ISD::SETLE; CC2 = ISD::SETO;  Opc = ISD::AND; break;
5385    case ISD::SETONE: CC1 = ISD::SETNE; CC2 = ISD::SETO;  Opc = ISD::AND; break;
5386    case ISD::SETUEQ: CC1 = ISD::SETEQ; CC2 = ISD::SETUO; Opc = ISD::OR;  break;
5387    case ISD::SETUGT: CC1 = ISD::SETGT; CC2 = ISD::SETUO; Opc = ISD::OR;  break;
5388    case ISD::SETUGE: CC1 = ISD::SETGE; CC2 = ISD::SETUO; Opc = ISD::OR;  break;
5389    case ISD::SETULT: CC1 = ISD::SETLT; CC2 = ISD::SETUO; Opc = ISD::OR;  break;
5390    case ISD::SETULE: CC1 = ISD::SETLE; CC2 = ISD::SETUO; Opc = ISD::OR;  break;
5391    case ISD::SETUNE: CC1 = ISD::SETNE; CC2 = ISD::SETUO; Opc = ISD::OR;  break;
5392    // FIXME: Implement more expansions.
5393    }
5394
5395    SDValue SetCC1 = DAG.getSetCC(VT, LHS, RHS, CC1);
5396    SDValue SetCC2 = DAG.getSetCC(VT, LHS, RHS, CC2);
5397    LHS = DAG.getNode(Opc, VT, SetCC1, SetCC2);
5398    RHS = SDValue();
5399    CC  = SDValue();
5400    break;
5401  }
5402  }
5403}
5404
5405/// EmitStackConvert - Emit a store/load combination to the stack.  This stores
5406/// SrcOp to a stack slot of type SlotVT, truncating it if needed.  It then does
5407/// a load from the stack slot to DestVT, extending it if needed.
5408/// The resultant code need not be legal.
5409SDValue SelectionDAGLegalize::EmitStackConvert(SDValue SrcOp,
5410                                               MVT SlotVT,
5411                                               MVT DestVT) {
5412  // Create the stack frame object.
5413  unsigned SrcAlign = TLI.getTargetData()->getPrefTypeAlignment(
5414                                          SrcOp.getValueType().getTypeForMVT());
5415  SDValue FIPtr = DAG.CreateStackTemporary(SlotVT, SrcAlign);
5416
5417  FrameIndexSDNode *StackPtrFI = cast<FrameIndexSDNode>(FIPtr);
5418  int SPFI = StackPtrFI->getIndex();
5419
5420  unsigned SrcSize = SrcOp.getValueType().getSizeInBits();
5421  unsigned SlotSize = SlotVT.getSizeInBits();
5422  unsigned DestSize = DestVT.getSizeInBits();
5423  unsigned DestAlign = TLI.getTargetData()->getPrefTypeAlignment(
5424                                                        DestVT.getTypeForMVT());
5425
5426  // Emit a store to the stack slot.  Use a truncstore if the input value is
5427  // later than DestVT.
5428  SDValue Store;
5429
5430  if (SrcSize > SlotSize)
5431    Store = DAG.getTruncStore(DAG.getEntryNode(), SrcOp, FIPtr,
5432                              PseudoSourceValue::getFixedStack(SPFI), 0,
5433                              SlotVT, false, SrcAlign);
5434  else {
5435    assert(SrcSize == SlotSize && "Invalid store");
5436    Store = DAG.getStore(DAG.getEntryNode(), SrcOp, FIPtr,
5437                         PseudoSourceValue::getFixedStack(SPFI), 0,
5438                         false, SrcAlign);
5439  }
5440
5441  // Result is a load from the stack slot.
5442  if (SlotSize == DestSize)
5443    return DAG.getLoad(DestVT, Store, FIPtr, NULL, 0, false, DestAlign);
5444
5445  assert(SlotSize < DestSize && "Unknown extension!");
5446  return DAG.getExtLoad(ISD::EXTLOAD, DestVT, Store, FIPtr, NULL, 0, SlotVT,
5447                        false, DestAlign);
5448}
5449
5450SDValue SelectionDAGLegalize::ExpandSCALAR_TO_VECTOR(SDNode *Node) {
5451  // Create a vector sized/aligned stack slot, store the value to element #0,
5452  // then load the whole vector back out.
5453  SDValue StackPtr = DAG.CreateStackTemporary(Node->getValueType(0));
5454
5455  FrameIndexSDNode *StackPtrFI = cast<FrameIndexSDNode>(StackPtr);
5456  int SPFI = StackPtrFI->getIndex();
5457
5458  SDValue Ch = DAG.getStore(DAG.getEntryNode(), Node->getOperand(0), StackPtr,
5459                              PseudoSourceValue::getFixedStack(SPFI), 0);
5460  return DAG.getLoad(Node->getValueType(0), Ch, StackPtr,
5461                     PseudoSourceValue::getFixedStack(SPFI), 0);
5462}
5463
5464
5465/// ExpandBUILD_VECTOR - Expand a BUILD_VECTOR node on targets that don't
5466/// support the operation, but do support the resultant vector type.
5467SDValue SelectionDAGLegalize::ExpandBUILD_VECTOR(SDNode *Node) {
5468
5469  // If the only non-undef value is the low element, turn this into a
5470  // SCALAR_TO_VECTOR node.  If this is { X, X, X, X }, determine X.
5471  unsigned NumElems = Node->getNumOperands();
5472  bool isOnlyLowElement = true;
5473  SDValue SplatValue = Node->getOperand(0);
5474
5475  // FIXME: it would be far nicer to change this into map<SDValue,uint64_t>
5476  // and use a bitmask instead of a list of elements.
5477  std::map<SDValue, std::vector<unsigned> > Values;
5478  Values[SplatValue].push_back(0);
5479  bool isConstant = true;
5480  if (!isa<ConstantFPSDNode>(SplatValue) && !isa<ConstantSDNode>(SplatValue) &&
5481      SplatValue.getOpcode() != ISD::UNDEF)
5482    isConstant = false;
5483
5484  for (unsigned i = 1; i < NumElems; ++i) {
5485    SDValue V = Node->getOperand(i);
5486    Values[V].push_back(i);
5487    if (V.getOpcode() != ISD::UNDEF)
5488      isOnlyLowElement = false;
5489    if (SplatValue != V)
5490      SplatValue = SDValue(0,0);
5491
5492    // If this isn't a constant element or an undef, we can't use a constant
5493    // pool load.
5494    if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V) &&
5495        V.getOpcode() != ISD::UNDEF)
5496      isConstant = false;
5497  }
5498
5499  if (isOnlyLowElement) {
5500    // If the low element is an undef too, then this whole things is an undef.
5501    if (Node->getOperand(0).getOpcode() == ISD::UNDEF)
5502      return DAG.getNode(ISD::UNDEF, Node->getValueType(0));
5503    // Otherwise, turn this into a scalar_to_vector node.
5504    return DAG.getNode(ISD::SCALAR_TO_VECTOR, Node->getValueType(0),
5505                       Node->getOperand(0));
5506  }
5507
5508  // If all elements are constants, create a load from the constant pool.
5509  if (isConstant) {
5510    MVT VT = Node->getValueType(0);
5511    std::vector<Constant*> CV;
5512    for (unsigned i = 0, e = NumElems; i != e; ++i) {
5513      if (ConstantFPSDNode *V =
5514          dyn_cast<ConstantFPSDNode>(Node->getOperand(i))) {
5515        CV.push_back(const_cast<ConstantFP *>(V->getConstantFPValue()));
5516      } else if (ConstantSDNode *V =
5517                   dyn_cast<ConstantSDNode>(Node->getOperand(i))) {
5518        CV.push_back(const_cast<ConstantInt *>(V->getConstantIntValue()));
5519      } else {
5520        assert(Node->getOperand(i).getOpcode() == ISD::UNDEF);
5521        const Type *OpNTy =
5522          Node->getOperand(0).getValueType().getTypeForMVT();
5523        CV.push_back(UndefValue::get(OpNTy));
5524      }
5525    }
5526    Constant *CP = ConstantVector::get(CV);
5527    SDValue CPIdx = DAG.getConstantPool(CP, TLI.getPointerTy());
5528    unsigned Alignment = 1 << cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
5529    return DAG.getLoad(VT, DAG.getEntryNode(), CPIdx,
5530                       PseudoSourceValue::getConstantPool(), 0,
5531                       false, Alignment);
5532  }
5533
5534  if (SplatValue.getNode()) {   // Splat of one value?
5535    // Build the shuffle constant vector: <0, 0, 0, 0>
5536    MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
5537    SDValue Zero = DAG.getConstant(0, MaskVT.getVectorElementType());
5538    std::vector<SDValue> ZeroVec(NumElems, Zero);
5539    SDValue SplatMask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
5540                                      &ZeroVec[0], ZeroVec.size());
5541
5542    // If the target supports VECTOR_SHUFFLE and this shuffle mask, use it.
5543    if (isShuffleLegal(Node->getValueType(0), SplatMask)) {
5544      // Get the splatted value into the low element of a vector register.
5545      SDValue LowValVec =
5546        DAG.getNode(ISD::SCALAR_TO_VECTOR, Node->getValueType(0), SplatValue);
5547
5548      // Return shuffle(LowValVec, undef, <0,0,0,0>)
5549      return DAG.getNode(ISD::VECTOR_SHUFFLE, Node->getValueType(0), LowValVec,
5550                         DAG.getNode(ISD::UNDEF, Node->getValueType(0)),
5551                         SplatMask);
5552    }
5553  }
5554
5555  // If there are only two unique elements, we may be able to turn this into a
5556  // vector shuffle.
5557  if (Values.size() == 2) {
5558    // Get the two values in deterministic order.
5559    SDValue Val1 = Node->getOperand(1);
5560    SDValue Val2;
5561    std::map<SDValue, std::vector<unsigned> >::iterator MI = Values.begin();
5562    if (MI->first != Val1)
5563      Val2 = MI->first;
5564    else
5565      Val2 = (++MI)->first;
5566
5567    // If Val1 is an undef, make sure end ends up as Val2, to ensure that our
5568    // vector shuffle has the undef vector on the RHS.
5569    if (Val1.getOpcode() == ISD::UNDEF)
5570      std::swap(Val1, Val2);
5571
5572    // Build the shuffle constant vector: e.g. <0, 4, 0, 4>
5573    MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
5574    MVT MaskEltVT = MaskVT.getVectorElementType();
5575    std::vector<SDValue> MaskVec(NumElems);
5576
5577    // Set elements of the shuffle mask for Val1.
5578    std::vector<unsigned> &Val1Elts = Values[Val1];
5579    for (unsigned i = 0, e = Val1Elts.size(); i != e; ++i)
5580      MaskVec[Val1Elts[i]] = DAG.getConstant(0, MaskEltVT);
5581
5582    // Set elements of the shuffle mask for Val2.
5583    std::vector<unsigned> &Val2Elts = Values[Val2];
5584    for (unsigned i = 0, e = Val2Elts.size(); i != e; ++i)
5585      if (Val2.getOpcode() != ISD::UNDEF)
5586        MaskVec[Val2Elts[i]] = DAG.getConstant(NumElems, MaskEltVT);
5587      else
5588        MaskVec[Val2Elts[i]] = DAG.getNode(ISD::UNDEF, MaskEltVT);
5589
5590    SDValue ShuffleMask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
5591                                        &MaskVec[0], MaskVec.size());
5592
5593    // If the target supports SCALAR_TO_VECTOR and this shuffle mask, use it.
5594    if (TLI.isOperationLegal(ISD::SCALAR_TO_VECTOR, Node->getValueType(0)) &&
5595        isShuffleLegal(Node->getValueType(0), ShuffleMask)) {
5596      Val1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, Node->getValueType(0), Val1);
5597      Val2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, Node->getValueType(0), Val2);
5598      SDValue Ops[] = { Val1, Val2, ShuffleMask };
5599
5600      // Return shuffle(LoValVec, HiValVec, <0,1,0,1>)
5601      return DAG.getNode(ISD::VECTOR_SHUFFLE, Node->getValueType(0), Ops, 3);
5602    }
5603  }
5604
5605  // Otherwise, we can't handle this case efficiently.  Allocate a sufficiently
5606  // aligned object on the stack, store each element into it, then load
5607  // the result as a vector.
5608  MVT VT = Node->getValueType(0);
5609  // Create the stack frame object.
5610  SDValue FIPtr = DAG.CreateStackTemporary(VT);
5611
5612  // Emit a store of each element to the stack slot.
5613  SmallVector<SDValue, 8> Stores;
5614  unsigned TypeByteSize = Node->getOperand(0).getValueType().getSizeInBits()/8;
5615  // Store (in the right endianness) the elements to memory.
5616  for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) {
5617    // Ignore undef elements.
5618    if (Node->getOperand(i).getOpcode() == ISD::UNDEF) continue;
5619
5620    unsigned Offset = TypeByteSize*i;
5621
5622    SDValue Idx = DAG.getConstant(Offset, FIPtr.getValueType());
5623    Idx = DAG.getNode(ISD::ADD, FIPtr.getValueType(), FIPtr, Idx);
5624
5625    Stores.push_back(DAG.getStore(DAG.getEntryNode(), Node->getOperand(i), Idx,
5626                                  NULL, 0));
5627  }
5628
5629  SDValue StoreChain;
5630  if (!Stores.empty())    // Not all undef elements?
5631    StoreChain = DAG.getNode(ISD::TokenFactor, MVT::Other,
5632                             &Stores[0], Stores.size());
5633  else
5634    StoreChain = DAG.getEntryNode();
5635
5636  // Result is a load from the stack slot.
5637  return DAG.getLoad(VT, StoreChain, FIPtr, NULL, 0);
5638}
5639
5640void SelectionDAGLegalize::ExpandShiftParts(unsigned NodeOp,
5641                                            SDValue Op, SDValue Amt,
5642                                            SDValue &Lo, SDValue &Hi) {
5643  // Expand the subcomponents.
5644  SDValue LHSL, LHSH;
5645  ExpandOp(Op, LHSL, LHSH);
5646
5647  SDValue Ops[] = { LHSL, LHSH, Amt };
5648  MVT VT = LHSL.getValueType();
5649  Lo = DAG.getNode(NodeOp, DAG.getNodeValueTypes(VT, VT), 2, Ops, 3);
5650  Hi = Lo.getValue(1);
5651}
5652
5653
5654/// ExpandShift - Try to find a clever way to expand this shift operation out to
5655/// smaller elements.  If we can't find a way that is more efficient than a
5656/// libcall on this target, return false.  Otherwise, return true with the
5657/// low-parts expanded into Lo and Hi.
5658bool SelectionDAGLegalize::ExpandShift(unsigned Opc, SDValue Op,SDValue Amt,
5659                                       SDValue &Lo, SDValue &Hi) {
5660  assert((Opc == ISD::SHL || Opc == ISD::SRA || Opc == ISD::SRL) &&
5661         "This is not a shift!");
5662
5663  MVT NVT = TLI.getTypeToTransformTo(Op.getValueType());
5664  SDValue ShAmt = LegalizeOp(Amt);
5665  MVT ShTy = ShAmt.getValueType();
5666  unsigned ShBits = ShTy.getSizeInBits();
5667  unsigned VTBits = Op.getValueType().getSizeInBits();
5668  unsigned NVTBits = NVT.getSizeInBits();
5669
5670  // Handle the case when Amt is an immediate.
5671  if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Amt.getNode())) {
5672    unsigned Cst = CN->getZExtValue();
5673    // Expand the incoming operand to be shifted, so that we have its parts
5674    SDValue InL, InH;
5675    ExpandOp(Op, InL, InH);
5676    switch(Opc) {
5677    case ISD::SHL:
5678      if (Cst > VTBits) {
5679        Lo = DAG.getConstant(0, NVT);
5680        Hi = DAG.getConstant(0, NVT);
5681      } else if (Cst > NVTBits) {
5682        Lo = DAG.getConstant(0, NVT);
5683        Hi = DAG.getNode(ISD::SHL, NVT, InL, DAG.getConstant(Cst-NVTBits,ShTy));
5684      } else if (Cst == NVTBits) {
5685        Lo = DAG.getConstant(0, NVT);
5686        Hi = InL;
5687      } else {
5688        Lo = DAG.getNode(ISD::SHL, NVT, InL, DAG.getConstant(Cst, ShTy));
5689        Hi = DAG.getNode(ISD::OR, NVT,
5690           DAG.getNode(ISD::SHL, NVT, InH, DAG.getConstant(Cst, ShTy)),
5691           DAG.getNode(ISD::SRL, NVT, InL, DAG.getConstant(NVTBits-Cst, ShTy)));
5692      }
5693      return true;
5694    case ISD::SRL:
5695      if (Cst > VTBits) {
5696        Lo = DAG.getConstant(0, NVT);
5697        Hi = DAG.getConstant(0, NVT);
5698      } else if (Cst > NVTBits) {
5699        Lo = DAG.getNode(ISD::SRL, NVT, InH, DAG.getConstant(Cst-NVTBits,ShTy));
5700        Hi = DAG.getConstant(0, NVT);
5701      } else if (Cst == NVTBits) {
5702        Lo = InH;
5703        Hi = DAG.getConstant(0, NVT);
5704      } else {
5705        Lo = DAG.getNode(ISD::OR, NVT,
5706           DAG.getNode(ISD::SRL, NVT, InL, DAG.getConstant(Cst, ShTy)),
5707           DAG.getNode(ISD::SHL, NVT, InH, DAG.getConstant(NVTBits-Cst, ShTy)));
5708        Hi = DAG.getNode(ISD::SRL, NVT, InH, DAG.getConstant(Cst, ShTy));
5709      }
5710      return true;
5711    case ISD::SRA:
5712      if (Cst > VTBits) {
5713        Hi = Lo = DAG.getNode(ISD::SRA, NVT, InH,
5714                              DAG.getConstant(NVTBits-1, ShTy));
5715      } else if (Cst > NVTBits) {
5716        Lo = DAG.getNode(ISD::SRA, NVT, InH,
5717                           DAG.getConstant(Cst-NVTBits, ShTy));
5718        Hi = DAG.getNode(ISD::SRA, NVT, InH,
5719                              DAG.getConstant(NVTBits-1, ShTy));
5720      } else if (Cst == NVTBits) {
5721        Lo = InH;
5722        Hi = DAG.getNode(ISD::SRA, NVT, InH,
5723                              DAG.getConstant(NVTBits-1, ShTy));
5724      } else {
5725        Lo = DAG.getNode(ISD::OR, NVT,
5726           DAG.getNode(ISD::SRL, NVT, InL, DAG.getConstant(Cst, ShTy)),
5727           DAG.getNode(ISD::SHL, NVT, InH, DAG.getConstant(NVTBits-Cst, ShTy)));
5728        Hi = DAG.getNode(ISD::SRA, NVT, InH, DAG.getConstant(Cst, ShTy));
5729      }
5730      return true;
5731    }
5732  }
5733
5734  // Okay, the shift amount isn't constant.  However, if we can tell that it is
5735  // >= 32 or < 32, we can still simplify it, without knowing the actual value.
5736  APInt Mask = APInt::getHighBitsSet(ShBits, ShBits - Log2_32(NVTBits));
5737  APInt KnownZero, KnownOne;
5738  DAG.ComputeMaskedBits(Amt, Mask, KnownZero, KnownOne);
5739
5740  // If we know that if any of the high bits of the shift amount are one, then
5741  // we can do this as a couple of simple shifts.
5742  if (KnownOne.intersects(Mask)) {
5743    // Mask out the high bit, which we know is set.
5744    Amt = DAG.getNode(ISD::AND, Amt.getValueType(), Amt,
5745                      DAG.getConstant(~Mask, Amt.getValueType()));
5746
5747    // Expand the incoming operand to be shifted, so that we have its parts
5748    SDValue InL, InH;
5749    ExpandOp(Op, InL, InH);
5750    switch(Opc) {
5751    case ISD::SHL:
5752      Lo = DAG.getConstant(0, NVT);              // Low part is zero.
5753      Hi = DAG.getNode(ISD::SHL, NVT, InL, Amt); // High part from Lo part.
5754      return true;
5755    case ISD::SRL:
5756      Hi = DAG.getConstant(0, NVT);              // Hi part is zero.
5757      Lo = DAG.getNode(ISD::SRL, NVT, InH, Amt); // Lo part from Hi part.
5758      return true;
5759    case ISD::SRA:
5760      Hi = DAG.getNode(ISD::SRA, NVT, InH,       // Sign extend high part.
5761                       DAG.getConstant(NVTBits-1, Amt.getValueType()));
5762      Lo = DAG.getNode(ISD::SRA, NVT, InH, Amt); // Lo part from Hi part.
5763      return true;
5764    }
5765  }
5766
5767  // If we know that the high bits of the shift amount are all zero, then we can
5768  // do this as a couple of simple shifts.
5769  if ((KnownZero & Mask) == Mask) {
5770    // Compute 32-amt.
5771    SDValue Amt2 = DAG.getNode(ISD::SUB, Amt.getValueType(),
5772                                 DAG.getConstant(NVTBits, Amt.getValueType()),
5773                                 Amt);
5774
5775    // Expand the incoming operand to be shifted, so that we have its parts
5776    SDValue InL, InH;
5777    ExpandOp(Op, InL, InH);
5778    switch(Opc) {
5779    case ISD::SHL:
5780      Lo = DAG.getNode(ISD::SHL, NVT, InL, Amt);
5781      Hi = DAG.getNode(ISD::OR, NVT,
5782                       DAG.getNode(ISD::SHL, NVT, InH, Amt),
5783                       DAG.getNode(ISD::SRL, NVT, InL, Amt2));
5784      return true;
5785    case ISD::SRL:
5786      Hi = DAG.getNode(ISD::SRL, NVT, InH, Amt);
5787      Lo = DAG.getNode(ISD::OR, NVT,
5788                       DAG.getNode(ISD::SRL, NVT, InL, Amt),
5789                       DAG.getNode(ISD::SHL, NVT, InH, Amt2));
5790      return true;
5791    case ISD::SRA:
5792      Hi = DAG.getNode(ISD::SRA, NVT, InH, Amt);
5793      Lo = DAG.getNode(ISD::OR, NVT,
5794                       DAG.getNode(ISD::SRL, NVT, InL, Amt),
5795                       DAG.getNode(ISD::SHL, NVT, InH, Amt2));
5796      return true;
5797    }
5798  }
5799
5800  return false;
5801}
5802
5803
5804// ExpandLibCall - Expand a node into a call to a libcall.  If the result value
5805// does not fit into a register, return the lo part and set the hi part to the
5806// by-reg argument.  If it does fit into a single register, return the result
5807// and leave the Hi part unset.
5808SDValue SelectionDAGLegalize::ExpandLibCall(RTLIB::Libcall LC, SDNode *Node,
5809                                            bool isSigned, SDValue &Hi) {
5810  assert(!IsLegalizingCall && "Cannot overlap legalization of calls!");
5811  // The input chain to this libcall is the entry node of the function.
5812  // Legalizing the call will automatically add the previous call to the
5813  // dependence.
5814  SDValue InChain = DAG.getEntryNode();
5815
5816  TargetLowering::ArgListTy Args;
5817  TargetLowering::ArgListEntry Entry;
5818  for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) {
5819    MVT ArgVT = Node->getOperand(i).getValueType();
5820    const Type *ArgTy = ArgVT.getTypeForMVT();
5821    Entry.Node = Node->getOperand(i); Entry.Ty = ArgTy;
5822    Entry.isSExt = isSigned;
5823    Entry.isZExt = !isSigned;
5824    Args.push_back(Entry);
5825  }
5826  SDValue Callee = DAG.getExternalSymbol(TLI.getLibcallName(LC),
5827                                         TLI.getPointerTy());
5828
5829  // Splice the libcall in wherever FindInputOutputChains tells us to.
5830  const Type *RetTy = Node->getValueType(0).getTypeForMVT();
5831  std::pair<SDValue,SDValue> CallInfo =
5832    TLI.LowerCallTo(InChain, RetTy, isSigned, !isSigned, false, false,
5833                    CallingConv::C, false, Callee, Args, DAG);
5834
5835  // Legalize the call sequence, starting with the chain.  This will advance
5836  // the LastCALLSEQ_END to the legalized version of the CALLSEQ_END node that
5837  // was added by LowerCallTo (guaranteeing proper serialization of calls).
5838  LegalizeOp(CallInfo.second);
5839  SDValue Result;
5840  switch (getTypeAction(CallInfo.first.getValueType())) {
5841  default: assert(0 && "Unknown thing");
5842  case Legal:
5843    Result = CallInfo.first;
5844    break;
5845  case Expand:
5846    ExpandOp(CallInfo.first, Result, Hi);
5847    break;
5848  }
5849  return Result;
5850}
5851
5852/// LegalizeINT_TO_FP - Legalize a [US]INT_TO_FP operation.
5853///
5854SDValue SelectionDAGLegalize::
5855LegalizeINT_TO_FP(SDValue Result, bool isSigned, MVT DestTy, SDValue Op) {
5856  bool isCustom = false;
5857  SDValue Tmp1;
5858  switch (getTypeAction(Op.getValueType())) {
5859  case Legal:
5860    switch (TLI.getOperationAction(isSigned ? ISD::SINT_TO_FP : ISD::UINT_TO_FP,
5861                                   Op.getValueType())) {
5862    default: assert(0 && "Unknown operation action!");
5863    case TargetLowering::Custom:
5864      isCustom = true;
5865      // FALLTHROUGH
5866    case TargetLowering::Legal:
5867      Tmp1 = LegalizeOp(Op);
5868      if (Result.getNode())
5869        Result = DAG.UpdateNodeOperands(Result, Tmp1);
5870      else
5871        Result = DAG.getNode(isSigned ? ISD::SINT_TO_FP : ISD::UINT_TO_FP,
5872                             DestTy, Tmp1);
5873      if (isCustom) {
5874        Tmp1 = TLI.LowerOperation(Result, DAG);
5875        if (Tmp1.getNode()) Result = Tmp1;
5876      }
5877      break;
5878    case TargetLowering::Expand:
5879      Result = ExpandLegalINT_TO_FP(isSigned, LegalizeOp(Op), DestTy);
5880      break;
5881    case TargetLowering::Promote:
5882      Result = PromoteLegalINT_TO_FP(LegalizeOp(Op), DestTy, isSigned);
5883      break;
5884    }
5885    break;
5886  case Expand:
5887    Result = ExpandIntToFP(isSigned, DestTy, Op);
5888    break;
5889  case Promote:
5890    Tmp1 = PromoteOp(Op);
5891    if (isSigned) {
5892      Tmp1 = DAG.getNode(ISD::SIGN_EXTEND_INREG, Tmp1.getValueType(),
5893               Tmp1, DAG.getValueType(Op.getValueType()));
5894    } else {
5895      Tmp1 = DAG.getZeroExtendInReg(Tmp1,
5896                                    Op.getValueType());
5897    }
5898    if (Result.getNode())
5899      Result = DAG.UpdateNodeOperands(Result, Tmp1);
5900    else
5901      Result = DAG.getNode(isSigned ? ISD::SINT_TO_FP : ISD::UINT_TO_FP,
5902                           DestTy, Tmp1);
5903    Result = LegalizeOp(Result);  // The 'op' is not necessarily legal!
5904    break;
5905  }
5906  return Result;
5907}
5908
5909/// ExpandIntToFP - Expand a [US]INT_TO_FP operation.
5910///
5911SDValue SelectionDAGLegalize::
5912ExpandIntToFP(bool isSigned, MVT DestTy, SDValue Source) {
5913  MVT SourceVT = Source.getValueType();
5914  bool ExpandSource = getTypeAction(SourceVT) == Expand;
5915
5916  // Expand unsupported int-to-fp vector casts by unrolling them.
5917  if (DestTy.isVector()) {
5918    if (!ExpandSource)
5919      return LegalizeOp(UnrollVectorOp(Source));
5920    MVT DestEltTy = DestTy.getVectorElementType();
5921    if (DestTy.getVectorNumElements() == 1) {
5922      SDValue Scalar = ScalarizeVectorOp(Source);
5923      SDValue Result = LegalizeINT_TO_FP(SDValue(), isSigned,
5924                                         DestEltTy, Scalar);
5925      return DAG.getNode(ISD::BUILD_VECTOR, DestTy, Result);
5926    }
5927    SDValue Lo, Hi;
5928    SplitVectorOp(Source, Lo, Hi);
5929    MVT SplitDestTy = MVT::getVectorVT(DestEltTy,
5930                                       DestTy.getVectorNumElements() / 2);
5931    SDValue LoResult = LegalizeINT_TO_FP(SDValue(), isSigned, SplitDestTy, Lo);
5932    SDValue HiResult = LegalizeINT_TO_FP(SDValue(), isSigned, SplitDestTy, Hi);
5933    return LegalizeOp(DAG.getNode(ISD::CONCAT_VECTORS, DestTy, LoResult,
5934                                  HiResult));
5935  }
5936
5937  // Special case for i32 source to take advantage of UINTTOFP_I32_F32, etc.
5938  if (!isSigned && SourceVT != MVT::i32) {
5939    // The integer value loaded will be incorrectly if the 'sign bit' of the
5940    // incoming integer is set.  To handle this, we dynamically test to see if
5941    // it is set, and, if so, add a fudge factor.
5942    SDValue Hi;
5943    if (ExpandSource) {
5944      SDValue Lo;
5945      ExpandOp(Source, Lo, Hi);
5946      Source = DAG.getNode(ISD::BUILD_PAIR, SourceVT, Lo, Hi);
5947    } else {
5948      // The comparison for the sign bit will use the entire operand.
5949      Hi = Source;
5950    }
5951
5952    // Check to see if the target has a custom way to lower this.  If so, use
5953    // it.  (Note we've already expanded the operand in this case.)
5954    switch (TLI.getOperationAction(ISD::UINT_TO_FP, SourceVT)) {
5955    default: assert(0 && "This action not implemented for this operation!");
5956    case TargetLowering::Legal:
5957    case TargetLowering::Expand:
5958      break;   // This case is handled below.
5959    case TargetLowering::Custom: {
5960      SDValue NV = TLI.LowerOperation(DAG.getNode(ISD::UINT_TO_FP, DestTy,
5961                                                    Source), DAG);
5962      if (NV.getNode())
5963        return LegalizeOp(NV);
5964      break;   // The target decided this was legal after all
5965    }
5966    }
5967
5968    // If this is unsigned, and not supported, first perform the conversion to
5969    // signed, then adjust the result if the sign bit is set.
5970    SDValue SignedConv = ExpandIntToFP(true, DestTy, Source);
5971
5972    SDValue SignSet = DAG.getSetCC(TLI.getSetCCResultType(Hi), Hi,
5973                                     DAG.getConstant(0, Hi.getValueType()),
5974                                     ISD::SETLT);
5975    SDValue Zero = DAG.getIntPtrConstant(0), Four = DAG.getIntPtrConstant(4);
5976    SDValue CstOffset = DAG.getNode(ISD::SELECT, Zero.getValueType(),
5977                                      SignSet, Four, Zero);
5978    uint64_t FF = 0x5f800000ULL;
5979    if (TLI.isLittleEndian()) FF <<= 32;
5980    static Constant *FudgeFactor = ConstantInt::get(Type::Int64Ty, FF);
5981
5982    SDValue CPIdx = DAG.getConstantPool(FudgeFactor, TLI.getPointerTy());
5983    unsigned Alignment = 1 << cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
5984    CPIdx = DAG.getNode(ISD::ADD, TLI.getPointerTy(), CPIdx, CstOffset);
5985    Alignment = std::min(Alignment, 4u);
5986    SDValue FudgeInReg;
5987    if (DestTy == MVT::f32)
5988      FudgeInReg = DAG.getLoad(MVT::f32, DAG.getEntryNode(), CPIdx,
5989                               PseudoSourceValue::getConstantPool(), 0,
5990                               false, Alignment);
5991    else if (DestTy.bitsGT(MVT::f32))
5992      // FIXME: Avoid the extend by construction the right constantpool?
5993      FudgeInReg = DAG.getExtLoad(ISD::EXTLOAD, DestTy, DAG.getEntryNode(),
5994                                  CPIdx,
5995                                  PseudoSourceValue::getConstantPool(), 0,
5996                                  MVT::f32, false, Alignment);
5997    else
5998      assert(0 && "Unexpected conversion");
5999
6000    MVT SCVT = SignedConv.getValueType();
6001    if (SCVT != DestTy) {
6002      // Destination type needs to be expanded as well. The FADD now we are
6003      // constructing will be expanded into a libcall.
6004      if (SCVT.getSizeInBits() != DestTy.getSizeInBits()) {
6005        assert(SCVT.getSizeInBits() * 2 == DestTy.getSizeInBits());
6006        SignedConv = DAG.getNode(ISD::BUILD_PAIR, DestTy,
6007                                 SignedConv, SignedConv.getValue(1));
6008      }
6009      SignedConv = DAG.getNode(ISD::BIT_CONVERT, DestTy, SignedConv);
6010    }
6011    return DAG.getNode(ISD::FADD, DestTy, SignedConv, FudgeInReg);
6012  }
6013
6014  // Check to see if the target has a custom way to lower this.  If so, use it.
6015  switch (TLI.getOperationAction(ISD::SINT_TO_FP, SourceVT)) {
6016  default: assert(0 && "This action not implemented for this operation!");
6017  case TargetLowering::Legal:
6018  case TargetLowering::Expand:
6019    break;   // This case is handled below.
6020  case TargetLowering::Custom: {
6021    SDValue NV = TLI.LowerOperation(DAG.getNode(ISD::SINT_TO_FP, DestTy,
6022                                                  Source), DAG);
6023    if (NV.getNode())
6024      return LegalizeOp(NV);
6025    break;   // The target decided this was legal after all
6026  }
6027  }
6028
6029  // Expand the source, then glue it back together for the call.  We must expand
6030  // the source in case it is shared (this pass of legalize must traverse it).
6031  if (ExpandSource) {
6032    SDValue SrcLo, SrcHi;
6033    ExpandOp(Source, SrcLo, SrcHi);
6034    Source = DAG.getNode(ISD::BUILD_PAIR, SourceVT, SrcLo, SrcHi);
6035  }
6036
6037  RTLIB::Libcall LC = isSigned ?
6038    RTLIB::getSINTTOFP(SourceVT, DestTy) :
6039    RTLIB::getUINTTOFP(SourceVT, DestTy);
6040  assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unknown int value type");
6041
6042  Source = DAG.getNode(ISD::SINT_TO_FP, DestTy, Source);
6043  SDValue HiPart;
6044  SDValue Result = ExpandLibCall(LC, Source.getNode(), isSigned, HiPart);
6045  if (Result.getValueType() != DestTy && HiPart.getNode())
6046    Result = DAG.getNode(ISD::BUILD_PAIR, DestTy, Result, HiPart);
6047  return Result;
6048}
6049
6050/// ExpandLegalINT_TO_FP - This function is responsible for legalizing a
6051/// INT_TO_FP operation of the specified operand when the target requests that
6052/// we expand it.  At this point, we know that the result and operand types are
6053/// legal for the target.
6054SDValue SelectionDAGLegalize::ExpandLegalINT_TO_FP(bool isSigned,
6055                                                   SDValue Op0,
6056                                                   MVT DestVT) {
6057  if (Op0.getValueType() == MVT::i32) {
6058    // simple 32-bit [signed|unsigned] integer to float/double expansion
6059
6060    // Get the stack frame index of a 8 byte buffer.
6061    SDValue StackSlot = DAG.CreateStackTemporary(MVT::f64);
6062
6063    // word offset constant for Hi/Lo address computation
6064    SDValue WordOff = DAG.getConstant(sizeof(int), TLI.getPointerTy());
6065    // set up Hi and Lo (into buffer) address based on endian
6066    SDValue Hi = StackSlot;
6067    SDValue Lo = DAG.getNode(ISD::ADD, TLI.getPointerTy(), StackSlot,WordOff);
6068    if (TLI.isLittleEndian())
6069      std::swap(Hi, Lo);
6070
6071    // if signed map to unsigned space
6072    SDValue Op0Mapped;
6073    if (isSigned) {
6074      // constant used to invert sign bit (signed to unsigned mapping)
6075      SDValue SignBit = DAG.getConstant(0x80000000u, MVT::i32);
6076      Op0Mapped = DAG.getNode(ISD::XOR, MVT::i32, Op0, SignBit);
6077    } else {
6078      Op0Mapped = Op0;
6079    }
6080    // store the lo of the constructed double - based on integer input
6081    SDValue Store1 = DAG.getStore(DAG.getEntryNode(),
6082                                    Op0Mapped, Lo, NULL, 0);
6083    // initial hi portion of constructed double
6084    SDValue InitialHi = DAG.getConstant(0x43300000u, MVT::i32);
6085    // store the hi of the constructed double - biased exponent
6086    SDValue Store2=DAG.getStore(Store1, InitialHi, Hi, NULL, 0);
6087    // load the constructed double
6088    SDValue Load = DAG.getLoad(MVT::f64, Store2, StackSlot, NULL, 0);
6089    // FP constant to bias correct the final result
6090    SDValue Bias = DAG.getConstantFP(isSigned ?
6091                                            BitsToDouble(0x4330000080000000ULL)
6092                                          : BitsToDouble(0x4330000000000000ULL),
6093                                     MVT::f64);
6094    // subtract the bias
6095    SDValue Sub = DAG.getNode(ISD::FSUB, MVT::f64, Load, Bias);
6096    // final result
6097    SDValue Result;
6098    // handle final rounding
6099    if (DestVT == MVT::f64) {
6100      // do nothing
6101      Result = Sub;
6102    } else if (DestVT.bitsLT(MVT::f64)) {
6103      Result = DAG.getNode(ISD::FP_ROUND, DestVT, Sub,
6104                           DAG.getIntPtrConstant(0));
6105    } else if (DestVT.bitsGT(MVT::f64)) {
6106      Result = DAG.getNode(ISD::FP_EXTEND, DestVT, Sub);
6107    }
6108    return Result;
6109  }
6110  assert(!isSigned && "Legalize cannot Expand SINT_TO_FP for i64 yet");
6111  SDValue Tmp1 = DAG.getNode(ISD::SINT_TO_FP, DestVT, Op0);
6112
6113  SDValue SignSet = DAG.getSetCC(TLI.getSetCCResultType(Op0), Op0,
6114                                   DAG.getConstant(0, Op0.getValueType()),
6115                                   ISD::SETLT);
6116  SDValue Zero = DAG.getIntPtrConstant(0), Four = DAG.getIntPtrConstant(4);
6117  SDValue CstOffset = DAG.getNode(ISD::SELECT, Zero.getValueType(),
6118                                    SignSet, Four, Zero);
6119
6120  // If the sign bit of the integer is set, the large number will be treated
6121  // as a negative number.  To counteract this, the dynamic code adds an
6122  // offset depending on the data type.
6123  uint64_t FF;
6124  switch (Op0.getValueType().getSimpleVT()) {
6125  default: assert(0 && "Unsupported integer type!");
6126  case MVT::i8 : FF = 0x43800000ULL; break;  // 2^8  (as a float)
6127  case MVT::i16: FF = 0x47800000ULL; break;  // 2^16 (as a float)
6128  case MVT::i32: FF = 0x4F800000ULL; break;  // 2^32 (as a float)
6129  case MVT::i64: FF = 0x5F800000ULL; break;  // 2^64 (as a float)
6130  }
6131  if (TLI.isLittleEndian()) FF <<= 32;
6132  static Constant *FudgeFactor = ConstantInt::get(Type::Int64Ty, FF);
6133
6134  SDValue CPIdx = DAG.getConstantPool(FudgeFactor, TLI.getPointerTy());
6135  unsigned Alignment = 1 << cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
6136  CPIdx = DAG.getNode(ISD::ADD, TLI.getPointerTy(), CPIdx, CstOffset);
6137  Alignment = std::min(Alignment, 4u);
6138  SDValue FudgeInReg;
6139  if (DestVT == MVT::f32)
6140    FudgeInReg = DAG.getLoad(MVT::f32, DAG.getEntryNode(), CPIdx,
6141                             PseudoSourceValue::getConstantPool(), 0,
6142                             false, Alignment);
6143  else {
6144    FudgeInReg =
6145      LegalizeOp(DAG.getExtLoad(ISD::EXTLOAD, DestVT,
6146                                DAG.getEntryNode(), CPIdx,
6147                                PseudoSourceValue::getConstantPool(), 0,
6148                                MVT::f32, false, Alignment));
6149  }
6150
6151  return DAG.getNode(ISD::FADD, DestVT, Tmp1, FudgeInReg);
6152}
6153
6154/// PromoteLegalINT_TO_FP - This function is responsible for legalizing a
6155/// *INT_TO_FP operation of the specified operand when the target requests that
6156/// we promote it.  At this point, we know that the result and operand types are
6157/// legal for the target, and that there is a legal UINT_TO_FP or SINT_TO_FP
6158/// operation that takes a larger input.
6159SDValue SelectionDAGLegalize::PromoteLegalINT_TO_FP(SDValue LegalOp,
6160                                                    MVT DestVT,
6161                                                    bool isSigned) {
6162  // First step, figure out the appropriate *INT_TO_FP operation to use.
6163  MVT NewInTy = LegalOp.getValueType();
6164
6165  unsigned OpToUse = 0;
6166
6167  // Scan for the appropriate larger type to use.
6168  while (1) {
6169    NewInTy = (MVT::SimpleValueType)(NewInTy.getSimpleVT()+1);
6170    assert(NewInTy.isInteger() && "Ran out of possibilities!");
6171
6172    // If the target supports SINT_TO_FP of this type, use it.
6173    switch (TLI.getOperationAction(ISD::SINT_TO_FP, NewInTy)) {
6174      default: break;
6175      case TargetLowering::Legal:
6176        if (!TLI.isTypeLegal(NewInTy))
6177          break;  // Can't use this datatype.
6178        // FALL THROUGH.
6179      case TargetLowering::Custom:
6180        OpToUse = ISD::SINT_TO_FP;
6181        break;
6182    }
6183    if (OpToUse) break;
6184    if (isSigned) continue;
6185
6186    // If the target supports UINT_TO_FP of this type, use it.
6187    switch (TLI.getOperationAction(ISD::UINT_TO_FP, NewInTy)) {
6188      default: break;
6189      case TargetLowering::Legal:
6190        if (!TLI.isTypeLegal(NewInTy))
6191          break;  // Can't use this datatype.
6192        // FALL THROUGH.
6193      case TargetLowering::Custom:
6194        OpToUse = ISD::UINT_TO_FP;
6195        break;
6196    }
6197    if (OpToUse) break;
6198
6199    // Otherwise, try a larger type.
6200  }
6201
6202  // Okay, we found the operation and type to use.  Zero extend our input to the
6203  // desired type then run the operation on it.
6204  return DAG.getNode(OpToUse, DestVT,
6205                     DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
6206                                 NewInTy, LegalOp));
6207}
6208
6209/// PromoteLegalFP_TO_INT - This function is responsible for legalizing a
6210/// FP_TO_*INT operation of the specified operand when the target requests that
6211/// we promote it.  At this point, we know that the result and operand types are
6212/// legal for the target, and that there is a legal FP_TO_UINT or FP_TO_SINT
6213/// operation that returns a larger result.
6214SDValue SelectionDAGLegalize::PromoteLegalFP_TO_INT(SDValue LegalOp,
6215                                                    MVT DestVT,
6216                                                    bool isSigned) {
6217  // First step, figure out the appropriate FP_TO*INT operation to use.
6218  MVT NewOutTy = DestVT;
6219
6220  unsigned OpToUse = 0;
6221
6222  // Scan for the appropriate larger type to use.
6223  while (1) {
6224    NewOutTy = (MVT::SimpleValueType)(NewOutTy.getSimpleVT()+1);
6225    assert(NewOutTy.isInteger() && "Ran out of possibilities!");
6226
6227    // If the target supports FP_TO_SINT returning this type, use it.
6228    switch (TLI.getOperationAction(ISD::FP_TO_SINT, NewOutTy)) {
6229    default: break;
6230    case TargetLowering::Legal:
6231      if (!TLI.isTypeLegal(NewOutTy))
6232        break;  // Can't use this datatype.
6233      // FALL THROUGH.
6234    case TargetLowering::Custom:
6235      OpToUse = ISD::FP_TO_SINT;
6236      break;
6237    }
6238    if (OpToUse) break;
6239
6240    // If the target supports FP_TO_UINT of this type, use it.
6241    switch (TLI.getOperationAction(ISD::FP_TO_UINT, NewOutTy)) {
6242    default: break;
6243    case TargetLowering::Legal:
6244      if (!TLI.isTypeLegal(NewOutTy))
6245        break;  // Can't use this datatype.
6246      // FALL THROUGH.
6247    case TargetLowering::Custom:
6248      OpToUse = ISD::FP_TO_UINT;
6249      break;
6250    }
6251    if (OpToUse) break;
6252
6253    // Otherwise, try a larger type.
6254  }
6255
6256
6257  // Okay, we found the operation and type to use.
6258  SDValue Operation = DAG.getNode(OpToUse, NewOutTy, LegalOp);
6259
6260  // If the operation produces an invalid type, it must be custom lowered.  Use
6261  // the target lowering hooks to expand it.  Just keep the low part of the
6262  // expanded operation, we know that we're truncating anyway.
6263  if (getTypeAction(NewOutTy) == Expand) {
6264    SmallVector<SDValue, 2> Results;
6265    TLI.ReplaceNodeResults(Operation.getNode(), Results, DAG);
6266    assert(Results.size() == 1 && "Incorrect FP_TO_XINT lowering!");
6267    Operation = Results[0];
6268  }
6269
6270  // Truncate the result of the extended FP_TO_*INT operation to the desired
6271  // size.
6272  return DAG.getNode(ISD::TRUNCATE, DestVT, Operation);
6273}
6274
6275/// ExpandBSWAP - Open code the operations for BSWAP of the specified operation.
6276///
6277SDValue SelectionDAGLegalize::ExpandBSWAP(SDValue Op) {
6278  MVT VT = Op.getValueType();
6279  MVT SHVT = TLI.getShiftAmountTy();
6280  SDValue Tmp1, Tmp2, Tmp3, Tmp4, Tmp5, Tmp6, Tmp7, Tmp8;
6281  switch (VT.getSimpleVT()) {
6282  default: assert(0 && "Unhandled Expand type in BSWAP!"); abort();
6283  case MVT::i16:
6284    Tmp2 = DAG.getNode(ISD::SHL, VT, Op, DAG.getConstant(8, SHVT));
6285    Tmp1 = DAG.getNode(ISD::SRL, VT, Op, DAG.getConstant(8, SHVT));
6286    return DAG.getNode(ISD::OR, VT, Tmp1, Tmp2);
6287  case MVT::i32:
6288    Tmp4 = DAG.getNode(ISD::SHL, VT, Op, DAG.getConstant(24, SHVT));
6289    Tmp3 = DAG.getNode(ISD::SHL, VT, Op, DAG.getConstant(8, SHVT));
6290    Tmp2 = DAG.getNode(ISD::SRL, VT, Op, DAG.getConstant(8, SHVT));
6291    Tmp1 = DAG.getNode(ISD::SRL, VT, Op, DAG.getConstant(24, SHVT));
6292    Tmp3 = DAG.getNode(ISD::AND, VT, Tmp3, DAG.getConstant(0xFF0000, VT));
6293    Tmp2 = DAG.getNode(ISD::AND, VT, Tmp2, DAG.getConstant(0xFF00, VT));
6294    Tmp4 = DAG.getNode(ISD::OR, VT, Tmp4, Tmp3);
6295    Tmp2 = DAG.getNode(ISD::OR, VT, Tmp2, Tmp1);
6296    return DAG.getNode(ISD::OR, VT, Tmp4, Tmp2);
6297  case MVT::i64:
6298    Tmp8 = DAG.getNode(ISD::SHL, VT, Op, DAG.getConstant(56, SHVT));
6299    Tmp7 = DAG.getNode(ISD::SHL, VT, Op, DAG.getConstant(40, SHVT));
6300    Tmp6 = DAG.getNode(ISD::SHL, VT, Op, DAG.getConstant(24, SHVT));
6301    Tmp5 = DAG.getNode(ISD::SHL, VT, Op, DAG.getConstant(8, SHVT));
6302    Tmp4 = DAG.getNode(ISD::SRL, VT, Op, DAG.getConstant(8, SHVT));
6303    Tmp3 = DAG.getNode(ISD::SRL, VT, Op, DAG.getConstant(24, SHVT));
6304    Tmp2 = DAG.getNode(ISD::SRL, VT, Op, DAG.getConstant(40, SHVT));
6305    Tmp1 = DAG.getNode(ISD::SRL, VT, Op, DAG.getConstant(56, SHVT));
6306    Tmp7 = DAG.getNode(ISD::AND, VT, Tmp7, DAG.getConstant(255ULL<<48, VT));
6307    Tmp6 = DAG.getNode(ISD::AND, VT, Tmp6, DAG.getConstant(255ULL<<40, VT));
6308    Tmp5 = DAG.getNode(ISD::AND, VT, Tmp5, DAG.getConstant(255ULL<<32, VT));
6309    Tmp4 = DAG.getNode(ISD::AND, VT, Tmp4, DAG.getConstant(255ULL<<24, VT));
6310    Tmp3 = DAG.getNode(ISD::AND, VT, Tmp3, DAG.getConstant(255ULL<<16, VT));
6311    Tmp2 = DAG.getNode(ISD::AND, VT, Tmp2, DAG.getConstant(255ULL<<8 , VT));
6312    Tmp8 = DAG.getNode(ISD::OR, VT, Tmp8, Tmp7);
6313    Tmp6 = DAG.getNode(ISD::OR, VT, Tmp6, Tmp5);
6314    Tmp4 = DAG.getNode(ISD::OR, VT, Tmp4, Tmp3);
6315    Tmp2 = DAG.getNode(ISD::OR, VT, Tmp2, Tmp1);
6316    Tmp8 = DAG.getNode(ISD::OR, VT, Tmp8, Tmp6);
6317    Tmp4 = DAG.getNode(ISD::OR, VT, Tmp4, Tmp2);
6318    return DAG.getNode(ISD::OR, VT, Tmp8, Tmp4);
6319  }
6320}
6321
6322/// ExpandBitCount - Expand the specified bitcount instruction into operations.
6323///
6324SDValue SelectionDAGLegalize::ExpandBitCount(unsigned Opc, SDValue Op) {
6325  switch (Opc) {
6326  default: assert(0 && "Cannot expand this yet!");
6327  case ISD::CTPOP: {
6328    static const uint64_t mask[6] = {
6329      0x5555555555555555ULL, 0x3333333333333333ULL,
6330      0x0F0F0F0F0F0F0F0FULL, 0x00FF00FF00FF00FFULL,
6331      0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL
6332    };
6333    MVT VT = Op.getValueType();
6334    MVT ShVT = TLI.getShiftAmountTy();
6335    unsigned len = VT.getSizeInBits();
6336    for (unsigned i = 0; (1U << i) <= (len / 2); ++i) {
6337      //x = (x & mask[i][len/8]) + (x >> (1 << i) & mask[i][len/8])
6338      SDValue Tmp2 = DAG.getConstant(mask[i], VT);
6339      SDValue Tmp3 = DAG.getConstant(1ULL << i, ShVT);
6340      Op = DAG.getNode(ISD::ADD, VT, DAG.getNode(ISD::AND, VT, Op, Tmp2),
6341                       DAG.getNode(ISD::AND, VT,
6342                                   DAG.getNode(ISD::SRL, VT, Op, Tmp3),Tmp2));
6343    }
6344    return Op;
6345  }
6346  case ISD::CTLZ: {
6347    // for now, we do this:
6348    // x = x | (x >> 1);
6349    // x = x | (x >> 2);
6350    // ...
6351    // x = x | (x >>16);
6352    // x = x | (x >>32); // for 64-bit input
6353    // return popcount(~x);
6354    //
6355    // but see also: http://www.hackersdelight.org/HDcode/nlz.cc
6356    MVT VT = Op.getValueType();
6357    MVT ShVT = TLI.getShiftAmountTy();
6358    unsigned len = VT.getSizeInBits();
6359    for (unsigned i = 0; (1U << i) <= (len / 2); ++i) {
6360      SDValue Tmp3 = DAG.getConstant(1ULL << i, ShVT);
6361      Op = DAG.getNode(ISD::OR, VT, Op, DAG.getNode(ISD::SRL, VT, Op, Tmp3));
6362    }
6363    Op = DAG.getNode(ISD::XOR, VT, Op, DAG.getConstant(~0ULL, VT));
6364    return DAG.getNode(ISD::CTPOP, VT, Op);
6365  }
6366  case ISD::CTTZ: {
6367    // for now, we use: { return popcount(~x & (x - 1)); }
6368    // unless the target has ctlz but not ctpop, in which case we use:
6369    // { return 32 - nlz(~x & (x-1)); }
6370    // see also http://www.hackersdelight.org/HDcode/ntz.cc
6371    MVT VT = Op.getValueType();
6372    SDValue Tmp2 = DAG.getConstant(~0ULL, VT);
6373    SDValue Tmp3 = DAG.getNode(ISD::AND, VT,
6374                       DAG.getNode(ISD::XOR, VT, Op, Tmp2),
6375                       DAG.getNode(ISD::SUB, VT, Op, DAG.getConstant(1, VT)));
6376    // If ISD::CTLZ is legal and CTPOP isn't, then do that instead.
6377    if (!TLI.isOperationLegal(ISD::CTPOP, VT) &&
6378        TLI.isOperationLegal(ISD::CTLZ, VT))
6379      return DAG.getNode(ISD::SUB, VT,
6380                         DAG.getConstant(VT.getSizeInBits(), VT),
6381                         DAG.getNode(ISD::CTLZ, VT, Tmp3));
6382    return DAG.getNode(ISD::CTPOP, VT, Tmp3);
6383  }
6384  }
6385}
6386
6387/// ExpandOp - Expand the specified SDValue into its two component pieces
6388/// Lo&Hi.  Note that the Op MUST be an expanded type.  As a result of this, the
6389/// LegalizedNodes map is filled in for any results that are not expanded, the
6390/// ExpandedNodes map is filled in for any results that are expanded, and the
6391/// Lo/Hi values are returned.
6392void SelectionDAGLegalize::ExpandOp(SDValue Op, SDValue &Lo, SDValue &Hi){
6393  MVT VT = Op.getValueType();
6394  MVT NVT = TLI.getTypeToTransformTo(VT);
6395  SDNode *Node = Op.getNode();
6396  assert(getTypeAction(VT) == Expand && "Not an expanded type!");
6397  assert(((NVT.isInteger() && NVT.bitsLT(VT)) || VT.isFloatingPoint() ||
6398         VT.isVector()) && "Cannot expand to FP value or to larger int value!");
6399
6400  // See if we already expanded it.
6401  DenseMap<SDValue, std::pair<SDValue, SDValue> >::iterator I
6402    = ExpandedNodes.find(Op);
6403  if (I != ExpandedNodes.end()) {
6404    Lo = I->second.first;
6405    Hi = I->second.second;
6406    return;
6407  }
6408
6409  switch (Node->getOpcode()) {
6410  case ISD::CopyFromReg:
6411    assert(0 && "CopyFromReg must be legal!");
6412  case ISD::FP_ROUND_INREG:
6413    if (VT == MVT::ppcf128 &&
6414        TLI.getOperationAction(ISD::FP_ROUND_INREG, VT) ==
6415            TargetLowering::Custom) {
6416      SDValue SrcLo, SrcHi, Src;
6417      ExpandOp(Op.getOperand(0), SrcLo, SrcHi);
6418      Src = DAG.getNode(ISD::BUILD_PAIR, VT, SrcLo, SrcHi);
6419      SDValue Result = TLI.LowerOperation(
6420        DAG.getNode(ISD::FP_ROUND_INREG, VT, Src, Op.getOperand(1)), DAG);
6421      assert(Result.getNode()->getOpcode() == ISD::BUILD_PAIR);
6422      Lo = Result.getNode()->getOperand(0);
6423      Hi = Result.getNode()->getOperand(1);
6424      break;
6425    }
6426    // fall through
6427  default:
6428#ifndef NDEBUG
6429    cerr << "NODE: "; Node->dump(&DAG); cerr << "\n";
6430#endif
6431    assert(0 && "Do not know how to expand this operator!");
6432    abort();
6433  case ISD::EXTRACT_ELEMENT:
6434    ExpandOp(Node->getOperand(0), Lo, Hi);
6435    if (cast<ConstantSDNode>(Node->getOperand(1))->getZExtValue())
6436      return ExpandOp(Hi, Lo, Hi);
6437    return ExpandOp(Lo, Lo, Hi);
6438  case ISD::EXTRACT_VECTOR_ELT:
6439    // ExpandEXTRACT_VECTOR_ELT tolerates invalid result types.
6440    Lo  = ExpandEXTRACT_VECTOR_ELT(Op);
6441    return ExpandOp(Lo, Lo, Hi);
6442  case ISD::UNDEF:
6443    Lo = DAG.getNode(ISD::UNDEF, NVT);
6444    Hi = DAG.getNode(ISD::UNDEF, NVT);
6445    break;
6446  case ISD::Constant: {
6447    unsigned NVTBits = NVT.getSizeInBits();
6448    const APInt &Cst = cast<ConstantSDNode>(Node)->getAPIntValue();
6449    Lo = DAG.getConstant(APInt(Cst).trunc(NVTBits), NVT);
6450    Hi = DAG.getConstant(Cst.lshr(NVTBits).trunc(NVTBits), NVT);
6451    break;
6452  }
6453  case ISD::ConstantFP: {
6454    ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Node);
6455    if (CFP->getValueType(0) == MVT::ppcf128) {
6456      APInt api = CFP->getValueAPF().bitcastToAPInt();
6457      Lo = DAG.getConstantFP(APFloat(APInt(64, 1, &api.getRawData()[1])),
6458                             MVT::f64);
6459      Hi = DAG.getConstantFP(APFloat(APInt(64, 1, &api.getRawData()[0])),
6460                             MVT::f64);
6461      break;
6462    }
6463    Lo = ExpandConstantFP(CFP, false, DAG, TLI);
6464    if (getTypeAction(Lo.getValueType()) == Expand)
6465      ExpandOp(Lo, Lo, Hi);
6466    break;
6467  }
6468  case ISD::BUILD_PAIR:
6469    // Return the operands.
6470    Lo = Node->getOperand(0);
6471    Hi = Node->getOperand(1);
6472    break;
6473
6474  case ISD::MERGE_VALUES:
6475    if (Node->getNumValues() == 1) {
6476      ExpandOp(Op.getOperand(0), Lo, Hi);
6477      break;
6478    }
6479    // FIXME: For now only expand i64,chain = MERGE_VALUES (x, y)
6480    assert(Op.getResNo() == 0 && Node->getNumValues() == 2 &&
6481           Op.getValue(1).getValueType() == MVT::Other &&
6482           "unhandled MERGE_VALUES");
6483    ExpandOp(Op.getOperand(0), Lo, Hi);
6484    // Remember that we legalized the chain.
6485    AddLegalizedOperand(Op.getValue(1), LegalizeOp(Op.getOperand(1)));
6486    break;
6487
6488  case ISD::SIGN_EXTEND_INREG:
6489    ExpandOp(Node->getOperand(0), Lo, Hi);
6490    // sext_inreg the low part if needed.
6491    Lo = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Lo, Node->getOperand(1));
6492
6493    // The high part gets the sign extension from the lo-part.  This handles
6494    // things like sextinreg V:i64 from i8.
6495    Hi = DAG.getNode(ISD::SRA, NVT, Lo,
6496                     DAG.getConstant(NVT.getSizeInBits()-1,
6497                                     TLI.getShiftAmountTy()));
6498    break;
6499
6500  case ISD::BSWAP: {
6501    ExpandOp(Node->getOperand(0), Lo, Hi);
6502    SDValue TempLo = DAG.getNode(ISD::BSWAP, NVT, Hi);
6503    Hi = DAG.getNode(ISD::BSWAP, NVT, Lo);
6504    Lo = TempLo;
6505    break;
6506  }
6507
6508  case ISD::CTPOP:
6509    ExpandOp(Node->getOperand(0), Lo, Hi);
6510    Lo = DAG.getNode(ISD::ADD, NVT,          // ctpop(HL) -> ctpop(H)+ctpop(L)
6511                     DAG.getNode(ISD::CTPOP, NVT, Lo),
6512                     DAG.getNode(ISD::CTPOP, NVT, Hi));
6513    Hi = DAG.getConstant(0, NVT);
6514    break;
6515
6516  case ISD::CTLZ: {
6517    // ctlz (HL) -> ctlz(H) != 32 ? ctlz(H) : (ctlz(L)+32)
6518    ExpandOp(Node->getOperand(0), Lo, Hi);
6519    SDValue BitsC = DAG.getConstant(NVT.getSizeInBits(), NVT);
6520    SDValue HLZ = DAG.getNode(ISD::CTLZ, NVT, Hi);
6521    SDValue TopNotZero = DAG.getSetCC(TLI.getSetCCResultType(HLZ), HLZ, BitsC,
6522                                        ISD::SETNE);
6523    SDValue LowPart = DAG.getNode(ISD::CTLZ, NVT, Lo);
6524    LowPart = DAG.getNode(ISD::ADD, NVT, LowPart, BitsC);
6525
6526    Lo = DAG.getNode(ISD::SELECT, NVT, TopNotZero, HLZ, LowPart);
6527    Hi = DAG.getConstant(0, NVT);
6528    break;
6529  }
6530
6531  case ISD::CTTZ: {
6532    // cttz (HL) -> cttz(L) != 32 ? cttz(L) : (cttz(H)+32)
6533    ExpandOp(Node->getOperand(0), Lo, Hi);
6534    SDValue BitsC = DAG.getConstant(NVT.getSizeInBits(), NVT);
6535    SDValue LTZ = DAG.getNode(ISD::CTTZ, NVT, Lo);
6536    SDValue BotNotZero = DAG.getSetCC(TLI.getSetCCResultType(LTZ), LTZ, BitsC,
6537                                        ISD::SETNE);
6538    SDValue HiPart = DAG.getNode(ISD::CTTZ, NVT, Hi);
6539    HiPart = DAG.getNode(ISD::ADD, NVT, HiPart, BitsC);
6540
6541    Lo = DAG.getNode(ISD::SELECT, NVT, BotNotZero, LTZ, HiPart);
6542    Hi = DAG.getConstant(0, NVT);
6543    break;
6544  }
6545
6546  case ISD::VAARG: {
6547    SDValue Ch = Node->getOperand(0);   // Legalize the chain.
6548    SDValue Ptr = Node->getOperand(1);  // Legalize the pointer.
6549    Lo = DAG.getVAArg(NVT, Ch, Ptr, Node->getOperand(2));
6550    Hi = DAG.getVAArg(NVT, Lo.getValue(1), Ptr, Node->getOperand(2));
6551
6552    // Remember that we legalized the chain.
6553    Hi = LegalizeOp(Hi);
6554    AddLegalizedOperand(Op.getValue(1), Hi.getValue(1));
6555    if (TLI.isBigEndian())
6556      std::swap(Lo, Hi);
6557    break;
6558  }
6559
6560  case ISD::LOAD: {
6561    LoadSDNode *LD = cast<LoadSDNode>(Node);
6562    SDValue Ch  = LD->getChain();    // Legalize the chain.
6563    SDValue Ptr = LD->getBasePtr();  // Legalize the pointer.
6564    ISD::LoadExtType ExtType = LD->getExtensionType();
6565    const Value *SV = LD->getSrcValue();
6566    int SVOffset = LD->getSrcValueOffset();
6567    unsigned Alignment = LD->getAlignment();
6568    bool isVolatile = LD->isVolatile();
6569
6570    if (ExtType == ISD::NON_EXTLOAD) {
6571      Lo = DAG.getLoad(NVT, Ch, Ptr, SV, SVOffset,
6572                       isVolatile, Alignment);
6573      if (VT == MVT::f32 || VT == MVT::f64) {
6574        // f32->i32 or f64->i64 one to one expansion.
6575        // Remember that we legalized the chain.
6576        AddLegalizedOperand(SDValue(Node, 1), LegalizeOp(Lo.getValue(1)));
6577        // Recursively expand the new load.
6578        if (getTypeAction(NVT) == Expand)
6579          ExpandOp(Lo, Lo, Hi);
6580        break;
6581      }
6582
6583      // Increment the pointer to the other half.
6584      unsigned IncrementSize = Lo.getValueType().getSizeInBits()/8;
6585      Ptr = DAG.getNode(ISD::ADD, Ptr.getValueType(), Ptr,
6586                        DAG.getIntPtrConstant(IncrementSize));
6587      SVOffset += IncrementSize;
6588      Alignment = MinAlign(Alignment, IncrementSize);
6589      Hi = DAG.getLoad(NVT, Ch, Ptr, SV, SVOffset,
6590                       isVolatile, Alignment);
6591
6592      // Build a factor node to remember that this load is independent of the
6593      // other one.
6594      SDValue TF = DAG.getNode(ISD::TokenFactor, MVT::Other, Lo.getValue(1),
6595                                 Hi.getValue(1));
6596
6597      // Remember that we legalized the chain.
6598      AddLegalizedOperand(Op.getValue(1), LegalizeOp(TF));
6599      if (TLI.isBigEndian())
6600        std::swap(Lo, Hi);
6601    } else {
6602      MVT EVT = LD->getMemoryVT();
6603
6604      if ((VT == MVT::f64 && EVT == MVT::f32) ||
6605          (VT == MVT::ppcf128 && (EVT==MVT::f64 || EVT==MVT::f32))) {
6606        // f64 = EXTLOAD f32 should expand to LOAD, FP_EXTEND
6607        SDValue Load = DAG.getLoad(EVT, Ch, Ptr, SV,
6608                                     SVOffset, isVolatile, Alignment);
6609        // Remember that we legalized the chain.
6610        AddLegalizedOperand(SDValue(Node, 1), LegalizeOp(Load.getValue(1)));
6611        ExpandOp(DAG.getNode(ISD::FP_EXTEND, VT, Load), Lo, Hi);
6612        break;
6613      }
6614
6615      if (EVT == NVT)
6616        Lo = DAG.getLoad(NVT, Ch, Ptr, SV,
6617                         SVOffset, isVolatile, Alignment);
6618      else
6619        Lo = DAG.getExtLoad(ExtType, NVT, Ch, Ptr, SV,
6620                            SVOffset, EVT, isVolatile,
6621                            Alignment);
6622
6623      // Remember that we legalized the chain.
6624      AddLegalizedOperand(SDValue(Node, 1), LegalizeOp(Lo.getValue(1)));
6625
6626      if (ExtType == ISD::SEXTLOAD) {
6627        // The high part is obtained by SRA'ing all but one of the bits of the
6628        // lo part.
6629        unsigned LoSize = Lo.getValueType().getSizeInBits();
6630        Hi = DAG.getNode(ISD::SRA, NVT, Lo,
6631                         DAG.getConstant(LoSize-1, TLI.getShiftAmountTy()));
6632      } else if (ExtType == ISD::ZEXTLOAD) {
6633        // The high part is just a zero.
6634        Hi = DAG.getConstant(0, NVT);
6635      } else /* if (ExtType == ISD::EXTLOAD) */ {
6636        // The high part is undefined.
6637        Hi = DAG.getNode(ISD::UNDEF, NVT);
6638      }
6639    }
6640    break;
6641  }
6642  case ISD::AND:
6643  case ISD::OR:
6644  case ISD::XOR: {   // Simple logical operators -> two trivial pieces.
6645    SDValue LL, LH, RL, RH;
6646    ExpandOp(Node->getOperand(0), LL, LH);
6647    ExpandOp(Node->getOperand(1), RL, RH);
6648    Lo = DAG.getNode(Node->getOpcode(), NVT, LL, RL);
6649    Hi = DAG.getNode(Node->getOpcode(), NVT, LH, RH);
6650    break;
6651  }
6652  case ISD::SELECT: {
6653    SDValue LL, LH, RL, RH;
6654    ExpandOp(Node->getOperand(1), LL, LH);
6655    ExpandOp(Node->getOperand(2), RL, RH);
6656    if (getTypeAction(NVT) == Expand)
6657      NVT = TLI.getTypeToExpandTo(NVT);
6658    Lo = DAG.getNode(ISD::SELECT, NVT, Node->getOperand(0), LL, RL);
6659    if (VT != MVT::f32)
6660      Hi = DAG.getNode(ISD::SELECT, NVT, Node->getOperand(0), LH, RH);
6661    break;
6662  }
6663  case ISD::SELECT_CC: {
6664    SDValue TL, TH, FL, FH;
6665    ExpandOp(Node->getOperand(2), TL, TH);
6666    ExpandOp(Node->getOperand(3), FL, FH);
6667    if (getTypeAction(NVT) == Expand)
6668      NVT = TLI.getTypeToExpandTo(NVT);
6669    Lo = DAG.getNode(ISD::SELECT_CC, NVT, Node->getOperand(0),
6670                     Node->getOperand(1), TL, FL, Node->getOperand(4));
6671    if (VT != MVT::f32)
6672      Hi = DAG.getNode(ISD::SELECT_CC, NVT, Node->getOperand(0),
6673                       Node->getOperand(1), TH, FH, Node->getOperand(4));
6674    break;
6675  }
6676  case ISD::ANY_EXTEND:
6677    // The low part is any extension of the input (which degenerates to a copy).
6678    Lo = DAG.getNode(ISD::ANY_EXTEND, NVT, Node->getOperand(0));
6679    // The high part is undefined.
6680    Hi = DAG.getNode(ISD::UNDEF, NVT);
6681    break;
6682  case ISD::SIGN_EXTEND: {
6683    // The low part is just a sign extension of the input (which degenerates to
6684    // a copy).
6685    Lo = DAG.getNode(ISD::SIGN_EXTEND, NVT, Node->getOperand(0));
6686
6687    // The high part is obtained by SRA'ing all but one of the bits of the lo
6688    // part.
6689    unsigned LoSize = Lo.getValueType().getSizeInBits();
6690    Hi = DAG.getNode(ISD::SRA, NVT, Lo,
6691                     DAG.getConstant(LoSize-1, TLI.getShiftAmountTy()));
6692    break;
6693  }
6694  case ISD::ZERO_EXTEND:
6695    // The low part is just a zero extension of the input (which degenerates to
6696    // a copy).
6697    Lo = DAG.getNode(ISD::ZERO_EXTEND, NVT, Node->getOperand(0));
6698
6699    // The high part is just a zero.
6700    Hi = DAG.getConstant(0, NVT);
6701    break;
6702
6703  case ISD::TRUNCATE: {
6704    // The input value must be larger than this value.  Expand *it*.
6705    SDValue NewLo;
6706    ExpandOp(Node->getOperand(0), NewLo, Hi);
6707
6708    // The low part is now either the right size, or it is closer.  If not the
6709    // right size, make an illegal truncate so we recursively expand it.
6710    if (NewLo.getValueType() != Node->getValueType(0))
6711      NewLo = DAG.getNode(ISD::TRUNCATE, Node->getValueType(0), NewLo);
6712    ExpandOp(NewLo, Lo, Hi);
6713    break;
6714  }
6715
6716  case ISD::BIT_CONVERT: {
6717    SDValue Tmp;
6718    if (TLI.getOperationAction(ISD::BIT_CONVERT, VT) == TargetLowering::Custom){
6719      // If the target wants to, allow it to lower this itself.
6720      switch (getTypeAction(Node->getOperand(0).getValueType())) {
6721      case Expand: assert(0 && "cannot expand FP!");
6722      case Legal:   Tmp = LegalizeOp(Node->getOperand(0)); break;
6723      case Promote: Tmp = PromoteOp (Node->getOperand(0)); break;
6724      }
6725      Tmp = TLI.LowerOperation(DAG.getNode(ISD::BIT_CONVERT, VT, Tmp), DAG);
6726    }
6727
6728    // f32 / f64 must be expanded to i32 / i64.
6729    if (VT == MVT::f32 || VT == MVT::f64) {
6730      Lo = DAG.getNode(ISD::BIT_CONVERT, NVT, Node->getOperand(0));
6731      if (getTypeAction(NVT) == Expand)
6732        ExpandOp(Lo, Lo, Hi);
6733      break;
6734    }
6735
6736    // If source operand will be expanded to the same type as VT, i.e.
6737    // i64 <- f64, i32 <- f32, expand the source operand instead.
6738    MVT VT0 = Node->getOperand(0).getValueType();
6739    if (getTypeAction(VT0) == Expand && TLI.getTypeToTransformTo(VT0) == VT) {
6740      ExpandOp(Node->getOperand(0), Lo, Hi);
6741      break;
6742    }
6743
6744    // Turn this into a load/store pair by default.
6745    if (Tmp.getNode() == 0)
6746      Tmp = EmitStackConvert(Node->getOperand(0), VT, VT);
6747
6748    ExpandOp(Tmp, Lo, Hi);
6749    break;
6750  }
6751
6752  case ISD::READCYCLECOUNTER: {
6753    assert(TLI.getOperationAction(ISD::READCYCLECOUNTER, VT) ==
6754                 TargetLowering::Custom &&
6755           "Must custom expand ReadCycleCounter");
6756    SDValue Tmp = TLI.LowerOperation(Op, DAG);
6757    assert(Tmp.getNode() && "Node must be custom expanded!");
6758    ExpandOp(Tmp.getValue(0), Lo, Hi);
6759    AddLegalizedOperand(SDValue(Node, 1), // Remember we legalized the chain.
6760                        LegalizeOp(Tmp.getValue(1)));
6761    break;
6762  }
6763
6764  case ISD::ATOMIC_CMP_SWAP_64: {
6765    // This operation does not need a loop.
6766    SDValue Tmp = TLI.LowerOperation(Op, DAG);
6767    assert(Tmp.getNode() && "Node must be custom expanded!");
6768    ExpandOp(Tmp.getValue(0), Lo, Hi);
6769    AddLegalizedOperand(SDValue(Node, 1), // Remember we legalized the chain.
6770                        LegalizeOp(Tmp.getValue(1)));
6771    break;
6772  }
6773
6774  case ISD::ATOMIC_LOAD_ADD_64:
6775  case ISD::ATOMIC_LOAD_SUB_64:
6776  case ISD::ATOMIC_LOAD_AND_64:
6777  case ISD::ATOMIC_LOAD_OR_64:
6778  case ISD::ATOMIC_LOAD_XOR_64:
6779  case ISD::ATOMIC_LOAD_NAND_64:
6780  case ISD::ATOMIC_SWAP_64: {
6781    // These operations require a loop to be generated.  We can't do that yet,
6782    // so substitute a target-dependent pseudo and expand that later.
6783    SDValue In2Lo, In2Hi, In2;
6784    ExpandOp(Op.getOperand(2), In2Lo, In2Hi);
6785    In2 = DAG.getNode(ISD::BUILD_PAIR, VT, In2Lo, In2Hi);
6786    AtomicSDNode* Anode = cast<AtomicSDNode>(Node);
6787    SDValue Replace =
6788      DAG.getAtomic(Op.getOpcode(), Op.getOperand(0), Op.getOperand(1), In2,
6789                    Anode->getSrcValue(), Anode->getAlignment());
6790    SDValue Result = TLI.LowerOperation(Replace, DAG);
6791    ExpandOp(Result.getValue(0), Lo, Hi);
6792    // Remember that we legalized the chain.
6793    AddLegalizedOperand(SDValue(Node,1), LegalizeOp(Result.getValue(1)));
6794    break;
6795  }
6796
6797    // These operators cannot be expanded directly, emit them as calls to
6798    // library functions.
6799  case ISD::FP_TO_SINT: {
6800    if (TLI.getOperationAction(ISD::FP_TO_SINT, VT) == TargetLowering::Custom) {
6801      SDValue Op;
6802      switch (getTypeAction(Node->getOperand(0).getValueType())) {
6803      case Expand: assert(0 && "cannot expand FP!");
6804      case Legal:   Op = LegalizeOp(Node->getOperand(0)); break;
6805      case Promote: Op = PromoteOp (Node->getOperand(0)); break;
6806      }
6807
6808      Op = TLI.LowerOperation(DAG.getNode(ISD::FP_TO_SINT, VT, Op), DAG);
6809
6810      // Now that the custom expander is done, expand the result, which is still
6811      // VT.
6812      if (Op.getNode()) {
6813        ExpandOp(Op, Lo, Hi);
6814        break;
6815      }
6816    }
6817
6818    RTLIB::Libcall LC = RTLIB::getFPTOSINT(Node->getOperand(0).getValueType(),
6819                                           VT);
6820    assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unexpected uint-to-fp conversion!");
6821    Lo = ExpandLibCall(LC, Node, false/*sign irrelevant*/, Hi);
6822    break;
6823  }
6824
6825  case ISD::FP_TO_UINT: {
6826    if (TLI.getOperationAction(ISD::FP_TO_UINT, VT) == TargetLowering::Custom) {
6827      SDValue Op;
6828      switch (getTypeAction(Node->getOperand(0).getValueType())) {
6829        case Expand: assert(0 && "cannot expand FP!");
6830        case Legal:   Op = LegalizeOp(Node->getOperand(0)); break;
6831        case Promote: Op = PromoteOp (Node->getOperand(0)); break;
6832      }
6833
6834      Op = TLI.LowerOperation(DAG.getNode(ISD::FP_TO_UINT, VT, Op), DAG);
6835
6836      // Now that the custom expander is done, expand the result.
6837      if (Op.getNode()) {
6838        ExpandOp(Op, Lo, Hi);
6839        break;
6840      }
6841    }
6842
6843    RTLIB::Libcall LC = RTLIB::getFPTOUINT(Node->getOperand(0).getValueType(),
6844                                           VT);
6845    assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unexpected fp-to-uint conversion!");
6846    Lo = ExpandLibCall(LC, Node, false/*sign irrelevant*/, Hi);
6847    break;
6848  }
6849
6850  case ISD::SHL: {
6851    // If the target wants custom lowering, do so.
6852    SDValue ShiftAmt = LegalizeOp(Node->getOperand(1));
6853    if (TLI.getOperationAction(ISD::SHL, VT) == TargetLowering::Custom) {
6854      SDValue Op = DAG.getNode(ISD::SHL, VT, Node->getOperand(0), ShiftAmt);
6855      Op = TLI.LowerOperation(Op, DAG);
6856      if (Op.getNode()) {
6857        // Now that the custom expander is done, expand the result, which is
6858        // still VT.
6859        ExpandOp(Op, Lo, Hi);
6860        break;
6861      }
6862    }
6863
6864    // If ADDC/ADDE are supported and if the shift amount is a constant 1, emit
6865    // this X << 1 as X+X.
6866    if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(ShiftAmt)) {
6867      if (ShAmt->getAPIntValue() == 1 && TLI.isOperationLegal(ISD::ADDC, NVT) &&
6868          TLI.isOperationLegal(ISD::ADDE, NVT)) {
6869        SDValue LoOps[2], HiOps[3];
6870        ExpandOp(Node->getOperand(0), LoOps[0], HiOps[0]);
6871        SDVTList VTList = DAG.getVTList(LoOps[0].getValueType(), MVT::Flag);
6872        LoOps[1] = LoOps[0];
6873        Lo = DAG.getNode(ISD::ADDC, VTList, LoOps, 2);
6874
6875        HiOps[1] = HiOps[0];
6876        HiOps[2] = Lo.getValue(1);
6877        Hi = DAG.getNode(ISD::ADDE, VTList, HiOps, 3);
6878        break;
6879      }
6880    }
6881
6882    // If we can emit an efficient shift operation, do so now.
6883    if (ExpandShift(ISD::SHL, Node->getOperand(0), ShiftAmt, Lo, Hi))
6884      break;
6885
6886    // If this target supports SHL_PARTS, use it.
6887    TargetLowering::LegalizeAction Action =
6888      TLI.getOperationAction(ISD::SHL_PARTS, NVT);
6889    if ((Action == TargetLowering::Legal && TLI.isTypeLegal(NVT)) ||
6890        Action == TargetLowering::Custom) {
6891      ExpandShiftParts(ISD::SHL_PARTS, Node->getOperand(0), ShiftAmt, Lo, Hi);
6892      break;
6893    }
6894
6895    // Otherwise, emit a libcall.
6896    Lo = ExpandLibCall(RTLIB::SHL_I64, Node, false/*left shift=unsigned*/, Hi);
6897    break;
6898  }
6899
6900  case ISD::SRA: {
6901    // If the target wants custom lowering, do so.
6902    SDValue ShiftAmt = LegalizeOp(Node->getOperand(1));
6903    if (TLI.getOperationAction(ISD::SRA, VT) == TargetLowering::Custom) {
6904      SDValue Op = DAG.getNode(ISD::SRA, VT, Node->getOperand(0), ShiftAmt);
6905      Op = TLI.LowerOperation(Op, DAG);
6906      if (Op.getNode()) {
6907        // Now that the custom expander is done, expand the result, which is
6908        // still VT.
6909        ExpandOp(Op, Lo, Hi);
6910        break;
6911      }
6912    }
6913
6914    // If we can emit an efficient shift operation, do so now.
6915    if (ExpandShift(ISD::SRA, Node->getOperand(0), ShiftAmt, Lo, Hi))
6916      break;
6917
6918    // If this target supports SRA_PARTS, use it.
6919    TargetLowering::LegalizeAction Action =
6920      TLI.getOperationAction(ISD::SRA_PARTS, NVT);
6921    if ((Action == TargetLowering::Legal && TLI.isTypeLegal(NVT)) ||
6922        Action == TargetLowering::Custom) {
6923      ExpandShiftParts(ISD::SRA_PARTS, Node->getOperand(0), ShiftAmt, Lo, Hi);
6924      break;
6925    }
6926
6927    // Otherwise, emit a libcall.
6928    Lo = ExpandLibCall(RTLIB::SRA_I64, Node, true/*ashr is signed*/, Hi);
6929    break;
6930  }
6931
6932  case ISD::SRL: {
6933    // If the target wants custom lowering, do so.
6934    SDValue ShiftAmt = LegalizeOp(Node->getOperand(1));
6935    if (TLI.getOperationAction(ISD::SRL, VT) == TargetLowering::Custom) {
6936      SDValue Op = DAG.getNode(ISD::SRL, VT, Node->getOperand(0), ShiftAmt);
6937      Op = TLI.LowerOperation(Op, DAG);
6938      if (Op.getNode()) {
6939        // Now that the custom expander is done, expand the result, which is
6940        // still VT.
6941        ExpandOp(Op, Lo, Hi);
6942        break;
6943      }
6944    }
6945
6946    // If we can emit an efficient shift operation, do so now.
6947    if (ExpandShift(ISD::SRL, Node->getOperand(0), ShiftAmt, Lo, Hi))
6948      break;
6949
6950    // If this target supports SRL_PARTS, use it.
6951    TargetLowering::LegalizeAction Action =
6952      TLI.getOperationAction(ISD::SRL_PARTS, NVT);
6953    if ((Action == TargetLowering::Legal && TLI.isTypeLegal(NVT)) ||
6954        Action == TargetLowering::Custom) {
6955      ExpandShiftParts(ISD::SRL_PARTS, Node->getOperand(0), ShiftAmt, Lo, Hi);
6956      break;
6957    }
6958
6959    // Otherwise, emit a libcall.
6960    Lo = ExpandLibCall(RTLIB::SRL_I64, Node, false/*lshr is unsigned*/, Hi);
6961    break;
6962  }
6963
6964  case ISD::ADD:
6965  case ISD::SUB: {
6966    // If the target wants to custom expand this, let them.
6967    if (TLI.getOperationAction(Node->getOpcode(), VT) ==
6968            TargetLowering::Custom) {
6969      SDValue Result = TLI.LowerOperation(Op, DAG);
6970      if (Result.getNode()) {
6971        ExpandOp(Result, Lo, Hi);
6972        break;
6973      }
6974    }
6975    // Expand the subcomponents.
6976    SDValue LHSL, LHSH, RHSL, RHSH;
6977    ExpandOp(Node->getOperand(0), LHSL, LHSH);
6978    ExpandOp(Node->getOperand(1), RHSL, RHSH);
6979    SDValue LoOps[2], HiOps[3];
6980    LoOps[0] = LHSL;
6981    LoOps[1] = RHSL;
6982    HiOps[0] = LHSH;
6983    HiOps[1] = RHSH;
6984
6985    //cascaded check to see if any smaller size has a a carry flag.
6986    unsigned OpV = Node->getOpcode() == ISD::ADD ? ISD::ADDC : ISD::SUBC;
6987    bool hasCarry = false;
6988    for (unsigned BitSize = NVT.getSizeInBits(); BitSize != 0; BitSize /= 2) {
6989      MVT AVT = MVT::getIntegerVT(BitSize);
6990      if (TLI.isOperationLegal(OpV, AVT)) {
6991        hasCarry = true;
6992        break;
6993      }
6994    }
6995
6996    if(hasCarry) {
6997      SDVTList VTList = DAG.getVTList(LHSL.getValueType(), MVT::Flag);
6998      if (Node->getOpcode() == ISD::ADD) {
6999        Lo = DAG.getNode(ISD::ADDC, VTList, LoOps, 2);
7000        HiOps[2] = Lo.getValue(1);
7001        Hi = DAG.getNode(ISD::ADDE, VTList, HiOps, 3);
7002      } else {
7003        Lo = DAG.getNode(ISD::SUBC, VTList, LoOps, 2);
7004        HiOps[2] = Lo.getValue(1);
7005        Hi = DAG.getNode(ISD::SUBE, VTList, HiOps, 3);
7006      }
7007      break;
7008    } else {
7009      if (Node->getOpcode() == ISD::ADD) {
7010        Lo = DAG.getNode(ISD::ADD, NVT, LoOps, 2);
7011        Hi = DAG.getNode(ISD::ADD, NVT, HiOps, 2);
7012        SDValue Cmp1 = DAG.getSetCC(TLI.getSetCCResultType(Lo),
7013                                    Lo, LoOps[0], ISD::SETULT);
7014        SDValue Carry1 = DAG.getNode(ISD::SELECT, NVT, Cmp1,
7015                                     DAG.getConstant(1, NVT),
7016                                     DAG.getConstant(0, NVT));
7017        SDValue Cmp2 = DAG.getSetCC(TLI.getSetCCResultType(Lo),
7018                                    Lo, LoOps[1], ISD::SETULT);
7019        SDValue Carry2 = DAG.getNode(ISD::SELECT, NVT, Cmp2,
7020                                    DAG.getConstant(1, NVT),
7021                                    Carry1);
7022        Hi = DAG.getNode(ISD::ADD, NVT, Hi, Carry2);
7023      } else {
7024        Lo = DAG.getNode(ISD::SUB, NVT, LoOps, 2);
7025        Hi = DAG.getNode(ISD::SUB, NVT, HiOps, 2);
7026        SDValue Cmp = DAG.getSetCC(NVT, LoOps[0], LoOps[1], ISD::SETULT);
7027        SDValue Borrow = DAG.getNode(ISD::SELECT, NVT, Cmp,
7028                                     DAG.getConstant(1, NVT),
7029                                     DAG.getConstant(0, NVT));
7030        Hi = DAG.getNode(ISD::SUB, NVT, Hi, Borrow);
7031      }
7032      break;
7033    }
7034  }
7035
7036  case ISD::ADDC:
7037  case ISD::SUBC: {
7038    // Expand the subcomponents.
7039    SDValue LHSL, LHSH, RHSL, RHSH;
7040    ExpandOp(Node->getOperand(0), LHSL, LHSH);
7041    ExpandOp(Node->getOperand(1), RHSL, RHSH);
7042    SDVTList VTList = DAG.getVTList(LHSL.getValueType(), MVT::Flag);
7043    SDValue LoOps[2] = { LHSL, RHSL };
7044    SDValue HiOps[3] = { LHSH, RHSH };
7045
7046    if (Node->getOpcode() == ISD::ADDC) {
7047      Lo = DAG.getNode(ISD::ADDC, VTList, LoOps, 2);
7048      HiOps[2] = Lo.getValue(1);
7049      Hi = DAG.getNode(ISD::ADDE, VTList, HiOps, 3);
7050    } else {
7051      Lo = DAG.getNode(ISD::SUBC, VTList, LoOps, 2);
7052      HiOps[2] = Lo.getValue(1);
7053      Hi = DAG.getNode(ISD::SUBE, VTList, HiOps, 3);
7054    }
7055    // Remember that we legalized the flag.
7056    AddLegalizedOperand(Op.getValue(1), LegalizeOp(Hi.getValue(1)));
7057    break;
7058  }
7059  case ISD::ADDE:
7060  case ISD::SUBE: {
7061    // Expand the subcomponents.
7062    SDValue LHSL, LHSH, RHSL, RHSH;
7063    ExpandOp(Node->getOperand(0), LHSL, LHSH);
7064    ExpandOp(Node->getOperand(1), RHSL, RHSH);
7065    SDVTList VTList = DAG.getVTList(LHSL.getValueType(), MVT::Flag);
7066    SDValue LoOps[3] = { LHSL, RHSL, Node->getOperand(2) };
7067    SDValue HiOps[3] = { LHSH, RHSH };
7068
7069    Lo = DAG.getNode(Node->getOpcode(), VTList, LoOps, 3);
7070    HiOps[2] = Lo.getValue(1);
7071    Hi = DAG.getNode(Node->getOpcode(), VTList, HiOps, 3);
7072
7073    // Remember that we legalized the flag.
7074    AddLegalizedOperand(Op.getValue(1), LegalizeOp(Hi.getValue(1)));
7075    break;
7076  }
7077  case ISD::MUL: {
7078    // If the target wants to custom expand this, let them.
7079    if (TLI.getOperationAction(ISD::MUL, VT) == TargetLowering::Custom) {
7080      SDValue New = TLI.LowerOperation(Op, DAG);
7081      if (New.getNode()) {
7082        ExpandOp(New, Lo, Hi);
7083        break;
7084      }
7085    }
7086
7087    bool HasMULHS = TLI.isOperationLegal(ISD::MULHS, NVT);
7088    bool HasMULHU = TLI.isOperationLegal(ISD::MULHU, NVT);
7089    bool HasSMUL_LOHI = TLI.isOperationLegal(ISD::SMUL_LOHI, NVT);
7090    bool HasUMUL_LOHI = TLI.isOperationLegal(ISD::UMUL_LOHI, NVT);
7091    if (HasMULHU || HasMULHS || HasUMUL_LOHI || HasSMUL_LOHI) {
7092      SDValue LL, LH, RL, RH;
7093      ExpandOp(Node->getOperand(0), LL, LH);
7094      ExpandOp(Node->getOperand(1), RL, RH);
7095      unsigned OuterBitSize = Op.getValueSizeInBits();
7096      unsigned InnerBitSize = RH.getValueSizeInBits();
7097      unsigned LHSSB = DAG.ComputeNumSignBits(Op.getOperand(0));
7098      unsigned RHSSB = DAG.ComputeNumSignBits(Op.getOperand(1));
7099      APInt HighMask = APInt::getHighBitsSet(OuterBitSize, InnerBitSize);
7100      if (DAG.MaskedValueIsZero(Node->getOperand(0), HighMask) &&
7101          DAG.MaskedValueIsZero(Node->getOperand(1), HighMask)) {
7102        // The inputs are both zero-extended.
7103        if (HasUMUL_LOHI) {
7104          // We can emit a umul_lohi.
7105          Lo = DAG.getNode(ISD::UMUL_LOHI, DAG.getVTList(NVT, NVT), LL, RL);
7106          Hi = SDValue(Lo.getNode(), 1);
7107          break;
7108        }
7109        if (HasMULHU) {
7110          // We can emit a mulhu+mul.
7111          Lo = DAG.getNode(ISD::MUL, NVT, LL, RL);
7112          Hi = DAG.getNode(ISD::MULHU, NVT, LL, RL);
7113          break;
7114        }
7115      }
7116      if (LHSSB > InnerBitSize && RHSSB > InnerBitSize) {
7117        // The input values are both sign-extended.
7118        if (HasSMUL_LOHI) {
7119          // We can emit a smul_lohi.
7120          Lo = DAG.getNode(ISD::SMUL_LOHI, DAG.getVTList(NVT, NVT), LL, RL);
7121          Hi = SDValue(Lo.getNode(), 1);
7122          break;
7123        }
7124        if (HasMULHS) {
7125          // We can emit a mulhs+mul.
7126          Lo = DAG.getNode(ISD::MUL, NVT, LL, RL);
7127          Hi = DAG.getNode(ISD::MULHS, NVT, LL, RL);
7128          break;
7129        }
7130      }
7131      if (HasUMUL_LOHI) {
7132        // Lo,Hi = umul LHS, RHS.
7133        SDValue UMulLOHI = DAG.getNode(ISD::UMUL_LOHI,
7134                                         DAG.getVTList(NVT, NVT), LL, RL);
7135        Lo = UMulLOHI;
7136        Hi = UMulLOHI.getValue(1);
7137        RH = DAG.getNode(ISD::MUL, NVT, LL, RH);
7138        LH = DAG.getNode(ISD::MUL, NVT, LH, RL);
7139        Hi = DAG.getNode(ISD::ADD, NVT, Hi, RH);
7140        Hi = DAG.getNode(ISD::ADD, NVT, Hi, LH);
7141        break;
7142      }
7143      if (HasMULHU) {
7144        Lo = DAG.getNode(ISD::MUL, NVT, LL, RL);
7145        Hi = DAG.getNode(ISD::MULHU, NVT, LL, RL);
7146        RH = DAG.getNode(ISD::MUL, NVT, LL, RH);
7147        LH = DAG.getNode(ISD::MUL, NVT, LH, RL);
7148        Hi = DAG.getNode(ISD::ADD, NVT, Hi, RH);
7149        Hi = DAG.getNode(ISD::ADD, NVT, Hi, LH);
7150        break;
7151      }
7152    }
7153
7154    // If nothing else, we can make a libcall.
7155    Lo = ExpandLibCall(RTLIB::MUL_I64, Node, false/*sign irrelevant*/, Hi);
7156    break;
7157  }
7158  case ISD::SDIV:
7159    Lo = ExpandLibCall(RTLIB::SDIV_I64, Node, true, Hi);
7160    break;
7161  case ISD::UDIV:
7162    Lo = ExpandLibCall(RTLIB::UDIV_I64, Node, true, Hi);
7163    break;
7164  case ISD::SREM:
7165    Lo = ExpandLibCall(RTLIB::SREM_I64, Node, true, Hi);
7166    break;
7167  case ISD::UREM:
7168    Lo = ExpandLibCall(RTLIB::UREM_I64, Node, true, Hi);
7169    break;
7170
7171  case ISD::FADD:
7172    Lo = ExpandLibCall(GetFPLibCall(VT, RTLIB::ADD_F32,
7173                                        RTLIB::ADD_F64,
7174                                        RTLIB::ADD_F80,
7175                                        RTLIB::ADD_PPCF128),
7176                       Node, false, Hi);
7177    break;
7178  case ISD::FSUB:
7179    Lo = ExpandLibCall(GetFPLibCall(VT, RTLIB::SUB_F32,
7180                                        RTLIB::SUB_F64,
7181                                        RTLIB::SUB_F80,
7182                                        RTLIB::SUB_PPCF128),
7183                       Node, false, Hi);
7184    break;
7185  case ISD::FMUL:
7186    Lo = ExpandLibCall(GetFPLibCall(VT, RTLIB::MUL_F32,
7187                                        RTLIB::MUL_F64,
7188                                        RTLIB::MUL_F80,
7189                                        RTLIB::MUL_PPCF128),
7190                       Node, false, Hi);
7191    break;
7192  case ISD::FDIV:
7193    Lo = ExpandLibCall(GetFPLibCall(VT, RTLIB::DIV_F32,
7194                                        RTLIB::DIV_F64,
7195                                        RTLIB::DIV_F80,
7196                                        RTLIB::DIV_PPCF128),
7197                       Node, false, Hi);
7198    break;
7199  case ISD::FP_EXTEND: {
7200    if (VT == MVT::ppcf128) {
7201      assert(Node->getOperand(0).getValueType()==MVT::f32 ||
7202             Node->getOperand(0).getValueType()==MVT::f64);
7203      const uint64_t zero = 0;
7204      if (Node->getOperand(0).getValueType()==MVT::f32)
7205        Hi = DAG.getNode(ISD::FP_EXTEND, MVT::f64, Node->getOperand(0));
7206      else
7207        Hi = Node->getOperand(0);
7208      Lo = DAG.getConstantFP(APFloat(APInt(64, 1, &zero)), MVT::f64);
7209      break;
7210    }
7211    RTLIB::Libcall LC = RTLIB::getFPEXT(Node->getOperand(0).getValueType(), VT);
7212    assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unsupported FP_EXTEND!");
7213    Lo = ExpandLibCall(LC, Node, true, Hi);
7214    break;
7215  }
7216  case ISD::FP_ROUND: {
7217    RTLIB::Libcall LC = RTLIB::getFPROUND(Node->getOperand(0).getValueType(),
7218                                          VT);
7219    assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unsupported FP_ROUND!");
7220    Lo = ExpandLibCall(LC, Node, true, Hi);
7221    break;
7222  }
7223  case ISD::FSQRT:
7224  case ISD::FSIN:
7225  case ISD::FCOS:
7226  case ISD::FLOG:
7227  case ISD::FLOG2:
7228  case ISD::FLOG10:
7229  case ISD::FEXP:
7230  case ISD::FEXP2:
7231  case ISD::FTRUNC:
7232  case ISD::FFLOOR:
7233  case ISD::FCEIL:
7234  case ISD::FRINT:
7235  case ISD::FNEARBYINT:
7236  case ISD::FPOW:
7237  case ISD::FPOWI: {
7238    RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
7239    switch(Node->getOpcode()) {
7240    case ISD::FSQRT:
7241      LC = GetFPLibCall(VT, RTLIB::SQRT_F32, RTLIB::SQRT_F64,
7242                        RTLIB::SQRT_F80, RTLIB::SQRT_PPCF128);
7243      break;
7244    case ISD::FSIN:
7245      LC = GetFPLibCall(VT, RTLIB::SIN_F32, RTLIB::SIN_F64,
7246                        RTLIB::SIN_F80, RTLIB::SIN_PPCF128);
7247      break;
7248    case ISD::FCOS:
7249      LC = GetFPLibCall(VT, RTLIB::COS_F32, RTLIB::COS_F64,
7250                        RTLIB::COS_F80, RTLIB::COS_PPCF128);
7251      break;
7252    case ISD::FLOG:
7253      LC = GetFPLibCall(VT, RTLIB::LOG_F32, RTLIB::LOG_F64,
7254                        RTLIB::LOG_F80, RTLIB::LOG_PPCF128);
7255      break;
7256    case ISD::FLOG2:
7257      LC = GetFPLibCall(VT, RTLIB::LOG2_F32, RTLIB::LOG2_F64,
7258                        RTLIB::LOG2_F80, RTLIB::LOG2_PPCF128);
7259      break;
7260    case ISD::FLOG10:
7261      LC = GetFPLibCall(VT, RTLIB::LOG10_F32, RTLIB::LOG10_F64,
7262                        RTLIB::LOG10_F80, RTLIB::LOG10_PPCF128);
7263      break;
7264    case ISD::FEXP:
7265      LC = GetFPLibCall(VT, RTLIB::EXP_F32, RTLIB::EXP_F64,
7266                        RTLIB::EXP_F80, RTLIB::EXP_PPCF128);
7267      break;
7268    case ISD::FEXP2:
7269      LC = GetFPLibCall(VT, RTLIB::EXP2_F32, RTLIB::EXP2_F64,
7270                        RTLIB::EXP2_F80, RTLIB::EXP2_PPCF128);
7271      break;
7272    case ISD::FTRUNC:
7273      LC = GetFPLibCall(VT, RTLIB::TRUNC_F32, RTLIB::TRUNC_F64,
7274                        RTLIB::TRUNC_F80, RTLIB::TRUNC_PPCF128);
7275      break;
7276    case ISD::FFLOOR:
7277      LC = GetFPLibCall(VT, RTLIB::FLOOR_F32, RTLIB::FLOOR_F64,
7278                        RTLIB::FLOOR_F80, RTLIB::FLOOR_PPCF128);
7279      break;
7280    case ISD::FCEIL:
7281      LC = GetFPLibCall(VT, RTLIB::CEIL_F32, RTLIB::CEIL_F64,
7282                        RTLIB::CEIL_F80, RTLIB::CEIL_PPCF128);
7283      break;
7284    case ISD::FRINT:
7285      LC = GetFPLibCall(VT, RTLIB::RINT_F32, RTLIB::RINT_F64,
7286                        RTLIB::RINT_F80, RTLIB::RINT_PPCF128);
7287      break;
7288    case ISD::FNEARBYINT:
7289      LC = GetFPLibCall(VT, RTLIB::NEARBYINT_F32, RTLIB::NEARBYINT_F64,
7290                        RTLIB::NEARBYINT_F80, RTLIB::NEARBYINT_PPCF128);
7291      break;
7292    case ISD::FPOW:
7293      LC = GetFPLibCall(VT, RTLIB::POW_F32, RTLIB::POW_F64, RTLIB::POW_F80,
7294                        RTLIB::POW_PPCF128);
7295      break;
7296    case ISD::FPOWI:
7297      LC = GetFPLibCall(VT, RTLIB::POWI_F32, RTLIB::POWI_F64, RTLIB::POWI_F80,
7298                        RTLIB::POWI_PPCF128);
7299      break;
7300    default: assert(0 && "Unreachable!");
7301    }
7302    Lo = ExpandLibCall(LC, Node, false, Hi);
7303    break;
7304  }
7305  case ISD::FABS: {
7306    if (VT == MVT::ppcf128) {
7307      SDValue Tmp;
7308      ExpandOp(Node->getOperand(0), Lo, Tmp);
7309      Hi = DAG.getNode(ISD::FABS, NVT, Tmp);
7310      // lo = hi==fabs(hi) ? lo : -lo;
7311      Lo = DAG.getNode(ISD::SELECT_CC, NVT, Hi, Tmp,
7312                    Lo, DAG.getNode(ISD::FNEG, NVT, Lo),
7313                    DAG.getCondCode(ISD::SETEQ));
7314      break;
7315    }
7316    SDValue Mask = (VT == MVT::f64)
7317      ? DAG.getConstantFP(BitsToDouble(~(1ULL << 63)), VT)
7318      : DAG.getConstantFP(BitsToFloat(~(1U << 31)), VT);
7319    Mask = DAG.getNode(ISD::BIT_CONVERT, NVT, Mask);
7320    Lo = DAG.getNode(ISD::BIT_CONVERT, NVT, Node->getOperand(0));
7321    Lo = DAG.getNode(ISD::AND, NVT, Lo, Mask);
7322    if (getTypeAction(NVT) == Expand)
7323      ExpandOp(Lo, Lo, Hi);
7324    break;
7325  }
7326  case ISD::FNEG: {
7327    if (VT == MVT::ppcf128) {
7328      ExpandOp(Node->getOperand(0), Lo, Hi);
7329      Lo = DAG.getNode(ISD::FNEG, MVT::f64, Lo);
7330      Hi = DAG.getNode(ISD::FNEG, MVT::f64, Hi);
7331      break;
7332    }
7333    SDValue Mask = (VT == MVT::f64)
7334      ? DAG.getConstantFP(BitsToDouble(1ULL << 63), VT)
7335      : DAG.getConstantFP(BitsToFloat(1U << 31), VT);
7336    Mask = DAG.getNode(ISD::BIT_CONVERT, NVT, Mask);
7337    Lo = DAG.getNode(ISD::BIT_CONVERT, NVT, Node->getOperand(0));
7338    Lo = DAG.getNode(ISD::XOR, NVT, Lo, Mask);
7339    if (getTypeAction(NVT) == Expand)
7340      ExpandOp(Lo, Lo, Hi);
7341    break;
7342  }
7343  case ISD::FCOPYSIGN: {
7344    Lo = ExpandFCOPYSIGNToBitwiseOps(Node, NVT, DAG, TLI);
7345    if (getTypeAction(NVT) == Expand)
7346      ExpandOp(Lo, Lo, Hi);
7347    break;
7348  }
7349  case ISD::SINT_TO_FP:
7350  case ISD::UINT_TO_FP: {
7351    bool isSigned = Node->getOpcode() == ISD::SINT_TO_FP;
7352    MVT SrcVT = Node->getOperand(0).getValueType();
7353
7354    // Promote the operand if needed.  Do this before checking for
7355    // ppcf128 so conversions of i16 and i8 work.
7356    if (getTypeAction(SrcVT) == Promote) {
7357      SDValue Tmp = PromoteOp(Node->getOperand(0));
7358      Tmp = isSigned
7359        ? DAG.getNode(ISD::SIGN_EXTEND_INREG, Tmp.getValueType(), Tmp,
7360                      DAG.getValueType(SrcVT))
7361        : DAG.getZeroExtendInReg(Tmp, SrcVT);
7362      Node = DAG.UpdateNodeOperands(Op, Tmp).getNode();
7363      SrcVT = Node->getOperand(0).getValueType();
7364    }
7365
7366    if (VT == MVT::ppcf128 && SrcVT == MVT::i32) {
7367      static const uint64_t zero = 0;
7368      if (isSigned) {
7369        Hi = LegalizeOp(DAG.getNode(ISD::SINT_TO_FP, MVT::f64,
7370                                    Node->getOperand(0)));
7371        Lo = DAG.getConstantFP(APFloat(APInt(64, 1, &zero)), MVT::f64);
7372      } else {
7373        static const uint64_t TwoE32[] = { 0x41f0000000000000LL, 0 };
7374        Hi = LegalizeOp(DAG.getNode(ISD::SINT_TO_FP, MVT::f64,
7375                                    Node->getOperand(0)));
7376        Lo = DAG.getConstantFP(APFloat(APInt(64, 1, &zero)), MVT::f64);
7377        Hi = DAG.getNode(ISD::BUILD_PAIR, VT, Lo, Hi);
7378        // X>=0 ? {(f64)x, 0} : {(f64)x, 0} + 2^32
7379        ExpandOp(DAG.getNode(ISD::SELECT_CC, MVT::ppcf128, Node->getOperand(0),
7380                             DAG.getConstant(0, MVT::i32),
7381                             DAG.getNode(ISD::FADD, MVT::ppcf128, Hi,
7382                                         DAG.getConstantFP(
7383                                            APFloat(APInt(128, 2, TwoE32)),
7384                                            MVT::ppcf128)),
7385                             Hi,
7386                             DAG.getCondCode(ISD::SETLT)),
7387                 Lo, Hi);
7388      }
7389      break;
7390    }
7391    if (VT == MVT::ppcf128 && SrcVT == MVT::i64 && !isSigned) {
7392      // si64->ppcf128 done by libcall, below
7393      static const uint64_t TwoE64[] = { 0x43f0000000000000LL, 0 };
7394      ExpandOp(DAG.getNode(ISD::SINT_TO_FP, MVT::ppcf128, Node->getOperand(0)),
7395               Lo, Hi);
7396      Hi = DAG.getNode(ISD::BUILD_PAIR, VT, Lo, Hi);
7397      // x>=0 ? (ppcf128)(i64)x : (ppcf128)(i64)x + 2^64
7398      ExpandOp(DAG.getNode(ISD::SELECT_CC, MVT::ppcf128, Node->getOperand(0),
7399                           DAG.getConstant(0, MVT::i64),
7400                           DAG.getNode(ISD::FADD, MVT::ppcf128, Hi,
7401                                       DAG.getConstantFP(
7402                                          APFloat(APInt(128, 2, TwoE64)),
7403                                          MVT::ppcf128)),
7404                           Hi,
7405                           DAG.getCondCode(ISD::SETLT)),
7406               Lo, Hi);
7407      break;
7408    }
7409
7410    Lo = ExpandIntToFP(Node->getOpcode() == ISD::SINT_TO_FP, VT,
7411                       Node->getOperand(0));
7412    if (getTypeAction(Lo.getValueType()) == Expand)
7413      // float to i32 etc. can be 'expanded' to a single node.
7414      ExpandOp(Lo, Lo, Hi);
7415    break;
7416  }
7417  }
7418
7419  // Make sure the resultant values have been legalized themselves, unless this
7420  // is a type that requires multi-step expansion.
7421  if (getTypeAction(NVT) != Expand && NVT != MVT::isVoid) {
7422    Lo = LegalizeOp(Lo);
7423    if (Hi.getNode())
7424      // Don't legalize the high part if it is expanded to a single node.
7425      Hi = LegalizeOp(Hi);
7426  }
7427
7428  // Remember in a map if the values will be reused later.
7429  bool isNew =
7430    ExpandedNodes.insert(std::make_pair(Op, std::make_pair(Lo, Hi))).second;
7431  assert(isNew && "Value already expanded?!?");
7432  isNew = isNew;
7433}
7434
7435/// SplitVectorOp - Given an operand of vector type, break it down into
7436/// two smaller values, still of vector type.
7437void SelectionDAGLegalize::SplitVectorOp(SDValue Op, SDValue &Lo,
7438                                         SDValue &Hi) {
7439  assert(Op.getValueType().isVector() && "Cannot split non-vector type!");
7440  SDNode *Node = Op.getNode();
7441  unsigned NumElements = Op.getValueType().getVectorNumElements();
7442  assert(NumElements > 1 && "Cannot split a single element vector!");
7443
7444  MVT NewEltVT = Op.getValueType().getVectorElementType();
7445
7446  unsigned NewNumElts_Lo = 1 << Log2_32(NumElements-1);
7447  unsigned NewNumElts_Hi = NumElements - NewNumElts_Lo;
7448
7449  MVT NewVT_Lo = MVT::getVectorVT(NewEltVT, NewNumElts_Lo);
7450  MVT NewVT_Hi = MVT::getVectorVT(NewEltVT, NewNumElts_Hi);
7451
7452  // See if we already split it.
7453  std::map<SDValue, std::pair<SDValue, SDValue> >::iterator I
7454    = SplitNodes.find(Op);
7455  if (I != SplitNodes.end()) {
7456    Lo = I->second.first;
7457    Hi = I->second.second;
7458    return;
7459  }
7460
7461  switch (Node->getOpcode()) {
7462  default:
7463#ifndef NDEBUG
7464    Node->dump(&DAG);
7465#endif
7466    assert(0 && "Unhandled operation in SplitVectorOp!");
7467  case ISD::UNDEF:
7468    Lo = DAG.getNode(ISD::UNDEF, NewVT_Lo);
7469    Hi = DAG.getNode(ISD::UNDEF, NewVT_Hi);
7470    break;
7471  case ISD::BUILD_PAIR:
7472    Lo = Node->getOperand(0);
7473    Hi = Node->getOperand(1);
7474    break;
7475  case ISD::INSERT_VECTOR_ELT: {
7476    if (ConstantSDNode *Idx = dyn_cast<ConstantSDNode>(Node->getOperand(2))) {
7477      SplitVectorOp(Node->getOperand(0), Lo, Hi);
7478      unsigned Index = Idx->getZExtValue();
7479      SDValue ScalarOp = Node->getOperand(1);
7480      if (Index < NewNumElts_Lo)
7481        Lo = DAG.getNode(ISD::INSERT_VECTOR_ELT, NewVT_Lo, Lo, ScalarOp,
7482                         DAG.getIntPtrConstant(Index));
7483      else
7484        Hi = DAG.getNode(ISD::INSERT_VECTOR_ELT, NewVT_Hi, Hi, ScalarOp,
7485                         DAG.getIntPtrConstant(Index - NewNumElts_Lo));
7486      break;
7487    }
7488    SDValue Tmp = PerformInsertVectorEltInMemory(Node->getOperand(0),
7489                                                   Node->getOperand(1),
7490                                                   Node->getOperand(2));
7491    SplitVectorOp(Tmp, Lo, Hi);
7492    break;
7493  }
7494  case ISD::VECTOR_SHUFFLE: {
7495    // Build the low part.
7496    SDValue Mask = Node->getOperand(2);
7497    SmallVector<SDValue, 8> Ops;
7498    MVT PtrVT = TLI.getPointerTy();
7499
7500    // Insert all of the elements from the input that are needed.  We use
7501    // buildvector of extractelement here because the input vectors will have
7502    // to be legalized, so this makes the code simpler.
7503    for (unsigned i = 0; i != NewNumElts_Lo; ++i) {
7504      SDValue IdxNode = Mask.getOperand(i);
7505      if (IdxNode.getOpcode() == ISD::UNDEF) {
7506        Ops.push_back(DAG.getNode(ISD::UNDEF, NewEltVT));
7507        continue;
7508      }
7509      unsigned Idx = cast<ConstantSDNode>(IdxNode)->getZExtValue();
7510      SDValue InVec = Node->getOperand(0);
7511      if (Idx >= NumElements) {
7512        InVec = Node->getOperand(1);
7513        Idx -= NumElements;
7514      }
7515      Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, NewEltVT, InVec,
7516                                DAG.getConstant(Idx, PtrVT)));
7517    }
7518    Lo = DAG.getNode(ISD::BUILD_VECTOR, NewVT_Lo, &Ops[0], Ops.size());
7519    Ops.clear();
7520
7521    for (unsigned i = NewNumElts_Lo; i != NumElements; ++i) {
7522      SDValue IdxNode = Mask.getOperand(i);
7523      if (IdxNode.getOpcode() == ISD::UNDEF) {
7524        Ops.push_back(DAG.getNode(ISD::UNDEF, NewEltVT));
7525        continue;
7526      }
7527      unsigned Idx = cast<ConstantSDNode>(IdxNode)->getZExtValue();
7528      SDValue InVec = Node->getOperand(0);
7529      if (Idx >= NumElements) {
7530        InVec = Node->getOperand(1);
7531        Idx -= NumElements;
7532      }
7533      Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, NewEltVT, InVec,
7534                                DAG.getConstant(Idx, PtrVT)));
7535    }
7536    Hi = DAG.getNode(ISD::BUILD_VECTOR, NewVT_Hi, &Ops[0], Ops.size());
7537    break;
7538  }
7539  case ISD::BUILD_VECTOR: {
7540    SmallVector<SDValue, 8> LoOps(Node->op_begin(),
7541                                    Node->op_begin()+NewNumElts_Lo);
7542    Lo = DAG.getNode(ISD::BUILD_VECTOR, NewVT_Lo, &LoOps[0], LoOps.size());
7543
7544    SmallVector<SDValue, 8> HiOps(Node->op_begin()+NewNumElts_Lo,
7545                                    Node->op_end());
7546    Hi = DAG.getNode(ISD::BUILD_VECTOR, NewVT_Hi, &HiOps[0], HiOps.size());
7547    break;
7548  }
7549  case ISD::CONCAT_VECTORS: {
7550    // FIXME: Handle non-power-of-two vectors?
7551    unsigned NewNumSubvectors = Node->getNumOperands() / 2;
7552    if (NewNumSubvectors == 1) {
7553      Lo = Node->getOperand(0);
7554      Hi = Node->getOperand(1);
7555    } else {
7556      SmallVector<SDValue, 8> LoOps(Node->op_begin(),
7557                                    Node->op_begin()+NewNumSubvectors);
7558      Lo = DAG.getNode(ISD::CONCAT_VECTORS, NewVT_Lo, &LoOps[0], LoOps.size());
7559
7560      SmallVector<SDValue, 8> HiOps(Node->op_begin()+NewNumSubvectors,
7561                                      Node->op_end());
7562      Hi = DAG.getNode(ISD::CONCAT_VECTORS, NewVT_Hi, &HiOps[0], HiOps.size());
7563    }
7564    break;
7565  }
7566  case ISD::EXTRACT_SUBVECTOR: {
7567    SDValue Vec = Op.getOperand(0);
7568    SDValue Idx = Op.getOperand(1);
7569    MVT     IdxVT = Idx.getValueType();
7570
7571    Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, NewVT_Lo, Vec, Idx);
7572    ConstantSDNode *CIdx = dyn_cast<ConstantSDNode>(Idx);
7573    if (CIdx) {
7574      Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, NewVT_Hi, Vec,
7575                       DAG.getConstant(CIdx->getZExtValue() + NewNumElts_Lo,
7576                                       IdxVT));
7577    } else {
7578      Idx = DAG.getNode(ISD::ADD, IdxVT, Idx,
7579                        DAG.getConstant(NewNumElts_Lo, IdxVT));
7580      Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, NewVT_Hi, Vec, Idx);
7581    }
7582    break;
7583  }
7584  case ISD::SELECT: {
7585    SDValue Cond = Node->getOperand(0);
7586
7587    SDValue LL, LH, RL, RH;
7588    SplitVectorOp(Node->getOperand(1), LL, LH);
7589    SplitVectorOp(Node->getOperand(2), RL, RH);
7590
7591    if (Cond.getValueType().isVector()) {
7592      // Handle a vector merge.
7593      SDValue CL, CH;
7594      SplitVectorOp(Cond, CL, CH);
7595      Lo = DAG.getNode(Node->getOpcode(), NewVT_Lo, CL, LL, RL);
7596      Hi = DAG.getNode(Node->getOpcode(), NewVT_Hi, CH, LH, RH);
7597    } else {
7598      // Handle a simple select with vector operands.
7599      Lo = DAG.getNode(Node->getOpcode(), NewVT_Lo, Cond, LL, RL);
7600      Hi = DAG.getNode(Node->getOpcode(), NewVT_Hi, Cond, LH, RH);
7601    }
7602    break;
7603  }
7604  case ISD::SELECT_CC: {
7605    SDValue CondLHS = Node->getOperand(0);
7606    SDValue CondRHS = Node->getOperand(1);
7607    SDValue CondCode = Node->getOperand(4);
7608
7609    SDValue LL, LH, RL, RH;
7610    SplitVectorOp(Node->getOperand(2), LL, LH);
7611    SplitVectorOp(Node->getOperand(3), RL, RH);
7612
7613    // Handle a simple select with vector operands.
7614    Lo = DAG.getNode(ISD::SELECT_CC, NewVT_Lo, CondLHS, CondRHS,
7615                     LL, RL, CondCode);
7616    Hi = DAG.getNode(ISD::SELECT_CC, NewVT_Hi, CondLHS, CondRHS,
7617                     LH, RH, CondCode);
7618    break;
7619  }
7620  case ISD::VSETCC: {
7621    SDValue LL, LH, RL, RH;
7622    SplitVectorOp(Node->getOperand(0), LL, LH);
7623    SplitVectorOp(Node->getOperand(1), RL, RH);
7624    Lo = DAG.getNode(ISD::VSETCC, NewVT_Lo, LL, RL, Node->getOperand(2));
7625    Hi = DAG.getNode(ISD::VSETCC, NewVT_Hi, LH, RH, Node->getOperand(2));
7626    break;
7627  }
7628  case ISD::ADD:
7629  case ISD::SUB:
7630  case ISD::MUL:
7631  case ISD::FADD:
7632  case ISD::FSUB:
7633  case ISD::FMUL:
7634  case ISD::SDIV:
7635  case ISD::UDIV:
7636  case ISD::FDIV:
7637  case ISD::FPOW:
7638  case ISD::AND:
7639  case ISD::OR:
7640  case ISD::XOR:
7641  case ISD::UREM:
7642  case ISD::SREM:
7643  case ISD::FREM: {
7644    SDValue LL, LH, RL, RH;
7645    SplitVectorOp(Node->getOperand(0), LL, LH);
7646    SplitVectorOp(Node->getOperand(1), RL, RH);
7647
7648    Lo = DAG.getNode(Node->getOpcode(), NewVT_Lo, LL, RL);
7649    Hi = DAG.getNode(Node->getOpcode(), NewVT_Hi, LH, RH);
7650    break;
7651  }
7652  case ISD::FP_ROUND:
7653  case ISD::FPOWI: {
7654    SDValue L, H;
7655    SplitVectorOp(Node->getOperand(0), L, H);
7656
7657    Lo = DAG.getNode(Node->getOpcode(), NewVT_Lo, L, Node->getOperand(1));
7658    Hi = DAG.getNode(Node->getOpcode(), NewVT_Hi, H, Node->getOperand(1));
7659    break;
7660  }
7661  case ISD::CTTZ:
7662  case ISD::CTLZ:
7663  case ISD::CTPOP:
7664  case ISD::FNEG:
7665  case ISD::FABS:
7666  case ISD::FSQRT:
7667  case ISD::FSIN:
7668  case ISD::FCOS:
7669  case ISD::FLOG:
7670  case ISD::FLOG2:
7671  case ISD::FLOG10:
7672  case ISD::FEXP:
7673  case ISD::FEXP2:
7674  case ISD::FP_TO_SINT:
7675  case ISD::FP_TO_UINT:
7676  case ISD::SINT_TO_FP:
7677  case ISD::UINT_TO_FP:
7678  case ISD::TRUNCATE:
7679  case ISD::ANY_EXTEND:
7680  case ISD::SIGN_EXTEND:
7681  case ISD::ZERO_EXTEND:
7682  case ISD::FP_EXTEND: {
7683    SDValue L, H;
7684    SplitVectorOp(Node->getOperand(0), L, H);
7685
7686    Lo = DAG.getNode(Node->getOpcode(), NewVT_Lo, L);
7687    Hi = DAG.getNode(Node->getOpcode(), NewVT_Hi, H);
7688    break;
7689  }
7690  case ISD::CONVERT_RNDSAT: {
7691    ISD::CvtCode CvtCode = cast<CvtRndSatSDNode>(Node)->getCvtCode();
7692    SDValue L, H;
7693    SplitVectorOp(Node->getOperand(0), L, H);
7694    SDValue DTyOpL =  DAG.getValueType(NewVT_Lo);
7695    SDValue DTyOpH =  DAG.getValueType(NewVT_Hi);
7696    SDValue STyOpL =  DAG.getValueType(L.getValueType());
7697    SDValue STyOpH =  DAG.getValueType(H.getValueType());
7698
7699    SDValue RndOp = Node->getOperand(3);
7700    SDValue SatOp = Node->getOperand(4);
7701
7702    Lo = DAG.getConvertRndSat(NewVT_Lo, L, DTyOpL, STyOpL,
7703                              RndOp, SatOp, CvtCode);
7704    Hi = DAG.getConvertRndSat(NewVT_Hi, H, DTyOpH, STyOpH,
7705                              RndOp, SatOp, CvtCode);
7706    break;
7707  }
7708  case ISD::LOAD: {
7709    LoadSDNode *LD = cast<LoadSDNode>(Node);
7710    SDValue Ch = LD->getChain();
7711    SDValue Ptr = LD->getBasePtr();
7712    ISD::LoadExtType ExtType = LD->getExtensionType();
7713    const Value *SV = LD->getSrcValue();
7714    int SVOffset = LD->getSrcValueOffset();
7715    MVT MemoryVT = LD->getMemoryVT();
7716    unsigned Alignment = LD->getAlignment();
7717    bool isVolatile = LD->isVolatile();
7718
7719    assert(LD->isUnindexed() && "Indexed vector loads are not supported yet!");
7720    SDValue Offset = DAG.getNode(ISD::UNDEF, Ptr.getValueType());
7721
7722    MVT MemNewEltVT = MemoryVT.getVectorElementType();
7723    MVT MemNewVT_Lo = MVT::getVectorVT(MemNewEltVT, NewNumElts_Lo);
7724    MVT MemNewVT_Hi = MVT::getVectorVT(MemNewEltVT, NewNumElts_Hi);
7725
7726    Lo = DAG.getLoad(ISD::UNINDEXED, ExtType,
7727                     NewVT_Lo, Ch, Ptr, Offset,
7728                     SV, SVOffset, MemNewVT_Lo, isVolatile, Alignment);
7729    unsigned IncrementSize = NewNumElts_Lo * MemNewEltVT.getSizeInBits()/8;
7730    Ptr = DAG.getNode(ISD::ADD, Ptr.getValueType(), Ptr,
7731                      DAG.getIntPtrConstant(IncrementSize));
7732    SVOffset += IncrementSize;
7733    Alignment = MinAlign(Alignment, IncrementSize);
7734    Hi = DAG.getLoad(ISD::UNINDEXED, ExtType,
7735                     NewVT_Hi, Ch, Ptr, Offset,
7736                     SV, SVOffset, MemNewVT_Hi, isVolatile, Alignment);
7737
7738    // Build a factor node to remember that this load is independent of the
7739    // other one.
7740    SDValue TF = DAG.getNode(ISD::TokenFactor, MVT::Other, Lo.getValue(1),
7741                               Hi.getValue(1));
7742
7743    // Remember that we legalized the chain.
7744    AddLegalizedOperand(Op.getValue(1), LegalizeOp(TF));
7745    break;
7746  }
7747  case ISD::BIT_CONVERT: {
7748    // We know the result is a vector.  The input may be either a vector or a
7749    // scalar value.
7750    SDValue InOp = Node->getOperand(0);
7751    if (!InOp.getValueType().isVector() ||
7752        InOp.getValueType().getVectorNumElements() == 1) {
7753      // The input is a scalar or single-element vector.
7754      // Lower to a store/load so that it can be split.
7755      // FIXME: this could be improved probably.
7756      unsigned LdAlign = TLI.getTargetData()->getPrefTypeAlignment(
7757                                            Op.getValueType().getTypeForMVT());
7758      SDValue Ptr = DAG.CreateStackTemporary(InOp.getValueType(), LdAlign);
7759      int FI = cast<FrameIndexSDNode>(Ptr.getNode())->getIndex();
7760
7761      SDValue St = DAG.getStore(DAG.getEntryNode(),
7762                                  InOp, Ptr,
7763                                  PseudoSourceValue::getFixedStack(FI), 0);
7764      InOp = DAG.getLoad(Op.getValueType(), St, Ptr,
7765                         PseudoSourceValue::getFixedStack(FI), 0);
7766    }
7767    // Split the vector and convert each of the pieces now.
7768    SplitVectorOp(InOp, Lo, Hi);
7769    Lo = DAG.getNode(ISD::BIT_CONVERT, NewVT_Lo, Lo);
7770    Hi = DAG.getNode(ISD::BIT_CONVERT, NewVT_Hi, Hi);
7771    break;
7772  }
7773  }
7774
7775  // Remember in a map if the values will be reused later.
7776  bool isNew =
7777    SplitNodes.insert(std::make_pair(Op, std::make_pair(Lo, Hi))).second;
7778  assert(isNew && "Value already split?!?");
7779  isNew = isNew;
7780}
7781
7782
7783/// ScalarizeVectorOp - Given an operand of single-element vector type
7784/// (e.g. v1f32), convert it into the equivalent operation that returns a
7785/// scalar (e.g. f32) value.
7786SDValue SelectionDAGLegalize::ScalarizeVectorOp(SDValue Op) {
7787  assert(Op.getValueType().isVector() && "Bad ScalarizeVectorOp invocation!");
7788  SDNode *Node = Op.getNode();
7789  MVT NewVT = Op.getValueType().getVectorElementType();
7790  assert(Op.getValueType().getVectorNumElements() == 1);
7791
7792  // See if we already scalarized it.
7793  std::map<SDValue, SDValue>::iterator I = ScalarizedNodes.find(Op);
7794  if (I != ScalarizedNodes.end()) return I->second;
7795
7796  SDValue Result;
7797  switch (Node->getOpcode()) {
7798  default:
7799#ifndef NDEBUG
7800    Node->dump(&DAG); cerr << "\n";
7801#endif
7802    assert(0 && "Unknown vector operation in ScalarizeVectorOp!");
7803  case ISD::ADD:
7804  case ISD::FADD:
7805  case ISD::SUB:
7806  case ISD::FSUB:
7807  case ISD::MUL:
7808  case ISD::FMUL:
7809  case ISD::SDIV:
7810  case ISD::UDIV:
7811  case ISD::FDIV:
7812  case ISD::SREM:
7813  case ISD::UREM:
7814  case ISD::FREM:
7815  case ISD::FPOW:
7816  case ISD::AND:
7817  case ISD::OR:
7818  case ISD::XOR:
7819    Result = DAG.getNode(Node->getOpcode(),
7820                         NewVT,
7821                         ScalarizeVectorOp(Node->getOperand(0)),
7822                         ScalarizeVectorOp(Node->getOperand(1)));
7823    break;
7824  case ISD::FNEG:
7825  case ISD::FABS:
7826  case ISD::FSQRT:
7827  case ISD::FSIN:
7828  case ISD::FCOS:
7829  case ISD::FLOG:
7830  case ISD::FLOG2:
7831  case ISD::FLOG10:
7832  case ISD::FEXP:
7833  case ISD::FEXP2:
7834  case ISD::FP_TO_SINT:
7835  case ISD::FP_TO_UINT:
7836  case ISD::SINT_TO_FP:
7837  case ISD::UINT_TO_FP:
7838  case ISD::SIGN_EXTEND:
7839  case ISD::ZERO_EXTEND:
7840  case ISD::ANY_EXTEND:
7841  case ISD::TRUNCATE:
7842  case ISD::FP_EXTEND:
7843    Result = DAG.getNode(Node->getOpcode(),
7844                         NewVT,
7845                         ScalarizeVectorOp(Node->getOperand(0)));
7846    break;
7847  case ISD::CONVERT_RNDSAT: {
7848    SDValue Op0 = ScalarizeVectorOp(Node->getOperand(0));
7849    Result = DAG.getConvertRndSat(NewVT, Op0,
7850                                  DAG.getValueType(NewVT),
7851                                  DAG.getValueType(Op0.getValueType()),
7852                                  Node->getOperand(3),
7853                                  Node->getOperand(4),
7854                                  cast<CvtRndSatSDNode>(Node)->getCvtCode());
7855    break;
7856  }
7857  case ISD::FPOWI:
7858  case ISD::FP_ROUND:
7859    Result = DAG.getNode(Node->getOpcode(),
7860                         NewVT,
7861                         ScalarizeVectorOp(Node->getOperand(0)),
7862                         Node->getOperand(1));
7863    break;
7864  case ISD::LOAD: {
7865    LoadSDNode *LD = cast<LoadSDNode>(Node);
7866    SDValue Ch = LegalizeOp(LD->getChain());     // Legalize the chain.
7867    SDValue Ptr = LegalizeOp(LD->getBasePtr());  // Legalize the pointer.
7868    ISD::LoadExtType ExtType = LD->getExtensionType();
7869    const Value *SV = LD->getSrcValue();
7870    int SVOffset = LD->getSrcValueOffset();
7871    MVT MemoryVT = LD->getMemoryVT();
7872    unsigned Alignment = LD->getAlignment();
7873    bool isVolatile = LD->isVolatile();
7874
7875    assert(LD->isUnindexed() && "Indexed vector loads are not supported yet!");
7876    SDValue Offset = DAG.getNode(ISD::UNDEF, Ptr.getValueType());
7877
7878    Result = DAG.getLoad(ISD::UNINDEXED, ExtType,
7879                         NewVT, Ch, Ptr, Offset, SV, SVOffset,
7880                         MemoryVT.getVectorElementType(),
7881                         isVolatile, Alignment);
7882
7883    // Remember that we legalized the chain.
7884    AddLegalizedOperand(Op.getValue(1), LegalizeOp(Result.getValue(1)));
7885    break;
7886  }
7887  case ISD::BUILD_VECTOR:
7888    Result = Node->getOperand(0);
7889    break;
7890  case ISD::INSERT_VECTOR_ELT:
7891    // Returning the inserted scalar element.
7892    Result = Node->getOperand(1);
7893    break;
7894  case ISD::CONCAT_VECTORS:
7895    assert(Node->getOperand(0).getValueType() == NewVT &&
7896           "Concat of non-legal vectors not yet supported!");
7897    Result = Node->getOperand(0);
7898    break;
7899  case ISD::VECTOR_SHUFFLE: {
7900    // Figure out if the scalar is the LHS or RHS and return it.
7901    SDValue EltNum = Node->getOperand(2).getOperand(0);
7902    if (cast<ConstantSDNode>(EltNum)->getZExtValue())
7903      Result = ScalarizeVectorOp(Node->getOperand(1));
7904    else
7905      Result = ScalarizeVectorOp(Node->getOperand(0));
7906    break;
7907  }
7908  case ISD::EXTRACT_SUBVECTOR:
7909    Result = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, NewVT, Node->getOperand(0),
7910                         Node->getOperand(1));
7911    break;
7912  case ISD::BIT_CONVERT: {
7913    SDValue Op0 = Op.getOperand(0);
7914    if (Op0.getValueType().getVectorNumElements() == 1)
7915      Op0 = ScalarizeVectorOp(Op0);
7916    Result = DAG.getNode(ISD::BIT_CONVERT, NewVT, Op0);
7917    break;
7918  }
7919  case ISD::SELECT:
7920    Result = DAG.getNode(ISD::SELECT, NewVT, Op.getOperand(0),
7921                         ScalarizeVectorOp(Op.getOperand(1)),
7922                         ScalarizeVectorOp(Op.getOperand(2)));
7923    break;
7924  case ISD::SELECT_CC:
7925    Result = DAG.getNode(ISD::SELECT_CC, NewVT, Node->getOperand(0),
7926                         Node->getOperand(1),
7927                         ScalarizeVectorOp(Op.getOperand(2)),
7928                         ScalarizeVectorOp(Op.getOperand(3)),
7929                         Node->getOperand(4));
7930    break;
7931  case ISD::VSETCC: {
7932    SDValue Op0 = ScalarizeVectorOp(Op.getOperand(0));
7933    SDValue Op1 = ScalarizeVectorOp(Op.getOperand(1));
7934    Result = DAG.getNode(ISD::SETCC, TLI.getSetCCResultType(Op0), Op0, Op1,
7935                         Op.getOperand(2));
7936    Result = DAG.getNode(ISD::SELECT, NewVT, Result,
7937                         DAG.getConstant(-1ULL, NewVT),
7938                         DAG.getConstant(0ULL, NewVT));
7939    break;
7940  }
7941  }
7942
7943  if (TLI.isTypeLegal(NewVT))
7944    Result = LegalizeOp(Result);
7945  bool isNew = ScalarizedNodes.insert(std::make_pair(Op, Result)).second;
7946  assert(isNew && "Value already scalarized?");
7947  isNew = isNew;
7948  return Result;
7949}
7950
7951
7952SDValue SelectionDAGLegalize::WidenVectorOp(SDValue Op, MVT WidenVT) {
7953  std::map<SDValue, SDValue>::iterator I = WidenNodes.find(Op);
7954  if (I != WidenNodes.end()) return I->second;
7955
7956  MVT VT = Op.getValueType();
7957  assert(VT.isVector() && "Cannot widen non-vector type!");
7958
7959  SDValue Result;
7960  SDNode *Node = Op.getNode();
7961  MVT EVT = VT.getVectorElementType();
7962
7963  unsigned NumElts = VT.getVectorNumElements();
7964  unsigned NewNumElts = WidenVT.getVectorNumElements();
7965  assert(NewNumElts > NumElts  && "Cannot widen to smaller type!");
7966  assert(NewNumElts < 17);
7967
7968  // When widen is called, it is assumed that it is more efficient to use a
7969  // wide type.  The default action is to widen to operation to a wider legal
7970  // vector type and then do the operation if it is legal by calling LegalizeOp
7971  // again.  If there is no vector equivalent, we will unroll the operation, do
7972  // it, and rebuild the vector.  If most of the operations are vectorizible to
7973  // the legal type, the resulting code will be more efficient.  If this is not
7974  // the case, the resulting code will preform badly as we end up generating
7975  // code to pack/unpack the results. It is the function that calls widen
7976  // that is responsible for seeing this doesn't happen.
7977  switch (Node->getOpcode()) {
7978  default:
7979#ifndef NDEBUG
7980      Node->dump(&DAG);
7981#endif
7982      assert(0 && "Unexpected operation in WidenVectorOp!");
7983      break;
7984  case ISD::CopyFromReg:
7985    assert(0 && "CopyFromReg doesn't need widening!");
7986  case ISD::Constant:
7987  case ISD::ConstantFP:
7988    // To build a vector of these elements, clients should call BuildVector
7989    // and with each element instead of creating a node with a vector type
7990    assert(0 && "Unexpected operation in WidenVectorOp!");
7991  case ISD::VAARG:
7992    // Variable Arguments with vector types doesn't make any sense to me
7993    assert(0 && "Unexpected operation in WidenVectorOp!");
7994    break;
7995  case ISD::UNDEF:
7996    Result = DAG.getNode(ISD::UNDEF, WidenVT);
7997    break;
7998  case ISD::BUILD_VECTOR: {
7999    // Build a vector with undefined for the new nodes
8000    SDValueVector NewOps(Node->op_begin(), Node->op_end());
8001    for (unsigned i = NumElts; i < NewNumElts; ++i) {
8002      NewOps.push_back(DAG.getNode(ISD::UNDEF,EVT));
8003    }
8004    Result = DAG.getNode(ISD::BUILD_VECTOR, WidenVT, &NewOps[0], NewOps.size());
8005    break;
8006  }
8007  case ISD::INSERT_VECTOR_ELT: {
8008    SDValue Tmp1 = WidenVectorOp(Node->getOperand(0), WidenVT);
8009    Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, WidenVT, Tmp1,
8010                         Node->getOperand(1), Node->getOperand(2));
8011    break;
8012  }
8013  case ISD::VECTOR_SHUFFLE: {
8014    SDValue Tmp1 = WidenVectorOp(Node->getOperand(0), WidenVT);
8015    SDValue Tmp2 = WidenVectorOp(Node->getOperand(1), WidenVT);
8016    // VECTOR_SHUFFLE 3rd operand must be a constant build vector that is
8017    // used as permutation array. We build the vector here instead of widening
8018    // because we don't want to legalize and have it turned to something else.
8019    SDValue PermOp = Node->getOperand(2);
8020    SDValueVector NewOps;
8021    MVT PVT = PermOp.getValueType().getVectorElementType();
8022    for (unsigned i = 0; i < NumElts; ++i) {
8023      if (PermOp.getOperand(i).getOpcode() == ISD::UNDEF) {
8024        NewOps.push_back(PermOp.getOperand(i));
8025      } else {
8026        unsigned Idx =
8027          cast<ConstantSDNode>(PermOp.getOperand(i))->getZExtValue();
8028        if (Idx < NumElts) {
8029          NewOps.push_back(PermOp.getOperand(i));
8030        }
8031        else {
8032          NewOps.push_back(DAG.getConstant(Idx + NewNumElts - NumElts,
8033                                           PermOp.getOperand(i).getValueType()));
8034        }
8035      }
8036    }
8037    for (unsigned i = NumElts; i < NewNumElts; ++i) {
8038      NewOps.push_back(DAG.getNode(ISD::UNDEF,PVT));
8039    }
8040
8041    SDValue Tmp3 = DAG.getNode(ISD::BUILD_VECTOR,
8042                               MVT::getVectorVT(PVT, NewOps.size()),
8043                               &NewOps[0], NewOps.size());
8044
8045    Result = DAG.getNode(ISD::VECTOR_SHUFFLE, WidenVT, Tmp1, Tmp2, Tmp3);
8046    break;
8047  }
8048  case ISD::LOAD: {
8049    // If the load widen returns true, we can use a single load for the
8050    // vector.  Otherwise, it is returning a token factor for multiple
8051    // loads.
8052    SDValue TFOp;
8053    if (LoadWidenVectorOp(Result, TFOp, Op, WidenVT))
8054      AddLegalizedOperand(Op.getValue(1), LegalizeOp(TFOp.getValue(1)));
8055    else
8056      AddLegalizedOperand(Op.getValue(1), LegalizeOp(TFOp.getValue(0)));
8057    break;
8058  }
8059
8060  case ISD::BIT_CONVERT: {
8061    SDValue Tmp1 = Node->getOperand(0);
8062    // Converts between two different types so we need to determine
8063    // the correct widen type for the input operand.
8064    MVT TVT = Tmp1.getValueType();
8065    assert(TVT.isVector() && "can not widen non vector type");
8066    MVT TEVT = TVT.getVectorElementType();
8067    assert(WidenVT.getSizeInBits() % EVT.getSizeInBits() == 0 &&
8068         "can not widen bit bit convert that are not multiple of element type");
8069    MVT TWidenVT =  MVT::getVectorVT(TEVT,
8070                                   WidenVT.getSizeInBits()/EVT.getSizeInBits());
8071    Tmp1 = WidenVectorOp(Tmp1, TWidenVT);
8072    assert(Tmp1.getValueType().getSizeInBits() == WidenVT.getSizeInBits());
8073    Result = DAG.getNode(Node->getOpcode(), WidenVT, Tmp1);
8074
8075    TargetLowering::LegalizeAction action =
8076      TLI.getOperationAction(Node->getOpcode(), WidenVT);
8077    switch (action)  {
8078    default: assert(0 && "action not supported");
8079    case TargetLowering::Legal:
8080        break;
8081    case TargetLowering::Promote:
8082        // We defer the promotion to when we legalize the op
8083      break;
8084    case TargetLowering::Expand:
8085      // Expand the operation into a bunch of nasty scalar code.
8086      Result = LegalizeOp(UnrollVectorOp(Result));
8087      break;
8088    }
8089    break;
8090  }
8091
8092  case ISD::SINT_TO_FP:
8093  case ISD::UINT_TO_FP:
8094  case ISD::FP_TO_SINT:
8095  case ISD::FP_TO_UINT: {
8096    SDValue Tmp1 = Node->getOperand(0);
8097    // Converts between two different types so we need to determine
8098    // the correct widen type for the input operand.
8099    MVT TVT = Tmp1.getValueType();
8100    assert(TVT.isVector() && "can not widen non vector type");
8101    MVT TEVT = TVT.getVectorElementType();
8102    MVT TWidenVT =  MVT::getVectorVT(TEVT, NewNumElts);
8103    Tmp1 = WidenVectorOp(Tmp1, TWidenVT);
8104    assert(Tmp1.getValueType().getVectorNumElements() == NewNumElts);
8105    Result = DAG.getNode(Node->getOpcode(), WidenVT, Tmp1);
8106    break;
8107  }
8108
8109  case ISD::FP_EXTEND:
8110    assert(0 && "Case not implemented.  Dynamically dead with 2 FP types!");
8111  case ISD::TRUNCATE:
8112  case ISD::SIGN_EXTEND:
8113  case ISD::ZERO_EXTEND:
8114  case ISD::ANY_EXTEND:
8115  case ISD::FP_ROUND:
8116  case ISD::SIGN_EXTEND_INREG:
8117  case ISD::FABS:
8118  case ISD::FNEG:
8119  case ISD::FSQRT:
8120  case ISD::FSIN:
8121  case ISD::FCOS:
8122  case ISD::CTPOP:
8123  case ISD::CTTZ:
8124  case ISD::CTLZ: {
8125    // Unary op widening
8126    SDValue Tmp1;
8127    Tmp1 = WidenVectorOp(Node->getOperand(0), WidenVT);
8128    assert(Tmp1.getValueType() == WidenVT);
8129    Result = DAG.getNode(Node->getOpcode(), WidenVT, Tmp1);
8130    break;
8131  }
8132  case ISD::CONVERT_RNDSAT: {
8133    SDValue RndOp = Node->getOperand(3);
8134    SDValue SatOp = Node->getOperand(4);
8135    SDValue SrcOp = Node->getOperand(0);
8136
8137    // Converts between two different types so we need to determine
8138    // the correct widen type for the input operand.
8139    MVT SVT = SrcOp.getValueType();
8140    assert(SVT.isVector() && "can not widen non vector type");
8141    MVT SEVT = SVT.getVectorElementType();
8142    MVT SWidenVT =  MVT::getVectorVT(SEVT, NewNumElts);
8143
8144    SrcOp = WidenVectorOp(SrcOp, SWidenVT);
8145    assert(SrcOp.getValueType() == WidenVT);
8146    SDValue DTyOp = DAG.getValueType(WidenVT);
8147    SDValue STyOp = DAG.getValueType(SrcOp.getValueType());
8148    ISD::CvtCode CvtCode = cast<CvtRndSatSDNode>(Node)->getCvtCode();
8149
8150    Result = DAG.getConvertRndSat(WidenVT, SrcOp, DTyOp, STyOp,
8151                                  RndOp, SatOp, CvtCode);
8152    break;
8153  }
8154  case ISD::FPOW:
8155  case ISD::FPOWI:
8156  case ISD::ADD:
8157  case ISD::SUB:
8158  case ISD::MUL:
8159  case ISD::MULHS:
8160  case ISD::MULHU:
8161  case ISD::AND:
8162  case ISD::OR:
8163  case ISD::XOR:
8164  case ISD::FADD:
8165  case ISD::FSUB:
8166  case ISD::FMUL:
8167  case ISD::SDIV:
8168  case ISD::SREM:
8169  case ISD::FDIV:
8170  case ISD::FREM:
8171  case ISD::FCOPYSIGN:
8172  case ISD::UDIV:
8173  case ISD::UREM:
8174  case ISD::BSWAP: {
8175    // Binary op widening
8176    SDValue Tmp1 = WidenVectorOp(Node->getOperand(0), WidenVT);
8177    SDValue Tmp2 = WidenVectorOp(Node->getOperand(1), WidenVT);
8178    assert(Tmp1.getValueType() == WidenVT && Tmp2.getValueType() == WidenVT);
8179    Result = DAG.getNode(Node->getOpcode(), WidenVT, Tmp1, Tmp2);
8180    break;
8181  }
8182
8183  case ISD::SHL:
8184  case ISD::SRA:
8185  case ISD::SRL: {
8186    SDValue Tmp1 = WidenVectorOp(Node->getOperand(0), WidenVT);
8187    assert(Tmp1.getValueType() == WidenVT);
8188    SDValue ShOp = Node->getOperand(1);
8189    MVT ShVT = ShOp.getValueType();
8190    MVT NewShVT = MVT::getVectorVT(ShVT.getVectorElementType(),
8191                                   WidenVT.getVectorNumElements());
8192    ShOp = WidenVectorOp(ShOp, NewShVT);
8193    assert(ShOp.getValueType() == NewShVT);
8194    Result = DAG.getNode(Node->getOpcode(), WidenVT, Tmp1, ShOp);
8195    break;
8196  }
8197
8198  case ISD::EXTRACT_VECTOR_ELT: {
8199    SDValue Tmp1 = WidenVectorOp(Node->getOperand(0), WidenVT);
8200    assert(Tmp1.getValueType() == WidenVT);
8201    Result = DAG.getNode(Node->getOpcode(), EVT, Tmp1, Node->getOperand(1));
8202    break;
8203  }
8204  case ISD::CONCAT_VECTORS: {
8205    // We concurrently support only widen on a multiple of the incoming vector.
8206    // We could widen on a multiple of the incoming operand if necessary.
8207    unsigned NumConcat = NewNumElts / NumElts;
8208    assert(NewNumElts % NumElts == 0 && "Can widen only a multiple of vector");
8209    SDValue UndefVal = DAG.getNode(ISD::UNDEF, VT);
8210    SmallVector<SDValue, 8> MOps;
8211    MOps.push_back(Op);
8212    for (unsigned i = 1; i != NumConcat; ++i) {
8213      MOps.push_back(UndefVal);
8214    }
8215    Result = LegalizeOp(DAG.getNode(ISD::CONCAT_VECTORS, WidenVT,
8216                                    &MOps[0], MOps.size()));
8217    break;
8218  }
8219  case ISD::EXTRACT_SUBVECTOR: {
8220    SDValue Tmp1 = Node->getOperand(0);
8221    SDValue Idx = Node->getOperand(1);
8222    ConstantSDNode *CIdx = dyn_cast<ConstantSDNode>(Idx);
8223    if (CIdx && CIdx->getZExtValue() == 0) {
8224      // Since we are access the start of the vector, the incoming
8225      // vector type might be the proper.
8226      MVT Tmp1VT = Tmp1.getValueType();
8227      if (Tmp1VT == WidenVT)
8228        return Tmp1;
8229      else {
8230        unsigned Tmp1VTNumElts = Tmp1VT.getVectorNumElements();
8231        if (Tmp1VTNumElts < NewNumElts)
8232          Result = WidenVectorOp(Tmp1, WidenVT);
8233        else
8234          Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, WidenVT, Tmp1, Idx);
8235      }
8236    } else if (NewNumElts % NumElts == 0) {
8237      // Widen the extracted subvector.
8238      unsigned NumConcat = NewNumElts / NumElts;
8239      SDValue UndefVal = DAG.getNode(ISD::UNDEF, VT);
8240      SmallVector<SDValue, 8> MOps;
8241      MOps.push_back(Op);
8242      for (unsigned i = 1; i != NumConcat; ++i) {
8243        MOps.push_back(UndefVal);
8244      }
8245      Result = LegalizeOp(DAG.getNode(ISD::CONCAT_VECTORS, WidenVT,
8246                                      &MOps[0], MOps.size()));
8247    } else {
8248      assert(0 && "can not widen extract subvector");
8249     // This could be implemented using insert and build vector but I would
8250     // like to see when this happens.
8251    }
8252    break;
8253  }
8254
8255  case ISD::SELECT: {
8256    // Determine new condition widen type and widen
8257    SDValue Cond1 = Node->getOperand(0);
8258    MVT CondVT = Cond1.getValueType();
8259    assert(CondVT.isVector() && "can not widen non vector type");
8260    MVT CondEVT = CondVT.getVectorElementType();
8261    MVT CondWidenVT =  MVT::getVectorVT(CondEVT, NewNumElts);
8262    Cond1 = WidenVectorOp(Cond1, CondWidenVT);
8263    assert(Cond1.getValueType() == CondWidenVT && "Condition not widen");
8264
8265    SDValue Tmp1 = WidenVectorOp(Node->getOperand(1), WidenVT);
8266    SDValue Tmp2 = WidenVectorOp(Node->getOperand(2), WidenVT);
8267    assert(Tmp1.getValueType() == WidenVT && Tmp2.getValueType() == WidenVT);
8268    Result = DAG.getNode(Node->getOpcode(), WidenVT, Cond1, Tmp1, Tmp2);
8269    break;
8270  }
8271
8272  case ISD::SELECT_CC: {
8273    // Determine new condition widen type and widen
8274    SDValue Cond1 = Node->getOperand(0);
8275    SDValue Cond2 = Node->getOperand(1);
8276    MVT CondVT = Cond1.getValueType();
8277    assert(CondVT.isVector() && "can not widen non vector type");
8278    assert(CondVT == Cond2.getValueType() && "mismatch lhs/rhs");
8279    MVT CondEVT = CondVT.getVectorElementType();
8280    MVT CondWidenVT =  MVT::getVectorVT(CondEVT, NewNumElts);
8281    Cond1 = WidenVectorOp(Cond1, CondWidenVT);
8282    Cond2 = WidenVectorOp(Cond2, CondWidenVT);
8283    assert(Cond1.getValueType() == CondWidenVT &&
8284           Cond2.getValueType() == CondWidenVT && "condition not widen");
8285
8286    SDValue Tmp1 = WidenVectorOp(Node->getOperand(2), WidenVT);
8287    SDValue Tmp2 = WidenVectorOp(Node->getOperand(3), WidenVT);
8288    assert(Tmp1.getValueType() == WidenVT && Tmp2.getValueType() == WidenVT &&
8289           "operands not widen");
8290    Result = DAG.getNode(Node->getOpcode(), WidenVT, Cond1, Cond2, Tmp1,
8291                         Tmp2, Node->getOperand(4));
8292    break;
8293  }
8294  case ISD::VSETCC: {
8295    // Determine widen for the operand
8296    SDValue Tmp1 = Node->getOperand(0);
8297    MVT TmpVT = Tmp1.getValueType();
8298    assert(TmpVT.isVector() && "can not widen non vector type");
8299    MVT TmpEVT = TmpVT.getVectorElementType();
8300    MVT TmpWidenVT =  MVT::getVectorVT(TmpEVT, NewNumElts);
8301    Tmp1 = WidenVectorOp(Tmp1, TmpWidenVT);
8302    SDValue Tmp2 = WidenVectorOp(Node->getOperand(1), TmpWidenVT);
8303    Result = DAG.getNode(Node->getOpcode(), WidenVT, Tmp1, Tmp2,
8304                         Node->getOperand(2));
8305    break;
8306  }
8307  case ISD::ATOMIC_CMP_SWAP_8:
8308  case ISD::ATOMIC_CMP_SWAP_16:
8309  case ISD::ATOMIC_CMP_SWAP_32:
8310  case ISD::ATOMIC_CMP_SWAP_64:
8311  case ISD::ATOMIC_LOAD_ADD_8:
8312  case ISD::ATOMIC_LOAD_SUB_8:
8313  case ISD::ATOMIC_LOAD_AND_8:
8314  case ISD::ATOMIC_LOAD_OR_8:
8315  case ISD::ATOMIC_LOAD_XOR_8:
8316  case ISD::ATOMIC_LOAD_NAND_8:
8317  case ISD::ATOMIC_LOAD_MIN_8:
8318  case ISD::ATOMIC_LOAD_MAX_8:
8319  case ISD::ATOMIC_LOAD_UMIN_8:
8320  case ISD::ATOMIC_LOAD_UMAX_8:
8321  case ISD::ATOMIC_SWAP_8:
8322  case ISD::ATOMIC_LOAD_ADD_16:
8323  case ISD::ATOMIC_LOAD_SUB_16:
8324  case ISD::ATOMIC_LOAD_AND_16:
8325  case ISD::ATOMIC_LOAD_OR_16:
8326  case ISD::ATOMIC_LOAD_XOR_16:
8327  case ISD::ATOMIC_LOAD_NAND_16:
8328  case ISD::ATOMIC_LOAD_MIN_16:
8329  case ISD::ATOMIC_LOAD_MAX_16:
8330  case ISD::ATOMIC_LOAD_UMIN_16:
8331  case ISD::ATOMIC_LOAD_UMAX_16:
8332  case ISD::ATOMIC_SWAP_16:
8333  case ISD::ATOMIC_LOAD_ADD_32:
8334  case ISD::ATOMIC_LOAD_SUB_32:
8335  case ISD::ATOMIC_LOAD_AND_32:
8336  case ISD::ATOMIC_LOAD_OR_32:
8337  case ISD::ATOMIC_LOAD_XOR_32:
8338  case ISD::ATOMIC_LOAD_NAND_32:
8339  case ISD::ATOMIC_LOAD_MIN_32:
8340  case ISD::ATOMIC_LOAD_MAX_32:
8341  case ISD::ATOMIC_LOAD_UMIN_32:
8342  case ISD::ATOMIC_LOAD_UMAX_32:
8343  case ISD::ATOMIC_SWAP_32:
8344  case ISD::ATOMIC_LOAD_ADD_64:
8345  case ISD::ATOMIC_LOAD_SUB_64:
8346  case ISD::ATOMIC_LOAD_AND_64:
8347  case ISD::ATOMIC_LOAD_OR_64:
8348  case ISD::ATOMIC_LOAD_XOR_64:
8349  case ISD::ATOMIC_LOAD_NAND_64:
8350  case ISD::ATOMIC_LOAD_MIN_64:
8351  case ISD::ATOMIC_LOAD_MAX_64:
8352  case ISD::ATOMIC_LOAD_UMIN_64:
8353  case ISD::ATOMIC_LOAD_UMAX_64:
8354  case ISD::ATOMIC_SWAP_64: {
8355    // For now, we assume that using vectors for these operations don't make
8356    // much sense so we just split it.  We return an empty result
8357    SDValue X, Y;
8358    SplitVectorOp(Op, X, Y);
8359    return Result;
8360    break;
8361  }
8362
8363  } // end switch (Node->getOpcode())
8364
8365  assert(Result.getNode() && "Didn't set a result!");
8366  if (Result != Op)
8367    Result = LegalizeOp(Result);
8368
8369  AddWidenedOperand(Op, Result);
8370  return Result;
8371}
8372
8373// Utility function to find a legal vector type and its associated element
8374// type from a preferred width and whose vector type must be the same size
8375// as the VVT.
8376//  TLI:   Target lowering used to determine legal types
8377//  Width: Preferred width of element type
8378//  VVT:   Vector value type whose size we must match.
8379// Returns VecEVT and EVT - the vector type and its associated element type
8380static void FindWidenVecType(TargetLowering &TLI, unsigned Width, MVT VVT,
8381                             MVT& EVT, MVT& VecEVT) {
8382  // We start with the preferred width, make it a power of 2 and see if
8383  // we can find a vector type of that width. If not, we reduce it by
8384  // another power of 2.  If we have widen the type, a vector of bytes should
8385  // always be legal.
8386  assert(TLI.isTypeLegal(VVT));
8387  unsigned EWidth = Width + 1;
8388  do {
8389    assert(EWidth > 0);
8390    EWidth =  (1 << Log2_32(EWidth-1));
8391    EVT = MVT::getIntegerVT(EWidth);
8392    unsigned NumEVT = VVT.getSizeInBits()/EWidth;
8393    VecEVT = MVT::getVectorVT(EVT, NumEVT);
8394  } while (!TLI.isTypeLegal(VecEVT) ||
8395           VVT.getSizeInBits() != VecEVT.getSizeInBits());
8396}
8397
8398SDValue SelectionDAGLegalize::genWidenVectorLoads(SDValueVector& LdChain,
8399                                                    SDValue   Chain,
8400                                                    SDValue   BasePtr,
8401                                                    const Value *SV,
8402                                                    int         SVOffset,
8403                                                    unsigned    Alignment,
8404                                                    bool        isVolatile,
8405                                                    unsigned    LdWidth,
8406                                                    MVT         ResType) {
8407  // We assume that we have good rules to handle loading power of two loads so
8408  // we break down the operations to power of 2 loads.  The strategy is to
8409  // load the largest power of 2 that we can easily transform to a legal vector
8410  // and then insert into that vector, and the cast the result into the legal
8411  // vector that we want.  This avoids unnecessary stack converts.
8412  // TODO: If the Ldwidth is legal, alignment is the same as the LdWidth, and
8413  //       the load is nonvolatile, we an use a wider load for the value.
8414  // Find a vector length we can load a large chunk
8415  MVT EVT, VecEVT;
8416  unsigned EVTWidth;
8417  FindWidenVecType(TLI, LdWidth, ResType, EVT, VecEVT);
8418  EVTWidth = EVT.getSizeInBits();
8419
8420  SDValue LdOp = DAG.getLoad(EVT, Chain, BasePtr, SV, SVOffset,
8421                               isVolatile, Alignment);
8422  SDValue VecOp = DAG.getNode(ISD::SCALAR_TO_VECTOR, VecEVT, LdOp);
8423  LdChain.push_back(LdOp.getValue(1));
8424
8425  // Check if we can load the element with one instruction
8426  if (LdWidth == EVTWidth) {
8427    return DAG.getNode(ISD::BIT_CONVERT, ResType, VecOp);
8428  }
8429
8430  // The vector element order is endianness dependent.
8431  unsigned Idx = 1;
8432  LdWidth -= EVTWidth;
8433  unsigned Offset = 0;
8434
8435  while (LdWidth > 0) {
8436    unsigned Increment = EVTWidth / 8;
8437    Offset += Increment;
8438    BasePtr = DAG.getNode(ISD::ADD, BasePtr.getValueType(), BasePtr,
8439                          DAG.getIntPtrConstant(Increment));
8440
8441    if (LdWidth < EVTWidth) {
8442      // Our current type we are using is too large, use a smaller size by
8443      // using a smaller power of 2
8444      unsigned oEVTWidth = EVTWidth;
8445      FindWidenVecType(TLI, LdWidth, ResType, EVT, VecEVT);
8446      EVTWidth = EVT.getSizeInBits();
8447      // Readjust position and vector position based on new load type
8448      Idx = Idx * (oEVTWidth/EVTWidth);
8449      VecOp = DAG.getNode(ISD::BIT_CONVERT, VecEVT, VecOp);
8450    }
8451
8452    SDValue LdOp = DAG.getLoad(EVT, Chain, BasePtr, SV,
8453                                 SVOffset+Offset, isVolatile,
8454                                 MinAlign(Alignment, Offset));
8455    LdChain.push_back(LdOp.getValue(1));
8456    VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, VecEVT, VecOp, LdOp,
8457                        DAG.getIntPtrConstant(Idx++));
8458
8459    LdWidth -= EVTWidth;
8460  }
8461
8462  return DAG.getNode(ISD::BIT_CONVERT, ResType, VecOp);
8463}
8464
8465bool SelectionDAGLegalize::LoadWidenVectorOp(SDValue& Result,
8466                                             SDValue& TFOp,
8467                                             SDValue Op,
8468                                             MVT NVT) {
8469  // TODO: Add support for ConcatVec and the ability to load many vector
8470  //       types (e.g., v4i8).  This will not work when a vector register
8471  //       to memory mapping is strange (e.g., vector elements are not
8472  //       stored in some sequential order).
8473
8474  // It must be true that the widen vector type is bigger than where
8475  // we need to load from.
8476  LoadSDNode *LD = cast<LoadSDNode>(Op.getNode());
8477  MVT LdVT = LD->getMemoryVT();
8478  assert(LdVT.isVector() && NVT.isVector());
8479  assert(LdVT.getVectorElementType() == NVT.getVectorElementType());
8480
8481  // Load information
8482  SDValue Chain = LD->getChain();
8483  SDValue BasePtr = LD->getBasePtr();
8484  int       SVOffset = LD->getSrcValueOffset();
8485  unsigned  Alignment = LD->getAlignment();
8486  bool      isVolatile = LD->isVolatile();
8487  const Value *SV = LD->getSrcValue();
8488  unsigned int LdWidth = LdVT.getSizeInBits();
8489
8490  // Load value as a large register
8491  SDValueVector LdChain;
8492  Result = genWidenVectorLoads(LdChain, Chain, BasePtr, SV, SVOffset,
8493                               Alignment, isVolatile, LdWidth, NVT);
8494
8495  if (LdChain.size() == 1) {
8496    TFOp = LdChain[0];
8497    return true;
8498  }
8499  else {
8500    TFOp=DAG.getNode(ISD::TokenFactor, MVT::Other, &LdChain[0], LdChain.size());
8501    return false;
8502  }
8503}
8504
8505
8506void SelectionDAGLegalize::genWidenVectorStores(SDValueVector& StChain,
8507                                                SDValue   Chain,
8508                                                SDValue   BasePtr,
8509                                                const Value *SV,
8510                                                int         SVOffset,
8511                                                unsigned    Alignment,
8512                                                bool        isVolatile,
8513                                                SDValue     ValOp,
8514                                                unsigned    StWidth) {
8515  // Breaks the stores into a series of power of 2 width stores.  For any
8516  // width, we convert the vector to the vector of element size that we
8517  // want to store.  This avoids requiring a stack convert.
8518
8519  // Find a width of the element type we can store with
8520  MVT VVT = ValOp.getValueType();
8521  MVT EVT, VecEVT;
8522  unsigned EVTWidth;
8523  FindWidenVecType(TLI, StWidth, VVT, EVT, VecEVT);
8524  EVTWidth = EVT.getSizeInBits();
8525
8526  SDValue VecOp = DAG.getNode(ISD::BIT_CONVERT, VecEVT, ValOp);
8527  SDValue EOp = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, EVT, VecOp,
8528                            DAG.getIntPtrConstant(0));
8529  SDValue StOp = DAG.getStore(Chain, EOp, BasePtr, SV, SVOffset,
8530                               isVolatile, Alignment);
8531  StChain.push_back(StOp);
8532
8533  // Check if we are done
8534  if (StWidth == EVTWidth) {
8535    return;
8536  }
8537
8538  unsigned Idx = 1;
8539  StWidth -= EVTWidth;
8540  unsigned Offset = 0;
8541
8542  while (StWidth > 0) {
8543    unsigned Increment = EVTWidth / 8;
8544    Offset += Increment;
8545    BasePtr = DAG.getNode(ISD::ADD, BasePtr.getValueType(), BasePtr,
8546                          DAG.getIntPtrConstant(Increment));
8547
8548    if (StWidth < EVTWidth) {
8549      // Our current type we are using is too large, use a smaller size by
8550      // using a smaller power of 2
8551      unsigned oEVTWidth = EVTWidth;
8552      FindWidenVecType(TLI, StWidth, VVT, EVT, VecEVT);
8553      EVTWidth = EVT.getSizeInBits();
8554      // Readjust position and vector position based on new load type
8555      Idx = Idx * (oEVTWidth/EVTWidth);
8556      VecOp = DAG.getNode(ISD::BIT_CONVERT, VecEVT, VecOp);
8557    }
8558
8559    EOp = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, EVT, VecOp,
8560                      DAG.getIntPtrConstant(Idx++));
8561    StChain.push_back(DAG.getStore(Chain, EOp, BasePtr, SV,
8562                                   SVOffset + Offset, isVolatile,
8563                                   MinAlign(Alignment, Offset)));
8564    StWidth -= EVTWidth;
8565  }
8566}
8567
8568
8569SDValue SelectionDAGLegalize::StoreWidenVectorOp(StoreSDNode *ST,
8570                                                   SDValue Chain,
8571                                                   SDValue BasePtr) {
8572  // TODO: It might be cleaner if we can use SplitVector and have more legal
8573  //        vector types that can be stored into memory (e.g., v4xi8 can
8574  //        be stored as a word). This will not work when a vector register
8575  //        to memory mapping is strange (e.g., vector elements are not
8576  //        stored in some sequential order).
8577
8578  MVT StVT = ST->getMemoryVT();
8579  SDValue ValOp = ST->getValue();
8580
8581  // Check if we have widen this node with another value
8582  std::map<SDValue, SDValue>::iterator I = WidenNodes.find(ValOp);
8583  if (I != WidenNodes.end())
8584    ValOp = I->second;
8585
8586  MVT VVT = ValOp.getValueType();
8587
8588  // It must be true that we the widen vector type is bigger than where
8589  // we need to store.
8590  assert(StVT.isVector() && VVT.isVector());
8591  assert(StVT.getSizeInBits() < VVT.getSizeInBits());
8592  assert(StVT.getVectorElementType() == VVT.getVectorElementType());
8593
8594  // Store value
8595  SDValueVector StChain;
8596  genWidenVectorStores(StChain, Chain, BasePtr, ST->getSrcValue(),
8597                       ST->getSrcValueOffset(), ST->getAlignment(),
8598                       ST->isVolatile(), ValOp, StVT.getSizeInBits());
8599  if (StChain.size() == 1)
8600    return StChain[0];
8601  else
8602    return DAG.getNode(ISD::TokenFactor, MVT::Other,&StChain[0],StChain.size());
8603}
8604
8605
8606// SelectionDAG::Legalize - This is the entry point for the file.
8607//
8608void SelectionDAG::Legalize(bool TypesNeedLegalizing) {
8609  /// run - This is the main entry point to this class.
8610  ///
8611  SelectionDAGLegalize(*this, TypesNeedLegalizing).LegalizeDAG();
8612}
8613
8614