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