LegalizeDAG.cpp revision e400af83b3f8b69407a8963f1d2e2c82fa766f33
1//===-- LegalizeDAG.cpp - Implement SelectionDAG::Legalize ----------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source 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/Target/TargetFrameInfo.h"
19#include "llvm/Target/TargetLowering.h"
20#include "llvm/Target/TargetData.h"
21#include "llvm/Target/TargetMachine.h"
22#include "llvm/Target/TargetOptions.h"
23#include "llvm/CallingConv.h"
24#include "llvm/Constants.h"
25#include "llvm/DerivedTypes.h"
26#include "llvm/Support/CommandLine.h"
27#include "llvm/Support/Compiler.h"
28#include "llvm/Support/MathExtras.h"
29#include "llvm/ADT/DenseMap.h"
30#include "llvm/ADT/SmallVector.h"
31#include "llvm/ADT/SmallPtrSet.h"
32#include <map>
33using namespace llvm;
34
35#ifndef NDEBUG
36static cl::opt<bool>
37ViewLegalizeDAGs("view-legalize-dags", cl::Hidden,
38                 cl::desc("Pop up a window to show dags before legalize"));
39#else
40static const bool ViewLegalizeDAGs = 0;
41#endif
42
43//===----------------------------------------------------------------------===//
44/// SelectionDAGLegalize - This takes an arbitrary SelectionDAG as input and
45/// hacks on it until the target machine can handle it.  This involves
46/// eliminating value sizes the machine cannot handle (promoting small sizes to
47/// large sizes or splitting up large values into small values) as well as
48/// eliminating operations the machine cannot handle.
49///
50/// This code also does a small amount of optimization and recognition of idioms
51/// as part of its processing.  For example, if a target does not support a
52/// 'setcc' instruction efficiently, but does support 'brcc' instruction, this
53/// will attempt merge setcc and brc instructions into brcc's.
54///
55namespace {
56class VISIBILITY_HIDDEN SelectionDAGLegalize {
57  TargetLowering &TLI;
58  SelectionDAG &DAG;
59
60  // Libcall insertion helpers.
61
62  /// LastCALLSEQ_END - This keeps track of the CALLSEQ_END node that has been
63  /// legalized.  We use this to ensure that calls are properly serialized
64  /// against each other, including inserted libcalls.
65  SDOperand LastCALLSEQ_END;
66
67  /// IsLegalizingCall - This member is used *only* for purposes of providing
68  /// helpful assertions that a libcall isn't created while another call is
69  /// being legalized (which could lead to non-serialized call sequences).
70  bool IsLegalizingCall;
71
72  enum LegalizeAction {
73    Legal,      // The target natively supports this operation.
74    Promote,    // This operation should be executed in a larger type.
75    Expand      // Try to expand this to other ops, otherwise use a libcall.
76  };
77
78  /// ValueTypeActions - This is a bitvector that contains two bits for each
79  /// value type, where the two bits correspond to the LegalizeAction enum.
80  /// This can be queried with "getTypeAction(VT)".
81  TargetLowering::ValueTypeActionImpl ValueTypeActions;
82
83  /// LegalizedNodes - For nodes that are of legal width, and that have more
84  /// than one use, this map indicates what regularized operand to use.  This
85  /// allows us to avoid legalizing the same thing more than once.
86  DenseMap<SDOperand, SDOperand> LegalizedNodes;
87
88  /// PromotedNodes - For nodes that are below legal width, and that have more
89  /// than one use, this map indicates what promoted value to use.  This allows
90  /// us to avoid promoting the same thing more than once.
91  DenseMap<SDOperand, SDOperand> PromotedNodes;
92
93  /// ExpandedNodes - For nodes that need to be expanded this map indicates
94  /// which which operands are the expanded version of the input.  This allows
95  /// us to avoid expanding the same node more than once.
96  DenseMap<SDOperand, std::pair<SDOperand, SDOperand> > ExpandedNodes;
97
98  /// SplitNodes - For vector nodes that need to be split, this map indicates
99  /// which which operands are the split version of the input.  This allows us
100  /// to avoid splitting the same node more than once.
101  std::map<SDOperand, std::pair<SDOperand, SDOperand> > SplitNodes;
102
103  /// ScalarizedNodes - For nodes that need to be converted from vector types to
104  /// scalar types, this contains the mapping of ones we have already
105  /// processed to the result.
106  std::map<SDOperand, SDOperand> ScalarizedNodes;
107
108  void AddLegalizedOperand(SDOperand From, SDOperand To) {
109    LegalizedNodes.insert(std::make_pair(From, To));
110    // If someone requests legalization of the new node, return itself.
111    if (From != To)
112      LegalizedNodes.insert(std::make_pair(To, To));
113  }
114  void AddPromotedOperand(SDOperand From, SDOperand To) {
115    bool isNew = PromotedNodes.insert(std::make_pair(From, To));
116    assert(isNew && "Got into the map somehow?");
117    // If someone requests legalization of the new node, return itself.
118    LegalizedNodes.insert(std::make_pair(To, To));
119  }
120
121public:
122
123  SelectionDAGLegalize(SelectionDAG &DAG);
124
125  /// getTypeAction - Return how we should legalize values of this type, either
126  /// it is already legal or we need to expand it into multiple registers of
127  /// smaller integer type, or we need to promote it to a larger type.
128  LegalizeAction getTypeAction(MVT::ValueType VT) const {
129    return (LegalizeAction)ValueTypeActions.getTypeAction(VT);
130  }
131
132  /// isTypeLegal - Return true if this type is legal on this target.
133  ///
134  bool isTypeLegal(MVT::ValueType VT) const {
135    return getTypeAction(VT) == Legal;
136  }
137
138  void LegalizeDAG();
139
140private:
141  /// HandleOp - Legalize, Promote, or Expand the specified operand as
142  /// appropriate for its type.
143  void HandleOp(SDOperand Op);
144
145  /// LegalizeOp - We know that the specified value has a legal type.
146  /// Recursively ensure that the operands have legal types, then return the
147  /// result.
148  SDOperand LegalizeOp(SDOperand O);
149
150  /// UnrollVectorOp - We know that the given vector has a legal type, however
151  /// the operation it performs is not legal and is an operation that we have
152  /// no way of lowering.  "Unroll" the vector, splitting out the scalars and
153  /// operating on each element individually.
154  SDOperand UnrollVectorOp(SDOperand O);
155
156  /// PromoteOp - Given an operation that produces a value in an invalid type,
157  /// promote it to compute the value into a larger type.  The produced value
158  /// will have the correct bits for the low portion of the register, but no
159  /// guarantee is made about the top bits: it may be zero, sign-extended, or
160  /// garbage.
161  SDOperand PromoteOp(SDOperand O);
162
163  /// ExpandOp - Expand the specified SDOperand into its two component pieces
164  /// Lo&Hi.  Note that the Op MUST be an expanded type.  As a result of this,
165  /// the LegalizeNodes map is filled in for any results that are not expanded,
166  /// the ExpandedNodes map is filled in for any results that are expanded, and
167  /// the Lo/Hi values are returned.   This applies to integer types and Vector
168  /// types.
169  void ExpandOp(SDOperand O, SDOperand &Lo, SDOperand &Hi);
170
171  /// SplitVectorOp - Given an operand of vector type, break it down into
172  /// two smaller values.
173  void SplitVectorOp(SDOperand O, SDOperand &Lo, SDOperand &Hi);
174
175  /// ScalarizeVectorOp - Given an operand of single-element vector type
176  /// (e.g. v1f32), convert it into the equivalent operation that returns a
177  /// scalar (e.g. f32) value.
178  SDOperand ScalarizeVectorOp(SDOperand O);
179
180  /// isShuffleLegal - Return true if a vector shuffle is legal with the
181  /// specified mask and type.  Targets can specify exactly which masks they
182  /// support and the code generator is tasked with not creating illegal masks.
183  ///
184  /// Note that this will also return true for shuffles that are promoted to a
185  /// different type.
186  ///
187  /// If this is a legal shuffle, this method returns the (possibly promoted)
188  /// build_vector Mask.  If it's not a legal shuffle, it returns null.
189  SDNode *isShuffleLegal(MVT::ValueType VT, SDOperand Mask) const;
190
191  bool LegalizeAllNodesNotLeadingTo(SDNode *N, SDNode *Dest,
192                                    SmallPtrSet<SDNode*, 32> &NodesLeadingTo);
193
194  void LegalizeSetCCOperands(SDOperand &LHS, SDOperand &RHS, SDOperand &CC);
195
196  SDOperand ExpandLibCall(const char *Name, SDNode *Node, bool isSigned,
197                          SDOperand &Hi);
198  SDOperand ExpandIntToFP(bool isSigned, MVT::ValueType DestTy,
199                          SDOperand Source);
200
201  SDOperand ExpandBIT_CONVERT(MVT::ValueType DestVT, SDOperand SrcOp);
202  SDOperand ExpandBUILD_VECTOR(SDNode *Node);
203  SDOperand ExpandSCALAR_TO_VECTOR(SDNode *Node);
204  SDOperand ExpandLegalINT_TO_FP(bool isSigned,
205                                 SDOperand LegalOp,
206                                 MVT::ValueType DestVT);
207  SDOperand PromoteLegalINT_TO_FP(SDOperand LegalOp, MVT::ValueType DestVT,
208                                  bool isSigned);
209  SDOperand PromoteLegalFP_TO_INT(SDOperand LegalOp, MVT::ValueType DestVT,
210                                  bool isSigned);
211
212  SDOperand ExpandBSWAP(SDOperand Op);
213  SDOperand ExpandBitCount(unsigned Opc, SDOperand Op);
214  bool ExpandShift(unsigned Opc, SDOperand Op, SDOperand Amt,
215                   SDOperand &Lo, SDOperand &Hi);
216  void ExpandShiftParts(unsigned NodeOp, SDOperand Op, SDOperand Amt,
217                        SDOperand &Lo, SDOperand &Hi);
218
219  SDOperand ExpandEXTRACT_SUBVECTOR(SDOperand Op);
220  SDOperand ExpandEXTRACT_VECTOR_ELT(SDOperand Op);
221
222  SDOperand getIntPtrConstant(uint64_t Val) {
223    return DAG.getConstant(Val, TLI.getPointerTy());
224  }
225};
226}
227
228/// isVectorShuffleLegal - Return true if a vector shuffle is legal with the
229/// specified mask and type.  Targets can specify exactly which masks they
230/// support and the code generator is tasked with not creating illegal masks.
231///
232/// Note that this will also return true for shuffles that are promoted to a
233/// different type.
234SDNode *SelectionDAGLegalize::isShuffleLegal(MVT::ValueType VT,
235                                             SDOperand Mask) const {
236  switch (TLI.getOperationAction(ISD::VECTOR_SHUFFLE, VT)) {
237  default: return 0;
238  case TargetLowering::Legal:
239  case TargetLowering::Custom:
240    break;
241  case TargetLowering::Promote: {
242    // If this is promoted to a different type, convert the shuffle mask and
243    // ask if it is legal in the promoted type!
244    MVT::ValueType NVT = TLI.getTypeToPromoteTo(ISD::VECTOR_SHUFFLE, VT);
245
246    // If we changed # elements, change the shuffle mask.
247    unsigned NumEltsGrowth =
248      MVT::getVectorNumElements(NVT) / MVT::getVectorNumElements(VT);
249    assert(NumEltsGrowth && "Cannot promote to vector type with fewer elts!");
250    if (NumEltsGrowth > 1) {
251      // Renumber the elements.
252      SmallVector<SDOperand, 8> Ops;
253      for (unsigned i = 0, e = Mask.getNumOperands(); i != e; ++i) {
254        SDOperand InOp = Mask.getOperand(i);
255        for (unsigned j = 0; j != NumEltsGrowth; ++j) {
256          if (InOp.getOpcode() == ISD::UNDEF)
257            Ops.push_back(DAG.getNode(ISD::UNDEF, MVT::i32));
258          else {
259            unsigned InEltNo = cast<ConstantSDNode>(InOp)->getValue();
260            Ops.push_back(DAG.getConstant(InEltNo*NumEltsGrowth+j, MVT::i32));
261          }
262        }
263      }
264      Mask = DAG.getNode(ISD::BUILD_VECTOR, NVT, &Ops[0], Ops.size());
265    }
266    VT = NVT;
267    break;
268  }
269  }
270  return TLI.isShuffleMaskLegal(Mask, VT) ? Mask.Val : 0;
271}
272
273SelectionDAGLegalize::SelectionDAGLegalize(SelectionDAG &dag)
274  : TLI(dag.getTargetLoweringInfo()), DAG(dag),
275    ValueTypeActions(TLI.getValueTypeActions()) {
276  assert(MVT::LAST_VALUETYPE <= 32 &&
277         "Too many value types for ValueTypeActions to hold!");
278}
279
280/// ComputeTopDownOrdering - Compute a top-down ordering of the dag, where Order
281/// contains all of a nodes operands before it contains the node.
282static void ComputeTopDownOrdering(SelectionDAG &DAG,
283                                   SmallVector<SDNode*, 64> &Order) {
284
285  DenseMap<SDNode*, unsigned> Visited;
286  std::vector<SDNode*> Worklist;
287  Worklist.reserve(128);
288
289  // Compute ordering from all of the leaves in the graphs, those (like the
290  // entry node) that have no operands.
291  for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
292       E = DAG.allnodes_end(); I != E; ++I) {
293    if (I->getNumOperands() == 0) {
294      Visited[I] = 0 - 1U;
295      Worklist.push_back(I);
296    }
297  }
298
299  while (!Worklist.empty()) {
300    SDNode *N = Worklist.back();
301    Worklist.pop_back();
302
303    if (++Visited[N] != N->getNumOperands())
304      continue;  // Haven't visited all operands yet
305
306    Order.push_back(N);
307
308    // Now that we have N in, add anything that uses it if all of their operands
309    // are now done.
310    for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end();
311         UI != E; ++UI)
312      Worklist.push_back(*UI);
313  }
314
315  assert(Order.size() == Visited.size() &&
316         Order.size() ==
317         (unsigned)std::distance(DAG.allnodes_begin(), DAG.allnodes_end()) &&
318         "Error: DAG is cyclic!");
319}
320
321
322void SelectionDAGLegalize::LegalizeDAG() {
323  LastCALLSEQ_END = DAG.getEntryNode();
324  IsLegalizingCall = false;
325
326  // The legalize process is inherently a bottom-up recursive process (users
327  // legalize their uses before themselves).  Given infinite stack space, we
328  // could just start legalizing on the root and traverse the whole graph.  In
329  // practice however, this causes us to run out of stack space on large basic
330  // blocks.  To avoid this problem, compute an ordering of the nodes where each
331  // node is only legalized after all of its operands are legalized.
332  SmallVector<SDNode*, 64> Order;
333  ComputeTopDownOrdering(DAG, Order);
334
335  for (unsigned i = 0, e = Order.size(); i != e; ++i)
336    HandleOp(SDOperand(Order[i], 0));
337
338  // Finally, it's possible the root changed.  Get the new root.
339  SDOperand OldRoot = DAG.getRoot();
340  assert(LegalizedNodes.count(OldRoot) && "Root didn't get legalized?");
341  DAG.setRoot(LegalizedNodes[OldRoot]);
342
343  ExpandedNodes.clear();
344  LegalizedNodes.clear();
345  PromotedNodes.clear();
346  SplitNodes.clear();
347  ScalarizedNodes.clear();
348
349  // Remove dead nodes now.
350  DAG.RemoveDeadNodes();
351}
352
353
354/// FindCallEndFromCallStart - Given a chained node that is part of a call
355/// sequence, find the CALLSEQ_END node that terminates the call sequence.
356static SDNode *FindCallEndFromCallStart(SDNode *Node) {
357  if (Node->getOpcode() == ISD::CALLSEQ_END)
358    return Node;
359  if (Node->use_empty())
360    return 0;   // No CallSeqEnd
361
362  // The chain is usually at the end.
363  SDOperand TheChain(Node, Node->getNumValues()-1);
364  if (TheChain.getValueType() != MVT::Other) {
365    // Sometimes it's at the beginning.
366    TheChain = SDOperand(Node, 0);
367    if (TheChain.getValueType() != MVT::Other) {
368      // Otherwise, hunt for it.
369      for (unsigned i = 1, e = Node->getNumValues(); i != e; ++i)
370        if (Node->getValueType(i) == MVT::Other) {
371          TheChain = SDOperand(Node, i);
372          break;
373        }
374
375      // Otherwise, we walked into a node without a chain.
376      if (TheChain.getValueType() != MVT::Other)
377        return 0;
378    }
379  }
380
381  for (SDNode::use_iterator UI = Node->use_begin(),
382       E = Node->use_end(); UI != E; ++UI) {
383
384    // Make sure to only follow users of our token chain.
385    SDNode *User = *UI;
386    for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i)
387      if (User->getOperand(i) == TheChain)
388        if (SDNode *Result = FindCallEndFromCallStart(User))
389          return Result;
390  }
391  return 0;
392}
393
394/// FindCallStartFromCallEnd - Given a chained node that is part of a call
395/// sequence, find the CALLSEQ_START node that initiates the call sequence.
396static SDNode *FindCallStartFromCallEnd(SDNode *Node) {
397  assert(Node && "Didn't find callseq_start for a call??");
398  if (Node->getOpcode() == ISD::CALLSEQ_START) return Node;
399
400  assert(Node->getOperand(0).getValueType() == MVT::Other &&
401         "Node doesn't have a token chain argument!");
402  return FindCallStartFromCallEnd(Node->getOperand(0).Val);
403}
404
405/// LegalizeAllNodesNotLeadingTo - Recursively walk the uses of N, looking to
406/// see if any uses can reach Dest.  If no dest operands can get to dest,
407/// legalize them, legalize ourself, and return false, otherwise, return true.
408///
409/// Keep track of the nodes we fine that actually do lead to Dest in
410/// NodesLeadingTo.  This avoids retraversing them exponential number of times.
411///
412bool SelectionDAGLegalize::LegalizeAllNodesNotLeadingTo(SDNode *N, SDNode *Dest,
413                                     SmallPtrSet<SDNode*, 32> &NodesLeadingTo) {
414  if (N == Dest) return true;  // N certainly leads to Dest :)
415
416  // If we've already processed this node and it does lead to Dest, there is no
417  // need to reprocess it.
418  if (NodesLeadingTo.count(N)) return true;
419
420  // If the first result of this node has been already legalized, then it cannot
421  // reach N.
422  switch (getTypeAction(N->getValueType(0))) {
423  case Legal:
424    if (LegalizedNodes.count(SDOperand(N, 0))) return false;
425    break;
426  case Promote:
427    if (PromotedNodes.count(SDOperand(N, 0))) return false;
428    break;
429  case Expand:
430    if (ExpandedNodes.count(SDOperand(N, 0))) return false;
431    break;
432  }
433
434  // Okay, this node has not already been legalized.  Check and legalize all
435  // operands.  If none lead to Dest, then we can legalize this node.
436  bool OperandsLeadToDest = false;
437  for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
438    OperandsLeadToDest |=     // If an operand leads to Dest, so do we.
439      LegalizeAllNodesNotLeadingTo(N->getOperand(i).Val, Dest, NodesLeadingTo);
440
441  if (OperandsLeadToDest) {
442    NodesLeadingTo.insert(N);
443    return true;
444  }
445
446  // Okay, this node looks safe, legalize it and return false.
447  HandleOp(SDOperand(N, 0));
448  return false;
449}
450
451/// HandleOp - Legalize, Promote, or Expand the specified operand as
452/// appropriate for its type.
453void SelectionDAGLegalize::HandleOp(SDOperand Op) {
454  MVT::ValueType VT = Op.getValueType();
455  switch (getTypeAction(VT)) {
456  default: assert(0 && "Bad type action!");
457  case Legal:   (void)LegalizeOp(Op); break;
458  case Promote: (void)PromoteOp(Op); break;
459  case Expand:
460    if (!MVT::isVector(VT)) {
461      // If this is an illegal scalar, expand it into its two component
462      // pieces.
463      SDOperand X, Y;
464      if (Op.getOpcode() == ISD::TargetConstant)
465        break;  // Allow illegal target nodes.
466      ExpandOp(Op, X, Y);
467    } else if (MVT::getVectorNumElements(VT) == 1) {
468      // If this is an illegal single element vector, convert it to a
469      // scalar operation.
470      (void)ScalarizeVectorOp(Op);
471    } else {
472      // Otherwise, this is an illegal multiple element vector.
473      // Split it in half and legalize both parts.
474      SDOperand X, Y;
475      SplitVectorOp(Op, X, Y);
476    }
477    break;
478  }
479}
480
481/// ExpandConstantFP - Expands the ConstantFP node to an integer constant or
482/// a load from the constant pool.
483static SDOperand ExpandConstantFP(ConstantFPSDNode *CFP, bool UseCP,
484                                  SelectionDAG &DAG, TargetLowering &TLI) {
485  bool Extend = false;
486
487  // If a FP immediate is precise when represented as a float and if the
488  // target can do an extending load from float to double, we put it into
489  // the constant pool as a float, even if it's is statically typed as a
490  // double.
491  MVT::ValueType VT = CFP->getValueType(0);
492  bool isDouble = VT == MVT::f64;
493  ConstantFP *LLVMC = ConstantFP::get(MVT::getTypeForValueType(VT),
494                                      CFP->getValueAPF());
495  if (!UseCP) {
496    if (VT!=MVT::f64 && VT!=MVT::f32)
497      assert(0 && "Invalid type expansion");
498    return DAG.getConstant(LLVMC->getValueAPF().convertToAPInt().getZExtValue(),
499                           isDouble ? MVT::i64 : MVT::i32);
500  }
501
502  if (isDouble && CFP->isValueValidForType(MVT::f32, CFP->getValueAPF()) &&
503      // Only do this if the target has a native EXTLOAD instruction from f32.
504      // Do not try to be clever about long doubles (so far)
505      TLI.isLoadXLegal(ISD::EXTLOAD, MVT::f32)) {
506    LLVMC = cast<ConstantFP>(ConstantExpr::getFPTrunc(LLVMC,Type::FloatTy));
507    VT = MVT::f32;
508    Extend = true;
509  }
510
511  SDOperand CPIdx = DAG.getConstantPool(LLVMC, TLI.getPointerTy());
512  if (Extend) {
513    return DAG.getExtLoad(ISD::EXTLOAD, MVT::f64, DAG.getEntryNode(),
514                          CPIdx, NULL, 0, MVT::f32);
515  } else {
516    return DAG.getLoad(VT, DAG.getEntryNode(), CPIdx, NULL, 0);
517  }
518}
519
520
521/// ExpandFCOPYSIGNToBitwiseOps - Expands fcopysign to a series of bitwise
522/// operations.
523static
524SDOperand ExpandFCOPYSIGNToBitwiseOps(SDNode *Node, MVT::ValueType NVT,
525                                      SelectionDAG &DAG, TargetLowering &TLI) {
526  MVT::ValueType VT = Node->getValueType(0);
527  MVT::ValueType SrcVT = Node->getOperand(1).getValueType();
528  assert((SrcVT == MVT::f32 || SrcVT == MVT::f64) &&
529         "fcopysign expansion only supported for f32 and f64");
530  MVT::ValueType SrcNVT = (SrcVT == MVT::f64) ? MVT::i64 : MVT::i32;
531
532  // First get the sign bit of second operand.
533  SDOperand Mask1 = (SrcVT == MVT::f64)
534    ? DAG.getConstantFP(BitsToDouble(1ULL << 63), SrcVT)
535    : DAG.getConstantFP(BitsToFloat(1U << 31), SrcVT);
536  Mask1 = DAG.getNode(ISD::BIT_CONVERT, SrcNVT, Mask1);
537  SDOperand SignBit= DAG.getNode(ISD::BIT_CONVERT, SrcNVT, Node->getOperand(1));
538  SignBit = DAG.getNode(ISD::AND, SrcNVT, SignBit, Mask1);
539  // Shift right or sign-extend it if the two operands have different types.
540  int SizeDiff = MVT::getSizeInBits(SrcNVT) - MVT::getSizeInBits(NVT);
541  if (SizeDiff > 0) {
542    SignBit = DAG.getNode(ISD::SRL, SrcNVT, SignBit,
543                          DAG.getConstant(SizeDiff, TLI.getShiftAmountTy()));
544    SignBit = DAG.getNode(ISD::TRUNCATE, NVT, SignBit);
545  } else if (SizeDiff < 0)
546    SignBit = DAG.getNode(ISD::SIGN_EXTEND, NVT, SignBit);
547
548  // Clear the sign bit of first operand.
549  SDOperand Mask2 = (VT == MVT::f64)
550    ? DAG.getConstantFP(BitsToDouble(~(1ULL << 63)), VT)
551    : DAG.getConstantFP(BitsToFloat(~(1U << 31)), VT);
552  Mask2 = DAG.getNode(ISD::BIT_CONVERT, NVT, Mask2);
553  SDOperand Result = DAG.getNode(ISD::BIT_CONVERT, NVT, Node->getOperand(0));
554  Result = DAG.getNode(ISD::AND, NVT, Result, Mask2);
555
556  // Or the value with the sign bit.
557  Result = DAG.getNode(ISD::OR, NVT, Result, SignBit);
558  return Result;
559}
560
561/// ExpandUnalignedStore - Expands an unaligned store to 2 half-size stores.
562static
563SDOperand ExpandUnalignedStore(StoreSDNode *ST, SelectionDAG &DAG,
564                               TargetLowering &TLI) {
565  SDOperand Chain = ST->getChain();
566  SDOperand Ptr = ST->getBasePtr();
567  SDOperand Val = ST->getValue();
568  MVT::ValueType VT = Val.getValueType();
569  int Alignment = ST->getAlignment();
570  int SVOffset = ST->getSrcValueOffset();
571  if (MVT::isFloatingPoint(ST->getStoredVT())) {
572    // Expand to a bitconvert of the value to the integer type of the
573    // same size, then a (misaligned) int store.
574    MVT::ValueType intVT;
575    if (VT==MVT::f64)
576      intVT = MVT::i64;
577    else if (VT==MVT::f32)
578      intVT = MVT::i32;
579    else
580      assert(0 && "Unaligned load of unsupported floating point type");
581
582    SDOperand Result = DAG.getNode(ISD::BIT_CONVERT, intVT, Val);
583    return DAG.getStore(Chain, Result, Ptr, ST->getSrcValue(),
584                        SVOffset, ST->isVolatile(), Alignment);
585  }
586  assert(MVT::isInteger(ST->getStoredVT()) &&
587         "Unaligned store of unknown type.");
588  // Get the half-size VT
589  MVT::ValueType NewStoredVT = ST->getStoredVT() - 1;
590  int NumBits = MVT::getSizeInBits(NewStoredVT);
591  int IncrementSize = NumBits / 8;
592
593  // Divide the stored value in two parts.
594  SDOperand ShiftAmount = DAG.getConstant(NumBits, TLI.getShiftAmountTy());
595  SDOperand Lo = Val;
596  SDOperand Hi = DAG.getNode(ISD::SRL, VT, Val, ShiftAmount);
597
598  // Store the two parts
599  SDOperand Store1, Store2;
600  Store1 = DAG.getTruncStore(Chain, TLI.isLittleEndian()?Lo:Hi, Ptr,
601                             ST->getSrcValue(), SVOffset, NewStoredVT,
602                             ST->isVolatile(), Alignment);
603  Ptr = DAG.getNode(ISD::ADD, Ptr.getValueType(), Ptr,
604                    DAG.getConstant(IncrementSize, TLI.getPointerTy()));
605  Alignment = MinAlign(Alignment, IncrementSize);
606  Store2 = DAG.getTruncStore(Chain, TLI.isLittleEndian()?Hi:Lo, Ptr,
607                             ST->getSrcValue(), SVOffset + IncrementSize,
608                             NewStoredVT, ST->isVolatile(), Alignment);
609
610  return DAG.getNode(ISD::TokenFactor, MVT::Other, Store1, Store2);
611}
612
613/// ExpandUnalignedLoad - Expands an unaligned load to 2 half-size loads.
614static
615SDOperand ExpandUnalignedLoad(LoadSDNode *LD, SelectionDAG &DAG,
616                              TargetLowering &TLI) {
617  int SVOffset = LD->getSrcValueOffset();
618  SDOperand Chain = LD->getChain();
619  SDOperand Ptr = LD->getBasePtr();
620  MVT::ValueType VT = LD->getValueType(0);
621  MVT::ValueType LoadedVT = LD->getLoadedVT();
622  if (MVT::isFloatingPoint(VT) && !MVT::isVector(VT)) {
623    // Expand to a (misaligned) integer load of the same size,
624    // then bitconvert to floating point.
625    MVT::ValueType intVT;
626    if (LoadedVT == MVT::f64)
627      intVT = MVT::i64;
628    else if (LoadedVT == MVT::f32)
629      intVT = MVT::i32;
630    else
631      assert(0 && "Unaligned load of unsupported floating point type");
632
633    SDOperand newLoad = DAG.getLoad(intVT, Chain, Ptr, LD->getSrcValue(),
634                                    SVOffset, LD->isVolatile(),
635                                    LD->getAlignment());
636    SDOperand Result = DAG.getNode(ISD::BIT_CONVERT, LoadedVT, newLoad);
637    if (LoadedVT != VT)
638      Result = DAG.getNode(ISD::FP_EXTEND, VT, Result);
639
640    SDOperand Ops[] = { Result, Chain };
641    return DAG.getNode(ISD::MERGE_VALUES, DAG.getVTList(VT, MVT::Other),
642                       Ops, 2);
643  }
644  assert((MVT::isInteger(LoadedVT) || MVT::isVector(LoadedVT)) &&
645         "Unaligned load of unsupported type.");
646
647  // Compute the new VT that is half the size of the old one.  We either have an
648  // integer MVT or we have a vector MVT.
649  unsigned NumBits = MVT::getSizeInBits(LoadedVT);
650  MVT::ValueType NewLoadedVT;
651  if (!MVT::isVector(LoadedVT)) {
652    NewLoadedVT = MVT::getIntegerType(NumBits/2);
653  } else {
654    // FIXME: This is not right for <1 x anything> it is also not right for
655    // non-power-of-two vectors.
656    NewLoadedVT = MVT::getVectorType(MVT::getVectorElementType(LoadedVT),
657                                     MVT::getVectorNumElements(LoadedVT)/2);
658  }
659  NumBits >>= 1;
660
661  unsigned Alignment = LD->getAlignment();
662  unsigned IncrementSize = NumBits / 8;
663  ISD::LoadExtType HiExtType = LD->getExtensionType();
664
665  // If the original load is NON_EXTLOAD, the hi part load must be ZEXTLOAD.
666  if (HiExtType == ISD::NON_EXTLOAD)
667    HiExtType = ISD::ZEXTLOAD;
668
669  // Load the value in two parts
670  SDOperand Lo, Hi;
671  if (TLI.isLittleEndian()) {
672    Lo = DAG.getExtLoad(ISD::ZEXTLOAD, VT, Chain, Ptr, LD->getSrcValue(),
673                        SVOffset, NewLoadedVT, LD->isVolatile(), Alignment);
674    Ptr = DAG.getNode(ISD::ADD, Ptr.getValueType(), Ptr,
675                      DAG.getConstant(IncrementSize, TLI.getPointerTy()));
676    Hi = DAG.getExtLoad(HiExtType, VT, Chain, Ptr, LD->getSrcValue(),
677                        SVOffset + IncrementSize, NewLoadedVT, LD->isVolatile(),
678                        MinAlign(Alignment, IncrementSize));
679  } else {
680    Hi = DAG.getExtLoad(HiExtType, VT, Chain, Ptr, LD->getSrcValue(), SVOffset,
681                        NewLoadedVT,LD->isVolatile(), Alignment);
682    Ptr = DAG.getNode(ISD::ADD, Ptr.getValueType(), Ptr,
683                      DAG.getConstant(IncrementSize, TLI.getPointerTy()));
684    Lo = DAG.getExtLoad(ISD::ZEXTLOAD, VT, Chain, Ptr, LD->getSrcValue(),
685                        SVOffset + IncrementSize, NewLoadedVT, LD->isVolatile(),
686                        MinAlign(Alignment, IncrementSize));
687  }
688
689  // aggregate the two parts
690  SDOperand ShiftAmount = DAG.getConstant(NumBits, TLI.getShiftAmountTy());
691  SDOperand Result = DAG.getNode(ISD::SHL, VT, Hi, ShiftAmount);
692  Result = DAG.getNode(ISD::OR, VT, Result, Lo);
693
694  SDOperand TF = DAG.getNode(ISD::TokenFactor, MVT::Other, Lo.getValue(1),
695                             Hi.getValue(1));
696
697  SDOperand Ops[] = { Result, TF };
698  return DAG.getNode(ISD::MERGE_VALUES, DAG.getVTList(VT, MVT::Other), Ops, 2);
699}
700
701/// UnrollVectorOp - We know that the given vector has a legal type, however
702/// the operation it performs is not legal and is an operation that we have
703/// no way of lowering.  "Unroll" the vector, splitting out the scalars and
704/// operating on each element individually.
705SDOperand SelectionDAGLegalize::UnrollVectorOp(SDOperand Op) {
706  MVT::ValueType VT = Op.getValueType();
707  assert(isTypeLegal(VT) &&
708         "Caller should expand or promote operands that are not legal!");
709  assert(Op.Val->getNumValues() == 1 &&
710         "Can't unroll a vector with multiple results!");
711  unsigned NE = MVT::getVectorNumElements(VT);
712  MVT::ValueType EltVT = MVT::getVectorElementType(VT);
713
714  SmallVector<SDOperand, 8> Scalars;
715  SmallVector<SDOperand, 4> Operands(Op.getNumOperands());
716  for (unsigned i = 0; i != NE; ++i) {
717    for (unsigned j = 0; j != Op.getNumOperands(); ++j) {
718      SDOperand Operand = Op.getOperand(j);
719      MVT::ValueType OperandVT = Operand.getValueType();
720      if (MVT::isVector(OperandVT)) {
721        // A vector operand; extract a single element.
722        MVT::ValueType OperandEltVT = MVT::getVectorElementType(OperandVT);
723        Operands[j] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
724                                  OperandEltVT,
725                                  Operand,
726                                  DAG.getConstant(i, MVT::i32));
727      } else {
728        // A scalar operand; just use it as is.
729        Operands[j] = Operand;
730      }
731    }
732    Scalars.push_back(DAG.getNode(Op.getOpcode(), EltVT,
733                                  &Operands[0], Operands.size()));
734  }
735
736  return DAG.getNode(ISD::BUILD_VECTOR, VT, &Scalars[0], Scalars.size());
737}
738
739/// LegalizeOp - We know that the specified value has a legal type, and
740/// that its operands are legal.  Now ensure that the operation itself
741/// is legal, recursively ensuring that the operands' operations remain
742/// legal.
743SDOperand SelectionDAGLegalize::LegalizeOp(SDOperand Op) {
744  if (Op.getOpcode() == ISD::TargetConstant) // Allow illegal target nodes.
745    return Op;
746
747  assert(isTypeLegal(Op.getValueType()) &&
748         "Caller should expand or promote operands that are not legal!");
749  SDNode *Node = Op.Val;
750
751  // If this operation defines any values that cannot be represented in a
752  // register on this target, make sure to expand or promote them.
753  if (Node->getNumValues() > 1) {
754    for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
755      if (getTypeAction(Node->getValueType(i)) != Legal) {
756        HandleOp(Op.getValue(i));
757        assert(LegalizedNodes.count(Op) &&
758               "Handling didn't add legal operands!");
759        return LegalizedNodes[Op];
760      }
761  }
762
763  // Note that LegalizeOp may be reentered even from single-use nodes, which
764  // means that we always must cache transformed nodes.
765  DenseMap<SDOperand, SDOperand>::iterator I = LegalizedNodes.find(Op);
766  if (I != LegalizedNodes.end()) return I->second;
767
768  SDOperand Tmp1, Tmp2, Tmp3, Tmp4;
769  SDOperand Result = Op;
770  bool isCustom = false;
771
772  switch (Node->getOpcode()) {
773  case ISD::FrameIndex:
774  case ISD::EntryToken:
775  case ISD::Register:
776  case ISD::BasicBlock:
777  case ISD::TargetFrameIndex:
778  case ISD::TargetJumpTable:
779  case ISD::TargetConstant:
780  case ISD::TargetConstantFP:
781  case ISD::TargetConstantPool:
782  case ISD::TargetGlobalAddress:
783  case ISD::TargetGlobalTLSAddress:
784  case ISD::TargetExternalSymbol:
785  case ISD::VALUETYPE:
786  case ISD::SRCVALUE:
787  case ISD::STRING:
788  case ISD::CONDCODE:
789    // Primitives must all be legal.
790    assert(TLI.isOperationLegal(Node->getOpcode(), Node->getValueType(0)) &&
791           "This must be legal!");
792    break;
793  default:
794    if (Node->getOpcode() >= ISD::BUILTIN_OP_END) {
795      // If this is a target node, legalize it by legalizing the operands then
796      // passing it through.
797      SmallVector<SDOperand, 8> Ops;
798      for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i)
799        Ops.push_back(LegalizeOp(Node->getOperand(i)));
800
801      Result = DAG.UpdateNodeOperands(Result.getValue(0), &Ops[0], Ops.size());
802
803      for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
804        AddLegalizedOperand(Op.getValue(i), Result.getValue(i));
805      return Result.getValue(Op.ResNo);
806    }
807    // Otherwise this is an unhandled builtin node.  splat.
808#ifndef NDEBUG
809    cerr << "NODE: "; Node->dump(&DAG); cerr << "\n";
810#endif
811    assert(0 && "Do not know how to legalize this operator!");
812    abort();
813  case ISD::GLOBAL_OFFSET_TABLE:
814  case ISD::GlobalAddress:
815  case ISD::GlobalTLSAddress:
816  case ISD::ExternalSymbol:
817  case ISD::ConstantPool:
818  case ISD::JumpTable: // Nothing to do.
819    switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
820    default: assert(0 && "This action is not supported yet!");
821    case TargetLowering::Custom:
822      Tmp1 = TLI.LowerOperation(Op, DAG);
823      if (Tmp1.Val) Result = Tmp1;
824      // FALLTHROUGH if the target doesn't want to lower this op after all.
825    case TargetLowering::Legal:
826      break;
827    }
828    break;
829  case ISD::FRAMEADDR:
830  case ISD::RETURNADDR:
831    // The only option for these nodes is to custom lower them.  If the target
832    // does not custom lower them, then return zero.
833    Tmp1 = TLI.LowerOperation(Op, DAG);
834    if (Tmp1.Val)
835      Result = Tmp1;
836    else
837      Result = DAG.getConstant(0, TLI.getPointerTy());
838    break;
839  case ISD::FRAME_TO_ARGS_OFFSET: {
840    MVT::ValueType VT = Node->getValueType(0);
841    switch (TLI.getOperationAction(Node->getOpcode(), VT)) {
842    default: assert(0 && "This action is not supported yet!");
843    case TargetLowering::Custom:
844      Result = TLI.LowerOperation(Op, DAG);
845      if (Result.Val) break;
846      // Fall Thru
847    case TargetLowering::Legal:
848      Result = DAG.getConstant(0, VT);
849      break;
850    }
851    }
852    break;
853  case ISD::EXCEPTIONADDR: {
854    Tmp1 = LegalizeOp(Node->getOperand(0));
855    MVT::ValueType VT = Node->getValueType(0);
856    switch (TLI.getOperationAction(Node->getOpcode(), VT)) {
857    default: assert(0 && "This action is not supported yet!");
858    case TargetLowering::Expand: {
859        unsigned Reg = TLI.getExceptionAddressRegister();
860        Result = DAG.getCopyFromReg(Tmp1, Reg, VT).getValue(Op.ResNo);
861      }
862      break;
863    case TargetLowering::Custom:
864      Result = TLI.LowerOperation(Op, DAG);
865      if (Result.Val) break;
866      // Fall Thru
867    case TargetLowering::Legal: {
868      SDOperand Ops[] = { DAG.getConstant(0, VT), Tmp1 };
869      Result = DAG.getNode(ISD::MERGE_VALUES, DAG.getVTList(VT, MVT::Other),
870                           Ops, 2).getValue(Op.ResNo);
871      break;
872    }
873    }
874    }
875    break;
876  case ISD::EHSELECTION: {
877    Tmp1 = LegalizeOp(Node->getOperand(0));
878    Tmp2 = LegalizeOp(Node->getOperand(1));
879    MVT::ValueType VT = Node->getValueType(0);
880    switch (TLI.getOperationAction(Node->getOpcode(), VT)) {
881    default: assert(0 && "This action is not supported yet!");
882    case TargetLowering::Expand: {
883        unsigned Reg = TLI.getExceptionSelectorRegister();
884        Result = DAG.getCopyFromReg(Tmp2, Reg, VT).getValue(Op.ResNo);
885      }
886      break;
887    case TargetLowering::Custom:
888      Result = TLI.LowerOperation(Op, DAG);
889      if (Result.Val) break;
890      // Fall Thru
891    case TargetLowering::Legal: {
892      SDOperand Ops[] = { DAG.getConstant(0, VT), Tmp2 };
893      Result = DAG.getNode(ISD::MERGE_VALUES, DAG.getVTList(VT, MVT::Other),
894                           Ops, 2).getValue(Op.ResNo);
895      break;
896    }
897    }
898    }
899    break;
900  case ISD::EH_RETURN: {
901    MVT::ValueType VT = Node->getValueType(0);
902    // The only "good" option for this node is to custom lower it.
903    switch (TLI.getOperationAction(Node->getOpcode(), VT)) {
904    default: assert(0 && "This action is not supported at all!");
905    case TargetLowering::Custom:
906      Result = TLI.LowerOperation(Op, DAG);
907      if (Result.Val) break;
908      // Fall Thru
909    case TargetLowering::Legal:
910      // Target does not know, how to lower this, lower to noop
911      Result = LegalizeOp(Node->getOperand(0));
912      break;
913    }
914    }
915    break;
916  case ISD::AssertSext:
917  case ISD::AssertZext:
918    Tmp1 = LegalizeOp(Node->getOperand(0));
919    Result = DAG.UpdateNodeOperands(Result, Tmp1, Node->getOperand(1));
920    break;
921  case ISD::MERGE_VALUES:
922    // Legalize eliminates MERGE_VALUES nodes.
923    Result = Node->getOperand(Op.ResNo);
924    break;
925  case ISD::CopyFromReg:
926    Tmp1 = LegalizeOp(Node->getOperand(0));
927    Result = Op.getValue(0);
928    if (Node->getNumValues() == 2) {
929      Result = DAG.UpdateNodeOperands(Result, Tmp1, Node->getOperand(1));
930    } else {
931      assert(Node->getNumValues() == 3 && "Invalid copyfromreg!");
932      if (Node->getNumOperands() == 3) {
933        Tmp2 = LegalizeOp(Node->getOperand(2));
934        Result = DAG.UpdateNodeOperands(Result, Tmp1, Node->getOperand(1),Tmp2);
935      } else {
936        Result = DAG.UpdateNodeOperands(Result, Tmp1, Node->getOperand(1));
937      }
938      AddLegalizedOperand(Op.getValue(2), Result.getValue(2));
939    }
940    // Since CopyFromReg produces two values, make sure to remember that we
941    // legalized both of them.
942    AddLegalizedOperand(Op.getValue(0), Result);
943    AddLegalizedOperand(Op.getValue(1), Result.getValue(1));
944    return Result.getValue(Op.ResNo);
945  case ISD::UNDEF: {
946    MVT::ValueType VT = Op.getValueType();
947    switch (TLI.getOperationAction(ISD::UNDEF, VT)) {
948    default: assert(0 && "This action is not supported yet!");
949    case TargetLowering::Expand:
950      if (MVT::isInteger(VT))
951        Result = DAG.getConstant(0, VT);
952      else if (MVT::isFloatingPoint(VT))
953        Result = DAG.getConstantFP(APFloat(APInt(MVT::getSizeInBits(VT), 0)),
954                                   VT);
955      else
956        assert(0 && "Unknown value type!");
957      break;
958    case TargetLowering::Legal:
959      break;
960    }
961    break;
962  }
963
964  case ISD::INTRINSIC_W_CHAIN:
965  case ISD::INTRINSIC_WO_CHAIN:
966  case ISD::INTRINSIC_VOID: {
967    SmallVector<SDOperand, 8> Ops;
968    for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i)
969      Ops.push_back(LegalizeOp(Node->getOperand(i)));
970    Result = DAG.UpdateNodeOperands(Result, &Ops[0], Ops.size());
971
972    // Allow the target to custom lower its intrinsics if it wants to.
973    if (TLI.getOperationAction(Node->getOpcode(), MVT::Other) ==
974        TargetLowering::Custom) {
975      Tmp3 = TLI.LowerOperation(Result, DAG);
976      if (Tmp3.Val) Result = Tmp3;
977    }
978
979    if (Result.Val->getNumValues() == 1) break;
980
981    // Must have return value and chain result.
982    assert(Result.Val->getNumValues() == 2 &&
983           "Cannot return more than two values!");
984
985    // Since loads produce two values, make sure to remember that we
986    // legalized both of them.
987    AddLegalizedOperand(SDOperand(Node, 0), Result.getValue(0));
988    AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
989    return Result.getValue(Op.ResNo);
990  }
991
992  case ISD::LOCATION:
993    assert(Node->getNumOperands() == 5 && "Invalid LOCATION node!");
994    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the input chain.
995
996    switch (TLI.getOperationAction(ISD::LOCATION, MVT::Other)) {
997    case TargetLowering::Promote:
998    default: assert(0 && "This action is not supported yet!");
999    case TargetLowering::Expand: {
1000      MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
1001      bool useDEBUG_LOC = TLI.isOperationLegal(ISD::DEBUG_LOC, MVT::Other);
1002      bool useLABEL = TLI.isOperationLegal(ISD::LABEL, MVT::Other);
1003
1004      if (MMI && (useDEBUG_LOC || useLABEL)) {
1005        const std::string &FName =
1006          cast<StringSDNode>(Node->getOperand(3))->getValue();
1007        const std::string &DirName =
1008          cast<StringSDNode>(Node->getOperand(4))->getValue();
1009        unsigned SrcFile = MMI->RecordSource(DirName, FName);
1010
1011        SmallVector<SDOperand, 8> Ops;
1012        Ops.push_back(Tmp1);  // chain
1013        SDOperand LineOp = Node->getOperand(1);
1014        SDOperand ColOp = Node->getOperand(2);
1015
1016        if (useDEBUG_LOC) {
1017          Ops.push_back(LineOp);  // line #
1018          Ops.push_back(ColOp);  // col #
1019          Ops.push_back(DAG.getConstant(SrcFile, MVT::i32));  // source file id
1020          Result = DAG.getNode(ISD::DEBUG_LOC, MVT::Other, &Ops[0], Ops.size());
1021        } else {
1022          unsigned Line = cast<ConstantSDNode>(LineOp)->getValue();
1023          unsigned Col = cast<ConstantSDNode>(ColOp)->getValue();
1024          unsigned ID = MMI->RecordLabel(Line, Col, SrcFile);
1025          Ops.push_back(DAG.getConstant(ID, MVT::i32));
1026          Result = DAG.getNode(ISD::LABEL, MVT::Other,&Ops[0],Ops.size());
1027        }
1028      } else {
1029        Result = Tmp1;  // chain
1030      }
1031      break;
1032    }
1033    case TargetLowering::Legal:
1034      if (Tmp1 != Node->getOperand(0) ||
1035          getTypeAction(Node->getOperand(1).getValueType()) == Promote) {
1036        SmallVector<SDOperand, 8> Ops;
1037        Ops.push_back(Tmp1);
1038        if (getTypeAction(Node->getOperand(1).getValueType()) == Legal) {
1039          Ops.push_back(Node->getOperand(1));  // line # must be legal.
1040          Ops.push_back(Node->getOperand(2));  // col # must be legal.
1041        } else {
1042          // Otherwise promote them.
1043          Ops.push_back(PromoteOp(Node->getOperand(1)));
1044          Ops.push_back(PromoteOp(Node->getOperand(2)));
1045        }
1046        Ops.push_back(Node->getOperand(3));  // filename must be legal.
1047        Ops.push_back(Node->getOperand(4));  // working dir # must be legal.
1048        Result = DAG.UpdateNodeOperands(Result, &Ops[0], Ops.size());
1049      }
1050      break;
1051    }
1052    break;
1053
1054  case ISD::DEBUG_LOC:
1055    assert(Node->getNumOperands() == 4 && "Invalid DEBUG_LOC node!");
1056    switch (TLI.getOperationAction(ISD::DEBUG_LOC, MVT::Other)) {
1057    default: assert(0 && "This action is not supported yet!");
1058    case TargetLowering::Legal:
1059      Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1060      Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the line #.
1061      Tmp3 = LegalizeOp(Node->getOperand(2));  // Legalize the col #.
1062      Tmp4 = LegalizeOp(Node->getOperand(3));  // Legalize the source file id.
1063      Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3, Tmp4);
1064      break;
1065    }
1066    break;
1067
1068  case ISD::LABEL:
1069    assert(Node->getNumOperands() == 2 && "Invalid LABEL node!");
1070    switch (TLI.getOperationAction(ISD::LABEL, MVT::Other)) {
1071    default: assert(0 && "This action is not supported yet!");
1072    case TargetLowering::Legal:
1073      Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1074      Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the label id.
1075      Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
1076      break;
1077    case TargetLowering::Expand:
1078      Result = LegalizeOp(Node->getOperand(0));
1079      break;
1080    }
1081    break;
1082
1083  case ISD::Constant: {
1084    ConstantSDNode *CN = cast<ConstantSDNode>(Node);
1085    unsigned opAction =
1086      TLI.getOperationAction(ISD::Constant, CN->getValueType(0));
1087
1088    // We know we don't need to expand constants here, constants only have one
1089    // value and we check that it is fine above.
1090
1091    if (opAction == TargetLowering::Custom) {
1092      Tmp1 = TLI.LowerOperation(Result, DAG);
1093      if (Tmp1.Val)
1094        Result = Tmp1;
1095    }
1096    break;
1097  }
1098  case ISD::ConstantFP: {
1099    // Spill FP immediates to the constant pool if the target cannot directly
1100    // codegen them.  Targets often have some immediate values that can be
1101    // efficiently generated into an FP register without a load.  We explicitly
1102    // leave these constants as ConstantFP nodes for the target to deal with.
1103    ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Node);
1104
1105    // Check to see if this FP immediate is already legal.
1106    bool isLegal = false;
1107    for (TargetLowering::legal_fpimm_iterator I = TLI.legal_fpimm_begin(),
1108           E = TLI.legal_fpimm_end(); I != E; ++I)
1109      if (CFP->isExactlyValue(*I)) {
1110        isLegal = true;
1111        break;
1112      }
1113
1114    // If this is a legal constant, turn it into a TargetConstantFP node.
1115    if (isLegal) {
1116      Result = DAG.getTargetConstantFP(CFP->getValueAPF(),
1117                                       CFP->getValueType(0));
1118      break;
1119    }
1120
1121    switch (TLI.getOperationAction(ISD::ConstantFP, CFP->getValueType(0))) {
1122    default: assert(0 && "This action is not supported yet!");
1123    case TargetLowering::Custom:
1124      Tmp3 = TLI.LowerOperation(Result, DAG);
1125      if (Tmp3.Val) {
1126        Result = Tmp3;
1127        break;
1128      }
1129      // FALLTHROUGH
1130    case TargetLowering::Expand:
1131      Result = ExpandConstantFP(CFP, true, DAG, TLI);
1132    }
1133    break;
1134  }
1135  case ISD::TokenFactor:
1136    if (Node->getNumOperands() == 2) {
1137      Tmp1 = LegalizeOp(Node->getOperand(0));
1138      Tmp2 = LegalizeOp(Node->getOperand(1));
1139      Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
1140    } else if (Node->getNumOperands() == 3) {
1141      Tmp1 = LegalizeOp(Node->getOperand(0));
1142      Tmp2 = LegalizeOp(Node->getOperand(1));
1143      Tmp3 = LegalizeOp(Node->getOperand(2));
1144      Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3);
1145    } else {
1146      SmallVector<SDOperand, 8> Ops;
1147      // Legalize the operands.
1148      for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i)
1149        Ops.push_back(LegalizeOp(Node->getOperand(i)));
1150      Result = DAG.UpdateNodeOperands(Result, &Ops[0], Ops.size());
1151    }
1152    break;
1153
1154  case ISD::FORMAL_ARGUMENTS:
1155  case ISD::CALL:
1156    // The only option for this is to custom lower it.
1157    Tmp3 = TLI.LowerOperation(Result.getValue(0), DAG);
1158    assert(Tmp3.Val && "Target didn't custom lower this node!");
1159
1160    // The number of incoming and outgoing values should match; unless the final
1161    // outgoing value is a flag.
1162    assert((Tmp3.Val->getNumValues() == Result.Val->getNumValues() ||
1163            (Tmp3.Val->getNumValues() == Result.Val->getNumValues() + 1 &&
1164             Tmp3.Val->getValueType(Tmp3.Val->getNumValues() - 1) ==
1165               MVT::Flag)) &&
1166           "Lowering call/formal_arguments produced unexpected # results!");
1167
1168    // Since CALL/FORMAL_ARGUMENTS nodes produce multiple values, make sure to
1169    // remember that we legalized all of them, so it doesn't get relegalized.
1170    for (unsigned i = 0, e = Tmp3.Val->getNumValues(); i != e; ++i) {
1171      if (Tmp3.Val->getValueType(i) == MVT::Flag)
1172        continue;
1173      Tmp1 = LegalizeOp(Tmp3.getValue(i));
1174      if (Op.ResNo == i)
1175        Tmp2 = Tmp1;
1176      AddLegalizedOperand(SDOperand(Node, i), Tmp1);
1177    }
1178    return Tmp2;
1179   case ISD::EXTRACT_SUBREG: {
1180      Tmp1 = LegalizeOp(Node->getOperand(0));
1181      ConstantSDNode *idx = dyn_cast<ConstantSDNode>(Node->getOperand(1));
1182      assert(idx && "Operand must be a constant");
1183      Tmp2 = DAG.getTargetConstant(idx->getValue(), idx->getValueType(0));
1184      Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
1185    }
1186    break;
1187  case ISD::INSERT_SUBREG: {
1188      Tmp1 = LegalizeOp(Node->getOperand(0));
1189      Tmp2 = LegalizeOp(Node->getOperand(1));
1190      ConstantSDNode *idx = dyn_cast<ConstantSDNode>(Node->getOperand(2));
1191      assert(idx && "Operand must be a constant");
1192      Tmp3 = DAG.getTargetConstant(idx->getValue(), idx->getValueType(0));
1193      Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3);
1194    }
1195    break;
1196  case ISD::BUILD_VECTOR:
1197    switch (TLI.getOperationAction(ISD::BUILD_VECTOR, Node->getValueType(0))) {
1198    default: assert(0 && "This action is not supported yet!");
1199    case TargetLowering::Custom:
1200      Tmp3 = TLI.LowerOperation(Result, DAG);
1201      if (Tmp3.Val) {
1202        Result = Tmp3;
1203        break;
1204      }
1205      // FALLTHROUGH
1206    case TargetLowering::Expand:
1207      Result = ExpandBUILD_VECTOR(Result.Val);
1208      break;
1209    }
1210    break;
1211  case ISD::INSERT_VECTOR_ELT:
1212    Tmp1 = LegalizeOp(Node->getOperand(0));  // InVec
1213    Tmp2 = LegalizeOp(Node->getOperand(1));  // InVal
1214    Tmp3 = LegalizeOp(Node->getOperand(2));  // InEltNo
1215    Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3);
1216
1217    switch (TLI.getOperationAction(ISD::INSERT_VECTOR_ELT,
1218                                   Node->getValueType(0))) {
1219    default: assert(0 && "This action is not supported yet!");
1220    case TargetLowering::Legal:
1221      break;
1222    case TargetLowering::Custom:
1223      Tmp3 = TLI.LowerOperation(Result, DAG);
1224      if (Tmp3.Val) {
1225        Result = Tmp3;
1226        break;
1227      }
1228      // FALLTHROUGH
1229    case TargetLowering::Expand: {
1230      // If the insert index is a constant, codegen this as a scalar_to_vector,
1231      // then a shuffle that inserts it into the right position in the vector.
1232      if (ConstantSDNode *InsertPos = dyn_cast<ConstantSDNode>(Tmp3)) {
1233        SDOperand ScVec = DAG.getNode(ISD::SCALAR_TO_VECTOR,
1234                                      Tmp1.getValueType(), Tmp2);
1235
1236        unsigned NumElts = MVT::getVectorNumElements(Tmp1.getValueType());
1237        MVT::ValueType ShufMaskVT = MVT::getIntVectorWithNumElements(NumElts);
1238        MVT::ValueType ShufMaskEltVT = MVT::getVectorElementType(ShufMaskVT);
1239
1240        // We generate a shuffle of InVec and ScVec, so the shuffle mask should
1241        // be 0,1,2,3,4,5... with the appropriate element replaced with elt 0 of
1242        // the RHS.
1243        SmallVector<SDOperand, 8> ShufOps;
1244        for (unsigned i = 0; i != NumElts; ++i) {
1245          if (i != InsertPos->getValue())
1246            ShufOps.push_back(DAG.getConstant(i, ShufMaskEltVT));
1247          else
1248            ShufOps.push_back(DAG.getConstant(NumElts, ShufMaskEltVT));
1249        }
1250        SDOperand ShufMask = DAG.getNode(ISD::BUILD_VECTOR, ShufMaskVT,
1251                                         &ShufOps[0], ShufOps.size());
1252
1253        Result = DAG.getNode(ISD::VECTOR_SHUFFLE, Tmp1.getValueType(),
1254                             Tmp1, ScVec, ShufMask);
1255        Result = LegalizeOp(Result);
1256        break;
1257      }
1258
1259      // If the target doesn't support this, we have to spill the input vector
1260      // to a temporary stack slot, update the element, then reload it.  This is
1261      // badness.  We could also load the value into a vector register (either
1262      // with a "move to register" or "extload into register" instruction, then
1263      // permute it into place, if the idx is a constant and if the idx is
1264      // supported by the target.
1265      MVT::ValueType VT    = Tmp1.getValueType();
1266      MVT::ValueType EltVT = Tmp2.getValueType();
1267      MVT::ValueType IdxVT = Tmp3.getValueType();
1268      MVT::ValueType PtrVT = TLI.getPointerTy();
1269      SDOperand StackPtr = DAG.CreateStackTemporary(VT);
1270      // Store the vector.
1271      SDOperand Ch = DAG.getStore(DAG.getEntryNode(), Tmp1, StackPtr, NULL, 0);
1272
1273      // Truncate or zero extend offset to target pointer type.
1274      unsigned CastOpc = (IdxVT > PtrVT) ? ISD::TRUNCATE : ISD::ZERO_EXTEND;
1275      Tmp3 = DAG.getNode(CastOpc, PtrVT, Tmp3);
1276      // Add the offset to the index.
1277      unsigned EltSize = MVT::getSizeInBits(EltVT)/8;
1278      Tmp3 = DAG.getNode(ISD::MUL, IdxVT, Tmp3,DAG.getConstant(EltSize, IdxVT));
1279      SDOperand StackPtr2 = DAG.getNode(ISD::ADD, IdxVT, Tmp3, StackPtr);
1280      // Store the scalar value.
1281      Ch = DAG.getStore(Ch, Tmp2, StackPtr2, NULL, 0);
1282      // Load the updated vector.
1283      Result = DAG.getLoad(VT, Ch, StackPtr, NULL, 0);
1284      break;
1285    }
1286    }
1287    break;
1288  case ISD::SCALAR_TO_VECTOR:
1289    if (!TLI.isTypeLegal(Node->getOperand(0).getValueType())) {
1290      Result = LegalizeOp(ExpandSCALAR_TO_VECTOR(Node));
1291      break;
1292    }
1293
1294    Tmp1 = LegalizeOp(Node->getOperand(0));  // InVal
1295    Result = DAG.UpdateNodeOperands(Result, Tmp1);
1296    switch (TLI.getOperationAction(ISD::SCALAR_TO_VECTOR,
1297                                   Node->getValueType(0))) {
1298    default: assert(0 && "This action is not supported yet!");
1299    case TargetLowering::Legal:
1300      break;
1301    case TargetLowering::Custom:
1302      Tmp3 = TLI.LowerOperation(Result, DAG);
1303      if (Tmp3.Val) {
1304        Result = Tmp3;
1305        break;
1306      }
1307      // FALLTHROUGH
1308    case TargetLowering::Expand:
1309      Result = LegalizeOp(ExpandSCALAR_TO_VECTOR(Node));
1310      break;
1311    }
1312    break;
1313  case ISD::VECTOR_SHUFFLE:
1314    Tmp1 = LegalizeOp(Node->getOperand(0));   // Legalize the input vectors,
1315    Tmp2 = LegalizeOp(Node->getOperand(1));   // but not the shuffle mask.
1316    Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Node->getOperand(2));
1317
1318    // Allow targets to custom lower the SHUFFLEs they support.
1319    switch (TLI.getOperationAction(ISD::VECTOR_SHUFFLE,Result.getValueType())) {
1320    default: assert(0 && "Unknown operation action!");
1321    case TargetLowering::Legal:
1322      assert(isShuffleLegal(Result.getValueType(), Node->getOperand(2)) &&
1323             "vector shuffle should not be created if not legal!");
1324      break;
1325    case TargetLowering::Custom:
1326      Tmp3 = TLI.LowerOperation(Result, DAG);
1327      if (Tmp3.Val) {
1328        Result = Tmp3;
1329        break;
1330      }
1331      // FALLTHROUGH
1332    case TargetLowering::Expand: {
1333      MVT::ValueType VT = Node->getValueType(0);
1334      MVT::ValueType EltVT = MVT::getVectorElementType(VT);
1335      MVT::ValueType PtrVT = TLI.getPointerTy();
1336      SDOperand Mask = Node->getOperand(2);
1337      unsigned NumElems = Mask.getNumOperands();
1338      SmallVector<SDOperand,8> Ops;
1339      for (unsigned i = 0; i != NumElems; ++i) {
1340        SDOperand Arg = Mask.getOperand(i);
1341        if (Arg.getOpcode() == ISD::UNDEF) {
1342          Ops.push_back(DAG.getNode(ISD::UNDEF, EltVT));
1343        } else {
1344          assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
1345          unsigned Idx = cast<ConstantSDNode>(Arg)->getValue();
1346          if (Idx < NumElems)
1347            Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, EltVT, Tmp1,
1348                                      DAG.getConstant(Idx, PtrVT)));
1349          else
1350            Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, EltVT, Tmp2,
1351                                      DAG.getConstant(Idx - NumElems, PtrVT)));
1352        }
1353      }
1354      Result = DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
1355      break;
1356    }
1357    case TargetLowering::Promote: {
1358      // Change base type to a different vector type.
1359      MVT::ValueType OVT = Node->getValueType(0);
1360      MVT::ValueType NVT = TLI.getTypeToPromoteTo(Node->getOpcode(), OVT);
1361
1362      // Cast the two input vectors.
1363      Tmp1 = DAG.getNode(ISD::BIT_CONVERT, NVT, Tmp1);
1364      Tmp2 = DAG.getNode(ISD::BIT_CONVERT, NVT, Tmp2);
1365
1366      // Convert the shuffle mask to the right # elements.
1367      Tmp3 = SDOperand(isShuffleLegal(OVT, Node->getOperand(2)), 0);
1368      assert(Tmp3.Val && "Shuffle not legal?");
1369      Result = DAG.getNode(ISD::VECTOR_SHUFFLE, NVT, Tmp1, Tmp2, Tmp3);
1370      Result = DAG.getNode(ISD::BIT_CONVERT, OVT, Result);
1371      break;
1372    }
1373    }
1374    break;
1375
1376  case ISD::EXTRACT_VECTOR_ELT:
1377    Tmp1 = Node->getOperand(0);
1378    Tmp2 = LegalizeOp(Node->getOperand(1));
1379    Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
1380    Result = ExpandEXTRACT_VECTOR_ELT(Result);
1381    break;
1382
1383  case ISD::EXTRACT_SUBVECTOR:
1384    Tmp1 = Node->getOperand(0);
1385    Tmp2 = LegalizeOp(Node->getOperand(1));
1386    Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
1387    Result = ExpandEXTRACT_SUBVECTOR(Result);
1388    break;
1389
1390  case ISD::CALLSEQ_START: {
1391    SDNode *CallEnd = FindCallEndFromCallStart(Node);
1392
1393    // Recursively Legalize all of the inputs of the call end that do not lead
1394    // to this call start.  This ensures that any libcalls that need be inserted
1395    // are inserted *before* the CALLSEQ_START.
1396    {SmallPtrSet<SDNode*, 32> NodesLeadingTo;
1397    for (unsigned i = 0, e = CallEnd->getNumOperands(); i != e; ++i)
1398      LegalizeAllNodesNotLeadingTo(CallEnd->getOperand(i).Val, Node,
1399                                   NodesLeadingTo);
1400    }
1401
1402    // Now that we legalized all of the inputs (which may have inserted
1403    // libcalls) create the new CALLSEQ_START node.
1404    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1405
1406    // Merge in the last call, to ensure that this call start after the last
1407    // call ended.
1408    if (LastCALLSEQ_END.getOpcode() != ISD::EntryToken) {
1409      Tmp1 = DAG.getNode(ISD::TokenFactor, MVT::Other, Tmp1, LastCALLSEQ_END);
1410      Tmp1 = LegalizeOp(Tmp1);
1411    }
1412
1413    // Do not try to legalize the target-specific arguments (#1+).
1414    if (Tmp1 != Node->getOperand(0)) {
1415      SmallVector<SDOperand, 8> Ops(Node->op_begin(), Node->op_end());
1416      Ops[0] = Tmp1;
1417      Result = DAG.UpdateNodeOperands(Result, &Ops[0], Ops.size());
1418    }
1419
1420    // Remember that the CALLSEQ_START is legalized.
1421    AddLegalizedOperand(Op.getValue(0), Result);
1422    if (Node->getNumValues() == 2)    // If this has a flag result, remember it.
1423      AddLegalizedOperand(Op.getValue(1), Result.getValue(1));
1424
1425    // Now that the callseq_start and all of the non-call nodes above this call
1426    // sequence have been legalized, legalize the call itself.  During this
1427    // process, no libcalls can/will be inserted, guaranteeing that no calls
1428    // can overlap.
1429    assert(!IsLegalizingCall && "Inconsistent sequentialization of calls!");
1430    SDOperand InCallSEQ = LastCALLSEQ_END;
1431    // Note that we are selecting this call!
1432    LastCALLSEQ_END = SDOperand(CallEnd, 0);
1433    IsLegalizingCall = true;
1434
1435    // Legalize the call, starting from the CALLSEQ_END.
1436    LegalizeOp(LastCALLSEQ_END);
1437    assert(!IsLegalizingCall && "CALLSEQ_END should have cleared this!");
1438    return Result;
1439  }
1440  case ISD::CALLSEQ_END:
1441    // If the CALLSEQ_START node hasn't been legalized first, legalize it.  This
1442    // will cause this node to be legalized as well as handling libcalls right.
1443    if (LastCALLSEQ_END.Val != Node) {
1444      LegalizeOp(SDOperand(FindCallStartFromCallEnd(Node), 0));
1445      DenseMap<SDOperand, SDOperand>::iterator I = LegalizedNodes.find(Op);
1446      assert(I != LegalizedNodes.end() &&
1447             "Legalizing the call start should have legalized this node!");
1448      return I->second;
1449    }
1450
1451    // Otherwise, the call start has been legalized and everything is going
1452    // according to plan.  Just legalize ourselves normally here.
1453    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1454    // Do not try to legalize the target-specific arguments (#1+), except for
1455    // an optional flag input.
1456    if (Node->getOperand(Node->getNumOperands()-1).getValueType() != MVT::Flag){
1457      if (Tmp1 != Node->getOperand(0)) {
1458        SmallVector<SDOperand, 8> Ops(Node->op_begin(), Node->op_end());
1459        Ops[0] = Tmp1;
1460        Result = DAG.UpdateNodeOperands(Result, &Ops[0], Ops.size());
1461      }
1462    } else {
1463      Tmp2 = LegalizeOp(Node->getOperand(Node->getNumOperands()-1));
1464      if (Tmp1 != Node->getOperand(0) ||
1465          Tmp2 != Node->getOperand(Node->getNumOperands()-1)) {
1466        SmallVector<SDOperand, 8> Ops(Node->op_begin(), Node->op_end());
1467        Ops[0] = Tmp1;
1468        Ops.back() = Tmp2;
1469        Result = DAG.UpdateNodeOperands(Result, &Ops[0], Ops.size());
1470      }
1471    }
1472    assert(IsLegalizingCall && "Call sequence imbalance between start/end?");
1473    // This finishes up call legalization.
1474    IsLegalizingCall = false;
1475
1476    // If the CALLSEQ_END node has a flag, remember that we legalized it.
1477    AddLegalizedOperand(SDOperand(Node, 0), Result.getValue(0));
1478    if (Node->getNumValues() == 2)
1479      AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
1480    return Result.getValue(Op.ResNo);
1481  case ISD::DYNAMIC_STACKALLOC: {
1482    MVT::ValueType VT = Node->getValueType(0);
1483    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1484    Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the size.
1485    Tmp3 = LegalizeOp(Node->getOperand(2));  // Legalize the alignment.
1486    Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3);
1487
1488    Tmp1 = Result.getValue(0);
1489    Tmp2 = Result.getValue(1);
1490    switch (TLI.getOperationAction(Node->getOpcode(), VT)) {
1491    default: assert(0 && "This action is not supported yet!");
1492    case TargetLowering::Expand: {
1493      unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
1494      assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
1495             " not tell us which reg is the stack pointer!");
1496      SDOperand Chain = Tmp1.getOperand(0);
1497
1498      // Chain the dynamic stack allocation so that it doesn't modify the stack
1499      // pointer when other instructions are using the stack.
1500      Chain = DAG.getCALLSEQ_START(Chain,
1501                                   DAG.getConstant(0, TLI.getPointerTy()));
1502
1503      SDOperand Size  = Tmp2.getOperand(1);
1504      SDOperand SP = DAG.getCopyFromReg(Chain, SPReg, VT);
1505      Chain = SP.getValue(1);
1506      unsigned Align = cast<ConstantSDNode>(Tmp3)->getValue();
1507      unsigned StackAlign =
1508        TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
1509      if (Align > StackAlign)
1510        SP = DAG.getNode(ISD::AND, VT, SP,
1511                         DAG.getConstant(-(uint64_t)Align, VT));
1512      Tmp1 = DAG.getNode(ISD::SUB, VT, SP, Size);       // Value
1513      Chain = DAG.getCopyToReg(Chain, SPReg, Tmp1);     // Output chain
1514
1515      Tmp2 =
1516        DAG.getCALLSEQ_END(Chain,
1517                           DAG.getConstant(0, TLI.getPointerTy()),
1518                           DAG.getConstant(0, TLI.getPointerTy()),
1519                           SDOperand());
1520
1521      Tmp1 = LegalizeOp(Tmp1);
1522      Tmp2 = LegalizeOp(Tmp2);
1523      break;
1524    }
1525    case TargetLowering::Custom:
1526      Tmp3 = TLI.LowerOperation(Tmp1, DAG);
1527      if (Tmp3.Val) {
1528        Tmp1 = LegalizeOp(Tmp3);
1529        Tmp2 = LegalizeOp(Tmp3.getValue(1));
1530      }
1531      break;
1532    case TargetLowering::Legal:
1533      break;
1534    }
1535    // Since this op produce two values, make sure to remember that we
1536    // legalized both of them.
1537    AddLegalizedOperand(SDOperand(Node, 0), Tmp1);
1538    AddLegalizedOperand(SDOperand(Node, 1), Tmp2);
1539    return Op.ResNo ? Tmp2 : Tmp1;
1540  }
1541  case ISD::INLINEASM: {
1542    SmallVector<SDOperand, 8> Ops(Node->op_begin(), Node->op_end());
1543    bool Changed = false;
1544    // Legalize all of the operands of the inline asm, in case they are nodes
1545    // that need to be expanded or something.  Note we skip the asm string and
1546    // all of the TargetConstant flags.
1547    SDOperand Op = LegalizeOp(Ops[0]);
1548    Changed = Op != Ops[0];
1549    Ops[0] = Op;
1550
1551    bool HasInFlag = Ops.back().getValueType() == MVT::Flag;
1552    for (unsigned i = 2, e = Ops.size()-HasInFlag; i < e; ) {
1553      unsigned NumVals = cast<ConstantSDNode>(Ops[i])->getValue() >> 3;
1554      for (++i; NumVals; ++i, --NumVals) {
1555        SDOperand Op = LegalizeOp(Ops[i]);
1556        if (Op != Ops[i]) {
1557          Changed = true;
1558          Ops[i] = Op;
1559        }
1560      }
1561    }
1562
1563    if (HasInFlag) {
1564      Op = LegalizeOp(Ops.back());
1565      Changed |= Op != Ops.back();
1566      Ops.back() = Op;
1567    }
1568
1569    if (Changed)
1570      Result = DAG.UpdateNodeOperands(Result, &Ops[0], Ops.size());
1571
1572    // INLINE asm returns a chain and flag, make sure to add both to the map.
1573    AddLegalizedOperand(SDOperand(Node, 0), Result.getValue(0));
1574    AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
1575    return Result.getValue(Op.ResNo);
1576  }
1577  case ISD::BR:
1578    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1579    // Ensure that libcalls are emitted before a branch.
1580    Tmp1 = DAG.getNode(ISD::TokenFactor, MVT::Other, Tmp1, LastCALLSEQ_END);
1581    Tmp1 = LegalizeOp(Tmp1);
1582    LastCALLSEQ_END = DAG.getEntryNode();
1583
1584    Result = DAG.UpdateNodeOperands(Result, Tmp1, Node->getOperand(1));
1585    break;
1586  case ISD::BRIND:
1587    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1588    // Ensure that libcalls are emitted before a branch.
1589    Tmp1 = DAG.getNode(ISD::TokenFactor, MVT::Other, Tmp1, LastCALLSEQ_END);
1590    Tmp1 = LegalizeOp(Tmp1);
1591    LastCALLSEQ_END = DAG.getEntryNode();
1592
1593    switch (getTypeAction(Node->getOperand(1).getValueType())) {
1594    default: assert(0 && "Indirect target must be legal type (pointer)!");
1595    case Legal:
1596      Tmp2 = LegalizeOp(Node->getOperand(1)); // Legalize the condition.
1597      break;
1598    }
1599    Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
1600    break;
1601  case ISD::BR_JT:
1602    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1603    // Ensure that libcalls are emitted before a branch.
1604    Tmp1 = DAG.getNode(ISD::TokenFactor, MVT::Other, Tmp1, LastCALLSEQ_END);
1605    Tmp1 = LegalizeOp(Tmp1);
1606    LastCALLSEQ_END = DAG.getEntryNode();
1607
1608    Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the jumptable node.
1609    Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Node->getOperand(2));
1610
1611    switch (TLI.getOperationAction(ISD::BR_JT, MVT::Other)) {
1612    default: assert(0 && "This action is not supported yet!");
1613    case TargetLowering::Legal: break;
1614    case TargetLowering::Custom:
1615      Tmp1 = TLI.LowerOperation(Result, DAG);
1616      if (Tmp1.Val) Result = Tmp1;
1617      break;
1618    case TargetLowering::Expand: {
1619      SDOperand Chain = Result.getOperand(0);
1620      SDOperand Table = Result.getOperand(1);
1621      SDOperand Index = Result.getOperand(2);
1622
1623      MVT::ValueType PTy = TLI.getPointerTy();
1624      MachineFunction &MF = DAG.getMachineFunction();
1625      unsigned EntrySize = MF.getJumpTableInfo()->getEntrySize();
1626      Index= DAG.getNode(ISD::MUL, PTy, Index, DAG.getConstant(EntrySize, PTy));
1627      SDOperand Addr = DAG.getNode(ISD::ADD, PTy, Index, Table);
1628
1629      SDOperand LD;
1630      switch (EntrySize) {
1631      default: assert(0 && "Size of jump table not supported yet."); break;
1632      case 4: LD = DAG.getLoad(MVT::i32, Chain, Addr, NULL, 0); break;
1633      case 8: LD = DAG.getLoad(MVT::i64, Chain, Addr, NULL, 0); break;
1634      }
1635
1636      Addr = LD;
1637      if (TLI.getTargetMachine().getRelocationModel() == Reloc::PIC_) {
1638        // For PIC, the sequence is:
1639        // BRIND(load(Jumptable + index) + RelocBase)
1640        // RelocBase can be JumpTable, GOT or some sort of global base.
1641        if (PTy != MVT::i32)
1642          Addr = DAG.getNode(ISD::SIGN_EXTEND, PTy, Addr);
1643        Addr = DAG.getNode(ISD::ADD, PTy, Addr,
1644                           TLI.getPICJumpTableRelocBase(Table, DAG));
1645      }
1646      Result = DAG.getNode(ISD::BRIND, MVT::Other, LD.getValue(1), Addr);
1647    }
1648    }
1649    break;
1650  case ISD::BRCOND:
1651    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1652    // Ensure that libcalls are emitted before a return.
1653    Tmp1 = DAG.getNode(ISD::TokenFactor, MVT::Other, Tmp1, LastCALLSEQ_END);
1654    Tmp1 = LegalizeOp(Tmp1);
1655    LastCALLSEQ_END = DAG.getEntryNode();
1656
1657    switch (getTypeAction(Node->getOperand(1).getValueType())) {
1658    case Expand: assert(0 && "It's impossible to expand bools");
1659    case Legal:
1660      Tmp2 = LegalizeOp(Node->getOperand(1)); // Legalize the condition.
1661      break;
1662    case Promote:
1663      Tmp2 = PromoteOp(Node->getOperand(1));  // Promote the condition.
1664
1665      // The top bits of the promoted condition are not necessarily zero, ensure
1666      // that the value is properly zero extended.
1667      if (!DAG.MaskedValueIsZero(Tmp2,
1668                                 MVT::getIntVTBitMask(Tmp2.getValueType())^1))
1669        Tmp2 = DAG.getZeroExtendInReg(Tmp2, MVT::i1);
1670      break;
1671    }
1672
1673    // Basic block destination (Op#2) is always legal.
1674    Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Node->getOperand(2));
1675
1676    switch (TLI.getOperationAction(ISD::BRCOND, MVT::Other)) {
1677    default: assert(0 && "This action is not supported yet!");
1678    case TargetLowering::Legal: break;
1679    case TargetLowering::Custom:
1680      Tmp1 = TLI.LowerOperation(Result, DAG);
1681      if (Tmp1.Val) Result = Tmp1;
1682      break;
1683    case TargetLowering::Expand:
1684      // Expand brcond's setcc into its constituent parts and create a BR_CC
1685      // Node.
1686      if (Tmp2.getOpcode() == ISD::SETCC) {
1687        Result = DAG.getNode(ISD::BR_CC, MVT::Other, Tmp1, Tmp2.getOperand(2),
1688                             Tmp2.getOperand(0), Tmp2.getOperand(1),
1689                             Node->getOperand(2));
1690      } else {
1691        Result = DAG.getNode(ISD::BR_CC, MVT::Other, Tmp1,
1692                             DAG.getCondCode(ISD::SETNE), Tmp2,
1693                             DAG.getConstant(0, Tmp2.getValueType()),
1694                             Node->getOperand(2));
1695      }
1696      break;
1697    }
1698    break;
1699  case ISD::BR_CC:
1700    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1701    // Ensure that libcalls are emitted before a branch.
1702    Tmp1 = DAG.getNode(ISD::TokenFactor, MVT::Other, Tmp1, LastCALLSEQ_END);
1703    Tmp1 = LegalizeOp(Tmp1);
1704    Tmp2 = Node->getOperand(2);              // LHS
1705    Tmp3 = Node->getOperand(3);              // RHS
1706    Tmp4 = Node->getOperand(1);              // CC
1707
1708    LegalizeSetCCOperands(Tmp2, Tmp3, Tmp4);
1709    LastCALLSEQ_END = DAG.getEntryNode();
1710
1711    // If we didn't get both a LHS and RHS back from LegalizeSetCCOperands,
1712    // the LHS is a legal SETCC itself.  In this case, we need to compare
1713    // the result against zero to select between true and false values.
1714    if (Tmp3.Val == 0) {
1715      Tmp3 = DAG.getConstant(0, Tmp2.getValueType());
1716      Tmp4 = DAG.getCondCode(ISD::SETNE);
1717    }
1718
1719    Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp4, Tmp2, Tmp3,
1720                                    Node->getOperand(4));
1721
1722    switch (TLI.getOperationAction(ISD::BR_CC, Tmp3.getValueType())) {
1723    default: assert(0 && "Unexpected action for BR_CC!");
1724    case TargetLowering::Legal: break;
1725    case TargetLowering::Custom:
1726      Tmp4 = TLI.LowerOperation(Result, DAG);
1727      if (Tmp4.Val) Result = Tmp4;
1728      break;
1729    }
1730    break;
1731  case ISD::LOAD: {
1732    LoadSDNode *LD = cast<LoadSDNode>(Node);
1733    Tmp1 = LegalizeOp(LD->getChain());   // Legalize the chain.
1734    Tmp2 = LegalizeOp(LD->getBasePtr()); // Legalize the base pointer.
1735
1736    ISD::LoadExtType ExtType = LD->getExtensionType();
1737    if (ExtType == ISD::NON_EXTLOAD) {
1738      MVT::ValueType VT = Node->getValueType(0);
1739      Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, LD->getOffset());
1740      Tmp3 = Result.getValue(0);
1741      Tmp4 = Result.getValue(1);
1742
1743      switch (TLI.getOperationAction(Node->getOpcode(), VT)) {
1744      default: assert(0 && "This action is not supported yet!");
1745      case TargetLowering::Legal:
1746        // If this is an unaligned load and the target doesn't support it,
1747        // expand it.
1748        if (!TLI.allowsUnalignedMemoryAccesses()) {
1749          unsigned ABIAlignment = TLI.getTargetData()->
1750            getABITypeAlignment(MVT::getTypeForValueType(LD->getLoadedVT()));
1751          if (LD->getAlignment() < ABIAlignment){
1752            Result = ExpandUnalignedLoad(cast<LoadSDNode>(Result.Val), DAG,
1753                                         TLI);
1754            Tmp3 = Result.getOperand(0);
1755            Tmp4 = Result.getOperand(1);
1756            Tmp3 = LegalizeOp(Tmp3);
1757            Tmp4 = LegalizeOp(Tmp4);
1758          }
1759        }
1760        break;
1761      case TargetLowering::Custom:
1762        Tmp1 = TLI.LowerOperation(Tmp3, DAG);
1763        if (Tmp1.Val) {
1764          Tmp3 = LegalizeOp(Tmp1);
1765          Tmp4 = LegalizeOp(Tmp1.getValue(1));
1766        }
1767        break;
1768      case TargetLowering::Promote: {
1769        // Only promote a load of vector type to another.
1770        assert(MVT::isVector(VT) && "Cannot promote this load!");
1771        // Change base type to a different vector type.
1772        MVT::ValueType NVT = TLI.getTypeToPromoteTo(Node->getOpcode(), VT);
1773
1774        Tmp1 = DAG.getLoad(NVT, Tmp1, Tmp2, LD->getSrcValue(),
1775                           LD->getSrcValueOffset(),
1776                           LD->isVolatile(), LD->getAlignment());
1777        Tmp3 = LegalizeOp(DAG.getNode(ISD::BIT_CONVERT, VT, Tmp1));
1778        Tmp4 = LegalizeOp(Tmp1.getValue(1));
1779        break;
1780      }
1781      }
1782      // Since loads produce two values, make sure to remember that we
1783      // legalized both of them.
1784      AddLegalizedOperand(SDOperand(Node, 0), Tmp3);
1785      AddLegalizedOperand(SDOperand(Node, 1), Tmp4);
1786      return Op.ResNo ? Tmp4 : Tmp3;
1787    } else {
1788      MVT::ValueType SrcVT = LD->getLoadedVT();
1789      switch (TLI.getLoadXAction(ExtType, SrcVT)) {
1790      default: assert(0 && "This action is not supported yet!");
1791      case TargetLowering::Promote:
1792        assert(SrcVT == MVT::i1 &&
1793               "Can only promote extending LOAD from i1 -> i8!");
1794        Result = DAG.getExtLoad(ExtType, Node->getValueType(0), Tmp1, Tmp2,
1795                                LD->getSrcValue(), LD->getSrcValueOffset(),
1796                                MVT::i8, LD->isVolatile(), LD->getAlignment());
1797        Tmp1 = Result.getValue(0);
1798        Tmp2 = Result.getValue(1);
1799      break;
1800      case TargetLowering::Custom:
1801        isCustom = true;
1802        // FALLTHROUGH
1803      case TargetLowering::Legal:
1804        Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, LD->getOffset());
1805        Tmp1 = Result.getValue(0);
1806        Tmp2 = Result.getValue(1);
1807
1808        if (isCustom) {
1809          Tmp3 = TLI.LowerOperation(Result, DAG);
1810          if (Tmp3.Val) {
1811            Tmp1 = LegalizeOp(Tmp3);
1812            Tmp2 = LegalizeOp(Tmp3.getValue(1));
1813          }
1814        } else {
1815          // If this is an unaligned load and the target doesn't support it,
1816          // expand it.
1817          if (!TLI.allowsUnalignedMemoryAccesses()) {
1818            unsigned ABIAlignment = TLI.getTargetData()->
1819              getABITypeAlignment(MVT::getTypeForValueType(LD->getLoadedVT()));
1820            if (LD->getAlignment() < ABIAlignment){
1821              Result = ExpandUnalignedLoad(cast<LoadSDNode>(Result.Val), DAG,
1822                                           TLI);
1823              Tmp1 = Result.getOperand(0);
1824              Tmp2 = Result.getOperand(1);
1825              Tmp1 = LegalizeOp(Tmp1);
1826              Tmp2 = LegalizeOp(Tmp2);
1827            }
1828          }
1829        }
1830        break;
1831      case TargetLowering::Expand:
1832        // f64 = EXTLOAD f32 should expand to LOAD, FP_EXTEND
1833        if (SrcVT == MVT::f32 && Node->getValueType(0) == MVT::f64) {
1834          SDOperand Load = DAG.getLoad(SrcVT, Tmp1, Tmp2, LD->getSrcValue(),
1835                                       LD->getSrcValueOffset(),
1836                                       LD->isVolatile(), LD->getAlignment());
1837          Result = DAG.getNode(ISD::FP_EXTEND, Node->getValueType(0), Load);
1838          Tmp1 = LegalizeOp(Result);  // Relegalize new nodes.
1839          Tmp2 = LegalizeOp(Load.getValue(1));
1840          break;
1841        }
1842        assert(ExtType != ISD::EXTLOAD &&"EXTLOAD should always be supported!");
1843        // Turn the unsupported load into an EXTLOAD followed by an explicit
1844        // zero/sign extend inreg.
1845        Result = DAG.getExtLoad(ISD::EXTLOAD, Node->getValueType(0),
1846                                Tmp1, Tmp2, LD->getSrcValue(),
1847                                LD->getSrcValueOffset(), SrcVT,
1848                                LD->isVolatile(), LD->getAlignment());
1849        SDOperand ValRes;
1850        if (ExtType == ISD::SEXTLOAD)
1851          ValRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, Result.getValueType(),
1852                               Result, DAG.getValueType(SrcVT));
1853        else
1854          ValRes = DAG.getZeroExtendInReg(Result, SrcVT);
1855        Tmp1 = LegalizeOp(ValRes);  // Relegalize new nodes.
1856        Tmp2 = LegalizeOp(Result.getValue(1));  // Relegalize new nodes.
1857        break;
1858      }
1859      // Since loads produce two values, make sure to remember that we legalized
1860      // both of them.
1861      AddLegalizedOperand(SDOperand(Node, 0), Tmp1);
1862      AddLegalizedOperand(SDOperand(Node, 1), Tmp2);
1863      return Op.ResNo ? Tmp2 : Tmp1;
1864    }
1865  }
1866  case ISD::EXTRACT_ELEMENT: {
1867    MVT::ValueType OpTy = Node->getOperand(0).getValueType();
1868    switch (getTypeAction(OpTy)) {
1869    default: assert(0 && "EXTRACT_ELEMENT action for type unimplemented!");
1870    case Legal:
1871      if (cast<ConstantSDNode>(Node->getOperand(1))->getValue()) {
1872        // 1 -> Hi
1873        Result = DAG.getNode(ISD::SRL, OpTy, Node->getOperand(0),
1874                             DAG.getConstant(MVT::getSizeInBits(OpTy)/2,
1875                                             TLI.getShiftAmountTy()));
1876        Result = DAG.getNode(ISD::TRUNCATE, Node->getValueType(0), Result);
1877      } else {
1878        // 0 -> Lo
1879        Result = DAG.getNode(ISD::TRUNCATE, Node->getValueType(0),
1880                             Node->getOperand(0));
1881      }
1882      break;
1883    case Expand:
1884      // Get both the low and high parts.
1885      ExpandOp(Node->getOperand(0), Tmp1, Tmp2);
1886      if (cast<ConstantSDNode>(Node->getOperand(1))->getValue())
1887        Result = Tmp2;  // 1 -> Hi
1888      else
1889        Result = Tmp1;  // 0 -> Lo
1890      break;
1891    }
1892    break;
1893  }
1894
1895  case ISD::CopyToReg:
1896    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1897
1898    assert(isTypeLegal(Node->getOperand(2).getValueType()) &&
1899           "Register type must be legal!");
1900    // Legalize the incoming value (must be a legal type).
1901    Tmp2 = LegalizeOp(Node->getOperand(2));
1902    if (Node->getNumValues() == 1) {
1903      Result = DAG.UpdateNodeOperands(Result, Tmp1, Node->getOperand(1), Tmp2);
1904    } else {
1905      assert(Node->getNumValues() == 2 && "Unknown CopyToReg");
1906      if (Node->getNumOperands() == 4) {
1907        Tmp3 = LegalizeOp(Node->getOperand(3));
1908        Result = DAG.UpdateNodeOperands(Result, Tmp1, Node->getOperand(1), Tmp2,
1909                                        Tmp3);
1910      } else {
1911        Result = DAG.UpdateNodeOperands(Result, Tmp1, Node->getOperand(1),Tmp2);
1912      }
1913
1914      // Since this produces two values, make sure to remember that we legalized
1915      // both of them.
1916      AddLegalizedOperand(SDOperand(Node, 0), Result.getValue(0));
1917      AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
1918      return Result;
1919    }
1920    break;
1921
1922  case ISD::RET:
1923    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1924
1925    // Ensure that libcalls are emitted before a return.
1926    Tmp1 = DAG.getNode(ISD::TokenFactor, MVT::Other, Tmp1, LastCALLSEQ_END);
1927    Tmp1 = LegalizeOp(Tmp1);
1928    LastCALLSEQ_END = DAG.getEntryNode();
1929
1930    switch (Node->getNumOperands()) {
1931    case 3:  // ret val
1932      Tmp2 = Node->getOperand(1);
1933      Tmp3 = Node->getOperand(2);  // Signness
1934      switch (getTypeAction(Tmp2.getValueType())) {
1935      case Legal:
1936        Result = DAG.UpdateNodeOperands(Result, Tmp1, LegalizeOp(Tmp2), Tmp3);
1937        break;
1938      case Expand:
1939        if (!MVT::isVector(Tmp2.getValueType())) {
1940          SDOperand Lo, Hi;
1941          ExpandOp(Tmp2, Lo, Hi);
1942
1943          // Big endian systems want the hi reg first.
1944          if (!TLI.isLittleEndian())
1945            std::swap(Lo, Hi);
1946
1947          if (Hi.Val)
1948            Result = DAG.getNode(ISD::RET, MVT::Other, Tmp1, Lo, Tmp3, Hi,Tmp3);
1949          else
1950            Result = DAG.getNode(ISD::RET, MVT::Other, Tmp1, Lo, Tmp3);
1951          Result = LegalizeOp(Result);
1952        } else {
1953          SDNode *InVal = Tmp2.Val;
1954          int InIx = Tmp2.ResNo;
1955          unsigned NumElems = MVT::getVectorNumElements(InVal->getValueType(InIx));
1956          MVT::ValueType EVT = MVT::getVectorElementType(InVal->getValueType(InIx));
1957
1958          // Figure out if there is a simple type corresponding to this Vector
1959          // type.  If so, convert to the vector type.
1960          MVT::ValueType TVT = MVT::getVectorType(EVT, NumElems);
1961          if (TLI.isTypeLegal(TVT)) {
1962            // Turn this into a return of the vector type.
1963            Tmp2 = LegalizeOp(Tmp2);
1964            Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3);
1965          } else if (NumElems == 1) {
1966            // Turn this into a return of the scalar type.
1967            Tmp2 = ScalarizeVectorOp(Tmp2);
1968            Tmp2 = LegalizeOp(Tmp2);
1969            Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3);
1970
1971            // FIXME: Returns of gcc generic vectors smaller than a legal type
1972            // should be returned in integer registers!
1973
1974            // The scalarized value type may not be legal, e.g. it might require
1975            // promotion or expansion.  Relegalize the return.
1976            Result = LegalizeOp(Result);
1977          } else {
1978            // FIXME: Returns of gcc generic vectors larger than a legal vector
1979            // type should be returned by reference!
1980            SDOperand Lo, Hi;
1981            SplitVectorOp(Tmp2, Lo, Hi);
1982            Result = DAG.getNode(ISD::RET, MVT::Other, Tmp1, Lo, Tmp3, Hi,Tmp3);
1983            Result = LegalizeOp(Result);
1984          }
1985        }
1986        break;
1987      case Promote:
1988        Tmp2 = PromoteOp(Node->getOperand(1));
1989        Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3);
1990        Result = LegalizeOp(Result);
1991        break;
1992      }
1993      break;
1994    case 1:  // ret void
1995      Result = DAG.UpdateNodeOperands(Result, Tmp1);
1996      break;
1997    default: { // ret <values>
1998      SmallVector<SDOperand, 8> NewValues;
1999      NewValues.push_back(Tmp1);
2000      for (unsigned i = 1, e = Node->getNumOperands(); i < e; i += 2)
2001        switch (getTypeAction(Node->getOperand(i).getValueType())) {
2002        case Legal:
2003          NewValues.push_back(LegalizeOp(Node->getOperand(i)));
2004          NewValues.push_back(Node->getOperand(i+1));
2005          break;
2006        case Expand: {
2007          SDOperand Lo, Hi;
2008          assert(!MVT::isExtendedVT(Node->getOperand(i).getValueType()) &&
2009                 "FIXME: TODO: implement returning non-legal vector types!");
2010          ExpandOp(Node->getOperand(i), Lo, Hi);
2011          NewValues.push_back(Lo);
2012          NewValues.push_back(Node->getOperand(i+1));
2013          if (Hi.Val) {
2014            NewValues.push_back(Hi);
2015            NewValues.push_back(Node->getOperand(i+1));
2016          }
2017          break;
2018        }
2019        case Promote:
2020          assert(0 && "Can't promote multiple return value yet!");
2021        }
2022
2023      if (NewValues.size() == Node->getNumOperands())
2024        Result = DAG.UpdateNodeOperands(Result, &NewValues[0],NewValues.size());
2025      else
2026        Result = DAG.getNode(ISD::RET, MVT::Other,
2027                             &NewValues[0], NewValues.size());
2028      break;
2029    }
2030    }
2031
2032    if (Result.getOpcode() == ISD::RET) {
2033      switch (TLI.getOperationAction(Result.getOpcode(), MVT::Other)) {
2034      default: assert(0 && "This action is not supported yet!");
2035      case TargetLowering::Legal: break;
2036      case TargetLowering::Custom:
2037        Tmp1 = TLI.LowerOperation(Result, DAG);
2038        if (Tmp1.Val) Result = Tmp1;
2039        break;
2040      }
2041    }
2042    break;
2043  case ISD::STORE: {
2044    StoreSDNode *ST = cast<StoreSDNode>(Node);
2045    Tmp1 = LegalizeOp(ST->getChain());    // Legalize the chain.
2046    Tmp2 = LegalizeOp(ST->getBasePtr());  // Legalize the pointer.
2047    int SVOffset = ST->getSrcValueOffset();
2048    unsigned Alignment = ST->getAlignment();
2049    bool isVolatile = ST->isVolatile();
2050
2051    if (!ST->isTruncatingStore()) {
2052      // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
2053      // FIXME: We shouldn't do this for TargetConstantFP's.
2054      // FIXME: move this to the DAG Combiner!  Note that we can't regress due
2055      // to phase ordering between legalized code and the dag combiner.  This
2056      // probably means that we need to integrate dag combiner and legalizer
2057      // together.
2058      // We generally can't do this one for long doubles.
2059      if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(ST->getValue())) {
2060        if (CFP->getValueType(0) == MVT::f32 &&
2061            getTypeAction(MVT::i32) == Legal) {
2062          Tmp3 = DAG.getConstant((uint32_t)CFP->getValueAPF().
2063                                          convertToAPInt().getZExtValue(),
2064                                  MVT::i32);
2065          Result = DAG.getStore(Tmp1, Tmp3, Tmp2, ST->getSrcValue(),
2066                                SVOffset, isVolatile, Alignment);
2067          break;
2068        } else if (CFP->getValueType(0) == MVT::f64) {
2069          // If this target supports 64-bit registers, do a single 64-bit store.
2070          if (getTypeAction(MVT::i64) == Legal) {
2071            Tmp3 = DAG.getConstant(CFP->getValueAPF().convertToAPInt().
2072                                     getZExtValue(), MVT::i64);
2073            Result = DAG.getStore(Tmp1, Tmp3, Tmp2, ST->getSrcValue(),
2074                                  SVOffset, isVolatile, Alignment);
2075            break;
2076          } else if (getTypeAction(MVT::i32) == Legal) {
2077            // Otherwise, if the target supports 32-bit registers, use 2 32-bit
2078            // stores.  If the target supports neither 32- nor 64-bits, this
2079            // xform is certainly not worth it.
2080            uint64_t IntVal =CFP->getValueAPF().convertToAPInt().getZExtValue();
2081            SDOperand Lo = DAG.getConstant(uint32_t(IntVal), MVT::i32);
2082            SDOperand Hi = DAG.getConstant(uint32_t(IntVal >>32), MVT::i32);
2083            if (!TLI.isLittleEndian()) std::swap(Lo, Hi);
2084
2085            Lo = DAG.getStore(Tmp1, Lo, Tmp2, ST->getSrcValue(),
2086                              SVOffset, isVolatile, Alignment);
2087            Tmp2 = DAG.getNode(ISD::ADD, Tmp2.getValueType(), Tmp2,
2088                               getIntPtrConstant(4));
2089            Hi = DAG.getStore(Tmp1, Hi, Tmp2, ST->getSrcValue(), SVOffset+4,
2090                              isVolatile, MinAlign(Alignment, 4U));
2091
2092            Result = DAG.getNode(ISD::TokenFactor, MVT::Other, Lo, Hi);
2093            break;
2094          }
2095        }
2096      }
2097
2098      switch (getTypeAction(ST->getStoredVT())) {
2099      case Legal: {
2100        Tmp3 = LegalizeOp(ST->getValue());
2101        Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp3, Tmp2,
2102                                        ST->getOffset());
2103
2104        MVT::ValueType VT = Tmp3.getValueType();
2105        switch (TLI.getOperationAction(ISD::STORE, VT)) {
2106        default: assert(0 && "This action is not supported yet!");
2107        case TargetLowering::Legal:
2108          // If this is an unaligned store and the target doesn't support it,
2109          // expand it.
2110          if (!TLI.allowsUnalignedMemoryAccesses()) {
2111            unsigned ABIAlignment = TLI.getTargetData()->
2112              getABITypeAlignment(MVT::getTypeForValueType(ST->getStoredVT()));
2113            if (ST->getAlignment() < ABIAlignment)
2114              Result = ExpandUnalignedStore(cast<StoreSDNode>(Result.Val), DAG,
2115                                            TLI);
2116          }
2117          break;
2118        case TargetLowering::Custom:
2119          Tmp1 = TLI.LowerOperation(Result, DAG);
2120          if (Tmp1.Val) Result = Tmp1;
2121          break;
2122        case TargetLowering::Promote:
2123          assert(MVT::isVector(VT) && "Unknown legal promote case!");
2124          Tmp3 = DAG.getNode(ISD::BIT_CONVERT,
2125                             TLI.getTypeToPromoteTo(ISD::STORE, VT), Tmp3);
2126          Result = DAG.getStore(Tmp1, Tmp3, Tmp2,
2127                                ST->getSrcValue(), SVOffset, isVolatile,
2128                                Alignment);
2129          break;
2130        }
2131        break;
2132      }
2133      case Promote:
2134        // Truncate the value and store the result.
2135        Tmp3 = PromoteOp(ST->getValue());
2136        Result = DAG.getTruncStore(Tmp1, Tmp3, Tmp2, ST->getSrcValue(),
2137                                   SVOffset, ST->getStoredVT(),
2138                                   isVolatile, Alignment);
2139        break;
2140
2141      case Expand:
2142        unsigned IncrementSize = 0;
2143        SDOperand Lo, Hi;
2144
2145        // If this is a vector type, then we have to calculate the increment as
2146        // the product of the element size in bytes, and the number of elements
2147        // in the high half of the vector.
2148        if (MVT::isVector(ST->getValue().getValueType())) {
2149          SDNode *InVal = ST->getValue().Val;
2150          int InIx = ST->getValue().ResNo;
2151          unsigned NumElems = MVT::getVectorNumElements(InVal->getValueType(InIx));
2152          MVT::ValueType EVT = MVT::getVectorElementType(InVal->getValueType(InIx));
2153
2154          // Figure out if there is a simple type corresponding to this Vector
2155          // type.  If so, convert to the vector type.
2156          MVT::ValueType TVT = MVT::getVectorType(EVT, NumElems);
2157          if (TLI.isTypeLegal(TVT)) {
2158            // Turn this into a normal store of the vector type.
2159            Tmp3 = LegalizeOp(Node->getOperand(1));
2160            Result = DAG.getStore(Tmp1, Tmp3, Tmp2, ST->getSrcValue(),
2161                                  SVOffset, isVolatile, Alignment);
2162            Result = LegalizeOp(Result);
2163            break;
2164          } else if (NumElems == 1) {
2165            // Turn this into a normal store of the scalar type.
2166            Tmp3 = ScalarizeVectorOp(Node->getOperand(1));
2167            Result = DAG.getStore(Tmp1, Tmp3, Tmp2, ST->getSrcValue(),
2168                                  SVOffset, isVolatile, Alignment);
2169            // The scalarized value type may not be legal, e.g. it might require
2170            // promotion or expansion.  Relegalize the scalar store.
2171            Result = LegalizeOp(Result);
2172            break;
2173          } else {
2174            SplitVectorOp(Node->getOperand(1), Lo, Hi);
2175            IncrementSize = MVT::getVectorNumElements(Lo.Val->getValueType(0)) *
2176                            MVT::getSizeInBits(EVT)/8;
2177          }
2178        } else {
2179          ExpandOp(Node->getOperand(1), Lo, Hi);
2180          IncrementSize = Hi.Val ? MVT::getSizeInBits(Hi.getValueType())/8 : 0;
2181
2182          if (!TLI.isLittleEndian())
2183            std::swap(Lo, Hi);
2184        }
2185
2186        Lo = DAG.getStore(Tmp1, Lo, Tmp2, ST->getSrcValue(),
2187                          SVOffset, isVolatile, Alignment);
2188
2189        if (Hi.Val == NULL) {
2190          // Must be int <-> float one-to-one expansion.
2191          Result = Lo;
2192          break;
2193        }
2194
2195        Tmp2 = DAG.getNode(ISD::ADD, Tmp2.getValueType(), Tmp2,
2196                           getIntPtrConstant(IncrementSize));
2197        assert(isTypeLegal(Tmp2.getValueType()) &&
2198               "Pointers must be legal!");
2199        SVOffset += IncrementSize;
2200        Alignment = MinAlign(Alignment, IncrementSize);
2201        Hi = DAG.getStore(Tmp1, Hi, Tmp2, ST->getSrcValue(),
2202                          SVOffset, isVolatile, Alignment);
2203        Result = DAG.getNode(ISD::TokenFactor, MVT::Other, Lo, Hi);
2204        break;
2205      }
2206    } else {
2207      // Truncating store
2208      assert(isTypeLegal(ST->getValue().getValueType()) &&
2209             "Cannot handle illegal TRUNCSTORE yet!");
2210      Tmp3 = LegalizeOp(ST->getValue());
2211
2212      // The only promote case we handle is TRUNCSTORE:i1 X into
2213      //   -> TRUNCSTORE:i8 (and X, 1)
2214      if (ST->getStoredVT() == MVT::i1 &&
2215          TLI.getStoreXAction(MVT::i1) == TargetLowering::Promote) {
2216        // Promote the bool to a mask then store.
2217        Tmp3 = DAG.getNode(ISD::AND, Tmp3.getValueType(), Tmp3,
2218                           DAG.getConstant(1, Tmp3.getValueType()));
2219        Result = DAG.getTruncStore(Tmp1, Tmp3, Tmp2, ST->getSrcValue(),
2220                                   SVOffset, MVT::i8,
2221                                   isVolatile, Alignment);
2222      } else if (Tmp1 != ST->getChain() || Tmp3 != ST->getValue() ||
2223                 Tmp2 != ST->getBasePtr()) {
2224        Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp3, Tmp2,
2225                                        ST->getOffset());
2226      }
2227
2228      MVT::ValueType StVT = cast<StoreSDNode>(Result.Val)->getStoredVT();
2229      switch (TLI.getStoreXAction(StVT)) {
2230      default: assert(0 && "This action is not supported yet!");
2231      case TargetLowering::Legal:
2232        // If this is an unaligned store and the target doesn't support it,
2233        // expand it.
2234        if (!TLI.allowsUnalignedMemoryAccesses()) {
2235          unsigned ABIAlignment = TLI.getTargetData()->
2236            getABITypeAlignment(MVT::getTypeForValueType(ST->getStoredVT()));
2237          if (ST->getAlignment() < ABIAlignment)
2238            Result = ExpandUnalignedStore(cast<StoreSDNode>(Result.Val), DAG,
2239                                          TLI);
2240        }
2241        break;
2242      case TargetLowering::Custom:
2243        Tmp1 = TLI.LowerOperation(Result, DAG);
2244        if (Tmp1.Val) Result = Tmp1;
2245        break;
2246      }
2247    }
2248    break;
2249  }
2250  case ISD::PCMARKER:
2251    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
2252    Result = DAG.UpdateNodeOperands(Result, Tmp1, Node->getOperand(1));
2253    break;
2254  case ISD::STACKSAVE:
2255    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
2256    Result = DAG.UpdateNodeOperands(Result, Tmp1);
2257    Tmp1 = Result.getValue(0);
2258    Tmp2 = Result.getValue(1);
2259
2260    switch (TLI.getOperationAction(ISD::STACKSAVE, MVT::Other)) {
2261    default: assert(0 && "This action is not supported yet!");
2262    case TargetLowering::Legal: break;
2263    case TargetLowering::Custom:
2264      Tmp3 = TLI.LowerOperation(Result, DAG);
2265      if (Tmp3.Val) {
2266        Tmp1 = LegalizeOp(Tmp3);
2267        Tmp2 = LegalizeOp(Tmp3.getValue(1));
2268      }
2269      break;
2270    case TargetLowering::Expand:
2271      // Expand to CopyFromReg if the target set
2272      // StackPointerRegisterToSaveRestore.
2273      if (unsigned SP = TLI.getStackPointerRegisterToSaveRestore()) {
2274        Tmp1 = DAG.getCopyFromReg(Result.getOperand(0), SP,
2275                                  Node->getValueType(0));
2276        Tmp2 = Tmp1.getValue(1);
2277      } else {
2278        Tmp1 = DAG.getNode(ISD::UNDEF, Node->getValueType(0));
2279        Tmp2 = Node->getOperand(0);
2280      }
2281      break;
2282    }
2283
2284    // Since stacksave produce two values, make sure to remember that we
2285    // legalized both of them.
2286    AddLegalizedOperand(SDOperand(Node, 0), Tmp1);
2287    AddLegalizedOperand(SDOperand(Node, 1), Tmp2);
2288    return Op.ResNo ? Tmp2 : Tmp1;
2289
2290  case ISD::STACKRESTORE:
2291    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
2292    Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the pointer.
2293    Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
2294
2295    switch (TLI.getOperationAction(ISD::STACKRESTORE, MVT::Other)) {
2296    default: assert(0 && "This action is not supported yet!");
2297    case TargetLowering::Legal: break;
2298    case TargetLowering::Custom:
2299      Tmp1 = TLI.LowerOperation(Result, DAG);
2300      if (Tmp1.Val) Result = Tmp1;
2301      break;
2302    case TargetLowering::Expand:
2303      // Expand to CopyToReg if the target set
2304      // StackPointerRegisterToSaveRestore.
2305      if (unsigned SP = TLI.getStackPointerRegisterToSaveRestore()) {
2306        Result = DAG.getCopyToReg(Tmp1, SP, Tmp2);
2307      } else {
2308        Result = Tmp1;
2309      }
2310      break;
2311    }
2312    break;
2313
2314  case ISD::READCYCLECOUNTER:
2315    Tmp1 = LegalizeOp(Node->getOperand(0)); // Legalize the chain
2316    Result = DAG.UpdateNodeOperands(Result, Tmp1);
2317    switch (TLI.getOperationAction(ISD::READCYCLECOUNTER,
2318                                   Node->getValueType(0))) {
2319    default: assert(0 && "This action is not supported yet!");
2320    case TargetLowering::Legal:
2321      Tmp1 = Result.getValue(0);
2322      Tmp2 = Result.getValue(1);
2323      break;
2324    case TargetLowering::Custom:
2325      Result = TLI.LowerOperation(Result, DAG);
2326      Tmp1 = LegalizeOp(Result.getValue(0));
2327      Tmp2 = LegalizeOp(Result.getValue(1));
2328      break;
2329    }
2330
2331    // Since rdcc produce two values, make sure to remember that we legalized
2332    // both of them.
2333    AddLegalizedOperand(SDOperand(Node, 0), Tmp1);
2334    AddLegalizedOperand(SDOperand(Node, 1), Tmp2);
2335    return Result;
2336
2337  case ISD::SELECT:
2338    switch (getTypeAction(Node->getOperand(0).getValueType())) {
2339    case Expand: assert(0 && "It's impossible to expand bools");
2340    case Legal:
2341      Tmp1 = LegalizeOp(Node->getOperand(0)); // Legalize the condition.
2342      break;
2343    case Promote:
2344      Tmp1 = PromoteOp(Node->getOperand(0));  // Promote the condition.
2345      // Make sure the condition is either zero or one.
2346      if (!DAG.MaskedValueIsZero(Tmp1,
2347                                 MVT::getIntVTBitMask(Tmp1.getValueType())^1))
2348        Tmp1 = DAG.getZeroExtendInReg(Tmp1, MVT::i1);
2349      break;
2350    }
2351    Tmp2 = LegalizeOp(Node->getOperand(1));   // TrueVal
2352    Tmp3 = LegalizeOp(Node->getOperand(2));   // FalseVal
2353
2354    Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3);
2355
2356    switch (TLI.getOperationAction(ISD::SELECT, Tmp2.getValueType())) {
2357    default: assert(0 && "This action is not supported yet!");
2358    case TargetLowering::Legal: break;
2359    case TargetLowering::Custom: {
2360      Tmp1 = TLI.LowerOperation(Result, DAG);
2361      if (Tmp1.Val) Result = Tmp1;
2362      break;
2363    }
2364    case TargetLowering::Expand:
2365      if (Tmp1.getOpcode() == ISD::SETCC) {
2366        Result = DAG.getSelectCC(Tmp1.getOperand(0), Tmp1.getOperand(1),
2367                              Tmp2, Tmp3,
2368                              cast<CondCodeSDNode>(Tmp1.getOperand(2))->get());
2369      } else {
2370        Result = DAG.getSelectCC(Tmp1,
2371                                 DAG.getConstant(0, Tmp1.getValueType()),
2372                                 Tmp2, Tmp3, ISD::SETNE);
2373      }
2374      break;
2375    case TargetLowering::Promote: {
2376      MVT::ValueType NVT =
2377        TLI.getTypeToPromoteTo(ISD::SELECT, Tmp2.getValueType());
2378      unsigned ExtOp, TruncOp;
2379      if (MVT::isVector(Tmp2.getValueType())) {
2380        ExtOp   = ISD::BIT_CONVERT;
2381        TruncOp = ISD::BIT_CONVERT;
2382      } else if (MVT::isInteger(Tmp2.getValueType())) {
2383        ExtOp   = ISD::ANY_EXTEND;
2384        TruncOp = ISD::TRUNCATE;
2385      } else {
2386        ExtOp   = ISD::FP_EXTEND;
2387        TruncOp = ISD::FP_ROUND;
2388      }
2389      // Promote each of the values to the new type.
2390      Tmp2 = DAG.getNode(ExtOp, NVT, Tmp2);
2391      Tmp3 = DAG.getNode(ExtOp, NVT, Tmp3);
2392      // Perform the larger operation, then round down.
2393      Result = DAG.getNode(ISD::SELECT, NVT, Tmp1, Tmp2,Tmp3);
2394      Result = DAG.getNode(TruncOp, Node->getValueType(0), Result);
2395      break;
2396    }
2397    }
2398    break;
2399  case ISD::SELECT_CC: {
2400    Tmp1 = Node->getOperand(0);               // LHS
2401    Tmp2 = Node->getOperand(1);               // RHS
2402    Tmp3 = LegalizeOp(Node->getOperand(2));   // True
2403    Tmp4 = LegalizeOp(Node->getOperand(3));   // False
2404    SDOperand CC = Node->getOperand(4);
2405
2406    LegalizeSetCCOperands(Tmp1, Tmp2, CC);
2407
2408    // If we didn't get both a LHS and RHS back from LegalizeSetCCOperands,
2409    // the LHS is a legal SETCC itself.  In this case, we need to compare
2410    // the result against zero to select between true and false values.
2411    if (Tmp2.Val == 0) {
2412      Tmp2 = DAG.getConstant(0, Tmp1.getValueType());
2413      CC = DAG.getCondCode(ISD::SETNE);
2414    }
2415    Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3, Tmp4, CC);
2416
2417    // Everything is legal, see if we should expand this op or something.
2418    switch (TLI.getOperationAction(ISD::SELECT_CC, Tmp3.getValueType())) {
2419    default: assert(0 && "This action is not supported yet!");
2420    case TargetLowering::Legal: break;
2421    case TargetLowering::Custom:
2422      Tmp1 = TLI.LowerOperation(Result, DAG);
2423      if (Tmp1.Val) Result = Tmp1;
2424      break;
2425    }
2426    break;
2427  }
2428  case ISD::SETCC:
2429    Tmp1 = Node->getOperand(0);
2430    Tmp2 = Node->getOperand(1);
2431    Tmp3 = Node->getOperand(2);
2432    LegalizeSetCCOperands(Tmp1, Tmp2, Tmp3);
2433
2434    // If we had to Expand the SetCC operands into a SELECT node, then it may
2435    // not always be possible to return a true LHS & RHS.  In this case, just
2436    // return the value we legalized, returned in the LHS
2437    if (Tmp2.Val == 0) {
2438      Result = Tmp1;
2439      break;
2440    }
2441
2442    switch (TLI.getOperationAction(ISD::SETCC, Tmp1.getValueType())) {
2443    default: assert(0 && "Cannot handle this action for SETCC yet!");
2444    case TargetLowering::Custom:
2445      isCustom = true;
2446      // FALLTHROUGH.
2447    case TargetLowering::Legal:
2448      Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3);
2449      if (isCustom) {
2450        Tmp4 = TLI.LowerOperation(Result, DAG);
2451        if (Tmp4.Val) Result = Tmp4;
2452      }
2453      break;
2454    case TargetLowering::Promote: {
2455      // First step, figure out the appropriate operation to use.
2456      // Allow SETCC to not be supported for all legal data types
2457      // Mostly this targets FP
2458      MVT::ValueType NewInTy = Node->getOperand(0).getValueType();
2459      MVT::ValueType OldVT = NewInTy; OldVT = OldVT;
2460
2461      // Scan for the appropriate larger type to use.
2462      while (1) {
2463        NewInTy = (MVT::ValueType)(NewInTy+1);
2464
2465        assert(MVT::isInteger(NewInTy) == MVT::isInteger(OldVT) &&
2466               "Fell off of the edge of the integer world");
2467        assert(MVT::isFloatingPoint(NewInTy) == MVT::isFloatingPoint(OldVT) &&
2468               "Fell off of the edge of the floating point world");
2469
2470        // If the target supports SETCC of this type, use it.
2471        if (TLI.isOperationLegal(ISD::SETCC, NewInTy))
2472          break;
2473      }
2474      if (MVT::isInteger(NewInTy))
2475        assert(0 && "Cannot promote Legal Integer SETCC yet");
2476      else {
2477        Tmp1 = DAG.getNode(ISD::FP_EXTEND, NewInTy, Tmp1);
2478        Tmp2 = DAG.getNode(ISD::FP_EXTEND, NewInTy, Tmp2);
2479      }
2480      Tmp1 = LegalizeOp(Tmp1);
2481      Tmp2 = LegalizeOp(Tmp2);
2482      Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3);
2483      Result = LegalizeOp(Result);
2484      break;
2485    }
2486    case TargetLowering::Expand:
2487      // Expand a setcc node into a select_cc of the same condition, lhs, and
2488      // rhs that selects between const 1 (true) and const 0 (false).
2489      MVT::ValueType VT = Node->getValueType(0);
2490      Result = DAG.getNode(ISD::SELECT_CC, VT, Tmp1, Tmp2,
2491                           DAG.getConstant(1, VT), DAG.getConstant(0, VT),
2492                           Tmp3);
2493      break;
2494    }
2495    break;
2496  case ISD::MEMSET:
2497  case ISD::MEMCPY:
2498  case ISD::MEMMOVE: {
2499    Tmp1 = LegalizeOp(Node->getOperand(0));      // Chain
2500    Tmp2 = LegalizeOp(Node->getOperand(1));      // Pointer
2501
2502    if (Node->getOpcode() == ISD::MEMSET) {      // memset = ubyte
2503      switch (getTypeAction(Node->getOperand(2).getValueType())) {
2504      case Expand: assert(0 && "Cannot expand a byte!");
2505      case Legal:
2506        Tmp3 = LegalizeOp(Node->getOperand(2));
2507        break;
2508      case Promote:
2509        Tmp3 = PromoteOp(Node->getOperand(2));
2510        break;
2511      }
2512    } else {
2513      Tmp3 = LegalizeOp(Node->getOperand(2));    // memcpy/move = pointer,
2514    }
2515
2516    SDOperand Tmp4;
2517    switch (getTypeAction(Node->getOperand(3).getValueType())) {
2518    case Expand: {
2519      // Length is too big, just take the lo-part of the length.
2520      SDOperand HiPart;
2521      ExpandOp(Node->getOperand(3), Tmp4, HiPart);
2522      break;
2523    }
2524    case Legal:
2525      Tmp4 = LegalizeOp(Node->getOperand(3));
2526      break;
2527    case Promote:
2528      Tmp4 = PromoteOp(Node->getOperand(3));
2529      break;
2530    }
2531
2532    SDOperand Tmp5;
2533    switch (getTypeAction(Node->getOperand(4).getValueType())) {  // uint
2534    case Expand: assert(0 && "Cannot expand this yet!");
2535    case Legal:
2536      Tmp5 = LegalizeOp(Node->getOperand(4));
2537      break;
2538    case Promote:
2539      Tmp5 = PromoteOp(Node->getOperand(4));
2540      break;
2541    }
2542
2543    SDOperand Tmp6;
2544    switch (getTypeAction(Node->getOperand(5).getValueType())) {  // bool
2545    case Expand: assert(0 && "Cannot expand this yet!");
2546    case Legal:
2547      Tmp6 = LegalizeOp(Node->getOperand(5));
2548      break;
2549    case Promote:
2550      Tmp6 = PromoteOp(Node->getOperand(5));
2551      break;
2552    }
2553
2554    switch (TLI.getOperationAction(Node->getOpcode(), MVT::Other)) {
2555    default: assert(0 && "This action not implemented for this operation!");
2556    case TargetLowering::Custom:
2557      isCustom = true;
2558      // FALLTHROUGH
2559    case TargetLowering::Legal: {
2560      SDOperand Ops[] = { Tmp1, Tmp2, Tmp3, Tmp4, Tmp5, Tmp6 };
2561      Result = DAG.UpdateNodeOperands(Result, Ops, 6);
2562      if (isCustom) {
2563        Tmp1 = TLI.LowerOperation(Result, DAG);
2564        if (Tmp1.Val) Result = Tmp1;
2565      }
2566      break;
2567    }
2568    case TargetLowering::Expand: {
2569      // Otherwise, the target does not support this operation.  Lower the
2570      // operation to an explicit libcall as appropriate.
2571      MVT::ValueType IntPtr = TLI.getPointerTy();
2572      const Type *IntPtrTy = TLI.getTargetData()->getIntPtrType();
2573      TargetLowering::ArgListTy Args;
2574      TargetLowering::ArgListEntry Entry;
2575
2576      const char *FnName = 0;
2577      if (Node->getOpcode() == ISD::MEMSET) {
2578        Entry.Node = Tmp2; Entry.Ty = IntPtrTy;
2579        Args.push_back(Entry);
2580        // Extend the (previously legalized) ubyte argument to be an int value
2581        // for the call.
2582        if (Tmp3.getValueType() > MVT::i32)
2583          Tmp3 = DAG.getNode(ISD::TRUNCATE, MVT::i32, Tmp3);
2584        else
2585          Tmp3 = DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, Tmp3);
2586        Entry.Node = Tmp3; Entry.Ty = Type::Int32Ty; Entry.isSExt = true;
2587        Args.push_back(Entry);
2588        Entry.Node = Tmp4; Entry.Ty = IntPtrTy; Entry.isSExt = false;
2589        Args.push_back(Entry);
2590
2591        FnName = "memset";
2592      } else if (Node->getOpcode() == ISD::MEMCPY ||
2593                 Node->getOpcode() == ISD::MEMMOVE) {
2594        Entry.Ty = IntPtrTy;
2595        Entry.Node = Tmp2; Args.push_back(Entry);
2596        Entry.Node = Tmp3; Args.push_back(Entry);
2597        Entry.Node = Tmp4; Args.push_back(Entry);
2598        FnName = Node->getOpcode() == ISD::MEMMOVE ? "memmove" : "memcpy";
2599      } else {
2600        assert(0 && "Unknown op!");
2601      }
2602
2603      std::pair<SDOperand,SDOperand> CallResult =
2604        TLI.LowerCallTo(Tmp1, Type::VoidTy, false, false, CallingConv::C, false,
2605                        DAG.getExternalSymbol(FnName, IntPtr), Args, DAG);
2606      Result = CallResult.second;
2607      break;
2608    }
2609    }
2610    break;
2611  }
2612
2613  case ISD::SHL_PARTS:
2614  case ISD::SRA_PARTS:
2615  case ISD::SRL_PARTS: {
2616    SmallVector<SDOperand, 8> Ops;
2617    bool Changed = false;
2618    for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) {
2619      Ops.push_back(LegalizeOp(Node->getOperand(i)));
2620      Changed |= Ops.back() != Node->getOperand(i);
2621    }
2622    if (Changed)
2623      Result = DAG.UpdateNodeOperands(Result, &Ops[0], Ops.size());
2624
2625    switch (TLI.getOperationAction(Node->getOpcode(),
2626                                   Node->getValueType(0))) {
2627    default: assert(0 && "This action is not supported yet!");
2628    case TargetLowering::Legal: break;
2629    case TargetLowering::Custom:
2630      Tmp1 = TLI.LowerOperation(Result, DAG);
2631      if (Tmp1.Val) {
2632        SDOperand Tmp2, RetVal(0, 0);
2633        for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i) {
2634          Tmp2 = LegalizeOp(Tmp1.getValue(i));
2635          AddLegalizedOperand(SDOperand(Node, i), Tmp2);
2636          if (i == Op.ResNo)
2637            RetVal = Tmp2;
2638        }
2639        assert(RetVal.Val && "Illegal result number");
2640        return RetVal;
2641      }
2642      break;
2643    }
2644
2645    // Since these produce multiple values, make sure to remember that we
2646    // legalized all of them.
2647    for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
2648      AddLegalizedOperand(SDOperand(Node, i), Result.getValue(i));
2649    return Result.getValue(Op.ResNo);
2650  }
2651
2652    // Binary operators
2653  case ISD::ADD:
2654  case ISD::SUB:
2655  case ISD::MUL:
2656  case ISD::MULHS:
2657  case ISD::MULHU:
2658  case ISD::UDIV:
2659  case ISD::SDIV:
2660  case ISD::AND:
2661  case ISD::OR:
2662  case ISD::XOR:
2663  case ISD::SHL:
2664  case ISD::SRL:
2665  case ISD::SRA:
2666  case ISD::FADD:
2667  case ISD::FSUB:
2668  case ISD::FMUL:
2669  case ISD::FDIV:
2670  case ISD::FPOW:
2671    Tmp1 = LegalizeOp(Node->getOperand(0));   // LHS
2672    switch (getTypeAction(Node->getOperand(1).getValueType())) {
2673    case Expand: assert(0 && "Not possible");
2674    case Legal:
2675      Tmp2 = LegalizeOp(Node->getOperand(1)); // Legalize the RHS.
2676      break;
2677    case Promote:
2678      Tmp2 = PromoteOp(Node->getOperand(1));  // Promote the RHS.
2679      break;
2680    }
2681
2682    Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
2683
2684    switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
2685    default: assert(0 && "BinOp legalize operation not supported");
2686    case TargetLowering::Legal: break;
2687    case TargetLowering::Custom:
2688      Tmp1 = TLI.LowerOperation(Result, DAG);
2689      if (Tmp1.Val) Result = Tmp1;
2690      break;
2691    case TargetLowering::Expand: {
2692      MVT::ValueType VT = Op.getValueType();
2693
2694      // See if multiply or divide can be lowered using two-result operations.
2695      SDVTList VTs = DAG.getVTList(VT, VT);
2696      if (Node->getOpcode() == ISD::MUL) {
2697        // We just need the low half of the multiply; try both the signed
2698        // and unsigned forms. If the target supports both SMUL_LOHI and
2699        // UMUL_LOHI, form a preference by checking which forms of plain
2700        // MULH it supports.
2701        bool HasSMUL_LOHI = TLI.isOperationLegal(ISD::SMUL_LOHI, VT);
2702        bool HasUMUL_LOHI = TLI.isOperationLegal(ISD::UMUL_LOHI, VT);
2703        bool HasMULHS = TLI.isOperationLegal(ISD::MULHS, VT);
2704        bool HasMULHU = TLI.isOperationLegal(ISD::MULHU, VT);
2705        unsigned OpToUse = 0;
2706        if (HasSMUL_LOHI && !HasMULHS) {
2707          OpToUse = ISD::SMUL_LOHI;
2708        } else if (HasUMUL_LOHI && !HasMULHU) {
2709          OpToUse = ISD::UMUL_LOHI;
2710        } else if (HasSMUL_LOHI) {
2711          OpToUse = ISD::SMUL_LOHI;
2712        } else if (HasUMUL_LOHI) {
2713          OpToUse = ISD::UMUL_LOHI;
2714        }
2715        if (OpToUse) {
2716          Result = SDOperand(DAG.getNode(OpToUse, VTs, Tmp1, Tmp2).Val, 0);
2717          break;
2718        }
2719      }
2720      if (Node->getOpcode() == ISD::MULHS &&
2721          TLI.isOperationLegal(ISD::SMUL_LOHI, VT)) {
2722        Result = SDOperand(DAG.getNode(ISD::SMUL_LOHI, VTs, Tmp1, Tmp2).Val, 1);
2723        break;
2724      }
2725      if (Node->getOpcode() == ISD::MULHU &&
2726          TLI.isOperationLegal(ISD::UMUL_LOHI, VT)) {
2727        Result = SDOperand(DAG.getNode(ISD::UMUL_LOHI, VTs, Tmp1, Tmp2).Val, 1);
2728        break;
2729      }
2730      if (Node->getOpcode() == ISD::SDIV &&
2731          TLI.isOperationLegal(ISD::SDIVREM, VT)) {
2732        Result = SDOperand(DAG.getNode(ISD::SDIVREM, VTs, Tmp1, Tmp2).Val, 0);
2733        break;
2734      }
2735      if (Node->getOpcode() == ISD::UDIV &&
2736          TLI.isOperationLegal(ISD::UDIVREM, VT)) {
2737        Result = SDOperand(DAG.getNode(ISD::UDIVREM, VTs, Tmp1, Tmp2).Val, 0);
2738        break;
2739      }
2740
2741      // Check to see if we have a libcall for this operator.
2742      RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
2743      bool isSigned = false;
2744      switch (Node->getOpcode()) {
2745      case ISD::UDIV:
2746      case ISD::SDIV:
2747        if (VT == MVT::i32) {
2748          LC = Node->getOpcode() == ISD::UDIV
2749            ? RTLIB::UDIV_I32 : RTLIB::SDIV_I32;
2750          isSigned = Node->getOpcode() == ISD::SDIV;
2751        }
2752        break;
2753      case ISD::FPOW:
2754        LC = VT == MVT::f32 ? RTLIB::POW_F32 :
2755             VT == MVT::f64 ? RTLIB::POW_F64 :
2756             VT == MVT::f80 ? RTLIB::POW_F80 :
2757             VT == MVT::ppcf128 ? RTLIB::POW_PPCF128 :
2758             RTLIB::UNKNOWN_LIBCALL;
2759        break;
2760      default: break;
2761      }
2762      if (LC != RTLIB::UNKNOWN_LIBCALL) {
2763        SDOperand Dummy;
2764        Result = ExpandLibCall(TLI.getLibcallName(LC), Node, isSigned, Dummy);
2765        break;
2766      }
2767
2768      assert(MVT::isVector(Node->getValueType(0)) &&
2769             "Cannot expand this binary operator!");
2770      // Expand the operation into a bunch of nasty scalar code.
2771      Result = LegalizeOp(UnrollVectorOp(Op));
2772      break;
2773    }
2774    case TargetLowering::Promote: {
2775      switch (Node->getOpcode()) {
2776      default:  assert(0 && "Do not know how to promote this BinOp!");
2777      case ISD::AND:
2778      case ISD::OR:
2779      case ISD::XOR: {
2780        MVT::ValueType OVT = Node->getValueType(0);
2781        MVT::ValueType NVT = TLI.getTypeToPromoteTo(Node->getOpcode(), OVT);
2782        assert(MVT::isVector(OVT) && "Cannot promote this BinOp!");
2783        // Bit convert each of the values to the new type.
2784        Tmp1 = DAG.getNode(ISD::BIT_CONVERT, NVT, Tmp1);
2785        Tmp2 = DAG.getNode(ISD::BIT_CONVERT, NVT, Tmp2);
2786        Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1, Tmp2);
2787        // Bit convert the result back the original type.
2788        Result = DAG.getNode(ISD::BIT_CONVERT, OVT, Result);
2789        break;
2790      }
2791      }
2792    }
2793    }
2794    break;
2795
2796  case ISD::SMUL_LOHI:
2797  case ISD::UMUL_LOHI:
2798  case ISD::SDIVREM:
2799  case ISD::UDIVREM:
2800    // These nodes will only be produced by target-specific lowering, so
2801    // they shouldn't be here if they aren't legal.
2802    assert(TLI.isOperationLegal(Node->getOpcode(), Node->getValueType(0)) &&
2803           "This must be legal!");
2804
2805    Tmp1 = LegalizeOp(Node->getOperand(0));   // LHS
2806    Tmp2 = LegalizeOp(Node->getOperand(1));   // RHS
2807    Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
2808    break;
2809
2810  case ISD::FCOPYSIGN:  // FCOPYSIGN does not require LHS/RHS to match type!
2811    Tmp1 = LegalizeOp(Node->getOperand(0));   // LHS
2812    switch (getTypeAction(Node->getOperand(1).getValueType())) {
2813      case Expand: assert(0 && "Not possible");
2814      case Legal:
2815        Tmp2 = LegalizeOp(Node->getOperand(1)); // Legalize the RHS.
2816        break;
2817      case Promote:
2818        Tmp2 = PromoteOp(Node->getOperand(1));  // Promote the RHS.
2819        break;
2820    }
2821
2822    Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
2823
2824    switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
2825    default: assert(0 && "Operation not supported");
2826    case TargetLowering::Custom:
2827      Tmp1 = TLI.LowerOperation(Result, DAG);
2828      if (Tmp1.Val) Result = Tmp1;
2829      break;
2830    case TargetLowering::Legal: break;
2831    case TargetLowering::Expand: {
2832      // If this target supports fabs/fneg natively and select is cheap,
2833      // do this efficiently.
2834      if (!TLI.isSelectExpensive() &&
2835          TLI.getOperationAction(ISD::FABS, Tmp1.getValueType()) ==
2836          TargetLowering::Legal &&
2837          TLI.getOperationAction(ISD::FNEG, Tmp1.getValueType()) ==
2838          TargetLowering::Legal) {
2839        // Get the sign bit of the RHS.
2840        MVT::ValueType IVT =
2841          Tmp2.getValueType() == MVT::f32 ? MVT::i32 : MVT::i64;
2842        SDOperand SignBit = DAG.getNode(ISD::BIT_CONVERT, IVT, Tmp2);
2843        SignBit = DAG.getSetCC(TLI.getSetCCResultTy(),
2844                               SignBit, DAG.getConstant(0, IVT), ISD::SETLT);
2845        // Get the absolute value of the result.
2846        SDOperand AbsVal = DAG.getNode(ISD::FABS, Tmp1.getValueType(), Tmp1);
2847        // Select between the nabs and abs value based on the sign bit of
2848        // the input.
2849        Result = DAG.getNode(ISD::SELECT, AbsVal.getValueType(), SignBit,
2850                             DAG.getNode(ISD::FNEG, AbsVal.getValueType(),
2851                                         AbsVal),
2852                             AbsVal);
2853        Result = LegalizeOp(Result);
2854        break;
2855      }
2856
2857      // Otherwise, do bitwise ops!
2858      MVT::ValueType NVT =
2859        Node->getValueType(0) == MVT::f32 ? MVT::i32 : MVT::i64;
2860      Result = ExpandFCOPYSIGNToBitwiseOps(Node, NVT, DAG, TLI);
2861      Result = DAG.getNode(ISD::BIT_CONVERT, Node->getValueType(0), Result);
2862      Result = LegalizeOp(Result);
2863      break;
2864    }
2865    }
2866    break;
2867
2868  case ISD::ADDC:
2869  case ISD::SUBC:
2870    Tmp1 = LegalizeOp(Node->getOperand(0));
2871    Tmp2 = LegalizeOp(Node->getOperand(1));
2872    Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
2873    // Since this produces two values, make sure to remember that we legalized
2874    // both of them.
2875    AddLegalizedOperand(SDOperand(Node, 0), Result.getValue(0));
2876    AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
2877    return Result;
2878
2879  case ISD::ADDE:
2880  case ISD::SUBE:
2881    Tmp1 = LegalizeOp(Node->getOperand(0));
2882    Tmp2 = LegalizeOp(Node->getOperand(1));
2883    Tmp3 = LegalizeOp(Node->getOperand(2));
2884    Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3);
2885    // Since this produces two values, make sure to remember that we legalized
2886    // both of them.
2887    AddLegalizedOperand(SDOperand(Node, 0), Result.getValue(0));
2888    AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
2889    return Result;
2890
2891  case ISD::BUILD_PAIR: {
2892    MVT::ValueType PairTy = Node->getValueType(0);
2893    // TODO: handle the case where the Lo and Hi operands are not of legal type
2894    Tmp1 = LegalizeOp(Node->getOperand(0));   // Lo
2895    Tmp2 = LegalizeOp(Node->getOperand(1));   // Hi
2896    switch (TLI.getOperationAction(ISD::BUILD_PAIR, PairTy)) {
2897    case TargetLowering::Promote:
2898    case TargetLowering::Custom:
2899      assert(0 && "Cannot promote/custom this yet!");
2900    case TargetLowering::Legal:
2901      if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1))
2902        Result = DAG.getNode(ISD::BUILD_PAIR, PairTy, Tmp1, Tmp2);
2903      break;
2904    case TargetLowering::Expand:
2905      Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, PairTy, Tmp1);
2906      Tmp2 = DAG.getNode(ISD::ANY_EXTEND, PairTy, Tmp2);
2907      Tmp2 = DAG.getNode(ISD::SHL, PairTy, Tmp2,
2908                         DAG.getConstant(MVT::getSizeInBits(PairTy)/2,
2909                                         TLI.getShiftAmountTy()));
2910      Result = DAG.getNode(ISD::OR, PairTy, Tmp1, Tmp2);
2911      break;
2912    }
2913    break;
2914  }
2915
2916  case ISD::UREM:
2917  case ISD::SREM:
2918  case ISD::FREM:
2919    Tmp1 = LegalizeOp(Node->getOperand(0));   // LHS
2920    Tmp2 = LegalizeOp(Node->getOperand(1));   // RHS
2921
2922    switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
2923    case TargetLowering::Promote: assert(0 && "Cannot promote this yet!");
2924    case TargetLowering::Custom:
2925      isCustom = true;
2926      // FALLTHROUGH
2927    case TargetLowering::Legal:
2928      Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
2929      if (isCustom) {
2930        Tmp1 = TLI.LowerOperation(Result, DAG);
2931        if (Tmp1.Val) Result = Tmp1;
2932      }
2933      break;
2934    case TargetLowering::Expand: {
2935      unsigned DivOpc= (Node->getOpcode() == ISD::UREM) ? ISD::UDIV : ISD::SDIV;
2936      bool isSigned = DivOpc == ISD::SDIV;
2937      MVT::ValueType VT = Node->getValueType(0);
2938
2939      // See if remainder can be lowered using two-result operations.
2940      SDVTList VTs = DAG.getVTList(VT, VT);
2941      if (Node->getOpcode() == ISD::SREM &&
2942          TLI.isOperationLegal(ISD::SDIVREM, VT)) {
2943        Result = SDOperand(DAG.getNode(ISD::SDIVREM, VTs, Tmp1, Tmp2).Val, 1);
2944        break;
2945      }
2946      if (Node->getOpcode() == ISD::UREM &&
2947          TLI.isOperationLegal(ISD::UDIVREM, VT)) {
2948        Result = SDOperand(DAG.getNode(ISD::UDIVREM, VTs, Tmp1, Tmp2).Val, 1);
2949        break;
2950      }
2951
2952      if (MVT::isInteger(VT)) {
2953        if (TLI.getOperationAction(DivOpc, VT) ==
2954            TargetLowering::Legal) {
2955          // X % Y -> X-X/Y*Y
2956          Result = DAG.getNode(DivOpc, VT, Tmp1, Tmp2);
2957          Result = DAG.getNode(ISD::MUL, VT, Result, Tmp2);
2958          Result = DAG.getNode(ISD::SUB, VT, Tmp1, Result);
2959        } else if (MVT::isVector(VT)) {
2960          Result = LegalizeOp(UnrollVectorOp(Op));
2961        } else {
2962          assert(VT == MVT::i32 &&
2963                 "Cannot expand this binary operator!");
2964          RTLIB::Libcall LC = Node->getOpcode() == ISD::UREM
2965            ? RTLIB::UREM_I32 : RTLIB::SREM_I32;
2966          SDOperand Dummy;
2967          Result = ExpandLibCall(TLI.getLibcallName(LC), Node, isSigned, Dummy);
2968        }
2969      } else {
2970        assert(MVT::isFloatingPoint(VT) &&
2971               "remainder op must have integer or floating-point type");
2972        if (MVT::isVector(VT)) {
2973          Result = LegalizeOp(UnrollVectorOp(Op));
2974        } else {
2975          // Floating point mod -> fmod libcall.
2976          RTLIB::Libcall LC = VT == MVT::f32
2977            ? RTLIB::REM_F32 : RTLIB::REM_F64;
2978          SDOperand Dummy;
2979          Result = ExpandLibCall(TLI.getLibcallName(LC), Node,
2980                                 false/*sign irrelevant*/, Dummy);
2981        }
2982      }
2983      break;
2984    }
2985    }
2986    break;
2987  case ISD::VAARG: {
2988    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
2989    Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the pointer.
2990
2991    MVT::ValueType VT = Node->getValueType(0);
2992    switch (TLI.getOperationAction(Node->getOpcode(), MVT::Other)) {
2993    default: assert(0 && "This action is not supported yet!");
2994    case TargetLowering::Custom:
2995      isCustom = true;
2996      // FALLTHROUGH
2997    case TargetLowering::Legal:
2998      Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Node->getOperand(2));
2999      Result = Result.getValue(0);
3000      Tmp1 = Result.getValue(1);
3001
3002      if (isCustom) {
3003        Tmp2 = TLI.LowerOperation(Result, DAG);
3004        if (Tmp2.Val) {
3005          Result = LegalizeOp(Tmp2);
3006          Tmp1 = LegalizeOp(Tmp2.getValue(1));
3007        }
3008      }
3009      break;
3010    case TargetLowering::Expand: {
3011      SrcValueSDNode *SV = cast<SrcValueSDNode>(Node->getOperand(2));
3012      SDOperand VAList = DAG.getLoad(TLI.getPointerTy(), Tmp1, Tmp2,
3013                                     SV->getValue(), SV->getOffset());
3014      // Increment the pointer, VAList, to the next vaarg
3015      Tmp3 = DAG.getNode(ISD::ADD, TLI.getPointerTy(), VAList,
3016                         DAG.getConstant(MVT::getSizeInBits(VT)/8,
3017                                         TLI.getPointerTy()));
3018      // Store the incremented VAList to the legalized pointer
3019      Tmp3 = DAG.getStore(VAList.getValue(1), Tmp3, Tmp2, SV->getValue(),
3020                          SV->getOffset());
3021      // Load the actual argument out of the pointer VAList
3022      Result = DAG.getLoad(VT, Tmp3, VAList, NULL, 0);
3023      Tmp1 = LegalizeOp(Result.getValue(1));
3024      Result = LegalizeOp(Result);
3025      break;
3026    }
3027    }
3028    // Since VAARG produces two values, make sure to remember that we
3029    // legalized both of them.
3030    AddLegalizedOperand(SDOperand(Node, 0), Result);
3031    AddLegalizedOperand(SDOperand(Node, 1), Tmp1);
3032    return Op.ResNo ? Tmp1 : Result;
3033  }
3034
3035  case ISD::VACOPY:
3036    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
3037    Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the dest pointer.
3038    Tmp3 = LegalizeOp(Node->getOperand(2));  // Legalize the source pointer.
3039
3040    switch (TLI.getOperationAction(ISD::VACOPY, MVT::Other)) {
3041    default: assert(0 && "This action is not supported yet!");
3042    case TargetLowering::Custom:
3043      isCustom = true;
3044      // FALLTHROUGH
3045    case TargetLowering::Legal:
3046      Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3,
3047                                      Node->getOperand(3), Node->getOperand(4));
3048      if (isCustom) {
3049        Tmp1 = TLI.LowerOperation(Result, DAG);
3050        if (Tmp1.Val) Result = Tmp1;
3051      }
3052      break;
3053    case TargetLowering::Expand:
3054      // This defaults to loading a pointer from the input and storing it to the
3055      // output, returning the chain.
3056      SrcValueSDNode *SVD = cast<SrcValueSDNode>(Node->getOperand(3));
3057      SrcValueSDNode *SVS = cast<SrcValueSDNode>(Node->getOperand(4));
3058      Tmp4 = DAG.getLoad(TLI.getPointerTy(), Tmp1, Tmp3, SVD->getValue(),
3059                         SVD->getOffset());
3060      Result = DAG.getStore(Tmp4.getValue(1), Tmp4, Tmp2, SVS->getValue(),
3061                            SVS->getOffset());
3062      break;
3063    }
3064    break;
3065
3066  case ISD::VAEND:
3067    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
3068    Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the pointer.
3069
3070    switch (TLI.getOperationAction(ISD::VAEND, MVT::Other)) {
3071    default: assert(0 && "This action is not supported yet!");
3072    case TargetLowering::Custom:
3073      isCustom = true;
3074      // FALLTHROUGH
3075    case TargetLowering::Legal:
3076      Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Node->getOperand(2));
3077      if (isCustom) {
3078        Tmp1 = TLI.LowerOperation(Tmp1, DAG);
3079        if (Tmp1.Val) Result = Tmp1;
3080      }
3081      break;
3082    case TargetLowering::Expand:
3083      Result = Tmp1; // Default to a no-op, return the chain
3084      break;
3085    }
3086    break;
3087
3088  case ISD::VASTART:
3089    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
3090    Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the pointer.
3091
3092    Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Node->getOperand(2));
3093
3094    switch (TLI.getOperationAction(ISD::VASTART, MVT::Other)) {
3095    default: assert(0 && "This action is not supported yet!");
3096    case TargetLowering::Legal: break;
3097    case TargetLowering::Custom:
3098      Tmp1 = TLI.LowerOperation(Result, DAG);
3099      if (Tmp1.Val) Result = Tmp1;
3100      break;
3101    }
3102    break;
3103
3104  case ISD::ROTL:
3105  case ISD::ROTR:
3106    Tmp1 = LegalizeOp(Node->getOperand(0));   // LHS
3107    Tmp2 = LegalizeOp(Node->getOperand(1));   // RHS
3108    Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
3109    switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
3110    default:
3111      assert(0 && "ROTL/ROTR legalize operation not supported");
3112      break;
3113    case TargetLowering::Legal:
3114      break;
3115    case TargetLowering::Custom:
3116      Tmp1 = TLI.LowerOperation(Result, DAG);
3117      if (Tmp1.Val) Result = Tmp1;
3118      break;
3119    case TargetLowering::Promote:
3120      assert(0 && "Do not know how to promote ROTL/ROTR");
3121      break;
3122    case TargetLowering::Expand:
3123      assert(0 && "Do not know how to expand ROTL/ROTR");
3124      break;
3125    }
3126    break;
3127
3128  case ISD::BSWAP:
3129    Tmp1 = LegalizeOp(Node->getOperand(0));   // Op
3130    switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
3131    case TargetLowering::Custom:
3132      assert(0 && "Cannot custom legalize this yet!");
3133    case TargetLowering::Legal:
3134      Result = DAG.UpdateNodeOperands(Result, Tmp1);
3135      break;
3136    case TargetLowering::Promote: {
3137      MVT::ValueType OVT = Tmp1.getValueType();
3138      MVT::ValueType NVT = TLI.getTypeToPromoteTo(Node->getOpcode(), OVT);
3139      unsigned DiffBits = MVT::getSizeInBits(NVT) - MVT::getSizeInBits(OVT);
3140
3141      Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, NVT, Tmp1);
3142      Tmp1 = DAG.getNode(ISD::BSWAP, NVT, Tmp1);
3143      Result = DAG.getNode(ISD::SRL, NVT, Tmp1,
3144                           DAG.getConstant(DiffBits, TLI.getShiftAmountTy()));
3145      break;
3146    }
3147    case TargetLowering::Expand:
3148      Result = ExpandBSWAP(Tmp1);
3149      break;
3150    }
3151    break;
3152
3153  case ISD::CTPOP:
3154  case ISD::CTTZ:
3155  case ISD::CTLZ:
3156    Tmp1 = LegalizeOp(Node->getOperand(0));   // Op
3157    switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
3158    case TargetLowering::Custom:
3159    case TargetLowering::Legal:
3160      Result = DAG.UpdateNodeOperands(Result, Tmp1);
3161      if (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0)) ==
3162          TargetLowering::Custom) {
3163        Tmp1 = TLI.LowerOperation(Result, DAG);
3164        if (Tmp1.Val) {
3165          Result = Tmp1;
3166        }
3167      }
3168      break;
3169    case TargetLowering::Promote: {
3170      MVT::ValueType OVT = Tmp1.getValueType();
3171      MVT::ValueType NVT = TLI.getTypeToPromoteTo(Node->getOpcode(), OVT);
3172
3173      // Zero extend the argument.
3174      Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, NVT, Tmp1);
3175      // Perform the larger operation, then subtract if needed.
3176      Tmp1 = DAG.getNode(Node->getOpcode(), Node->getValueType(0), Tmp1);
3177      switch (Node->getOpcode()) {
3178      case ISD::CTPOP:
3179        Result = Tmp1;
3180        break;
3181      case ISD::CTTZ:
3182        //if Tmp1 == sizeinbits(NVT) then Tmp1 = sizeinbits(Old VT)
3183        Tmp2 = DAG.getSetCC(TLI.getSetCCResultTy(), Tmp1,
3184                            DAG.getConstant(MVT::getSizeInBits(NVT), NVT),
3185                            ISD::SETEQ);
3186        Result = DAG.getNode(ISD::SELECT, NVT, Tmp2,
3187                             DAG.getConstant(MVT::getSizeInBits(OVT),NVT), Tmp1);
3188        break;
3189      case ISD::CTLZ:
3190        // Tmp1 = Tmp1 - (sizeinbits(NVT) - sizeinbits(Old VT))
3191        Result = DAG.getNode(ISD::SUB, NVT, Tmp1,
3192                             DAG.getConstant(MVT::getSizeInBits(NVT) -
3193                                             MVT::getSizeInBits(OVT), NVT));
3194        break;
3195      }
3196      break;
3197    }
3198    case TargetLowering::Expand:
3199      Result = ExpandBitCount(Node->getOpcode(), Tmp1);
3200      break;
3201    }
3202    break;
3203
3204    // Unary operators
3205  case ISD::FABS:
3206  case ISD::FNEG:
3207  case ISD::FSQRT:
3208  case ISD::FSIN:
3209  case ISD::FCOS:
3210    Tmp1 = LegalizeOp(Node->getOperand(0));
3211    switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
3212    case TargetLowering::Promote:
3213    case TargetLowering::Custom:
3214     isCustom = true;
3215     // FALLTHROUGH
3216    case TargetLowering::Legal:
3217      Result = DAG.UpdateNodeOperands(Result, Tmp1);
3218      if (isCustom) {
3219        Tmp1 = TLI.LowerOperation(Result, DAG);
3220        if (Tmp1.Val) Result = Tmp1;
3221      }
3222      break;
3223    case TargetLowering::Expand:
3224      switch (Node->getOpcode()) {
3225      default: assert(0 && "Unreachable!");
3226      case ISD::FNEG:
3227        // Expand Y = FNEG(X) ->  Y = SUB -0.0, X
3228        Tmp2 = DAG.getConstantFP(-0.0, Node->getValueType(0));
3229        Result = DAG.getNode(ISD::FSUB, Node->getValueType(0), Tmp2, Tmp1);
3230        break;
3231      case ISD::FABS: {
3232        // Expand Y = FABS(X) -> Y = (X >u 0.0) ? X : fneg(X).
3233        MVT::ValueType VT = Node->getValueType(0);
3234        Tmp2 = DAG.getConstantFP(0.0, VT);
3235        Tmp2 = DAG.getSetCC(TLI.getSetCCResultTy(), Tmp1, Tmp2, ISD::SETUGT);
3236        Tmp3 = DAG.getNode(ISD::FNEG, VT, Tmp1);
3237        Result = DAG.getNode(ISD::SELECT, VT, Tmp2, Tmp1, Tmp3);
3238        break;
3239      }
3240      case ISD::FSQRT:
3241      case ISD::FSIN:
3242      case ISD::FCOS: {
3243        MVT::ValueType VT = Node->getValueType(0);
3244
3245        // Expand unsupported unary vector operators by unrolling them.
3246        if (MVT::isVector(VT)) {
3247          Result = LegalizeOp(UnrollVectorOp(Op));
3248          break;
3249        }
3250
3251        RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
3252        switch(Node->getOpcode()) {
3253        case ISD::FSQRT:
3254          LC = VT == MVT::f32 ? RTLIB::SQRT_F32 :
3255               VT == MVT::f64 ? RTLIB::SQRT_F64 :
3256               VT == MVT::f80 ? RTLIB::SQRT_F80 :
3257               VT == MVT::ppcf128 ? RTLIB::SQRT_PPCF128 :
3258               RTLIB::UNKNOWN_LIBCALL;
3259          break;
3260        case ISD::FSIN:
3261          LC = VT == MVT::f32 ? RTLIB::SIN_F32 : RTLIB::SIN_F64;
3262          break;
3263        case ISD::FCOS:
3264          LC = VT == MVT::f32 ? RTLIB::COS_F32 : RTLIB::COS_F64;
3265          break;
3266        default: assert(0 && "Unreachable!");
3267        }
3268        SDOperand Dummy;
3269        Result = ExpandLibCall(TLI.getLibcallName(LC), Node,
3270                               false/*sign irrelevant*/, Dummy);
3271        break;
3272      }
3273      }
3274      break;
3275    }
3276    break;
3277  case ISD::FPOWI: {
3278    MVT::ValueType VT = Node->getValueType(0);
3279
3280    // Expand unsupported unary vector operators by unrolling them.
3281    if (MVT::isVector(VT)) {
3282      Result = LegalizeOp(UnrollVectorOp(Op));
3283      break;
3284    }
3285
3286    // We always lower FPOWI into a libcall.  No target support for it yet.
3287    RTLIB::Libcall LC =
3288      VT == MVT::f32 ? RTLIB::POWI_F32 :
3289      VT == MVT::f64 ? RTLIB::POWI_F64 :
3290      VT == MVT::f80 ? RTLIB::POWI_F80 :
3291      VT == MVT::ppcf128 ? RTLIB::POWI_PPCF128 :
3292      RTLIB::UNKNOWN_LIBCALL;
3293    SDOperand Dummy;
3294    Result = ExpandLibCall(TLI.getLibcallName(LC), Node,
3295                           false/*sign irrelevant*/, Dummy);
3296    break;
3297  }
3298  case ISD::BIT_CONVERT:
3299    if (!isTypeLegal(Node->getOperand(0).getValueType())) {
3300      Result = ExpandBIT_CONVERT(Node->getValueType(0), Node->getOperand(0));
3301    } else if (MVT::isVector(Op.getOperand(0).getValueType())) {
3302      // The input has to be a vector type, we have to either scalarize it, pack
3303      // it, or convert it based on whether the input vector type is legal.
3304      SDNode *InVal = Node->getOperand(0).Val;
3305      int InIx = Node->getOperand(0).ResNo;
3306      unsigned NumElems = MVT::getVectorNumElements(InVal->getValueType(InIx));
3307      MVT::ValueType EVT = MVT::getVectorElementType(InVal->getValueType(InIx));
3308
3309      // Figure out if there is a simple type corresponding to this Vector
3310      // type.  If so, convert to the vector type.
3311      MVT::ValueType TVT = MVT::getVectorType(EVT, NumElems);
3312      if (TLI.isTypeLegal(TVT)) {
3313        // Turn this into a bit convert of the vector input.
3314        Result = DAG.getNode(ISD::BIT_CONVERT, Node->getValueType(0),
3315                             LegalizeOp(Node->getOperand(0)));
3316        break;
3317      } else if (NumElems == 1) {
3318        // Turn this into a bit convert of the scalar input.
3319        Result = DAG.getNode(ISD::BIT_CONVERT, Node->getValueType(0),
3320                             ScalarizeVectorOp(Node->getOperand(0)));
3321        break;
3322      } else {
3323        // FIXME: UNIMP!  Store then reload
3324        assert(0 && "Cast from unsupported vector type not implemented yet!");
3325      }
3326    } else {
3327      switch (TLI.getOperationAction(ISD::BIT_CONVERT,
3328                                     Node->getOperand(0).getValueType())) {
3329      default: assert(0 && "Unknown operation action!");
3330      case TargetLowering::Expand:
3331        Result = ExpandBIT_CONVERT(Node->getValueType(0), Node->getOperand(0));
3332        break;
3333      case TargetLowering::Legal:
3334        Tmp1 = LegalizeOp(Node->getOperand(0));
3335        Result = DAG.UpdateNodeOperands(Result, Tmp1);
3336        break;
3337      }
3338    }
3339    break;
3340
3341    // Conversion operators.  The source and destination have different types.
3342  case ISD::SINT_TO_FP:
3343  case ISD::UINT_TO_FP: {
3344    bool isSigned = Node->getOpcode() == ISD::SINT_TO_FP;
3345    switch (getTypeAction(Node->getOperand(0).getValueType())) {
3346    case Legal:
3347      switch (TLI.getOperationAction(Node->getOpcode(),
3348                                     Node->getOperand(0).getValueType())) {
3349      default: assert(0 && "Unknown operation action!");
3350      case TargetLowering::Custom:
3351        isCustom = true;
3352        // FALLTHROUGH
3353      case TargetLowering::Legal:
3354        Tmp1 = LegalizeOp(Node->getOperand(0));
3355        Result = DAG.UpdateNodeOperands(Result, Tmp1);
3356        if (isCustom) {
3357          Tmp1 = TLI.LowerOperation(Result, DAG);
3358          if (Tmp1.Val) Result = Tmp1;
3359        }
3360        break;
3361      case TargetLowering::Expand:
3362        Result = ExpandLegalINT_TO_FP(isSigned,
3363                                      LegalizeOp(Node->getOperand(0)),
3364                                      Node->getValueType(0));
3365        break;
3366      case TargetLowering::Promote:
3367        Result = PromoteLegalINT_TO_FP(LegalizeOp(Node->getOperand(0)),
3368                                       Node->getValueType(0),
3369                                       isSigned);
3370        break;
3371      }
3372      break;
3373    case Expand:
3374      Result = ExpandIntToFP(Node->getOpcode() == ISD::SINT_TO_FP,
3375                             Node->getValueType(0), Node->getOperand(0));
3376      break;
3377    case Promote:
3378      Tmp1 = PromoteOp(Node->getOperand(0));
3379      if (isSigned) {
3380        Tmp1 = DAG.getNode(ISD::SIGN_EXTEND_INREG, Tmp1.getValueType(),
3381                 Tmp1, DAG.getValueType(Node->getOperand(0).getValueType()));
3382      } else {
3383        Tmp1 = DAG.getZeroExtendInReg(Tmp1,
3384                                      Node->getOperand(0).getValueType());
3385      }
3386      Result = DAG.UpdateNodeOperands(Result, Tmp1);
3387      Result = LegalizeOp(Result);  // The 'op' is not necessarily legal!
3388      break;
3389    }
3390    break;
3391  }
3392  case ISD::TRUNCATE:
3393    switch (getTypeAction(Node->getOperand(0).getValueType())) {
3394    case Legal:
3395      Tmp1 = LegalizeOp(Node->getOperand(0));
3396      Result = DAG.UpdateNodeOperands(Result, Tmp1);
3397      break;
3398    case Expand:
3399      ExpandOp(Node->getOperand(0), Tmp1, Tmp2);
3400
3401      // Since the result is legal, we should just be able to truncate the low
3402      // part of the source.
3403      Result = DAG.getNode(ISD::TRUNCATE, Node->getValueType(0), Tmp1);
3404      break;
3405    case Promote:
3406      Result = PromoteOp(Node->getOperand(0));
3407      Result = DAG.getNode(ISD::TRUNCATE, Op.getValueType(), Result);
3408      break;
3409    }
3410    break;
3411
3412  case ISD::FP_TO_SINT:
3413  case ISD::FP_TO_UINT:
3414    switch (getTypeAction(Node->getOperand(0).getValueType())) {
3415    case Legal:
3416      Tmp1 = LegalizeOp(Node->getOperand(0));
3417
3418      switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))){
3419      default: assert(0 && "Unknown operation action!");
3420      case TargetLowering::Custom:
3421        isCustom = true;
3422        // FALLTHROUGH
3423      case TargetLowering::Legal:
3424        Result = DAG.UpdateNodeOperands(Result, Tmp1);
3425        if (isCustom) {
3426          Tmp1 = TLI.LowerOperation(Result, DAG);
3427          if (Tmp1.Val) Result = Tmp1;
3428        }
3429        break;
3430      case TargetLowering::Promote:
3431        Result = PromoteLegalFP_TO_INT(Tmp1, Node->getValueType(0),
3432                                       Node->getOpcode() == ISD::FP_TO_SINT);
3433        break;
3434      case TargetLowering::Expand:
3435        if (Node->getOpcode() == ISD::FP_TO_UINT) {
3436          SDOperand True, False;
3437          MVT::ValueType VT =  Node->getOperand(0).getValueType();
3438          MVT::ValueType NVT = Node->getValueType(0);
3439          unsigned ShiftAmt = MVT::getSizeInBits(NVT)-1;
3440          const uint64_t zero[] = {0, 0};
3441          APFloat apf = APFloat(APInt(MVT::getSizeInBits(VT), 2, zero));
3442          uint64_t x = 1ULL << ShiftAmt;
3443          (void)apf.convertFromZeroExtendedInteger
3444            (&x, MVT::getSizeInBits(NVT), false, APFloat::rmNearestTiesToEven);
3445          Tmp2 = DAG.getConstantFP(apf, VT);
3446          Tmp3 = DAG.getSetCC(TLI.getSetCCResultTy(),
3447                            Node->getOperand(0), Tmp2, ISD::SETLT);
3448          True = DAG.getNode(ISD::FP_TO_SINT, NVT, Node->getOperand(0));
3449          False = DAG.getNode(ISD::FP_TO_SINT, NVT,
3450                              DAG.getNode(ISD::FSUB, VT, Node->getOperand(0),
3451                                          Tmp2));
3452          False = DAG.getNode(ISD::XOR, NVT, False,
3453                              DAG.getConstant(1ULL << ShiftAmt, NVT));
3454          Result = DAG.getNode(ISD::SELECT, NVT, Tmp3, True, False);
3455          break;
3456        } else {
3457          assert(0 && "Do not know how to expand FP_TO_SINT yet!");
3458        }
3459        break;
3460      }
3461      break;
3462    case Expand: {
3463      MVT::ValueType VT = Op.getValueType();
3464      MVT::ValueType OVT = Node->getOperand(0).getValueType();
3465      // Convert ppcf128 to i32
3466      if (OVT == MVT::ppcf128 && VT == MVT::i32) {
3467        if (Node->getOpcode()==ISD::FP_TO_SINT)
3468          Result = DAG.getNode(ISD::FP_TO_SINT, VT,
3469                             DAG.getNode(ISD::FP_ROUND, MVT::f64,
3470                                         (DAG.getNode(ISD::FP_ROUND_INREG,
3471                                          MVT::ppcf128, Node->getOperand(0),
3472                                          DAG.getValueType(MVT::f64)))));
3473        else {
3474          const uint64_t TwoE31[] = {0x41e0000000000000LL, 0};
3475          APFloat apf = APFloat(APInt(128, 2, TwoE31));
3476          Tmp2 = DAG.getConstantFP(apf, OVT);
3477          //  X>=2^31 ? (int)(X-2^31)+0x80000000 : (int)X
3478          // FIXME: generated code sucks.
3479          Result = DAG.getNode(ISD::SELECT_CC, VT, Node->getOperand(0), Tmp2,
3480                               DAG.getNode(ISD::ADD, MVT::i32,
3481                                 DAG.getNode(ISD::FP_TO_SINT, VT,
3482                                   DAG.getNode(ISD::FSUB, OVT,
3483                                                 Node->getOperand(0), Tmp2)),
3484                                 DAG.getConstant(0x80000000, MVT::i32)),
3485                               DAG.getNode(ISD::FP_TO_SINT, VT,
3486                                           Node->getOperand(0)),
3487                               DAG.getCondCode(ISD::SETGE));
3488        }
3489        break;
3490      }
3491      // Convert f32 / f64 to i32 / i64.
3492      RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
3493      switch (Node->getOpcode()) {
3494      case ISD::FP_TO_SINT: {
3495        if (OVT == MVT::f32)
3496          LC = (VT == MVT::i32)
3497            ? RTLIB::FPTOSINT_F32_I32 : RTLIB::FPTOSINT_F32_I64;
3498        else if (OVT == MVT::f64)
3499          LC = (VT == MVT::i32)
3500            ? RTLIB::FPTOSINT_F64_I32 : RTLIB::FPTOSINT_F64_I64;
3501        else if (OVT == MVT::f80) {
3502          assert(VT == MVT::i64);
3503          LC = RTLIB::FPTOSINT_F80_I64;
3504        }
3505        else if (OVT == MVT::ppcf128) {
3506          assert(VT == MVT::i64);
3507          LC = RTLIB::FPTOSINT_PPCF128_I64;
3508        }
3509        break;
3510      }
3511      case ISD::FP_TO_UINT: {
3512        if (OVT == MVT::f32)
3513          LC = (VT == MVT::i32)
3514            ? RTLIB::FPTOUINT_F32_I32 : RTLIB::FPTOSINT_F32_I64;
3515        else if (OVT == MVT::f64)
3516          LC = (VT == MVT::i32)
3517            ? RTLIB::FPTOUINT_F64_I32 : RTLIB::FPTOSINT_F64_I64;
3518        else if (OVT == MVT::f80) {
3519          LC = (VT == MVT::i32)
3520            ? RTLIB::FPTOUINT_F80_I32 : RTLIB::FPTOUINT_F80_I64;
3521        }
3522        else if (OVT ==  MVT::ppcf128) {
3523          assert(VT == MVT::i64);
3524          LC = RTLIB::FPTOUINT_PPCF128_I64;
3525        }
3526        break;
3527      }
3528      default: assert(0 && "Unreachable!");
3529      }
3530      SDOperand Dummy;
3531      Result = ExpandLibCall(TLI.getLibcallName(LC), Node,
3532                             false/*sign irrelevant*/, Dummy);
3533      break;
3534    }
3535    case Promote:
3536      Tmp1 = PromoteOp(Node->getOperand(0));
3537      Result = DAG.UpdateNodeOperands(Result, LegalizeOp(Tmp1));
3538      Result = LegalizeOp(Result);
3539      break;
3540    }
3541    break;
3542
3543  case ISD::FP_EXTEND:
3544  case ISD::FP_ROUND: {
3545      MVT::ValueType newVT = Op.getValueType();
3546      MVT::ValueType oldVT = Op.getOperand(0).getValueType();
3547      if (TLI.getConvertAction(oldVT, newVT) == TargetLowering::Expand) {
3548        if (Node->getOpcode() == ISD::FP_ROUND && oldVT == MVT::ppcf128) {
3549          SDOperand Lo, Hi;
3550          ExpandOp(Node->getOperand(0), Lo, Hi);
3551          if (newVT == MVT::f64)
3552            Result = Hi;
3553          else
3554            Result = DAG.getNode(ISD::FP_ROUND, newVT, Hi);
3555          break;
3556        } else {
3557          // The only other way we can lower this is to turn it into a STORE,
3558          // LOAD pair, targetting a temporary location (a stack slot).
3559
3560          // NOTE: there is a choice here between constantly creating new stack
3561          // slots and always reusing the same one.  We currently always create
3562          // new ones, as reuse may inhibit scheduling.
3563          MVT::ValueType slotVT =
3564                  (Node->getOpcode() == ISD::FP_EXTEND) ? oldVT : newVT;
3565          const Type *Ty = MVT::getTypeForValueType(slotVT);
3566          uint64_t TySize = TLI.getTargetData()->getABITypeSize(Ty);
3567          unsigned Align  = TLI.getTargetData()->getPrefTypeAlignment(Ty);
3568          MachineFunction &MF = DAG.getMachineFunction();
3569          int SSFI =
3570            MF.getFrameInfo()->CreateStackObject(TySize, Align);
3571          SDOperand StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
3572          if (Node->getOpcode() == ISD::FP_EXTEND) {
3573            Result = DAG.getStore(DAG.getEntryNode(), Node->getOperand(0),
3574                                       StackSlot, NULL, 0);
3575            Result = DAG.getExtLoad(ISD::EXTLOAD, newVT,
3576                                       Result, StackSlot, NULL, 0, oldVT);
3577          } else {
3578            Result = DAG.getTruncStore(DAG.getEntryNode(), Node->getOperand(0),
3579                                       StackSlot, NULL, 0, newVT);
3580            Result = DAG.getLoad(newVT, Result, StackSlot, NULL, 0);
3581          }
3582          break;
3583        }
3584      }
3585    }
3586    // FALL THROUGH
3587  case ISD::ANY_EXTEND:
3588  case ISD::ZERO_EXTEND:
3589  case ISD::SIGN_EXTEND:
3590    switch (getTypeAction(Node->getOperand(0).getValueType())) {
3591    case Expand: assert(0 && "Shouldn't need to expand other operators here!");
3592    case Legal:
3593      Tmp1 = LegalizeOp(Node->getOperand(0));
3594      Result = DAG.UpdateNodeOperands(Result, Tmp1);
3595      break;
3596    case Promote:
3597      switch (Node->getOpcode()) {
3598      case ISD::ANY_EXTEND:
3599        Tmp1 = PromoteOp(Node->getOperand(0));
3600        Result = DAG.getNode(ISD::ANY_EXTEND, Op.getValueType(), Tmp1);
3601        break;
3602      case ISD::ZERO_EXTEND:
3603        Result = PromoteOp(Node->getOperand(0));
3604        Result = DAG.getNode(ISD::ANY_EXTEND, Op.getValueType(), Result);
3605        Result = DAG.getZeroExtendInReg(Result,
3606                                        Node->getOperand(0).getValueType());
3607        break;
3608      case ISD::SIGN_EXTEND:
3609        Result = PromoteOp(Node->getOperand(0));
3610        Result = DAG.getNode(ISD::ANY_EXTEND, Op.getValueType(), Result);
3611        Result = DAG.getNode(ISD::SIGN_EXTEND_INREG, Result.getValueType(),
3612                             Result,
3613                          DAG.getValueType(Node->getOperand(0).getValueType()));
3614        break;
3615      case ISD::FP_EXTEND:
3616        Result = PromoteOp(Node->getOperand(0));
3617        if (Result.getValueType() != Op.getValueType())
3618          // Dynamically dead while we have only 2 FP types.
3619          Result = DAG.getNode(ISD::FP_EXTEND, Op.getValueType(), Result);
3620        break;
3621      case ISD::FP_ROUND:
3622        Result = PromoteOp(Node->getOperand(0));
3623        Result = DAG.getNode(Node->getOpcode(), Op.getValueType(), Result);
3624        break;
3625      }
3626    }
3627    break;
3628  case ISD::FP_ROUND_INREG:
3629  case ISD::SIGN_EXTEND_INREG: {
3630    Tmp1 = LegalizeOp(Node->getOperand(0));
3631    MVT::ValueType ExtraVT = cast<VTSDNode>(Node->getOperand(1))->getVT();
3632
3633    // If this operation is not supported, convert it to a shl/shr or load/store
3634    // pair.
3635    switch (TLI.getOperationAction(Node->getOpcode(), ExtraVT)) {
3636    default: assert(0 && "This action not supported for this op yet!");
3637    case TargetLowering::Legal:
3638      Result = DAG.UpdateNodeOperands(Result, Tmp1, Node->getOperand(1));
3639      break;
3640    case TargetLowering::Expand:
3641      // If this is an integer extend and shifts are supported, do that.
3642      if (Node->getOpcode() == ISD::SIGN_EXTEND_INREG) {
3643        // NOTE: we could fall back on load/store here too for targets without
3644        // SAR.  However, it is doubtful that any exist.
3645        unsigned BitsDiff = MVT::getSizeInBits(Node->getValueType(0)) -
3646                            MVT::getSizeInBits(ExtraVT);
3647        SDOperand ShiftCst = DAG.getConstant(BitsDiff, TLI.getShiftAmountTy());
3648        Result = DAG.getNode(ISD::SHL, Node->getValueType(0),
3649                             Node->getOperand(0), ShiftCst);
3650        Result = DAG.getNode(ISD::SRA, Node->getValueType(0),
3651                             Result, ShiftCst);
3652      } else if (Node->getOpcode() == ISD::FP_ROUND_INREG) {
3653        // The only way we can lower this is to turn it into a TRUNCSTORE,
3654        // EXTLOAD pair, targetting a temporary location (a stack slot).
3655
3656        // NOTE: there is a choice here between constantly creating new stack
3657        // slots and always reusing the same one.  We currently always create
3658        // new ones, as reuse may inhibit scheduling.
3659        const Type *Ty = MVT::getTypeForValueType(ExtraVT);
3660        uint64_t TySize = TLI.getTargetData()->getABITypeSize(Ty);
3661        unsigned Align  = TLI.getTargetData()->getPrefTypeAlignment(Ty);
3662        MachineFunction &MF = DAG.getMachineFunction();
3663        int SSFI =
3664          MF.getFrameInfo()->CreateStackObject(TySize, Align);
3665        SDOperand StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
3666        Result = DAG.getTruncStore(DAG.getEntryNode(), Node->getOperand(0),
3667                                   StackSlot, NULL, 0, ExtraVT);
3668        Result = DAG.getExtLoad(ISD::EXTLOAD, Node->getValueType(0),
3669                                Result, StackSlot, NULL, 0, ExtraVT);
3670      } else {
3671        assert(0 && "Unknown op");
3672      }
3673      break;
3674    }
3675    break;
3676  }
3677  case ISD::TRAMPOLINE: {
3678    SDOperand Ops[6];
3679    for (unsigned i = 0; i != 6; ++i)
3680      Ops[i] = LegalizeOp(Node->getOperand(i));
3681    Result = DAG.UpdateNodeOperands(Result, Ops, 6);
3682    // The only option for this node is to custom lower it.
3683    Result = TLI.LowerOperation(Result, DAG);
3684    assert(Result.Val && "Should always custom lower!");
3685
3686    // Since trampoline produces two values, make sure to remember that we
3687    // legalized both of them.
3688    Tmp1 = LegalizeOp(Result.getValue(1));
3689    Result = LegalizeOp(Result);
3690    AddLegalizedOperand(SDOperand(Node, 0), Result);
3691    AddLegalizedOperand(SDOperand(Node, 1), Tmp1);
3692    return Op.ResNo ? Tmp1 : Result;
3693  }
3694   case ISD::FLT_ROUNDS: {
3695    MVT::ValueType VT = Node->getValueType(0);
3696    switch (TLI.getOperationAction(Node->getOpcode(), VT)) {
3697    default: assert(0 && "This action not supported for this op yet!");
3698    case TargetLowering::Custom:
3699      Result = TLI.LowerOperation(Op, DAG);
3700      if (Result.Val) break;
3701      // Fall Thru
3702    case TargetLowering::Legal:
3703      // If this operation is not supported, lower it to constant 1
3704      Result = DAG.getConstant(1, VT);
3705      break;
3706    }
3707  }
3708  }
3709
3710  assert(Result.getValueType() == Op.getValueType() &&
3711         "Bad legalization!");
3712
3713  // Make sure that the generated code is itself legal.
3714  if (Result != Op)
3715    Result = LegalizeOp(Result);
3716
3717  // Note that LegalizeOp may be reentered even from single-use nodes, which
3718  // means that we always must cache transformed nodes.
3719  AddLegalizedOperand(Op, Result);
3720  return Result;
3721}
3722
3723/// PromoteOp - Given an operation that produces a value in an invalid type,
3724/// promote it to compute the value into a larger type.  The produced value will
3725/// have the correct bits for the low portion of the register, but no guarantee
3726/// is made about the top bits: it may be zero, sign-extended, or garbage.
3727SDOperand SelectionDAGLegalize::PromoteOp(SDOperand Op) {
3728  MVT::ValueType VT = Op.getValueType();
3729  MVT::ValueType NVT = TLI.getTypeToTransformTo(VT);
3730  assert(getTypeAction(VT) == Promote &&
3731         "Caller should expand or legalize operands that are not promotable!");
3732  assert(NVT > VT && MVT::isInteger(NVT) == MVT::isInteger(VT) &&
3733         "Cannot promote to smaller type!");
3734
3735  SDOperand Tmp1, Tmp2, Tmp3;
3736  SDOperand Result;
3737  SDNode *Node = Op.Val;
3738
3739  DenseMap<SDOperand, SDOperand>::iterator I = PromotedNodes.find(Op);
3740  if (I != PromotedNodes.end()) return I->second;
3741
3742  switch (Node->getOpcode()) {
3743  case ISD::CopyFromReg:
3744    assert(0 && "CopyFromReg must be legal!");
3745  default:
3746#ifndef NDEBUG
3747    cerr << "NODE: "; Node->dump(&DAG); cerr << "\n";
3748#endif
3749    assert(0 && "Do not know how to promote this operator!");
3750    abort();
3751  case ISD::UNDEF:
3752    Result = DAG.getNode(ISD::UNDEF, NVT);
3753    break;
3754  case ISD::Constant:
3755    if (VT != MVT::i1)
3756      Result = DAG.getNode(ISD::SIGN_EXTEND, NVT, Op);
3757    else
3758      Result = DAG.getNode(ISD::ZERO_EXTEND, NVT, Op);
3759    assert(isa<ConstantSDNode>(Result) && "Didn't constant fold zext?");
3760    break;
3761  case ISD::ConstantFP:
3762    Result = DAG.getNode(ISD::FP_EXTEND, NVT, Op);
3763    assert(isa<ConstantFPSDNode>(Result) && "Didn't constant fold fp_extend?");
3764    break;
3765
3766  case ISD::SETCC:
3767    assert(isTypeLegal(TLI.getSetCCResultTy()) && "SetCC type is not legal??");
3768    Result = DAG.getNode(ISD::SETCC, TLI.getSetCCResultTy(),Node->getOperand(0),
3769                         Node->getOperand(1), Node->getOperand(2));
3770    break;
3771
3772  case ISD::TRUNCATE:
3773    switch (getTypeAction(Node->getOperand(0).getValueType())) {
3774    case Legal:
3775      Result = LegalizeOp(Node->getOperand(0));
3776      assert(Result.getValueType() >= NVT &&
3777             "This truncation doesn't make sense!");
3778      if (Result.getValueType() > NVT)    // Truncate to NVT instead of VT
3779        Result = DAG.getNode(ISD::TRUNCATE, NVT, Result);
3780      break;
3781    case Promote:
3782      // The truncation is not required, because we don't guarantee anything
3783      // about high bits anyway.
3784      Result = PromoteOp(Node->getOperand(0));
3785      break;
3786    case Expand:
3787      ExpandOp(Node->getOperand(0), Tmp1, Tmp2);
3788      // Truncate the low part of the expanded value to the result type
3789      Result = DAG.getNode(ISD::TRUNCATE, NVT, Tmp1);
3790    }
3791    break;
3792  case ISD::SIGN_EXTEND:
3793  case ISD::ZERO_EXTEND:
3794  case ISD::ANY_EXTEND:
3795    switch (getTypeAction(Node->getOperand(0).getValueType())) {
3796    case Expand: assert(0 && "BUG: Smaller reg should have been promoted!");
3797    case Legal:
3798      // Input is legal?  Just do extend all the way to the larger type.
3799      Result = DAG.getNode(Node->getOpcode(), NVT, Node->getOperand(0));
3800      break;
3801    case Promote:
3802      // Promote the reg if it's smaller.
3803      Result = PromoteOp(Node->getOperand(0));
3804      // The high bits are not guaranteed to be anything.  Insert an extend.
3805      if (Node->getOpcode() == ISD::SIGN_EXTEND)
3806        Result = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Result,
3807                         DAG.getValueType(Node->getOperand(0).getValueType()));
3808      else if (Node->getOpcode() == ISD::ZERO_EXTEND)
3809        Result = DAG.getZeroExtendInReg(Result,
3810                                        Node->getOperand(0).getValueType());
3811      break;
3812    }
3813    break;
3814  case ISD::BIT_CONVERT:
3815    Result = ExpandBIT_CONVERT(Node->getValueType(0), Node->getOperand(0));
3816    Result = PromoteOp(Result);
3817    break;
3818
3819  case ISD::FP_EXTEND:
3820    assert(0 && "Case not implemented.  Dynamically dead with 2 FP types!");
3821  case ISD::FP_ROUND:
3822    switch (getTypeAction(Node->getOperand(0).getValueType())) {
3823    case Expand: assert(0 && "BUG: Cannot expand FP regs!");
3824    case Promote:  assert(0 && "Unreachable with 2 FP types!");
3825    case Legal:
3826      // Input is legal?  Do an FP_ROUND_INREG.
3827      Result = DAG.getNode(ISD::FP_ROUND_INREG, NVT, Node->getOperand(0),
3828                           DAG.getValueType(VT));
3829      break;
3830    }
3831    break;
3832
3833  case ISD::SINT_TO_FP:
3834  case ISD::UINT_TO_FP:
3835    switch (getTypeAction(Node->getOperand(0).getValueType())) {
3836    case Legal:
3837      // No extra round required here.
3838      Result = DAG.getNode(Node->getOpcode(), NVT, Node->getOperand(0));
3839      break;
3840
3841    case Promote:
3842      Result = PromoteOp(Node->getOperand(0));
3843      if (Node->getOpcode() == ISD::SINT_TO_FP)
3844        Result = DAG.getNode(ISD::SIGN_EXTEND_INREG, Result.getValueType(),
3845                             Result,
3846                         DAG.getValueType(Node->getOperand(0).getValueType()));
3847      else
3848        Result = DAG.getZeroExtendInReg(Result,
3849                                        Node->getOperand(0).getValueType());
3850      // No extra round required here.
3851      Result = DAG.getNode(Node->getOpcode(), NVT, Result);
3852      break;
3853    case Expand:
3854      Result = ExpandIntToFP(Node->getOpcode() == ISD::SINT_TO_FP, NVT,
3855                             Node->getOperand(0));
3856      // Round if we cannot tolerate excess precision.
3857      if (NoExcessFPPrecision)
3858        Result = DAG.getNode(ISD::FP_ROUND_INREG, NVT, Result,
3859                             DAG.getValueType(VT));
3860      break;
3861    }
3862    break;
3863
3864  case ISD::SIGN_EXTEND_INREG:
3865    Result = PromoteOp(Node->getOperand(0));
3866    Result = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Result,
3867                         Node->getOperand(1));
3868    break;
3869  case ISD::FP_TO_SINT:
3870  case ISD::FP_TO_UINT:
3871    switch (getTypeAction(Node->getOperand(0).getValueType())) {
3872    case Legal:
3873    case Expand:
3874      Tmp1 = Node->getOperand(0);
3875      break;
3876    case Promote:
3877      // The input result is prerounded, so we don't have to do anything
3878      // special.
3879      Tmp1 = PromoteOp(Node->getOperand(0));
3880      break;
3881    }
3882    // If we're promoting a UINT to a larger size, check to see if the new node
3883    // will be legal.  If it isn't, check to see if FP_TO_SINT is legal, since
3884    // we can use that instead.  This allows us to generate better code for
3885    // FP_TO_UINT for small destination sizes on targets where FP_TO_UINT is not
3886    // legal, such as PowerPC.
3887    if (Node->getOpcode() == ISD::FP_TO_UINT &&
3888        !TLI.isOperationLegal(ISD::FP_TO_UINT, NVT) &&
3889        (TLI.isOperationLegal(ISD::FP_TO_SINT, NVT) ||
3890         TLI.getOperationAction(ISD::FP_TO_SINT, NVT)==TargetLowering::Custom)){
3891      Result = DAG.getNode(ISD::FP_TO_SINT, NVT, Tmp1);
3892    } else {
3893      Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1);
3894    }
3895    break;
3896
3897  case ISD::FABS:
3898  case ISD::FNEG:
3899    Tmp1 = PromoteOp(Node->getOperand(0));
3900    assert(Tmp1.getValueType() == NVT);
3901    Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1);
3902    // NOTE: we do not have to do any extra rounding here for
3903    // NoExcessFPPrecision, because we know the input will have the appropriate
3904    // precision, and these operations don't modify precision at all.
3905    break;
3906
3907  case ISD::FSQRT:
3908  case ISD::FSIN:
3909  case ISD::FCOS:
3910    Tmp1 = PromoteOp(Node->getOperand(0));
3911    assert(Tmp1.getValueType() == NVT);
3912    Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1);
3913    if (NoExcessFPPrecision)
3914      Result = DAG.getNode(ISD::FP_ROUND_INREG, NVT, Result,
3915                           DAG.getValueType(VT));
3916    break;
3917
3918  case ISD::FPOWI: {
3919    // Promote f32 powi to f64 powi.  Note that this could insert a libcall
3920    // directly as well, which may be better.
3921    Tmp1 = PromoteOp(Node->getOperand(0));
3922    assert(Tmp1.getValueType() == NVT);
3923    Result = DAG.getNode(ISD::FPOWI, NVT, Tmp1, Node->getOperand(1));
3924    if (NoExcessFPPrecision)
3925      Result = DAG.getNode(ISD::FP_ROUND_INREG, NVT, Result,
3926                           DAG.getValueType(VT));
3927    break;
3928  }
3929
3930  case ISD::AND:
3931  case ISD::OR:
3932  case ISD::XOR:
3933  case ISD::ADD:
3934  case ISD::SUB:
3935  case ISD::MUL:
3936    // The input may have strange things in the top bits of the registers, but
3937    // these operations don't care.  They may have weird bits going out, but
3938    // that too is okay if they are integer operations.
3939    Tmp1 = PromoteOp(Node->getOperand(0));
3940    Tmp2 = PromoteOp(Node->getOperand(1));
3941    assert(Tmp1.getValueType() == NVT && Tmp2.getValueType() == NVT);
3942    Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1, Tmp2);
3943    break;
3944  case ISD::FADD:
3945  case ISD::FSUB:
3946  case ISD::FMUL:
3947    Tmp1 = PromoteOp(Node->getOperand(0));
3948    Tmp2 = PromoteOp(Node->getOperand(1));
3949    assert(Tmp1.getValueType() == NVT && Tmp2.getValueType() == NVT);
3950    Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1, Tmp2);
3951
3952    // Floating point operations will give excess precision that we may not be
3953    // able to tolerate.  If we DO allow excess precision, just leave it,
3954    // otherwise excise it.
3955    // FIXME: Why would we need to round FP ops more than integer ones?
3956    //     Is Round(Add(Add(A,B),C)) != Round(Add(Round(Add(A,B)), C))
3957    if (NoExcessFPPrecision)
3958      Result = DAG.getNode(ISD::FP_ROUND_INREG, NVT, Result,
3959                           DAG.getValueType(VT));
3960    break;
3961
3962  case ISD::SDIV:
3963  case ISD::SREM:
3964    // These operators require that their input be sign extended.
3965    Tmp1 = PromoteOp(Node->getOperand(0));
3966    Tmp2 = PromoteOp(Node->getOperand(1));
3967    if (MVT::isInteger(NVT)) {
3968      Tmp1 = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Tmp1,
3969                         DAG.getValueType(VT));
3970      Tmp2 = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Tmp2,
3971                         DAG.getValueType(VT));
3972    }
3973    Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1, Tmp2);
3974
3975    // Perform FP_ROUND: this is probably overly pessimistic.
3976    if (MVT::isFloatingPoint(NVT) && NoExcessFPPrecision)
3977      Result = DAG.getNode(ISD::FP_ROUND_INREG, NVT, Result,
3978                           DAG.getValueType(VT));
3979    break;
3980  case ISD::FDIV:
3981  case ISD::FREM:
3982  case ISD::FCOPYSIGN:
3983    // These operators require that their input be fp extended.
3984    switch (getTypeAction(Node->getOperand(0).getValueType())) {
3985      case Legal:
3986        Tmp1 = LegalizeOp(Node->getOperand(0));
3987        break;
3988      case Promote:
3989        Tmp1 = PromoteOp(Node->getOperand(0));
3990        break;
3991      case Expand:
3992        assert(0 && "not implemented");
3993    }
3994    switch (getTypeAction(Node->getOperand(1).getValueType())) {
3995      case Legal:
3996        Tmp2 = LegalizeOp(Node->getOperand(1));
3997        break;
3998      case Promote:
3999        Tmp2 = PromoteOp(Node->getOperand(1));
4000        break;
4001      case Expand:
4002        assert(0 && "not implemented");
4003    }
4004    Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1, Tmp2);
4005
4006    // Perform FP_ROUND: this is probably overly pessimistic.
4007    if (NoExcessFPPrecision && Node->getOpcode() != ISD::FCOPYSIGN)
4008      Result = DAG.getNode(ISD::FP_ROUND_INREG, NVT, Result,
4009                           DAG.getValueType(VT));
4010    break;
4011
4012  case ISD::UDIV:
4013  case ISD::UREM:
4014    // These operators require that their input be zero extended.
4015    Tmp1 = PromoteOp(Node->getOperand(0));
4016    Tmp2 = PromoteOp(Node->getOperand(1));
4017    assert(MVT::isInteger(NVT) && "Operators don't apply to FP!");
4018    Tmp1 = DAG.getZeroExtendInReg(Tmp1, VT);
4019    Tmp2 = DAG.getZeroExtendInReg(Tmp2, VT);
4020    Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1, Tmp2);
4021    break;
4022
4023  case ISD::SHL:
4024    Tmp1 = PromoteOp(Node->getOperand(0));
4025    Result = DAG.getNode(ISD::SHL, NVT, Tmp1, Node->getOperand(1));
4026    break;
4027  case ISD::SRA:
4028    // The input value must be properly sign extended.
4029    Tmp1 = PromoteOp(Node->getOperand(0));
4030    Tmp1 = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Tmp1,
4031                       DAG.getValueType(VT));
4032    Result = DAG.getNode(ISD::SRA, NVT, Tmp1, Node->getOperand(1));
4033    break;
4034  case ISD::SRL:
4035    // The input value must be properly zero extended.
4036    Tmp1 = PromoteOp(Node->getOperand(0));
4037    Tmp1 = DAG.getZeroExtendInReg(Tmp1, VT);
4038    Result = DAG.getNode(ISD::SRL, NVT, Tmp1, Node->getOperand(1));
4039    break;
4040
4041  case ISD::VAARG:
4042    Tmp1 = Node->getOperand(0);   // Get the chain.
4043    Tmp2 = Node->getOperand(1);   // Get the pointer.
4044    if (TLI.getOperationAction(ISD::VAARG, VT) == TargetLowering::Custom) {
4045      Tmp3 = DAG.getVAArg(VT, Tmp1, Tmp2, Node->getOperand(2));
4046      Result = TLI.CustomPromoteOperation(Tmp3, DAG);
4047    } else {
4048      SrcValueSDNode *SV = cast<SrcValueSDNode>(Node->getOperand(2));
4049      SDOperand VAList = DAG.getLoad(TLI.getPointerTy(), Tmp1, Tmp2,
4050                                     SV->getValue(), SV->getOffset());
4051      // Increment the pointer, VAList, to the next vaarg
4052      Tmp3 = DAG.getNode(ISD::ADD, TLI.getPointerTy(), VAList,
4053                         DAG.getConstant(MVT::getSizeInBits(VT)/8,
4054                                         TLI.getPointerTy()));
4055      // Store the incremented VAList to the legalized pointer
4056      Tmp3 = DAG.getStore(VAList.getValue(1), Tmp3, Tmp2, SV->getValue(),
4057                          SV->getOffset());
4058      // Load the actual argument out of the pointer VAList
4059      Result = DAG.getExtLoad(ISD::EXTLOAD, NVT, Tmp3, VAList, NULL, 0, VT);
4060    }
4061    // Remember that we legalized the chain.
4062    AddLegalizedOperand(Op.getValue(1), LegalizeOp(Result.getValue(1)));
4063    break;
4064
4065  case ISD::LOAD: {
4066    LoadSDNode *LD = cast<LoadSDNode>(Node);
4067    ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(Node)
4068      ? ISD::EXTLOAD : LD->getExtensionType();
4069    Result = DAG.getExtLoad(ExtType, NVT,
4070                            LD->getChain(), LD->getBasePtr(),
4071                            LD->getSrcValue(), LD->getSrcValueOffset(),
4072                            LD->getLoadedVT(),
4073                            LD->isVolatile(),
4074                            LD->getAlignment());
4075    // Remember that we legalized the chain.
4076    AddLegalizedOperand(Op.getValue(1), LegalizeOp(Result.getValue(1)));
4077    break;
4078  }
4079  case ISD::SELECT:
4080    Tmp2 = PromoteOp(Node->getOperand(1));   // Legalize the op0
4081    Tmp3 = PromoteOp(Node->getOperand(2));   // Legalize the op1
4082    Result = DAG.getNode(ISD::SELECT, NVT, Node->getOperand(0), Tmp2, Tmp3);
4083    break;
4084  case ISD::SELECT_CC:
4085    Tmp2 = PromoteOp(Node->getOperand(2));   // True
4086    Tmp3 = PromoteOp(Node->getOperand(3));   // False
4087    Result = DAG.getNode(ISD::SELECT_CC, NVT, Node->getOperand(0),
4088                         Node->getOperand(1), Tmp2, Tmp3, Node->getOperand(4));
4089    break;
4090  case ISD::BSWAP:
4091    Tmp1 = Node->getOperand(0);
4092    Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, NVT, Tmp1);
4093    Tmp1 = DAG.getNode(ISD::BSWAP, NVT, Tmp1);
4094    Result = DAG.getNode(ISD::SRL, NVT, Tmp1,
4095                         DAG.getConstant(MVT::getSizeInBits(NVT) -
4096                                         MVT::getSizeInBits(VT),
4097                                         TLI.getShiftAmountTy()));
4098    break;
4099  case ISD::CTPOP:
4100  case ISD::CTTZ:
4101  case ISD::CTLZ:
4102    // Zero extend the argument
4103    Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, NVT, Node->getOperand(0));
4104    // Perform the larger operation, then subtract if needed.
4105    Tmp1 = DAG.getNode(Node->getOpcode(), NVT, Tmp1);
4106    switch(Node->getOpcode()) {
4107    case ISD::CTPOP:
4108      Result = Tmp1;
4109      break;
4110    case ISD::CTTZ:
4111      // if Tmp1 == sizeinbits(NVT) then Tmp1 = sizeinbits(Old VT)
4112      Tmp2 = DAG.getSetCC(TLI.getSetCCResultTy(), Tmp1,
4113                          DAG.getConstant(MVT::getSizeInBits(NVT), NVT),
4114                          ISD::SETEQ);
4115      Result = DAG.getNode(ISD::SELECT, NVT, Tmp2,
4116                           DAG.getConstant(MVT::getSizeInBits(VT), NVT), Tmp1);
4117      break;
4118    case ISD::CTLZ:
4119      //Tmp1 = Tmp1 - (sizeinbits(NVT) - sizeinbits(Old VT))
4120      Result = DAG.getNode(ISD::SUB, NVT, Tmp1,
4121                           DAG.getConstant(MVT::getSizeInBits(NVT) -
4122                                           MVT::getSizeInBits(VT), NVT));
4123      break;
4124    }
4125    break;
4126  case ISD::EXTRACT_SUBVECTOR:
4127    Result = PromoteOp(ExpandEXTRACT_SUBVECTOR(Op));
4128    break;
4129  case ISD::EXTRACT_VECTOR_ELT:
4130    Result = PromoteOp(ExpandEXTRACT_VECTOR_ELT(Op));
4131    break;
4132  }
4133
4134  assert(Result.Val && "Didn't set a result!");
4135
4136  // Make sure the result is itself legal.
4137  Result = LegalizeOp(Result);
4138
4139  // Remember that we promoted this!
4140  AddPromotedOperand(Op, Result);
4141  return Result;
4142}
4143
4144/// ExpandEXTRACT_VECTOR_ELT - Expand an EXTRACT_VECTOR_ELT operation into
4145/// a legal EXTRACT_VECTOR_ELT operation, scalar code, or memory traffic,
4146/// based on the vector type. The return type of this matches the element type
4147/// of the vector, which may not be legal for the target.
4148SDOperand SelectionDAGLegalize::ExpandEXTRACT_VECTOR_ELT(SDOperand Op) {
4149  // We know that operand #0 is the Vec vector.  If the index is a constant
4150  // or if the invec is a supported hardware type, we can use it.  Otherwise,
4151  // lower to a store then an indexed load.
4152  SDOperand Vec = Op.getOperand(0);
4153  SDOperand Idx = Op.getOperand(1);
4154
4155  MVT::ValueType TVT = Vec.getValueType();
4156  unsigned NumElems = MVT::getVectorNumElements(TVT);
4157
4158  switch (TLI.getOperationAction(ISD::EXTRACT_VECTOR_ELT, TVT)) {
4159  default: assert(0 && "This action is not supported yet!");
4160  case TargetLowering::Custom: {
4161    Vec = LegalizeOp(Vec);
4162    Op = DAG.UpdateNodeOperands(Op, Vec, Idx);
4163    SDOperand Tmp3 = TLI.LowerOperation(Op, DAG);
4164    if (Tmp3.Val)
4165      return Tmp3;
4166    break;
4167  }
4168  case TargetLowering::Legal:
4169    if (isTypeLegal(TVT)) {
4170      Vec = LegalizeOp(Vec);
4171      Op = DAG.UpdateNodeOperands(Op, Vec, Idx);
4172      return Op;
4173    }
4174    break;
4175  case TargetLowering::Expand:
4176    break;
4177  }
4178
4179  if (NumElems == 1) {
4180    // This must be an access of the only element.  Return it.
4181    Op = ScalarizeVectorOp(Vec);
4182  } else if (!TLI.isTypeLegal(TVT) && isa<ConstantSDNode>(Idx)) {
4183    ConstantSDNode *CIdx = cast<ConstantSDNode>(Idx);
4184    SDOperand Lo, Hi;
4185    SplitVectorOp(Vec, Lo, Hi);
4186    if (CIdx->getValue() < NumElems/2) {
4187      Vec = Lo;
4188    } else {
4189      Vec = Hi;
4190      Idx = DAG.getConstant(CIdx->getValue() - NumElems/2,
4191                            Idx.getValueType());
4192    }
4193
4194    // It's now an extract from the appropriate high or low part.  Recurse.
4195    Op = DAG.UpdateNodeOperands(Op, Vec, Idx);
4196    Op = ExpandEXTRACT_VECTOR_ELT(Op);
4197  } else {
4198    // Store the value to a temporary stack slot, then LOAD the scalar
4199    // element back out.
4200    SDOperand StackPtr = DAG.CreateStackTemporary(Vec.getValueType());
4201    SDOperand Ch = DAG.getStore(DAG.getEntryNode(), Vec, StackPtr, NULL, 0);
4202
4203    // Add the offset to the index.
4204    unsigned EltSize = MVT::getSizeInBits(Op.getValueType())/8;
4205    Idx = DAG.getNode(ISD::MUL, Idx.getValueType(), Idx,
4206                      DAG.getConstant(EltSize, Idx.getValueType()));
4207
4208    if (MVT::getSizeInBits(Idx.getValueType()) >
4209        MVT::getSizeInBits(TLI.getPointerTy()))
4210      Idx = DAG.getNode(ISD::TRUNCATE, TLI.getPointerTy(), Idx);
4211    else
4212      Idx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(), Idx);
4213
4214    StackPtr = DAG.getNode(ISD::ADD, Idx.getValueType(), Idx, StackPtr);
4215
4216    Op = DAG.getLoad(Op.getValueType(), Ch, StackPtr, NULL, 0);
4217  }
4218  return Op;
4219}
4220
4221/// ExpandEXTRACT_SUBVECTOR - Expand a EXTRACT_SUBVECTOR operation.  For now
4222/// we assume the operation can be split if it is not already legal.
4223SDOperand SelectionDAGLegalize::ExpandEXTRACT_SUBVECTOR(SDOperand Op) {
4224  // We know that operand #0 is the Vec vector.  For now we assume the index
4225  // is a constant and that the extracted result is a supported hardware type.
4226  SDOperand Vec = Op.getOperand(0);
4227  SDOperand Idx = LegalizeOp(Op.getOperand(1));
4228
4229  unsigned NumElems = MVT::getVectorNumElements(Vec.getValueType());
4230
4231  if (NumElems == MVT::getVectorNumElements(Op.getValueType())) {
4232    // This must be an access of the desired vector length.  Return it.
4233    return Vec;
4234  }
4235
4236  ConstantSDNode *CIdx = cast<ConstantSDNode>(Idx);
4237  SDOperand Lo, Hi;
4238  SplitVectorOp(Vec, Lo, Hi);
4239  if (CIdx->getValue() < NumElems/2) {
4240    Vec = Lo;
4241  } else {
4242    Vec = Hi;
4243    Idx = DAG.getConstant(CIdx->getValue() - NumElems/2, Idx.getValueType());
4244  }
4245
4246  // It's now an extract from the appropriate high or low part.  Recurse.
4247  Op = DAG.UpdateNodeOperands(Op, Vec, Idx);
4248  return ExpandEXTRACT_SUBVECTOR(Op);
4249}
4250
4251/// LegalizeSetCCOperands - Attempts to create a legal LHS and RHS for a SETCC
4252/// with condition CC on the current target.  This usually involves legalizing
4253/// or promoting the arguments.  In the case where LHS and RHS must be expanded,
4254/// there may be no choice but to create a new SetCC node to represent the
4255/// legalized value of setcc lhs, rhs.  In this case, the value is returned in
4256/// LHS, and the SDOperand returned in RHS has a nil SDNode value.
4257void SelectionDAGLegalize::LegalizeSetCCOperands(SDOperand &LHS,
4258                                                 SDOperand &RHS,
4259                                                 SDOperand &CC) {
4260  SDOperand Tmp1, Tmp2, Tmp3, Result;
4261
4262  switch (getTypeAction(LHS.getValueType())) {
4263  case Legal:
4264    Tmp1 = LegalizeOp(LHS);   // LHS
4265    Tmp2 = LegalizeOp(RHS);   // RHS
4266    break;
4267  case Promote:
4268    Tmp1 = PromoteOp(LHS);   // LHS
4269    Tmp2 = PromoteOp(RHS);   // RHS
4270
4271    // If this is an FP compare, the operands have already been extended.
4272    if (MVT::isInteger(LHS.getValueType())) {
4273      MVT::ValueType VT = LHS.getValueType();
4274      MVT::ValueType NVT = TLI.getTypeToTransformTo(VT);
4275
4276      // Otherwise, we have to insert explicit sign or zero extends.  Note
4277      // that we could insert sign extends for ALL conditions, but zero extend
4278      // is cheaper on many machines (an AND instead of two shifts), so prefer
4279      // it.
4280      switch (cast<CondCodeSDNode>(CC)->get()) {
4281      default: assert(0 && "Unknown integer comparison!");
4282      case ISD::SETEQ:
4283      case ISD::SETNE:
4284      case ISD::SETUGE:
4285      case ISD::SETUGT:
4286      case ISD::SETULE:
4287      case ISD::SETULT:
4288        // ALL of these operations will work if we either sign or zero extend
4289        // the operands (including the unsigned comparisons!).  Zero extend is
4290        // usually a simpler/cheaper operation, so prefer it.
4291        Tmp1 = DAG.getZeroExtendInReg(Tmp1, VT);
4292        Tmp2 = DAG.getZeroExtendInReg(Tmp2, VT);
4293        break;
4294      case ISD::SETGE:
4295      case ISD::SETGT:
4296      case ISD::SETLT:
4297      case ISD::SETLE:
4298        Tmp1 = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Tmp1,
4299                           DAG.getValueType(VT));
4300        Tmp2 = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Tmp2,
4301                           DAG.getValueType(VT));
4302        break;
4303      }
4304    }
4305    break;
4306  case Expand: {
4307    MVT::ValueType VT = LHS.getValueType();
4308    if (VT == MVT::f32 || VT == MVT::f64) {
4309      // Expand into one or more soft-fp libcall(s).
4310      RTLIB::Libcall LC1, LC2 = RTLIB::UNKNOWN_LIBCALL;
4311      switch (cast<CondCodeSDNode>(CC)->get()) {
4312      case ISD::SETEQ:
4313      case ISD::SETOEQ:
4314        LC1 = (VT == MVT::f32) ? RTLIB::OEQ_F32 : RTLIB::OEQ_F64;
4315        break;
4316      case ISD::SETNE:
4317      case ISD::SETUNE:
4318        LC1 = (VT == MVT::f32) ? RTLIB::UNE_F32 : RTLIB::UNE_F64;
4319        break;
4320      case ISD::SETGE:
4321      case ISD::SETOGE:
4322        LC1 = (VT == MVT::f32) ? RTLIB::OGE_F32 : RTLIB::OGE_F64;
4323        break;
4324      case ISD::SETLT:
4325      case ISD::SETOLT:
4326        LC1 = (VT == MVT::f32) ? RTLIB::OLT_F32 : RTLIB::OLT_F64;
4327        break;
4328      case ISD::SETLE:
4329      case ISD::SETOLE:
4330        LC1 = (VT == MVT::f32) ? RTLIB::OLE_F32 : RTLIB::OLE_F64;
4331        break;
4332      case ISD::SETGT:
4333      case ISD::SETOGT:
4334        LC1 = (VT == MVT::f32) ? RTLIB::OGT_F32 : RTLIB::OGT_F64;
4335        break;
4336      case ISD::SETUO:
4337        LC1 = (VT == MVT::f32) ? RTLIB::UO_F32 : RTLIB::UO_F64;
4338        break;
4339      case ISD::SETO:
4340        LC1 = (VT == MVT::f32) ? RTLIB::O_F32 : RTLIB::O_F64;
4341        break;
4342      default:
4343        LC1 = (VT == MVT::f32) ? RTLIB::UO_F32 : RTLIB::UO_F64;
4344        switch (cast<CondCodeSDNode>(CC)->get()) {
4345        case ISD::SETONE:
4346          // SETONE = SETOLT | SETOGT
4347          LC1 = (VT == MVT::f32) ? RTLIB::OLT_F32 : RTLIB::OLT_F64;
4348          // Fallthrough
4349        case ISD::SETUGT:
4350          LC2 = (VT == MVT::f32) ? RTLIB::OGT_F32 : RTLIB::OGT_F64;
4351          break;
4352        case ISD::SETUGE:
4353          LC2 = (VT == MVT::f32) ? RTLIB::OGE_F32 : RTLIB::OGE_F64;
4354          break;
4355        case ISD::SETULT:
4356          LC2 = (VT == MVT::f32) ? RTLIB::OLT_F32 : RTLIB::OLT_F64;
4357          break;
4358        case ISD::SETULE:
4359          LC2 = (VT == MVT::f32) ? RTLIB::OLE_F32 : RTLIB::OLE_F64;
4360          break;
4361        case ISD::SETUEQ:
4362          LC2 = (VT == MVT::f32) ? RTLIB::OEQ_F32 : RTLIB::OEQ_F64;
4363          break;
4364        default: assert(0 && "Unsupported FP setcc!");
4365        }
4366      }
4367
4368      SDOperand Dummy;
4369      Tmp1 = ExpandLibCall(TLI.getLibcallName(LC1),
4370                           DAG.getNode(ISD::MERGE_VALUES, VT, LHS, RHS).Val,
4371                           false /*sign irrelevant*/, Dummy);
4372      Tmp2 = DAG.getConstant(0, MVT::i32);
4373      CC = DAG.getCondCode(TLI.getCmpLibcallCC(LC1));
4374      if (LC2 != RTLIB::UNKNOWN_LIBCALL) {
4375        Tmp1 = DAG.getNode(ISD::SETCC, TLI.getSetCCResultTy(), Tmp1, Tmp2, CC);
4376        LHS = ExpandLibCall(TLI.getLibcallName(LC2),
4377                            DAG.getNode(ISD::MERGE_VALUES, VT, LHS, RHS).Val,
4378                            false /*sign irrelevant*/, Dummy);
4379        Tmp2 = DAG.getNode(ISD::SETCC, TLI.getSetCCResultTy(), LHS, Tmp2,
4380                           DAG.getCondCode(TLI.getCmpLibcallCC(LC2)));
4381        Tmp1 = DAG.getNode(ISD::OR, Tmp1.getValueType(), Tmp1, Tmp2);
4382        Tmp2 = SDOperand();
4383      }
4384      LHS = Tmp1;
4385      RHS = Tmp2;
4386      return;
4387    }
4388
4389    SDOperand LHSLo, LHSHi, RHSLo, RHSHi;
4390    ExpandOp(LHS, LHSLo, LHSHi);
4391    ExpandOp(RHS, RHSLo, RHSHi);
4392    ISD::CondCode CCCode = cast<CondCodeSDNode>(CC)->get();
4393
4394    if (VT==MVT::ppcf128) {
4395      // FIXME:  This generated code sucks.  We want to generate
4396      //         FCMP crN, hi1, hi2
4397      //         BNE crN, L:
4398      //         FCMP crN, lo1, lo2
4399      // The following can be improved, but not that much.
4400      Tmp1 = DAG.getSetCC(TLI.getSetCCResultTy(), LHSHi, RHSHi, ISD::SETEQ);
4401      Tmp2 = DAG.getSetCC(TLI.getSetCCResultTy(), LHSLo, RHSLo, CCCode);
4402      Tmp3 = DAG.getNode(ISD::AND, Tmp1.getValueType(), Tmp1, Tmp2);
4403      Tmp1 = DAG.getSetCC(TLI.getSetCCResultTy(), LHSHi, RHSHi, ISD::SETNE);
4404      Tmp2 = DAG.getSetCC(TLI.getSetCCResultTy(), LHSHi, RHSHi, CCCode);
4405      Tmp1 = DAG.getNode(ISD::AND, Tmp1.getValueType(), Tmp1, Tmp2);
4406      Tmp1 = DAG.getNode(ISD::OR, Tmp1.getValueType(), Tmp1, Tmp3);
4407      Tmp2 = SDOperand();
4408      break;
4409    }
4410
4411    switch (CCCode) {
4412    case ISD::SETEQ:
4413    case ISD::SETNE:
4414      if (RHSLo == RHSHi)
4415        if (ConstantSDNode *RHSCST = dyn_cast<ConstantSDNode>(RHSLo))
4416          if (RHSCST->isAllOnesValue()) {
4417            // Comparison to -1.
4418            Tmp1 = DAG.getNode(ISD::AND, LHSLo.getValueType(), LHSLo, LHSHi);
4419            Tmp2 = RHSLo;
4420            break;
4421          }
4422
4423      Tmp1 = DAG.getNode(ISD::XOR, LHSLo.getValueType(), LHSLo, RHSLo);
4424      Tmp2 = DAG.getNode(ISD::XOR, LHSLo.getValueType(), LHSHi, RHSHi);
4425      Tmp1 = DAG.getNode(ISD::OR, Tmp1.getValueType(), Tmp1, Tmp2);
4426      Tmp2 = DAG.getConstant(0, Tmp1.getValueType());
4427      break;
4428    default:
4429      // If this is a comparison of the sign bit, just look at the top part.
4430      // X > -1,  x < 0
4431      if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(RHS))
4432        if ((cast<CondCodeSDNode>(CC)->get() == ISD::SETLT &&
4433             CST->getValue() == 0) ||             // X < 0
4434            (cast<CondCodeSDNode>(CC)->get() == ISD::SETGT &&
4435             CST->isAllOnesValue())) {            // X > -1
4436          Tmp1 = LHSHi;
4437          Tmp2 = RHSHi;
4438          break;
4439        }
4440
4441      // FIXME: This generated code sucks.
4442      ISD::CondCode LowCC;
4443      switch (CCCode) {
4444      default: assert(0 && "Unknown integer setcc!");
4445      case ISD::SETLT:
4446      case ISD::SETULT: LowCC = ISD::SETULT; break;
4447      case ISD::SETGT:
4448      case ISD::SETUGT: LowCC = ISD::SETUGT; break;
4449      case ISD::SETLE:
4450      case ISD::SETULE: LowCC = ISD::SETULE; break;
4451      case ISD::SETGE:
4452      case ISD::SETUGE: LowCC = ISD::SETUGE; break;
4453      }
4454
4455      // Tmp1 = lo(op1) < lo(op2)   // Always unsigned comparison
4456      // Tmp2 = hi(op1) < hi(op2)   // Signedness depends on operands
4457      // dest = hi(op1) == hi(op2) ? Tmp1 : Tmp2;
4458
4459      // NOTE: on targets without efficient SELECT of bools, we can always use
4460      // this identity: (B1 ? B2 : B3) --> (B1 & B2)|(!B1&B3)
4461      TargetLowering::DAGCombinerInfo DagCombineInfo(DAG, false, true, NULL);
4462      Tmp1 = TLI.SimplifySetCC(TLI.getSetCCResultTy(), LHSLo, RHSLo, LowCC,
4463                               false, DagCombineInfo);
4464      if (!Tmp1.Val)
4465        Tmp1 = DAG.getSetCC(TLI.getSetCCResultTy(), LHSLo, RHSLo, LowCC);
4466      Tmp2 = TLI.SimplifySetCC(TLI.getSetCCResultTy(), LHSHi, RHSHi,
4467                               CCCode, false, DagCombineInfo);
4468      if (!Tmp2.Val)
4469        Tmp2 = DAG.getNode(ISD::SETCC, TLI.getSetCCResultTy(), LHSHi, RHSHi,CC);
4470
4471      ConstantSDNode *Tmp1C = dyn_cast<ConstantSDNode>(Tmp1.Val);
4472      ConstantSDNode *Tmp2C = dyn_cast<ConstantSDNode>(Tmp2.Val);
4473      if ((Tmp1C && Tmp1C->getValue() == 0) ||
4474          (Tmp2C && Tmp2C->getValue() == 0 &&
4475           (CCCode == ISD::SETLE || CCCode == ISD::SETGE ||
4476            CCCode == ISD::SETUGE || CCCode == ISD::SETULE)) ||
4477          (Tmp2C && Tmp2C->getValue() == 1 &&
4478           (CCCode == ISD::SETLT || CCCode == ISD::SETGT ||
4479            CCCode == ISD::SETUGT || CCCode == ISD::SETULT))) {
4480        // low part is known false, returns high part.
4481        // For LE / GE, if high part is known false, ignore the low part.
4482        // For LT / GT, if high part is known true, ignore the low part.
4483        Tmp1 = Tmp2;
4484        Tmp2 = SDOperand();
4485      } else {
4486        Result = TLI.SimplifySetCC(TLI.getSetCCResultTy(), LHSHi, RHSHi,
4487                                   ISD::SETEQ, false, DagCombineInfo);
4488        if (!Result.Val)
4489          Result=DAG.getSetCC(TLI.getSetCCResultTy(), LHSHi, RHSHi, ISD::SETEQ);
4490        Result = LegalizeOp(DAG.getNode(ISD::SELECT, Tmp1.getValueType(),
4491                                        Result, Tmp1, Tmp2));
4492        Tmp1 = Result;
4493        Tmp2 = SDOperand();
4494      }
4495    }
4496  }
4497  }
4498  LHS = Tmp1;
4499  RHS = Tmp2;
4500}
4501
4502/// ExpandBIT_CONVERT - Expand a BIT_CONVERT node into a store/load combination.
4503/// The resultant code need not be legal.  Note that SrcOp is the input operand
4504/// to the BIT_CONVERT, not the BIT_CONVERT node itself.
4505SDOperand SelectionDAGLegalize::ExpandBIT_CONVERT(MVT::ValueType DestVT,
4506                                                  SDOperand SrcOp) {
4507  // Create the stack frame object.
4508  SDOperand FIPtr = DAG.CreateStackTemporary(DestVT);
4509
4510  // Emit a store to the stack slot.
4511  SDOperand Store = DAG.getStore(DAG.getEntryNode(), SrcOp, FIPtr, NULL, 0);
4512  // Result is a load from the stack slot.
4513  return DAG.getLoad(DestVT, Store, FIPtr, NULL, 0);
4514}
4515
4516SDOperand SelectionDAGLegalize::ExpandSCALAR_TO_VECTOR(SDNode *Node) {
4517  // Create a vector sized/aligned stack slot, store the value to element #0,
4518  // then load the whole vector back out.
4519  SDOperand StackPtr = DAG.CreateStackTemporary(Node->getValueType(0));
4520  SDOperand Ch = DAG.getStore(DAG.getEntryNode(), Node->getOperand(0), StackPtr,
4521                              NULL, 0);
4522  return DAG.getLoad(Node->getValueType(0), Ch, StackPtr, NULL, 0);
4523}
4524
4525
4526/// ExpandBUILD_VECTOR - Expand a BUILD_VECTOR node on targets that don't
4527/// support the operation, but do support the resultant vector type.
4528SDOperand SelectionDAGLegalize::ExpandBUILD_VECTOR(SDNode *Node) {
4529
4530  // If the only non-undef value is the low element, turn this into a
4531  // SCALAR_TO_VECTOR node.  If this is { X, X, X, X }, determine X.
4532  unsigned NumElems = Node->getNumOperands();
4533  bool isOnlyLowElement = true;
4534  SDOperand SplatValue = Node->getOperand(0);
4535  std::map<SDOperand, std::vector<unsigned> > Values;
4536  Values[SplatValue].push_back(0);
4537  bool isConstant = true;
4538  if (!isa<ConstantFPSDNode>(SplatValue) && !isa<ConstantSDNode>(SplatValue) &&
4539      SplatValue.getOpcode() != ISD::UNDEF)
4540    isConstant = false;
4541
4542  for (unsigned i = 1; i < NumElems; ++i) {
4543    SDOperand V = Node->getOperand(i);
4544    Values[V].push_back(i);
4545    if (V.getOpcode() != ISD::UNDEF)
4546      isOnlyLowElement = false;
4547    if (SplatValue != V)
4548      SplatValue = SDOperand(0,0);
4549
4550    // If this isn't a constant element or an undef, we can't use a constant
4551    // pool load.
4552    if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V) &&
4553        V.getOpcode() != ISD::UNDEF)
4554      isConstant = false;
4555  }
4556
4557  if (isOnlyLowElement) {
4558    // If the low element is an undef too, then this whole things is an undef.
4559    if (Node->getOperand(0).getOpcode() == ISD::UNDEF)
4560      return DAG.getNode(ISD::UNDEF, Node->getValueType(0));
4561    // Otherwise, turn this into a scalar_to_vector node.
4562    return DAG.getNode(ISD::SCALAR_TO_VECTOR, Node->getValueType(0),
4563                       Node->getOperand(0));
4564  }
4565
4566  // If all elements are constants, create a load from the constant pool.
4567  if (isConstant) {
4568    MVT::ValueType VT = Node->getValueType(0);
4569    const Type *OpNTy =
4570      MVT::getTypeForValueType(Node->getOperand(0).getValueType());
4571    std::vector<Constant*> CV;
4572    for (unsigned i = 0, e = NumElems; i != e; ++i) {
4573      if (ConstantFPSDNode *V =
4574          dyn_cast<ConstantFPSDNode>(Node->getOperand(i))) {
4575        CV.push_back(ConstantFP::get(OpNTy, V->getValueAPF()));
4576      } else if (ConstantSDNode *V =
4577                 dyn_cast<ConstantSDNode>(Node->getOperand(i))) {
4578        CV.push_back(ConstantInt::get(OpNTy, V->getValue()));
4579      } else {
4580        assert(Node->getOperand(i).getOpcode() == ISD::UNDEF);
4581        CV.push_back(UndefValue::get(OpNTy));
4582      }
4583    }
4584    Constant *CP = ConstantVector::get(CV);
4585    SDOperand CPIdx = DAG.getConstantPool(CP, TLI.getPointerTy());
4586    return DAG.getLoad(VT, DAG.getEntryNode(), CPIdx, NULL, 0);
4587  }
4588
4589  if (SplatValue.Val) {   // Splat of one value?
4590    // Build the shuffle constant vector: <0, 0, 0, 0>
4591    MVT::ValueType MaskVT =
4592      MVT::getIntVectorWithNumElements(NumElems);
4593    SDOperand Zero = DAG.getConstant(0, MVT::getVectorElementType(MaskVT));
4594    std::vector<SDOperand> ZeroVec(NumElems, Zero);
4595    SDOperand SplatMask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
4596                                      &ZeroVec[0], ZeroVec.size());
4597
4598    // If the target supports VECTOR_SHUFFLE and this shuffle mask, use it.
4599    if (isShuffleLegal(Node->getValueType(0), SplatMask)) {
4600      // Get the splatted value into the low element of a vector register.
4601      SDOperand LowValVec =
4602        DAG.getNode(ISD::SCALAR_TO_VECTOR, Node->getValueType(0), SplatValue);
4603
4604      // Return shuffle(LowValVec, undef, <0,0,0,0>)
4605      return DAG.getNode(ISD::VECTOR_SHUFFLE, Node->getValueType(0), LowValVec,
4606                         DAG.getNode(ISD::UNDEF, Node->getValueType(0)),
4607                         SplatMask);
4608    }
4609  }
4610
4611  // If there are only two unique elements, we may be able to turn this into a
4612  // vector shuffle.
4613  if (Values.size() == 2) {
4614    // Build the shuffle constant vector: e.g. <0, 4, 0, 4>
4615    MVT::ValueType MaskVT =
4616      MVT::getIntVectorWithNumElements(NumElems);
4617    std::vector<SDOperand> MaskVec(NumElems);
4618    unsigned i = 0;
4619    for (std::map<SDOperand,std::vector<unsigned> >::iterator I=Values.begin(),
4620           E = Values.end(); I != E; ++I) {
4621      for (std::vector<unsigned>::iterator II = I->second.begin(),
4622             EE = I->second.end(); II != EE; ++II)
4623        MaskVec[*II] = DAG.getConstant(i, MVT::getVectorElementType(MaskVT));
4624      i += NumElems;
4625    }
4626    SDOperand ShuffleMask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
4627                                        &MaskVec[0], MaskVec.size());
4628
4629    // If the target supports VECTOR_SHUFFLE and this shuffle mask, use it.
4630    if (TLI.isOperationLegal(ISD::SCALAR_TO_VECTOR, Node->getValueType(0)) &&
4631        isShuffleLegal(Node->getValueType(0), ShuffleMask)) {
4632      SmallVector<SDOperand, 8> Ops;
4633      for(std::map<SDOperand,std::vector<unsigned> >::iterator I=Values.begin(),
4634            E = Values.end(); I != E; ++I) {
4635        SDOperand Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, Node->getValueType(0),
4636                                   I->first);
4637        Ops.push_back(Op);
4638      }
4639      Ops.push_back(ShuffleMask);
4640
4641      // Return shuffle(LoValVec, HiValVec, <0,1,0,1>)
4642      return DAG.getNode(ISD::VECTOR_SHUFFLE, Node->getValueType(0),
4643                         &Ops[0], Ops.size());
4644    }
4645  }
4646
4647  // Otherwise, we can't handle this case efficiently.  Allocate a sufficiently
4648  // aligned object on the stack, store each element into it, then load
4649  // the result as a vector.
4650  MVT::ValueType VT = Node->getValueType(0);
4651  // Create the stack frame object.
4652  SDOperand FIPtr = DAG.CreateStackTemporary(VT);
4653
4654  // Emit a store of each element to the stack slot.
4655  SmallVector<SDOperand, 8> Stores;
4656  unsigned TypeByteSize =
4657    MVT::getSizeInBits(Node->getOperand(0).getValueType())/8;
4658  // Store (in the right endianness) the elements to memory.
4659  for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) {
4660    // Ignore undef elements.
4661    if (Node->getOperand(i).getOpcode() == ISD::UNDEF) continue;
4662
4663    unsigned Offset = TypeByteSize*i;
4664
4665    SDOperand Idx = DAG.getConstant(Offset, FIPtr.getValueType());
4666    Idx = DAG.getNode(ISD::ADD, FIPtr.getValueType(), FIPtr, Idx);
4667
4668    Stores.push_back(DAG.getStore(DAG.getEntryNode(), Node->getOperand(i), Idx,
4669                                  NULL, 0));
4670  }
4671
4672  SDOperand StoreChain;
4673  if (!Stores.empty())    // Not all undef elements?
4674    StoreChain = DAG.getNode(ISD::TokenFactor, MVT::Other,
4675                             &Stores[0], Stores.size());
4676  else
4677    StoreChain = DAG.getEntryNode();
4678
4679  // Result is a load from the stack slot.
4680  return DAG.getLoad(VT, StoreChain, FIPtr, NULL, 0);
4681}
4682
4683void SelectionDAGLegalize::ExpandShiftParts(unsigned NodeOp,
4684                                            SDOperand Op, SDOperand Amt,
4685                                            SDOperand &Lo, SDOperand &Hi) {
4686  // Expand the subcomponents.
4687  SDOperand LHSL, LHSH;
4688  ExpandOp(Op, LHSL, LHSH);
4689
4690  SDOperand Ops[] = { LHSL, LHSH, Amt };
4691  MVT::ValueType VT = LHSL.getValueType();
4692  Lo = DAG.getNode(NodeOp, DAG.getNodeValueTypes(VT, VT), 2, Ops, 3);
4693  Hi = Lo.getValue(1);
4694}
4695
4696
4697/// ExpandShift - Try to find a clever way to expand this shift operation out to
4698/// smaller elements.  If we can't find a way that is more efficient than a
4699/// libcall on this target, return false.  Otherwise, return true with the
4700/// low-parts expanded into Lo and Hi.
4701bool SelectionDAGLegalize::ExpandShift(unsigned Opc, SDOperand Op,SDOperand Amt,
4702                                       SDOperand &Lo, SDOperand &Hi) {
4703  assert((Opc == ISD::SHL || Opc == ISD::SRA || Opc == ISD::SRL) &&
4704         "This is not a shift!");
4705
4706  MVT::ValueType NVT = TLI.getTypeToTransformTo(Op.getValueType());
4707  SDOperand ShAmt = LegalizeOp(Amt);
4708  MVT::ValueType ShTy = ShAmt.getValueType();
4709  unsigned VTBits = MVT::getSizeInBits(Op.getValueType());
4710  unsigned NVTBits = MVT::getSizeInBits(NVT);
4711
4712  // Handle the case when Amt is an immediate.
4713  if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Amt.Val)) {
4714    unsigned Cst = CN->getValue();
4715    // Expand the incoming operand to be shifted, so that we have its parts
4716    SDOperand InL, InH;
4717    ExpandOp(Op, InL, InH);
4718    switch(Opc) {
4719    case ISD::SHL:
4720      if (Cst > VTBits) {
4721        Lo = DAG.getConstant(0, NVT);
4722        Hi = DAG.getConstant(0, NVT);
4723      } else if (Cst > NVTBits) {
4724        Lo = DAG.getConstant(0, NVT);
4725        Hi = DAG.getNode(ISD::SHL, NVT, InL, DAG.getConstant(Cst-NVTBits,ShTy));
4726      } else if (Cst == NVTBits) {
4727        Lo = DAG.getConstant(0, NVT);
4728        Hi = InL;
4729      } else {
4730        Lo = DAG.getNode(ISD::SHL, NVT, InL, DAG.getConstant(Cst, ShTy));
4731        Hi = DAG.getNode(ISD::OR, NVT,
4732           DAG.getNode(ISD::SHL, NVT, InH, DAG.getConstant(Cst, ShTy)),
4733           DAG.getNode(ISD::SRL, NVT, InL, DAG.getConstant(NVTBits-Cst, ShTy)));
4734      }
4735      return true;
4736    case ISD::SRL:
4737      if (Cst > VTBits) {
4738        Lo = DAG.getConstant(0, NVT);
4739        Hi = DAG.getConstant(0, NVT);
4740      } else if (Cst > NVTBits) {
4741        Lo = DAG.getNode(ISD::SRL, NVT, InH, DAG.getConstant(Cst-NVTBits,ShTy));
4742        Hi = DAG.getConstant(0, NVT);
4743      } else if (Cst == NVTBits) {
4744        Lo = InH;
4745        Hi = DAG.getConstant(0, NVT);
4746      } else {
4747        Lo = DAG.getNode(ISD::OR, NVT,
4748           DAG.getNode(ISD::SRL, NVT, InL, DAG.getConstant(Cst, ShTy)),
4749           DAG.getNode(ISD::SHL, NVT, InH, DAG.getConstant(NVTBits-Cst, ShTy)));
4750        Hi = DAG.getNode(ISD::SRL, NVT, InH, DAG.getConstant(Cst, ShTy));
4751      }
4752      return true;
4753    case ISD::SRA:
4754      if (Cst > VTBits) {
4755        Hi = Lo = DAG.getNode(ISD::SRA, NVT, InH,
4756                              DAG.getConstant(NVTBits-1, ShTy));
4757      } else if (Cst > NVTBits) {
4758        Lo = DAG.getNode(ISD::SRA, NVT, InH,
4759                           DAG.getConstant(Cst-NVTBits, ShTy));
4760        Hi = DAG.getNode(ISD::SRA, NVT, InH,
4761                              DAG.getConstant(NVTBits-1, ShTy));
4762      } else if (Cst == NVTBits) {
4763        Lo = InH;
4764        Hi = DAG.getNode(ISD::SRA, NVT, InH,
4765                              DAG.getConstant(NVTBits-1, ShTy));
4766      } else {
4767        Lo = DAG.getNode(ISD::OR, NVT,
4768           DAG.getNode(ISD::SRL, NVT, InL, DAG.getConstant(Cst, ShTy)),
4769           DAG.getNode(ISD::SHL, NVT, InH, DAG.getConstant(NVTBits-Cst, ShTy)));
4770        Hi = DAG.getNode(ISD::SRA, NVT, InH, DAG.getConstant(Cst, ShTy));
4771      }
4772      return true;
4773    }
4774  }
4775
4776  // Okay, the shift amount isn't constant.  However, if we can tell that it is
4777  // >= 32 or < 32, we can still simplify it, without knowing the actual value.
4778  uint64_t Mask = NVTBits, KnownZero, KnownOne;
4779  DAG.ComputeMaskedBits(Amt, Mask, KnownZero, KnownOne);
4780
4781  // If we know that the high bit of the shift amount is one, then we can do
4782  // this as a couple of simple shifts.
4783  if (KnownOne & Mask) {
4784    // Mask out the high bit, which we know is set.
4785    Amt = DAG.getNode(ISD::AND, Amt.getValueType(), Amt,
4786                      DAG.getConstant(NVTBits-1, Amt.getValueType()));
4787
4788    // Expand the incoming operand to be shifted, so that we have its parts
4789    SDOperand InL, InH;
4790    ExpandOp(Op, InL, InH);
4791    switch(Opc) {
4792    case ISD::SHL:
4793      Lo = DAG.getConstant(0, NVT);              // Low part is zero.
4794      Hi = DAG.getNode(ISD::SHL, NVT, InL, Amt); // High part from Lo part.
4795      return true;
4796    case ISD::SRL:
4797      Hi = DAG.getConstant(0, NVT);              // Hi part is zero.
4798      Lo = DAG.getNode(ISD::SRL, NVT, InH, Amt); // Lo part from Hi part.
4799      return true;
4800    case ISD::SRA:
4801      Hi = DAG.getNode(ISD::SRA, NVT, InH,       // Sign extend high part.
4802                       DAG.getConstant(NVTBits-1, Amt.getValueType()));
4803      Lo = DAG.getNode(ISD::SRA, NVT, InH, Amt); // Lo part from Hi part.
4804      return true;
4805    }
4806  }
4807
4808  // If we know that the high bit of the shift amount is zero, then we can do
4809  // this as a couple of simple shifts.
4810  if (KnownZero & Mask) {
4811    // Compute 32-amt.
4812    SDOperand Amt2 = DAG.getNode(ISD::SUB, Amt.getValueType(),
4813                                 DAG.getConstant(NVTBits, Amt.getValueType()),
4814                                 Amt);
4815
4816    // Expand the incoming operand to be shifted, so that we have its parts
4817    SDOperand InL, InH;
4818    ExpandOp(Op, InL, InH);
4819    switch(Opc) {
4820    case ISD::SHL:
4821      Lo = DAG.getNode(ISD::SHL, NVT, InL, Amt);
4822      Hi = DAG.getNode(ISD::OR, NVT,
4823                       DAG.getNode(ISD::SHL, NVT, InH, Amt),
4824                       DAG.getNode(ISD::SRL, NVT, InL, Amt2));
4825      return true;
4826    case ISD::SRL:
4827      Hi = DAG.getNode(ISD::SRL, NVT, InH, Amt);
4828      Lo = DAG.getNode(ISD::OR, NVT,
4829                       DAG.getNode(ISD::SRL, NVT, InL, Amt),
4830                       DAG.getNode(ISD::SHL, NVT, InH, Amt2));
4831      return true;
4832    case ISD::SRA:
4833      Hi = DAG.getNode(ISD::SRA, NVT, InH, Amt);
4834      Lo = DAG.getNode(ISD::OR, NVT,
4835                       DAG.getNode(ISD::SRL, NVT, InL, Amt),
4836                       DAG.getNode(ISD::SHL, NVT, InH, Amt2));
4837      return true;
4838    }
4839  }
4840
4841  return false;
4842}
4843
4844
4845// ExpandLibCall - Expand a node into a call to a libcall.  If the result value
4846// does not fit into a register, return the lo part and set the hi part to the
4847// by-reg argument.  If it does fit into a single register, return the result
4848// and leave the Hi part unset.
4849SDOperand SelectionDAGLegalize::ExpandLibCall(const char *Name, SDNode *Node,
4850                                              bool isSigned, SDOperand &Hi) {
4851  assert(!IsLegalizingCall && "Cannot overlap legalization of calls!");
4852  // The input chain to this libcall is the entry node of the function.
4853  // Legalizing the call will automatically add the previous call to the
4854  // dependence.
4855  SDOperand InChain = DAG.getEntryNode();
4856
4857  TargetLowering::ArgListTy Args;
4858  TargetLowering::ArgListEntry Entry;
4859  for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) {
4860    MVT::ValueType ArgVT = Node->getOperand(i).getValueType();
4861    const Type *ArgTy = MVT::getTypeForValueType(ArgVT);
4862    Entry.Node = Node->getOperand(i); Entry.Ty = ArgTy;
4863    Entry.isSExt = isSigned;
4864    Args.push_back(Entry);
4865  }
4866  SDOperand Callee = DAG.getExternalSymbol(Name, TLI.getPointerTy());
4867
4868  // Splice the libcall in wherever FindInputOutputChains tells us to.
4869  const Type *RetTy = MVT::getTypeForValueType(Node->getValueType(0));
4870  std::pair<SDOperand,SDOperand> CallInfo =
4871    TLI.LowerCallTo(InChain, RetTy, isSigned, false, CallingConv::C, false,
4872                    Callee, Args, DAG);
4873
4874  // Legalize the call sequence, starting with the chain.  This will advance
4875  // the LastCALLSEQ_END to the legalized version of the CALLSEQ_END node that
4876  // was added by LowerCallTo (guaranteeing proper serialization of calls).
4877  LegalizeOp(CallInfo.second);
4878  SDOperand Result;
4879  switch (getTypeAction(CallInfo.first.getValueType())) {
4880  default: assert(0 && "Unknown thing");
4881  case Legal:
4882    Result = CallInfo.first;
4883    break;
4884  case Expand:
4885    ExpandOp(CallInfo.first, Result, Hi);
4886    break;
4887  }
4888  return Result;
4889}
4890
4891
4892/// ExpandIntToFP - Expand a [US]INT_TO_FP operation.
4893///
4894SDOperand SelectionDAGLegalize::
4895ExpandIntToFP(bool isSigned, MVT::ValueType DestTy, SDOperand Source) {
4896  assert(getTypeAction(Source.getValueType()) == Expand &&
4897         "This is not an expansion!");
4898  assert(Source.getValueType() == MVT::i64 && "Only handle expand from i64!");
4899
4900  if (!isSigned) {
4901    assert(Source.getValueType() == MVT::i64 &&
4902           "This only works for 64-bit -> FP");
4903    // The 64-bit value loaded will be incorrectly if the 'sign bit' of the
4904    // incoming integer is set.  To handle this, we dynamically test to see if
4905    // it is set, and, if so, add a fudge factor.
4906    SDOperand Lo, Hi;
4907    ExpandOp(Source, Lo, Hi);
4908
4909    // If this is unsigned, and not supported, first perform the conversion to
4910    // signed, then adjust the result if the sign bit is set.
4911    SDOperand SignedConv = ExpandIntToFP(true, DestTy,
4912                   DAG.getNode(ISD::BUILD_PAIR, Source.getValueType(), Lo, Hi));
4913
4914    SDOperand SignSet = DAG.getSetCC(TLI.getSetCCResultTy(), Hi,
4915                                     DAG.getConstant(0, Hi.getValueType()),
4916                                     ISD::SETLT);
4917    SDOperand Zero = getIntPtrConstant(0), Four = getIntPtrConstant(4);
4918    SDOperand CstOffset = DAG.getNode(ISD::SELECT, Zero.getValueType(),
4919                                      SignSet, Four, Zero);
4920    uint64_t FF = 0x5f800000ULL;
4921    if (TLI.isLittleEndian()) FF <<= 32;
4922    static Constant *FudgeFactor = ConstantInt::get(Type::Int64Ty, FF);
4923
4924    SDOperand CPIdx = DAG.getConstantPool(FudgeFactor, TLI.getPointerTy());
4925    CPIdx = DAG.getNode(ISD::ADD, TLI.getPointerTy(), CPIdx, CstOffset);
4926    SDOperand FudgeInReg;
4927    if (DestTy == MVT::f32)
4928      FudgeInReg = DAG.getLoad(MVT::f32, DAG.getEntryNode(), CPIdx, NULL, 0);
4929    else if (MVT::getSizeInBits(DestTy) > MVT::getSizeInBits(MVT::f32))
4930      // FIXME: Avoid the extend by construction the right constantpool?
4931      FudgeInReg = DAG.getExtLoad(ISD::EXTLOAD, DestTy, DAG.getEntryNode(),
4932                                  CPIdx, NULL, 0, MVT::f32);
4933    else
4934      assert(0 && "Unexpected conversion");
4935
4936    MVT::ValueType SCVT = SignedConv.getValueType();
4937    if (SCVT != DestTy) {
4938      // Destination type needs to be expanded as well. The FADD now we are
4939      // constructing will be expanded into a libcall.
4940      if (MVT::getSizeInBits(SCVT) != MVT::getSizeInBits(DestTy)) {
4941        assert(SCVT == MVT::i32 && DestTy == MVT::f64);
4942        SignedConv = DAG.getNode(ISD::BUILD_PAIR, MVT::i64,
4943                                 SignedConv, SignedConv.getValue(1));
4944      }
4945      SignedConv = DAG.getNode(ISD::BIT_CONVERT, DestTy, SignedConv);
4946    }
4947    return DAG.getNode(ISD::FADD, DestTy, SignedConv, FudgeInReg);
4948  }
4949
4950  // Check to see if the target has a custom way to lower this.  If so, use it.
4951  switch (TLI.getOperationAction(ISD::SINT_TO_FP, Source.getValueType())) {
4952  default: assert(0 && "This action not implemented for this operation!");
4953  case TargetLowering::Legal:
4954  case TargetLowering::Expand:
4955    break;   // This case is handled below.
4956  case TargetLowering::Custom: {
4957    SDOperand NV = TLI.LowerOperation(DAG.getNode(ISD::SINT_TO_FP, DestTy,
4958                                                  Source), DAG);
4959    if (NV.Val)
4960      return LegalizeOp(NV);
4961    break;   // The target decided this was legal after all
4962  }
4963  }
4964
4965  // Expand the source, then glue it back together for the call.  We must expand
4966  // the source in case it is shared (this pass of legalize must traverse it).
4967  SDOperand SrcLo, SrcHi;
4968  ExpandOp(Source, SrcLo, SrcHi);
4969  Source = DAG.getNode(ISD::BUILD_PAIR, Source.getValueType(), SrcLo, SrcHi);
4970
4971  RTLIB::Libcall LC;
4972  if (DestTy == MVT::f32)
4973    LC = RTLIB::SINTTOFP_I64_F32;
4974  else {
4975    assert(DestTy == MVT::f64 && "Unknown fp value type!");
4976    LC = RTLIB::SINTTOFP_I64_F64;
4977  }
4978
4979  assert(TLI.getLibcallName(LC) && "Don't know how to expand this SINT_TO_FP!");
4980  Source = DAG.getNode(ISD::SINT_TO_FP, DestTy, Source);
4981  SDOperand UnusedHiPart;
4982  return ExpandLibCall(TLI.getLibcallName(LC), Source.Val, isSigned,
4983                       UnusedHiPart);
4984}
4985
4986/// ExpandLegalINT_TO_FP - This function is responsible for legalizing a
4987/// INT_TO_FP operation of the specified operand when the target requests that
4988/// we expand it.  At this point, we know that the result and operand types are
4989/// legal for the target.
4990SDOperand SelectionDAGLegalize::ExpandLegalINT_TO_FP(bool isSigned,
4991                                                     SDOperand Op0,
4992                                                     MVT::ValueType DestVT) {
4993  if (Op0.getValueType() == MVT::i32) {
4994    // simple 32-bit [signed|unsigned] integer to float/double expansion
4995
4996    // get the stack frame index of a 8 byte buffer, pessimistically aligned
4997    MachineFunction &MF = DAG.getMachineFunction();
4998    const Type *F64Type = MVT::getTypeForValueType(MVT::f64);
4999    unsigned StackAlign =
5000      (unsigned)TLI.getTargetData()->getPrefTypeAlignment(F64Type);
5001    int SSFI = MF.getFrameInfo()->CreateStackObject(8, StackAlign);
5002    // get address of 8 byte buffer
5003    SDOperand StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
5004    // word offset constant for Hi/Lo address computation
5005    SDOperand WordOff = DAG.getConstant(sizeof(int), TLI.getPointerTy());
5006    // set up Hi and Lo (into buffer) address based on endian
5007    SDOperand Hi = StackSlot;
5008    SDOperand Lo = DAG.getNode(ISD::ADD, TLI.getPointerTy(), StackSlot,WordOff);
5009    if (TLI.isLittleEndian())
5010      std::swap(Hi, Lo);
5011
5012    // if signed map to unsigned space
5013    SDOperand Op0Mapped;
5014    if (isSigned) {
5015      // constant used to invert sign bit (signed to unsigned mapping)
5016      SDOperand SignBit = DAG.getConstant(0x80000000u, MVT::i32);
5017      Op0Mapped = DAG.getNode(ISD::XOR, MVT::i32, Op0, SignBit);
5018    } else {
5019      Op0Mapped = Op0;
5020    }
5021    // store the lo of the constructed double - based on integer input
5022    SDOperand Store1 = DAG.getStore(DAG.getEntryNode(),
5023                                    Op0Mapped, Lo, NULL, 0);
5024    // initial hi portion of constructed double
5025    SDOperand InitialHi = DAG.getConstant(0x43300000u, MVT::i32);
5026    // store the hi of the constructed double - biased exponent
5027    SDOperand Store2=DAG.getStore(Store1, InitialHi, Hi, NULL, 0);
5028    // load the constructed double
5029    SDOperand Load = DAG.getLoad(MVT::f64, Store2, StackSlot, NULL, 0);
5030    // FP constant to bias correct the final result
5031    SDOperand Bias = DAG.getConstantFP(isSigned ?
5032                                            BitsToDouble(0x4330000080000000ULL)
5033                                          : BitsToDouble(0x4330000000000000ULL),
5034                                     MVT::f64);
5035    // subtract the bias
5036    SDOperand Sub = DAG.getNode(ISD::FSUB, MVT::f64, Load, Bias);
5037    // final result
5038    SDOperand Result;
5039    // handle final rounding
5040    if (DestVT == MVT::f64) {
5041      // do nothing
5042      Result = Sub;
5043    } else if (MVT::getSizeInBits(DestVT) < MVT::getSizeInBits(MVT::f64)) {
5044      Result = DAG.getNode(ISD::FP_ROUND, DestVT, Sub);
5045    } else if (MVT::getSizeInBits(DestVT) > MVT::getSizeInBits(MVT::f64)) {
5046      Result = DAG.getNode(ISD::FP_EXTEND, DestVT, Sub);
5047    }
5048    return Result;
5049  }
5050  assert(!isSigned && "Legalize cannot Expand SINT_TO_FP for i64 yet");
5051  SDOperand Tmp1 = DAG.getNode(ISD::SINT_TO_FP, DestVT, Op0);
5052
5053  SDOperand SignSet = DAG.getSetCC(TLI.getSetCCResultTy(), Op0,
5054                                   DAG.getConstant(0, Op0.getValueType()),
5055                                   ISD::SETLT);
5056  SDOperand Zero = getIntPtrConstant(0), Four = getIntPtrConstant(4);
5057  SDOperand CstOffset = DAG.getNode(ISD::SELECT, Zero.getValueType(),
5058                                    SignSet, Four, Zero);
5059
5060  // If the sign bit of the integer is set, the large number will be treated
5061  // as a negative number.  To counteract this, the dynamic code adds an
5062  // offset depending on the data type.
5063  uint64_t FF;
5064  switch (Op0.getValueType()) {
5065  default: assert(0 && "Unsupported integer type!");
5066  case MVT::i8 : FF = 0x43800000ULL; break;  // 2^8  (as a float)
5067  case MVT::i16: FF = 0x47800000ULL; break;  // 2^16 (as a float)
5068  case MVT::i32: FF = 0x4F800000ULL; break;  // 2^32 (as a float)
5069  case MVT::i64: FF = 0x5F800000ULL; break;  // 2^64 (as a float)
5070  }
5071  if (TLI.isLittleEndian()) FF <<= 32;
5072  static Constant *FudgeFactor = ConstantInt::get(Type::Int64Ty, FF);
5073
5074  SDOperand CPIdx = DAG.getConstantPool(FudgeFactor, TLI.getPointerTy());
5075  CPIdx = DAG.getNode(ISD::ADD, TLI.getPointerTy(), CPIdx, CstOffset);
5076  SDOperand FudgeInReg;
5077  if (DestVT == MVT::f32)
5078    FudgeInReg = DAG.getLoad(MVT::f32, DAG.getEntryNode(), CPIdx, NULL, 0);
5079  else {
5080    FudgeInReg = LegalizeOp(DAG.getExtLoad(ISD::EXTLOAD, DestVT,
5081                                           DAG.getEntryNode(), CPIdx,
5082                                           NULL, 0, MVT::f32));
5083  }
5084
5085  return DAG.getNode(ISD::FADD, DestVT, Tmp1, FudgeInReg);
5086}
5087
5088/// PromoteLegalINT_TO_FP - This function is responsible for legalizing a
5089/// *INT_TO_FP operation of the specified operand when the target requests that
5090/// we promote it.  At this point, we know that the result and operand types are
5091/// legal for the target, and that there is a legal UINT_TO_FP or SINT_TO_FP
5092/// operation that takes a larger input.
5093SDOperand SelectionDAGLegalize::PromoteLegalINT_TO_FP(SDOperand LegalOp,
5094                                                      MVT::ValueType DestVT,
5095                                                      bool isSigned) {
5096  // First step, figure out the appropriate *INT_TO_FP operation to use.
5097  MVT::ValueType NewInTy = LegalOp.getValueType();
5098
5099  unsigned OpToUse = 0;
5100
5101  // Scan for the appropriate larger type to use.
5102  while (1) {
5103    NewInTy = (MVT::ValueType)(NewInTy+1);
5104    assert(MVT::isInteger(NewInTy) && "Ran out of possibilities!");
5105
5106    // If the target supports SINT_TO_FP of this type, use it.
5107    switch (TLI.getOperationAction(ISD::SINT_TO_FP, NewInTy)) {
5108      default: break;
5109      case TargetLowering::Legal:
5110        if (!TLI.isTypeLegal(NewInTy))
5111          break;  // Can't use this datatype.
5112        // FALL THROUGH.
5113      case TargetLowering::Custom:
5114        OpToUse = ISD::SINT_TO_FP;
5115        break;
5116    }
5117    if (OpToUse) break;
5118    if (isSigned) continue;
5119
5120    // If the target supports UINT_TO_FP of this type, use it.
5121    switch (TLI.getOperationAction(ISD::UINT_TO_FP, NewInTy)) {
5122      default: break;
5123      case TargetLowering::Legal:
5124        if (!TLI.isTypeLegal(NewInTy))
5125          break;  // Can't use this datatype.
5126        // FALL THROUGH.
5127      case TargetLowering::Custom:
5128        OpToUse = ISD::UINT_TO_FP;
5129        break;
5130    }
5131    if (OpToUse) break;
5132
5133    // Otherwise, try a larger type.
5134  }
5135
5136  // Okay, we found the operation and type to use.  Zero extend our input to the
5137  // desired type then run the operation on it.
5138  return DAG.getNode(OpToUse, DestVT,
5139                     DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
5140                                 NewInTy, LegalOp));
5141}
5142
5143/// PromoteLegalFP_TO_INT - This function is responsible for legalizing a
5144/// FP_TO_*INT operation of the specified operand when the target requests that
5145/// we promote it.  At this point, we know that the result and operand types are
5146/// legal for the target, and that there is a legal FP_TO_UINT or FP_TO_SINT
5147/// operation that returns a larger result.
5148SDOperand SelectionDAGLegalize::PromoteLegalFP_TO_INT(SDOperand LegalOp,
5149                                                      MVT::ValueType DestVT,
5150                                                      bool isSigned) {
5151  // First step, figure out the appropriate FP_TO*INT operation to use.
5152  MVT::ValueType NewOutTy = DestVT;
5153
5154  unsigned OpToUse = 0;
5155
5156  // Scan for the appropriate larger type to use.
5157  while (1) {
5158    NewOutTy = (MVT::ValueType)(NewOutTy+1);
5159    assert(MVT::isInteger(NewOutTy) && "Ran out of possibilities!");
5160
5161    // If the target supports FP_TO_SINT returning this type, use it.
5162    switch (TLI.getOperationAction(ISD::FP_TO_SINT, NewOutTy)) {
5163    default: break;
5164    case TargetLowering::Legal:
5165      if (!TLI.isTypeLegal(NewOutTy))
5166        break;  // Can't use this datatype.
5167      // FALL THROUGH.
5168    case TargetLowering::Custom:
5169      OpToUse = ISD::FP_TO_SINT;
5170      break;
5171    }
5172    if (OpToUse) break;
5173
5174    // If the target supports FP_TO_UINT of this type, use it.
5175    switch (TLI.getOperationAction(ISD::FP_TO_UINT, NewOutTy)) {
5176    default: break;
5177    case TargetLowering::Legal:
5178      if (!TLI.isTypeLegal(NewOutTy))
5179        break;  // Can't use this datatype.
5180      // FALL THROUGH.
5181    case TargetLowering::Custom:
5182      OpToUse = ISD::FP_TO_UINT;
5183      break;
5184    }
5185    if (OpToUse) break;
5186
5187    // Otherwise, try a larger type.
5188  }
5189
5190  // Okay, we found the operation and type to use.  Truncate the result of the
5191  // extended FP_TO_*INT operation to the desired size.
5192  return DAG.getNode(ISD::TRUNCATE, DestVT,
5193                     DAG.getNode(OpToUse, NewOutTy, LegalOp));
5194}
5195
5196/// ExpandBSWAP - Open code the operations for BSWAP of the specified operation.
5197///
5198SDOperand SelectionDAGLegalize::ExpandBSWAP(SDOperand Op) {
5199  MVT::ValueType VT = Op.getValueType();
5200  MVT::ValueType SHVT = TLI.getShiftAmountTy();
5201  SDOperand Tmp1, Tmp2, Tmp3, Tmp4, Tmp5, Tmp6, Tmp7, Tmp8;
5202  switch (VT) {
5203  default: assert(0 && "Unhandled Expand type in BSWAP!"); abort();
5204  case MVT::i16:
5205    Tmp2 = DAG.getNode(ISD::SHL, VT, Op, DAG.getConstant(8, SHVT));
5206    Tmp1 = DAG.getNode(ISD::SRL, VT, Op, DAG.getConstant(8, SHVT));
5207    return DAG.getNode(ISD::OR, VT, Tmp1, Tmp2);
5208  case MVT::i32:
5209    Tmp4 = DAG.getNode(ISD::SHL, VT, Op, DAG.getConstant(24, SHVT));
5210    Tmp3 = DAG.getNode(ISD::SHL, VT, Op, DAG.getConstant(8, SHVT));
5211    Tmp2 = DAG.getNode(ISD::SRL, VT, Op, DAG.getConstant(8, SHVT));
5212    Tmp1 = DAG.getNode(ISD::SRL, VT, Op, DAG.getConstant(24, SHVT));
5213    Tmp3 = DAG.getNode(ISD::AND, VT, Tmp3, DAG.getConstant(0xFF0000, VT));
5214    Tmp2 = DAG.getNode(ISD::AND, VT, Tmp2, DAG.getConstant(0xFF00, VT));
5215    Tmp4 = DAG.getNode(ISD::OR, VT, Tmp4, Tmp3);
5216    Tmp2 = DAG.getNode(ISD::OR, VT, Tmp2, Tmp1);
5217    return DAG.getNode(ISD::OR, VT, Tmp4, Tmp2);
5218  case MVT::i64:
5219    Tmp8 = DAG.getNode(ISD::SHL, VT, Op, DAG.getConstant(56, SHVT));
5220    Tmp7 = DAG.getNode(ISD::SHL, VT, Op, DAG.getConstant(40, SHVT));
5221    Tmp6 = DAG.getNode(ISD::SHL, VT, Op, DAG.getConstant(24, SHVT));
5222    Tmp5 = DAG.getNode(ISD::SHL, VT, Op, DAG.getConstant(8, SHVT));
5223    Tmp4 = DAG.getNode(ISD::SRL, VT, Op, DAG.getConstant(8, SHVT));
5224    Tmp3 = DAG.getNode(ISD::SRL, VT, Op, DAG.getConstant(24, SHVT));
5225    Tmp2 = DAG.getNode(ISD::SRL, VT, Op, DAG.getConstant(40, SHVT));
5226    Tmp1 = DAG.getNode(ISD::SRL, VT, Op, DAG.getConstant(56, SHVT));
5227    Tmp7 = DAG.getNode(ISD::AND, VT, Tmp7, DAG.getConstant(255ULL<<48, VT));
5228    Tmp6 = DAG.getNode(ISD::AND, VT, Tmp6, DAG.getConstant(255ULL<<40, VT));
5229    Tmp5 = DAG.getNode(ISD::AND, VT, Tmp5, DAG.getConstant(255ULL<<32, VT));
5230    Tmp4 = DAG.getNode(ISD::AND, VT, Tmp4, DAG.getConstant(255ULL<<24, VT));
5231    Tmp3 = DAG.getNode(ISD::AND, VT, Tmp3, DAG.getConstant(255ULL<<16, VT));
5232    Tmp2 = DAG.getNode(ISD::AND, VT, Tmp2, DAG.getConstant(255ULL<<8 , VT));
5233    Tmp8 = DAG.getNode(ISD::OR, VT, Tmp8, Tmp7);
5234    Tmp6 = DAG.getNode(ISD::OR, VT, Tmp6, Tmp5);
5235    Tmp4 = DAG.getNode(ISD::OR, VT, Tmp4, Tmp3);
5236    Tmp2 = DAG.getNode(ISD::OR, VT, Tmp2, Tmp1);
5237    Tmp8 = DAG.getNode(ISD::OR, VT, Tmp8, Tmp6);
5238    Tmp4 = DAG.getNode(ISD::OR, VT, Tmp4, Tmp2);
5239    return DAG.getNode(ISD::OR, VT, Tmp8, Tmp4);
5240  }
5241}
5242
5243/// ExpandBitCount - Expand the specified bitcount instruction into operations.
5244///
5245SDOperand SelectionDAGLegalize::ExpandBitCount(unsigned Opc, SDOperand Op) {
5246  switch (Opc) {
5247  default: assert(0 && "Cannot expand this yet!");
5248  case ISD::CTPOP: {
5249    static const uint64_t mask[6] = {
5250      0x5555555555555555ULL, 0x3333333333333333ULL,
5251      0x0F0F0F0F0F0F0F0FULL, 0x00FF00FF00FF00FFULL,
5252      0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL
5253    };
5254    MVT::ValueType VT = Op.getValueType();
5255    MVT::ValueType ShVT = TLI.getShiftAmountTy();
5256    unsigned len = MVT::getSizeInBits(VT);
5257    for (unsigned i = 0; (1U << i) <= (len / 2); ++i) {
5258      //x = (x & mask[i][len/8]) + (x >> (1 << i) & mask[i][len/8])
5259      SDOperand Tmp2 = DAG.getConstant(mask[i], VT);
5260      SDOperand Tmp3 = DAG.getConstant(1ULL << i, ShVT);
5261      Op = DAG.getNode(ISD::ADD, VT, DAG.getNode(ISD::AND, VT, Op, Tmp2),
5262                       DAG.getNode(ISD::AND, VT,
5263                                   DAG.getNode(ISD::SRL, VT, Op, Tmp3),Tmp2));
5264    }
5265    return Op;
5266  }
5267  case ISD::CTLZ: {
5268    // for now, we do this:
5269    // x = x | (x >> 1);
5270    // x = x | (x >> 2);
5271    // ...
5272    // x = x | (x >>16);
5273    // x = x | (x >>32); // for 64-bit input
5274    // return popcount(~x);
5275    //
5276    // but see also: http://www.hackersdelight.org/HDcode/nlz.cc
5277    MVT::ValueType VT = Op.getValueType();
5278    MVT::ValueType ShVT = TLI.getShiftAmountTy();
5279    unsigned len = MVT::getSizeInBits(VT);
5280    for (unsigned i = 0; (1U << i) <= (len / 2); ++i) {
5281      SDOperand Tmp3 = DAG.getConstant(1ULL << i, ShVT);
5282      Op = DAG.getNode(ISD::OR, VT, Op, DAG.getNode(ISD::SRL, VT, Op, Tmp3));
5283    }
5284    Op = DAG.getNode(ISD::XOR, VT, Op, DAG.getConstant(~0ULL, VT));
5285    return DAG.getNode(ISD::CTPOP, VT, Op);
5286  }
5287  case ISD::CTTZ: {
5288    // for now, we use: { return popcount(~x & (x - 1)); }
5289    // unless the target has ctlz but not ctpop, in which case we use:
5290    // { return 32 - nlz(~x & (x-1)); }
5291    // see also http://www.hackersdelight.org/HDcode/ntz.cc
5292    MVT::ValueType VT = Op.getValueType();
5293    SDOperand Tmp2 = DAG.getConstant(~0ULL, VT);
5294    SDOperand Tmp3 = DAG.getNode(ISD::AND, VT,
5295                       DAG.getNode(ISD::XOR, VT, Op, Tmp2),
5296                       DAG.getNode(ISD::SUB, VT, Op, DAG.getConstant(1, VT)));
5297    // If ISD::CTLZ is legal and CTPOP isn't, then do that instead.
5298    if (!TLI.isOperationLegal(ISD::CTPOP, VT) &&
5299        TLI.isOperationLegal(ISD::CTLZ, VT))
5300      return DAG.getNode(ISD::SUB, VT,
5301                         DAG.getConstant(MVT::getSizeInBits(VT), VT),
5302                         DAG.getNode(ISD::CTLZ, VT, Tmp3));
5303    return DAG.getNode(ISD::CTPOP, VT, Tmp3);
5304  }
5305  }
5306}
5307
5308/// ExpandOp - Expand the specified SDOperand into its two component pieces
5309/// Lo&Hi.  Note that the Op MUST be an expanded type.  As a result of this, the
5310/// LegalizeNodes map is filled in for any results that are not expanded, the
5311/// ExpandedNodes map is filled in for any results that are expanded, and the
5312/// Lo/Hi values are returned.
5313void SelectionDAGLegalize::ExpandOp(SDOperand Op, SDOperand &Lo, SDOperand &Hi){
5314  MVT::ValueType VT = Op.getValueType();
5315  MVT::ValueType NVT = TLI.getTypeToTransformTo(VT);
5316  SDNode *Node = Op.Val;
5317  assert(getTypeAction(VT) == Expand && "Not an expanded type!");
5318  assert(((MVT::isInteger(NVT) && NVT < VT) || MVT::isFloatingPoint(VT) ||
5319         MVT::isVector(VT)) &&
5320         "Cannot expand to FP value or to larger int value!");
5321
5322  // See if we already expanded it.
5323  DenseMap<SDOperand, std::pair<SDOperand, SDOperand> >::iterator I
5324    = ExpandedNodes.find(Op);
5325  if (I != ExpandedNodes.end()) {
5326    Lo = I->second.first;
5327    Hi = I->second.second;
5328    return;
5329  }
5330
5331  switch (Node->getOpcode()) {
5332  case ISD::CopyFromReg:
5333    assert(0 && "CopyFromReg must be legal!");
5334  case ISD::FP_ROUND_INREG:
5335    if (VT == MVT::ppcf128 &&
5336        TLI.getOperationAction(ISD::FP_ROUND_INREG, VT) ==
5337            TargetLowering::Custom) {
5338      SDOperand SrcLo, SrcHi, Src;
5339      ExpandOp(Op.getOperand(0), SrcLo, SrcHi);
5340      Src = DAG.getNode(ISD::BUILD_PAIR, VT, SrcLo, SrcHi);
5341      SDOperand Result = TLI.LowerOperation(
5342        DAG.getNode(ISD::FP_ROUND_INREG, VT, Src, Op.getOperand(1)), DAG);
5343      assert(Result.Val->getOpcode() == ISD::BUILD_PAIR);
5344      Lo = Result.Val->getOperand(0);
5345      Hi = Result.Val->getOperand(1);
5346      break;
5347    }
5348    // fall through
5349  default:
5350#ifndef NDEBUG
5351    cerr << "NODE: "; Node->dump(&DAG); cerr << "\n";
5352#endif
5353    assert(0 && "Do not know how to expand this operator!");
5354    abort();
5355  case ISD::EXTRACT_VECTOR_ELT:
5356    assert(VT==MVT::i64 && "Do not know how to expand this operator!");
5357    // ExpandEXTRACT_VECTOR_ELT tolerates invalid result types.
5358    Lo  = ExpandEXTRACT_VECTOR_ELT(Op);
5359    return ExpandOp(Lo, Lo, Hi);
5360  case ISD::UNDEF:
5361    NVT = TLI.getTypeToExpandTo(VT);
5362    Lo = DAG.getNode(ISD::UNDEF, NVT);
5363    Hi = DAG.getNode(ISD::UNDEF, NVT);
5364    break;
5365  case ISD::Constant: {
5366    uint64_t Cst = cast<ConstantSDNode>(Node)->getValue();
5367    Lo = DAG.getConstant(Cst, NVT);
5368    Hi = DAG.getConstant(Cst >> MVT::getSizeInBits(NVT), NVT);
5369    break;
5370  }
5371  case ISD::ConstantFP: {
5372    ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Node);
5373    if (CFP->getValueType(0) == MVT::ppcf128) {
5374      APInt api = CFP->getValueAPF().convertToAPInt();
5375      Lo = DAG.getConstantFP(APFloat(APInt(64, 1, &api.getRawData()[1])),
5376                             MVT::f64);
5377      Hi = DAG.getConstantFP(APFloat(APInt(64, 1, &api.getRawData()[0])),
5378                             MVT::f64);
5379      break;
5380    }
5381    Lo = ExpandConstantFP(CFP, false, DAG, TLI);
5382    if (getTypeAction(Lo.getValueType()) == Expand)
5383      ExpandOp(Lo, Lo, Hi);
5384    break;
5385  }
5386  case ISD::BUILD_PAIR:
5387    // Return the operands.
5388    Lo = Node->getOperand(0);
5389    Hi = Node->getOperand(1);
5390    break;
5391
5392  case ISD::SIGN_EXTEND_INREG:
5393    ExpandOp(Node->getOperand(0), Lo, Hi);
5394    // sext_inreg the low part if needed.
5395    Lo = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Lo, Node->getOperand(1));
5396
5397    // The high part gets the sign extension from the lo-part.  This handles
5398    // things like sextinreg V:i64 from i8.
5399    Hi = DAG.getNode(ISD::SRA, NVT, Lo,
5400                     DAG.getConstant(MVT::getSizeInBits(NVT)-1,
5401                                     TLI.getShiftAmountTy()));
5402    break;
5403
5404  case ISD::BSWAP: {
5405    ExpandOp(Node->getOperand(0), Lo, Hi);
5406    SDOperand TempLo = DAG.getNode(ISD::BSWAP, NVT, Hi);
5407    Hi = DAG.getNode(ISD::BSWAP, NVT, Lo);
5408    Lo = TempLo;
5409    break;
5410  }
5411
5412  case ISD::CTPOP:
5413    ExpandOp(Node->getOperand(0), Lo, Hi);
5414    Lo = DAG.getNode(ISD::ADD, NVT,          // ctpop(HL) -> ctpop(H)+ctpop(L)
5415                     DAG.getNode(ISD::CTPOP, NVT, Lo),
5416                     DAG.getNode(ISD::CTPOP, NVT, Hi));
5417    Hi = DAG.getConstant(0, NVT);
5418    break;
5419
5420  case ISD::CTLZ: {
5421    // ctlz (HL) -> ctlz(H) != 32 ? ctlz(H) : (ctlz(L)+32)
5422    ExpandOp(Node->getOperand(0), Lo, Hi);
5423    SDOperand BitsC = DAG.getConstant(MVT::getSizeInBits(NVT), NVT);
5424    SDOperand HLZ = DAG.getNode(ISD::CTLZ, NVT, Hi);
5425    SDOperand TopNotZero = DAG.getSetCC(TLI.getSetCCResultTy(), HLZ, BitsC,
5426                                        ISD::SETNE);
5427    SDOperand LowPart = DAG.getNode(ISD::CTLZ, NVT, Lo);
5428    LowPart = DAG.getNode(ISD::ADD, NVT, LowPart, BitsC);
5429
5430    Lo = DAG.getNode(ISD::SELECT, NVT, TopNotZero, HLZ, LowPart);
5431    Hi = DAG.getConstant(0, NVT);
5432    break;
5433  }
5434
5435  case ISD::CTTZ: {
5436    // cttz (HL) -> cttz(L) != 32 ? cttz(L) : (cttz(H)+32)
5437    ExpandOp(Node->getOperand(0), Lo, Hi);
5438    SDOperand BitsC = DAG.getConstant(MVT::getSizeInBits(NVT), NVT);
5439    SDOperand LTZ = DAG.getNode(ISD::CTTZ, NVT, Lo);
5440    SDOperand BotNotZero = DAG.getSetCC(TLI.getSetCCResultTy(), LTZ, BitsC,
5441                                        ISD::SETNE);
5442    SDOperand HiPart = DAG.getNode(ISD::CTTZ, NVT, Hi);
5443    HiPart = DAG.getNode(ISD::ADD, NVT, HiPart, BitsC);
5444
5445    Lo = DAG.getNode(ISD::SELECT, NVT, BotNotZero, LTZ, HiPart);
5446    Hi = DAG.getConstant(0, NVT);
5447    break;
5448  }
5449
5450  case ISD::VAARG: {
5451    SDOperand Ch = Node->getOperand(0);   // Legalize the chain.
5452    SDOperand Ptr = Node->getOperand(1);  // Legalize the pointer.
5453    Lo = DAG.getVAArg(NVT, Ch, Ptr, Node->getOperand(2));
5454    Hi = DAG.getVAArg(NVT, Lo.getValue(1), Ptr, Node->getOperand(2));
5455
5456    // Remember that we legalized the chain.
5457    Hi = LegalizeOp(Hi);
5458    AddLegalizedOperand(Op.getValue(1), Hi.getValue(1));
5459    if (!TLI.isLittleEndian())
5460      std::swap(Lo, Hi);
5461    break;
5462  }
5463
5464  case ISD::LOAD: {
5465    LoadSDNode *LD = cast<LoadSDNode>(Node);
5466    SDOperand Ch  = LD->getChain();    // Legalize the chain.
5467    SDOperand Ptr = LD->getBasePtr();  // Legalize the pointer.
5468    ISD::LoadExtType ExtType = LD->getExtensionType();
5469    int SVOffset = LD->getSrcValueOffset();
5470    unsigned Alignment = LD->getAlignment();
5471    bool isVolatile = LD->isVolatile();
5472
5473    if (ExtType == ISD::NON_EXTLOAD) {
5474      Lo = DAG.getLoad(NVT, Ch, Ptr, LD->getSrcValue(), SVOffset,
5475                       isVolatile, Alignment);
5476      if (VT == MVT::f32 || VT == MVT::f64) {
5477        // f32->i32 or f64->i64 one to one expansion.
5478        // Remember that we legalized the chain.
5479        AddLegalizedOperand(SDOperand(Node, 1), LegalizeOp(Lo.getValue(1)));
5480        // Recursively expand the new load.
5481        if (getTypeAction(NVT) == Expand)
5482          ExpandOp(Lo, Lo, Hi);
5483        break;
5484      }
5485
5486      // Increment the pointer to the other half.
5487      unsigned IncrementSize = MVT::getSizeInBits(Lo.getValueType())/8;
5488      Ptr = DAG.getNode(ISD::ADD, Ptr.getValueType(), Ptr,
5489                        getIntPtrConstant(IncrementSize));
5490      SVOffset += IncrementSize;
5491      Alignment = MinAlign(Alignment, IncrementSize);
5492      Hi = DAG.getLoad(NVT, Ch, Ptr, LD->getSrcValue(), SVOffset,
5493                       isVolatile, Alignment);
5494
5495      // Build a factor node to remember that this load is independent of the
5496      // other one.
5497      SDOperand TF = DAG.getNode(ISD::TokenFactor, MVT::Other, Lo.getValue(1),
5498                                 Hi.getValue(1));
5499
5500      // Remember that we legalized the chain.
5501      AddLegalizedOperand(Op.getValue(1), LegalizeOp(TF));
5502      if (!TLI.isLittleEndian())
5503        std::swap(Lo, Hi);
5504    } else {
5505      MVT::ValueType EVT = LD->getLoadedVT();
5506
5507      if ((VT == MVT::f64 && EVT == MVT::f32) ||
5508          (VT == MVT::ppcf128 && (EVT==MVT::f64 || EVT==MVT::f32))) {
5509        // f64 = EXTLOAD f32 should expand to LOAD, FP_EXTEND
5510        SDOperand Load = DAG.getLoad(EVT, Ch, Ptr, LD->getSrcValue(),
5511                                     SVOffset, isVolatile, Alignment);
5512        // Remember that we legalized the chain.
5513        AddLegalizedOperand(SDOperand(Node, 1), LegalizeOp(Load.getValue(1)));
5514        ExpandOp(DAG.getNode(ISD::FP_EXTEND, VT, Load), Lo, Hi);
5515        break;
5516      }
5517
5518      if (EVT == NVT)
5519        Lo = DAG.getLoad(NVT, Ch, Ptr, LD->getSrcValue(),
5520                         SVOffset, isVolatile, Alignment);
5521      else
5522        Lo = DAG.getExtLoad(ExtType, NVT, Ch, Ptr, LD->getSrcValue(),
5523                            SVOffset, EVT, isVolatile,
5524                            Alignment);
5525
5526      // Remember that we legalized the chain.
5527      AddLegalizedOperand(SDOperand(Node, 1), LegalizeOp(Lo.getValue(1)));
5528
5529      if (ExtType == ISD::SEXTLOAD) {
5530        // The high part is obtained by SRA'ing all but one of the bits of the
5531        // lo part.
5532        unsigned LoSize = MVT::getSizeInBits(Lo.getValueType());
5533        Hi = DAG.getNode(ISD::SRA, NVT, Lo,
5534                         DAG.getConstant(LoSize-1, TLI.getShiftAmountTy()));
5535      } else if (ExtType == ISD::ZEXTLOAD) {
5536        // The high part is just a zero.
5537        Hi = DAG.getConstant(0, NVT);
5538      } else /* if (ExtType == ISD::EXTLOAD) */ {
5539        // The high part is undefined.
5540        Hi = DAG.getNode(ISD::UNDEF, NVT);
5541      }
5542    }
5543    break;
5544  }
5545  case ISD::AND:
5546  case ISD::OR:
5547  case ISD::XOR: {   // Simple logical operators -> two trivial pieces.
5548    SDOperand LL, LH, RL, RH;
5549    ExpandOp(Node->getOperand(0), LL, LH);
5550    ExpandOp(Node->getOperand(1), RL, RH);
5551    Lo = DAG.getNode(Node->getOpcode(), NVT, LL, RL);
5552    Hi = DAG.getNode(Node->getOpcode(), NVT, LH, RH);
5553    break;
5554  }
5555  case ISD::SELECT: {
5556    SDOperand LL, LH, RL, RH;
5557    ExpandOp(Node->getOperand(1), LL, LH);
5558    ExpandOp(Node->getOperand(2), RL, RH);
5559    if (getTypeAction(NVT) == Expand)
5560      NVT = TLI.getTypeToExpandTo(NVT);
5561    Lo = DAG.getNode(ISD::SELECT, NVT, Node->getOperand(0), LL, RL);
5562    if (VT != MVT::f32)
5563      Hi = DAG.getNode(ISD::SELECT, NVT, Node->getOperand(0), LH, RH);
5564    break;
5565  }
5566  case ISD::SELECT_CC: {
5567    SDOperand TL, TH, FL, FH;
5568    ExpandOp(Node->getOperand(2), TL, TH);
5569    ExpandOp(Node->getOperand(3), FL, FH);
5570    if (getTypeAction(NVT) == Expand)
5571      NVT = TLI.getTypeToExpandTo(NVT);
5572    Lo = DAG.getNode(ISD::SELECT_CC, NVT, Node->getOperand(0),
5573                     Node->getOperand(1), TL, FL, Node->getOperand(4));
5574    if (VT != MVT::f32)
5575      Hi = DAG.getNode(ISD::SELECT_CC, NVT, Node->getOperand(0),
5576                       Node->getOperand(1), TH, FH, Node->getOperand(4));
5577    break;
5578  }
5579  case ISD::ANY_EXTEND:
5580    // The low part is any extension of the input (which degenerates to a copy).
5581    Lo = DAG.getNode(ISD::ANY_EXTEND, NVT, Node->getOperand(0));
5582    // The high part is undefined.
5583    Hi = DAG.getNode(ISD::UNDEF, NVT);
5584    break;
5585  case ISD::SIGN_EXTEND: {
5586    // The low part is just a sign extension of the input (which degenerates to
5587    // a copy).
5588    Lo = DAG.getNode(ISD::SIGN_EXTEND, NVT, Node->getOperand(0));
5589
5590    // The high part is obtained by SRA'ing all but one of the bits of the lo
5591    // part.
5592    unsigned LoSize = MVT::getSizeInBits(Lo.getValueType());
5593    Hi = DAG.getNode(ISD::SRA, NVT, Lo,
5594                     DAG.getConstant(LoSize-1, TLI.getShiftAmountTy()));
5595    break;
5596  }
5597  case ISD::ZERO_EXTEND:
5598    // The low part is just a zero extension of the input (which degenerates to
5599    // a copy).
5600    Lo = DAG.getNode(ISD::ZERO_EXTEND, NVT, Node->getOperand(0));
5601
5602    // The high part is just a zero.
5603    Hi = DAG.getConstant(0, NVT);
5604    break;
5605
5606  case ISD::TRUNCATE: {
5607    // The input value must be larger than this value.  Expand *it*.
5608    SDOperand NewLo;
5609    ExpandOp(Node->getOperand(0), NewLo, Hi);
5610
5611    // The low part is now either the right size, or it is closer.  If not the
5612    // right size, make an illegal truncate so we recursively expand it.
5613    if (NewLo.getValueType() != Node->getValueType(0))
5614      NewLo = DAG.getNode(ISD::TRUNCATE, Node->getValueType(0), NewLo);
5615    ExpandOp(NewLo, Lo, Hi);
5616    break;
5617  }
5618
5619  case ISD::BIT_CONVERT: {
5620    SDOperand Tmp;
5621    if (TLI.getOperationAction(ISD::BIT_CONVERT, VT) == TargetLowering::Custom){
5622      // If the target wants to, allow it to lower this itself.
5623      switch (getTypeAction(Node->getOperand(0).getValueType())) {
5624      case Expand: assert(0 && "cannot expand FP!");
5625      case Legal:   Tmp = LegalizeOp(Node->getOperand(0)); break;
5626      case Promote: Tmp = PromoteOp (Node->getOperand(0)); break;
5627      }
5628      Tmp = TLI.LowerOperation(DAG.getNode(ISD::BIT_CONVERT, VT, Tmp), DAG);
5629    }
5630
5631    // f32 / f64 must be expanded to i32 / i64.
5632    if (VT == MVT::f32 || VT == MVT::f64) {
5633      Lo = DAG.getNode(ISD::BIT_CONVERT, NVT, Node->getOperand(0));
5634      if (getTypeAction(NVT) == Expand)
5635        ExpandOp(Lo, Lo, Hi);
5636      break;
5637    }
5638
5639    // If source operand will be expanded to the same type as VT, i.e.
5640    // i64 <- f64, i32 <- f32, expand the source operand instead.
5641    MVT::ValueType VT0 = Node->getOperand(0).getValueType();
5642    if (getTypeAction(VT0) == Expand && TLI.getTypeToTransformTo(VT0) == VT) {
5643      ExpandOp(Node->getOperand(0), Lo, Hi);
5644      break;
5645    }
5646
5647    // Turn this into a load/store pair by default.
5648    if (Tmp.Val == 0)
5649      Tmp = ExpandBIT_CONVERT(VT, Node->getOperand(0));
5650
5651    ExpandOp(Tmp, Lo, Hi);
5652    break;
5653  }
5654
5655  case ISD::READCYCLECOUNTER:
5656    assert(TLI.getOperationAction(ISD::READCYCLECOUNTER, VT) ==
5657                 TargetLowering::Custom &&
5658           "Must custom expand ReadCycleCounter");
5659    Lo = TLI.LowerOperation(Op, DAG);
5660    assert(Lo.Val && "Node must be custom expanded!");
5661    Hi = Lo.getValue(1);
5662    AddLegalizedOperand(SDOperand(Node, 1), // Remember we legalized the chain.
5663                        LegalizeOp(Lo.getValue(2)));
5664    break;
5665
5666    // These operators cannot be expanded directly, emit them as calls to
5667    // library functions.
5668  case ISD::FP_TO_SINT: {
5669    if (TLI.getOperationAction(ISD::FP_TO_SINT, VT) == TargetLowering::Custom) {
5670      SDOperand Op;
5671      switch (getTypeAction(Node->getOperand(0).getValueType())) {
5672      case Expand: assert(0 && "cannot expand FP!");
5673      case Legal:   Op = LegalizeOp(Node->getOperand(0)); break;
5674      case Promote: Op = PromoteOp (Node->getOperand(0)); break;
5675      }
5676
5677      Op = TLI.LowerOperation(DAG.getNode(ISD::FP_TO_SINT, VT, Op), DAG);
5678
5679      // Now that the custom expander is done, expand the result, which is still
5680      // VT.
5681      if (Op.Val) {
5682        ExpandOp(Op, Lo, Hi);
5683        break;
5684      }
5685    }
5686
5687    RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
5688    if (Node->getOperand(0).getValueType() == MVT::f32)
5689      LC = RTLIB::FPTOSINT_F32_I64;
5690    else if (Node->getOperand(0).getValueType() == MVT::f64)
5691      LC = RTLIB::FPTOSINT_F64_I64;
5692    else if (Node->getOperand(0).getValueType() == MVT::f80)
5693      LC = RTLIB::FPTOSINT_F80_I64;
5694    else if (Node->getOperand(0).getValueType() == MVT::ppcf128)
5695      LC = RTLIB::FPTOSINT_PPCF128_I64;
5696    Lo = ExpandLibCall(TLI.getLibcallName(LC), Node,
5697                       false/*sign irrelevant*/, Hi);
5698    break;
5699  }
5700
5701  case ISD::FP_TO_UINT: {
5702    if (TLI.getOperationAction(ISD::FP_TO_UINT, VT) == TargetLowering::Custom) {
5703      SDOperand Op;
5704      switch (getTypeAction(Node->getOperand(0).getValueType())) {
5705        case Expand: assert(0 && "cannot expand FP!");
5706        case Legal:   Op = LegalizeOp(Node->getOperand(0)); break;
5707        case Promote: Op = PromoteOp (Node->getOperand(0)); break;
5708      }
5709
5710      Op = TLI.LowerOperation(DAG.getNode(ISD::FP_TO_UINT, VT, Op), DAG);
5711
5712      // Now that the custom expander is done, expand the result.
5713      if (Op.Val) {
5714        ExpandOp(Op, Lo, Hi);
5715        break;
5716      }
5717    }
5718
5719    RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
5720    if (Node->getOperand(0).getValueType() == MVT::f32)
5721      LC = RTLIB::FPTOUINT_F32_I64;
5722    else if (Node->getOperand(0).getValueType() == MVT::f64)
5723      LC = RTLIB::FPTOUINT_F64_I64;
5724    else if (Node->getOperand(0).getValueType() == MVT::f80)
5725      LC = RTLIB::FPTOUINT_F80_I64;
5726    else if (Node->getOperand(0).getValueType() == MVT::ppcf128)
5727      LC = RTLIB::FPTOUINT_PPCF128_I64;
5728    Lo = ExpandLibCall(TLI.getLibcallName(LC), Node,
5729                       false/*sign irrelevant*/, Hi);
5730    break;
5731  }
5732
5733  case ISD::SHL: {
5734    // If the target wants custom lowering, do so.
5735    SDOperand ShiftAmt = LegalizeOp(Node->getOperand(1));
5736    if (TLI.getOperationAction(ISD::SHL, VT) == TargetLowering::Custom) {
5737      SDOperand Op = DAG.getNode(ISD::SHL, VT, Node->getOperand(0), ShiftAmt);
5738      Op = TLI.LowerOperation(Op, DAG);
5739      if (Op.Val) {
5740        // Now that the custom expander is done, expand the result, which is
5741        // still VT.
5742        ExpandOp(Op, Lo, Hi);
5743        break;
5744      }
5745    }
5746
5747    // If ADDC/ADDE are supported and if the shift amount is a constant 1, emit
5748    // this X << 1 as X+X.
5749    if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(ShiftAmt)) {
5750      if (ShAmt->getValue() == 1 && TLI.isOperationLegal(ISD::ADDC, NVT) &&
5751          TLI.isOperationLegal(ISD::ADDE, NVT)) {
5752        SDOperand LoOps[2], HiOps[3];
5753        ExpandOp(Node->getOperand(0), LoOps[0], HiOps[0]);
5754        SDVTList VTList = DAG.getVTList(LoOps[0].getValueType(), MVT::Flag);
5755        LoOps[1] = LoOps[0];
5756        Lo = DAG.getNode(ISD::ADDC, VTList, LoOps, 2);
5757
5758        HiOps[1] = HiOps[0];
5759        HiOps[2] = Lo.getValue(1);
5760        Hi = DAG.getNode(ISD::ADDE, VTList, HiOps, 3);
5761        break;
5762      }
5763    }
5764
5765    // If we can emit an efficient shift operation, do so now.
5766    if (ExpandShift(ISD::SHL, Node->getOperand(0), ShiftAmt, Lo, Hi))
5767      break;
5768
5769    // If this target supports SHL_PARTS, use it.
5770    TargetLowering::LegalizeAction Action =
5771      TLI.getOperationAction(ISD::SHL_PARTS, NVT);
5772    if ((Action == TargetLowering::Legal && TLI.isTypeLegal(NVT)) ||
5773        Action == TargetLowering::Custom) {
5774      ExpandShiftParts(ISD::SHL_PARTS, Node->getOperand(0), ShiftAmt, Lo, Hi);
5775      break;
5776    }
5777
5778    // Otherwise, emit a libcall.
5779    Lo = ExpandLibCall(TLI.getLibcallName(RTLIB::SHL_I64), Node,
5780                       false/*left shift=unsigned*/, Hi);
5781    break;
5782  }
5783
5784  case ISD::SRA: {
5785    // If the target wants custom lowering, do so.
5786    SDOperand ShiftAmt = LegalizeOp(Node->getOperand(1));
5787    if (TLI.getOperationAction(ISD::SRA, VT) == TargetLowering::Custom) {
5788      SDOperand Op = DAG.getNode(ISD::SRA, VT, Node->getOperand(0), ShiftAmt);
5789      Op = TLI.LowerOperation(Op, DAG);
5790      if (Op.Val) {
5791        // Now that the custom expander is done, expand the result, which is
5792        // still VT.
5793        ExpandOp(Op, Lo, Hi);
5794        break;
5795      }
5796    }
5797
5798    // If we can emit an efficient shift operation, do so now.
5799    if (ExpandShift(ISD::SRA, Node->getOperand(0), ShiftAmt, Lo, Hi))
5800      break;
5801
5802    // If this target supports SRA_PARTS, use it.
5803    TargetLowering::LegalizeAction Action =
5804      TLI.getOperationAction(ISD::SRA_PARTS, NVT);
5805    if ((Action == TargetLowering::Legal && TLI.isTypeLegal(NVT)) ||
5806        Action == TargetLowering::Custom) {
5807      ExpandShiftParts(ISD::SRA_PARTS, Node->getOperand(0), ShiftAmt, Lo, Hi);
5808      break;
5809    }
5810
5811    // Otherwise, emit a libcall.
5812    Lo = ExpandLibCall(TLI.getLibcallName(RTLIB::SRA_I64), Node,
5813                       true/*ashr is signed*/, Hi);
5814    break;
5815  }
5816
5817  case ISD::SRL: {
5818    // If the target wants custom lowering, do so.
5819    SDOperand ShiftAmt = LegalizeOp(Node->getOperand(1));
5820    if (TLI.getOperationAction(ISD::SRL, VT) == TargetLowering::Custom) {
5821      SDOperand Op = DAG.getNode(ISD::SRL, VT, Node->getOperand(0), ShiftAmt);
5822      Op = TLI.LowerOperation(Op, DAG);
5823      if (Op.Val) {
5824        // Now that the custom expander is done, expand the result, which is
5825        // still VT.
5826        ExpandOp(Op, Lo, Hi);
5827        break;
5828      }
5829    }
5830
5831    // If we can emit an efficient shift operation, do so now.
5832    if (ExpandShift(ISD::SRL, Node->getOperand(0), ShiftAmt, Lo, Hi))
5833      break;
5834
5835    // If this target supports SRL_PARTS, use it.
5836    TargetLowering::LegalizeAction Action =
5837      TLI.getOperationAction(ISD::SRL_PARTS, NVT);
5838    if ((Action == TargetLowering::Legal && TLI.isTypeLegal(NVT)) ||
5839        Action == TargetLowering::Custom) {
5840      ExpandShiftParts(ISD::SRL_PARTS, Node->getOperand(0), ShiftAmt, Lo, Hi);
5841      break;
5842    }
5843
5844    // Otherwise, emit a libcall.
5845    Lo = ExpandLibCall(TLI.getLibcallName(RTLIB::SRL_I64), Node,
5846                       false/*lshr is unsigned*/, Hi);
5847    break;
5848  }
5849
5850  case ISD::ADD:
5851  case ISD::SUB: {
5852    // If the target wants to custom expand this, let them.
5853    if (TLI.getOperationAction(Node->getOpcode(), VT) ==
5854            TargetLowering::Custom) {
5855      Op = TLI.LowerOperation(Op, DAG);
5856      if (Op.Val) {
5857        ExpandOp(Op, Lo, Hi);
5858        break;
5859      }
5860    }
5861
5862    // Expand the subcomponents.
5863    SDOperand LHSL, LHSH, RHSL, RHSH;
5864    ExpandOp(Node->getOperand(0), LHSL, LHSH);
5865    ExpandOp(Node->getOperand(1), RHSL, RHSH);
5866    SDVTList VTList = DAG.getVTList(LHSL.getValueType(), MVT::Flag);
5867    SDOperand LoOps[2], HiOps[3];
5868    LoOps[0] = LHSL;
5869    LoOps[1] = RHSL;
5870    HiOps[0] = LHSH;
5871    HiOps[1] = RHSH;
5872    if (Node->getOpcode() == ISD::ADD) {
5873      Lo = DAG.getNode(ISD::ADDC, VTList, LoOps, 2);
5874      HiOps[2] = Lo.getValue(1);
5875      Hi = DAG.getNode(ISD::ADDE, VTList, HiOps, 3);
5876    } else {
5877      Lo = DAG.getNode(ISD::SUBC, VTList, LoOps, 2);
5878      HiOps[2] = Lo.getValue(1);
5879      Hi = DAG.getNode(ISD::SUBE, VTList, HiOps, 3);
5880    }
5881    break;
5882  }
5883
5884  case ISD::ADDC:
5885  case ISD::SUBC: {
5886    // Expand the subcomponents.
5887    SDOperand LHSL, LHSH, RHSL, RHSH;
5888    ExpandOp(Node->getOperand(0), LHSL, LHSH);
5889    ExpandOp(Node->getOperand(1), RHSL, RHSH);
5890    SDVTList VTList = DAG.getVTList(LHSL.getValueType(), MVT::Flag);
5891    SDOperand LoOps[2] = { LHSL, RHSL };
5892    SDOperand HiOps[3] = { LHSH, RHSH };
5893
5894    if (Node->getOpcode() == ISD::ADDC) {
5895      Lo = DAG.getNode(ISD::ADDC, VTList, LoOps, 2);
5896      HiOps[2] = Lo.getValue(1);
5897      Hi = DAG.getNode(ISD::ADDE, VTList, HiOps, 3);
5898    } else {
5899      Lo = DAG.getNode(ISD::SUBC, VTList, LoOps, 2);
5900      HiOps[2] = Lo.getValue(1);
5901      Hi = DAG.getNode(ISD::SUBE, VTList, HiOps, 3);
5902    }
5903    // Remember that we legalized the flag.
5904    AddLegalizedOperand(Op.getValue(1), LegalizeOp(Hi.getValue(1)));
5905    break;
5906  }
5907  case ISD::ADDE:
5908  case ISD::SUBE: {
5909    // Expand the subcomponents.
5910    SDOperand LHSL, LHSH, RHSL, RHSH;
5911    ExpandOp(Node->getOperand(0), LHSL, LHSH);
5912    ExpandOp(Node->getOperand(1), RHSL, RHSH);
5913    SDVTList VTList = DAG.getVTList(LHSL.getValueType(), MVT::Flag);
5914    SDOperand LoOps[3] = { LHSL, RHSL, Node->getOperand(2) };
5915    SDOperand HiOps[3] = { LHSH, RHSH };
5916
5917    Lo = DAG.getNode(Node->getOpcode(), VTList, LoOps, 3);
5918    HiOps[2] = Lo.getValue(1);
5919    Hi = DAG.getNode(Node->getOpcode(), VTList, HiOps, 3);
5920
5921    // Remember that we legalized the flag.
5922    AddLegalizedOperand(Op.getValue(1), LegalizeOp(Hi.getValue(1)));
5923    break;
5924  }
5925  case ISD::MUL: {
5926    // If the target wants to custom expand this, let them.
5927    if (TLI.getOperationAction(ISD::MUL, VT) == TargetLowering::Custom) {
5928      SDOperand New = TLI.LowerOperation(Op, DAG);
5929      if (New.Val) {
5930        ExpandOp(New, Lo, Hi);
5931        break;
5932      }
5933    }
5934
5935    bool HasMULHS = TLI.isOperationLegal(ISD::MULHS, NVT);
5936    bool HasMULHU = TLI.isOperationLegal(ISD::MULHU, NVT);
5937    bool HasSMUL_LOHI = TLI.isOperationLegal(ISD::SMUL_LOHI, NVT);
5938    bool HasUMUL_LOHI = TLI.isOperationLegal(ISD::UMUL_LOHI, NVT);
5939    if (HasMULHU || HasMULHS || HasUMUL_LOHI || HasSMUL_LOHI) {
5940      SDOperand LL, LH, RL, RH;
5941      ExpandOp(Node->getOperand(0), LL, LH);
5942      ExpandOp(Node->getOperand(1), RL, RH);
5943      unsigned BitSize = MVT::getSizeInBits(RH.getValueType());
5944      unsigned LHSSB = DAG.ComputeNumSignBits(Op.getOperand(0));
5945      unsigned RHSSB = DAG.ComputeNumSignBits(Op.getOperand(1));
5946      // FIXME: generalize this to handle other bit sizes
5947      if (LHSSB == 32 && RHSSB == 32 &&
5948          DAG.MaskedValueIsZero(Op.getOperand(0), 0xFFFFFFFF00000000ULL) &&
5949          DAG.MaskedValueIsZero(Op.getOperand(1), 0xFFFFFFFF00000000ULL)) {
5950        // The inputs are both zero-extended.
5951        if (HasUMUL_LOHI) {
5952          // We can emit a umul_lohi.
5953          Lo = DAG.getNode(ISD::UMUL_LOHI, DAG.getVTList(NVT, NVT), LL, RL);
5954          Hi = SDOperand(Lo.Val, 1);
5955          break;
5956        }
5957        if (HasMULHU) {
5958          // We can emit a mulhu+mul.
5959          Lo = DAG.getNode(ISD::MUL, NVT, LL, RL);
5960          Hi = DAG.getNode(ISD::MULHU, NVT, LL, RL);
5961          break;
5962        }
5963      }
5964      if (LHSSB > BitSize && RHSSB > BitSize) {
5965        // The input values are both sign-extended.
5966        if (HasSMUL_LOHI) {
5967          // We can emit a smul_lohi.
5968          Lo = DAG.getNode(ISD::SMUL_LOHI, DAG.getVTList(NVT, NVT), LL, RL);
5969          Hi = SDOperand(Lo.Val, 1);
5970          break;
5971        }
5972        if (HasMULHS) {
5973          // We can emit a mulhs+mul.
5974          Lo = DAG.getNode(ISD::MUL, NVT, LL, RL);
5975          Hi = DAG.getNode(ISD::MULHS, NVT, LL, RL);
5976          break;
5977        }
5978      }
5979      if (HasUMUL_LOHI) {
5980        // Lo,Hi = umul LHS, RHS.
5981        SDOperand UMulLOHI = DAG.getNode(ISD::UMUL_LOHI,
5982                                         DAG.getVTList(NVT, NVT), LL, RL);
5983        Lo = UMulLOHI;
5984        Hi = UMulLOHI.getValue(1);
5985        RH = DAG.getNode(ISD::MUL, NVT, LL, RH);
5986        LH = DAG.getNode(ISD::MUL, NVT, LH, RL);
5987        Hi = DAG.getNode(ISD::ADD, NVT, Hi, RH);
5988        Hi = DAG.getNode(ISD::ADD, NVT, Hi, LH);
5989        break;
5990      }
5991      if (HasMULHU) {
5992        Lo = DAG.getNode(ISD::MUL, NVT, LL, RL);
5993        Hi = DAG.getNode(ISD::MULHU, NVT, LL, RL);
5994        RH = DAG.getNode(ISD::MUL, NVT, LL, RH);
5995        LH = DAG.getNode(ISD::MUL, NVT, LH, RL);
5996        Hi = DAG.getNode(ISD::ADD, NVT, Hi, RH);
5997        Hi = DAG.getNode(ISD::ADD, NVT, Hi, LH);
5998        break;
5999      }
6000    }
6001
6002    // If nothing else, we can make a libcall.
6003    Lo = ExpandLibCall(TLI.getLibcallName(RTLIB::MUL_I64), Node,
6004                       false/*sign irrelevant*/, Hi);
6005    break;
6006  }
6007  case ISD::SDIV:
6008    Lo = ExpandLibCall(TLI.getLibcallName(RTLIB::SDIV_I64), Node, true, Hi);
6009    break;
6010  case ISD::UDIV:
6011    Lo = ExpandLibCall(TLI.getLibcallName(RTLIB::UDIV_I64), Node, true, Hi);
6012    break;
6013  case ISD::SREM:
6014    Lo = ExpandLibCall(TLI.getLibcallName(RTLIB::SREM_I64), Node, true, Hi);
6015    break;
6016  case ISD::UREM:
6017    Lo = ExpandLibCall(TLI.getLibcallName(RTLIB::UREM_I64), Node, true, Hi);
6018    break;
6019
6020  case ISD::FADD:
6021    Lo = ExpandLibCall(TLI.getLibcallName(VT == MVT::f32 ? RTLIB::ADD_F32 :
6022                                          VT == MVT::f64 ? RTLIB::ADD_F64 :
6023                                          VT == MVT::ppcf128 ?
6024                                                      RTLIB::ADD_PPCF128 :
6025                                          RTLIB::UNKNOWN_LIBCALL),
6026                       Node, false, Hi);
6027    break;
6028  case ISD::FSUB:
6029    Lo = ExpandLibCall(TLI.getLibcallName(VT == MVT::f32 ? RTLIB::SUB_F32 :
6030                                          VT == MVT::f64 ? RTLIB::SUB_F64 :
6031                                          VT == MVT::ppcf128 ?
6032                                                      RTLIB::SUB_PPCF128 :
6033                                          RTLIB::UNKNOWN_LIBCALL),
6034                       Node, false, Hi);
6035    break;
6036  case ISD::FMUL:
6037    Lo = ExpandLibCall(TLI.getLibcallName(VT == MVT::f32 ? RTLIB::MUL_F32 :
6038                                          VT == MVT::f64 ? RTLIB::MUL_F64 :
6039                                          VT == MVT::ppcf128 ?
6040                                                      RTLIB::MUL_PPCF128 :
6041                                          RTLIB::UNKNOWN_LIBCALL),
6042                       Node, false, Hi);
6043    break;
6044  case ISD::FDIV:
6045    Lo = ExpandLibCall(TLI.getLibcallName(VT == MVT::f32 ? RTLIB::DIV_F32 :
6046                                          VT == MVT::f64 ? RTLIB::DIV_F64 :
6047                                          VT == MVT::ppcf128 ?
6048                                                      RTLIB::DIV_PPCF128 :
6049                                          RTLIB::UNKNOWN_LIBCALL),
6050                       Node, false, Hi);
6051    break;
6052  case ISD::FP_EXTEND:
6053    if (VT == MVT::ppcf128) {
6054      assert(Node->getOperand(0).getValueType()==MVT::f32 ||
6055             Node->getOperand(0).getValueType()==MVT::f64);
6056      const uint64_t zero = 0;
6057      if (Node->getOperand(0).getValueType()==MVT::f32)
6058        Hi = DAG.getNode(ISD::FP_EXTEND, MVT::f64, Node->getOperand(0));
6059      else
6060        Hi = Node->getOperand(0);
6061      Lo = DAG.getConstantFP(APFloat(APInt(64, 1, &zero)), MVT::f64);
6062      break;
6063    }
6064    Lo = ExpandLibCall(TLI.getLibcallName(RTLIB::FPEXT_F32_F64), Node, true,Hi);
6065    break;
6066  case ISD::FP_ROUND:
6067    Lo = ExpandLibCall(TLI.getLibcallName(RTLIB::FPROUND_F64_F32),Node,true,Hi);
6068    break;
6069  case ISD::FPOWI:
6070    Lo = ExpandLibCall(TLI.getLibcallName((VT == MVT::f32) ? RTLIB::POWI_F32 :
6071                                          (VT == MVT::f64) ? RTLIB::POWI_F64 :
6072                                          (VT == MVT::f80) ? RTLIB::POWI_F80 :
6073                                          (VT == MVT::ppcf128) ?
6074                                                         RTLIB::POWI_PPCF128 :
6075                                          RTLIB::UNKNOWN_LIBCALL),
6076                       Node, false, Hi);
6077    break;
6078  case ISD::FSQRT:
6079  case ISD::FSIN:
6080  case ISD::FCOS: {
6081    RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
6082    switch(Node->getOpcode()) {
6083    case ISD::FSQRT:
6084      LC = (VT == MVT::f32) ? RTLIB::SQRT_F32 :
6085           (VT == MVT::f64) ? RTLIB::SQRT_F64 :
6086           (VT == MVT::f80) ? RTLIB::SQRT_F80 :
6087           (VT == MVT::ppcf128) ? RTLIB::SQRT_PPCF128 :
6088           RTLIB::UNKNOWN_LIBCALL;
6089      break;
6090    case ISD::FSIN:
6091      LC = (VT == MVT::f32) ? RTLIB::SIN_F32 : RTLIB::SIN_F64;
6092      break;
6093    case ISD::FCOS:
6094      LC = (VT == MVT::f32) ? RTLIB::COS_F32 : RTLIB::COS_F64;
6095      break;
6096    default: assert(0 && "Unreachable!");
6097    }
6098    Lo = ExpandLibCall(TLI.getLibcallName(LC), Node, false, Hi);
6099    break;
6100  }
6101  case ISD::FABS: {
6102    if (VT == MVT::ppcf128) {
6103      SDOperand Tmp;
6104      ExpandOp(Node->getOperand(0), Lo, Tmp);
6105      Hi = DAG.getNode(ISD::FABS, NVT, Tmp);
6106      // lo = hi==fabs(hi) ? lo : -lo;
6107      Lo = DAG.getNode(ISD::SELECT_CC, NVT, Hi, Tmp,
6108                    Lo, DAG.getNode(ISD::FNEG, NVT, Lo),
6109                    DAG.getCondCode(ISD::SETEQ));
6110      break;
6111    }
6112    SDOperand Mask = (VT == MVT::f64)
6113      ? DAG.getConstantFP(BitsToDouble(~(1ULL << 63)), VT)
6114      : DAG.getConstantFP(BitsToFloat(~(1U << 31)), VT);
6115    Mask = DAG.getNode(ISD::BIT_CONVERT, NVT, Mask);
6116    Lo = DAG.getNode(ISD::BIT_CONVERT, NVT, Node->getOperand(0));
6117    Lo = DAG.getNode(ISD::AND, NVT, Lo, Mask);
6118    if (getTypeAction(NVT) == Expand)
6119      ExpandOp(Lo, Lo, Hi);
6120    break;
6121  }
6122  case ISD::FNEG: {
6123    if (VT == MVT::ppcf128) {
6124      ExpandOp(Node->getOperand(0), Lo, Hi);
6125      Lo = DAG.getNode(ISD::FNEG, MVT::f64, Lo);
6126      Hi = DAG.getNode(ISD::FNEG, MVT::f64, Hi);
6127      break;
6128    }
6129    SDOperand Mask = (VT == MVT::f64)
6130      ? DAG.getConstantFP(BitsToDouble(1ULL << 63), VT)
6131      : DAG.getConstantFP(BitsToFloat(1U << 31), VT);
6132    Mask = DAG.getNode(ISD::BIT_CONVERT, NVT, Mask);
6133    Lo = DAG.getNode(ISD::BIT_CONVERT, NVT, Node->getOperand(0));
6134    Lo = DAG.getNode(ISD::XOR, NVT, Lo, Mask);
6135    if (getTypeAction(NVT) == Expand)
6136      ExpandOp(Lo, Lo, Hi);
6137    break;
6138  }
6139  case ISD::FCOPYSIGN: {
6140    Lo = ExpandFCOPYSIGNToBitwiseOps(Node, NVT, DAG, TLI);
6141    if (getTypeAction(NVT) == Expand)
6142      ExpandOp(Lo, Lo, Hi);
6143    break;
6144  }
6145  case ISD::SINT_TO_FP:
6146  case ISD::UINT_TO_FP: {
6147    bool isSigned = Node->getOpcode() == ISD::SINT_TO_FP;
6148    MVT::ValueType SrcVT = Node->getOperand(0).getValueType();
6149    if (VT == MVT::ppcf128 && SrcVT != MVT::i64) {
6150      static uint64_t zero = 0;
6151      if (isSigned) {
6152        Hi = LegalizeOp(DAG.getNode(ISD::SINT_TO_FP, MVT::f64,
6153                                    Node->getOperand(0)));
6154        Lo = DAG.getConstantFP(APFloat(APInt(64, 1, &zero)), MVT::f64);
6155      } else {
6156        static uint64_t TwoE32[] = { 0x41f0000000000000LL, 0 };
6157        Hi = LegalizeOp(DAG.getNode(ISD::SINT_TO_FP, MVT::f64,
6158                                    Node->getOperand(0)));
6159        Lo = DAG.getConstantFP(APFloat(APInt(64, 1, &zero)), MVT::f64);
6160        Hi = DAG.getNode(ISD::BUILD_PAIR, VT, Lo, Hi);
6161        // X>=0 ? {(f64)x, 0} : {(f64)x, 0} + 2^32
6162        ExpandOp(DAG.getNode(ISD::SELECT_CC, MVT::ppcf128, Node->getOperand(0),
6163                             DAG.getConstant(0, MVT::i32),
6164                             DAG.getNode(ISD::FADD, MVT::ppcf128, Hi,
6165                                         DAG.getConstantFP(
6166                                            APFloat(APInt(128, 2, TwoE32)),
6167                                            MVT::ppcf128)),
6168                             Hi,
6169                             DAG.getCondCode(ISD::SETLT)),
6170                 Lo, Hi);
6171      }
6172      break;
6173    }
6174    if (VT == MVT::ppcf128 && SrcVT == MVT::i64 && !isSigned) {
6175      // si64->ppcf128 done by libcall, below
6176      static uint64_t TwoE64[] = { 0x43f0000000000000LL, 0 };
6177      ExpandOp(DAG.getNode(ISD::SINT_TO_FP, MVT::ppcf128, Node->getOperand(0)),
6178               Lo, Hi);
6179      Hi = DAG.getNode(ISD::BUILD_PAIR, VT, Lo, Hi);
6180      // x>=0 ? (ppcf128)(i64)x : (ppcf128)(i64)x + 2^64
6181      ExpandOp(DAG.getNode(ISD::SELECT_CC, MVT::ppcf128, Node->getOperand(0),
6182                           DAG.getConstant(0, MVT::i64),
6183                           DAG.getNode(ISD::FADD, MVT::ppcf128, Hi,
6184                                       DAG.getConstantFP(
6185                                          APFloat(APInt(128, 2, TwoE64)),
6186                                          MVT::ppcf128)),
6187                           Hi,
6188                           DAG.getCondCode(ISD::SETLT)),
6189               Lo, Hi);
6190      break;
6191    }
6192    RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
6193    if (Node->getOperand(0).getValueType() == MVT::i64) {
6194      if (VT == MVT::f32)
6195        LC = isSigned ? RTLIB::SINTTOFP_I64_F32 : RTLIB::UINTTOFP_I64_F32;
6196      else if (VT == MVT::f64)
6197        LC = isSigned ? RTLIB::SINTTOFP_I64_F64 : RTLIB::UINTTOFP_I64_F64;
6198      else if (VT == MVT::f80) {
6199        assert(isSigned);
6200        LC = RTLIB::SINTTOFP_I64_F80;
6201      }
6202      else if (VT == MVT::ppcf128) {
6203        assert(isSigned);
6204        LC = RTLIB::SINTTOFP_I64_PPCF128;
6205      }
6206    } else {
6207      if (VT == MVT::f32)
6208        LC = isSigned ? RTLIB::SINTTOFP_I32_F32 : RTLIB::UINTTOFP_I32_F32;
6209      else
6210        LC = isSigned ? RTLIB::SINTTOFP_I32_F64 : RTLIB::UINTTOFP_I32_F64;
6211    }
6212
6213    // Promote the operand if needed.
6214    if (getTypeAction(SrcVT) == Promote) {
6215      SDOperand Tmp = PromoteOp(Node->getOperand(0));
6216      Tmp = isSigned
6217        ? DAG.getNode(ISD::SIGN_EXTEND_INREG, Tmp.getValueType(), Tmp,
6218                      DAG.getValueType(SrcVT))
6219        : DAG.getZeroExtendInReg(Tmp, SrcVT);
6220      Node = DAG.UpdateNodeOperands(Op, Tmp).Val;
6221    }
6222
6223    const char *LibCall = TLI.getLibcallName(LC);
6224    if (LibCall)
6225      Lo = ExpandLibCall(TLI.getLibcallName(LC), Node, isSigned, Hi);
6226    else  {
6227      Lo = ExpandIntToFP(Node->getOpcode() == ISD::SINT_TO_FP, VT,
6228                         Node->getOperand(0));
6229      if (getTypeAction(Lo.getValueType()) == Expand)
6230        ExpandOp(Lo, Lo, Hi);
6231    }
6232    break;
6233  }
6234  }
6235
6236  // Make sure the resultant values have been legalized themselves, unless this
6237  // is a type that requires multi-step expansion.
6238  if (getTypeAction(NVT) != Expand && NVT != MVT::isVoid) {
6239    Lo = LegalizeOp(Lo);
6240    if (Hi.Val)
6241      // Don't legalize the high part if it is expanded to a single node.
6242      Hi = LegalizeOp(Hi);
6243  }
6244
6245  // Remember in a map if the values will be reused later.
6246  bool isNew = ExpandedNodes.insert(std::make_pair(Op, std::make_pair(Lo, Hi)));
6247  assert(isNew && "Value already expanded?!?");
6248}
6249
6250/// SplitVectorOp - Given an operand of vector type, break it down into
6251/// two smaller values, still of vector type.
6252void SelectionDAGLegalize::SplitVectorOp(SDOperand Op, SDOperand &Lo,
6253                                         SDOperand &Hi) {
6254  assert(MVT::isVector(Op.getValueType()) && "Cannot split non-vector type!");
6255  SDNode *Node = Op.Val;
6256  unsigned NumElements = MVT::getVectorNumElements(Op.getValueType());
6257  assert(NumElements > 1 && "Cannot split a single element vector!");
6258
6259  MVT::ValueType NewEltVT = MVT::getVectorElementType(Op.getValueType());
6260
6261  unsigned NewNumElts_Lo = 1 << Log2_32(NumElements-1);
6262  unsigned NewNumElts_Hi = NumElements - NewNumElts_Lo;
6263
6264  MVT::ValueType NewVT_Lo = MVT::getVectorType(NewEltVT, NewNumElts_Lo);
6265  MVT::ValueType NewVT_Hi = MVT::getVectorType(NewEltVT, NewNumElts_Hi);
6266
6267  // See if we already split it.
6268  std::map<SDOperand, std::pair<SDOperand, SDOperand> >::iterator I
6269    = SplitNodes.find(Op);
6270  if (I != SplitNodes.end()) {
6271    Lo = I->second.first;
6272    Hi = I->second.second;
6273    return;
6274  }
6275
6276  switch (Node->getOpcode()) {
6277  default:
6278#ifndef NDEBUG
6279    Node->dump(&DAG);
6280#endif
6281    assert(0 && "Unhandled operation in SplitVectorOp!");
6282  case ISD::UNDEF:
6283    Lo = DAG.getNode(ISD::UNDEF, NewVT_Lo);
6284    Hi = DAG.getNode(ISD::UNDEF, NewVT_Hi);
6285    break;
6286  case ISD::BUILD_PAIR:
6287    Lo = Node->getOperand(0);
6288    Hi = Node->getOperand(1);
6289    break;
6290  case ISD::INSERT_VECTOR_ELT: {
6291    SplitVectorOp(Node->getOperand(0), Lo, Hi);
6292    unsigned Index = cast<ConstantSDNode>(Node->getOperand(2))->getValue();
6293    SDOperand ScalarOp = Node->getOperand(1);
6294    if (Index < NewNumElts_Lo)
6295      Lo = DAG.getNode(ISD::INSERT_VECTOR_ELT, NewVT_Lo, Lo, ScalarOp,
6296                       DAG.getConstant(Index, TLI.getPointerTy()));
6297    else
6298      Hi = DAG.getNode(ISD::INSERT_VECTOR_ELT, NewVT_Hi, Hi, ScalarOp,
6299                       DAG.getConstant(Index - NewNumElts_Lo,
6300                                       TLI.getPointerTy()));
6301    break;
6302  }
6303  case ISD::VECTOR_SHUFFLE: {
6304    // Build the low part.
6305    SDOperand Mask = Node->getOperand(2);
6306    SmallVector<SDOperand, 8> Ops;
6307    MVT::ValueType PtrVT = TLI.getPointerTy();
6308
6309    // Insert all of the elements from the input that are needed.  We use
6310    // buildvector of extractelement here because the input vectors will have
6311    // to be legalized, so this makes the code simpler.
6312    for (unsigned i = 0; i != NewNumElts_Lo; ++i) {
6313      unsigned Idx = cast<ConstantSDNode>(Mask.getOperand(i))->getValue();
6314      SDOperand InVec = Node->getOperand(0);
6315      if (Idx >= NumElements) {
6316        InVec = Node->getOperand(1);
6317        Idx -= NumElements;
6318      }
6319      Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, NewEltVT, InVec,
6320                                DAG.getConstant(Idx, PtrVT)));
6321    }
6322    Lo = DAG.getNode(ISD::BUILD_VECTOR, NewVT_Lo, &Ops[0], Ops.size());
6323    Ops.clear();
6324
6325    for (unsigned i = NewNumElts_Lo; i != NumElements; ++i) {
6326      unsigned Idx = cast<ConstantSDNode>(Mask.getOperand(i))->getValue();
6327      SDOperand InVec = Node->getOperand(0);
6328      if (Idx >= NumElements) {
6329        InVec = Node->getOperand(1);
6330        Idx -= NumElements;
6331      }
6332      Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, NewEltVT, InVec,
6333                                DAG.getConstant(Idx, PtrVT)));
6334    }
6335    Hi = DAG.getNode(ISD::BUILD_VECTOR, NewVT_Lo, &Ops[0], Ops.size());
6336    break;
6337  }
6338  case ISD::BUILD_VECTOR: {
6339    SmallVector<SDOperand, 8> LoOps(Node->op_begin(),
6340                                    Node->op_begin()+NewNumElts_Lo);
6341    Lo = DAG.getNode(ISD::BUILD_VECTOR, NewVT_Lo, &LoOps[0], LoOps.size());
6342
6343    SmallVector<SDOperand, 8> HiOps(Node->op_begin()+NewNumElts_Lo,
6344                                    Node->op_end());
6345    Hi = DAG.getNode(ISD::BUILD_VECTOR, NewVT_Hi, &HiOps[0], HiOps.size());
6346    break;
6347  }
6348  case ISD::CONCAT_VECTORS: {
6349    // FIXME: Handle non-power-of-two vectors?
6350    unsigned NewNumSubvectors = Node->getNumOperands() / 2;
6351    if (NewNumSubvectors == 1) {
6352      Lo = Node->getOperand(0);
6353      Hi = Node->getOperand(1);
6354    } else {
6355      SmallVector<SDOperand, 8> LoOps(Node->op_begin(),
6356                                      Node->op_begin()+NewNumSubvectors);
6357      Lo = DAG.getNode(ISD::CONCAT_VECTORS, NewVT_Lo, &LoOps[0], LoOps.size());
6358
6359      SmallVector<SDOperand, 8> HiOps(Node->op_begin()+NewNumSubvectors,
6360                                      Node->op_end());
6361      Hi = DAG.getNode(ISD::CONCAT_VECTORS, NewVT_Hi, &HiOps[0], HiOps.size());
6362    }
6363    break;
6364  }
6365  case ISD::SELECT: {
6366    SDOperand Cond = Node->getOperand(0);
6367
6368    SDOperand LL, LH, RL, RH;
6369    SplitVectorOp(Node->getOperand(1), LL, LH);
6370    SplitVectorOp(Node->getOperand(2), RL, RH);
6371
6372    if (MVT::isVector(Cond.getValueType())) {
6373      // Handle a vector merge.
6374      SDOperand CL, CH;
6375      SplitVectorOp(Cond, CL, CH);
6376      Lo = DAG.getNode(Node->getOpcode(), NewVT_Lo, CL, LL, RL);
6377      Hi = DAG.getNode(Node->getOpcode(), NewVT_Hi, CH, LH, RH);
6378    } else {
6379      // Handle a simple select with vector operands.
6380      Lo = DAG.getNode(Node->getOpcode(), NewVT_Lo, Cond, LL, RL);
6381      Hi = DAG.getNode(Node->getOpcode(), NewVT_Hi, Cond, LH, RH);
6382    }
6383    break;
6384  }
6385  case ISD::ADD:
6386  case ISD::SUB:
6387  case ISD::MUL:
6388  case ISD::FADD:
6389  case ISD::FSUB:
6390  case ISD::FMUL:
6391  case ISD::SDIV:
6392  case ISD::UDIV:
6393  case ISD::FDIV:
6394  case ISD::FPOW:
6395  case ISD::AND:
6396  case ISD::OR:
6397  case ISD::XOR:
6398  case ISD::UREM:
6399  case ISD::SREM:
6400  case ISD::FREM: {
6401    SDOperand LL, LH, RL, RH;
6402    SplitVectorOp(Node->getOperand(0), LL, LH);
6403    SplitVectorOp(Node->getOperand(1), RL, RH);
6404
6405    Lo = DAG.getNode(Node->getOpcode(), NewVT_Lo, LL, RL);
6406    Hi = DAG.getNode(Node->getOpcode(), NewVT_Hi, LH, RH);
6407    break;
6408  }
6409  case ISD::FPOWI: {
6410    SDOperand L, H;
6411    SplitVectorOp(Node->getOperand(0), L, H);
6412
6413    Lo = DAG.getNode(Node->getOpcode(), NewVT_Lo, L, Node->getOperand(1));
6414    Hi = DAG.getNode(Node->getOpcode(), NewVT_Hi, H, Node->getOperand(1));
6415    break;
6416  }
6417  case ISD::CTTZ:
6418  case ISD::CTLZ:
6419  case ISD::CTPOP:
6420  case ISD::FNEG:
6421  case ISD::FABS:
6422  case ISD::FSQRT:
6423  case ISD::FSIN:
6424  case ISD::FCOS:
6425  case ISD::FP_TO_SINT:
6426  case ISD::FP_TO_UINT:
6427  case ISD::SINT_TO_FP:
6428  case ISD::UINT_TO_FP: {
6429    SDOperand L, H;
6430    SplitVectorOp(Node->getOperand(0), L, H);
6431
6432    Lo = DAG.getNode(Node->getOpcode(), NewVT_Lo, L);
6433    Hi = DAG.getNode(Node->getOpcode(), NewVT_Hi, H);
6434    break;
6435  }
6436  case ISD::LOAD: {
6437    LoadSDNode *LD = cast<LoadSDNode>(Node);
6438    SDOperand Ch = LD->getChain();
6439    SDOperand Ptr = LD->getBasePtr();
6440    const Value *SV = LD->getSrcValue();
6441    int SVOffset = LD->getSrcValueOffset();
6442    unsigned Alignment = LD->getAlignment();
6443    bool isVolatile = LD->isVolatile();
6444
6445    Lo = DAG.getLoad(NewVT_Lo, Ch, Ptr, SV, SVOffset, isVolatile, Alignment);
6446    unsigned IncrementSize = NewNumElts_Lo * MVT::getSizeInBits(NewEltVT)/8;
6447    Ptr = DAG.getNode(ISD::ADD, Ptr.getValueType(), Ptr,
6448                      getIntPtrConstant(IncrementSize));
6449    SVOffset += IncrementSize;
6450    Alignment = MinAlign(Alignment, IncrementSize);
6451    Hi = DAG.getLoad(NewVT_Hi, Ch, Ptr, SV, SVOffset, isVolatile, Alignment);
6452
6453    // Build a factor node to remember that this load is independent of the
6454    // other one.
6455    SDOperand TF = DAG.getNode(ISD::TokenFactor, MVT::Other, Lo.getValue(1),
6456                               Hi.getValue(1));
6457
6458    // Remember that we legalized the chain.
6459    AddLegalizedOperand(Op.getValue(1), LegalizeOp(TF));
6460    break;
6461  }
6462  case ISD::BIT_CONVERT: {
6463    // We know the result is a vector.  The input may be either a vector or a
6464    // scalar value.
6465    SDOperand InOp = Node->getOperand(0);
6466    if (!MVT::isVector(InOp.getValueType()) ||
6467        MVT::getVectorNumElements(InOp.getValueType()) == 1) {
6468      // The input is a scalar or single-element vector.
6469      // Lower to a store/load so that it can be split.
6470      // FIXME: this could be improved probably.
6471      SDOperand Ptr = DAG.CreateStackTemporary(InOp.getValueType());
6472
6473      SDOperand St = DAG.getStore(DAG.getEntryNode(),
6474                                  InOp, Ptr, NULL, 0);
6475      InOp = DAG.getLoad(Op.getValueType(), St, Ptr, NULL, 0);
6476    }
6477    // Split the vector and convert each of the pieces now.
6478    SplitVectorOp(InOp, Lo, Hi);
6479    Lo = DAG.getNode(ISD::BIT_CONVERT, NewVT_Lo, Lo);
6480    Hi = DAG.getNode(ISD::BIT_CONVERT, NewVT_Hi, Hi);
6481    break;
6482  }
6483  }
6484
6485  // Remember in a map if the values will be reused later.
6486  bool isNew =
6487    SplitNodes.insert(std::make_pair(Op, std::make_pair(Lo, Hi))).second;
6488  assert(isNew && "Value already split?!?");
6489}
6490
6491
6492/// ScalarizeVectorOp - Given an operand of single-element vector type
6493/// (e.g. v1f32), convert it into the equivalent operation that returns a
6494/// scalar (e.g. f32) value.
6495SDOperand SelectionDAGLegalize::ScalarizeVectorOp(SDOperand Op) {
6496  assert(MVT::isVector(Op.getValueType()) &&
6497         "Bad ScalarizeVectorOp invocation!");
6498  SDNode *Node = Op.Val;
6499  MVT::ValueType NewVT = MVT::getVectorElementType(Op.getValueType());
6500  assert(MVT::getVectorNumElements(Op.getValueType()) == 1);
6501
6502  // See if we already scalarized it.
6503  std::map<SDOperand, SDOperand>::iterator I = ScalarizedNodes.find(Op);
6504  if (I != ScalarizedNodes.end()) return I->second;
6505
6506  SDOperand Result;
6507  switch (Node->getOpcode()) {
6508  default:
6509#ifndef NDEBUG
6510    Node->dump(&DAG); cerr << "\n";
6511#endif
6512    assert(0 && "Unknown vector operation in ScalarizeVectorOp!");
6513  case ISD::ADD:
6514  case ISD::FADD:
6515  case ISD::SUB:
6516  case ISD::FSUB:
6517  case ISD::MUL:
6518  case ISD::FMUL:
6519  case ISD::SDIV:
6520  case ISD::UDIV:
6521  case ISD::FDIV:
6522  case ISD::SREM:
6523  case ISD::UREM:
6524  case ISD::FREM:
6525  case ISD::FPOW:
6526  case ISD::AND:
6527  case ISD::OR:
6528  case ISD::XOR:
6529    Result = DAG.getNode(Node->getOpcode(),
6530                         NewVT,
6531                         ScalarizeVectorOp(Node->getOperand(0)),
6532                         ScalarizeVectorOp(Node->getOperand(1)));
6533    break;
6534  case ISD::FNEG:
6535  case ISD::FABS:
6536  case ISD::FSQRT:
6537  case ISD::FSIN:
6538  case ISD::FCOS:
6539    Result = DAG.getNode(Node->getOpcode(),
6540                         NewVT,
6541                         ScalarizeVectorOp(Node->getOperand(0)));
6542    break;
6543  case ISD::FPOWI:
6544    Result = DAG.getNode(Node->getOpcode(),
6545                         NewVT,
6546                         ScalarizeVectorOp(Node->getOperand(0)),
6547                         Node->getOperand(1));
6548    break;
6549  case ISD::LOAD: {
6550    LoadSDNode *LD = cast<LoadSDNode>(Node);
6551    SDOperand Ch = LegalizeOp(LD->getChain());     // Legalize the chain.
6552    SDOperand Ptr = LegalizeOp(LD->getBasePtr());  // Legalize the pointer.
6553
6554    const Value *SV = LD->getSrcValue();
6555    int SVOffset = LD->getSrcValueOffset();
6556    Result = DAG.getLoad(NewVT, Ch, Ptr, SV, SVOffset,
6557                         LD->isVolatile(), LD->getAlignment());
6558
6559    // Remember that we legalized the chain.
6560    AddLegalizedOperand(Op.getValue(1), LegalizeOp(Result.getValue(1)));
6561    break;
6562  }
6563  case ISD::BUILD_VECTOR:
6564    Result = Node->getOperand(0);
6565    break;
6566  case ISD::INSERT_VECTOR_ELT:
6567    // Returning the inserted scalar element.
6568    Result = Node->getOperand(1);
6569    break;
6570  case ISD::CONCAT_VECTORS:
6571    assert(Node->getOperand(0).getValueType() == NewVT &&
6572           "Concat of non-legal vectors not yet supported!");
6573    Result = Node->getOperand(0);
6574    break;
6575  case ISD::VECTOR_SHUFFLE: {
6576    // Figure out if the scalar is the LHS or RHS and return it.
6577    SDOperand EltNum = Node->getOperand(2).getOperand(0);
6578    if (cast<ConstantSDNode>(EltNum)->getValue())
6579      Result = ScalarizeVectorOp(Node->getOperand(1));
6580    else
6581      Result = ScalarizeVectorOp(Node->getOperand(0));
6582    break;
6583  }
6584  case ISD::EXTRACT_SUBVECTOR:
6585    Result = Node->getOperand(0);
6586    assert(Result.getValueType() == NewVT);
6587    break;
6588  case ISD::BIT_CONVERT:
6589    Result = DAG.getNode(ISD::BIT_CONVERT, NewVT, Op.getOperand(0));
6590    break;
6591  case ISD::SELECT:
6592    Result = DAG.getNode(ISD::SELECT, NewVT, Op.getOperand(0),
6593                         ScalarizeVectorOp(Op.getOperand(1)),
6594                         ScalarizeVectorOp(Op.getOperand(2)));
6595    break;
6596  }
6597
6598  if (TLI.isTypeLegal(NewVT))
6599    Result = LegalizeOp(Result);
6600  bool isNew = ScalarizedNodes.insert(std::make_pair(Op, Result)).second;
6601  assert(isNew && "Value already scalarized?");
6602  return Result;
6603}
6604
6605
6606// SelectionDAG::Legalize - This is the entry point for the file.
6607//
6608void SelectionDAG::Legalize() {
6609  if (ViewLegalizeDAGs) viewGraph();
6610
6611  /// run - This is the main entry point to this class.
6612  ///
6613  SelectionDAGLegalize(*this).LegalizeDAG();
6614}
6615
6616