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