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