LegalizeDAG.cpp revision b49e52c7e2d828c45583f862c0f7e1a4a2649aca
1//===-- LegalizeDAG.cpp - Implement SelectionDAG::Legalize ----------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the SelectionDAG::Legalize method.
11//
12//===----------------------------------------------------------------------===//
13
14#include "llvm/CodeGen/SelectionDAG.h"
15#include "llvm/CodeGen/MachineFunction.h"
16#include "llvm/CodeGen/MachineFrameInfo.h"
17#include "llvm/Target/TargetLowering.h"
18#include "llvm/Target/TargetData.h"
19#include "llvm/Target/TargetOptions.h"
20#include "llvm/CallingConv.h"
21#include "llvm/Constants.h"
22#include "llvm/Support/MathExtras.h"
23#include "llvm/Support/CommandLine.h"
24#include <iostream>
25#include <map>
26using namespace llvm;
27
28#ifndef NDEBUG
29static cl::opt<bool>
30ViewLegalizeDAGs("view-legalize-dags", cl::Hidden,
31                 cl::desc("Pop up a window to show dags before legalize"));
32#else
33static const bool ViewLegalizeDAGs = 0;
34#endif
35
36//===----------------------------------------------------------------------===//
37/// SelectionDAGLegalize - This takes an arbitrary SelectionDAG as input and
38/// hacks on it until the target machine can handle it.  This involves
39/// eliminating value sizes the machine cannot handle (promoting small sizes to
40/// large sizes or splitting up large values into small values) as well as
41/// eliminating operations the machine cannot handle.
42///
43/// This code also does a small amount of optimization and recognition of idioms
44/// as part of its processing.  For example, if a target does not support a
45/// 'setcc' instruction efficiently, but does support 'brcc' instruction, this
46/// will attempt merge setcc and brc instructions into brcc's.
47///
48namespace {
49class SelectionDAGLegalize {
50  TargetLowering &TLI;
51  SelectionDAG &DAG;
52
53  // Libcall insertion helpers.
54
55  /// LastCALLSEQ_END - This keeps track of the CALLSEQ_END node that has been
56  /// legalized.  We use this to ensure that calls are properly serialized
57  /// against each other, including inserted libcalls.
58  SDOperand LastCALLSEQ_END;
59
60  /// IsLegalizingCall - This member is used *only* for purposes of providing
61  /// helpful assertions that a libcall isn't created while another call is
62  /// being legalized (which could lead to non-serialized call sequences).
63  bool IsLegalizingCall;
64
65  enum LegalizeAction {
66    Legal,      // The target natively supports this operation.
67    Promote,    // This operation should be executed in a larger type.
68    Expand,     // Try to expand this to other ops, otherwise use a libcall.
69  };
70
71  /// ValueTypeActions - This is a bitvector that contains two bits for each
72  /// value type, where the two bits correspond to the LegalizeAction enum.
73  /// This can be queried with "getTypeAction(VT)".
74  TargetLowering::ValueTypeActionImpl ValueTypeActions;
75
76  /// LegalizedNodes - For nodes that are of legal width, and that have more
77  /// than one use, this map indicates what regularized operand to use.  This
78  /// allows us to avoid legalizing the same thing more than once.
79  std::map<SDOperand, SDOperand> LegalizedNodes;
80
81  /// PromotedNodes - For nodes that are below legal width, and that have more
82  /// than one use, this map indicates what promoted value to use.  This allows
83  /// us to avoid promoting the same thing more than once.
84  std::map<SDOperand, SDOperand> PromotedNodes;
85
86  /// ExpandedNodes - For nodes that need to be expanded this map indicates
87  /// which which operands are the expanded version of the input.  This allows
88  /// us to avoid expanding the same node more than once.
89  std::map<SDOperand, std::pair<SDOperand, SDOperand> > ExpandedNodes;
90
91  /// SplitNodes - For vector nodes that need to be split, this map indicates
92  /// which which operands are the split version of the input.  This allows us
93  /// to avoid splitting the same node more than once.
94  std::map<SDOperand, std::pair<SDOperand, SDOperand> > SplitNodes;
95
96  /// PackedNodes - For nodes that need to be packed from MVT::Vector types to
97  /// concrete packed types, this contains the mapping of ones we have already
98  /// processed to the result.
99  std::map<SDOperand, SDOperand> PackedNodes;
100
101  void AddLegalizedOperand(SDOperand From, SDOperand To) {
102    LegalizedNodes.insert(std::make_pair(From, To));
103    // If someone requests legalization of the new node, return itself.
104    if (From != To)
105      LegalizedNodes.insert(std::make_pair(To, To));
106  }
107  void AddPromotedOperand(SDOperand From, SDOperand To) {
108    bool isNew = PromotedNodes.insert(std::make_pair(From, To)).second;
109    assert(isNew && "Got into the map somehow?");
110    // If someone requests legalization of the new node, return itself.
111    LegalizedNodes.insert(std::make_pair(To, To));
112  }
113
114public:
115
116  SelectionDAGLegalize(SelectionDAG &DAG);
117
118  /// getTypeAction - Return how we should legalize values of this type, either
119  /// it is already legal or we need to expand it into multiple registers of
120  /// smaller integer type, or we need to promote it to a larger type.
121  LegalizeAction getTypeAction(MVT::ValueType VT) const {
122    return (LegalizeAction)ValueTypeActions.getTypeAction(VT);
123  }
124
125  /// isTypeLegal - Return true if this type is legal on this target.
126  ///
127  bool isTypeLegal(MVT::ValueType VT) const {
128    return getTypeAction(VT) == Legal;
129  }
130
131  void LegalizeDAG();
132
133private:
134  /// HandleOp - Legalize, Promote, Expand or Pack the specified operand as
135  /// appropriate for its type.
136  void HandleOp(SDOperand Op);
137
138  /// LegalizeOp - We know that the specified value has a legal type.
139  /// Recursively ensure that the operands have legal types, then return the
140  /// result.
141  SDOperand LegalizeOp(SDOperand O);
142
143  /// PromoteOp - Given an operation that produces a value in an invalid type,
144  /// promote it to compute the value into a larger type.  The produced value
145  /// will have the correct bits for the low portion of the register, but no
146  /// guarantee is made about the top bits: it may be zero, sign-extended, or
147  /// garbage.
148  SDOperand PromoteOp(SDOperand O);
149
150  /// ExpandOp - Expand the specified SDOperand into its two component pieces
151  /// Lo&Hi.  Note that the Op MUST be an expanded type.  As a result of this,
152  /// the LegalizeNodes map is filled in for any results that are not expanded,
153  /// the ExpandedNodes map is filled in for any results that are expanded, and
154  /// the Lo/Hi values are returned.   This applies to integer types and Vector
155  /// types.
156  void ExpandOp(SDOperand O, SDOperand &Lo, SDOperand &Hi);
157
158  /// SplitVectorOp - Given an operand of MVT::Vector type, break it down into
159  /// two smaller values of MVT::Vector type.
160  void SplitVectorOp(SDOperand O, SDOperand &Lo, SDOperand &Hi);
161
162  /// PackVectorOp - Given an operand of MVT::Vector type, convert it into the
163  /// equivalent operation that returns a packed value (e.g. MVT::V4F32).  When
164  /// this is called, we know that PackedVT is the right type for the result and
165  /// we know that this type is legal for the target.
166  SDOperand PackVectorOp(SDOperand O, MVT::ValueType PackedVT);
167
168  /// isShuffleLegal - Return true if a vector shuffle is legal with the
169  /// specified mask and type.  Targets can specify exactly which masks they
170  /// support and the code generator is tasked with not creating illegal masks.
171  ///
172  /// Note that this will also return true for shuffles that are promoted to a
173  /// different type.
174  ///
175  /// If this is a legal shuffle, this method returns the (possibly promoted)
176  /// build_vector Mask.  If it's not a legal shuffle, it returns null.
177  SDNode *isShuffleLegal(MVT::ValueType VT, SDOperand Mask) const;
178
179  bool LegalizeAllNodesNotLeadingTo(SDNode *N, SDNode *Dest);
180
181  void LegalizeSetCCOperands(SDOperand &LHS, SDOperand &RHS, SDOperand &CC);
182
183  SDOperand CreateStackTemporary(MVT::ValueType VT);
184
185  SDOperand ExpandLibCall(const char *Name, SDNode *Node,
186                          SDOperand &Hi);
187  SDOperand ExpandIntToFP(bool isSigned, MVT::ValueType DestTy,
188                          SDOperand Source);
189
190  SDOperand ExpandBIT_CONVERT(MVT::ValueType DestVT, SDOperand SrcOp);
191  SDOperand ExpandBUILD_VECTOR(SDNode *Node);
192  SDOperand ExpandSCALAR_TO_VECTOR(SDNode *Node);
193  SDOperand ExpandLegalINT_TO_FP(bool isSigned,
194                                 SDOperand LegalOp,
195                                 MVT::ValueType DestVT);
196  SDOperand PromoteLegalINT_TO_FP(SDOperand LegalOp, MVT::ValueType DestVT,
197                                  bool isSigned);
198  SDOperand PromoteLegalFP_TO_INT(SDOperand LegalOp, MVT::ValueType DestVT,
199                                  bool isSigned);
200
201  SDOperand ExpandBSWAP(SDOperand Op);
202  SDOperand ExpandBitCount(unsigned Opc, SDOperand Op);
203  bool ExpandShift(unsigned Opc, SDOperand Op, SDOperand Amt,
204                   SDOperand &Lo, SDOperand &Hi);
205  void ExpandShiftParts(unsigned NodeOp, SDOperand Op, SDOperand Amt,
206                        SDOperand &Lo, SDOperand &Hi);
207
208  SDOperand LowerVEXTRACT_VECTOR_ELT(SDOperand Op);
209  SDOperand ExpandEXTRACT_VECTOR_ELT(SDOperand Op);
210
211  SDOperand getIntPtrConstant(uint64_t Val) {
212    return DAG.getConstant(Val, TLI.getPointerTy());
213  }
214};
215}
216
217/// isVectorShuffleLegal - Return true if a vector shuffle is legal with the
218/// specified mask and type.  Targets can specify exactly which masks they
219/// support and the code generator is tasked with not creating illegal masks.
220///
221/// Note that this will also return true for shuffles that are promoted to a
222/// different type.
223SDNode *SelectionDAGLegalize::isShuffleLegal(MVT::ValueType VT,
224                                             SDOperand Mask) const {
225  switch (TLI.getOperationAction(ISD::VECTOR_SHUFFLE, VT)) {
226  default: return 0;
227  case TargetLowering::Legal:
228  case TargetLowering::Custom:
229    break;
230  case TargetLowering::Promote: {
231    // If this is promoted to a different type, convert the shuffle mask and
232    // ask if it is legal in the promoted type!
233    MVT::ValueType NVT = TLI.getTypeToPromoteTo(ISD::VECTOR_SHUFFLE, VT);
234
235    // If we changed # elements, change the shuffle mask.
236    unsigned NumEltsGrowth =
237      MVT::getVectorNumElements(NVT) / MVT::getVectorNumElements(VT);
238    assert(NumEltsGrowth && "Cannot promote to vector type with fewer elts!");
239    if (NumEltsGrowth > 1) {
240      // Renumber the elements.
241      std::vector<SDOperand> Ops;
242      for (unsigned i = 0, e = Mask.getNumOperands(); i != e; ++i) {
243        SDOperand InOp = Mask.getOperand(i);
244        for (unsigned j = 0; j != NumEltsGrowth; ++j) {
245          if (InOp.getOpcode() == ISD::UNDEF)
246            Ops.push_back(DAG.getNode(ISD::UNDEF, MVT::i32));
247          else {
248            unsigned InEltNo = cast<ConstantSDNode>(InOp)->getValue();
249            Ops.push_back(DAG.getConstant(InEltNo*NumEltsGrowth+j, MVT::i32));
250          }
251        }
252      }
253      Mask = DAG.getNode(ISD::BUILD_VECTOR, NVT, Ops);
254    }
255    VT = NVT;
256    break;
257  }
258  }
259  return TLI.isShuffleMaskLegal(Mask, VT) ? Mask.Val : 0;
260}
261
262/// getScalarizedOpcode - Return the scalar opcode that corresponds to the
263/// specified vector opcode.
264static unsigned getScalarizedOpcode(unsigned VecOp, MVT::ValueType VT) {
265  switch (VecOp) {
266  default: assert(0 && "Don't know how to scalarize this opcode!");
267  case ISD::VADD:  return MVT::isInteger(VT) ? ISD::ADD : ISD::FADD;
268  case ISD::VSUB:  return MVT::isInteger(VT) ? ISD::SUB : ISD::FSUB;
269  case ISD::VMUL:  return MVT::isInteger(VT) ? ISD::MUL : ISD::FMUL;
270  case ISD::VSDIV: return MVT::isInteger(VT) ? ISD::SDIV: ISD::FDIV;
271  case ISD::VUDIV: return MVT::isInteger(VT) ? ISD::UDIV: ISD::FDIV;
272  case ISD::VAND:  return MVT::isInteger(VT) ? ISD::AND : 0;
273  case ISD::VOR:   return MVT::isInteger(VT) ? ISD::OR  : 0;
274  case ISD::VXOR:  return MVT::isInteger(VT) ? ISD::XOR : 0;
275  }
276}
277
278SelectionDAGLegalize::SelectionDAGLegalize(SelectionDAG &dag)
279  : TLI(dag.getTargetLoweringInfo()), DAG(dag),
280    ValueTypeActions(TLI.getValueTypeActions()) {
281  assert(MVT::LAST_VALUETYPE <= 32 &&
282         "Too many value types for ValueTypeActions to hold!");
283}
284
285/// ComputeTopDownOrdering - Add the specified node to the Order list if it has
286/// not been visited yet and if all of its operands have already been visited.
287static void ComputeTopDownOrdering(SDNode *N, std::vector<SDNode*> &Order,
288                                   std::map<SDNode*, unsigned> &Visited) {
289  if (++Visited[N] != N->getNumOperands())
290    return;  // Haven't visited all operands yet
291
292  Order.push_back(N);
293
294  if (N->hasOneUse()) { // Tail recurse in common case.
295    ComputeTopDownOrdering(*N->use_begin(), Order, Visited);
296    return;
297  }
298
299  // Now that we have N in, add anything that uses it if all of their operands
300  // are now done.
301  for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end(); UI != E;++UI)
302    ComputeTopDownOrdering(*UI, Order, Visited);
303}
304
305
306void SelectionDAGLegalize::LegalizeDAG() {
307  LastCALLSEQ_END = DAG.getEntryNode();
308  IsLegalizingCall = false;
309
310  // The legalize process is inherently a bottom-up recursive process (users
311  // legalize their uses before themselves).  Given infinite stack space, we
312  // could just start legalizing on the root and traverse the whole graph.  In
313  // practice however, this causes us to run out of stack space on large basic
314  // blocks.  To avoid this problem, compute an ordering of the nodes where each
315  // node is only legalized after all of its operands are legalized.
316  std::map<SDNode*, unsigned> Visited;
317  std::vector<SDNode*> Order;
318
319  // Compute ordering from all of the leaves in the graphs, those (like the
320  // entry node) that have no operands.
321  for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
322       E = DAG.allnodes_end(); I != E; ++I) {
323    if (I->getNumOperands() == 0) {
324      Visited[I] = 0 - 1U;
325      ComputeTopDownOrdering(I, Order, Visited);
326    }
327  }
328
329  assert(Order.size() == Visited.size() &&
330         Order.size() ==
331            (unsigned)std::distance(DAG.allnodes_begin(), DAG.allnodes_end()) &&
332         "Error: DAG is cyclic!");
333  Visited.clear();
334
335  for (unsigned i = 0, e = Order.size(); i != e; ++i)
336    HandleOp(SDOperand(Order[i], 0));
337
338  // Finally, it's possible the root changed.  Get the new root.
339  SDOperand OldRoot = DAG.getRoot();
340  assert(LegalizedNodes.count(OldRoot) && "Root didn't get legalized?");
341  DAG.setRoot(LegalizedNodes[OldRoot]);
342
343  ExpandedNodes.clear();
344  LegalizedNodes.clear();
345  PromotedNodes.clear();
346  SplitNodes.clear();
347  PackedNodes.clear();
348
349  // Remove dead nodes now.
350  DAG.RemoveDeadNodes(OldRoot.Val);
351}
352
353
354/// FindCallEndFromCallStart - Given a chained node that is part of a call
355/// sequence, find the CALLSEQ_END node that terminates the call sequence.
356static SDNode *FindCallEndFromCallStart(SDNode *Node) {
357  if (Node->getOpcode() == ISD::CALLSEQ_END)
358    return Node;
359  if (Node->use_empty())
360    return 0;   // No CallSeqEnd
361
362  // The chain is usually at the end.
363  SDOperand TheChain(Node, Node->getNumValues()-1);
364  if (TheChain.getValueType() != MVT::Other) {
365    // Sometimes it's at the beginning.
366    TheChain = SDOperand(Node, 0);
367    if (TheChain.getValueType() != MVT::Other) {
368      // Otherwise, hunt for it.
369      for (unsigned i = 1, e = Node->getNumValues(); i != e; ++i)
370        if (Node->getValueType(i) == MVT::Other) {
371          TheChain = SDOperand(Node, i);
372          break;
373        }
374
375      // Otherwise, we walked into a node without a chain.
376      if (TheChain.getValueType() != MVT::Other)
377        return 0;
378    }
379  }
380
381  for (SDNode::use_iterator UI = Node->use_begin(),
382       E = Node->use_end(); UI != E; ++UI) {
383
384    // Make sure to only follow users of our token chain.
385    SDNode *User = *UI;
386    for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i)
387      if (User->getOperand(i) == TheChain)
388        if (SDNode *Result = FindCallEndFromCallStart(User))
389          return Result;
390  }
391  return 0;
392}
393
394/// FindCallStartFromCallEnd - Given a chained node that is part of a call
395/// sequence, find the CALLSEQ_START node that initiates the call sequence.
396static SDNode *FindCallStartFromCallEnd(SDNode *Node) {
397  assert(Node && "Didn't find callseq_start for a call??");
398  if (Node->getOpcode() == ISD::CALLSEQ_START) return Node;
399
400  assert(Node->getOperand(0).getValueType() == MVT::Other &&
401         "Node doesn't have a token chain argument!");
402  return FindCallStartFromCallEnd(Node->getOperand(0).Val);
403}
404
405/// LegalizeAllNodesNotLeadingTo - Recursively walk the uses of N, looking to
406/// see if any uses can reach Dest.  If no dest operands can get to dest,
407/// legalize them, legalize ourself, and return false, otherwise, return true.
408bool SelectionDAGLegalize::LegalizeAllNodesNotLeadingTo(SDNode *N,
409                                                        SDNode *Dest) {
410  if (N == Dest) return true;  // N certainly leads to Dest :)
411
412  // If the first result of this node has been already legalized, then it cannot
413  // reach N.
414  switch (getTypeAction(N->getValueType(0))) {
415  case Legal:
416    if (LegalizedNodes.count(SDOperand(N, 0))) return false;
417    break;
418  case Promote:
419    if (PromotedNodes.count(SDOperand(N, 0))) return false;
420    break;
421  case Expand:
422    if (ExpandedNodes.count(SDOperand(N, 0))) return false;
423    break;
424  }
425
426  // Okay, this node has not already been legalized.  Check and legalize all
427  // operands.  If none lead to Dest, then we can legalize this node.
428  bool OperandsLeadToDest = false;
429  for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
430    OperandsLeadToDest |=     // If an operand leads to Dest, so do we.
431      LegalizeAllNodesNotLeadingTo(N->getOperand(i).Val, Dest);
432
433  if (OperandsLeadToDest) return true;
434
435  // Okay, this node looks safe, legalize it and return false.
436  switch (getTypeAction(N->getValueType(0))) {
437  case Legal:
438    LegalizeOp(SDOperand(N, 0));
439    break;
440  case Promote:
441    PromoteOp(SDOperand(N, 0));
442    break;
443  case Expand: {
444    SDOperand X, Y;
445    ExpandOp(SDOperand(N, 0), X, Y);
446    break;
447  }
448  }
449  return false;
450}
451
452/// HandleOp - Legalize, Promote, Expand or Pack the specified operand as
453/// appropriate for its type.
454void SelectionDAGLegalize::HandleOp(SDOperand Op) {
455  switch (getTypeAction(Op.getValueType())) {
456  default: assert(0 && "Bad type action!");
457  case Legal:   LegalizeOp(Op); break;
458  case Promote: PromoteOp(Op);  break;
459  case Expand:
460    if (Op.getValueType() != MVT::Vector) {
461      SDOperand X, Y;
462      ExpandOp(Op, X, Y);
463    } else {
464      SDNode *N = Op.Val;
465      unsigned NumOps = N->getNumOperands();
466      unsigned NumElements =
467        cast<ConstantSDNode>(N->getOperand(NumOps-2))->getValue();
468      MVT::ValueType EVT = cast<VTSDNode>(N->getOperand(NumOps-1))->getVT();
469      MVT::ValueType PackedVT = getVectorType(EVT, NumElements);
470      if (PackedVT != MVT::Other && TLI.isTypeLegal(PackedVT)) {
471        // In the common case, this is a legal vector type, convert it to the
472        // packed operation and type now.
473        PackVectorOp(Op, PackedVT);
474      } else if (NumElements == 1) {
475        // Otherwise, if this is a single element vector, convert it to a
476        // scalar operation.
477        PackVectorOp(Op, EVT);
478      } else {
479        // Otherwise, this is a multiple element vector that isn't supported.
480        // Split it in half and legalize both parts.
481        SDOperand X, Y;
482        SplitVectorOp(Op, X, Y);
483      }
484    }
485    break;
486  }
487}
488
489
490/// LegalizeOp - We know that the specified value has a legal type.
491/// Recursively ensure that the operands have legal types, then return the
492/// result.
493SDOperand SelectionDAGLegalize::LegalizeOp(SDOperand Op) {
494  assert(isTypeLegal(Op.getValueType()) &&
495         "Caller should expand or promote operands that are not legal!");
496  SDNode *Node = Op.Val;
497
498  // If this operation defines any values that cannot be represented in a
499  // register on this target, make sure to expand or promote them.
500  if (Node->getNumValues() > 1) {
501    for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
502      if (getTypeAction(Node->getValueType(i)) != Legal) {
503        HandleOp(Op.getValue(i));
504        assert(LegalizedNodes.count(Op) &&
505               "Handling didn't add legal operands!");
506        return LegalizedNodes[Op];
507      }
508  }
509
510  // Note that LegalizeOp may be reentered even from single-use nodes, which
511  // means that we always must cache transformed nodes.
512  std::map<SDOperand, SDOperand>::iterator I = LegalizedNodes.find(Op);
513  if (I != LegalizedNodes.end()) return I->second;
514
515  SDOperand Tmp1, Tmp2, Tmp3, Tmp4;
516  SDOperand Result = Op;
517  bool isCustom = false;
518
519  switch (Node->getOpcode()) {
520  case ISD::FrameIndex:
521  case ISD::EntryToken:
522  case ISD::Register:
523  case ISD::BasicBlock:
524  case ISD::TargetFrameIndex:
525  case ISD::TargetConstant:
526  case ISD::TargetConstantFP:
527  case ISD::TargetConstantPool:
528  case ISD::TargetGlobalAddress:
529  case ISD::TargetExternalSymbol:
530  case ISD::VALUETYPE:
531  case ISD::SRCVALUE:
532  case ISD::STRING:
533  case ISD::CONDCODE:
534    // Primitives must all be legal.
535    assert(TLI.isOperationLegal(Node->getValueType(0), Node->getValueType(0)) &&
536           "This must be legal!");
537    break;
538  default:
539    if (Node->getOpcode() >= ISD::BUILTIN_OP_END) {
540      // If this is a target node, legalize it by legalizing the operands then
541      // passing it through.
542      std::vector<SDOperand> Ops;
543      bool Changed = false;
544      for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) {
545        Ops.push_back(LegalizeOp(Node->getOperand(i)));
546        Changed = Changed || Node->getOperand(i) != Ops.back();
547      }
548      if (Changed)
549        if (Node->getNumValues() == 1)
550          Result = DAG.getNode(Node->getOpcode(), Node->getValueType(0), Ops);
551        else {
552          std::vector<MVT::ValueType> VTs(Node->value_begin(),
553                                          Node->value_end());
554          Result = DAG.getNode(Node->getOpcode(), VTs, Ops);
555        }
556
557      for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
558        AddLegalizedOperand(Op.getValue(i), Result.getValue(i));
559      return Result.getValue(Op.ResNo);
560    }
561    // Otherwise this is an unhandled builtin node.  splat.
562    std::cerr << "NODE: "; Node->dump(); std::cerr << "\n";
563    assert(0 && "Do not know how to legalize this operator!");
564    abort();
565  case ISD::GlobalAddress:
566  case ISD::ExternalSymbol:
567  case ISD::ConstantPool:           // Nothing to do.
568    switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
569    default: assert(0 && "This action is not supported yet!");
570    case TargetLowering::Custom:
571      Tmp1 = TLI.LowerOperation(Op, DAG);
572      if (Tmp1.Val) Result = Tmp1;
573      // FALLTHROUGH if the target doesn't want to lower this op after all.
574    case TargetLowering::Legal:
575      break;
576    }
577    break;
578  case ISD::AssertSext:
579  case ISD::AssertZext:
580    Tmp1 = LegalizeOp(Node->getOperand(0));
581    Result = DAG.UpdateNodeOperands(Result, Tmp1, Node->getOperand(1));
582    break;
583  case ISD::MERGE_VALUES:
584    // Legalize eliminates MERGE_VALUES nodes.
585    Result = Node->getOperand(Op.ResNo);
586    break;
587  case ISD::CopyFromReg:
588    Tmp1 = LegalizeOp(Node->getOperand(0));
589    Result = Op.getValue(0);
590    if (Node->getNumValues() == 2) {
591      Result = DAG.UpdateNodeOperands(Result, Tmp1, Node->getOperand(1));
592    } else {
593      assert(Node->getNumValues() == 3 && "Invalid copyfromreg!");
594      if (Node->getNumOperands() == 3) {
595        Tmp2 = LegalizeOp(Node->getOperand(2));
596        Result = DAG.UpdateNodeOperands(Result, Tmp1, Node->getOperand(1),Tmp2);
597      } else {
598        Result = DAG.UpdateNodeOperands(Result, Tmp1, Node->getOperand(1));
599      }
600      AddLegalizedOperand(Op.getValue(2), Result.getValue(2));
601    }
602    // Since CopyFromReg produces two values, make sure to remember that we
603    // legalized both of them.
604    AddLegalizedOperand(Op.getValue(0), Result);
605    AddLegalizedOperand(Op.getValue(1), Result.getValue(1));
606    return Result.getValue(Op.ResNo);
607  case ISD::UNDEF: {
608    MVT::ValueType VT = Op.getValueType();
609    switch (TLI.getOperationAction(ISD::UNDEF, VT)) {
610    default: assert(0 && "This action is not supported yet!");
611    case TargetLowering::Expand:
612      if (MVT::isInteger(VT))
613        Result = DAG.getConstant(0, VT);
614      else if (MVT::isFloatingPoint(VT))
615        Result = DAG.getConstantFP(0, VT);
616      else
617        assert(0 && "Unknown value type!");
618      break;
619    case TargetLowering::Legal:
620      break;
621    }
622    break;
623  }
624
625  case ISD::INTRINSIC_W_CHAIN:
626  case ISD::INTRINSIC_WO_CHAIN:
627  case ISD::INTRINSIC_VOID: {
628    std::vector<SDOperand> Ops;
629    for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i)
630      Ops.push_back(LegalizeOp(Node->getOperand(i)));
631    Result = DAG.UpdateNodeOperands(Result, Ops);
632
633    // Allow the target to custom lower its intrinsics if it wants to.
634    if (TLI.getOperationAction(Node->getOpcode(), MVT::Other) ==
635        TargetLowering::Custom) {
636      Tmp3 = TLI.LowerOperation(Result, DAG);
637      if (Tmp3.Val) Result = Tmp3;
638    }
639
640    if (Result.Val->getNumValues() == 1) break;
641
642    // Must have return value and chain result.
643    assert(Result.Val->getNumValues() == 2 &&
644           "Cannot return more than two values!");
645
646    // Since loads produce two values, make sure to remember that we
647    // legalized both of them.
648    AddLegalizedOperand(SDOperand(Node, 0), Result.getValue(0));
649    AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
650    return Result.getValue(Op.ResNo);
651  }
652
653  case ISD::LOCATION:
654    assert(Node->getNumOperands() == 5 && "Invalid LOCATION node!");
655    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the input chain.
656
657    switch (TLI.getOperationAction(ISD::LOCATION, MVT::Other)) {
658    case TargetLowering::Promote:
659    default: assert(0 && "This action is not supported yet!");
660    case TargetLowering::Expand: {
661      MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
662      bool useDEBUG_LOC = TLI.isOperationLegal(ISD::DEBUG_LOC, MVT::Other);
663      bool useDEBUG_LABEL = TLI.isOperationLegal(ISD::DEBUG_LABEL, MVT::Other);
664
665      if (DebugInfo && (useDEBUG_LOC || useDEBUG_LABEL)) {
666        const std::string &FName =
667          cast<StringSDNode>(Node->getOperand(3))->getValue();
668        const std::string &DirName =
669          cast<StringSDNode>(Node->getOperand(4))->getValue();
670        unsigned SrcFile = DebugInfo->RecordSource(DirName, FName);
671
672        std::vector<SDOperand> Ops;
673        Ops.push_back(Tmp1);  // chain
674        SDOperand LineOp = Node->getOperand(1);
675        SDOperand ColOp = Node->getOperand(2);
676
677        if (useDEBUG_LOC) {
678          Ops.push_back(LineOp);  // line #
679          Ops.push_back(ColOp);  // col #
680          Ops.push_back(DAG.getConstant(SrcFile, MVT::i32));  // source file id
681          Result = DAG.getNode(ISD::DEBUG_LOC, MVT::Other, Ops);
682        } else {
683          unsigned Line = cast<ConstantSDNode>(LineOp)->getValue();
684          unsigned Col = cast<ConstantSDNode>(ColOp)->getValue();
685          unsigned ID = DebugInfo->RecordLabel(Line, Col, SrcFile);
686          Ops.push_back(DAG.getConstant(ID, MVT::i32));
687          Result = DAG.getNode(ISD::DEBUG_LABEL, MVT::Other, Ops);
688        }
689      } else {
690        Result = Tmp1;  // chain
691      }
692      break;
693    }
694    case TargetLowering::Legal:
695      if (Tmp1 != Node->getOperand(0) ||
696          getTypeAction(Node->getOperand(1).getValueType()) == Promote) {
697        std::vector<SDOperand> Ops;
698        Ops.push_back(Tmp1);
699        if (getTypeAction(Node->getOperand(1).getValueType()) == Legal) {
700          Ops.push_back(Node->getOperand(1));  // line # must be legal.
701          Ops.push_back(Node->getOperand(2));  // col # must be legal.
702        } else {
703          // Otherwise promote them.
704          Ops.push_back(PromoteOp(Node->getOperand(1)));
705          Ops.push_back(PromoteOp(Node->getOperand(2)));
706        }
707        Ops.push_back(Node->getOperand(3));  // filename must be legal.
708        Ops.push_back(Node->getOperand(4));  // working dir # must be legal.
709        Result = DAG.UpdateNodeOperands(Result, Ops);
710      }
711      break;
712    }
713    break;
714
715  case ISD::DEBUG_LOC:
716    assert(Node->getNumOperands() == 4 && "Invalid DEBUG_LOC node!");
717    switch (TLI.getOperationAction(ISD::DEBUG_LOC, MVT::Other)) {
718    default: assert(0 && "This action is not supported yet!");
719    case TargetLowering::Legal:
720      Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
721      Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the line #.
722      Tmp3 = LegalizeOp(Node->getOperand(2));  // Legalize the col #.
723      Tmp4 = LegalizeOp(Node->getOperand(3));  // Legalize the source file id.
724      Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3, Tmp4);
725      break;
726    }
727    break;
728
729  case ISD::DEBUG_LABEL:
730    assert(Node->getNumOperands() == 2 && "Invalid DEBUG_LABEL node!");
731    switch (TLI.getOperationAction(ISD::DEBUG_LABEL, MVT::Other)) {
732    default: assert(0 && "This action is not supported yet!");
733    case TargetLowering::Legal:
734      Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
735      Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the label id.
736      Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
737      break;
738    }
739    break;
740
741  case ISD::Constant:
742    // We know we don't need to expand constants here, constants only have one
743    // value and we check that it is fine above.
744
745    // FIXME: Maybe we should handle things like targets that don't support full
746    // 32-bit immediates?
747    break;
748  case ISD::ConstantFP: {
749    // Spill FP immediates to the constant pool if the target cannot directly
750    // codegen them.  Targets often have some immediate values that can be
751    // efficiently generated into an FP register without a load.  We explicitly
752    // leave these constants as ConstantFP nodes for the target to deal with.
753    ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Node);
754
755    // Check to see if this FP immediate is already legal.
756    bool isLegal = false;
757    for (TargetLowering::legal_fpimm_iterator I = TLI.legal_fpimm_begin(),
758           E = TLI.legal_fpimm_end(); I != E; ++I)
759      if (CFP->isExactlyValue(*I)) {
760        isLegal = true;
761        break;
762      }
763
764    // If this is a legal constant, turn it into a TargetConstantFP node.
765    if (isLegal) {
766      Result = DAG.getTargetConstantFP(CFP->getValue(), CFP->getValueType(0));
767      break;
768    }
769
770    switch (TLI.getOperationAction(ISD::ConstantFP, CFP->getValueType(0))) {
771    default: assert(0 && "This action is not supported yet!");
772    case TargetLowering::Custom:
773      Tmp3 = TLI.LowerOperation(Result, DAG);
774      if (Tmp3.Val) {
775        Result = Tmp3;
776        break;
777      }
778      // FALLTHROUGH
779    case TargetLowering::Expand:
780      // Otherwise we need to spill the constant to memory.
781      bool Extend = false;
782
783      // If a FP immediate is precise when represented as a float and if the
784      // target can do an extending load from float to double, we put it into
785      // the constant pool as a float, even if it's is statically typed as a
786      // double.
787      MVT::ValueType VT = CFP->getValueType(0);
788      bool isDouble = VT == MVT::f64;
789      ConstantFP *LLVMC = ConstantFP::get(isDouble ? Type::DoubleTy :
790                                             Type::FloatTy, CFP->getValue());
791      if (isDouble && CFP->isExactlyValue((float)CFP->getValue()) &&
792          // Only do this if the target has a native EXTLOAD instruction from
793          // f32.
794          TLI.isOperationLegal(ISD::EXTLOAD, MVT::f32)) {
795        LLVMC = cast<ConstantFP>(ConstantExpr::getCast(LLVMC, Type::FloatTy));
796        VT = MVT::f32;
797        Extend = true;
798      }
799
800      SDOperand CPIdx = DAG.getConstantPool(LLVMC, TLI.getPointerTy());
801      if (Extend) {
802        Result = DAG.getExtLoad(ISD::EXTLOAD, MVT::f64, DAG.getEntryNode(),
803                                CPIdx, DAG.getSrcValue(NULL), MVT::f32);
804      } else {
805        Result = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx,
806                             DAG.getSrcValue(NULL));
807      }
808    }
809    break;
810  }
811  case ISD::TokenFactor:
812    if (Node->getNumOperands() == 2) {
813      Tmp1 = LegalizeOp(Node->getOperand(0));
814      Tmp2 = LegalizeOp(Node->getOperand(1));
815      Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
816    } else if (Node->getNumOperands() == 3) {
817      Tmp1 = LegalizeOp(Node->getOperand(0));
818      Tmp2 = LegalizeOp(Node->getOperand(1));
819      Tmp3 = LegalizeOp(Node->getOperand(2));
820      Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3);
821    } else {
822      std::vector<SDOperand> Ops;
823      // Legalize the operands.
824      for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i)
825        Ops.push_back(LegalizeOp(Node->getOperand(i)));
826      Result = DAG.UpdateNodeOperands(Result, Ops);
827    }
828    break;
829
830  case ISD::BUILD_VECTOR:
831    switch (TLI.getOperationAction(ISD::BUILD_VECTOR, Node->getValueType(0))) {
832    default: assert(0 && "This action is not supported yet!");
833    case TargetLowering::Custom:
834      Tmp3 = TLI.LowerOperation(Result, DAG);
835      if (Tmp3.Val) {
836        Result = Tmp3;
837        break;
838      }
839      // FALLTHROUGH
840    case TargetLowering::Expand:
841      Result = ExpandBUILD_VECTOR(Result.Val);
842      break;
843    }
844    break;
845  case ISD::INSERT_VECTOR_ELT:
846    Tmp1 = LegalizeOp(Node->getOperand(0));  // InVec
847    Tmp2 = LegalizeOp(Node->getOperand(1));  // InVal
848    Tmp3 = LegalizeOp(Node->getOperand(2));  // InEltNo
849    Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3);
850
851    switch (TLI.getOperationAction(ISD::INSERT_VECTOR_ELT,
852                                   Node->getValueType(0))) {
853    default: assert(0 && "This action is not supported yet!");
854    case TargetLowering::Legal:
855      break;
856    case TargetLowering::Custom:
857      Tmp3 = TLI.LowerOperation(Result, DAG);
858      if (Tmp3.Val) {
859        Result = Tmp3;
860        break;
861      }
862      // FALLTHROUGH
863    case TargetLowering::Expand: {
864      // If the target doesn't support this, we have to spill the input vector
865      // to a temporary stack slot, update the element, then reload it.  This is
866      // badness.  We could also load the value into a vector register (either
867      // with a "move to register" or "extload into register" instruction, then
868      // permute it into place, if the idx is a constant and if the idx is
869      // supported by the target.
870      MVT::ValueType VT    = Tmp1.getValueType();
871      MVT::ValueType EltVT = Tmp2.getValueType();
872      MVT::ValueType IdxVT = Tmp3.getValueType();
873      MVT::ValueType PtrVT = TLI.getPointerTy();
874      SDOperand StackPtr = CreateStackTemporary(VT);
875      // Store the vector.
876      SDOperand Ch = DAG.getNode(ISD::STORE, MVT::Other, DAG.getEntryNode(),
877                                 Tmp1, StackPtr, DAG.getSrcValue(NULL));
878
879      // Truncate or zero extend offset to target pointer type.
880      unsigned CastOpc = (IdxVT > PtrVT) ? ISD::TRUNCATE : ISD::ZERO_EXTEND;
881      Tmp3 = DAG.getNode(CastOpc, PtrVT, Tmp3);
882      // Add the offset to the index.
883      unsigned EltSize = MVT::getSizeInBits(EltVT)/8;
884      Tmp3 = DAG.getNode(ISD::MUL, IdxVT, Tmp3,DAG.getConstant(EltSize, IdxVT));
885      SDOperand StackPtr2 = DAG.getNode(ISD::ADD, IdxVT, Tmp3, StackPtr);
886      // Store the scalar value.
887      Ch = DAG.getNode(ISD::STORE, MVT::Other, Ch,
888                       Tmp2, StackPtr2, DAG.getSrcValue(NULL));
889      // Load the updated vector.
890      Result = DAG.getLoad(VT, Ch, StackPtr, DAG.getSrcValue(NULL));
891      break;
892    }
893    }
894    break;
895  case ISD::SCALAR_TO_VECTOR:
896    if (!TLI.isTypeLegal(Node->getOperand(0).getValueType())) {
897      Result = LegalizeOp(ExpandSCALAR_TO_VECTOR(Node));
898      break;
899    }
900
901    Tmp1 = LegalizeOp(Node->getOperand(0));  // InVal
902    Result = DAG.UpdateNodeOperands(Result, Tmp1);
903    switch (TLI.getOperationAction(ISD::SCALAR_TO_VECTOR,
904                                   Node->getValueType(0))) {
905    default: assert(0 && "This action is not supported yet!");
906    case TargetLowering::Legal:
907      break;
908    case TargetLowering::Custom:
909      Tmp3 = TLI.LowerOperation(Result, DAG);
910      if (Tmp3.Val) {
911        Result = Tmp3;
912        break;
913      }
914      // FALLTHROUGH
915    case TargetLowering::Expand:
916      Result = LegalizeOp(ExpandSCALAR_TO_VECTOR(Node));
917      break;
918    }
919    break;
920  case ISD::VECTOR_SHUFFLE:
921    Tmp1 = LegalizeOp(Node->getOperand(0));   // Legalize the input vectors,
922    Tmp2 = LegalizeOp(Node->getOperand(1));   // but not the shuffle mask.
923    Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Node->getOperand(2));
924
925    // Allow targets to custom lower the SHUFFLEs they support.
926    switch (TLI.getOperationAction(ISD::VECTOR_SHUFFLE,Result.getValueType())) {
927    default: assert(0 && "Unknown operation action!");
928    case TargetLowering::Legal:
929      assert(isShuffleLegal(Result.getValueType(), Node->getOperand(2)) &&
930             "vector shuffle should not be created if not legal!");
931      break;
932    case TargetLowering::Custom:
933      Tmp3 = TLI.LowerOperation(Result, DAG);
934      if (Tmp3.Val) {
935        Result = Tmp3;
936        break;
937      }
938      // FALLTHROUGH
939    case TargetLowering::Expand: {
940      MVT::ValueType VT = Node->getValueType(0);
941      MVT::ValueType EltVT = MVT::getVectorBaseType(VT);
942      MVT::ValueType PtrVT = TLI.getPointerTy();
943      SDOperand Mask = Node->getOperand(2);
944      unsigned NumElems = Mask.getNumOperands();
945      std::vector<SDOperand> Ops;
946      for (unsigned i = 0; i != NumElems; ++i) {
947        SDOperand Arg = Mask.getOperand(i);
948        if (Arg.getOpcode() == ISD::UNDEF) {
949          Ops.push_back(DAG.getNode(ISD::UNDEF, EltVT));
950        } else {
951          assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
952          unsigned Idx = cast<ConstantSDNode>(Arg)->getValue();
953          if (Idx < NumElems)
954            Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, EltVT, Tmp1,
955                                      DAG.getConstant(Idx, PtrVT)));
956          else
957            Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, EltVT, Tmp2,
958                                      DAG.getConstant(Idx - NumElems, PtrVT)));
959        }
960      }
961      Result = DAG.getNode(ISD::BUILD_VECTOR, VT, Ops);
962      break;
963    }
964    case TargetLowering::Promote: {
965      // Change base type to a different vector type.
966      MVT::ValueType OVT = Node->getValueType(0);
967      MVT::ValueType NVT = TLI.getTypeToPromoteTo(Node->getOpcode(), OVT);
968
969      // Cast the two input vectors.
970      Tmp1 = DAG.getNode(ISD::BIT_CONVERT, NVT, Tmp1);
971      Tmp2 = DAG.getNode(ISD::BIT_CONVERT, NVT, Tmp2);
972
973      // Convert the shuffle mask to the right # elements.
974      Tmp3 = SDOperand(isShuffleLegal(OVT, Node->getOperand(2)), 0);
975      assert(Tmp3.Val && "Shuffle not legal?");
976      Result = DAG.getNode(ISD::VECTOR_SHUFFLE, NVT, Tmp1, Tmp2, Tmp3);
977      Result = DAG.getNode(ISD::BIT_CONVERT, OVT, Result);
978      break;
979    }
980    }
981    break;
982
983  case ISD::EXTRACT_VECTOR_ELT:
984    Tmp1 = LegalizeOp(Node->getOperand(0));
985    Tmp2 = LegalizeOp(Node->getOperand(1));
986    Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
987
988    switch (TLI.getOperationAction(ISD::EXTRACT_VECTOR_ELT,
989                                   Tmp1.getValueType())) {
990    default: assert(0 && "This action is not supported yet!");
991    case TargetLowering::Legal:
992      break;
993    case TargetLowering::Custom:
994      Tmp3 = TLI.LowerOperation(Result, DAG);
995      if (Tmp3.Val) {
996        Result = Tmp3;
997        break;
998      }
999      // FALLTHROUGH
1000    case TargetLowering::Expand:
1001      Result = ExpandEXTRACT_VECTOR_ELT(Result);
1002      break;
1003    }
1004    break;
1005
1006  case ISD::VEXTRACT_VECTOR_ELT:
1007    Result = LegalizeOp(LowerVEXTRACT_VECTOR_ELT(Op));
1008    break;
1009
1010  case ISD::CALLSEQ_START: {
1011    SDNode *CallEnd = FindCallEndFromCallStart(Node);
1012
1013    // Recursively Legalize all of the inputs of the call end that do not lead
1014    // to this call start.  This ensures that any libcalls that need be inserted
1015    // are inserted *before* the CALLSEQ_START.
1016    for (unsigned i = 0, e = CallEnd->getNumOperands(); i != e; ++i)
1017      LegalizeAllNodesNotLeadingTo(CallEnd->getOperand(i).Val, Node);
1018
1019    // Now that we legalized all of the inputs (which may have inserted
1020    // libcalls) create the new CALLSEQ_START node.
1021    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1022
1023    // Merge in the last call, to ensure that this call start after the last
1024    // call ended.
1025    Tmp1 = DAG.getNode(ISD::TokenFactor, MVT::Other, Tmp1, LastCALLSEQ_END);
1026    Tmp1 = LegalizeOp(Tmp1);
1027
1028    // Do not try to legalize the target-specific arguments (#1+).
1029    if (Tmp1 != Node->getOperand(0)) {
1030      std::vector<SDOperand> Ops(Node->op_begin(), Node->op_end());
1031      Ops[0] = Tmp1;
1032      Result = DAG.UpdateNodeOperands(Result, Ops);
1033    }
1034
1035    // Remember that the CALLSEQ_START is legalized.
1036    AddLegalizedOperand(Op.getValue(0), Result);
1037    if (Node->getNumValues() == 2)    // If this has a flag result, remember it.
1038      AddLegalizedOperand(Op.getValue(1), Result.getValue(1));
1039
1040    // Now that the callseq_start and all of the non-call nodes above this call
1041    // sequence have been legalized, legalize the call itself.  During this
1042    // process, no libcalls can/will be inserted, guaranteeing that no calls
1043    // can overlap.
1044    assert(!IsLegalizingCall && "Inconsistent sequentialization of calls!");
1045    SDOperand InCallSEQ = LastCALLSEQ_END;
1046    // Note that we are selecting this call!
1047    LastCALLSEQ_END = SDOperand(CallEnd, 0);
1048    IsLegalizingCall = true;
1049
1050    // Legalize the call, starting from the CALLSEQ_END.
1051    LegalizeOp(LastCALLSEQ_END);
1052    assert(!IsLegalizingCall && "CALLSEQ_END should have cleared this!");
1053    return Result;
1054  }
1055  case ISD::CALLSEQ_END:
1056    // If the CALLSEQ_START node hasn't been legalized first, legalize it.  This
1057    // will cause this node to be legalized as well as handling libcalls right.
1058    if (LastCALLSEQ_END.Val != Node) {
1059      LegalizeOp(SDOperand(FindCallStartFromCallEnd(Node), 0));
1060      std::map<SDOperand, SDOperand>::iterator I = LegalizedNodes.find(Op);
1061      assert(I != LegalizedNodes.end() &&
1062             "Legalizing the call start should have legalized this node!");
1063      return I->second;
1064    }
1065
1066    // Otherwise, the call start has been legalized and everything is going
1067    // according to plan.  Just legalize ourselves normally here.
1068    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1069    // Do not try to legalize the target-specific arguments (#1+), except for
1070    // an optional flag input.
1071    if (Node->getOperand(Node->getNumOperands()-1).getValueType() != MVT::Flag){
1072      if (Tmp1 != Node->getOperand(0)) {
1073        std::vector<SDOperand> Ops(Node->op_begin(), Node->op_end());
1074        Ops[0] = Tmp1;
1075        Result = DAG.UpdateNodeOperands(Result, Ops);
1076      }
1077    } else {
1078      Tmp2 = LegalizeOp(Node->getOperand(Node->getNumOperands()-1));
1079      if (Tmp1 != Node->getOperand(0) ||
1080          Tmp2 != Node->getOperand(Node->getNumOperands()-1)) {
1081        std::vector<SDOperand> Ops(Node->op_begin(), Node->op_end());
1082        Ops[0] = Tmp1;
1083        Ops.back() = Tmp2;
1084        Result = DAG.UpdateNodeOperands(Result, Ops);
1085      }
1086    }
1087    assert(IsLegalizingCall && "Call sequence imbalance between start/end?");
1088    // This finishes up call legalization.
1089    IsLegalizingCall = false;
1090
1091    // If the CALLSEQ_END node has a flag, remember that we legalized it.
1092    AddLegalizedOperand(SDOperand(Node, 0), Result.getValue(0));
1093    if (Node->getNumValues() == 2)
1094      AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
1095    return Result.getValue(Op.ResNo);
1096  case ISD::DYNAMIC_STACKALLOC: {
1097    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1098    Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the size.
1099    Tmp3 = LegalizeOp(Node->getOperand(2));  // Legalize the alignment.
1100    Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3);
1101
1102    Tmp1 = Result.getValue(0);
1103    Tmp2 = Result.getValue(1);
1104    switch (TLI.getOperationAction(Node->getOpcode(),
1105                                   Node->getValueType(0))) {
1106    default: assert(0 && "This action is not supported yet!");
1107    case TargetLowering::Expand: {
1108      unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
1109      assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
1110             " not tell us which reg is the stack pointer!");
1111      SDOperand Chain = Tmp1.getOperand(0);
1112      SDOperand Size  = Tmp2.getOperand(1);
1113      SDOperand SP = DAG.getCopyFromReg(Chain, SPReg, Node->getValueType(0));
1114      Tmp1 = DAG.getNode(ISD::SUB, Node->getValueType(0), SP, Size);    // Value
1115      Tmp2 = DAG.getCopyToReg(SP.getValue(1), SPReg, Tmp1);      // Output chain
1116      Tmp1 = LegalizeOp(Tmp1);
1117      Tmp2 = LegalizeOp(Tmp2);
1118      break;
1119    }
1120    case TargetLowering::Custom:
1121      Tmp3 = TLI.LowerOperation(Tmp1, DAG);
1122      if (Tmp3.Val) {
1123        Tmp1 = LegalizeOp(Tmp3);
1124        Tmp2 = LegalizeOp(Tmp3.getValue(1));
1125      }
1126      break;
1127    case TargetLowering::Legal:
1128      break;
1129    }
1130    // Since this op produce two values, make sure to remember that we
1131    // legalized both of them.
1132    AddLegalizedOperand(SDOperand(Node, 0), Tmp1);
1133    AddLegalizedOperand(SDOperand(Node, 1), Tmp2);
1134    return Op.ResNo ? Tmp2 : Tmp1;
1135  }
1136  case ISD::INLINEASM:
1137    Tmp1 = LegalizeOp(Node->getOperand(0));   // Legalize Chain.
1138    Tmp2 = Node->getOperand(Node->getNumOperands()-1);
1139    if (Tmp2.getValueType() == MVT::Flag)     // Legalize Flag if it exists.
1140      Tmp2 = Tmp3 = SDOperand(0, 0);
1141    else
1142      Tmp3 = LegalizeOp(Tmp2);
1143
1144    if (Tmp1 != Node->getOperand(0) || Tmp2 != Tmp3) {
1145      std::vector<SDOperand> Ops(Node->op_begin(), Node->op_end());
1146      Ops[0] = Tmp1;
1147      if (Tmp3.Val) Ops.back() = Tmp3;
1148      Result = DAG.UpdateNodeOperands(Result, Ops);
1149    }
1150
1151    // INLINE asm returns a chain and flag, make sure to add both to the map.
1152    AddLegalizedOperand(SDOperand(Node, 0), Result.getValue(0));
1153    AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
1154    return Result.getValue(Op.ResNo);
1155  case ISD::BR:
1156    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1157    // Ensure that libcalls are emitted before a branch.
1158    Tmp1 = DAG.getNode(ISD::TokenFactor, MVT::Other, Tmp1, LastCALLSEQ_END);
1159    Tmp1 = LegalizeOp(Tmp1);
1160    LastCALLSEQ_END = DAG.getEntryNode();
1161
1162    Result = DAG.UpdateNodeOperands(Result, Tmp1, Node->getOperand(1));
1163    break;
1164
1165  case ISD::BRCOND:
1166    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1167    // Ensure that libcalls are emitted before a return.
1168    Tmp1 = DAG.getNode(ISD::TokenFactor, MVT::Other, Tmp1, LastCALLSEQ_END);
1169    Tmp1 = LegalizeOp(Tmp1);
1170    LastCALLSEQ_END = DAG.getEntryNode();
1171
1172    switch (getTypeAction(Node->getOperand(1).getValueType())) {
1173    case Expand: assert(0 && "It's impossible to expand bools");
1174    case Legal:
1175      Tmp2 = LegalizeOp(Node->getOperand(1)); // Legalize the condition.
1176      break;
1177    case Promote:
1178      Tmp2 = PromoteOp(Node->getOperand(1));  // Promote the condition.
1179      break;
1180    }
1181
1182    // Basic block destination (Op#2) is always legal.
1183    Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Node->getOperand(2));
1184
1185    switch (TLI.getOperationAction(ISD::BRCOND, MVT::Other)) {
1186    default: assert(0 && "This action is not supported yet!");
1187    case TargetLowering::Legal: break;
1188    case TargetLowering::Custom:
1189      Tmp1 = TLI.LowerOperation(Result, DAG);
1190      if (Tmp1.Val) Result = Tmp1;
1191      break;
1192    case TargetLowering::Expand:
1193      // Expand brcond's setcc into its constituent parts and create a BR_CC
1194      // Node.
1195      if (Tmp2.getOpcode() == ISD::SETCC) {
1196        Result = DAG.getNode(ISD::BR_CC, MVT::Other, Tmp1, Tmp2.getOperand(2),
1197                             Tmp2.getOperand(0), Tmp2.getOperand(1),
1198                             Node->getOperand(2));
1199      } else {
1200        // Make sure the condition is either zero or one.  It may have been
1201        // promoted from something else.
1202        unsigned NumBits = MVT::getSizeInBits(Tmp2.getValueType());
1203        if (!TLI.MaskedValueIsZero(Tmp2, (~0ULL >> (64-NumBits))^1))
1204          Tmp2 = DAG.getZeroExtendInReg(Tmp2, MVT::i1);
1205
1206        Result = DAG.getNode(ISD::BR_CC, MVT::Other, Tmp1,
1207                             DAG.getCondCode(ISD::SETNE), Tmp2,
1208                             DAG.getConstant(0, Tmp2.getValueType()),
1209                             Node->getOperand(2));
1210      }
1211      break;
1212    }
1213    break;
1214  case ISD::BR_CC:
1215    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1216    // Ensure that libcalls are emitted before a branch.
1217    Tmp1 = DAG.getNode(ISD::TokenFactor, MVT::Other, Tmp1, LastCALLSEQ_END);
1218    Tmp1 = LegalizeOp(Tmp1);
1219    LastCALLSEQ_END = DAG.getEntryNode();
1220
1221    Tmp2 = Node->getOperand(2);              // LHS
1222    Tmp3 = Node->getOperand(3);              // RHS
1223    Tmp4 = Node->getOperand(1);              // CC
1224
1225    LegalizeSetCCOperands(Tmp2, Tmp3, Tmp4);
1226
1227    // If we didn't get both a LHS and RHS back from LegalizeSetCCOperands,
1228    // the LHS is a legal SETCC itself.  In this case, we need to compare
1229    // the result against zero to select between true and false values.
1230    if (Tmp3.Val == 0) {
1231      Tmp3 = DAG.getConstant(0, Tmp2.getValueType());
1232      Tmp4 = DAG.getCondCode(ISD::SETNE);
1233    }
1234
1235    Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp4, Tmp2, Tmp3,
1236                                    Node->getOperand(4));
1237
1238    switch (TLI.getOperationAction(ISD::BR_CC, Tmp3.getValueType())) {
1239    default: assert(0 && "Unexpected action for BR_CC!");
1240    case TargetLowering::Legal: break;
1241    case TargetLowering::Custom:
1242      Tmp4 = TLI.LowerOperation(Result, DAG);
1243      if (Tmp4.Val) Result = Tmp4;
1244      break;
1245    }
1246    break;
1247  case ISD::LOAD: {
1248    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1249    Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the pointer.
1250
1251    MVT::ValueType VT = Node->getValueType(0);
1252    Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Node->getOperand(2));
1253    Tmp2 = Result.getValue(0);
1254    Tmp3 = Result.getValue(1);
1255
1256    switch (TLI.getOperationAction(Node->getOpcode(), VT)) {
1257    default: assert(0 && "This action is not supported yet!");
1258    case TargetLowering::Legal: break;
1259    case TargetLowering::Custom:
1260      Tmp1 = TLI.LowerOperation(Tmp2, DAG);
1261      if (Tmp1.Val) {
1262        Tmp2 = LegalizeOp(Tmp1);
1263        Tmp3 = LegalizeOp(Tmp1.getValue(1));
1264      }
1265      break;
1266    }
1267    // Since loads produce two values, make sure to remember that we
1268    // legalized both of them.
1269    AddLegalizedOperand(SDOperand(Node, 0), Tmp2);
1270    AddLegalizedOperand(SDOperand(Node, 1), Tmp3);
1271    return Op.ResNo ? Tmp3 : Tmp2;
1272  }
1273  case ISD::EXTLOAD:
1274  case ISD::SEXTLOAD:
1275  case ISD::ZEXTLOAD: {
1276    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1277    Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the pointer.
1278
1279    MVT::ValueType SrcVT = cast<VTSDNode>(Node->getOperand(3))->getVT();
1280    switch (TLI.getOperationAction(Node->getOpcode(), SrcVT)) {
1281    default: assert(0 && "This action is not supported yet!");
1282    case TargetLowering::Promote:
1283      assert(SrcVT == MVT::i1 && "Can only promote EXTLOAD from i1 -> i8!");
1284      Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Node->getOperand(2),
1285                                      DAG.getValueType(MVT::i8));
1286      Tmp1 = Result.getValue(0);
1287      Tmp2 = Result.getValue(1);
1288      break;
1289    case TargetLowering::Custom:
1290      isCustom = true;
1291      // FALLTHROUGH
1292    case TargetLowering::Legal:
1293      Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Node->getOperand(2),
1294                                      Node->getOperand(3));
1295      Tmp1 = Result.getValue(0);
1296      Tmp2 = Result.getValue(1);
1297
1298      if (isCustom) {
1299        Tmp3 = TLI.LowerOperation(Tmp3, DAG);
1300        if (Tmp3.Val) {
1301          Tmp1 = LegalizeOp(Tmp3);
1302          Tmp2 = LegalizeOp(Tmp3.getValue(1));
1303        }
1304      }
1305      break;
1306    case TargetLowering::Expand:
1307      // f64 = EXTLOAD f32 should expand to LOAD, FP_EXTEND
1308      if (SrcVT == MVT::f32 && Node->getValueType(0) == MVT::f64) {
1309        SDOperand Load = DAG.getLoad(SrcVT, Tmp1, Tmp2, Node->getOperand(2));
1310        Result = DAG.getNode(ISD::FP_EXTEND, Node->getValueType(0), Load);
1311        Tmp1 = LegalizeOp(Result);  // Relegalize new nodes.
1312        Tmp2 = LegalizeOp(Load.getValue(1));
1313        break;
1314      }
1315      assert(Node->getOpcode() != ISD::EXTLOAD &&
1316             "EXTLOAD should always be supported!");
1317      // Turn the unsupported load into an EXTLOAD followed by an explicit
1318      // zero/sign extend inreg.
1319      Result = DAG.getExtLoad(ISD::EXTLOAD, Node->getValueType(0),
1320                              Tmp1, Tmp2, Node->getOperand(2), SrcVT);
1321      SDOperand ValRes;
1322      if (Node->getOpcode() == ISD::SEXTLOAD)
1323        ValRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, Result.getValueType(),
1324                             Result, DAG.getValueType(SrcVT));
1325      else
1326        ValRes = DAG.getZeroExtendInReg(Result, SrcVT);
1327      Tmp1 = LegalizeOp(ValRes);  // Relegalize new nodes.
1328      Tmp2 = LegalizeOp(Result.getValue(1));  // Relegalize new nodes.
1329      break;
1330    }
1331    // Since loads produce two values, make sure to remember that we legalized
1332    // both of them.
1333    AddLegalizedOperand(SDOperand(Node, 0), Tmp1);
1334    AddLegalizedOperand(SDOperand(Node, 1), Tmp2);
1335    return Op.ResNo ? Tmp2 : Tmp1;
1336  }
1337  case ISD::EXTRACT_ELEMENT: {
1338    MVT::ValueType OpTy = Node->getOperand(0).getValueType();
1339    switch (getTypeAction(OpTy)) {
1340    default: assert(0 && "EXTRACT_ELEMENT action for type unimplemented!");
1341    case Legal:
1342      if (cast<ConstantSDNode>(Node->getOperand(1))->getValue()) {
1343        // 1 -> Hi
1344        Result = DAG.getNode(ISD::SRL, OpTy, Node->getOperand(0),
1345                             DAG.getConstant(MVT::getSizeInBits(OpTy)/2,
1346                                             TLI.getShiftAmountTy()));
1347        Result = DAG.getNode(ISD::TRUNCATE, Node->getValueType(0), Result);
1348      } else {
1349        // 0 -> Lo
1350        Result = DAG.getNode(ISD::TRUNCATE, Node->getValueType(0),
1351                             Node->getOperand(0));
1352      }
1353      break;
1354    case Expand:
1355      // Get both the low and high parts.
1356      ExpandOp(Node->getOperand(0), Tmp1, Tmp2);
1357      if (cast<ConstantSDNode>(Node->getOperand(1))->getValue())
1358        Result = Tmp2;  // 1 -> Hi
1359      else
1360        Result = Tmp1;  // 0 -> Lo
1361      break;
1362    }
1363    break;
1364  }
1365
1366  case ISD::CopyToReg:
1367    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1368
1369    assert(isTypeLegal(Node->getOperand(2).getValueType()) &&
1370           "Register type must be legal!");
1371    // Legalize the incoming value (must be a legal type).
1372    Tmp2 = LegalizeOp(Node->getOperand(2));
1373    if (Node->getNumValues() == 1) {
1374      Result = DAG.UpdateNodeOperands(Result, Tmp1, Node->getOperand(1), Tmp2);
1375    } else {
1376      assert(Node->getNumValues() == 2 && "Unknown CopyToReg");
1377      if (Node->getNumOperands() == 4) {
1378        Tmp3 = LegalizeOp(Node->getOperand(3));
1379        Result = DAG.UpdateNodeOperands(Result, Tmp1, Node->getOperand(1), Tmp2,
1380                                        Tmp3);
1381      } else {
1382        Result = DAG.UpdateNodeOperands(Result, Tmp1, Node->getOperand(1),Tmp2);
1383      }
1384
1385      // Since this produces two values, make sure to remember that we legalized
1386      // both of them.
1387      AddLegalizedOperand(SDOperand(Node, 0), Result.getValue(0));
1388      AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
1389      return Result;
1390    }
1391    break;
1392
1393  case ISD::RET:
1394    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1395
1396    // Ensure that libcalls are emitted before a return.
1397    Tmp1 = DAG.getNode(ISD::TokenFactor, MVT::Other, Tmp1, LastCALLSEQ_END);
1398    Tmp1 = LegalizeOp(Tmp1);
1399    LastCALLSEQ_END = DAG.getEntryNode();
1400    Tmp2 = Node->getOperand(1);
1401
1402    switch (Node->getNumOperands()) {
1403    case 2:  // ret val
1404      switch (getTypeAction(Tmp2.getValueType())) {
1405      case Legal:
1406        Result = DAG.UpdateNodeOperands(Result, Tmp1, LegalizeOp(Tmp2));
1407        break;
1408      case Expand:
1409        if (Tmp2.getValueType() != MVT::Vector) {
1410          SDOperand Lo, Hi;
1411          ExpandOp(Tmp2, Lo, Hi);
1412          Result = DAG.getNode(ISD::RET, MVT::Other, Tmp1, Lo, Hi);
1413        } else {
1414          SDNode *InVal = Tmp2.Val;
1415          unsigned NumElems =
1416            cast<ConstantSDNode>(*(InVal->op_end()-2))->getValue();
1417          MVT::ValueType EVT = cast<VTSDNode>(*(InVal->op_end()-1))->getVT();
1418
1419          // Figure out if there is a Packed type corresponding to this Vector
1420          // type.  If so, convert to the packed type.
1421          MVT::ValueType TVT = MVT::getVectorType(EVT, NumElems);
1422          if (TVT != MVT::Other && TLI.isTypeLegal(TVT)) {
1423            // Turn this into a return of the packed type.
1424            Tmp2 = PackVectorOp(Tmp2, TVT);
1425            Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
1426          } else if (NumElems == 1) {
1427            // Turn this into a return of the scalar type.
1428            Tmp2 = PackVectorOp(Tmp2, EVT);
1429            Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
1430
1431            // FIXME: Returns of gcc generic vectors smaller than a legal type
1432            // should be returned in integer registers!
1433
1434            // The scalarized value type may not be legal, e.g. it might require
1435            // promotion or expansion.  Relegalize the return.
1436            Result = LegalizeOp(Result);
1437          } else {
1438            // FIXME: Returns of gcc generic vectors larger than a legal vector
1439            // type should be returned by reference!
1440            SDOperand Lo, Hi;
1441            SplitVectorOp(Tmp2, Lo, Hi);
1442            Result = DAG.getNode(ISD::RET, MVT::Other, Tmp1, Lo, Hi);
1443            Result = LegalizeOp(Result);
1444          }
1445        }
1446        break;
1447      case Promote:
1448        Tmp2 = PromoteOp(Node->getOperand(1));
1449        Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
1450        Result = LegalizeOp(Result);
1451        break;
1452      }
1453      break;
1454    case 1:  // ret void
1455      Result = DAG.UpdateNodeOperands(Result, Tmp1);
1456      break;
1457    default: { // ret <values>
1458      std::vector<SDOperand> NewValues;
1459      NewValues.push_back(Tmp1);
1460      for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i)
1461        switch (getTypeAction(Node->getOperand(i).getValueType())) {
1462        case Legal:
1463          NewValues.push_back(LegalizeOp(Node->getOperand(i)));
1464          break;
1465        case Expand: {
1466          SDOperand Lo, Hi;
1467          assert(Node->getOperand(i).getValueType() != MVT::Vector &&
1468                 "FIXME: TODO: implement returning non-legal vector types!");
1469          ExpandOp(Node->getOperand(i), Lo, Hi);
1470          NewValues.push_back(Lo);
1471          NewValues.push_back(Hi);
1472          break;
1473        }
1474        case Promote:
1475          assert(0 && "Can't promote multiple return value yet!");
1476        }
1477
1478      if (NewValues.size() == Node->getNumOperands())
1479        Result = DAG.UpdateNodeOperands(Result, NewValues);
1480      else
1481        Result = DAG.getNode(ISD::RET, MVT::Other, NewValues);
1482      break;
1483    }
1484    }
1485
1486    if (Result.getOpcode() == ISD::RET) {
1487      switch (TLI.getOperationAction(Result.getOpcode(), MVT::Other)) {
1488      default: assert(0 && "This action is not supported yet!");
1489      case TargetLowering::Legal: break;
1490      case TargetLowering::Custom:
1491        Tmp1 = TLI.LowerOperation(Result, DAG);
1492        if (Tmp1.Val) Result = Tmp1;
1493        break;
1494      }
1495    }
1496    break;
1497  case ISD::STORE: {
1498    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1499    Tmp2 = LegalizeOp(Node->getOperand(2));  // Legalize the pointer.
1500
1501    // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
1502    // FIXME: We shouldn't do this for TargetConstantFP's.
1503    // FIXME: move this to the DAG Combiner!
1504    if (ConstantFPSDNode *CFP =dyn_cast<ConstantFPSDNode>(Node->getOperand(1))){
1505      if (CFP->getValueType(0) == MVT::f32) {
1506        Tmp3 = DAG.getConstant(FloatToBits(CFP->getValue()), MVT::i32);
1507      } else {
1508        assert(CFP->getValueType(0) == MVT::f64 && "Unknown FP type!");
1509        Tmp3 = DAG.getConstant(DoubleToBits(CFP->getValue()), MVT::i64);
1510      }
1511      Result = DAG.getNode(ISD::STORE, MVT::Other, Tmp1, Tmp3, Tmp2,
1512                           Node->getOperand(3));
1513      break;
1514    }
1515
1516    switch (getTypeAction(Node->getOperand(1).getValueType())) {
1517    case Legal: {
1518      Tmp3 = LegalizeOp(Node->getOperand(1));
1519      Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp3, Tmp2,
1520                                      Node->getOperand(3));
1521
1522      MVT::ValueType VT = Tmp3.getValueType();
1523      switch (TLI.getOperationAction(ISD::STORE, VT)) {
1524      default: assert(0 && "This action is not supported yet!");
1525      case TargetLowering::Legal:  break;
1526      case TargetLowering::Custom:
1527        Tmp1 = TLI.LowerOperation(Result, DAG);
1528        if (Tmp1.Val) Result = Tmp1;
1529        break;
1530      }
1531      break;
1532    }
1533    case Promote:
1534      // Truncate the value and store the result.
1535      Tmp3 = PromoteOp(Node->getOperand(1));
1536      Result = DAG.getNode(ISD::TRUNCSTORE, MVT::Other, Tmp1, Tmp3, Tmp2,
1537                           Node->getOperand(3),
1538                          DAG.getValueType(Node->getOperand(1).getValueType()));
1539      break;
1540
1541    case Expand:
1542      unsigned IncrementSize = 0;
1543      SDOperand Lo, Hi;
1544
1545      // If this is a vector type, then we have to calculate the increment as
1546      // the product of the element size in bytes, and the number of elements
1547      // in the high half of the vector.
1548      if (Node->getOperand(1).getValueType() == MVT::Vector) {
1549        SDNode *InVal = Node->getOperand(1).Val;
1550        unsigned NumElems =
1551          cast<ConstantSDNode>(*(InVal->op_end()-2))->getValue();
1552        MVT::ValueType EVT = cast<VTSDNode>(*(InVal->op_end()-1))->getVT();
1553
1554        // Figure out if there is a Packed type corresponding to this Vector
1555        // type.  If so, convert to the packed type.
1556        MVT::ValueType TVT = MVT::getVectorType(EVT, NumElems);
1557        if (TVT != MVT::Other && TLI.isTypeLegal(TVT)) {
1558          // Turn this into a normal store of the packed type.
1559          Tmp3 = PackVectorOp(Node->getOperand(1), TVT);
1560          Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp3, Tmp2,
1561                                          Node->getOperand(3));
1562          break;
1563        } else if (NumElems == 1) {
1564          // Turn this into a normal store of the scalar type.
1565          Tmp3 = PackVectorOp(Node->getOperand(1), EVT);
1566          Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp3, Tmp2,
1567                                          Node->getOperand(3));
1568          // The scalarized value type may not be legal, e.g. it might require
1569          // promotion or expansion.  Relegalize the scalar store.
1570          Result = LegalizeOp(Result);
1571          break;
1572        } else {
1573          SplitVectorOp(Node->getOperand(1), Lo, Hi);
1574          IncrementSize = NumElems/2 * MVT::getSizeInBits(EVT)/8;
1575        }
1576      } else {
1577        ExpandOp(Node->getOperand(1), Lo, Hi);
1578        IncrementSize = MVT::getSizeInBits(Hi.getValueType())/8;
1579
1580        if (!TLI.isLittleEndian())
1581          std::swap(Lo, Hi);
1582      }
1583
1584      Lo = DAG.getNode(ISD::STORE, MVT::Other, Tmp1, Lo, Tmp2,
1585                       Node->getOperand(3));
1586      Tmp2 = DAG.getNode(ISD::ADD, Tmp2.getValueType(), Tmp2,
1587                         getIntPtrConstant(IncrementSize));
1588      assert(isTypeLegal(Tmp2.getValueType()) &&
1589             "Pointers must be legal!");
1590      // FIXME: This sets the srcvalue of both halves to be the same, which is
1591      // wrong.
1592      Hi = DAG.getNode(ISD::STORE, MVT::Other, Tmp1, Hi, Tmp2,
1593                       Node->getOperand(3));
1594      Result = DAG.getNode(ISD::TokenFactor, MVT::Other, Lo, Hi);
1595      break;
1596    }
1597    break;
1598  }
1599  case ISD::PCMARKER:
1600    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1601    Result = DAG.UpdateNodeOperands(Result, Tmp1, Node->getOperand(1));
1602    break;
1603  case ISD::STACKSAVE:
1604    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1605    Result = DAG.UpdateNodeOperands(Result, Tmp1);
1606    Tmp1 = Result.getValue(0);
1607    Tmp2 = Result.getValue(1);
1608
1609    switch (TLI.getOperationAction(ISD::STACKSAVE, MVT::Other)) {
1610    default: assert(0 && "This action is not supported yet!");
1611    case TargetLowering::Legal: break;
1612    case TargetLowering::Custom:
1613      Tmp3 = TLI.LowerOperation(Result, DAG);
1614      if (Tmp3.Val) {
1615        Tmp1 = LegalizeOp(Tmp3);
1616        Tmp2 = LegalizeOp(Tmp3.getValue(1));
1617      }
1618      break;
1619    case TargetLowering::Expand:
1620      // Expand to CopyFromReg if the target set
1621      // StackPointerRegisterToSaveRestore.
1622      if (unsigned SP = TLI.getStackPointerRegisterToSaveRestore()) {
1623        Tmp1 = DAG.getCopyFromReg(Result.getOperand(0), SP,
1624                                  Node->getValueType(0));
1625        Tmp2 = Tmp1.getValue(1);
1626      } else {
1627        Tmp1 = DAG.getNode(ISD::UNDEF, Node->getValueType(0));
1628        Tmp2 = Node->getOperand(0);
1629      }
1630      break;
1631    }
1632
1633    // Since stacksave produce two values, make sure to remember that we
1634    // legalized both of them.
1635    AddLegalizedOperand(SDOperand(Node, 0), Tmp1);
1636    AddLegalizedOperand(SDOperand(Node, 1), Tmp2);
1637    return Op.ResNo ? Tmp2 : Tmp1;
1638
1639  case ISD::STACKRESTORE:
1640    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1641    Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the pointer.
1642    Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
1643
1644    switch (TLI.getOperationAction(ISD::STACKRESTORE, MVT::Other)) {
1645    default: assert(0 && "This action is not supported yet!");
1646    case TargetLowering::Legal: break;
1647    case TargetLowering::Custom:
1648      Tmp1 = TLI.LowerOperation(Result, DAG);
1649      if (Tmp1.Val) Result = Tmp1;
1650      break;
1651    case TargetLowering::Expand:
1652      // Expand to CopyToReg if the target set
1653      // StackPointerRegisterToSaveRestore.
1654      if (unsigned SP = TLI.getStackPointerRegisterToSaveRestore()) {
1655        Result = DAG.getCopyToReg(Tmp1, SP, Tmp2);
1656      } else {
1657        Result = Tmp1;
1658      }
1659      break;
1660    }
1661    break;
1662
1663  case ISD::READCYCLECOUNTER:
1664    Tmp1 = LegalizeOp(Node->getOperand(0)); // Legalize the chain
1665    Result = DAG.UpdateNodeOperands(Result, Tmp1);
1666
1667    // Since rdcc produce two values, make sure to remember that we legalized
1668    // both of them.
1669    AddLegalizedOperand(SDOperand(Node, 0), Result.getValue(0));
1670    AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
1671    return Result;
1672
1673  case ISD::TRUNCSTORE: {
1674    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1675    Tmp3 = LegalizeOp(Node->getOperand(2));  // Legalize the pointer.
1676
1677    assert(isTypeLegal(Node->getOperand(1).getValueType()) &&
1678           "Cannot handle illegal TRUNCSTORE yet!");
1679    Tmp2 = LegalizeOp(Node->getOperand(1));
1680
1681    // The only promote case we handle is TRUNCSTORE:i1 X into
1682    //   -> TRUNCSTORE:i8 (and X, 1)
1683    if (cast<VTSDNode>(Node->getOperand(4))->getVT() == MVT::i1 &&
1684        TLI.getOperationAction(ISD::TRUNCSTORE, MVT::i1) ==
1685              TargetLowering::Promote) {
1686      // Promote the bool to a mask then store.
1687      Tmp2 = DAG.getNode(ISD::AND, Tmp2.getValueType(), Tmp2,
1688                         DAG.getConstant(1, Tmp2.getValueType()));
1689      Result = DAG.getNode(ISD::TRUNCSTORE, MVT::Other, Tmp1, Tmp2, Tmp3,
1690                           Node->getOperand(3), DAG.getValueType(MVT::i8));
1691
1692    } else if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1) ||
1693               Tmp3 != Node->getOperand(2)) {
1694      Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3,
1695                                      Node->getOperand(3), Node->getOperand(4));
1696    }
1697
1698    MVT::ValueType StVT = cast<VTSDNode>(Result.Val->getOperand(4))->getVT();
1699    switch (TLI.getOperationAction(Result.Val->getOpcode(), StVT)) {
1700    default: assert(0 && "This action is not supported yet!");
1701    case TargetLowering::Legal: break;
1702    case TargetLowering::Custom:
1703      Tmp1 = TLI.LowerOperation(Result, DAG);
1704      if (Tmp1.Val) Result = Tmp1;
1705      break;
1706    }
1707    break;
1708  }
1709  case ISD::SELECT:
1710    switch (getTypeAction(Node->getOperand(0).getValueType())) {
1711    case Expand: assert(0 && "It's impossible to expand bools");
1712    case Legal:
1713      Tmp1 = LegalizeOp(Node->getOperand(0)); // Legalize the condition.
1714      break;
1715    case Promote:
1716      Tmp1 = PromoteOp(Node->getOperand(0));  // Promote the condition.
1717      break;
1718    }
1719    Tmp2 = LegalizeOp(Node->getOperand(1));   // TrueVal
1720    Tmp3 = LegalizeOp(Node->getOperand(2));   // FalseVal
1721
1722    Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3);
1723
1724    switch (TLI.getOperationAction(ISD::SELECT, Tmp2.getValueType())) {
1725    default: assert(0 && "This action is not supported yet!");
1726    case TargetLowering::Legal: break;
1727    case TargetLowering::Custom: {
1728      Tmp1 = TLI.LowerOperation(Result, DAG);
1729      if (Tmp1.Val) Result = Tmp1;
1730      break;
1731    }
1732    case TargetLowering::Expand:
1733      if (Tmp1.getOpcode() == ISD::SETCC) {
1734        Result = DAG.getSelectCC(Tmp1.getOperand(0), Tmp1.getOperand(1),
1735                              Tmp2, Tmp3,
1736                              cast<CondCodeSDNode>(Tmp1.getOperand(2))->get());
1737      } else {
1738        // Make sure the condition is either zero or one.  It may have been
1739        // promoted from something else.
1740        unsigned NumBits = MVT::getSizeInBits(Tmp1.getValueType());
1741        if (!TLI.MaskedValueIsZero(Tmp1, (~0ULL >> (64-NumBits))^1))
1742          Tmp1 = DAG.getZeroExtendInReg(Tmp1, MVT::i1);
1743        Result = DAG.getSelectCC(Tmp1,
1744                                 DAG.getConstant(0, Tmp1.getValueType()),
1745                                 Tmp2, Tmp3, ISD::SETNE);
1746      }
1747      break;
1748    case TargetLowering::Promote: {
1749      MVT::ValueType NVT =
1750        TLI.getTypeToPromoteTo(ISD::SELECT, Tmp2.getValueType());
1751      unsigned ExtOp, TruncOp;
1752      if (MVT::isInteger(Tmp2.getValueType())) {
1753        ExtOp   = ISD::ANY_EXTEND;
1754        TruncOp = ISD::TRUNCATE;
1755      } else {
1756        ExtOp   = ISD::FP_EXTEND;
1757        TruncOp = ISD::FP_ROUND;
1758      }
1759      // Promote each of the values to the new type.
1760      Tmp2 = DAG.getNode(ExtOp, NVT, Tmp2);
1761      Tmp3 = DAG.getNode(ExtOp, NVT, Tmp3);
1762      // Perform the larger operation, then round down.
1763      Result = DAG.getNode(ISD::SELECT, NVT, Tmp1, Tmp2,Tmp3);
1764      Result = DAG.getNode(TruncOp, Node->getValueType(0), Result);
1765      break;
1766    }
1767    }
1768    break;
1769  case ISD::SELECT_CC: {
1770    Tmp1 = Node->getOperand(0);               // LHS
1771    Tmp2 = Node->getOperand(1);               // RHS
1772    Tmp3 = LegalizeOp(Node->getOperand(2));   // True
1773    Tmp4 = LegalizeOp(Node->getOperand(3));   // False
1774    SDOperand CC = Node->getOperand(4);
1775
1776    LegalizeSetCCOperands(Tmp1, Tmp2, CC);
1777
1778    // If we didn't get both a LHS and RHS back from LegalizeSetCCOperands,
1779    // the LHS is a legal SETCC itself.  In this case, we need to compare
1780    // the result against zero to select between true and false values.
1781    if (Tmp2.Val == 0) {
1782      Tmp2 = DAG.getConstant(0, Tmp1.getValueType());
1783      CC = DAG.getCondCode(ISD::SETNE);
1784    }
1785    Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3, Tmp4, CC);
1786
1787    // Everything is legal, see if we should expand this op or something.
1788    switch (TLI.getOperationAction(ISD::SELECT_CC, Tmp3.getValueType())) {
1789    default: assert(0 && "This action is not supported yet!");
1790    case TargetLowering::Legal: break;
1791    case TargetLowering::Custom:
1792      Tmp1 = TLI.LowerOperation(Result, DAG);
1793      if (Tmp1.Val) Result = Tmp1;
1794      break;
1795    }
1796    break;
1797  }
1798  case ISD::SETCC:
1799    Tmp1 = Node->getOperand(0);
1800    Tmp2 = Node->getOperand(1);
1801    Tmp3 = Node->getOperand(2);
1802    LegalizeSetCCOperands(Tmp1, Tmp2, Tmp3);
1803
1804    // If we had to Expand the SetCC operands into a SELECT node, then it may
1805    // not always be possible to return a true LHS & RHS.  In this case, just
1806    // return the value we legalized, returned in the LHS
1807    if (Tmp2.Val == 0) {
1808      Result = Tmp1;
1809      break;
1810    }
1811
1812    switch (TLI.getOperationAction(ISD::SETCC, Tmp1.getValueType())) {
1813    default: assert(0 && "Cannot handle this action for SETCC yet!");
1814    case TargetLowering::Custom:
1815      isCustom = true;
1816      // FALLTHROUGH.
1817    case TargetLowering::Legal:
1818      Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Node->getOperand(2));
1819      if (isCustom) {
1820        Tmp3 = TLI.LowerOperation(Result, DAG);
1821        if (Tmp3.Val) Result = Tmp3;
1822      }
1823      break;
1824    case TargetLowering::Promote: {
1825      // First step, figure out the appropriate operation to use.
1826      // Allow SETCC to not be supported for all legal data types
1827      // Mostly this targets FP
1828      MVT::ValueType NewInTy = Node->getOperand(0).getValueType();
1829      MVT::ValueType OldVT = NewInTy;
1830
1831      // Scan for the appropriate larger type to use.
1832      while (1) {
1833        NewInTy = (MVT::ValueType)(NewInTy+1);
1834
1835        assert(MVT::isInteger(NewInTy) == MVT::isInteger(OldVT) &&
1836               "Fell off of the edge of the integer world");
1837        assert(MVT::isFloatingPoint(NewInTy) == MVT::isFloatingPoint(OldVT) &&
1838               "Fell off of the edge of the floating point world");
1839
1840        // If the target supports SETCC of this type, use it.
1841        if (TLI.isOperationLegal(ISD::SETCC, NewInTy))
1842          break;
1843      }
1844      if (MVT::isInteger(NewInTy))
1845        assert(0 && "Cannot promote Legal Integer SETCC yet");
1846      else {
1847        Tmp1 = DAG.getNode(ISD::FP_EXTEND, NewInTy, Tmp1);
1848        Tmp2 = DAG.getNode(ISD::FP_EXTEND, NewInTy, Tmp2);
1849      }
1850      Tmp1 = LegalizeOp(Tmp1);
1851      Tmp2 = LegalizeOp(Tmp2);
1852      Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Node->getOperand(2));
1853      Result = LegalizeOp(Result);
1854      break;
1855    }
1856    case TargetLowering::Expand:
1857      // Expand a setcc node into a select_cc of the same condition, lhs, and
1858      // rhs that selects between const 1 (true) and const 0 (false).
1859      MVT::ValueType VT = Node->getValueType(0);
1860      Result = DAG.getNode(ISD::SELECT_CC, VT, Tmp1, Tmp2,
1861                           DAG.getConstant(1, VT), DAG.getConstant(0, VT),
1862                           Node->getOperand(2));
1863      break;
1864    }
1865    break;
1866  case ISD::MEMSET:
1867  case ISD::MEMCPY:
1868  case ISD::MEMMOVE: {
1869    Tmp1 = LegalizeOp(Node->getOperand(0));      // Chain
1870    Tmp2 = LegalizeOp(Node->getOperand(1));      // Pointer
1871
1872    if (Node->getOpcode() == ISD::MEMSET) {      // memset = ubyte
1873      switch (getTypeAction(Node->getOperand(2).getValueType())) {
1874      case Expand: assert(0 && "Cannot expand a byte!");
1875      case Legal:
1876        Tmp3 = LegalizeOp(Node->getOperand(2));
1877        break;
1878      case Promote:
1879        Tmp3 = PromoteOp(Node->getOperand(2));
1880        break;
1881      }
1882    } else {
1883      Tmp3 = LegalizeOp(Node->getOperand(2));    // memcpy/move = pointer,
1884    }
1885
1886    SDOperand Tmp4;
1887    switch (getTypeAction(Node->getOperand(3).getValueType())) {
1888    case Expand: {
1889      // Length is too big, just take the lo-part of the length.
1890      SDOperand HiPart;
1891      ExpandOp(Node->getOperand(3), HiPart, Tmp4);
1892      break;
1893    }
1894    case Legal:
1895      Tmp4 = LegalizeOp(Node->getOperand(3));
1896      break;
1897    case Promote:
1898      Tmp4 = PromoteOp(Node->getOperand(3));
1899      break;
1900    }
1901
1902    SDOperand Tmp5;
1903    switch (getTypeAction(Node->getOperand(4).getValueType())) {  // uint
1904    case Expand: assert(0 && "Cannot expand this yet!");
1905    case Legal:
1906      Tmp5 = LegalizeOp(Node->getOperand(4));
1907      break;
1908    case Promote:
1909      Tmp5 = PromoteOp(Node->getOperand(4));
1910      break;
1911    }
1912
1913    switch (TLI.getOperationAction(Node->getOpcode(), MVT::Other)) {
1914    default: assert(0 && "This action not implemented for this operation!");
1915    case TargetLowering::Custom:
1916      isCustom = true;
1917      // FALLTHROUGH
1918    case TargetLowering::Legal:
1919      Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3, Tmp4, Tmp5);
1920      if (isCustom) {
1921        Tmp1 = TLI.LowerOperation(Result, DAG);
1922        if (Tmp1.Val) Result = Tmp1;
1923      }
1924      break;
1925    case TargetLowering::Expand: {
1926      // Otherwise, the target does not support this operation.  Lower the
1927      // operation to an explicit libcall as appropriate.
1928      MVT::ValueType IntPtr = TLI.getPointerTy();
1929      const Type *IntPtrTy = TLI.getTargetData().getIntPtrType();
1930      std::vector<std::pair<SDOperand, const Type*> > Args;
1931
1932      const char *FnName = 0;
1933      if (Node->getOpcode() == ISD::MEMSET) {
1934        Args.push_back(std::make_pair(Tmp2, IntPtrTy));
1935        // Extend the (previously legalized) ubyte argument to be an int value
1936        // for the call.
1937        if (Tmp3.getValueType() > MVT::i32)
1938          Tmp3 = DAG.getNode(ISD::TRUNCATE, MVT::i32, Tmp3);
1939        else
1940          Tmp3 = DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, Tmp3);
1941        Args.push_back(std::make_pair(Tmp3, Type::IntTy));
1942        Args.push_back(std::make_pair(Tmp4, IntPtrTy));
1943
1944        FnName = "memset";
1945      } else if (Node->getOpcode() == ISD::MEMCPY ||
1946                 Node->getOpcode() == ISD::MEMMOVE) {
1947        Args.push_back(std::make_pair(Tmp2, IntPtrTy));
1948        Args.push_back(std::make_pair(Tmp3, IntPtrTy));
1949        Args.push_back(std::make_pair(Tmp4, IntPtrTy));
1950        FnName = Node->getOpcode() == ISD::MEMMOVE ? "memmove" : "memcpy";
1951      } else {
1952        assert(0 && "Unknown op!");
1953      }
1954
1955      std::pair<SDOperand,SDOperand> CallResult =
1956        TLI.LowerCallTo(Tmp1, Type::VoidTy, false, CallingConv::C, false,
1957                        DAG.getExternalSymbol(FnName, IntPtr), Args, DAG);
1958      Result = CallResult.second;
1959      break;
1960    }
1961    }
1962    break;
1963  }
1964
1965  case ISD::SHL_PARTS:
1966  case ISD::SRA_PARTS:
1967  case ISD::SRL_PARTS: {
1968    std::vector<SDOperand> Ops;
1969    bool Changed = false;
1970    for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) {
1971      Ops.push_back(LegalizeOp(Node->getOperand(i)));
1972      Changed |= Ops.back() != Node->getOperand(i);
1973    }
1974    if (Changed)
1975      Result = DAG.UpdateNodeOperands(Result, Ops);
1976
1977    switch (TLI.getOperationAction(Node->getOpcode(),
1978                                   Node->getValueType(0))) {
1979    default: assert(0 && "This action is not supported yet!");
1980    case TargetLowering::Legal: break;
1981    case TargetLowering::Custom:
1982      Tmp1 = TLI.LowerOperation(Result, DAG);
1983      if (Tmp1.Val) {
1984        SDOperand Tmp2, RetVal(0, 0);
1985        for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i) {
1986          Tmp2 = LegalizeOp(Tmp1.getValue(i));
1987          AddLegalizedOperand(SDOperand(Node, i), Tmp2);
1988          if (i == Op.ResNo)
1989            RetVal = Tmp2;
1990        }
1991        assert(RetVal.Val && "Illegal result number");
1992        return RetVal;
1993      }
1994      break;
1995    }
1996
1997    // Since these produce multiple values, make sure to remember that we
1998    // legalized all of them.
1999    for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
2000      AddLegalizedOperand(SDOperand(Node, i), Result.getValue(i));
2001    return Result.getValue(Op.ResNo);
2002  }
2003
2004    // Binary operators
2005  case ISD::ADD:
2006  case ISD::SUB:
2007  case ISD::MUL:
2008  case ISD::MULHS:
2009  case ISD::MULHU:
2010  case ISD::UDIV:
2011  case ISD::SDIV:
2012  case ISD::AND:
2013  case ISD::OR:
2014  case ISD::XOR:
2015  case ISD::SHL:
2016  case ISD::SRL:
2017  case ISD::SRA:
2018  case ISD::FADD:
2019  case ISD::FSUB:
2020  case ISD::FMUL:
2021  case ISD::FDIV:
2022    Tmp1 = LegalizeOp(Node->getOperand(0));   // LHS
2023    switch (getTypeAction(Node->getOperand(1).getValueType())) {
2024    case Expand: assert(0 && "Not possible");
2025    case Legal:
2026      Tmp2 = LegalizeOp(Node->getOperand(1)); // Legalize the RHS.
2027      break;
2028    case Promote:
2029      Tmp2 = PromoteOp(Node->getOperand(1));  // Promote the RHS.
2030      break;
2031    }
2032
2033    Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
2034
2035    switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
2036    default: assert(0 && "BinOp legalize operation not supported");
2037    case TargetLowering::Legal: break;
2038    case TargetLowering::Custom:
2039      Tmp1 = TLI.LowerOperation(Result, DAG);
2040      if (Tmp1.Val) Result = Tmp1;
2041      break;
2042    case TargetLowering::Expand: {
2043      assert(MVT::isVector(Node->getValueType(0)) &&
2044             "Cannot expand this binary operator!");
2045      // Expand the operation into a bunch of nasty scalar code.
2046      std::vector<SDOperand> Ops;
2047      MVT::ValueType EltVT = MVT::getVectorBaseType(Node->getValueType(0));
2048      MVT::ValueType PtrVT = TLI.getPointerTy();
2049      for (unsigned i = 0, e = MVT::getVectorNumElements(Node->getValueType(0));
2050           i != e; ++i) {
2051        SDOperand Idx = DAG.getConstant(i, PtrVT);
2052        SDOperand LHS = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, EltVT, Tmp1, Idx);
2053        SDOperand RHS = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, EltVT, Tmp2, Idx);
2054        Ops.push_back(DAG.getNode(Node->getOpcode(), EltVT, LHS, RHS));
2055      }
2056      Result = DAG.getNode(ISD::BUILD_VECTOR, Node->getValueType(0), Ops);
2057      break;
2058    }
2059    }
2060    break;
2061
2062  case ISD::FCOPYSIGN:  // FCOPYSIGN does not require LHS/RHS to match type!
2063    Tmp1 = LegalizeOp(Node->getOperand(0));   // LHS
2064    switch (getTypeAction(Node->getOperand(1).getValueType())) {
2065      case Expand: assert(0 && "Not possible");
2066      case Legal:
2067        Tmp2 = LegalizeOp(Node->getOperand(1)); // Legalize the RHS.
2068        break;
2069      case Promote:
2070        Tmp2 = PromoteOp(Node->getOperand(1));  // Promote the RHS.
2071        break;
2072    }
2073
2074    Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
2075
2076    switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
2077    default: assert(0 && "Operation not supported");
2078    case TargetLowering::Custom:
2079      Tmp1 = TLI.LowerOperation(Result, DAG);
2080      if (Tmp1.Val) Result = Tmp1;
2081      break;
2082    case TargetLowering::Legal: break;
2083    case TargetLowering::Expand:
2084      // If this target supports fabs/fneg natively, do this efficiently.
2085      if (TLI.isOperationLegal(ISD::FABS, Tmp1.getValueType()) &&
2086          TLI.isOperationLegal(ISD::FNEG, Tmp1.getValueType())) {
2087        // Get the sign bit of the RHS.
2088        MVT::ValueType IVT =
2089          Tmp2.getValueType() == MVT::f32 ? MVT::i32 : MVT::i64;
2090        SDOperand SignBit = DAG.getNode(ISD::BIT_CONVERT, IVT, Tmp2);
2091        SignBit = DAG.getSetCC(TLI.getSetCCResultTy(),
2092                               SignBit, DAG.getConstant(0, IVT), ISD::SETLT);
2093        // Get the absolute value of the result.
2094        SDOperand AbsVal = DAG.getNode(ISD::FABS, Tmp1.getValueType(), Tmp1);
2095        // Select between the nabs and abs value based on the sign bit of
2096        // the input.
2097        Result = DAG.getNode(ISD::SELECT, AbsVal.getValueType(), SignBit,
2098                             DAG.getNode(ISD::FNEG, AbsVal.getValueType(),
2099                                         AbsVal),
2100                             AbsVal);
2101        Result = LegalizeOp(Result);
2102        break;
2103      }
2104
2105      // Otherwise, do bitwise ops!
2106
2107      // copysign -> copysignf/copysign libcall.
2108      const char *FnName;
2109      if (Node->getValueType(0) == MVT::f32) {
2110        FnName = "copysignf";
2111        if (Tmp2.getValueType() != MVT::f32)  // Force operands to match type.
2112          Result = DAG.UpdateNodeOperands(Result, Tmp1,
2113                                    DAG.getNode(ISD::FP_ROUND, MVT::f32, Tmp2));
2114      } else {
2115        FnName = "copysign";
2116        if (Tmp2.getValueType() != MVT::f64)  // Force operands to match type.
2117          Result = DAG.UpdateNodeOperands(Result, Tmp1,
2118                                   DAG.getNode(ISD::FP_EXTEND, MVT::f64, Tmp2));
2119      }
2120      SDOperand Dummy;
2121      Result = ExpandLibCall(FnName, Node, Dummy);
2122      break;
2123    }
2124    break;
2125
2126  case ISD::ADDC:
2127  case ISD::SUBC:
2128    Tmp1 = LegalizeOp(Node->getOperand(0));
2129    Tmp2 = LegalizeOp(Node->getOperand(1));
2130    Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
2131    // Since this produces two values, make sure to remember that we legalized
2132    // both of them.
2133    AddLegalizedOperand(SDOperand(Node, 0), Result.getValue(0));
2134    AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
2135    return Result;
2136
2137  case ISD::ADDE:
2138  case ISD::SUBE:
2139    Tmp1 = LegalizeOp(Node->getOperand(0));
2140    Tmp2 = LegalizeOp(Node->getOperand(1));
2141    Tmp3 = LegalizeOp(Node->getOperand(2));
2142    Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3);
2143    // Since this produces two values, make sure to remember that we legalized
2144    // both of them.
2145    AddLegalizedOperand(SDOperand(Node, 0), Result.getValue(0));
2146    AddLegalizedOperand(SDOperand(Node, 1), Result.getValue(1));
2147    return Result;
2148
2149  case ISD::BUILD_PAIR: {
2150    MVT::ValueType PairTy = Node->getValueType(0);
2151    // TODO: handle the case where the Lo and Hi operands are not of legal type
2152    Tmp1 = LegalizeOp(Node->getOperand(0));   // Lo
2153    Tmp2 = LegalizeOp(Node->getOperand(1));   // Hi
2154    switch (TLI.getOperationAction(ISD::BUILD_PAIR, PairTy)) {
2155    case TargetLowering::Promote:
2156    case TargetLowering::Custom:
2157      assert(0 && "Cannot promote/custom this yet!");
2158    case TargetLowering::Legal:
2159      if (Tmp1 != Node->getOperand(0) || Tmp2 != Node->getOperand(1))
2160        Result = DAG.getNode(ISD::BUILD_PAIR, PairTy, Tmp1, Tmp2);
2161      break;
2162    case TargetLowering::Expand:
2163      Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, PairTy, Tmp1);
2164      Tmp2 = DAG.getNode(ISD::ANY_EXTEND, PairTy, Tmp2);
2165      Tmp2 = DAG.getNode(ISD::SHL, PairTy, Tmp2,
2166                         DAG.getConstant(MVT::getSizeInBits(PairTy)/2,
2167                                         TLI.getShiftAmountTy()));
2168      Result = DAG.getNode(ISD::OR, PairTy, Tmp1, Tmp2);
2169      break;
2170    }
2171    break;
2172  }
2173
2174  case ISD::UREM:
2175  case ISD::SREM:
2176  case ISD::FREM:
2177    Tmp1 = LegalizeOp(Node->getOperand(0));   // LHS
2178    Tmp2 = LegalizeOp(Node->getOperand(1));   // RHS
2179
2180    switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
2181    case TargetLowering::Promote: assert(0 && "Cannot promote this yet!");
2182    case TargetLowering::Custom:
2183      isCustom = true;
2184      // FALLTHROUGH
2185    case TargetLowering::Legal:
2186      Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
2187      if (isCustom) {
2188        Tmp1 = TLI.LowerOperation(Result, DAG);
2189        if (Tmp1.Val) Result = Tmp1;
2190      }
2191      break;
2192    case TargetLowering::Expand:
2193      if (MVT::isInteger(Node->getValueType(0))) {
2194        // X % Y -> X-X/Y*Y
2195        MVT::ValueType VT = Node->getValueType(0);
2196        unsigned Opc = Node->getOpcode() == ISD::UREM ? ISD::UDIV : ISD::SDIV;
2197        Result = DAG.getNode(Opc, VT, Tmp1, Tmp2);
2198        Result = DAG.getNode(ISD::MUL, VT, Result, Tmp2);
2199        Result = DAG.getNode(ISD::SUB, VT, Tmp1, Result);
2200      } else {
2201        // Floating point mod -> fmod libcall.
2202        const char *FnName = Node->getValueType(0) == MVT::f32 ? "fmodf":"fmod";
2203        SDOperand Dummy;
2204        Result = ExpandLibCall(FnName, Node, Dummy);
2205      }
2206      break;
2207    }
2208    break;
2209  case ISD::VAARG: {
2210    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
2211    Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the pointer.
2212
2213    MVT::ValueType VT = Node->getValueType(0);
2214    switch (TLI.getOperationAction(Node->getOpcode(), MVT::Other)) {
2215    default: assert(0 && "This action is not supported yet!");
2216    case TargetLowering::Custom:
2217      isCustom = true;
2218      // FALLTHROUGH
2219    case TargetLowering::Legal:
2220      Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Node->getOperand(2));
2221      Result = Result.getValue(0);
2222      Tmp1 = Result.getValue(1);
2223
2224      if (isCustom) {
2225        Tmp2 = TLI.LowerOperation(Result, DAG);
2226        if (Tmp2.Val) {
2227          Result = LegalizeOp(Tmp2);
2228          Tmp1 = LegalizeOp(Tmp2.getValue(1));
2229        }
2230      }
2231      break;
2232    case TargetLowering::Expand: {
2233      SDOperand VAList = DAG.getLoad(TLI.getPointerTy(), Tmp1, Tmp2,
2234                                     Node->getOperand(2));
2235      // Increment the pointer, VAList, to the next vaarg
2236      Tmp3 = DAG.getNode(ISD::ADD, TLI.getPointerTy(), VAList,
2237                         DAG.getConstant(MVT::getSizeInBits(VT)/8,
2238                                         TLI.getPointerTy()));
2239      // Store the incremented VAList to the legalized pointer
2240      Tmp3 = DAG.getNode(ISD::STORE, MVT::Other, VAList.getValue(1), Tmp3, Tmp2,
2241                         Node->getOperand(2));
2242      // Load the actual argument out of the pointer VAList
2243      Result = DAG.getLoad(VT, Tmp3, VAList, DAG.getSrcValue(0));
2244      Tmp1 = LegalizeOp(Result.getValue(1));
2245      Result = LegalizeOp(Result);
2246      break;
2247    }
2248    }
2249    // Since VAARG produces two values, make sure to remember that we
2250    // legalized both of them.
2251    AddLegalizedOperand(SDOperand(Node, 0), Result);
2252    AddLegalizedOperand(SDOperand(Node, 1), Tmp1);
2253    return Op.ResNo ? Tmp1 : Result;
2254  }
2255
2256  case ISD::VACOPY:
2257    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
2258    Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the dest pointer.
2259    Tmp3 = LegalizeOp(Node->getOperand(2));  // Legalize the source pointer.
2260
2261    switch (TLI.getOperationAction(ISD::VACOPY, MVT::Other)) {
2262    default: assert(0 && "This action is not supported yet!");
2263    case TargetLowering::Custom:
2264      isCustom = true;
2265      // FALLTHROUGH
2266    case TargetLowering::Legal:
2267      Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Tmp3,
2268                                      Node->getOperand(3), Node->getOperand(4));
2269      if (isCustom) {
2270        Tmp1 = TLI.LowerOperation(Result, DAG);
2271        if (Tmp1.Val) Result = Tmp1;
2272      }
2273      break;
2274    case TargetLowering::Expand:
2275      // This defaults to loading a pointer from the input and storing it to the
2276      // output, returning the chain.
2277      Tmp4 = DAG.getLoad(TLI.getPointerTy(), Tmp1, Tmp3, Node->getOperand(3));
2278      Result = DAG.getNode(ISD::STORE, MVT::Other, Tmp4.getValue(1), Tmp4, Tmp2,
2279                           Node->getOperand(4));
2280      break;
2281    }
2282    break;
2283
2284  case ISD::VAEND:
2285    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
2286    Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the pointer.
2287
2288    switch (TLI.getOperationAction(ISD::VAEND, MVT::Other)) {
2289    default: assert(0 && "This action is not supported yet!");
2290    case TargetLowering::Custom:
2291      isCustom = true;
2292      // FALLTHROUGH
2293    case TargetLowering::Legal:
2294      Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Node->getOperand(2));
2295      if (isCustom) {
2296        Tmp1 = TLI.LowerOperation(Tmp1, DAG);
2297        if (Tmp1.Val) Result = Tmp1;
2298      }
2299      break;
2300    case TargetLowering::Expand:
2301      Result = Tmp1; // Default to a no-op, return the chain
2302      break;
2303    }
2304    break;
2305
2306  case ISD::VASTART:
2307    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
2308    Tmp2 = LegalizeOp(Node->getOperand(1));  // Legalize the pointer.
2309
2310    Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, Node->getOperand(2));
2311
2312    switch (TLI.getOperationAction(ISD::VASTART, MVT::Other)) {
2313    default: assert(0 && "This action is not supported yet!");
2314    case TargetLowering::Legal: break;
2315    case TargetLowering::Custom:
2316      Tmp1 = TLI.LowerOperation(Result, DAG);
2317      if (Tmp1.Val) Result = Tmp1;
2318      break;
2319    }
2320    break;
2321
2322  case ISD::ROTL:
2323  case ISD::ROTR:
2324    Tmp1 = LegalizeOp(Node->getOperand(0));   // LHS
2325    Tmp2 = LegalizeOp(Node->getOperand(1));   // RHS
2326
2327    assert(TLI.isOperationLegal(Node->getOpcode(), Node->getValueType(0)) &&
2328           "Cannot handle this yet!");
2329    Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2);
2330    break;
2331
2332  case ISD::BSWAP:
2333    Tmp1 = LegalizeOp(Node->getOperand(0));   // Op
2334    switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
2335    case TargetLowering::Custom:
2336      assert(0 && "Cannot custom legalize this yet!");
2337    case TargetLowering::Legal:
2338      Result = DAG.UpdateNodeOperands(Result, Tmp1);
2339      break;
2340    case TargetLowering::Promote: {
2341      MVT::ValueType OVT = Tmp1.getValueType();
2342      MVT::ValueType NVT = TLI.getTypeToPromoteTo(Node->getOpcode(), OVT);
2343      unsigned DiffBits = getSizeInBits(NVT) - getSizeInBits(OVT);
2344
2345      Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, NVT, Tmp1);
2346      Tmp1 = DAG.getNode(ISD::BSWAP, NVT, Tmp1);
2347      Result = DAG.getNode(ISD::SRL, NVT, Tmp1,
2348                           DAG.getConstant(DiffBits, TLI.getShiftAmountTy()));
2349      break;
2350    }
2351    case TargetLowering::Expand:
2352      Result = ExpandBSWAP(Tmp1);
2353      break;
2354    }
2355    break;
2356
2357  case ISD::CTPOP:
2358  case ISD::CTTZ:
2359  case ISD::CTLZ:
2360    Tmp1 = LegalizeOp(Node->getOperand(0));   // Op
2361    switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
2362    case TargetLowering::Custom: assert(0 && "Cannot custom handle this yet!");
2363    case TargetLowering::Legal:
2364      Result = DAG.UpdateNodeOperands(Result, Tmp1);
2365      break;
2366    case TargetLowering::Promote: {
2367      MVT::ValueType OVT = Tmp1.getValueType();
2368      MVT::ValueType NVT = TLI.getTypeToPromoteTo(Node->getOpcode(), OVT);
2369
2370      // Zero extend the argument.
2371      Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, NVT, Tmp1);
2372      // Perform the larger operation, then subtract if needed.
2373      Tmp1 = DAG.getNode(Node->getOpcode(), Node->getValueType(0), Tmp1);
2374      switch (Node->getOpcode()) {
2375      case ISD::CTPOP:
2376        Result = Tmp1;
2377        break;
2378      case ISD::CTTZ:
2379        //if Tmp1 == sizeinbits(NVT) then Tmp1 = sizeinbits(Old VT)
2380        Tmp2 = DAG.getSetCC(TLI.getSetCCResultTy(), Tmp1,
2381                            DAG.getConstant(getSizeInBits(NVT), NVT),
2382                            ISD::SETEQ);
2383        Result = DAG.getNode(ISD::SELECT, NVT, Tmp2,
2384                           DAG.getConstant(getSizeInBits(OVT),NVT), Tmp1);
2385        break;
2386      case ISD::CTLZ:
2387        // Tmp1 = Tmp1 - (sizeinbits(NVT) - sizeinbits(Old VT))
2388        Result = DAG.getNode(ISD::SUB, NVT, Tmp1,
2389                             DAG.getConstant(getSizeInBits(NVT) -
2390                                             getSizeInBits(OVT), NVT));
2391        break;
2392      }
2393      break;
2394    }
2395    case TargetLowering::Expand:
2396      Result = ExpandBitCount(Node->getOpcode(), Tmp1);
2397      break;
2398    }
2399    break;
2400
2401    // Unary operators
2402  case ISD::FABS:
2403  case ISD::FNEG:
2404  case ISD::FSQRT:
2405  case ISD::FSIN:
2406  case ISD::FCOS:
2407    Tmp1 = LegalizeOp(Node->getOperand(0));
2408    switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))) {
2409    case TargetLowering::Promote:
2410    case TargetLowering::Custom:
2411     isCustom = true;
2412     // FALLTHROUGH
2413    case TargetLowering::Legal:
2414      Result = DAG.UpdateNodeOperands(Result, Tmp1);
2415      if (isCustom) {
2416        Tmp1 = TLI.LowerOperation(Result, DAG);
2417        if (Tmp1.Val) Result = Tmp1;
2418      }
2419      break;
2420    case TargetLowering::Expand:
2421      switch (Node->getOpcode()) {
2422      default: assert(0 && "Unreachable!");
2423      case ISD::FNEG:
2424        // Expand Y = FNEG(X) ->  Y = SUB -0.0, X
2425        Tmp2 = DAG.getConstantFP(-0.0, Node->getValueType(0));
2426        Result = DAG.getNode(ISD::FSUB, Node->getValueType(0), Tmp2, Tmp1);
2427        break;
2428      case ISD::FABS: {
2429        // Expand Y = FABS(X) -> Y = (X >u 0.0) ? X : fneg(X).
2430        MVT::ValueType VT = Node->getValueType(0);
2431        Tmp2 = DAG.getConstantFP(0.0, VT);
2432        Tmp2 = DAG.getSetCC(TLI.getSetCCResultTy(), Tmp1, Tmp2, ISD::SETUGT);
2433        Tmp3 = DAG.getNode(ISD::FNEG, VT, Tmp1);
2434        Result = DAG.getNode(ISD::SELECT, VT, Tmp2, Tmp1, Tmp3);
2435        break;
2436      }
2437      case ISD::FSQRT:
2438      case ISD::FSIN:
2439      case ISD::FCOS: {
2440        MVT::ValueType VT = Node->getValueType(0);
2441        const char *FnName = 0;
2442        switch(Node->getOpcode()) {
2443        case ISD::FSQRT: FnName = VT == MVT::f32 ? "sqrtf" : "sqrt"; break;
2444        case ISD::FSIN:  FnName = VT == MVT::f32 ? "sinf"  : "sin"; break;
2445        case ISD::FCOS:  FnName = VT == MVT::f32 ? "cosf"  : "cos"; break;
2446        default: assert(0 && "Unreachable!");
2447        }
2448        SDOperand Dummy;
2449        Result = ExpandLibCall(FnName, Node, Dummy);
2450        break;
2451      }
2452      }
2453      break;
2454    }
2455    break;
2456
2457  case ISD::BIT_CONVERT:
2458    if (!isTypeLegal(Node->getOperand(0).getValueType())) {
2459      Result = ExpandBIT_CONVERT(Node->getValueType(0), Node->getOperand(0));
2460    } else {
2461      switch (TLI.getOperationAction(ISD::BIT_CONVERT,
2462                                     Node->getOperand(0).getValueType())) {
2463      default: assert(0 && "Unknown operation action!");
2464      case TargetLowering::Expand:
2465        Result = ExpandBIT_CONVERT(Node->getValueType(0), Node->getOperand(0));
2466        break;
2467      case TargetLowering::Legal:
2468        Tmp1 = LegalizeOp(Node->getOperand(0));
2469        Result = DAG.UpdateNodeOperands(Result, Tmp1);
2470        break;
2471      }
2472    }
2473    break;
2474  case ISD::VBIT_CONVERT: {
2475    assert(Op.getOperand(0).getValueType() == MVT::Vector &&
2476           "Can only have VBIT_CONVERT where input or output is MVT::Vector!");
2477
2478    // The input has to be a vector type, we have to either scalarize it, pack
2479    // it, or convert it based on whether the input vector type is legal.
2480    SDNode *InVal = Node->getOperand(0).Val;
2481    unsigned NumElems =
2482      cast<ConstantSDNode>(*(InVal->op_end()-2))->getValue();
2483    MVT::ValueType EVT = cast<VTSDNode>(*(InVal->op_end()-1))->getVT();
2484
2485    // Figure out if there is a Packed type corresponding to this Vector
2486    // type.  If so, convert to the packed type.
2487    MVT::ValueType TVT = MVT::getVectorType(EVT, NumElems);
2488    if (TVT != MVT::Other && TLI.isTypeLegal(TVT)) {
2489      // Turn this into a bit convert of the packed input.
2490      Result = DAG.getNode(ISD::BIT_CONVERT, Node->getValueType(0),
2491                           PackVectorOp(Node->getOperand(0), TVT));
2492      break;
2493    } else if (NumElems == 1) {
2494      // Turn this into a bit convert of the scalar input.
2495      Result = DAG.getNode(ISD::BIT_CONVERT, Node->getValueType(0),
2496                           PackVectorOp(Node->getOperand(0), EVT));
2497      break;
2498    } else {
2499      // FIXME: UNIMP!  Store then reload
2500      assert(0 && "Cast from unsupported vector type not implemented yet!");
2501    }
2502  }
2503
2504    // Conversion operators.  The source and destination have different types.
2505  case ISD::SINT_TO_FP:
2506  case ISD::UINT_TO_FP: {
2507    bool isSigned = Node->getOpcode() == ISD::SINT_TO_FP;
2508    switch (getTypeAction(Node->getOperand(0).getValueType())) {
2509    case Legal:
2510      switch (TLI.getOperationAction(Node->getOpcode(),
2511                                     Node->getOperand(0).getValueType())) {
2512      default: assert(0 && "Unknown operation action!");
2513      case TargetLowering::Custom:
2514        isCustom = true;
2515        // FALLTHROUGH
2516      case TargetLowering::Legal:
2517        Tmp1 = LegalizeOp(Node->getOperand(0));
2518        Result = DAG.UpdateNodeOperands(Result, Tmp1);
2519        if (isCustom) {
2520          Tmp1 = TLI.LowerOperation(Result, DAG);
2521          if (Tmp1.Val) Result = Tmp1;
2522        }
2523        break;
2524      case TargetLowering::Expand:
2525        Result = ExpandLegalINT_TO_FP(isSigned,
2526                                      LegalizeOp(Node->getOperand(0)),
2527                                      Node->getValueType(0));
2528        break;
2529      case TargetLowering::Promote:
2530        Result = PromoteLegalINT_TO_FP(LegalizeOp(Node->getOperand(0)),
2531                                       Node->getValueType(0),
2532                                       isSigned);
2533        break;
2534      }
2535      break;
2536    case Expand:
2537      Result = ExpandIntToFP(Node->getOpcode() == ISD::SINT_TO_FP,
2538                             Node->getValueType(0), Node->getOperand(0));
2539      break;
2540    case Promote:
2541      Tmp1 = PromoteOp(Node->getOperand(0));
2542      if (isSigned) {
2543        Tmp1 = DAG.getNode(ISD::SIGN_EXTEND_INREG, Tmp1.getValueType(),
2544                 Tmp1, DAG.getValueType(Node->getOperand(0).getValueType()));
2545      } else {
2546        Tmp1 = DAG.getZeroExtendInReg(Tmp1,
2547                                      Node->getOperand(0).getValueType());
2548      }
2549      Result = DAG.UpdateNodeOperands(Result, Tmp1);
2550      Result = LegalizeOp(Result);  // The 'op' is not necessarily legal!
2551      break;
2552    }
2553    break;
2554  }
2555  case ISD::TRUNCATE:
2556    switch (getTypeAction(Node->getOperand(0).getValueType())) {
2557    case Legal:
2558      Tmp1 = LegalizeOp(Node->getOperand(0));
2559      Result = DAG.UpdateNodeOperands(Result, Tmp1);
2560      break;
2561    case Expand:
2562      ExpandOp(Node->getOperand(0), Tmp1, Tmp2);
2563
2564      // Since the result is legal, we should just be able to truncate the low
2565      // part of the source.
2566      Result = DAG.getNode(ISD::TRUNCATE, Node->getValueType(0), Tmp1);
2567      break;
2568    case Promote:
2569      Result = PromoteOp(Node->getOperand(0));
2570      Result = DAG.getNode(ISD::TRUNCATE, Op.getValueType(), Result);
2571      break;
2572    }
2573    break;
2574
2575  case ISD::FP_TO_SINT:
2576  case ISD::FP_TO_UINT:
2577    switch (getTypeAction(Node->getOperand(0).getValueType())) {
2578    case Legal:
2579      Tmp1 = LegalizeOp(Node->getOperand(0));
2580
2581      switch (TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0))){
2582      default: assert(0 && "Unknown operation action!");
2583      case TargetLowering::Custom:
2584        isCustom = true;
2585        // FALLTHROUGH
2586      case TargetLowering::Legal:
2587        Result = DAG.UpdateNodeOperands(Result, Tmp1);
2588        if (isCustom) {
2589          Tmp1 = TLI.LowerOperation(Result, DAG);
2590          if (Tmp1.Val) Result = Tmp1;
2591        }
2592        break;
2593      case TargetLowering::Promote:
2594        Result = PromoteLegalFP_TO_INT(Tmp1, Node->getValueType(0),
2595                                       Node->getOpcode() == ISD::FP_TO_SINT);
2596        break;
2597      case TargetLowering::Expand:
2598        if (Node->getOpcode() == ISD::FP_TO_UINT) {
2599          SDOperand True, False;
2600          MVT::ValueType VT =  Node->getOperand(0).getValueType();
2601          MVT::ValueType NVT = Node->getValueType(0);
2602          unsigned ShiftAmt = MVT::getSizeInBits(Node->getValueType(0))-1;
2603          Tmp2 = DAG.getConstantFP((double)(1ULL << ShiftAmt), VT);
2604          Tmp3 = DAG.getSetCC(TLI.getSetCCResultTy(),
2605                            Node->getOperand(0), Tmp2, ISD::SETLT);
2606          True = DAG.getNode(ISD::FP_TO_SINT, NVT, Node->getOperand(0));
2607          False = DAG.getNode(ISD::FP_TO_SINT, NVT,
2608                              DAG.getNode(ISD::FSUB, VT, Node->getOperand(0),
2609                                          Tmp2));
2610          False = DAG.getNode(ISD::XOR, NVT, False,
2611                              DAG.getConstant(1ULL << ShiftAmt, NVT));
2612          Result = DAG.getNode(ISD::SELECT, NVT, Tmp3, True, False);
2613          break;
2614        } else {
2615          assert(0 && "Do not know how to expand FP_TO_SINT yet!");
2616        }
2617        break;
2618      }
2619      break;
2620    case Expand:
2621      assert(0 && "Shouldn't need to expand other operators here!");
2622    case Promote:
2623      Tmp1 = PromoteOp(Node->getOperand(0));
2624      Result = DAG.UpdateNodeOperands(Result, LegalizeOp(Tmp1));
2625      Result = LegalizeOp(Result);
2626      break;
2627    }
2628    break;
2629
2630  case ISD::ANY_EXTEND:
2631  case ISD::ZERO_EXTEND:
2632  case ISD::SIGN_EXTEND:
2633  case ISD::FP_EXTEND:
2634  case ISD::FP_ROUND:
2635    switch (getTypeAction(Node->getOperand(0).getValueType())) {
2636    case Expand: assert(0 && "Shouldn't need to expand other operators here!");
2637    case Legal:
2638      Tmp1 = LegalizeOp(Node->getOperand(0));
2639      Result = DAG.UpdateNodeOperands(Result, Tmp1);
2640      break;
2641    case Promote:
2642      switch (Node->getOpcode()) {
2643      case ISD::ANY_EXTEND:
2644        Tmp1 = PromoteOp(Node->getOperand(0));
2645        Result = DAG.getNode(ISD::ANY_EXTEND, Op.getValueType(), Tmp1);
2646        break;
2647      case ISD::ZERO_EXTEND:
2648        Result = PromoteOp(Node->getOperand(0));
2649        Result = DAG.getNode(ISD::ANY_EXTEND, Op.getValueType(), Result);
2650        Result = DAG.getZeroExtendInReg(Result,
2651                                        Node->getOperand(0).getValueType());
2652        break;
2653      case ISD::SIGN_EXTEND:
2654        Result = PromoteOp(Node->getOperand(0));
2655        Result = DAG.getNode(ISD::ANY_EXTEND, Op.getValueType(), Result);
2656        Result = DAG.getNode(ISD::SIGN_EXTEND_INREG, Result.getValueType(),
2657                             Result,
2658                          DAG.getValueType(Node->getOperand(0).getValueType()));
2659        break;
2660      case ISD::FP_EXTEND:
2661        Result = PromoteOp(Node->getOperand(0));
2662        if (Result.getValueType() != Op.getValueType())
2663          // Dynamically dead while we have only 2 FP types.
2664          Result = DAG.getNode(ISD::FP_EXTEND, Op.getValueType(), Result);
2665        break;
2666      case ISD::FP_ROUND:
2667        Result = PromoteOp(Node->getOperand(0));
2668        Result = DAG.getNode(Node->getOpcode(), Op.getValueType(), Result);
2669        break;
2670      }
2671    }
2672    break;
2673  case ISD::FP_ROUND_INREG:
2674  case ISD::SIGN_EXTEND_INREG: {
2675    Tmp1 = LegalizeOp(Node->getOperand(0));
2676    MVT::ValueType ExtraVT = cast<VTSDNode>(Node->getOperand(1))->getVT();
2677
2678    // If this operation is not supported, convert it to a shl/shr or load/store
2679    // pair.
2680    switch (TLI.getOperationAction(Node->getOpcode(), ExtraVT)) {
2681    default: assert(0 && "This action not supported for this op yet!");
2682    case TargetLowering::Legal:
2683      Result = DAG.UpdateNodeOperands(Result, Tmp1, Node->getOperand(1));
2684      break;
2685    case TargetLowering::Expand:
2686      // If this is an integer extend and shifts are supported, do that.
2687      if (Node->getOpcode() == ISD::SIGN_EXTEND_INREG) {
2688        // NOTE: we could fall back on load/store here too for targets without
2689        // SAR.  However, it is doubtful that any exist.
2690        unsigned BitsDiff = MVT::getSizeInBits(Node->getValueType(0)) -
2691                            MVT::getSizeInBits(ExtraVT);
2692        SDOperand ShiftCst = DAG.getConstant(BitsDiff, TLI.getShiftAmountTy());
2693        Result = DAG.getNode(ISD::SHL, Node->getValueType(0),
2694                             Node->getOperand(0), ShiftCst);
2695        Result = DAG.getNode(ISD::SRA, Node->getValueType(0),
2696                             Result, ShiftCst);
2697      } else if (Node->getOpcode() == ISD::FP_ROUND_INREG) {
2698        // The only way we can lower this is to turn it into a STORETRUNC,
2699        // EXTLOAD pair, targetting a temporary location (a stack slot).
2700
2701        // NOTE: there is a choice here between constantly creating new stack
2702        // slots and always reusing the same one.  We currently always create
2703        // new ones, as reuse may inhibit scheduling.
2704        const Type *Ty = MVT::getTypeForValueType(ExtraVT);
2705        unsigned TySize = (unsigned)TLI.getTargetData().getTypeSize(Ty);
2706        unsigned Align  = TLI.getTargetData().getTypeAlignment(Ty);
2707        MachineFunction &MF = DAG.getMachineFunction();
2708        int SSFI =
2709          MF.getFrameInfo()->CreateStackObject((unsigned)TySize, Align);
2710        SDOperand StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
2711        Result = DAG.getNode(ISD::TRUNCSTORE, MVT::Other, DAG.getEntryNode(),
2712                             Node->getOperand(0), StackSlot,
2713                             DAG.getSrcValue(NULL), DAG.getValueType(ExtraVT));
2714        Result = DAG.getExtLoad(ISD::EXTLOAD, Node->getValueType(0),
2715                                Result, StackSlot, DAG.getSrcValue(NULL),
2716                                ExtraVT);
2717      } else {
2718        assert(0 && "Unknown op");
2719      }
2720      break;
2721    }
2722    break;
2723  }
2724  }
2725
2726  assert(Result.getValueType() == Op.getValueType() &&
2727         "Bad legalization!");
2728
2729  // Make sure that the generated code is itself legal.
2730  if (Result != Op)
2731    Result = LegalizeOp(Result);
2732
2733  // Note that LegalizeOp may be reentered even from single-use nodes, which
2734  // means that we always must cache transformed nodes.
2735  AddLegalizedOperand(Op, Result);
2736  return Result;
2737}
2738
2739/// PromoteOp - Given an operation that produces a value in an invalid type,
2740/// promote it to compute the value into a larger type.  The produced value will
2741/// have the correct bits for the low portion of the register, but no guarantee
2742/// is made about the top bits: it may be zero, sign-extended, or garbage.
2743SDOperand SelectionDAGLegalize::PromoteOp(SDOperand Op) {
2744  MVT::ValueType VT = Op.getValueType();
2745  MVT::ValueType NVT = TLI.getTypeToTransformTo(VT);
2746  assert(getTypeAction(VT) == Promote &&
2747         "Caller should expand or legalize operands that are not promotable!");
2748  assert(NVT > VT && MVT::isInteger(NVT) == MVT::isInteger(VT) &&
2749         "Cannot promote to smaller type!");
2750
2751  SDOperand Tmp1, Tmp2, Tmp3;
2752  SDOperand Result;
2753  SDNode *Node = Op.Val;
2754
2755  std::map<SDOperand, SDOperand>::iterator I = PromotedNodes.find(Op);
2756  if (I != PromotedNodes.end()) return I->second;
2757
2758  switch (Node->getOpcode()) {
2759  case ISD::CopyFromReg:
2760    assert(0 && "CopyFromReg must be legal!");
2761  default:
2762    std::cerr << "NODE: "; Node->dump(); std::cerr << "\n";
2763    assert(0 && "Do not know how to promote this operator!");
2764    abort();
2765  case ISD::UNDEF:
2766    Result = DAG.getNode(ISD::UNDEF, NVT);
2767    break;
2768  case ISD::Constant:
2769    if (VT != MVT::i1)
2770      Result = DAG.getNode(ISD::SIGN_EXTEND, NVT, Op);
2771    else
2772      Result = DAG.getNode(ISD::ZERO_EXTEND, NVT, Op);
2773    assert(isa<ConstantSDNode>(Result) && "Didn't constant fold zext?");
2774    break;
2775  case ISD::ConstantFP:
2776    Result = DAG.getNode(ISD::FP_EXTEND, NVT, Op);
2777    assert(isa<ConstantFPSDNode>(Result) && "Didn't constant fold fp_extend?");
2778    break;
2779
2780  case ISD::SETCC:
2781    assert(isTypeLegal(TLI.getSetCCResultTy()) && "SetCC type is not legal??");
2782    Result = DAG.getNode(ISD::SETCC, TLI.getSetCCResultTy(),Node->getOperand(0),
2783                         Node->getOperand(1), Node->getOperand(2));
2784    break;
2785
2786  case ISD::TRUNCATE:
2787    switch (getTypeAction(Node->getOperand(0).getValueType())) {
2788    case Legal:
2789      Result = LegalizeOp(Node->getOperand(0));
2790      assert(Result.getValueType() >= NVT &&
2791             "This truncation doesn't make sense!");
2792      if (Result.getValueType() > NVT)    // Truncate to NVT instead of VT
2793        Result = DAG.getNode(ISD::TRUNCATE, NVT, Result);
2794      break;
2795    case Promote:
2796      // The truncation is not required, because we don't guarantee anything
2797      // about high bits anyway.
2798      Result = PromoteOp(Node->getOperand(0));
2799      break;
2800    case Expand:
2801      ExpandOp(Node->getOperand(0), Tmp1, Tmp2);
2802      // Truncate the low part of the expanded value to the result type
2803      Result = DAG.getNode(ISD::TRUNCATE, NVT, Tmp1);
2804    }
2805    break;
2806  case ISD::SIGN_EXTEND:
2807  case ISD::ZERO_EXTEND:
2808  case ISD::ANY_EXTEND:
2809    switch (getTypeAction(Node->getOperand(0).getValueType())) {
2810    case Expand: assert(0 && "BUG: Smaller reg should have been promoted!");
2811    case Legal:
2812      // Input is legal?  Just do extend all the way to the larger type.
2813      Result = DAG.getNode(Node->getOpcode(), NVT, Node->getOperand(0));
2814      break;
2815    case Promote:
2816      // Promote the reg if it's smaller.
2817      Result = PromoteOp(Node->getOperand(0));
2818      // The high bits are not guaranteed to be anything.  Insert an extend.
2819      if (Node->getOpcode() == ISD::SIGN_EXTEND)
2820        Result = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Result,
2821                         DAG.getValueType(Node->getOperand(0).getValueType()));
2822      else if (Node->getOpcode() == ISD::ZERO_EXTEND)
2823        Result = DAG.getZeroExtendInReg(Result,
2824                                        Node->getOperand(0).getValueType());
2825      break;
2826    }
2827    break;
2828  case ISD::BIT_CONVERT:
2829    Result = ExpandBIT_CONVERT(Node->getValueType(0), Node->getOperand(0));
2830    Result = PromoteOp(Result);
2831    break;
2832
2833  case ISD::FP_EXTEND:
2834    assert(0 && "Case not implemented.  Dynamically dead with 2 FP types!");
2835  case ISD::FP_ROUND:
2836    switch (getTypeAction(Node->getOperand(0).getValueType())) {
2837    case Expand: assert(0 && "BUG: Cannot expand FP regs!");
2838    case Promote:  assert(0 && "Unreachable with 2 FP types!");
2839    case Legal:
2840      // Input is legal?  Do an FP_ROUND_INREG.
2841      Result = DAG.getNode(ISD::FP_ROUND_INREG, NVT, Node->getOperand(0),
2842                           DAG.getValueType(VT));
2843      break;
2844    }
2845    break;
2846
2847  case ISD::SINT_TO_FP:
2848  case ISD::UINT_TO_FP:
2849    switch (getTypeAction(Node->getOperand(0).getValueType())) {
2850    case Legal:
2851      // No extra round required here.
2852      Result = DAG.getNode(Node->getOpcode(), NVT, Node->getOperand(0));
2853      break;
2854
2855    case Promote:
2856      Result = PromoteOp(Node->getOperand(0));
2857      if (Node->getOpcode() == ISD::SINT_TO_FP)
2858        Result = DAG.getNode(ISD::SIGN_EXTEND_INREG, Result.getValueType(),
2859                             Result,
2860                         DAG.getValueType(Node->getOperand(0).getValueType()));
2861      else
2862        Result = DAG.getZeroExtendInReg(Result,
2863                                        Node->getOperand(0).getValueType());
2864      // No extra round required here.
2865      Result = DAG.getNode(Node->getOpcode(), NVT, Result);
2866      break;
2867    case Expand:
2868      Result = ExpandIntToFP(Node->getOpcode() == ISD::SINT_TO_FP, NVT,
2869                             Node->getOperand(0));
2870      // Round if we cannot tolerate excess precision.
2871      if (NoExcessFPPrecision)
2872        Result = DAG.getNode(ISD::FP_ROUND_INREG, NVT, Result,
2873                             DAG.getValueType(VT));
2874      break;
2875    }
2876    break;
2877
2878  case ISD::SIGN_EXTEND_INREG:
2879    Result = PromoteOp(Node->getOperand(0));
2880    Result = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Result,
2881                         Node->getOperand(1));
2882    break;
2883  case ISD::FP_TO_SINT:
2884  case ISD::FP_TO_UINT:
2885    switch (getTypeAction(Node->getOperand(0).getValueType())) {
2886    case Legal:
2887      Tmp1 = Node->getOperand(0);
2888      break;
2889    case Promote:
2890      // The input result is prerounded, so we don't have to do anything
2891      // special.
2892      Tmp1 = PromoteOp(Node->getOperand(0));
2893      break;
2894    case Expand:
2895      assert(0 && "not implemented");
2896    }
2897    // If we're promoting a UINT to a larger size, check to see if the new node
2898    // will be legal.  If it isn't, check to see if FP_TO_SINT is legal, since
2899    // we can use that instead.  This allows us to generate better code for
2900    // FP_TO_UINT for small destination sizes on targets where FP_TO_UINT is not
2901    // legal, such as PowerPC.
2902    if (Node->getOpcode() == ISD::FP_TO_UINT &&
2903        !TLI.isOperationLegal(ISD::FP_TO_UINT, NVT) &&
2904        (TLI.isOperationLegal(ISD::FP_TO_SINT, NVT) ||
2905         TLI.getOperationAction(ISD::FP_TO_SINT, NVT)==TargetLowering::Custom)){
2906      Result = DAG.getNode(ISD::FP_TO_SINT, NVT, Tmp1);
2907    } else {
2908      Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1);
2909    }
2910    break;
2911
2912  case ISD::FABS:
2913  case ISD::FNEG:
2914    Tmp1 = PromoteOp(Node->getOperand(0));
2915    assert(Tmp1.getValueType() == NVT);
2916    Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1);
2917    // NOTE: we do not have to do any extra rounding here for
2918    // NoExcessFPPrecision, because we know the input will have the appropriate
2919    // precision, and these operations don't modify precision at all.
2920    break;
2921
2922  case ISD::FSQRT:
2923  case ISD::FSIN:
2924  case ISD::FCOS:
2925    Tmp1 = PromoteOp(Node->getOperand(0));
2926    assert(Tmp1.getValueType() == NVT);
2927    Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1);
2928    if (NoExcessFPPrecision)
2929      Result = DAG.getNode(ISD::FP_ROUND_INREG, NVT, Result,
2930                           DAG.getValueType(VT));
2931    break;
2932
2933  case ISD::AND:
2934  case ISD::OR:
2935  case ISD::XOR:
2936  case ISD::ADD:
2937  case ISD::SUB:
2938  case ISD::MUL:
2939    // The input may have strange things in the top bits of the registers, but
2940    // these operations don't care.  They may have weird bits going out, but
2941    // that too is okay if they are integer operations.
2942    Tmp1 = PromoteOp(Node->getOperand(0));
2943    Tmp2 = PromoteOp(Node->getOperand(1));
2944    assert(Tmp1.getValueType() == NVT && Tmp2.getValueType() == NVT);
2945    Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1, Tmp2);
2946    break;
2947  case ISD::FADD:
2948  case ISD::FSUB:
2949  case ISD::FMUL:
2950    Tmp1 = PromoteOp(Node->getOperand(0));
2951    Tmp2 = PromoteOp(Node->getOperand(1));
2952    assert(Tmp1.getValueType() == NVT && Tmp2.getValueType() == NVT);
2953    Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1, Tmp2);
2954
2955    // Floating point operations will give excess precision that we may not be
2956    // able to tolerate.  If we DO allow excess precision, just leave it,
2957    // otherwise excise it.
2958    // FIXME: Why would we need to round FP ops more than integer ones?
2959    //     Is Round(Add(Add(A,B),C)) != Round(Add(Round(Add(A,B)), C))
2960    if (NoExcessFPPrecision)
2961      Result = DAG.getNode(ISD::FP_ROUND_INREG, NVT, Result,
2962                           DAG.getValueType(VT));
2963    break;
2964
2965  case ISD::SDIV:
2966  case ISD::SREM:
2967    // These operators require that their input be sign extended.
2968    Tmp1 = PromoteOp(Node->getOperand(0));
2969    Tmp2 = PromoteOp(Node->getOperand(1));
2970    if (MVT::isInteger(NVT)) {
2971      Tmp1 = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Tmp1,
2972                         DAG.getValueType(VT));
2973      Tmp2 = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Tmp2,
2974                         DAG.getValueType(VT));
2975    }
2976    Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1, Tmp2);
2977
2978    // Perform FP_ROUND: this is probably overly pessimistic.
2979    if (MVT::isFloatingPoint(NVT) && NoExcessFPPrecision)
2980      Result = DAG.getNode(ISD::FP_ROUND_INREG, NVT, Result,
2981                           DAG.getValueType(VT));
2982    break;
2983  case ISD::FDIV:
2984  case ISD::FREM:
2985  case ISD::FCOPYSIGN:
2986    // These operators require that their input be fp extended.
2987    Tmp1 = PromoteOp(Node->getOperand(0));
2988    Tmp2 = PromoteOp(Node->getOperand(1));
2989    Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1, Tmp2);
2990
2991    // Perform FP_ROUND: this is probably overly pessimistic.
2992    if (NoExcessFPPrecision && Node->getOpcode() != ISD::FCOPYSIGN)
2993      Result = DAG.getNode(ISD::FP_ROUND_INREG, NVT, Result,
2994                           DAG.getValueType(VT));
2995    break;
2996
2997  case ISD::UDIV:
2998  case ISD::UREM:
2999    // These operators require that their input be zero extended.
3000    Tmp1 = PromoteOp(Node->getOperand(0));
3001    Tmp2 = PromoteOp(Node->getOperand(1));
3002    assert(MVT::isInteger(NVT) && "Operators don't apply to FP!");
3003    Tmp1 = DAG.getZeroExtendInReg(Tmp1, VT);
3004    Tmp2 = DAG.getZeroExtendInReg(Tmp2, VT);
3005    Result = DAG.getNode(Node->getOpcode(), NVT, Tmp1, Tmp2);
3006    break;
3007
3008  case ISD::SHL:
3009    Tmp1 = PromoteOp(Node->getOperand(0));
3010    Result = DAG.getNode(ISD::SHL, NVT, Tmp1, Node->getOperand(1));
3011    break;
3012  case ISD::SRA:
3013    // The input value must be properly sign extended.
3014    Tmp1 = PromoteOp(Node->getOperand(0));
3015    Tmp1 = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Tmp1,
3016                       DAG.getValueType(VT));
3017    Result = DAG.getNode(ISD::SRA, NVT, Tmp1, Node->getOperand(1));
3018    break;
3019  case ISD::SRL:
3020    // The input value must be properly zero extended.
3021    Tmp1 = PromoteOp(Node->getOperand(0));
3022    Tmp1 = DAG.getZeroExtendInReg(Tmp1, VT);
3023    Result = DAG.getNode(ISD::SRL, NVT, Tmp1, Node->getOperand(1));
3024    break;
3025
3026  case ISD::VAARG:
3027    Tmp1 = Node->getOperand(0);   // Get the chain.
3028    Tmp2 = Node->getOperand(1);   // Get the pointer.
3029    if (TLI.getOperationAction(ISD::VAARG, VT) == TargetLowering::Custom) {
3030      Tmp3 = DAG.getVAArg(VT, Tmp1, Tmp2, Node->getOperand(2));
3031      Result = TLI.CustomPromoteOperation(Tmp3, DAG);
3032    } else {
3033      SDOperand VAList = DAG.getLoad(TLI.getPointerTy(), Tmp1, Tmp2,
3034                                     Node->getOperand(2));
3035      // Increment the pointer, VAList, to the next vaarg
3036      Tmp3 = DAG.getNode(ISD::ADD, TLI.getPointerTy(), VAList,
3037                         DAG.getConstant(MVT::getSizeInBits(VT)/8,
3038                                         TLI.getPointerTy()));
3039      // Store the incremented VAList to the legalized pointer
3040      Tmp3 = DAG.getNode(ISD::STORE, MVT::Other, VAList.getValue(1), Tmp3, Tmp2,
3041                         Node->getOperand(2));
3042      // Load the actual argument out of the pointer VAList
3043      Result = DAG.getExtLoad(ISD::EXTLOAD, NVT, Tmp3, VAList,
3044                              DAG.getSrcValue(0), VT);
3045    }
3046    // Remember that we legalized the chain.
3047    AddLegalizedOperand(Op.getValue(1), LegalizeOp(Result.getValue(1)));
3048    break;
3049
3050  case ISD::LOAD:
3051    Result = DAG.getExtLoad(ISD::EXTLOAD, NVT, Node->getOperand(0),
3052                            Node->getOperand(1), Node->getOperand(2), VT);
3053    // Remember that we legalized the chain.
3054    AddLegalizedOperand(Op.getValue(1), LegalizeOp(Result.getValue(1)));
3055    break;
3056  case ISD::SEXTLOAD:
3057  case ISD::ZEXTLOAD:
3058  case ISD::EXTLOAD:
3059    Result = DAG.getExtLoad(Node->getOpcode(), NVT, Node->getOperand(0),
3060                            Node->getOperand(1), Node->getOperand(2),
3061                            cast<VTSDNode>(Node->getOperand(3))->getVT());
3062    // Remember that we legalized the chain.
3063    AddLegalizedOperand(Op.getValue(1), LegalizeOp(Result.getValue(1)));
3064    break;
3065  case ISD::SELECT:
3066    Tmp2 = PromoteOp(Node->getOperand(1));   // Legalize the op0
3067    Tmp3 = PromoteOp(Node->getOperand(2));   // Legalize the op1
3068    Result = DAG.getNode(ISD::SELECT, NVT, Node->getOperand(0), Tmp2, Tmp3);
3069    break;
3070  case ISD::SELECT_CC:
3071    Tmp2 = PromoteOp(Node->getOperand(2));   // True
3072    Tmp3 = PromoteOp(Node->getOperand(3));   // False
3073    Result = DAG.getNode(ISD::SELECT_CC, NVT, Node->getOperand(0),
3074                         Node->getOperand(1), Tmp2, Tmp3, Node->getOperand(4));
3075    break;
3076  case ISD::BSWAP:
3077    Tmp1 = Node->getOperand(0);
3078    Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, NVT, Tmp1);
3079    Tmp1 = DAG.getNode(ISD::BSWAP, NVT, Tmp1);
3080    Result = DAG.getNode(ISD::SRL, NVT, Tmp1,
3081                         DAG.getConstant(getSizeInBits(NVT) - getSizeInBits(VT),
3082                                         TLI.getShiftAmountTy()));
3083    break;
3084  case ISD::CTPOP:
3085  case ISD::CTTZ:
3086  case ISD::CTLZ:
3087    // Zero extend the argument
3088    Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, NVT, Node->getOperand(0));
3089    // Perform the larger operation, then subtract if needed.
3090    Tmp1 = DAG.getNode(Node->getOpcode(), NVT, Tmp1);
3091    switch(Node->getOpcode()) {
3092    case ISD::CTPOP:
3093      Result = Tmp1;
3094      break;
3095    case ISD::CTTZ:
3096      // if Tmp1 == sizeinbits(NVT) then Tmp1 = sizeinbits(Old VT)
3097      Tmp2 = DAG.getSetCC(TLI.getSetCCResultTy(), Tmp1,
3098                          DAG.getConstant(getSizeInBits(NVT), NVT), ISD::SETEQ);
3099      Result = DAG.getNode(ISD::SELECT, NVT, Tmp2,
3100                           DAG.getConstant(getSizeInBits(VT), NVT), Tmp1);
3101      break;
3102    case ISD::CTLZ:
3103      //Tmp1 = Tmp1 - (sizeinbits(NVT) - sizeinbits(Old VT))
3104      Result = DAG.getNode(ISD::SUB, NVT, Tmp1,
3105                           DAG.getConstant(getSizeInBits(NVT) -
3106                                           getSizeInBits(VT), NVT));
3107      break;
3108    }
3109    break;
3110  case ISD::VEXTRACT_VECTOR_ELT:
3111    Result = PromoteOp(LowerVEXTRACT_VECTOR_ELT(Op));
3112    break;
3113  case ISD::EXTRACT_VECTOR_ELT:
3114    Result = PromoteOp(ExpandEXTRACT_VECTOR_ELT(Op));
3115    break;
3116  }
3117
3118  assert(Result.Val && "Didn't set a result!");
3119
3120  // Make sure the result is itself legal.
3121  Result = LegalizeOp(Result);
3122
3123  // Remember that we promoted this!
3124  AddPromotedOperand(Op, Result);
3125  return Result;
3126}
3127
3128/// LowerVEXTRACT_VECTOR_ELT - Lower a VEXTRACT_VECTOR_ELT operation into a
3129/// EXTRACT_VECTOR_ELT operation, to memory operations, or to scalar code based
3130/// on the vector type.  The return type of this matches the element type of the
3131/// vector, which may not be legal for the target.
3132SDOperand SelectionDAGLegalize::LowerVEXTRACT_VECTOR_ELT(SDOperand Op) {
3133  // We know that operand #0 is the Vec vector.  If the index is a constant
3134  // or if the invec is a supported hardware type, we can use it.  Otherwise,
3135  // lower to a store then an indexed load.
3136  SDOperand Vec = Op.getOperand(0);
3137  SDOperand Idx = LegalizeOp(Op.getOperand(1));
3138
3139  SDNode *InVal = Vec.Val;
3140  unsigned NumElems = cast<ConstantSDNode>(*(InVal->op_end()-2))->getValue();
3141  MVT::ValueType EVT = cast<VTSDNode>(*(InVal->op_end()-1))->getVT();
3142
3143  // Figure out if there is a Packed type corresponding to this Vector
3144  // type.  If so, convert to the packed type.
3145  MVT::ValueType TVT = MVT::getVectorType(EVT, NumElems);
3146  if (TVT != MVT::Other && TLI.isTypeLegal(TVT)) {
3147    // Turn this into a packed extract_vector_elt operation.
3148    Vec = PackVectorOp(Vec, TVT);
3149    return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, Op.getValueType(), Vec, Idx);
3150  } else if (NumElems == 1) {
3151    // This must be an access of the only element.  Return it.
3152    return PackVectorOp(Vec, EVT);
3153  } else if (ConstantSDNode *CIdx = dyn_cast<ConstantSDNode>(Idx)) {
3154    SDOperand Lo, Hi;
3155    SplitVectorOp(Vec, Lo, Hi);
3156    if (CIdx->getValue() < NumElems/2) {
3157      Vec = Lo;
3158    } else {
3159      Vec = Hi;
3160      Idx = DAG.getConstant(CIdx->getValue() - NumElems/2, Idx.getValueType());
3161    }
3162
3163    // It's now an extract from the appropriate high or low part.  Recurse.
3164    Op = DAG.UpdateNodeOperands(Op, Vec, Idx);
3165    return LowerVEXTRACT_VECTOR_ELT(Op);
3166  } else {
3167    // Variable index case for extract element.
3168    // FIXME: IMPLEMENT STORE/LOAD lowering.  Need alignment of stack slot!!
3169    assert(0 && "unimp!");
3170    return SDOperand();
3171  }
3172}
3173
3174/// ExpandEXTRACT_VECTOR_ELT - Expand an EXTRACT_VECTOR_ELT operation into
3175/// memory traffic.
3176SDOperand SelectionDAGLegalize::ExpandEXTRACT_VECTOR_ELT(SDOperand Op) {
3177  SDOperand Vector = Op.getOperand(0);
3178  SDOperand Idx    = Op.getOperand(1);
3179
3180  // If the target doesn't support this, store the value to a temporary
3181  // stack slot, then LOAD the scalar element back out.
3182  SDOperand StackPtr = CreateStackTemporary(Vector.getValueType());
3183  SDOperand Ch = DAG.getNode(ISD::STORE, MVT::Other, DAG.getEntryNode(),
3184                             Vector, StackPtr, DAG.getSrcValue(NULL));
3185
3186  // Add the offset to the index.
3187  unsigned EltSize = MVT::getSizeInBits(Op.getValueType())/8;
3188  Idx = DAG.getNode(ISD::MUL, Idx.getValueType(), Idx,
3189                    DAG.getConstant(EltSize, Idx.getValueType()));
3190  StackPtr = DAG.getNode(ISD::ADD, Idx.getValueType(), Idx, StackPtr);
3191
3192  return DAG.getLoad(Op.getValueType(), Ch, StackPtr, DAG.getSrcValue(NULL));
3193}
3194
3195
3196/// LegalizeSetCCOperands - Attempts to create a legal LHS and RHS for a SETCC
3197/// with condition CC on the current target.  This usually involves legalizing
3198/// or promoting the arguments.  In the case where LHS and RHS must be expanded,
3199/// there may be no choice but to create a new SetCC node to represent the
3200/// legalized value of setcc lhs, rhs.  In this case, the value is returned in
3201/// LHS, and the SDOperand returned in RHS has a nil SDNode value.
3202void SelectionDAGLegalize::LegalizeSetCCOperands(SDOperand &LHS,
3203                                                 SDOperand &RHS,
3204                                                 SDOperand &CC) {
3205  SDOperand Tmp1, Tmp2, Result;
3206
3207  switch (getTypeAction(LHS.getValueType())) {
3208  case Legal:
3209    Tmp1 = LegalizeOp(LHS);   // LHS
3210    Tmp2 = LegalizeOp(RHS);   // RHS
3211    break;
3212  case Promote:
3213    Tmp1 = PromoteOp(LHS);   // LHS
3214    Tmp2 = PromoteOp(RHS);   // RHS
3215
3216    // If this is an FP compare, the operands have already been extended.
3217    if (MVT::isInteger(LHS.getValueType())) {
3218      MVT::ValueType VT = LHS.getValueType();
3219      MVT::ValueType NVT = TLI.getTypeToTransformTo(VT);
3220
3221      // Otherwise, we have to insert explicit sign or zero extends.  Note
3222      // that we could insert sign extends for ALL conditions, but zero extend
3223      // is cheaper on many machines (an AND instead of two shifts), so prefer
3224      // it.
3225      switch (cast<CondCodeSDNode>(CC)->get()) {
3226      default: assert(0 && "Unknown integer comparison!");
3227      case ISD::SETEQ:
3228      case ISD::SETNE:
3229      case ISD::SETUGE:
3230      case ISD::SETUGT:
3231      case ISD::SETULE:
3232      case ISD::SETULT:
3233        // ALL of these operations will work if we either sign or zero extend
3234        // the operands (including the unsigned comparisons!).  Zero extend is
3235        // usually a simpler/cheaper operation, so prefer it.
3236        Tmp1 = DAG.getZeroExtendInReg(Tmp1, VT);
3237        Tmp2 = DAG.getZeroExtendInReg(Tmp2, VT);
3238        break;
3239      case ISD::SETGE:
3240      case ISD::SETGT:
3241      case ISD::SETLT:
3242      case ISD::SETLE:
3243        Tmp1 = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Tmp1,
3244                           DAG.getValueType(VT));
3245        Tmp2 = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Tmp2,
3246                           DAG.getValueType(VT));
3247        break;
3248      }
3249    }
3250    break;
3251  case Expand:
3252    SDOperand LHSLo, LHSHi, RHSLo, RHSHi;
3253    ExpandOp(LHS, LHSLo, LHSHi);
3254    ExpandOp(RHS, RHSLo, RHSHi);
3255    switch (cast<CondCodeSDNode>(CC)->get()) {
3256    case ISD::SETEQ:
3257    case ISD::SETNE:
3258      if (RHSLo == RHSHi)
3259        if (ConstantSDNode *RHSCST = dyn_cast<ConstantSDNode>(RHSLo))
3260          if (RHSCST->isAllOnesValue()) {
3261            // Comparison to -1.
3262            Tmp1 = DAG.getNode(ISD::AND, LHSLo.getValueType(), LHSLo, LHSHi);
3263            Tmp2 = RHSLo;
3264            break;
3265          }
3266
3267      Tmp1 = DAG.getNode(ISD::XOR, LHSLo.getValueType(), LHSLo, RHSLo);
3268      Tmp2 = DAG.getNode(ISD::XOR, LHSLo.getValueType(), LHSHi, RHSHi);
3269      Tmp1 = DAG.getNode(ISD::OR, Tmp1.getValueType(), Tmp1, Tmp2);
3270      Tmp2 = DAG.getConstant(0, Tmp1.getValueType());
3271      break;
3272    default:
3273      // If this is a comparison of the sign bit, just look at the top part.
3274      // X > -1,  x < 0
3275      if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(RHS))
3276        if ((cast<CondCodeSDNode>(CC)->get() == ISD::SETLT &&
3277             CST->getValue() == 0) ||             // X < 0
3278            (cast<CondCodeSDNode>(CC)->get() == ISD::SETGT &&
3279             CST->isAllOnesValue())) {            // X > -1
3280          Tmp1 = LHSHi;
3281          Tmp2 = RHSHi;
3282          break;
3283        }
3284
3285      // FIXME: This generated code sucks.
3286      ISD::CondCode LowCC;
3287      switch (cast<CondCodeSDNode>(CC)->get()) {
3288      default: assert(0 && "Unknown integer setcc!");
3289      case ISD::SETLT:
3290      case ISD::SETULT: LowCC = ISD::SETULT; break;
3291      case ISD::SETGT:
3292      case ISD::SETUGT: LowCC = ISD::SETUGT; break;
3293      case ISD::SETLE:
3294      case ISD::SETULE: LowCC = ISD::SETULE; break;
3295      case ISD::SETGE:
3296      case ISD::SETUGE: LowCC = ISD::SETUGE; break;
3297      }
3298
3299      // Tmp1 = lo(op1) < lo(op2)   // Always unsigned comparison
3300      // Tmp2 = hi(op1) < hi(op2)   // Signedness depends on operands
3301      // dest = hi(op1) == hi(op2) ? Tmp1 : Tmp2;
3302
3303      // NOTE: on targets without efficient SELECT of bools, we can always use
3304      // this identity: (B1 ? B2 : B3) --> (B1 & B2)|(!B1&B3)
3305      Tmp1 = DAG.getSetCC(TLI.getSetCCResultTy(), LHSLo, RHSLo, LowCC);
3306      Tmp2 = DAG.getNode(ISD::SETCC, TLI.getSetCCResultTy(), LHSHi, RHSHi, CC);
3307      Result = DAG.getSetCC(TLI.getSetCCResultTy(), LHSHi, RHSHi, ISD::SETEQ);
3308      Result = LegalizeOp(DAG.getNode(ISD::SELECT, Tmp1.getValueType(),
3309                                      Result, Tmp1, Tmp2));
3310      Tmp1 = Result;
3311      Tmp2 = SDOperand();
3312    }
3313  }
3314  LHS = Tmp1;
3315  RHS = Tmp2;
3316}
3317
3318/// ExpandBIT_CONVERT - Expand a BIT_CONVERT node into a store/load combination.
3319/// The resultant code need not be legal.  Note that SrcOp is the input operand
3320/// to the BIT_CONVERT, not the BIT_CONVERT node itself.
3321SDOperand SelectionDAGLegalize::ExpandBIT_CONVERT(MVT::ValueType DestVT,
3322                                                  SDOperand SrcOp) {
3323  // Create the stack frame object.
3324  SDOperand FIPtr = CreateStackTemporary(DestVT);
3325
3326  // Emit a store to the stack slot.
3327  SDOperand Store = DAG.getNode(ISD::STORE, MVT::Other, DAG.getEntryNode(),
3328                                SrcOp, FIPtr, DAG.getSrcValue(NULL));
3329  // Result is a load from the stack slot.
3330  return DAG.getLoad(DestVT, Store, FIPtr, DAG.getSrcValue(0));
3331}
3332
3333SDOperand SelectionDAGLegalize::ExpandSCALAR_TO_VECTOR(SDNode *Node) {
3334  // Create a vector sized/aligned stack slot, store the value to element #0,
3335  // then load the whole vector back out.
3336  SDOperand StackPtr = CreateStackTemporary(Node->getValueType(0));
3337  SDOperand Ch = DAG.getNode(ISD::STORE, MVT::Other, DAG.getEntryNode(),
3338                             Node->getOperand(0), StackPtr,
3339                             DAG.getSrcValue(NULL));
3340  return DAG.getLoad(Node->getValueType(0), Ch, StackPtr,DAG.getSrcValue(NULL));
3341}
3342
3343
3344/// ExpandBUILD_VECTOR - Expand a BUILD_VECTOR node on targets that don't
3345/// support the operation, but do support the resultant packed vector type.
3346SDOperand SelectionDAGLegalize::ExpandBUILD_VECTOR(SDNode *Node) {
3347
3348  // If the only non-undef value is the low element, turn this into a
3349  // SCALAR_TO_VECTOR node.  If this is { X, X, X, X }, determine X.
3350  unsigned NumElems = Node->getNumOperands();
3351  bool isOnlyLowElement = true;
3352  SDOperand SplatValue = Node->getOperand(0);
3353  std::map<SDOperand, std::vector<unsigned> > Values;
3354  Values[SplatValue].push_back(0);
3355  bool isConstant = true;
3356  if (!isa<ConstantFPSDNode>(SplatValue) && !isa<ConstantSDNode>(SplatValue) &&
3357      SplatValue.getOpcode() != ISD::UNDEF)
3358    isConstant = false;
3359
3360  for (unsigned i = 1; i < NumElems; ++i) {
3361    SDOperand V = Node->getOperand(i);
3362    std::map<SDOperand, std::vector<unsigned> >::iterator I = Values.find(V);
3363    if (I != Values.end())
3364      I->second.push_back(i);
3365    else
3366      Values[V].push_back(i);
3367    if (V.getOpcode() != ISD::UNDEF)
3368      isOnlyLowElement = false;
3369    if (SplatValue != V)
3370      SplatValue = SDOperand(0,0);
3371
3372    // If this isn't a constant element or an undef, we can't use a constant
3373    // pool load.
3374    if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V) &&
3375        V.getOpcode() != ISD::UNDEF)
3376      isConstant = false;
3377  }
3378
3379  if (isOnlyLowElement) {
3380    // If the low element is an undef too, then this whole things is an undef.
3381    if (Node->getOperand(0).getOpcode() == ISD::UNDEF)
3382      return DAG.getNode(ISD::UNDEF, Node->getValueType(0));
3383    // Otherwise, turn this into a scalar_to_vector node.
3384    return DAG.getNode(ISD::SCALAR_TO_VECTOR, Node->getValueType(0),
3385                       Node->getOperand(0));
3386  }
3387
3388  // If all elements are constants, create a load from the constant pool.
3389  if (isConstant) {
3390    MVT::ValueType VT = Node->getValueType(0);
3391    const Type *OpNTy =
3392      MVT::getTypeForValueType(Node->getOperand(0).getValueType());
3393    std::vector<Constant*> CV;
3394    for (unsigned i = 0, e = NumElems; i != e; ++i) {
3395      if (ConstantFPSDNode *V =
3396          dyn_cast<ConstantFPSDNode>(Node->getOperand(i))) {
3397        CV.push_back(ConstantFP::get(OpNTy, V->getValue()));
3398      } else if (ConstantSDNode *V =
3399                 dyn_cast<ConstantSDNode>(Node->getOperand(i))) {
3400        CV.push_back(ConstantUInt::get(OpNTy, V->getValue()));
3401      } else {
3402        assert(Node->getOperand(i).getOpcode() == ISD::UNDEF);
3403        CV.push_back(UndefValue::get(OpNTy));
3404      }
3405    }
3406    Constant *CP = ConstantPacked::get(CV);
3407    SDOperand CPIdx = DAG.getConstantPool(CP, TLI.getPointerTy());
3408    return DAG.getLoad(VT, DAG.getEntryNode(), CPIdx,
3409                       DAG.getSrcValue(NULL));
3410  }
3411
3412  if (SplatValue.Val) {   // Splat of one value?
3413    // Build the shuffle constant vector: <0, 0, 0, 0>
3414    MVT::ValueType MaskVT =
3415      MVT::getIntVectorWithNumElements(NumElems);
3416    SDOperand Zero = DAG.getConstant(0, MVT::getVectorBaseType(MaskVT));
3417    std::vector<SDOperand> ZeroVec(NumElems, Zero);
3418    SDOperand SplatMask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, ZeroVec);
3419
3420    // If the target supports VECTOR_SHUFFLE and this shuffle mask, use it.
3421    if (isShuffleLegal(Node->getValueType(0), SplatMask)) {
3422      // Get the splatted value into the low element of a vector register.
3423      SDOperand LowValVec =
3424        DAG.getNode(ISD::SCALAR_TO_VECTOR, Node->getValueType(0), SplatValue);
3425
3426      // Return shuffle(LowValVec, undef, <0,0,0,0>)
3427      return DAG.getNode(ISD::VECTOR_SHUFFLE, Node->getValueType(0), LowValVec,
3428                         DAG.getNode(ISD::UNDEF, Node->getValueType(0)),
3429                         SplatMask);
3430    }
3431  }
3432
3433  // If there are only two unique elements, we may be able to turn this into a
3434  // vector shuffle.
3435  if (Values.size() == 2) {
3436    // Build the shuffle constant vector: e.g. <0, 4, 0, 4>
3437    MVT::ValueType MaskVT =
3438      MVT::getIntVectorWithNumElements(NumElems);
3439    std::vector<SDOperand> MaskVec(NumElems);
3440    unsigned i = 0;
3441    for (std::map<SDOperand,std::vector<unsigned> >::iterator I=Values.begin(),
3442           E = Values.end(); I != E; ++I) {
3443      for (std::vector<unsigned>::iterator II = I->second.begin(),
3444             EE = I->second.end(); II != EE; ++II)
3445        MaskVec[*II] = DAG.getConstant(i, MVT::getVectorBaseType(MaskVT));
3446      i += NumElems;
3447    }
3448    SDOperand ShuffleMask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, MaskVec);
3449
3450    // If the target supports VECTOR_SHUFFLE and this shuffle mask, use it.
3451    if (TLI.isOperationLegal(ISD::SCALAR_TO_VECTOR, Node->getValueType(0)) &&
3452        isShuffleLegal(Node->getValueType(0), ShuffleMask)) {
3453      std::vector<SDOperand> Ops;
3454      for(std::map<SDOperand,std::vector<unsigned> >::iterator I=Values.begin(),
3455            E = Values.end(); I != E; ++I) {
3456        SDOperand Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, Node->getValueType(0),
3457                                   I->first);
3458        Ops.push_back(Op);
3459      }
3460      Ops.push_back(ShuffleMask);
3461
3462      // Return shuffle(LoValVec, HiValVec, <0,1,0,1>)
3463      return DAG.getNode(ISD::VECTOR_SHUFFLE, Node->getValueType(0), Ops);
3464    }
3465  }
3466
3467  // Otherwise, we can't handle this case efficiently.  Allocate a sufficiently
3468  // aligned object on the stack, store each element into it, then load
3469  // the result as a vector.
3470  MVT::ValueType VT = Node->getValueType(0);
3471  // Create the stack frame object.
3472  SDOperand FIPtr = CreateStackTemporary(VT);
3473
3474  // Emit a store of each element to the stack slot.
3475  std::vector<SDOperand> Stores;
3476  unsigned TypeByteSize =
3477    MVT::getSizeInBits(Node->getOperand(0).getValueType())/8;
3478  unsigned VectorSize = MVT::getSizeInBits(VT)/8;
3479  // Store (in the right endianness) the elements to memory.
3480  for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) {
3481    // Ignore undef elements.
3482    if (Node->getOperand(i).getOpcode() == ISD::UNDEF) continue;
3483
3484    unsigned Offset = TypeByteSize*i;
3485
3486    SDOperand Idx = DAG.getConstant(Offset, FIPtr.getValueType());
3487    Idx = DAG.getNode(ISD::ADD, FIPtr.getValueType(), FIPtr, Idx);
3488
3489    Stores.push_back(DAG.getNode(ISD::STORE, MVT::Other, DAG.getEntryNode(),
3490                                 Node->getOperand(i), Idx,
3491                                 DAG.getSrcValue(NULL)));
3492  }
3493
3494  SDOperand StoreChain;
3495  if (!Stores.empty())    // Not all undef elements?
3496    StoreChain = DAG.getNode(ISD::TokenFactor, MVT::Other, Stores);
3497  else
3498    StoreChain = DAG.getEntryNode();
3499
3500  // Result is a load from the stack slot.
3501  return DAG.getLoad(VT, StoreChain, FIPtr, DAG.getSrcValue(0));
3502}
3503
3504/// CreateStackTemporary - Create a stack temporary, suitable for holding the
3505/// specified value type.
3506SDOperand SelectionDAGLegalize::CreateStackTemporary(MVT::ValueType VT) {
3507  MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
3508  unsigned ByteSize = MVT::getSizeInBits(VT)/8;
3509  int FrameIdx = FrameInfo->CreateStackObject(ByteSize, ByteSize);
3510  return DAG.getFrameIndex(FrameIdx, TLI.getPointerTy());
3511}
3512
3513void SelectionDAGLegalize::ExpandShiftParts(unsigned NodeOp,
3514                                            SDOperand Op, SDOperand Amt,
3515                                            SDOperand &Lo, SDOperand &Hi) {
3516  // Expand the subcomponents.
3517  SDOperand LHSL, LHSH;
3518  ExpandOp(Op, LHSL, LHSH);
3519
3520  std::vector<SDOperand> Ops;
3521  Ops.push_back(LHSL);
3522  Ops.push_back(LHSH);
3523  Ops.push_back(Amt);
3524  std::vector<MVT::ValueType> VTs(2, LHSL.getValueType());
3525  Lo = DAG.getNode(NodeOp, VTs, Ops);
3526  Hi = Lo.getValue(1);
3527}
3528
3529
3530/// ExpandShift - Try to find a clever way to expand this shift operation out to
3531/// smaller elements.  If we can't find a way that is more efficient than a
3532/// libcall on this target, return false.  Otherwise, return true with the
3533/// low-parts expanded into Lo and Hi.
3534bool SelectionDAGLegalize::ExpandShift(unsigned Opc, SDOperand Op,SDOperand Amt,
3535                                       SDOperand &Lo, SDOperand &Hi) {
3536  assert((Opc == ISD::SHL || Opc == ISD::SRA || Opc == ISD::SRL) &&
3537         "This is not a shift!");
3538
3539  MVT::ValueType NVT = TLI.getTypeToTransformTo(Op.getValueType());
3540  SDOperand ShAmt = LegalizeOp(Amt);
3541  MVT::ValueType ShTy = ShAmt.getValueType();
3542  unsigned VTBits = MVT::getSizeInBits(Op.getValueType());
3543  unsigned NVTBits = MVT::getSizeInBits(NVT);
3544
3545  // Handle the case when Amt is an immediate.  Other cases are currently broken
3546  // and are disabled.
3547  if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Amt.Val)) {
3548    unsigned Cst = CN->getValue();
3549    // Expand the incoming operand to be shifted, so that we have its parts
3550    SDOperand InL, InH;
3551    ExpandOp(Op, InL, InH);
3552    switch(Opc) {
3553    case ISD::SHL:
3554      if (Cst > VTBits) {
3555        Lo = DAG.getConstant(0, NVT);
3556        Hi = DAG.getConstant(0, NVT);
3557      } else if (Cst > NVTBits) {
3558        Lo = DAG.getConstant(0, NVT);
3559        Hi = DAG.getNode(ISD::SHL, NVT, InL, DAG.getConstant(Cst-NVTBits,ShTy));
3560      } else if (Cst == NVTBits) {
3561        Lo = DAG.getConstant(0, NVT);
3562        Hi = InL;
3563      } else {
3564        Lo = DAG.getNode(ISD::SHL, NVT, InL, DAG.getConstant(Cst, ShTy));
3565        Hi = DAG.getNode(ISD::OR, NVT,
3566           DAG.getNode(ISD::SHL, NVT, InH, DAG.getConstant(Cst, ShTy)),
3567           DAG.getNode(ISD::SRL, NVT, InL, DAG.getConstant(NVTBits-Cst, ShTy)));
3568      }
3569      return true;
3570    case ISD::SRL:
3571      if (Cst > VTBits) {
3572        Lo = DAG.getConstant(0, NVT);
3573        Hi = DAG.getConstant(0, NVT);
3574      } else if (Cst > NVTBits) {
3575        Lo = DAG.getNode(ISD::SRL, NVT, InH, DAG.getConstant(Cst-NVTBits,ShTy));
3576        Hi = DAG.getConstant(0, NVT);
3577      } else if (Cst == NVTBits) {
3578        Lo = InH;
3579        Hi = DAG.getConstant(0, NVT);
3580      } else {
3581        Lo = DAG.getNode(ISD::OR, NVT,
3582           DAG.getNode(ISD::SRL, NVT, InL, DAG.getConstant(Cst, ShTy)),
3583           DAG.getNode(ISD::SHL, NVT, InH, DAG.getConstant(NVTBits-Cst, ShTy)));
3584        Hi = DAG.getNode(ISD::SRL, NVT, InH, DAG.getConstant(Cst, ShTy));
3585      }
3586      return true;
3587    case ISD::SRA:
3588      if (Cst > VTBits) {
3589        Hi = Lo = DAG.getNode(ISD::SRA, NVT, InH,
3590                              DAG.getConstant(NVTBits-1, ShTy));
3591      } else if (Cst > NVTBits) {
3592        Lo = DAG.getNode(ISD::SRA, NVT, InH,
3593                           DAG.getConstant(Cst-NVTBits, ShTy));
3594        Hi = DAG.getNode(ISD::SRA, NVT, InH,
3595                              DAG.getConstant(NVTBits-1, ShTy));
3596      } else if (Cst == NVTBits) {
3597        Lo = InH;
3598        Hi = DAG.getNode(ISD::SRA, NVT, InH,
3599                              DAG.getConstant(NVTBits-1, ShTy));
3600      } else {
3601        Lo = DAG.getNode(ISD::OR, NVT,
3602           DAG.getNode(ISD::SRL, NVT, InL, DAG.getConstant(Cst, ShTy)),
3603           DAG.getNode(ISD::SHL, NVT, InH, DAG.getConstant(NVTBits-Cst, ShTy)));
3604        Hi = DAG.getNode(ISD::SRA, NVT, InH, DAG.getConstant(Cst, ShTy));
3605      }
3606      return true;
3607    }
3608  }
3609  return false;
3610}
3611
3612
3613// ExpandLibCall - Expand a node into a call to a libcall.  If the result value
3614// does not fit into a register, return the lo part and set the hi part to the
3615// by-reg argument.  If it does fit into a single register, return the result
3616// and leave the Hi part unset.
3617SDOperand SelectionDAGLegalize::ExpandLibCall(const char *Name, SDNode *Node,
3618                                              SDOperand &Hi) {
3619  assert(!IsLegalizingCall && "Cannot overlap legalization of calls!");
3620  // The input chain to this libcall is the entry node of the function.
3621  // Legalizing the call will automatically add the previous call to the
3622  // dependence.
3623  SDOperand InChain = DAG.getEntryNode();
3624
3625  TargetLowering::ArgListTy Args;
3626  for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) {
3627    MVT::ValueType ArgVT = Node->getOperand(i).getValueType();
3628    const Type *ArgTy = MVT::getTypeForValueType(ArgVT);
3629    Args.push_back(std::make_pair(Node->getOperand(i), ArgTy));
3630  }
3631  SDOperand Callee = DAG.getExternalSymbol(Name, TLI.getPointerTy());
3632
3633  // Splice the libcall in wherever FindInputOutputChains tells us to.
3634  const Type *RetTy = MVT::getTypeForValueType(Node->getValueType(0));
3635  std::pair<SDOperand,SDOperand> CallInfo =
3636    TLI.LowerCallTo(InChain, RetTy, false, CallingConv::C, false,
3637                    Callee, Args, DAG);
3638
3639  // Legalize the call sequence, starting with the chain.  This will advance
3640  // the LastCALLSEQ_END to the legalized version of the CALLSEQ_END node that
3641  // was added by LowerCallTo (guaranteeing proper serialization of calls).
3642  LegalizeOp(CallInfo.second);
3643  SDOperand Result;
3644  switch (getTypeAction(CallInfo.first.getValueType())) {
3645  default: assert(0 && "Unknown thing");
3646  case Legal:
3647    Result = CallInfo.first;
3648    break;
3649  case Expand:
3650    ExpandOp(CallInfo.first, Result, Hi);
3651    break;
3652  }
3653  return Result;
3654}
3655
3656
3657/// ExpandIntToFP - Expand a [US]INT_TO_FP operation, assuming that the
3658/// destination type is legal.
3659SDOperand SelectionDAGLegalize::
3660ExpandIntToFP(bool isSigned, MVT::ValueType DestTy, SDOperand Source) {
3661  assert(isTypeLegal(DestTy) && "Destination type is not legal!");
3662  assert(getTypeAction(Source.getValueType()) == Expand &&
3663         "This is not an expansion!");
3664  assert(Source.getValueType() == MVT::i64 && "Only handle expand from i64!");
3665
3666  if (!isSigned) {
3667    assert(Source.getValueType() == MVT::i64 &&
3668           "This only works for 64-bit -> FP");
3669    // The 64-bit value loaded will be incorrectly if the 'sign bit' of the
3670    // incoming integer is set.  To handle this, we dynamically test to see if
3671    // it is set, and, if so, add a fudge factor.
3672    SDOperand Lo, Hi;
3673    ExpandOp(Source, Lo, Hi);
3674
3675    // If this is unsigned, and not supported, first perform the conversion to
3676    // signed, then adjust the result if the sign bit is set.
3677    SDOperand SignedConv = ExpandIntToFP(true, DestTy,
3678                   DAG.getNode(ISD::BUILD_PAIR, Source.getValueType(), Lo, Hi));
3679
3680    SDOperand SignSet = DAG.getSetCC(TLI.getSetCCResultTy(), Hi,
3681                                     DAG.getConstant(0, Hi.getValueType()),
3682                                     ISD::SETLT);
3683    SDOperand Zero = getIntPtrConstant(0), Four = getIntPtrConstant(4);
3684    SDOperand CstOffset = DAG.getNode(ISD::SELECT, Zero.getValueType(),
3685                                      SignSet, Four, Zero);
3686    uint64_t FF = 0x5f800000ULL;
3687    if (TLI.isLittleEndian()) FF <<= 32;
3688    static Constant *FudgeFactor = ConstantUInt::get(Type::ULongTy, FF);
3689
3690    SDOperand CPIdx = DAG.getConstantPool(FudgeFactor, TLI.getPointerTy());
3691    CPIdx = DAG.getNode(ISD::ADD, TLI.getPointerTy(), CPIdx, CstOffset);
3692    SDOperand FudgeInReg;
3693    if (DestTy == MVT::f32)
3694      FudgeInReg = DAG.getLoad(MVT::f32, DAG.getEntryNode(), CPIdx,
3695                               DAG.getSrcValue(NULL));
3696    else {
3697      assert(DestTy == MVT::f64 && "Unexpected conversion");
3698      FudgeInReg = DAG.getExtLoad(ISD::EXTLOAD, MVT::f64, DAG.getEntryNode(),
3699                                  CPIdx, DAG.getSrcValue(NULL), MVT::f32);
3700    }
3701    return DAG.getNode(ISD::FADD, DestTy, SignedConv, FudgeInReg);
3702  }
3703
3704  // Check to see if the target has a custom way to lower this.  If so, use it.
3705  switch (TLI.getOperationAction(ISD::SINT_TO_FP, Source.getValueType())) {
3706  default: assert(0 && "This action not implemented for this operation!");
3707  case TargetLowering::Legal:
3708  case TargetLowering::Expand:
3709    break;   // This case is handled below.
3710  case TargetLowering::Custom: {
3711    SDOperand NV = TLI.LowerOperation(DAG.getNode(ISD::SINT_TO_FP, DestTy,
3712                                                  Source), DAG);
3713    if (NV.Val)
3714      return LegalizeOp(NV);
3715    break;   // The target decided this was legal after all
3716  }
3717  }
3718
3719  // Expand the source, then glue it back together for the call.  We must expand
3720  // the source in case it is shared (this pass of legalize must traverse it).
3721  SDOperand SrcLo, SrcHi;
3722  ExpandOp(Source, SrcLo, SrcHi);
3723  Source = DAG.getNode(ISD::BUILD_PAIR, Source.getValueType(), SrcLo, SrcHi);
3724
3725  const char *FnName = 0;
3726  if (DestTy == MVT::f32)
3727    FnName = "__floatdisf";
3728  else {
3729    assert(DestTy == MVT::f64 && "Unknown fp value type!");
3730    FnName = "__floatdidf";
3731  }
3732
3733  Source = DAG.getNode(ISD::SINT_TO_FP, DestTy, Source);
3734  SDOperand UnusedHiPart;
3735  return ExpandLibCall(FnName, Source.Val, UnusedHiPart);
3736}
3737
3738/// ExpandLegalINT_TO_FP - This function is responsible for legalizing a
3739/// INT_TO_FP operation of the specified operand when the target requests that
3740/// we expand it.  At this point, we know that the result and operand types are
3741/// legal for the target.
3742SDOperand SelectionDAGLegalize::ExpandLegalINT_TO_FP(bool isSigned,
3743                                                     SDOperand Op0,
3744                                                     MVT::ValueType DestVT) {
3745  if (Op0.getValueType() == MVT::i32) {
3746    // simple 32-bit [signed|unsigned] integer to float/double expansion
3747
3748    // get the stack frame index of a 8 byte buffer
3749    MachineFunction &MF = DAG.getMachineFunction();
3750    int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8);
3751    // get address of 8 byte buffer
3752    SDOperand StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
3753    // word offset constant for Hi/Lo address computation
3754    SDOperand WordOff = DAG.getConstant(sizeof(int), TLI.getPointerTy());
3755    // set up Hi and Lo (into buffer) address based on endian
3756    SDOperand Hi = StackSlot;
3757    SDOperand Lo = DAG.getNode(ISD::ADD, TLI.getPointerTy(), StackSlot,WordOff);
3758    if (TLI.isLittleEndian())
3759      std::swap(Hi, Lo);
3760
3761    // if signed map to unsigned space
3762    SDOperand Op0Mapped;
3763    if (isSigned) {
3764      // constant used to invert sign bit (signed to unsigned mapping)
3765      SDOperand SignBit = DAG.getConstant(0x80000000u, MVT::i32);
3766      Op0Mapped = DAG.getNode(ISD::XOR, MVT::i32, Op0, SignBit);
3767    } else {
3768      Op0Mapped = Op0;
3769    }
3770    // store the lo of the constructed double - based on integer input
3771    SDOperand Store1 = DAG.getNode(ISD::STORE, MVT::Other, DAG.getEntryNode(),
3772                                   Op0Mapped, Lo, DAG.getSrcValue(NULL));
3773    // initial hi portion of constructed double
3774    SDOperand InitialHi = DAG.getConstant(0x43300000u, MVT::i32);
3775    // store the hi of the constructed double - biased exponent
3776    SDOperand Store2 = DAG.getNode(ISD::STORE, MVT::Other, Store1,
3777                                   InitialHi, Hi, DAG.getSrcValue(NULL));
3778    // load the constructed double
3779    SDOperand Load = DAG.getLoad(MVT::f64, Store2, StackSlot,
3780                               DAG.getSrcValue(NULL));
3781    // FP constant to bias correct the final result
3782    SDOperand Bias = DAG.getConstantFP(isSigned ?
3783                                            BitsToDouble(0x4330000080000000ULL)
3784                                          : BitsToDouble(0x4330000000000000ULL),
3785                                     MVT::f64);
3786    // subtract the bias
3787    SDOperand Sub = DAG.getNode(ISD::FSUB, MVT::f64, Load, Bias);
3788    // final result
3789    SDOperand Result;
3790    // handle final rounding
3791    if (DestVT == MVT::f64) {
3792      // do nothing
3793      Result = Sub;
3794    } else {
3795     // if f32 then cast to f32
3796      Result = DAG.getNode(ISD::FP_ROUND, MVT::f32, Sub);
3797    }
3798    return Result;
3799  }
3800  assert(!isSigned && "Legalize cannot Expand SINT_TO_FP for i64 yet");
3801  SDOperand Tmp1 = DAG.getNode(ISD::SINT_TO_FP, DestVT, Op0);
3802
3803  SDOperand SignSet = DAG.getSetCC(TLI.getSetCCResultTy(), Op0,
3804                                   DAG.getConstant(0, Op0.getValueType()),
3805                                   ISD::SETLT);
3806  SDOperand Zero = getIntPtrConstant(0), Four = getIntPtrConstant(4);
3807  SDOperand CstOffset = DAG.getNode(ISD::SELECT, Zero.getValueType(),
3808                                    SignSet, Four, Zero);
3809
3810  // If the sign bit of the integer is set, the large number will be treated
3811  // as a negative number.  To counteract this, the dynamic code adds an
3812  // offset depending on the data type.
3813  uint64_t FF;
3814  switch (Op0.getValueType()) {
3815  default: assert(0 && "Unsupported integer type!");
3816  case MVT::i8 : FF = 0x43800000ULL; break;  // 2^8  (as a float)
3817  case MVT::i16: FF = 0x47800000ULL; break;  // 2^16 (as a float)
3818  case MVT::i32: FF = 0x4F800000ULL; break;  // 2^32 (as a float)
3819  case MVT::i64: FF = 0x5F800000ULL; break;  // 2^64 (as a float)
3820  }
3821  if (TLI.isLittleEndian()) FF <<= 32;
3822  static Constant *FudgeFactor = ConstantUInt::get(Type::ULongTy, FF);
3823
3824  SDOperand CPIdx = DAG.getConstantPool(FudgeFactor, TLI.getPointerTy());
3825  CPIdx = DAG.getNode(ISD::ADD, TLI.getPointerTy(), CPIdx, CstOffset);
3826  SDOperand FudgeInReg;
3827  if (DestVT == MVT::f32)
3828    FudgeInReg = DAG.getLoad(MVT::f32, DAG.getEntryNode(), CPIdx,
3829                             DAG.getSrcValue(NULL));
3830  else {
3831    assert(DestVT == MVT::f64 && "Unexpected conversion");
3832    FudgeInReg = LegalizeOp(DAG.getExtLoad(ISD::EXTLOAD, MVT::f64,
3833                                           DAG.getEntryNode(), CPIdx,
3834                                           DAG.getSrcValue(NULL), MVT::f32));
3835  }
3836
3837  return DAG.getNode(ISD::FADD, DestVT, Tmp1, FudgeInReg);
3838}
3839
3840/// PromoteLegalINT_TO_FP - This function is responsible for legalizing a
3841/// *INT_TO_FP operation of the specified operand when the target requests that
3842/// we promote it.  At this point, we know that the result and operand types are
3843/// legal for the target, and that there is a legal UINT_TO_FP or SINT_TO_FP
3844/// operation that takes a larger input.
3845SDOperand SelectionDAGLegalize::PromoteLegalINT_TO_FP(SDOperand LegalOp,
3846                                                      MVT::ValueType DestVT,
3847                                                      bool isSigned) {
3848  // First step, figure out the appropriate *INT_TO_FP operation to use.
3849  MVT::ValueType NewInTy = LegalOp.getValueType();
3850
3851  unsigned OpToUse = 0;
3852
3853  // Scan for the appropriate larger type to use.
3854  while (1) {
3855    NewInTy = (MVT::ValueType)(NewInTy+1);
3856    assert(MVT::isInteger(NewInTy) && "Ran out of possibilities!");
3857
3858    // If the target supports SINT_TO_FP of this type, use it.
3859    switch (TLI.getOperationAction(ISD::SINT_TO_FP, NewInTy)) {
3860      default: break;
3861      case TargetLowering::Legal:
3862        if (!TLI.isTypeLegal(NewInTy))
3863          break;  // Can't use this datatype.
3864        // FALL THROUGH.
3865      case TargetLowering::Custom:
3866        OpToUse = ISD::SINT_TO_FP;
3867        break;
3868    }
3869    if (OpToUse) break;
3870    if (isSigned) continue;
3871
3872    // If the target supports UINT_TO_FP of this type, use it.
3873    switch (TLI.getOperationAction(ISD::UINT_TO_FP, NewInTy)) {
3874      default: break;
3875      case TargetLowering::Legal:
3876        if (!TLI.isTypeLegal(NewInTy))
3877          break;  // Can't use this datatype.
3878        // FALL THROUGH.
3879      case TargetLowering::Custom:
3880        OpToUse = ISD::UINT_TO_FP;
3881        break;
3882    }
3883    if (OpToUse) break;
3884
3885    // Otherwise, try a larger type.
3886  }
3887
3888  // Okay, we found the operation and type to use.  Zero extend our input to the
3889  // desired type then run the operation on it.
3890  return DAG.getNode(OpToUse, DestVT,
3891                     DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
3892                                 NewInTy, LegalOp));
3893}
3894
3895/// PromoteLegalFP_TO_INT - This function is responsible for legalizing a
3896/// FP_TO_*INT operation of the specified operand when the target requests that
3897/// we promote it.  At this point, we know that the result and operand types are
3898/// legal for the target, and that there is a legal FP_TO_UINT or FP_TO_SINT
3899/// operation that returns a larger result.
3900SDOperand SelectionDAGLegalize::PromoteLegalFP_TO_INT(SDOperand LegalOp,
3901                                                      MVT::ValueType DestVT,
3902                                                      bool isSigned) {
3903  // First step, figure out the appropriate FP_TO*INT operation to use.
3904  MVT::ValueType NewOutTy = DestVT;
3905
3906  unsigned OpToUse = 0;
3907
3908  // Scan for the appropriate larger type to use.
3909  while (1) {
3910    NewOutTy = (MVT::ValueType)(NewOutTy+1);
3911    assert(MVT::isInteger(NewOutTy) && "Ran out of possibilities!");
3912
3913    // If the target supports FP_TO_SINT returning this type, use it.
3914    switch (TLI.getOperationAction(ISD::FP_TO_SINT, NewOutTy)) {
3915    default: break;
3916    case TargetLowering::Legal:
3917      if (!TLI.isTypeLegal(NewOutTy))
3918        break;  // Can't use this datatype.
3919      // FALL THROUGH.
3920    case TargetLowering::Custom:
3921      OpToUse = ISD::FP_TO_SINT;
3922      break;
3923    }
3924    if (OpToUse) break;
3925
3926    // If the target supports FP_TO_UINT of this type, use it.
3927    switch (TLI.getOperationAction(ISD::FP_TO_UINT, NewOutTy)) {
3928    default: break;
3929    case TargetLowering::Legal:
3930      if (!TLI.isTypeLegal(NewOutTy))
3931        break;  // Can't use this datatype.
3932      // FALL THROUGH.
3933    case TargetLowering::Custom:
3934      OpToUse = ISD::FP_TO_UINT;
3935      break;
3936    }
3937    if (OpToUse) break;
3938
3939    // Otherwise, try a larger type.
3940  }
3941
3942  // Okay, we found the operation and type to use.  Truncate the result of the
3943  // extended FP_TO_*INT operation to the desired size.
3944  return DAG.getNode(ISD::TRUNCATE, DestVT,
3945                     DAG.getNode(OpToUse, NewOutTy, LegalOp));
3946}
3947
3948/// ExpandBSWAP - Open code the operations for BSWAP of the specified operation.
3949///
3950SDOperand SelectionDAGLegalize::ExpandBSWAP(SDOperand Op) {
3951  MVT::ValueType VT = Op.getValueType();
3952  MVT::ValueType SHVT = TLI.getShiftAmountTy();
3953  SDOperand Tmp1, Tmp2, Tmp3, Tmp4, Tmp5, Tmp6, Tmp7, Tmp8;
3954  switch (VT) {
3955  default: assert(0 && "Unhandled Expand type in BSWAP!"); abort();
3956  case MVT::i16:
3957    Tmp2 = DAG.getNode(ISD::SHL, VT, Op, DAG.getConstant(8, SHVT));
3958    Tmp1 = DAG.getNode(ISD::SRL, VT, Op, DAG.getConstant(8, SHVT));
3959    return DAG.getNode(ISD::OR, VT, Tmp1, Tmp2);
3960  case MVT::i32:
3961    Tmp4 = DAG.getNode(ISD::SHL, VT, Op, DAG.getConstant(24, SHVT));
3962    Tmp3 = DAG.getNode(ISD::SHL, VT, Op, DAG.getConstant(8, SHVT));
3963    Tmp2 = DAG.getNode(ISD::SRL, VT, Op, DAG.getConstant(8, SHVT));
3964    Tmp1 = DAG.getNode(ISD::SRL, VT, Op, DAG.getConstant(24, SHVT));
3965    Tmp3 = DAG.getNode(ISD::AND, VT, Tmp3, DAG.getConstant(0xFF0000, VT));
3966    Tmp2 = DAG.getNode(ISD::AND, VT, Tmp2, DAG.getConstant(0xFF00, VT));
3967    Tmp4 = DAG.getNode(ISD::OR, VT, Tmp4, Tmp3);
3968    Tmp2 = DAG.getNode(ISD::OR, VT, Tmp2, Tmp1);
3969    return DAG.getNode(ISD::OR, VT, Tmp4, Tmp2);
3970  case MVT::i64:
3971    Tmp8 = DAG.getNode(ISD::SHL, VT, Op, DAG.getConstant(56, SHVT));
3972    Tmp7 = DAG.getNode(ISD::SHL, VT, Op, DAG.getConstant(40, SHVT));
3973    Tmp6 = DAG.getNode(ISD::SHL, VT, Op, DAG.getConstant(24, SHVT));
3974    Tmp5 = DAG.getNode(ISD::SHL, VT, Op, DAG.getConstant(8, SHVT));
3975    Tmp4 = DAG.getNode(ISD::SRL, VT, Op, DAG.getConstant(8, SHVT));
3976    Tmp3 = DAG.getNode(ISD::SRL, VT, Op, DAG.getConstant(24, SHVT));
3977    Tmp2 = DAG.getNode(ISD::SRL, VT, Op, DAG.getConstant(40, SHVT));
3978    Tmp1 = DAG.getNode(ISD::SRL, VT, Op, DAG.getConstant(56, SHVT));
3979    Tmp7 = DAG.getNode(ISD::AND, VT, Tmp7, DAG.getConstant(255ULL<<48, VT));
3980    Tmp6 = DAG.getNode(ISD::AND, VT, Tmp6, DAG.getConstant(255ULL<<40, VT));
3981    Tmp5 = DAG.getNode(ISD::AND, VT, Tmp5, DAG.getConstant(255ULL<<32, VT));
3982    Tmp4 = DAG.getNode(ISD::AND, VT, Tmp4, DAG.getConstant(255ULL<<24, VT));
3983    Tmp3 = DAG.getNode(ISD::AND, VT, Tmp3, DAG.getConstant(255ULL<<16, VT));
3984    Tmp2 = DAG.getNode(ISD::AND, VT, Tmp2, DAG.getConstant(255ULL<<8 , VT));
3985    Tmp8 = DAG.getNode(ISD::OR, VT, Tmp8, Tmp7);
3986    Tmp6 = DAG.getNode(ISD::OR, VT, Tmp6, Tmp5);
3987    Tmp4 = DAG.getNode(ISD::OR, VT, Tmp4, Tmp3);
3988    Tmp2 = DAG.getNode(ISD::OR, VT, Tmp2, Tmp1);
3989    Tmp8 = DAG.getNode(ISD::OR, VT, Tmp8, Tmp6);
3990    Tmp4 = DAG.getNode(ISD::OR, VT, Tmp4, Tmp2);
3991    return DAG.getNode(ISD::OR, VT, Tmp8, Tmp4);
3992  }
3993}
3994
3995/// ExpandBitCount - Expand the specified bitcount instruction into operations.
3996///
3997SDOperand SelectionDAGLegalize::ExpandBitCount(unsigned Opc, SDOperand Op) {
3998  switch (Opc) {
3999  default: assert(0 && "Cannot expand this yet!");
4000  case ISD::CTPOP: {
4001    static const uint64_t mask[6] = {
4002      0x5555555555555555ULL, 0x3333333333333333ULL,
4003      0x0F0F0F0F0F0F0F0FULL, 0x00FF00FF00FF00FFULL,
4004      0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL
4005    };
4006    MVT::ValueType VT = Op.getValueType();
4007    MVT::ValueType ShVT = TLI.getShiftAmountTy();
4008    unsigned len = getSizeInBits(VT);
4009    for (unsigned i = 0; (1U << i) <= (len / 2); ++i) {
4010      //x = (x & mask[i][len/8]) + (x >> (1 << i) & mask[i][len/8])
4011      SDOperand Tmp2 = DAG.getConstant(mask[i], VT);
4012      SDOperand Tmp3 = DAG.getConstant(1ULL << i, ShVT);
4013      Op = DAG.getNode(ISD::ADD, VT, DAG.getNode(ISD::AND, VT, Op, Tmp2),
4014                       DAG.getNode(ISD::AND, VT,
4015                                   DAG.getNode(ISD::SRL, VT, Op, Tmp3),Tmp2));
4016    }
4017    return Op;
4018  }
4019  case ISD::CTLZ: {
4020    // for now, we do this:
4021    // x = x | (x >> 1);
4022    // x = x | (x >> 2);
4023    // ...
4024    // x = x | (x >>16);
4025    // x = x | (x >>32); // for 64-bit input
4026    // return popcount(~x);
4027    //
4028    // but see also: http://www.hackersdelight.org/HDcode/nlz.cc
4029    MVT::ValueType VT = Op.getValueType();
4030    MVT::ValueType ShVT = TLI.getShiftAmountTy();
4031    unsigned len = getSizeInBits(VT);
4032    for (unsigned i = 0; (1U << i) <= (len / 2); ++i) {
4033      SDOperand Tmp3 = DAG.getConstant(1ULL << i, ShVT);
4034      Op = DAG.getNode(ISD::OR, VT, Op, DAG.getNode(ISD::SRL, VT, Op, Tmp3));
4035    }
4036    Op = DAG.getNode(ISD::XOR, VT, Op, DAG.getConstant(~0ULL, VT));
4037    return DAG.getNode(ISD::CTPOP, VT, Op);
4038  }
4039  case ISD::CTTZ: {
4040    // for now, we use: { return popcount(~x & (x - 1)); }
4041    // unless the target has ctlz but not ctpop, in which case we use:
4042    // { return 32 - nlz(~x & (x-1)); }
4043    // see also http://www.hackersdelight.org/HDcode/ntz.cc
4044    MVT::ValueType VT = Op.getValueType();
4045    SDOperand Tmp2 = DAG.getConstant(~0ULL, VT);
4046    SDOperand Tmp3 = DAG.getNode(ISD::AND, VT,
4047                       DAG.getNode(ISD::XOR, VT, Op, Tmp2),
4048                       DAG.getNode(ISD::SUB, VT, Op, DAG.getConstant(1, VT)));
4049    // If ISD::CTLZ is legal and CTPOP isn't, then do that instead.
4050    if (!TLI.isOperationLegal(ISD::CTPOP, VT) &&
4051        TLI.isOperationLegal(ISD::CTLZ, VT))
4052      return DAG.getNode(ISD::SUB, VT,
4053                         DAG.getConstant(getSizeInBits(VT), VT),
4054                         DAG.getNode(ISD::CTLZ, VT, Tmp3));
4055    return DAG.getNode(ISD::CTPOP, VT, Tmp3);
4056  }
4057  }
4058}
4059
4060
4061/// ExpandOp - Expand the specified SDOperand into its two component pieces
4062/// Lo&Hi.  Note that the Op MUST be an expanded type.  As a result of this, the
4063/// LegalizeNodes map is filled in for any results that are not expanded, the
4064/// ExpandedNodes map is filled in for any results that are expanded, and the
4065/// Lo/Hi values are returned.
4066void SelectionDAGLegalize::ExpandOp(SDOperand Op, SDOperand &Lo, SDOperand &Hi){
4067  MVT::ValueType VT = Op.getValueType();
4068  MVT::ValueType NVT = TLI.getTypeToTransformTo(VT);
4069  SDNode *Node = Op.Val;
4070  assert(getTypeAction(VT) == Expand && "Not an expanded type!");
4071  assert((MVT::isInteger(VT) || VT == MVT::Vector) &&
4072         "Cannot expand FP values!");
4073  assert(((MVT::isInteger(NVT) && NVT < VT) || VT == MVT::Vector) &&
4074         "Cannot expand to FP value or to larger int value!");
4075
4076  // See if we already expanded it.
4077  std::map<SDOperand, std::pair<SDOperand, SDOperand> >::iterator I
4078    = ExpandedNodes.find(Op);
4079  if (I != ExpandedNodes.end()) {
4080    Lo = I->second.first;
4081    Hi = I->second.second;
4082    return;
4083  }
4084
4085  switch (Node->getOpcode()) {
4086  case ISD::CopyFromReg:
4087    assert(0 && "CopyFromReg must be legal!");
4088  default:
4089    std::cerr << "NODE: "; Node->dump(); std::cerr << "\n";
4090    assert(0 && "Do not know how to expand this operator!");
4091    abort();
4092  case ISD::UNDEF:
4093    Lo = DAG.getNode(ISD::UNDEF, NVT);
4094    Hi = DAG.getNode(ISD::UNDEF, NVT);
4095    break;
4096  case ISD::Constant: {
4097    uint64_t Cst = cast<ConstantSDNode>(Node)->getValue();
4098    Lo = DAG.getConstant(Cst, NVT);
4099    Hi = DAG.getConstant(Cst >> MVT::getSizeInBits(NVT), NVT);
4100    break;
4101  }
4102  case ISD::BUILD_PAIR:
4103    // Return the operands.
4104    Lo = Node->getOperand(0);
4105    Hi = Node->getOperand(1);
4106    break;
4107
4108  case ISD::SIGN_EXTEND_INREG:
4109    ExpandOp(Node->getOperand(0), Lo, Hi);
4110    // Sign extend the lo-part.
4111    Hi = DAG.getNode(ISD::SRA, NVT, Lo,
4112                     DAG.getConstant(MVT::getSizeInBits(NVT)-1,
4113                                     TLI.getShiftAmountTy()));
4114    // sext_inreg the low part if needed.
4115    Lo = DAG.getNode(ISD::SIGN_EXTEND_INREG, NVT, Lo, Node->getOperand(1));
4116    break;
4117
4118  case ISD::BSWAP: {
4119    ExpandOp(Node->getOperand(0), Lo, Hi);
4120    SDOperand TempLo = DAG.getNode(ISD::BSWAP, NVT, Hi);
4121    Hi = DAG.getNode(ISD::BSWAP, NVT, Lo);
4122    Lo = TempLo;
4123    break;
4124  }
4125
4126  case ISD::CTPOP:
4127    ExpandOp(Node->getOperand(0), Lo, Hi);
4128    Lo = DAG.getNode(ISD::ADD, NVT,          // ctpop(HL) -> ctpop(H)+ctpop(L)
4129                     DAG.getNode(ISD::CTPOP, NVT, Lo),
4130                     DAG.getNode(ISD::CTPOP, NVT, Hi));
4131    Hi = DAG.getConstant(0, NVT);
4132    break;
4133
4134  case ISD::CTLZ: {
4135    // ctlz (HL) -> ctlz(H) != 32 ? ctlz(H) : (ctlz(L)+32)
4136    ExpandOp(Node->getOperand(0), Lo, Hi);
4137    SDOperand BitsC = DAG.getConstant(MVT::getSizeInBits(NVT), NVT);
4138    SDOperand HLZ = DAG.getNode(ISD::CTLZ, NVT, Hi);
4139    SDOperand TopNotZero = DAG.getSetCC(TLI.getSetCCResultTy(), HLZ, BitsC,
4140                                        ISD::SETNE);
4141    SDOperand LowPart = DAG.getNode(ISD::CTLZ, NVT, Lo);
4142    LowPart = DAG.getNode(ISD::ADD, NVT, LowPart, BitsC);
4143
4144    Lo = DAG.getNode(ISD::SELECT, NVT, TopNotZero, HLZ, LowPart);
4145    Hi = DAG.getConstant(0, NVT);
4146    break;
4147  }
4148
4149  case ISD::CTTZ: {
4150    // cttz (HL) -> cttz(L) != 32 ? cttz(L) : (cttz(H)+32)
4151    ExpandOp(Node->getOperand(0), Lo, Hi);
4152    SDOperand BitsC = DAG.getConstant(MVT::getSizeInBits(NVT), NVT);
4153    SDOperand LTZ = DAG.getNode(ISD::CTTZ, NVT, Lo);
4154    SDOperand BotNotZero = DAG.getSetCC(TLI.getSetCCResultTy(), LTZ, BitsC,
4155                                        ISD::SETNE);
4156    SDOperand HiPart = DAG.getNode(ISD::CTTZ, NVT, Hi);
4157    HiPart = DAG.getNode(ISD::ADD, NVT, HiPart, BitsC);
4158
4159    Lo = DAG.getNode(ISD::SELECT, NVT, BotNotZero, LTZ, HiPart);
4160    Hi = DAG.getConstant(0, NVT);
4161    break;
4162  }
4163
4164  case ISD::VAARG: {
4165    SDOperand Ch = Node->getOperand(0);   // Legalize the chain.
4166    SDOperand Ptr = Node->getOperand(1);  // Legalize the pointer.
4167    Lo = DAG.getVAArg(NVT, Ch, Ptr, Node->getOperand(2));
4168    Hi = DAG.getVAArg(NVT, Lo.getValue(1), Ptr, Node->getOperand(2));
4169
4170    // Remember that we legalized the chain.
4171    Hi = LegalizeOp(Hi);
4172    AddLegalizedOperand(Op.getValue(1), Hi.getValue(1));
4173    if (!TLI.isLittleEndian())
4174      std::swap(Lo, Hi);
4175    break;
4176  }
4177
4178  case ISD::LOAD: {
4179    SDOperand Ch = Node->getOperand(0);   // Legalize the chain.
4180    SDOperand Ptr = Node->getOperand(1);  // Legalize the pointer.
4181    Lo = DAG.getLoad(NVT, Ch, Ptr, Node->getOperand(2));
4182
4183    // Increment the pointer to the other half.
4184    unsigned IncrementSize = MVT::getSizeInBits(Lo.getValueType())/8;
4185    Ptr = DAG.getNode(ISD::ADD, Ptr.getValueType(), Ptr,
4186                      getIntPtrConstant(IncrementSize));
4187    // FIXME: This creates a bogus srcvalue!
4188    Hi = DAG.getLoad(NVT, Ch, Ptr, Node->getOperand(2));
4189
4190    // Build a factor node to remember that this load is independent of the
4191    // other one.
4192    SDOperand TF = DAG.getNode(ISD::TokenFactor, MVT::Other, Lo.getValue(1),
4193                               Hi.getValue(1));
4194
4195    // Remember that we legalized the chain.
4196    AddLegalizedOperand(Op.getValue(1), LegalizeOp(TF));
4197    if (!TLI.isLittleEndian())
4198      std::swap(Lo, Hi);
4199    break;
4200  }
4201  case ISD::AND:
4202  case ISD::OR:
4203  case ISD::XOR: {   // Simple logical operators -> two trivial pieces.
4204    SDOperand LL, LH, RL, RH;
4205    ExpandOp(Node->getOperand(0), LL, LH);
4206    ExpandOp(Node->getOperand(1), RL, RH);
4207    Lo = DAG.getNode(Node->getOpcode(), NVT, LL, RL);
4208    Hi = DAG.getNode(Node->getOpcode(), NVT, LH, RH);
4209    break;
4210  }
4211  case ISD::SELECT: {
4212    SDOperand LL, LH, RL, RH;
4213    ExpandOp(Node->getOperand(1), LL, LH);
4214    ExpandOp(Node->getOperand(2), RL, RH);
4215    Lo = DAG.getNode(ISD::SELECT, NVT, Node->getOperand(0), LL, RL);
4216    Hi = DAG.getNode(ISD::SELECT, NVT, Node->getOperand(0), LH, RH);
4217    break;
4218  }
4219  case ISD::SELECT_CC: {
4220    SDOperand TL, TH, FL, FH;
4221    ExpandOp(Node->getOperand(2), TL, TH);
4222    ExpandOp(Node->getOperand(3), FL, FH);
4223    Lo = DAG.getNode(ISD::SELECT_CC, NVT, Node->getOperand(0),
4224                     Node->getOperand(1), TL, FL, Node->getOperand(4));
4225    Hi = DAG.getNode(ISD::SELECT_CC, NVT, Node->getOperand(0),
4226                     Node->getOperand(1), TH, FH, Node->getOperand(4));
4227    break;
4228  }
4229  case ISD::SEXTLOAD: {
4230    SDOperand Chain = Node->getOperand(0);
4231    SDOperand Ptr   = Node->getOperand(1);
4232    MVT::ValueType EVT = cast<VTSDNode>(Node->getOperand(3))->getVT();
4233
4234    if (EVT == NVT)
4235      Lo = DAG.getLoad(NVT, Chain, Ptr, Node->getOperand(2));
4236    else
4237      Lo = DAG.getExtLoad(ISD::SEXTLOAD, NVT, Chain, Ptr, Node->getOperand(2),
4238                          EVT);
4239
4240    // Remember that we legalized the chain.
4241    AddLegalizedOperand(SDOperand(Node, 1), LegalizeOp(Lo.getValue(1)));
4242
4243    // The high part is obtained by SRA'ing all but one of the bits of the lo
4244    // part.
4245    unsigned LoSize = MVT::getSizeInBits(Lo.getValueType());
4246    Hi = DAG.getNode(ISD::SRA, NVT, Lo, DAG.getConstant(LoSize-1,
4247                                                       TLI.getShiftAmountTy()));
4248    break;
4249  }
4250  case ISD::ZEXTLOAD: {
4251    SDOperand Chain = Node->getOperand(0);
4252    SDOperand Ptr   = Node->getOperand(1);
4253    MVT::ValueType EVT = cast<VTSDNode>(Node->getOperand(3))->getVT();
4254
4255    if (EVT == NVT)
4256      Lo = DAG.getLoad(NVT, Chain, Ptr, Node->getOperand(2));
4257    else
4258      Lo = DAG.getExtLoad(ISD::ZEXTLOAD, NVT, Chain, Ptr, Node->getOperand(2),
4259                          EVT);
4260
4261    // Remember that we legalized the chain.
4262    AddLegalizedOperand(SDOperand(Node, 1), LegalizeOp(Lo.getValue(1)));
4263
4264    // The high part is just a zero.
4265    Hi = DAG.getConstant(0, NVT);
4266    break;
4267  }
4268  case ISD::EXTLOAD: {
4269    SDOperand Chain = Node->getOperand(0);
4270    SDOperand Ptr   = Node->getOperand(1);
4271    MVT::ValueType EVT = cast<VTSDNode>(Node->getOperand(3))->getVT();
4272
4273    if (EVT == NVT)
4274      Lo = DAG.getLoad(NVT, Chain, Ptr, Node->getOperand(2));
4275    else
4276      Lo = DAG.getExtLoad(ISD::EXTLOAD, NVT, Chain, Ptr, Node->getOperand(2),
4277                          EVT);
4278
4279    // Remember that we legalized the chain.
4280    AddLegalizedOperand(SDOperand(Node, 1), LegalizeOp(Lo.getValue(1)));
4281
4282    // The high part is undefined.
4283    Hi = DAG.getNode(ISD::UNDEF, NVT);
4284    break;
4285  }
4286  case ISD::ANY_EXTEND:
4287    // The low part is any extension of the input (which degenerates to a copy).
4288    Lo = DAG.getNode(ISD::ANY_EXTEND, NVT, Node->getOperand(0));
4289    // The high part is undefined.
4290    Hi = DAG.getNode(ISD::UNDEF, NVT);
4291    break;
4292  case ISD::SIGN_EXTEND: {
4293    // The low part is just a sign extension of the input (which degenerates to
4294    // a copy).
4295    Lo = DAG.getNode(ISD::SIGN_EXTEND, NVT, Node->getOperand(0));
4296
4297    // The high part is obtained by SRA'ing all but one of the bits of the lo
4298    // part.
4299    unsigned LoSize = MVT::getSizeInBits(Lo.getValueType());
4300    Hi = DAG.getNode(ISD::SRA, NVT, Lo,
4301                     DAG.getConstant(LoSize-1, TLI.getShiftAmountTy()));
4302    break;
4303  }
4304  case ISD::ZERO_EXTEND:
4305    // The low part is just a zero extension of the input (which degenerates to
4306    // a copy).
4307    Lo = DAG.getNode(ISD::ZERO_EXTEND, NVT, Node->getOperand(0));
4308
4309    // The high part is just a zero.
4310    Hi = DAG.getConstant(0, NVT);
4311    break;
4312
4313  case ISD::BIT_CONVERT: {
4314    SDOperand Tmp = ExpandBIT_CONVERT(Node->getValueType(0),
4315                                      Node->getOperand(0));
4316    ExpandOp(Tmp, Lo, Hi);
4317    break;
4318  }
4319
4320  case ISD::READCYCLECOUNTER:
4321    assert(TLI.getOperationAction(ISD::READCYCLECOUNTER, VT) ==
4322                 TargetLowering::Custom &&
4323           "Must custom expand ReadCycleCounter");
4324    Lo = TLI.LowerOperation(Op, DAG);
4325    assert(Lo.Val && "Node must be custom expanded!");
4326    Hi = Lo.getValue(1);
4327    AddLegalizedOperand(SDOperand(Node, 1), // Remember we legalized the chain.
4328                        LegalizeOp(Lo.getValue(2)));
4329    break;
4330
4331    // These operators cannot be expanded directly, emit them as calls to
4332    // library functions.
4333  case ISD::FP_TO_SINT:
4334    if (TLI.getOperationAction(ISD::FP_TO_SINT, VT) == TargetLowering::Custom) {
4335      SDOperand Op;
4336      switch (getTypeAction(Node->getOperand(0).getValueType())) {
4337      case Expand: assert(0 && "cannot expand FP!");
4338      case Legal:   Op = LegalizeOp(Node->getOperand(0)); break;
4339      case Promote: Op = PromoteOp (Node->getOperand(0)); break;
4340      }
4341
4342      Op = TLI.LowerOperation(DAG.getNode(ISD::FP_TO_SINT, VT, Op), DAG);
4343
4344      // Now that the custom expander is done, expand the result, which is still
4345      // VT.
4346      if (Op.Val) {
4347        ExpandOp(Op, Lo, Hi);
4348        break;
4349      }
4350    }
4351
4352    if (Node->getOperand(0).getValueType() == MVT::f32)
4353      Lo = ExpandLibCall("__fixsfdi", Node, Hi);
4354    else
4355      Lo = ExpandLibCall("__fixdfdi", Node, Hi);
4356    break;
4357
4358  case ISD::FP_TO_UINT:
4359    if (TLI.getOperationAction(ISD::FP_TO_UINT, VT) == TargetLowering::Custom) {
4360      SDOperand Op;
4361      switch (getTypeAction(Node->getOperand(0).getValueType())) {
4362        case Expand: assert(0 && "cannot expand FP!");
4363        case Legal:   Op = LegalizeOp(Node->getOperand(0)); break;
4364        case Promote: Op = PromoteOp (Node->getOperand(0)); break;
4365      }
4366
4367      Op = TLI.LowerOperation(DAG.getNode(ISD::FP_TO_UINT, VT, Op), DAG);
4368
4369      // Now that the custom expander is done, expand the result.
4370      if (Op.Val) {
4371        ExpandOp(Op, Lo, Hi);
4372        break;
4373      }
4374    }
4375
4376    if (Node->getOperand(0).getValueType() == MVT::f32)
4377      Lo = ExpandLibCall("__fixunssfdi", Node, Hi);
4378    else
4379      Lo = ExpandLibCall("__fixunsdfdi", Node, Hi);
4380    break;
4381
4382  case ISD::SHL: {
4383    // If the target wants custom lowering, do so.
4384    SDOperand ShiftAmt = LegalizeOp(Node->getOperand(1));
4385    if (TLI.getOperationAction(ISD::SHL, VT) == TargetLowering::Custom) {
4386      SDOperand Op = DAG.getNode(ISD::SHL, VT, Node->getOperand(0), ShiftAmt);
4387      Op = TLI.LowerOperation(Op, DAG);
4388      if (Op.Val) {
4389        // Now that the custom expander is done, expand the result, which is
4390        // still VT.
4391        ExpandOp(Op, Lo, Hi);
4392        break;
4393      }
4394    }
4395
4396    // If we can emit an efficient shift operation, do so now.
4397    if (ExpandShift(ISD::SHL, Node->getOperand(0), ShiftAmt, Lo, Hi))
4398      break;
4399
4400    // If this target supports SHL_PARTS, use it.
4401    TargetLowering::LegalizeAction Action =
4402      TLI.getOperationAction(ISD::SHL_PARTS, NVT);
4403    if ((Action == TargetLowering::Legal && TLI.isTypeLegal(NVT)) ||
4404        Action == TargetLowering::Custom) {
4405      ExpandShiftParts(ISD::SHL_PARTS, Node->getOperand(0), ShiftAmt, Lo, Hi);
4406      break;
4407    }
4408
4409    // Otherwise, emit a libcall.
4410    Lo = ExpandLibCall("__ashldi3", Node, Hi);
4411    break;
4412  }
4413
4414  case ISD::SRA: {
4415    // If the target wants custom lowering, do so.
4416    SDOperand ShiftAmt = LegalizeOp(Node->getOperand(1));
4417    if (TLI.getOperationAction(ISD::SRA, VT) == TargetLowering::Custom) {
4418      SDOperand Op = DAG.getNode(ISD::SRA, VT, Node->getOperand(0), ShiftAmt);
4419      Op = TLI.LowerOperation(Op, DAG);
4420      if (Op.Val) {
4421        // Now that the custom expander is done, expand the result, which is
4422        // still VT.
4423        ExpandOp(Op, Lo, Hi);
4424        break;
4425      }
4426    }
4427
4428    // If we can emit an efficient shift operation, do so now.
4429    if (ExpandShift(ISD::SRA, Node->getOperand(0), ShiftAmt, Lo, Hi))
4430      break;
4431
4432    // If this target supports SRA_PARTS, use it.
4433    TargetLowering::LegalizeAction Action =
4434      TLI.getOperationAction(ISD::SRA_PARTS, NVT);
4435    if ((Action == TargetLowering::Legal && TLI.isTypeLegal(NVT)) ||
4436        Action == TargetLowering::Custom) {
4437      ExpandShiftParts(ISD::SRA_PARTS, Node->getOperand(0), ShiftAmt, Lo, Hi);
4438      break;
4439    }
4440
4441    // Otherwise, emit a libcall.
4442    Lo = ExpandLibCall("__ashrdi3", Node, Hi);
4443    break;
4444  }
4445
4446  case ISD::SRL: {
4447    // If the target wants custom lowering, do so.
4448    SDOperand ShiftAmt = LegalizeOp(Node->getOperand(1));
4449    if (TLI.getOperationAction(ISD::SRL, VT) == TargetLowering::Custom) {
4450      SDOperand Op = DAG.getNode(ISD::SRL, VT, Node->getOperand(0), ShiftAmt);
4451      Op = TLI.LowerOperation(Op, DAG);
4452      if (Op.Val) {
4453        // Now that the custom expander is done, expand the result, which is
4454        // still VT.
4455        ExpandOp(Op, Lo, Hi);
4456        break;
4457      }
4458    }
4459
4460    // If we can emit an efficient shift operation, do so now.
4461    if (ExpandShift(ISD::SRL, Node->getOperand(0), ShiftAmt, Lo, Hi))
4462      break;
4463
4464    // If this target supports SRL_PARTS, use it.
4465    TargetLowering::LegalizeAction Action =
4466      TLI.getOperationAction(ISD::SRL_PARTS, NVT);
4467    if ((Action == TargetLowering::Legal && TLI.isTypeLegal(NVT)) ||
4468        Action == TargetLowering::Custom) {
4469      ExpandShiftParts(ISD::SRL_PARTS, Node->getOperand(0), ShiftAmt, Lo, Hi);
4470      break;
4471    }
4472
4473    // Otherwise, emit a libcall.
4474    Lo = ExpandLibCall("__lshrdi3", Node, Hi);
4475    break;
4476  }
4477
4478  case ISD::ADD:
4479  case ISD::SUB: {
4480    // If the target wants to custom expand this, let them.
4481    if (TLI.getOperationAction(Node->getOpcode(), VT) ==
4482            TargetLowering::Custom) {
4483      Op = TLI.LowerOperation(Op, DAG);
4484      if (Op.Val) {
4485        ExpandOp(Op, Lo, Hi);
4486        break;
4487      }
4488    }
4489
4490    // Expand the subcomponents.
4491    SDOperand LHSL, LHSH, RHSL, RHSH;
4492    ExpandOp(Node->getOperand(0), LHSL, LHSH);
4493    ExpandOp(Node->getOperand(1), RHSL, RHSH);
4494    std::vector<MVT::ValueType> VTs;
4495    std::vector<SDOperand> LoOps, HiOps;
4496    VTs.push_back(LHSL.getValueType());
4497    VTs.push_back(MVT::Flag);
4498    LoOps.push_back(LHSL);
4499    LoOps.push_back(RHSL);
4500    HiOps.push_back(LHSH);
4501    HiOps.push_back(RHSH);
4502    if (Node->getOpcode() == ISD::ADD) {
4503      Lo = DAG.getNode(ISD::ADDC, VTs, LoOps);
4504      HiOps.push_back(Lo.getValue(1));
4505      Hi = DAG.getNode(ISD::ADDE, VTs, HiOps);
4506    } else {
4507      Lo = DAG.getNode(ISD::SUBC, VTs, LoOps);
4508      HiOps.push_back(Lo.getValue(1));
4509      Hi = DAG.getNode(ISD::SUBE, VTs, HiOps);
4510    }
4511    break;
4512  }
4513  case ISD::MUL: {
4514    if (TLI.isOperationLegal(ISD::MULHU, NVT)) {
4515      SDOperand LL, LH, RL, RH;
4516      ExpandOp(Node->getOperand(0), LL, LH);
4517      ExpandOp(Node->getOperand(1), RL, RH);
4518      unsigned SH = MVT::getSizeInBits(RH.getValueType())-1;
4519      // MULHS implicitly sign extends its inputs.  Check to see if ExpandOp
4520      // extended the sign bit of the low half through the upper half, and if so
4521      // emit a MULHS instead of the alternate sequence that is valid for any
4522      // i64 x i64 multiply.
4523      if (TLI.isOperationLegal(ISD::MULHS, NVT) &&
4524          // is RH an extension of the sign bit of RL?
4525          RH.getOpcode() == ISD::SRA && RH.getOperand(0) == RL &&
4526          RH.getOperand(1).getOpcode() == ISD::Constant &&
4527          cast<ConstantSDNode>(RH.getOperand(1))->getValue() == SH &&
4528          // is LH an extension of the sign bit of LL?
4529          LH.getOpcode() == ISD::SRA && LH.getOperand(0) == LL &&
4530          LH.getOperand(1).getOpcode() == ISD::Constant &&
4531          cast<ConstantSDNode>(LH.getOperand(1))->getValue() == SH) {
4532        Hi = DAG.getNode(ISD::MULHS, NVT, LL, RL);
4533      } else {
4534        Hi = DAG.getNode(ISD::MULHU, NVT, LL, RL);
4535        RH = DAG.getNode(ISD::MUL, NVT, LL, RH);
4536        LH = DAG.getNode(ISD::MUL, NVT, LH, RL);
4537        Hi = DAG.getNode(ISD::ADD, NVT, Hi, RH);
4538        Hi = DAG.getNode(ISD::ADD, NVT, Hi, LH);
4539      }
4540      Lo = DAG.getNode(ISD::MUL, NVT, LL, RL);
4541    } else {
4542      Lo = ExpandLibCall("__muldi3" , Node, Hi);
4543    }
4544    break;
4545  }
4546  case ISD::SDIV: Lo = ExpandLibCall("__divdi3" , Node, Hi); break;
4547  case ISD::UDIV: Lo = ExpandLibCall("__udivdi3", Node, Hi); break;
4548  case ISD::SREM: Lo = ExpandLibCall("__moddi3" , Node, Hi); break;
4549  case ISD::UREM: Lo = ExpandLibCall("__umoddi3", Node, Hi); break;
4550  }
4551
4552  // Make sure the resultant values have been legalized themselves, unless this
4553  // is a type that requires multi-step expansion.
4554  if (getTypeAction(NVT) != Expand && NVT != MVT::isVoid) {
4555    Lo = LegalizeOp(Lo);
4556    Hi = LegalizeOp(Hi);
4557  }
4558
4559  // Remember in a map if the values will be reused later.
4560  bool isNew =
4561    ExpandedNodes.insert(std::make_pair(Op, std::make_pair(Lo, Hi))).second;
4562  assert(isNew && "Value already expanded?!?");
4563}
4564
4565/// SplitVectorOp - Given an operand of MVT::Vector type, break it down into
4566/// two smaller values of MVT::Vector type.
4567void SelectionDAGLegalize::SplitVectorOp(SDOperand Op, SDOperand &Lo,
4568                                         SDOperand &Hi) {
4569  assert(Op.getValueType() == MVT::Vector && "Cannot split non-vector type!");
4570  SDNode *Node = Op.Val;
4571  unsigned NumElements = cast<ConstantSDNode>(*(Node->op_end()-2))->getValue();
4572  assert(NumElements > 1 && "Cannot split a single element vector!");
4573  unsigned NewNumElts = NumElements/2;
4574  SDOperand NewNumEltsNode = DAG.getConstant(NewNumElts, MVT::i32);
4575  SDOperand TypeNode = *(Node->op_end()-1);
4576
4577  // See if we already split it.
4578  std::map<SDOperand, std::pair<SDOperand, SDOperand> >::iterator I
4579    = SplitNodes.find(Op);
4580  if (I != SplitNodes.end()) {
4581    Lo = I->second.first;
4582    Hi = I->second.second;
4583    return;
4584  }
4585
4586  switch (Node->getOpcode()) {
4587  default: Node->dump(); assert(0 && "Unknown vector operation!");
4588  case ISD::VBUILD_VECTOR: {
4589    std::vector<SDOperand> LoOps(Node->op_begin(), Node->op_begin()+NewNumElts);
4590    LoOps.push_back(NewNumEltsNode);
4591    LoOps.push_back(TypeNode);
4592    Lo = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, LoOps);
4593
4594    std::vector<SDOperand> HiOps(Node->op_begin()+NewNumElts, Node->op_end()-2);
4595    HiOps.push_back(NewNumEltsNode);
4596    HiOps.push_back(TypeNode);
4597    Hi = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, HiOps);
4598    break;
4599  }
4600  case ISD::VADD:
4601  case ISD::VSUB:
4602  case ISD::VMUL:
4603  case ISD::VSDIV:
4604  case ISD::VUDIV:
4605  case ISD::VAND:
4606  case ISD::VOR:
4607  case ISD::VXOR: {
4608    SDOperand LL, LH, RL, RH;
4609    SplitVectorOp(Node->getOperand(0), LL, LH);
4610    SplitVectorOp(Node->getOperand(1), RL, RH);
4611
4612    Lo = DAG.getNode(Node->getOpcode(), MVT::Vector, LL, RL,
4613                     NewNumEltsNode, TypeNode);
4614    Hi = DAG.getNode(Node->getOpcode(), MVT::Vector, LH, RH,
4615                     NewNumEltsNode, TypeNode);
4616    break;
4617  }
4618  case ISD::VLOAD: {
4619    SDOperand Ch = Node->getOperand(0);   // Legalize the chain.
4620    SDOperand Ptr = Node->getOperand(1);  // Legalize the pointer.
4621    MVT::ValueType EVT = cast<VTSDNode>(TypeNode)->getVT();
4622
4623    Lo = DAG.getVecLoad(NewNumElts, EVT, Ch, Ptr, Node->getOperand(2));
4624    unsigned IncrementSize = NewNumElts * MVT::getSizeInBits(EVT)/8;
4625    Ptr = DAG.getNode(ISD::ADD, Ptr.getValueType(), Ptr,
4626                      getIntPtrConstant(IncrementSize));
4627    // FIXME: This creates a bogus srcvalue!
4628    Hi = DAG.getVecLoad(NewNumElts, EVT, Ch, Ptr, Node->getOperand(2));
4629
4630    // Build a factor node to remember that this load is independent of the
4631    // other one.
4632    SDOperand TF = DAG.getNode(ISD::TokenFactor, MVT::Other, Lo.getValue(1),
4633                               Hi.getValue(1));
4634
4635    // Remember that we legalized the chain.
4636    AddLegalizedOperand(Op.getValue(1), LegalizeOp(TF));
4637    break;
4638  }
4639  case ISD::VBIT_CONVERT: {
4640    // We know the result is a vector.  The input may be either a vector or a
4641    // scalar value.
4642    if (Op.getOperand(0).getValueType() != MVT::Vector) {
4643      // Lower to a store/load.  FIXME: this could be improved probably.
4644      SDOperand Ptr = CreateStackTemporary(Op.getOperand(0).getValueType());
4645
4646      SDOperand St = DAG.getNode(ISD::STORE, MVT::Other, DAG.getEntryNode(),
4647                                 Op.getOperand(0), Ptr, DAG.getSrcValue(0));
4648      MVT::ValueType EVT = cast<VTSDNode>(TypeNode)->getVT();
4649      St = DAG.getVecLoad(NumElements, EVT, St, Ptr, DAG.getSrcValue(0));
4650      SplitVectorOp(St, Lo, Hi);
4651    } else {
4652      // If the input is a vector type, we have to either scalarize it, pack it
4653      // or convert it based on whether the input vector type is legal.
4654      SDNode *InVal = Node->getOperand(0).Val;
4655      unsigned NumElems =
4656        cast<ConstantSDNode>(*(InVal->op_end()-2))->getValue();
4657      MVT::ValueType EVT = cast<VTSDNode>(*(InVal->op_end()-1))->getVT();
4658
4659      // If the input is from a single element vector, scalarize the vector,
4660      // then treat like a scalar.
4661      if (NumElems == 1) {
4662        SDOperand Scalar = PackVectorOp(Op.getOperand(0), EVT);
4663        Scalar = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Scalar,
4664                             Op.getOperand(1), Op.getOperand(2));
4665        SplitVectorOp(Scalar, Lo, Hi);
4666      } else {
4667        // Split the input vector.
4668        SplitVectorOp(Op.getOperand(0), Lo, Hi);
4669
4670        // Convert each of the pieces now.
4671        Lo = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Lo,
4672                         NewNumEltsNode, TypeNode);
4673        Hi = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Hi,
4674                         NewNumEltsNode, TypeNode);
4675      }
4676      break;
4677    }
4678  }
4679  }
4680
4681  // Remember in a map if the values will be reused later.
4682  bool isNew =
4683    SplitNodes.insert(std::make_pair(Op, std::make_pair(Lo, Hi))).second;
4684  assert(isNew && "Value already expanded?!?");
4685}
4686
4687
4688/// PackVectorOp - Given an operand of MVT::Vector type, convert it into the
4689/// equivalent operation that returns a scalar (e.g. F32) or packed value
4690/// (e.g. MVT::V4F32).  When this is called, we know that PackedVT is the right
4691/// type for the result.
4692SDOperand SelectionDAGLegalize::PackVectorOp(SDOperand Op,
4693                                             MVT::ValueType NewVT) {
4694  assert(Op.getValueType() == MVT::Vector && "Bad PackVectorOp invocation!");
4695  SDNode *Node = Op.Val;
4696
4697  // See if we already packed it.
4698  std::map<SDOperand, SDOperand>::iterator I = PackedNodes.find(Op);
4699  if (I != PackedNodes.end()) return I->second;
4700
4701  SDOperand Result;
4702  switch (Node->getOpcode()) {
4703  default:
4704    Node->dump(); std::cerr << "\n";
4705    assert(0 && "Unknown vector operation in PackVectorOp!");
4706  case ISD::VADD:
4707  case ISD::VSUB:
4708  case ISD::VMUL:
4709  case ISD::VSDIV:
4710  case ISD::VUDIV:
4711  case ISD::VAND:
4712  case ISD::VOR:
4713  case ISD::VXOR:
4714    Result = DAG.getNode(getScalarizedOpcode(Node->getOpcode(), NewVT),
4715                         NewVT,
4716                         PackVectorOp(Node->getOperand(0), NewVT),
4717                         PackVectorOp(Node->getOperand(1), NewVT));
4718    break;
4719  case ISD::VLOAD: {
4720    SDOperand Ch = LegalizeOp(Node->getOperand(0));   // Legalize the chain.
4721    SDOperand Ptr = LegalizeOp(Node->getOperand(1));  // Legalize the pointer.
4722
4723    Result = DAG.getLoad(NewVT, Ch, Ptr, Node->getOperand(2));
4724
4725    // Remember that we legalized the chain.
4726    AddLegalizedOperand(Op.getValue(1), LegalizeOp(Result.getValue(1)));
4727    break;
4728  }
4729  case ISD::VBUILD_VECTOR:
4730    if (Node->getOperand(0).getValueType() == NewVT) {
4731      // Returning a scalar?
4732      Result = Node->getOperand(0);
4733    } else {
4734      // Returning a BUILD_VECTOR?
4735
4736      // If all elements of the build_vector are undefs, return an undef.
4737      bool AllUndef = true;
4738      for (unsigned i = 0, e = Node->getNumOperands()-2; i != e; ++i)
4739        if (Node->getOperand(i).getOpcode() != ISD::UNDEF) {
4740          AllUndef = false;
4741          break;
4742        }
4743      if (AllUndef) {
4744        Result = DAG.getNode(ISD::UNDEF, NewVT);
4745      } else {
4746        std::vector<SDOperand> Ops(Node->op_begin(), Node->op_end()-2);
4747        Result = DAG.getNode(ISD::BUILD_VECTOR, NewVT, Ops);
4748      }
4749    }
4750    break;
4751  case ISD::VINSERT_VECTOR_ELT:
4752    if (!MVT::isVector(NewVT)) {
4753      // Returning a scalar?  Must be the inserted element.
4754      Result = Node->getOperand(1);
4755    } else {
4756      Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, NewVT,
4757                           PackVectorOp(Node->getOperand(0), NewVT),
4758                           Node->getOperand(1), Node->getOperand(2));
4759    }
4760    break;
4761  case ISD::VVECTOR_SHUFFLE:
4762    if (!MVT::isVector(NewVT)) {
4763      // Returning a scalar?  Figure out if it is the LHS or RHS and return it.
4764      SDOperand EltNum = Node->getOperand(2).getOperand(0);
4765      if (cast<ConstantSDNode>(EltNum)->getValue())
4766        Result = PackVectorOp(Node->getOperand(1), NewVT);
4767      else
4768        Result = PackVectorOp(Node->getOperand(0), NewVT);
4769    } else {
4770      // Otherwise, return a VECTOR_SHUFFLE node.  First convert the index
4771      // vector from a VBUILD_VECTOR to a BUILD_VECTOR.
4772      std::vector<SDOperand> BuildVecIdx(Node->getOperand(2).Val->op_begin(),
4773                                         Node->getOperand(2).Val->op_end()-2);
4774      MVT::ValueType BVT = MVT::getIntVectorWithNumElements(BuildVecIdx.size());
4775      SDOperand BV = DAG.getNode(ISD::BUILD_VECTOR, BVT, BuildVecIdx);
4776
4777      Result = DAG.getNode(ISD::VECTOR_SHUFFLE, NewVT,
4778                           PackVectorOp(Node->getOperand(0), NewVT),
4779                           PackVectorOp(Node->getOperand(1), NewVT), BV);
4780    }
4781    break;
4782  case ISD::VBIT_CONVERT:
4783    if (Op.getOperand(0).getValueType() != MVT::Vector)
4784      Result = DAG.getNode(ISD::BIT_CONVERT, NewVT, Op.getOperand(0));
4785    else {
4786      // If the input is a vector type, we have to either scalarize it, pack it
4787      // or convert it based on whether the input vector type is legal.
4788      SDNode *InVal = Node->getOperand(0).Val;
4789      unsigned NumElems =
4790        cast<ConstantSDNode>(*(InVal->op_end()-2))->getValue();
4791      MVT::ValueType EVT = cast<VTSDNode>(*(InVal->op_end()-1))->getVT();
4792
4793      // Figure out if there is a Packed type corresponding to this Vector
4794      // type.  If so, convert to the packed type.
4795      MVT::ValueType TVT = MVT::getVectorType(EVT, NumElems);
4796      if (TVT != MVT::Other && TLI.isTypeLegal(TVT)) {
4797        // Turn this into a bit convert of the packed input.
4798        Result = DAG.getNode(ISD::BIT_CONVERT, NewVT,
4799                             PackVectorOp(Node->getOperand(0), TVT));
4800        break;
4801      } else if (NumElems == 1) {
4802        // Turn this into a bit convert of the scalar input.
4803        Result = DAG.getNode(ISD::BIT_CONVERT, NewVT,
4804                             PackVectorOp(Node->getOperand(0), EVT));
4805        break;
4806      } else {
4807        // FIXME: UNIMP!
4808        assert(0 && "Cast from unsupported vector type not implemented yet!");
4809      }
4810    }
4811    break;
4812  case ISD::VSELECT:
4813    Result = DAG.getNode(ISD::SELECT, NewVT, Op.getOperand(0),
4814                         PackVectorOp(Op.getOperand(1), NewVT),
4815                         PackVectorOp(Op.getOperand(2), NewVT));
4816    break;
4817  }
4818
4819  if (TLI.isTypeLegal(NewVT))
4820    Result = LegalizeOp(Result);
4821  bool isNew = PackedNodes.insert(std::make_pair(Op, Result)).second;
4822  assert(isNew && "Value already packed?");
4823  return Result;
4824}
4825
4826
4827// SelectionDAG::Legalize - This is the entry point for the file.
4828//
4829void SelectionDAG::Legalize() {
4830  if (ViewLegalizeDAGs) viewGraph();
4831
4832  /// run - This is the main entry point to this class.
4833  ///
4834  SelectionDAGLegalize(*this).LegalizeDAG();
4835}
4836
4837